Compare commits

...

25 Commits

Author SHA1 Message Date
Oliver Kieselbach 0d6c03d64b Public texts no longer name a customer domain or IME decompiles
- Two code comments of the gather-rule timeline feed named a customer's domain next to the
  session id; the session id stays as the regression anchor.
- The get_ime_pattern_health description and the IME Pattern Health admin text no longer send
  the reader to "the IME decompile"; the IME-TOKEN-FAILURE and IME-DO-TEL pattern descriptions
  say "verified against IME x" / "absent from the x builds" (rules/dist regenerated).
- Code comments that cited decompiled IME builds cite the IME version instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 22:00:52 +02:00
Oliver Kieselbach b14866c9a6 bump pointer: internal (gather-rule state committed, B-hx3)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:46:44 +02:00
Oliver Kieselbach 25b133d3d0 bump pointer: internal (gather-rule state across restarts, D-309)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:45:29 +02:00
Oliver Kieselbach 684167292f Gather rules keep their place across agent restarts; byte-exact logparser reader; MCP filters by gather event types
- Logparser positions per (rule, file) and the on_change values persist in
  State\gather-rule-state.json, bound to the session id. A reboot, hard kill or WhiteGlove
  Part 2 no longer replays a log from byte 0 or re-emits an unchanged on_change result. A
  replaced log (fingerprint of its first 4 KB) is read from the beginning. Positions are saved
  after the events went out; restoring the file is fail-soft. --run-gather-rules stays in memory.
- LogLineReader: a maxLines stop loses no line, an unfinished last line is never split
  (interval rules wait one run, one-shot triggers read it again next run), UTF-16/UTF-32 logs
  are read by their byte order mark from any position, line ends as StreamReader.ReadLine,
  logLineNumber counts from the start of the file, lines over 32 MB are skipped. A maxLines
  value that is no positive number falls back to 1000.
- UserProfileResolver no longer caches "no user signed in yet" (detection retried at most
  every 30 s); guarded callers expand the token with the profile they checked.
- MCP get_session_events, search_sessions_by_event and query_raw_events accept a gather
  rule's own outputEventType; an empty first-page result for an uncatalogued type carries
  eventTypeNote with the closest built-in types instead of being rejected up front.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 21:45:10 +02:00
Oliver Kieselbach 6474860a57 bump pointer: internal (lesson from the vulnerabilities feedback)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 20:15:56 +02:00
Oliver Kieselbach d23f2eae3e bump pointer: internal (vulnerabilities feedback fixes, D-308)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 20:14:40 +02:00
Oliver Kieselbach fae6aa0b92 Vulnerabilities band filters always find entries, list controls stay put, first load shows the progress dialog
The summary endpoint takes perBand: above 0 it adds bandCves and bandSoftware, each severity and
priority band's top entries outside the lists. The portal asks for 10 per band and shows them only
under a filter, so Attend lists its 7 CVEs instead of nothing; the MCP tool never asks and keeps its
size. The Most exposed controls sit below the title in every state, bands with 0 entries are
disabled, and the first load shows CalculatingDialog (the Geographic Performance dialog without its
page) with separate estimates for all tenants and one tenant. D-308.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 20:13:47 +02:00
Oliver Kieselbach 43dfb731f1 bump pointer: internal (vulnerabilities tab redesign, D-307)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 19:38:45 +02:00
Oliver Kieselbach dd5534b0c9 Vulnerabilities tab shows a severity donut, the priority ladder and the most exposed software
The exposure summary groups CVE index rows by product: every new row carries the finding's
CPE vendor:product as Product, and a row without it borrows the product of a row with the
same title. The summary adds topSoftware, distinctSoftware and kevAffectedSessions, and
known-exploited CVEs and products stay listed below the topN cut (capped so the MCP result
stays under its 50k cap). The shared panel is rebuilt: KPI tiles, a severity donut and the
Act/Attend/Track ladder as list filters, and a Most exposed card with Software and CVEs
lenses. get_vulnerability_summary describes the new fields. D-307.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 19:35:09 +02:00
Oliver Kieselbach 54334de378 Rule pages point to AI-assisted rule authoring
The community box on the gather and analyze rule pages gets a line that an
assistant connected via MCP can draft, validate and test a rule, linking the
AI-assisted rule authoring docs page.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 19:11:56 +02:00
Oliver Kieselbach 9671191eef bump pointer: internal (/plans nav marking, slash links, MCP docs, D-306)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 18:43:41 +02:00
Oliver Kieselbach c5a4feb762 Internal links on the public pages end with a slash
The host answers /plans, /about, /privacy and the other page paths with a
301 to the slash path first. The navbar, the footer, the landing and
get-started calls to action, the terms page and two portal links to
/settings now point at the slash path directly. A guard renders every
public page with the build's trailing-slash setting and fails on an
internal link without it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 18:41:22 +02:00
Oliver Kieselbach 2253fca533 bump pointers: internal, .claude/commands (AI page and marketing click counts, D-305)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 18:16:42 +02:00
Oliver Kieselbach ff9e79dcc7 Landing gets an AI page (/ai) and counts clicks and section views
New public page /ai, linked from the navbar (AI), the Then just ask section
and the footer. It shows what an AI client can answer from the structured
enrollment data: a question gallery whose answer panel switches between chat
app, VS Code, terminal and self-hosted, the data path (where the model runs,
what reaches us) and how to connect. A test keeps every MCP tool and argument
on the page in line with the server's registrations for tenant users.

The landing, /get-started and /ai send anonymous click and section-view
counts (marketing_cta_clicked, marketing_section_viewed); every link and
button carries a data-track id. Layouts with their own OpenGraph metadata
keep the shared image and the large Twitter card again. The navbar tightens
between lg and xl so the new entry fits at 1024 px. The FAQ names the
documented MCP clients, and the terminal demo uses the real search_sessions
argument (deviceName).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 18:15:15 +02:00
Oliver Kieselbach e54b4585b8 bump pointers: internal, .claude/commands (event follow-up page live, D-304)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 17:17:41 +02:00
Oliver Kieselbach 7894d61e0b Event follow-up page for the Workplace Ninja Summit 2026
Unlisted page /events/<slug>/ for the link in the post-event mail: try it,
request a walkthrough, read the docs, plus the free community editions of
SCEPman and MyWorkID. It is noindex and kept out of the sitemap, robots.txt
and llms.txt. Every call to action sends one anonymous click event
(event_followup_clicked). The customer quote is now shared with the landing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 17:11:48 +02:00
Oliver Kieselbach 090f47d4fb Merge branch 'main' of https://github.com/okieselbach/AutopilotMonitor 2026-10-01 13:14:44 +02:00
Oliver Kieselbach c2d68b6537 bump pointer: internal (landing GitHub stars, D-303)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 13:13:35 +02:00
Oliver Kieselbach 5b0dfaad99 Landing shows the GitHub star count and a customer quote
The navbar gets a "Star" pill with the repository's star count from sm up;
phones keep the bare GitHub mark. A new section before the closing CTA
shows one customer quote with a star ask underneath. The footer's
"Star us on GitHub" line is gone, so the page asks twice, not three times.

The count is read once per web deploy (deploy-web.yml, own step, job token
only there) and inlined by next build as NEXT_PUBLIC_GITHUB_STARS, so
visitors' browsers never contact GitHub and the CSP stays as it is.
Without a value the pill renders without a counter (D-303).

The desktop links, bell and sign-in now start at lg instead of md: the bar
already overflowed between 768 and ~1000 px and the pill widened it further.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 13:13:33 +02:00
dependabot[bot] 50d29e61e8 chore(deps): bump the web-security group across 1 directory with 3 updates (#170)
Bumps the web-security group with 3 updates in the /src/Web/autopilot-monitor-web directory: [next](https://github.com/vercel/next.js), [brace-expansion](https://github.com/juliangruber/brace-expansion) and [dompurify](https://github.com/cure53/DOMPurify).


Updates `next` from 16.3.5 to 16.3.6
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.3.5...v16.3.6)

Updates `brace-expansion` from 1.1.18 to 1.1.21
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.18...v1.1.21)

Updates `dompurify` from 3.4.14 to 3.4.16
- [Release notes](https://github.com/cure53/DOMPurify/releases)
- [Commits](https://github.com/cure53/DOMPurify/compare/3.4.14...3.4.16)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.3.6
  dependency-type: direct:production
  dependency-group: web-security
- dependency-name: brace-expansion
  dependency-version: 1.1.21
  dependency-type: indirect
  dependency-group: web-security
- dependency-name: dompurify
  dependency-version: 3.4.16
  dependency-type: indirect
  dependency-group: web-security
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-01 11:16:00 +02:00
dependabot[bot] 4b03ba4e19 chore(deps): bump fast-uri (#169)
Bumps the mcp-security group with 1 update in the /src/McpServer/autopilot-monitor-mcp directory: [fast-uri](https://github.com/fastify/fast-uri).


Updates `fast-uri` from 3.1.7 to 3.1.8
- [Release notes](https://github.com/fastify/fast-uri/releases)
- [Commits](https://github.com/fastify/fast-uri/compare/v3.1.7...v3.1.8)

---
updated-dependencies:
- dependency-name: fast-uri
  dependency-version: 3.1.8
  dependency-type: indirect
  dependency-group: mcp-security
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-01 11:15:42 +02:00
dependabot[bot] f0aec031f3 chore(deps): bump the actions group with 2 updates (#168)
Bumps the actions group with 2 updates: [github/codeql-action/init](https://github.com/github/codeql-action) and [github/codeql-action/analyze](https://github.com/github/codeql-action).


Updates `github/codeql-action/init` from 4.38.0 to 4.38.2
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/b96794f015dfd88f77b49b1c93e0fa7110f94c63...2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2)

Updates `github/codeql-action/analyze` from 4.38.0 to 4.38.2
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/b96794f015dfd88f77b49b1c93e0fa7110f94c63...2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2)

---
updated-dependencies:
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-01 09:28:08 +02:00
Oliver Kieselbach 66208b3767 bump pointer: internal (rule notification placeholders, D-302)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 18:25:11 +02:00
Oliver Kieselbach c60e07dfd4 Rule notifications resolve {{token}} placeholders before they are sent
A stored rule result keeps the rule's template; only the web and the MCP
server resolved it. The notification builders sent the explanation as
stored, so a channel card showed {{reason}}, {{appName}},
{{failedSubcategory}} and {{errorCode}} although the session had recorded
all four values.

- RuleTemplateInterpolator: the backend copy of the resolution, applied in
  BuildRuleFiredAlert and AddRuleResultSections before the text is cut.
  In a notification a list item whose value was not recorded is dropped
  and a token in running text becomes an en dash.
- The cut lands on a line, sentence or word boundary instead of a
  character count; the limits are unchanged.
- tests/fixtures/rule-template-interpolation/cases.json: one case file
  run by the backend, the web and the MCP server.
- The engine's evidence auto-field list is one constant. The web, the MCP
  interpolator and the validate_rule token lint gain timeoutHours, which
  the engine already recorded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 18:12:02 +02:00
Oliver Kieselbach f564ee6a06 bump pointer: internal (hello wait timeout released)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 15:50:29 +02:00
163 changed files with 9203 additions and 932 deletions
+2 -2
View File
@@ -114,7 +114,7 @@ jobs:
dotnet-version: '10.0.x'
- name: Initialize CodeQL
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
@@ -125,6 +125,6 @@ jobs:
run: dotnet build AutopilotMonitor.sln --configuration Release
- name: Analyze
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
category: /language:${{ matrix.language }}
+19
View File
@@ -78,6 +78,23 @@ jobs:
working-directory: ${{ env.WEB_DIR }}
run: npm ci
# Star counter for the GitHub star link (utils/githubStars.ts). Baked into the static HTML
# so visitors' browsers never call GitHub; stale until the next web deploy. The token stays
# in this step, never in the build. Fail-soft: without a number the link has no counter.
- name: Read GitHub star count (fail-soft)
id: stars
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: |
count=$(gh api "repos/$REPO" --jq .stargazers_count 2>/dev/null || true)
if [[ "$count" =~ ^[0-9]+$ ]]; then
echo "count=$count" >> "$GITHUB_OUTPUT"
echo "GitHub stars: $count"
else
echo "::warning::GitHub star count unavailable - the star link renders without a counter"
fi
# next.config output:'export' -- `next build` writes the static site to out/
# (prebuild: sync-error-codes, generate-lastmod, generate-version, whats-new).
- name: Build
@@ -98,6 +115,8 @@ jobs:
GITHUB_SHA: ${{ github.sha }}
# Docs checkout for public/whats-new.json; the prebuild fails in CI without it.
WHATS_NEW_DOCS_DIR: ${{ github.workspace }}/whats-new-docs
# Star counter from the step above; empty when the lookup failed.
NEXT_PUBLIC_GITHUB_STARS: ${{ steps.stars.outputs.count }}
run: |
npm run build
test -f out/version.json || { echo "out/version.json missing - export did not run"; exit 1; }
+2 -2
View File
@@ -203,7 +203,7 @@
"category": "currentPhase",
"pattern": "^\\[DO TEL\\] = (?<doTelJson>\\{.*\\})",
"action": "updateDoTelemetry",
"description": "Captures Delivery Optimization telemetry JSON after a DO download completes. Contains file size, peer caching stats, download mode, and duration. IME removed the [DO TEL] emitter in 1.104 (absent in 1.104.102.0 and 1.105.103.0 decompiles, present in 1.97.107.0); kept while 1.101/1.103 devices are in the fleet — retire once those versions are gone.",
"description": "Captures Delivery Optimization telemetry JSON after a DO download completes. Contains file size, peer caching stats, download mode, and duration. IME removed the [DO TEL] emitter in 1.104 (absent from the 1.104.102.0 and 1.105.103.0 builds, present in 1.97.107.0); kept while 1.101/1.103 devices are in the fleet — retire once those versions are gone.",
"enabled": true
},
{
@@ -584,7 +584,7 @@
"category": "always",
"pattern": "^Failed to get AAD token\\..*?errorCode = (?<errorCode>.*?)$",
"action": "imeTokenFailure",
"description": "IME token acquisition failure ('Failed to get AAD token. len = N using client id ... and resource id ..., errorCode = N', IntuneTokenManager, IntuneManagementExtension.log). This line appears ROUTINELY during the device phase (no user token exists yet), so the agent holds the failure pending: any IME-TOKEN-SUCCESS match clears it, and the ime_token_failure Warning fires only when no success follows for the whole 30-min grace window (then deduped to one Warning per distinct errorCode). A genuine auth outage (WAM broken, conditional access, network) runs long enough to hit the window. Verified against IME 1.97 and 1.104 decompiled sources.",
"description": "IME token acquisition failure ('Failed to get AAD token. len = N using client id ... and resource id ..., errorCode = N', IntuneTokenManager, IntuneManagementExtension.log). This line appears ROUTINELY during the device phase (no user token exists yet), so the agent holds the failure pending: any IME-TOKEN-SUCCESS match clears it, and the ime_token_failure Warning fires only when no success follows for the whole 30-min grace window (then deduped to one Warning per distinct errorCode). A genuine auth outage (WAM broken, conditional access, network) runs long enough to hit the window. Verified against IME 1.97 and 1.104.",
"enabled": true
},
{
+1 -1
View File
@@ -4,6 +4,6 @@
"category": "currentPhase",
"pattern": "^\\[DO TEL\\] = (?<doTelJson>\\{.*\\})",
"action": "updateDoTelemetry",
"description": "Captures Delivery Optimization telemetry JSON after a DO download completes. Contains file size, peer caching stats, download mode, and duration. IME removed the [DO TEL] emitter in 1.104 (absent in 1.104.102.0 and 1.105.103.0 decompiles, present in 1.97.107.0); kept while 1.101/1.103 devices are in the fleet — retire once those versions are gone.",
"description": "Captures Delivery Optimization telemetry JSON after a DO download completes. Contains file size, peer caching stats, download mode, and duration. IME removed the [DO TEL] emitter in 1.104 (absent from the 1.104.102.0 and 1.105.103.0 builds, present in 1.97.107.0); kept while 1.101/1.103 devices are in the fleet — retire once those versions are gone.",
"enabled": true
}
@@ -4,6 +4,6 @@
"category": "always",
"pattern": "^Failed to get AAD token\\..*?errorCode = (?<errorCode>.*?)$",
"action": "imeTokenFailure",
"description": "IME token acquisition failure ('Failed to get AAD token. len = N using client id ... and resource id ..., errorCode = N', IntuneTokenManager, IntuneManagementExtension.log). This line appears ROUTINELY during the device phase (no user token exists yet), so the agent holds the failure pending: any IME-TOKEN-SUCCESS match clears it, and the ime_token_failure Warning fires only when no success follows for the whole 30-min grace window (then deduped to one Warning per distinct errorCode). A genuine auth outage (WAM broken, conditional access, network) runs long enough to hit the window. Verified against IME 1.97 and 1.104 decompiled sources.",
"description": "IME token acquisition failure ('Failed to get AAD token. len = N using client id ... and resource id ..., errorCode = N', IntuneTokenManager, IntuneManagementExtension.log). This line appears ROUTINELY during the device phase (no user token exists yet), so the agent holds the failure pending: any IME-TOKEN-SUCCESS match clears it, and the ime_token_failure Warning fires only when no success follows for the whole 30-min grace window (then deduped to one Warning per distinct errorCode). A genuine auth outage (WAM broken, conditional access, network) runs long enough to hit the window. Verified against IME 1.97 and 1.104.",
"enabled": true
}
@@ -41,15 +41,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
}
private GatherRuleContext Context(bool unrestricted = false, string? imeLogPathOverride = null)
=> new GatherRuleContext(
new AgentLogger(_tmp.Path, AgentLogLevel.Info),
{
var logger = new AgentLogger(_tmp.Path, AgentLogLevel.Info);
return new GatherRuleContext(
logger,
"sess", "tenant",
evt => _events.Add(evt),
imeLogPathOverride,
new LogFilePositionTracker())
new GatherRuleSessionState("sess", null, logger))
{
UnrestrictedMode = unrestricted
};
}
private static GatherRule Rule(string collectorType, string target,
Dictionary<string, string>? parameters = null) => new GatherRule
@@ -94,7 +94,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
public void Context_DebugLog_is_noop_without_writer()
{
var context = new GatherRuleContext(
_logger, "sess", "tenant", _ => { }, null, new LogFilePositionTracker());
_logger, "sess", "tenant", _ => { }, null, new GatherRuleSessionState("sess", null, _logger));
context.DebugLog("RULE-1", GatherRuleDebugLog.StageScope, "should not throw, should not write");
@@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Shared.Models;
using Newtonsoft.Json;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
{
/// <summary>
/// An agent restart inside one enrollment session — a new <see cref="GatherRuleExecutor"/> on the
/// same state directory — continues where the previous run stopped: logparser rules do not
/// replay their log, on_change rules do not re-emit an unchanged result. Regression anchor:
/// session c8106021, where every restart replayed the whole HP Image Assistant log (70 events).
/// </summary>
[Collection("SerialThreading")] // startup rules execute on the shared ThreadPool
public sealed class GatherRuleExecutorRestartTests : IDisposable
{
private readonly TempDirectory _tmp = new TempDirectory();
private readonly TempDirectory _stateDir = new TempDirectory();
private readonly List<EnrollmentEvent> _events = new List<EnrollmentEvent>();
private readonly object _eventsGate = new object();
private readonly List<GatherRuleExecutor> _executors = new List<GatherRuleExecutor>();
// %TEMP% lives under C:\Users (hard-blocked) — log targets sit beside the test assembly.
private readonly string _logDir = Path.Combine(
AppContext.BaseDirectory, "gather-restart-tests-" + Guid.NewGuid().ToString("N"));
public GatherRuleExecutorRestartTests()
{
Directory.CreateDirectory(_logDir);
}
public void Dispose()
{
foreach (var executor in _executors)
executor.Dispose();
_tmp.Dispose();
_stateDir.Dispose();
try { Directory.Delete(_logDir, recursive: true); } catch { /* best effort */ }
}
private string StateFile => Path.Combine(_stateDir.Path, GatherRuleStatePersistence.FileName);
private List<EnrollmentEvent> Events
{
get { lock (_eventsGate) return _events.ToList(); }
}
/// <summary>One agent run: a fresh executor whose startup rules run once. Not disposed — a hard kill.</summary>
private GatherRuleExecutor AgentRun(GatherRule rule, string sessionId = "session-a", string? stateDirectory = "default",
Action<EnrollmentEvent>? onEvent = null, string? debugLogPath = null)
{
var executor = new GatherRuleExecutor(
sessionId, "tenant",
evt =>
{
onEvent?.Invoke(evt);
lock (_eventsGate) _events.Add(evt);
},
new AgentLogger(_tmp.Path, AgentLogLevel.Info),
debugLogPath: debugLogPath,
stateDirectory: stateDirectory == "default" ? _stateDir.Path : stateDirectory)
{
UnrestrictedMode = true
};
_executors.Add(executor);
executor.UpdateRules(new List<GatherRule> { rule });
Assert.True(executor.WaitForStartupRules(30));
return executor;
}
private static GatherRule LogRule(string path, string id = "hpia-log-collect") => new GatherRule
{
RuleId = id,
Title = id,
CollectorType = "logparser",
Target = path,
Parameters = new Dictionary<string, string> { ["pattern"] = "^(?<status>Update .+)$", ["format"] = "text" },
Trigger = "startup",
OutputEventType = "HPiA-UpdateStatus",
Enabled = true,
};
private static GatherRule OnChangeFileRule(string path) => new GatherRule
{
RuleId = "GATHER-OC-FILE",
Title = "file presence",
CollectorType = "file",
Target = path,
Trigger = "startup",
OutputEventType = "gather_file_presence",
Enabled = true,
EmitMode = "on_change",
};
private string WriteLog(string name, string content)
{
var path = Path.Combine(_logDir, name);
File.WriteAllText(path, content);
return path;
}
private int StatusEvents => Events.Count(e => e.EventType == "HPiA-UpdateStatus");
[Fact]
public void Restart_does_not_replay_the_log_and_new_lines_arrive_once()
{
var path = WriteLog("HP Image Assistant.log", "Update one\nUpdate two\nnoise\n");
AgentRun(LogRule(path));
Assert.Equal(2, StatusEvents);
AgentRun(LogRule(path)); // reboot, nothing new
Assert.Equal(2, StatusEvents);
File.AppendAllText(path, "Update three\n");
AgentRun(LogRule(path)); // next restart picks up only the new line
Assert.Equal(3, StatusEvents);
Assert.Equal("Update three", Events.Last(e => e.EventType == "HPiA-UpdateStatus").Data["status"]);
}
[Fact]
public void Position_is_on_disk_right_after_the_run_without_a_clean_shutdown()
{
var path = WriteLog("hardkill.log", "Update one\n");
AgentRun(LogRule(path)); // never disposed
var saved = JsonConvert.DeserializeObject<GatherRuleStateData>(File.ReadAllText(StateFile))!;
var position = Assert.Single(saved.LogPositions!);
Assert.Equal(new FileInfo(path).Length, position.Position);
Assert.Equal("session-a", saved.SessionId);
}
[Fact]
public void Position_is_saved_only_after_the_events_went_out()
{
var path = WriteLog("ordering.log", "Update one\n");
var savedDuringEmit = new List<bool>();
AgentRun(LogRule(path), onEvent: _ => savedDuringEmit.Add(File.Exists(StateFile)));
Assert.Equal(new[] { false }, savedDuringEmit);
Assert.True(File.Exists(StateFile));
}
[Fact]
public void A_new_session_reads_the_log_from_the_beginning()
{
var path = WriteLog("rotated.log", "Update one\nUpdate two\n");
AgentRun(LogRule(path), sessionId: "session-a");
AgentRun(LogRule(path), sessionId: "session-b"); // session rotated on the same device
Assert.Equal(4, StatusEvents);
}
[Fact]
public void A_log_replaced_during_the_reboot_is_read_from_the_beginning()
{
var path = WriteLog("replaced.log", "Update one\n");
AgentRun(LogRule(path, "replaced"));
// The tool writes a new log after the reboot; it is already longer than the old position.
File.WriteAllText(path, "Update fresh A\nUpdate fresh B\nUpdate fresh C\n");
AgentRun(LogRule(path, "replaced"));
Assert.Equal(new[] { "Update one", "Update fresh A", "Update fresh B", "Update fresh C" },
Events.Where(e => e.EventType == "HPiA-UpdateStatus").Select(e => (string)e.Data["status"]).ToArray());
}
[Fact]
public void An_unchanged_on_change_result_stays_silent_after_a_restart()
{
var watched = Path.Combine(_logDir, "marker.txt");
AgentRun(OnChangeFileRule(watched)); // absent → first result emits
AgentRun(OnChangeFileRule(watched)); // reboot, still absent → silent
Assert.Single(Events, e => e.EventType == "gather_file_presence");
File.WriteAllText(watched, "present");
AgentRun(OnChangeFileRule(watched)); // changed → emits
Assert.Equal(2, Events.Count(e => e.EventType == "gather_file_presence"));
}
[Fact]
public void Without_a_state_directory_every_run_starts_over_and_writes_nothing()
{
var path = WriteLog("diagnostic.log", "Update one\n");
AgentRun(LogRule(path), stateDirectory: null);
AgentRun(LogRule(path), stateDirectory: null);
Assert.Equal(2, StatusEvents);
Assert.False(File.Exists(StateFile));
}
[Fact]
public void Debug_trace_says_what_was_restored_and_where_reading_continues()
{
var path = WriteLog("traced.log", "Update one\n");
var trace = Path.Combine(_tmp.Path, "gather-rules-debug.log");
AgentRun(LogRule(path));
File.AppendAllText(path, "Update two\n");
AgentRun(LogRule(path), debugLogPath: trace);
var text = File.ReadAllText(trace);
Assert.Contains("gather state: restored 1 logparser position(s) for 1 rule(s)", text);
Assert.Contains("hpia-log-collect | config | logparser position restored: traced.log", text);
Assert.Contains("traced.log: continuing at position", text);
}
}
}
@@ -0,0 +1,278 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using Newtonsoft.Json;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
{
/// <summary>
/// <see cref="GatherRuleSessionState"/> and <see cref="GatherRuleStatePersistence"/>: what is
/// written, what a restart restores, what it refuses, and when the file is (not) written.
/// </summary>
public sealed class GatherRuleSessionStateTests : IDisposable
{
private readonly TempDirectory _tmp = new TempDirectory();
private readonly TempDirectory _stateDir = new TempDirectory();
private readonly AgentLogger _logger;
public GatherRuleSessionStateTests()
{
_logger = new AgentLogger(_tmp.Path, AgentLogLevel.Info);
}
public void Dispose()
{
_tmp.Dispose();
_stateDir.Dispose();
}
private string StateFile => Path.Combine(_stateDir.Path, GatherRuleStatePersistence.FileName);
private GatherRuleSessionState NewState(string sessionId = "session-a") =>
new GatherRuleSessionState(sessionId, new GatherRuleStatePersistence(_stateDir.Path, _logger), _logger);
private static LogFileHead Head(string text) => LogFileHead.FromBytes(Encoding.UTF8.GetBytes(text));
// ── restore ─────────────────────────────────────────────────────────
[Fact]
public void Positions_and_emitted_hashes_survive_a_restart_of_the_same_session()
{
var first = NewState();
first.CommitLogPosition("RULE-1", @"C:\Logs\a.log", 120, 7, Head("2026-09-28 a.log start"), heldTailStart: -1);
first.CommitEmittedHash("RULE-2", "hash-value");
var second = NewState();
var position = second.PeekLogPosition("RULE-1", @"C:\Logs\a.log");
Assert.NotNull(position);
Assert.Equal(120, position!.Position);
Assert.Equal(7, position.LineNumber);
Assert.True(position.FromPreviousRun);
Assert.Equal("hash-value", second.GetEmittedHashes()["RULE-2"]);
Assert.StartsWith("restored 1 logparser position(s) for 1 rule(s) and 1 on_change value(s)", second.RestoreSummary);
}
[Fact]
public void State_of_another_session_is_ignored()
{
NewState("session-a").CommitLogPosition("RULE-1", @"C:\Logs\a.log", 120, 7, Head("start"), -1);
var rotated = NewState("session-b");
Assert.Null(rotated.PeekLogPosition("RULE-1", @"C:\Logs\a.log"));
Assert.Contains("saved for session session-a, current session is session-b", rotated.RestoreSummary);
}
[Fact]
public void Missing_file_is_a_first_run_and_corrupt_file_a_fresh_start()
{
Assert.StartsWith("no saved state", NewState().RestoreSummary);
File.WriteAllText(StateFile, "not json {{{");
var afterCorruption = NewState();
Assert.StartsWith("saved state discarded", afterCorruption.RestoreSummary);
Assert.Empty(afterCorruption.GetEmittedHashes());
}
[Fact]
public void Tampered_entries_are_dropped_and_the_rest_restored()
{
var data = new GatherRuleStateData
{
SessionId = "session-a",
SavedAtUtc = DateTime.UtcNow,
LogPositions = new List<GatherLogPositionData>
{
new GatherLogPositionData { RuleId = "OK", Path = @"C:\a.log", Position = 10, LineNumber = 1, HeadLength = 10, HeadHash = "h" },
new GatherLogPositionData { RuleId = "NEG", Path = @"C:\b.log", Position = -5, HeadLength = 10, HeadHash = "h" },
new GatherLogPositionData { RuleId = "", Path = @"C:\c.log", Position = 1, HeadLength = 1, HeadHash = "h" },
new GatherLogPositionData { RuleId = "BIGHEAD", Path = @"C:\d.log", Position = 1, HeadLength = 5000, HeadHash = "h" },
new GatherLogPositionData { RuleId = "NOHEAD", Path = @"C:\e.log", Position = 50, HeadLength = 0 },
},
OnChangeHashes = new Dictionary<string, string> { ["GOOD"] = "x", ["EMPTY"] = "" },
};
File.WriteAllText(StateFile, JsonConvert.SerializeObject(data));
var state = NewState();
Assert.NotNull(state.PeekLogPosition("OK", @"C:\a.log"));
Assert.Null(state.PeekLogPosition("NEG", @"C:\b.log"));
Assert.Null(state.PeekLogPosition("BIGHEAD", @"C:\d.log"));
Assert.Null(state.PeekLogPosition("NOHEAD", @"C:\e.log"));
Assert.Equal(new[] { "GOOD" }, state.GetEmittedHashes().Keys.ToArray());
Assert.Contains("5 invalid entries dropped", state.RestoreSummary);
}
[Fact]
public void A_path_no_real_file_can_have_is_dropped_and_never_stops_the_executor()
{
// Path APIs throw on these characters under .NET Framework; a throw here would keep
// every collector host down at every restart of the session.
var data = new GatherRuleStateData
{
SessionId = "session-a",
LogPositions = new List<GatherLogPositionData>
{
new GatherLogPositionData { RuleId = "BAD", Path = "C:\\Logs\\x.|og", Position = 1, HeadLength = 1, HeadHash = "h" },
new GatherLogPositionData { RuleId = "WILD", Path = "C:\\Logs\\*.log", Position = 1, HeadLength = 1, HeadHash = "h" },
new GatherLogPositionData { RuleId = "OK", Path = "C:\\Logs\\ok.log", Position = 1, HeadLength = 1, HeadHash = "h" },
},
};
File.WriteAllText(StateFile, JsonConvert.SerializeObject(data));
var state = NewState();
Assert.NotNull(state.PeekLogPosition("OK", "C:\\Logs\\ok.log"));
Assert.Null(state.PeekLogPosition("BAD", "C:\\Logs\\x.|og"));
Assert.Contains("2 invalid entries dropped", state.RestoreSummary);
}
// ── where reading starts ────────────────────────────────────────────
[Fact]
public void Reading_continues_while_the_file_head_still_matches()
{
var state = NewState();
state.CommitLogPosition("R", @"C:\a.log", 30, 3, Head("2026-09-28 first line\n"), -1);
var start = GatherRuleSessionState.ResolveStart(state.PeekLogPosition("R", @"C:\a.log"), 200,
Head("2026-09-28 first line\nsecond line\nthird"), out var how);
Assert.Equal(30, start);
Assert.Equal(LogReadStart.Continue, how);
}
[Fact]
public void A_shrunk_file_and_a_replaced_file_are_read_from_the_beginning()
{
var state = NewState();
state.CommitLogPosition("R", @"C:\a.log", 30, 3, Head("2026-09-28 first line\n"), -1);
var known = state.PeekLogPosition("R", @"C:\a.log");
Assert.Equal(0, GatherRuleSessionState.ResolveStart(known, 20, Head("2026-09-28 fir"), out var shrunk));
Assert.Equal(LogReadStart.Shrunk, shrunk);
// Replaced and already longer than the old position: only the head tells.
Assert.Equal(0, GatherRuleSessionState.ResolveStart(known, 500, Head("2026-09-30 a new log entirely, much longer"), out var replaced));
Assert.Equal(LogReadStart.Replaced, replaced);
// Shorter than the recorded head although not shorter than the position.
state.CommitLogPosition("S", @"C:\b.log", 5, 1, Head("0123456789abcdef"), -1);
Assert.Equal(0, GatherRuleSessionState.ResolveStart(state.PeekLogPosition("S", @"C:\b.log"), 8, Head("01234567"), out var cut));
Assert.Equal(LogReadStart.Replaced, cut);
}
[Fact]
public void Positions_are_kept_per_rule_for_the_same_file()
{
var state = NewState();
state.CommitLogPosition("RULE-A", @"C:\shared.log", 100, 10, Head("x"), -1);
Assert.Null(state.PeekLogPosition("RULE-B", @"C:\shared.log"));
Assert.NotNull(state.PeekLogPosition("RULE-A", @"C:\SHARED.LOG")); // paths compare case-insensitively
}
// ── when the file is written ────────────────────────────────────────
[Fact]
public void An_unchanged_commit_does_not_write_the_file()
{
var state = NewState();
state.CommitLogPosition("R", @"C:\a.log", 10, 1, Head("head"), -1);
File.Delete(StateFile);
state.CommitLogPosition("R", @"C:\a.log", 10, 1, Head("head"), -1);
state.CommitEmittedHash("H", "v");
File.Delete(StateFile);
state.CommitEmittedHash("H", "v");
Assert.False(File.Exists(StateFile));
}
[Fact]
public void A_failed_save_is_retried_at_the_next_commit()
{
var blocked = Path.Combine(_stateDir.Path, "blocked");
File.WriteAllText(blocked, "a file where the state directory should be");
var state = new GatherRuleSessionState("session-a", new GatherRuleStatePersistence(blocked, _logger), _logger);
state.CommitEmittedHash("H", "v"); // Directory.CreateDirectory fails
File.Delete(blocked);
state.CommitEmittedHash("H", "v"); // unchanged, but the earlier save is still owed
Assert.True(File.Exists(Path.Combine(blocked, GatherRuleStatePersistence.FileName)));
}
[Fact]
public void A_closed_state_no_longer_writes()
{
var state = NewState();
state.Close();
state.CommitEmittedHash("H", "v");
Assert.False(File.Exists(StateFile));
}
[Fact]
public void Without_persistence_nothing_is_written()
{
var state = new GatherRuleSessionState("session-a", null, _logger);
state.CommitLogPosition("R", @"C:\a.log", 10, 1, Head("head"), -1);
Assert.StartsWith("persistence off", state.RestoreSummary);
Assert.Empty(Directory.GetFiles(_stateDir.Path));
}
// ── bounds and concurrency ──────────────────────────────────────────
[Fact]
public void A_rule_forgets_its_least_recently_touched_file_beyond_the_cap()
{
var state = NewState();
for (var i = 0; i < GatherRuleSessionState.MaxLogFilesPerRule; i++)
state.CommitLogPosition("R", $@"C:\logs\{i}.log", 1, 1, Head("h"), -1);
state.PeekLogPosition("R", @"C:\logs\0.log"); // touched again — survives
state.CommitLogPosition("R", @"C:\logs\new.log", 1, 1, Head("h"), -1);
Assert.NotNull(state.PeekLogPosition("R", @"C:\logs\0.log"));
Assert.Null(state.PeekLogPosition("R", @"C:\logs\1.log"));
Assert.NotNull(state.PeekLogPosition("R", @"C:\logs\new.log"));
}
[Fact]
public void Parallel_commits_leave_a_consistent_file()
{
var state = NewState();
Parallel.For(0, 8, worker =>
{
for (var i = 0; i < 50; i++)
{
state.CommitLogPosition($"RULE-{worker}", $@"C:\logs\{worker}.log", i + 1, i, Head("h"), -1);
state.PeekLogPosition($"RULE-{worker}", $@"C:\logs\{worker}.log");
state.CommitEmittedHash($"RULE-{worker}", "hash-" + i);
}
});
var restored = NewState();
for (var worker = 0; worker < 8; worker++)
{
Assert.Equal(50, restored.PeekLogPosition($"RULE-{worker}", $@"C:\logs\{worker}.log")!.Position);
Assert.Equal("hash-49", restored.GetEmittedHashes()[$"RULE-{worker}"]);
}
}
}
}
@@ -0,0 +1,188 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
{
/// <summary>
/// <see cref="LogLineReader"/>, <see cref="LogTextEncoding"/> and <see cref="LogFileHead"/>:
/// exact byte positions, StreamReader-compatible line ends, byte order marks only at offset 0,
/// and the code-unit view of UTF-16/UTF-32 files.
/// </summary>
public sealed class LogLineReaderTests
{
private static byte[] Bytes(Encoding encoding, string text, bool withBom = true)
{
var body = encoding.GetBytes(text);
return withBom ? encoding.GetPreamble().Concat(body).ToArray() : body;
}
private static (List<string> Lines, List<long> EndPositions, List<bool> Terminated) ReadAll(
byte[] file, long start = 0, int maxLineBytes = 1024)
{
var encoding = LogFileHead.FromBytes(file.Take(LogFileHead.MaxBytes).ToArray()).Encoding;
using (var stream = new MemoryStream(file))
{
stream.Seek(start, SeekOrigin.Begin);
var reader = new LogLineReader(stream, encoding, maxLineBytes);
var lines = new List<string>();
var ends = new List<long>();
var terminated = new List<bool>();
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
ends.Add(reader.Position);
terminated.Add(reader.LastLineTerminated);
}
return (lines, ends, terminated);
}
}
[Fact]
public void Line_ends_match_StreamReader_including_a_lone_carriage_return()
{
var file = Encoding.UTF8.GetBytes("one\ntwo\r\nthree\rfour");
var result = ReadAll(file);
Assert.Equal(new[] { "one", "two", "three", "four" }, result.Lines);
Assert.Equal(new long[] { 4, 9, 15, 19 }, result.EndPositions);
Assert.Equal(new[] { true, true, true, false }, result.Terminated);
}
[Fact]
public void Position_after_each_line_is_the_offset_to_resume_from()
{
var file = Encoding.UTF8.GetBytes("alpha\nbeta\ngamma\n");
var first = ReadAll(file);
var resumed = ReadAll(file, start: first.EndPositions[0]);
Assert.Equal(new[] { "beta", "gamma" }, resumed.Lines);
Assert.Equal(file.Length, resumed.EndPositions.Last());
}
[Fact]
public void Utf8_byte_order_mark_is_skipped_only_at_offset_0()
{
var file = Bytes(Encoding.UTF8, "first\nsecond\n");
var result = ReadAll(file);
Assert.Equal(new[] { "first", "second" }, result.Lines);
Assert.Equal(LogTextEncoding.Utf8WithBom, LogFileHead.FromBytes(file).Encoding);
}
[Theory]
[InlineData("utf-16le")]
[InlineData("utf-16be")]
[InlineData("utf-32le")]
[InlineData("utf-32be")]
public void Unicode_files_are_read_in_their_code_units_from_any_resume_point(string name)
{
var encoding = name == "utf-16le" ? Encoding.Unicode
: name == "utf-16be" ? Encoding.BigEndianUnicode
: name == "utf-32le" ? Encoding.UTF32
: new UTF32Encoding(bigEndian: true, byteOrderMark: true);
var file = Bytes(encoding, "ERROR first\r\nERROR zweite Zeile mit Umlaut äöü\r\n");
var whole = ReadAll(file);
var resumed = ReadAll(file, start: whole.EndPositions[0]);
Assert.Equal(name, LogFileHead.FromBytes(file).Encoding.Name);
Assert.Equal(new[] { "ERROR first", "ERROR zweite Zeile mit Umlaut äöü" }, whole.Lines);
Assert.Equal(new[] { "ERROR zweite Zeile mit Umlaut äöü" }, resumed.Lines);
Assert.Equal(file.Length, whole.EndPositions.Last());
}
[Fact]
public void File_without_byte_order_mark_is_utf8_and_ansi_bytes_decode_as_before()
{
var file = new byte[] { (byte)'M', (byte)'a', (byte)'n', 0xFC, (byte)'\n' }; // "Man" + Windows-1252 'ü'
var result = ReadAll(file);
Assert.Equal(LogTextEncoding.Utf8, LogFileHead.FromBytes(file).Encoding);
Assert.Equal(new StreamReader(new MemoryStream(file), Encoding.UTF8).ReadLine(), result.Lines.Single());
}
[Fact]
public void Carriage_return_at_end_of_file_ends_the_line_and_its_late_line_feed_is_skipped()
{
var firstWrite = Encoding.UTF8.GetBytes("done\r");
var later = Encoding.UTF8.GetBytes("done\r\nnext\n");
var first = ReadAll(firstWrite);
var resumed = ReadAll(later, start: first.EndPositions.Last());
Assert.Equal(new[] { "done" }, first.Lines);
Assert.True(first.Terminated.Single());
Assert.Equal(new[] { "next" }, resumed.Lines);
}
[Fact]
public void Overlong_line_is_consumed_without_being_kept_and_reading_continues_behind_it()
{
var file = Encoding.UTF8.GetBytes(new string('x', 50) + "\nshort\n");
using (var stream = new MemoryStream(file))
{
var reader = new LogLineReader(stream, LogTextEncoding.Utf8, maxLineBytes: 10);
Assert.Equal(string.Empty, reader.ReadLine());
Assert.True(reader.LastLineTruncated);
Assert.Equal(51, reader.Position);
Assert.Equal("short", reader.ReadLine());
Assert.False(reader.LastLineTruncated);
Assert.Null(reader.ReadLine());
}
}
[Fact]
public void Line_spanning_many_read_buffers_is_returned_whole()
{
var longLine = new string('y', 200_000);
var file = Encoding.UTF8.GetBytes(longLine + "\nend\n");
var result = ReadAll(file, maxLineBytes: 1_000_000);
Assert.Equal(new[] { longLine, "end" }, result.Lines);
}
[Fact]
public void Half_written_utf16_character_at_end_of_file_stays_in_the_unterminated_line()
{
var full = Bytes(Encoding.Unicode, "ok\r\nhalf");
var file = full.Concat(new byte[] { 0x41 }).ToArray(); // first byte of the next UTF-16 unit
var result = ReadAll(file);
Assert.Equal("ok", result.Lines[0]);
Assert.False(result.Terminated.Last());
Assert.Equal(file.Length, result.EndPositions.Last());
}
[Fact]
public void AlignDown_snaps_to_code_units_behind_the_byte_order_mark()
{
Assert.Equal(0, LogTextEncoding.Utf16LittleEndian.AlignDown(1));
Assert.Equal(2, LogTextEncoding.Utf16LittleEndian.AlignDown(3));
Assert.Equal(6, LogTextEncoding.Utf16LittleEndian.AlignDown(7));
Assert.Equal(8, LogTextEncoding.Utf32LittleEndian.AlignDown(11));
Assert.Equal(7, LogTextEncoding.Utf8.AlignDown(7));
}
[Fact]
public void Head_hash_of_a_prefix_matches_the_hash_of_the_shorter_file()
{
var shortFile = LogFileHead.FromBytes(Encoding.UTF8.GetBytes("2026-09-28 start"));
var grown = LogFileHead.FromBytes(Encoding.UTF8.GetBytes("2026-09-28 start\nmore lines"));
Assert.Equal(shortFile.Hash(shortFile.Length), grown.Hash(shortFile.Length));
Assert.NotEqual(shortFile.Hash(shortFile.Length), grown.Hash(grown.Length));
}
}
}
@@ -37,7 +37,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
logger, "sess", "tenant",
evt => _events.Add(evt),
null,
new LogFilePositionTracker(),
new GatherRuleSessionState("sess", null, logger),
new GatherRuleDebugLog(_debugLogPath, logger))
{
UnrestrictedMode = true
@@ -0,0 +1,225 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Shared.Models;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
{
/// <summary>
/// Reading semantics of <see cref="LogParserCollector"/> across runs on one context: every
/// line of a growing log is matched exactly once — no line lost at a maxLines cut, no line
/// split by a writer that is mid-line, UTF-16 logs readable after the first run, positions
/// kept per rule, line numbers counted from the start of the file.
/// </summary>
public sealed class LogParserCollectorReadingTests : IDisposable
{
private readonly TempDirectory _tmp = new TempDirectory();
private readonly List<EnrollmentEvent> _events = new List<EnrollmentEvent>();
private readonly GatherRuleContext _context;
// %TEMP% lives under C:\Users (hard-blocked) — parse targets sit beside the
// test assembly instead, admitted via UnrestrictedMode.
private readonly string _logDir = Path.Combine(
AppContext.BaseDirectory, "gather-reading-tests-" + Guid.NewGuid().ToString("N"));
public LogParserCollectorReadingTests()
{
Directory.CreateDirectory(_logDir);
_context = NewContext();
}
public void Dispose()
{
_tmp.Dispose();
try { Directory.Delete(_logDir, recursive: true); } catch { /* best effort */ }
}
private GatherRuleContext NewContext()
{
var logger = new AgentLogger(_tmp.Path, AgentLogLevel.Info);
return new GatherRuleContext(logger, "sess", "tenant",
evt => _events.Add(evt), null, new GatherRuleSessionState("sess", null, logger))
{
UnrestrictedMode = true
};
}
private string LogPath(string name) => Path.Combine(_logDir, name);
private static GatherRule TextRule(string ruleId, string target, string pattern,
string trigger = "interval", int? maxLines = null)
{
var parameters = new Dictionary<string, string> { ["pattern"] = pattern, ["format"] = "text" };
if (maxLines.HasValue) parameters["maxLines"] = maxLines.Value.ToString();
return new GatherRule
{
RuleId = ruleId,
Title = ruleId,
CollectorType = "logparser",
Target = target,
Parameters = parameters,
Trigger = trigger,
IntervalSeconds = trigger == "interval" ? 30 : (int?)null,
OutputEventType = "logparser_reading_test",
};
}
private List<string> Captured(string group) =>
_events.Select(e => e.Data.TryGetValue(group, out var v) ? (string)v : "<missing>").ToList();
[Fact]
public void Two_rules_on_one_file_each_read_the_whole_file()
{
var path = LogPath("shared.log");
File.WriteAllText(path, "ERROR one\nWARN two\nERROR three\n");
var collector = new LogParserCollector();
collector.Execute(TextRule("RULE-ERRORS", path, "^ERROR (?<what>\\w+)"), _context);
collector.Execute(TextRule("RULE-WARNINGS", path, "^WARN (?<what>\\w+)"), _context);
Assert.Equal(2, _events.Count(e => (string)e.Data["ruleId"] == "RULE-ERRORS"));
Assert.Single(_events, e => (string)e.Data["ruleId"] == "RULE-WARNINGS");
}
[Fact]
public void MaxLines_cut_loses_no_line_across_runs()
{
var path = LogPath("long.log");
var sb = new StringBuilder();
for (var i = 1; i <= 30; i++)
sb.Append("hit ").Append(i.ToString("D3")).Append(' ').Append('x', 90).Append('\n');
File.WriteAllText(path, sb.ToString());
var rule = TextRule("RULE-LONG", path, "^hit (?<n>\\d{3})", maxLines: 10);
var collector = new LogParserCollector();
for (var run = 0; run < 6; run++)
collector.Execute(rule, _context);
var expected = Enumerable.Range(1, 30).Select(i => i.ToString("D3")).ToList();
Assert.Equal(expected, Captured("n"));
}
[Fact]
public void Line_written_in_two_parts_is_matched_once_and_whole()
{
var path = LogPath("partial.log");
File.WriteAllText(path, "ERR");
var rule = TextRule("RULE-PARTIAL", path, "^ERROR (?<code>0x[0-9A-F]+)$");
var collector = new LogParserCollector();
collector.Execute(rule, _context); // the writer is mid-line
File.AppendAllText(path, "OR 0x1F\n");
collector.Execute(rule, _context);
Assert.Equal(new List<string> { "0x1F" }, Captured("code"));
}
[Fact]
public void Interval_rule_reads_a_line_still_unfinished_on_its_second_run_once()
{
var path = LogPath("never-terminated.log");
File.WriteAllText(path, "ERROR 0x2A");
var rule = TextRule("RULE-UNFINISHED", path, "^ERROR (?<code>0x[0-9A-F]+)$");
var collector = new LogParserCollector();
collector.Execute(rule, _context); // held: the writer may still be in the line
collector.Execute(rule, _context); // still unfinished — taken as it is
collector.Execute(rule, _context); // nothing new
Assert.Equal(new List<string> { "0x2A" }, Captured("code"));
}
[Fact]
public void One_shot_rule_reads_an_unfinished_line_now_and_whole_on_its_next_run()
{
var path = LogPath("startup.log");
File.WriteAllText(path, "ok\nERR");
var rule = TextRule("RULE-STARTUP", path, "^ERR(?<rest>.*)$", trigger: "startup");
var collector = new LogParserCollector();
collector.Execute(rule, _context); // agent start: the writer is mid-line
File.AppendAllText(path, "OR 0x1F\n");
collector.Execute(rule, _context); // next agent start
// Read twice, never split: the second read sees the whole line.
Assert.Equal(new List<string> { "", "OR 0x1F" }, Captured("rest"));
Assert.Equal(new long[] { 2, 2 }, _events.Select(e => Convert.ToInt64(e.Data["logLineNumber"])).ToArray());
}
[Fact]
public void Line_feed_written_after_a_trailing_carriage_return_is_consumed_without_a_line()
{
var path = LogPath("cr-at-end.log");
File.WriteAllText(path, "hit\r");
var rule = TextRule("RULE-CR", path, "^hit$");
var collector = new LogParserCollector();
collector.Execute(rule, _context);
File.AppendAllText(path, "\n");
collector.Execute(rule, _context);
Assert.Single(_events);
var position = _context.SessionState.PeekLogPosition("RULE-CR", path);
Assert.Equal(new FileInfo(path).Length, position!.Position);
Assert.Equal(1, position.LineNumber);
}
[Fact]
public void Utf16_log_appended_after_the_first_run_is_still_matched()
{
var path = LogPath("transcript.log");
File.WriteAllText(path, "ERROR first\r\n", Encoding.Unicode); // UTF-16 LE with BOM
var rule = TextRule("RULE-UTF16", path, "^ERROR (?<what>\\w+)$");
var collector = new LogParserCollector();
collector.Execute(rule, _context);
using (var stream = new FileStream(path, FileMode.Append, FileAccess.Write))
{
var bytes = new UnicodeEncoding(bigEndian: false, byteOrderMark: false).GetBytes("ERROR second\r\n");
stream.Write(bytes, 0, bytes.Length);
}
collector.Execute(rule, _context);
Assert.Equal(new List<string> { "first", "second" }, Captured("what"));
}
[Theory]
[InlineData("abc")]
[InlineData("0")]
[InlineData("-5")]
public void MaxLines_that_is_no_positive_number_falls_back_to_the_default(string maxLines)
{
var path = LogPath("misconfigured.log");
File.WriteAllText(path, "hit 1\nhit 2\n");
var rule = TextRule("RULE-MISCONFIGURED", path, "^hit (?<n>\\d)$");
rule.Parameters["maxLines"] = maxLines;
new LogParserCollector().Execute(rule, _context);
Assert.Equal(new List<string> { "1", "2" }, Captured("n"));
}
[Fact]
public void Line_numbers_count_from_the_start_of_the_file()
{
var path = LogPath("numbers.log");
File.WriteAllText(path, "a\nhit\nb\n");
var rule = TextRule("RULE-NUMBERS", path, "^hit$");
var collector = new LogParserCollector();
collector.Execute(rule, _context);
File.AppendAllText(path, "c\nhit\n");
collector.Execute(rule, _context);
Assert.Equal(new long[] { 2, 5 }, _events.Select(e => Convert.ToInt64(e.Data["logLineNumber"])).ToArray());
}
}
}
@@ -35,7 +35,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
tenantId: "tenant",
onEventCollected: _ => { },
imeLogPathOverride: null,
filePositionTracker: new LogFilePositionTracker())
sessionState: new GatherRuleSessionState("sess", null, logger))
{
// Bypass the registry allowlist guard for the synthetic test path.
UnrestrictedMode = true
@@ -337,7 +337,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
"Launch powershell executor in machine session",
new[] { "context=machine" }
};
// Wording from the IME decompile (ContentDownloaderDeliveryOptimization, identical 1.97–1.105).
// IME wording, identical from 1.97 to 1.105.
yield return new object[]
{
"IME-DO-TIMEOUT-2",
@@ -19,6 +19,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
/// completion markers (whiteglove.complete, clean-exit) — V1 sessions had only AgentLogs/
/// and ImeLogs/, which left forensics blind to decision-engine state and pending uploads.
/// </summary>
[Collection(UserProfileResolverCollection.Name)] // replaces UserProfileResolver's static state
public sealed class DiagnosticsPackageServiceTests
{
private static AgentConfiguration Cfg(string sessionId = "S1") => new AgentConfiguration
@@ -0,0 +1,96 @@
using System;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
{
/// <summary>
/// Serialises the test classes that replace <see cref="UserProfileResolver"/>'s static state.
/// </summary>
[CollectionDefinition(Name)]
public sealed class UserProfileResolverCollection
{
public const string Name = "UserProfileResolver";
}
/// <summary>
/// The agent starts before anyone has signed in. A lookup in that window must not pin
/// "no user" for the rest of the process — the %LOGGED_ON_USER_PROFILE% gather rules and the
/// RealmJoin user logs of the diagnostics package would never resolve.
/// </summary>
[Collection(UserProfileResolverCollection.Name)]
public sealed class UserProfileResolverTests : IDisposable
{
private static readonly DateTime Start = new DateTime(2026, 9, 28, 12, 0, 0, DateTimeKind.Utc);
public void Dispose() => UserProfileResolver.Reset();
[Fact]
public void User_who_signs_in_after_the_first_lookup_is_found_later()
{
string? signedIn = null;
var now = Start;
UserProfileResolver.SetDetectorForTesting(() => signedIn, () => now);
Assert.Null(UserProfileResolver.GetLoggedOnUserProfilePath());
signedIn = @"C:\Users\enduser";
now += UserProfileResolver.RetryInterval;
Assert.Equal(@"C:\Users\enduser", UserProfileResolver.GetLoggedOnUserProfilePath());
}
[Fact]
public void No_user_is_detected_again_only_after_the_retry_interval()
{
var detections = 0;
var now = Start;
UserProfileResolver.SetDetectorForTesting(() => { detections++; return null; }, () => now);
UserProfileResolver.GetLoggedOnUserProfilePath();
now += TimeSpan.FromSeconds(10);
UserProfileResolver.GetLoggedOnUserProfilePath();
UserProfileResolver.GetLoggedOnUserProfilePath();
Assert.Equal(1, detections);
now += UserProfileResolver.RetryInterval;
UserProfileResolver.GetLoggedOnUserProfilePath();
Assert.Equal(2, detections);
}
[Fact]
public void A_clock_stepping_backwards_does_not_delay_the_next_detection()
{
var detections = 0;
var now = Start;
UserProfileResolver.SetDetectorForTesting(() => { detections++; return null; }, () => now);
UserProfileResolver.GetLoggedOnUserProfilePath();
now -= TimeSpan.FromHours(1); // OOBE time sync
UserProfileResolver.GetLoggedOnUserProfilePath();
Assert.Equal(2, detections);
}
[Fact]
public void A_found_user_is_kept_without_detecting_again()
{
var detections = 0;
UserProfileResolver.SetDetectorForTesting(() => { detections++; return @"C:\Users\enduser"; }, () => Start);
UserProfileResolver.GetLoggedOnUserProfilePath();
UserProfileResolver.GetLoggedOnUserProfilePath();
Assert.Equal(1, detections);
}
[Fact]
public void Pinned_no_user_stays_null_without_real_detection()
{
UserProfileResolver.SetForTesting(null!);
Assert.Null(UserProfileResolver.GetLoggedOnUserProfilePath());
Assert.Null(UserProfileResolver.ExpandCustomTokens(@"%LOGGED_ON_USER_PROFILE%\AppData\Local\x.log"));
}
}
}
@@ -61,7 +61,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
// IME AppInstallStatus values (StatusServiceReports\..\Status), stable IME 1.50 .. 1.106.
// 1001/1003 sit inside the 1000 band but are NOT terminal — IME maps every InProgress
// enforcement state to 1001 (verified in the decompiled 1.106 StatusServiceHelpers).
// enforcement state to 1001 (verified against IME 1.106).
[Theory]
[InlineData(1000, "installed")]
[InlineData(1002, "installed")]
@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using AutopilotMonitor.Agent.V2.Core.Configuration;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
using AutopilotMonitor.Agent.V2.Core.Orchestration;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Shared.Models;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
{
/// <summary>
/// The production factory hands its state directory to the gather executor. Without it every
/// unit test of the gather state passes while the agent keeps replaying logs after each reboot —
/// the one line in <see cref="DefaultComponentFactory"/> is the whole feature.
/// </summary>
[Collection("SerialThreading")] // the startup rule executes on the shared ThreadPool
public sealed class DefaultComponentFactoryGatherStateTests : IDisposable
{
private readonly TempDirectory _tmp = new TempDirectory();
private readonly TempDirectory _stateDir = new TempDirectory();
// %TEMP% lives under C:\Users (hard-blocked) — the log sits beside the test assembly.
private readonly string _logDir = Path.Combine(
AppContext.BaseDirectory, "factory-gather-state-" + Guid.NewGuid().ToString("N"));
public DefaultComponentFactoryGatherStateTests() => Directory.CreateDirectory(_logDir);
public void Dispose()
{
_tmp.Dispose();
_stateDir.Dispose();
try { Directory.Delete(_logDir, recursive: true); } catch { /* best effort */ }
}
[Fact]
public void Gather_host_built_by_the_factory_persists_logparser_positions_in_the_state_directory()
{
var log = Path.Combine(_logDir, "vendor.log");
File.WriteAllText(log, "Update one\n");
var factory = new DefaultComponentFactory(
agentConfig: new AgentConfiguration
{
ApiBaseUrl = "https://example",
TenantId = "t",
SessionId = "s",
UnrestrictedMode = true,
},
remoteConfig: new AgentConfigResponse
{
Collectors = CollectorConfiguration.CreateDefault(),
GatherRules = new List<GatherRule>
{
new GatherRule
{
RuleId = "vendor-log",
Title = "vendor log",
CollectorType = "logparser",
Target = log,
Parameters = new Dictionary<string, string> { ["pattern"] = "^Update", ["format"] = "text" },
Trigger = "startup",
OutputEventType = "vendor_update",
Enabled = true,
},
},
},
networkMetrics: null,
agentVersion: "test",
stateDirectory: _stateDir.Path,
startupEventGate: null);
var hosts = factory.CreateCollectorHosts(
sessionId: "s",
tenantId: "t",
logger: new AgentLogger(_tmp.Path, AgentLogLevel.Info),
whiteGloveSealingPatternIds: Array.Empty<string>(),
ingress: new FakeSignalIngressSink(),
clock: new VirtualClock(new DateTime(2026, 9, 28, 12, 0, 0, DateTimeKind.Utc)),
telemetrySpool: null,
timelineEvents: null).Hosts;
try
{
hosts.OfType<GatherRuleExecutorHost>().Single().Start();
var stateFile = Path.Combine(_stateDir.Path, GatherRuleStatePersistence.FileName);
Assert.True(SpinWait.SpinUntil(() => File.Exists(stateFile), TimeSpan.FromSeconds(10)),
"the gather host did not write its state into the factory's state directory");
}
finally
{
foreach (var host in hosts)
{
try { host.Dispose(); } catch { /* best-effort cleanup */ }
}
}
}
}
}
@@ -16,7 +16,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
/// <summary>
/// GatherRuleExecutorHost feeds its phase_change / phase_exit / on_event triggers from the
/// POST-REDUCE <see cref="TimelineEventStream"/> (emitted timeline events), not from raw
/// signals. Regression anchor: session 32312a32 (rsneuffen.de) — a phase_change rule on
/// signals. Regression anchor: session 32312a32 — a phase_change rule on
/// FinalizingSetup fired at the raw EspPhaseChanged(FinalizingSetup) signal (ESP exit),
/// 7 minutes before the engine's RealmJoin-gated phase_transition(FinalizingSetup), and read
/// a registry key before the RealmJoin package wrote it. With the timeline feed the rule
@@ -58,8 +58,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
/// (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
/// AppActionProcessor.log: plugins hosted in IntuneManagementExtension.exe, verified against
/// the IME 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>
@@ -4,9 +4,9 @@ using System.Collections.Generic;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
{
/// <summary>
/// Tracks file read positions for incremental log file reading.
/// In-memory only - resets on agent restart, which is acceptable since
/// we start fresh per enrollment session.
/// Tracks the IME log tracker's file read positions for incremental log file reading.
/// The bookmarks survive agent restarts through the tracker's own state file
/// (<see cref="GetAllPositions"/> / <see cref="RestorePosition"/>); the freshness timestamps do not.
/// </summary>
public class LogFilePositionTracker
{
@@ -360,7 +360,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
: (DateTime?)null;
}
/// <summary>StateMessageEnforcementState bands (verified against decompiled IME 1.97/1.104).</summary>
/// <summary>StateMessageEnforcementState bands (verified against IME 1.97/1.104).</summary>
internal static string ClassifyEnforcementState(int state)
{
if (state >= 1000 && state < 2000) return "success";
@@ -472,7 +472,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
// Expand BEFORE the guard: the guard must judge the path that is read,
// and an unresolved token is not a path it can judge.
var expandedPath = UserProfileResolver.ExpandCustomTokens(entry.Path);
var expandedPath = UserProfileResolver.ExpandCustomTokens(entry.Path, userProfilePath);
if (expandedPath == null)
{
_logger.Warning($"Diagnostics path skipped (no user session for token): {entry.Path}");
@@ -1,6 +1,7 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
@@ -14,7 +15,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
/// The agent runs as SYSTEM, so standard environment variables like %USERPROFILE% or
/// %LOCALAPPDATA% resolve to the SYSTEM profile — not the logged-on user. This class
/// detects the real user via explorer.exe ownership (WTS session query, WMI fallback —
/// see <see cref="Interop.ProcessOwnerLookup"/>) and caches the result for the agent's lifetime.
/// see <see cref="Interop.ProcessOwnerLookup"/>) and caches the first user it finds for the
/// agent's lifetime. "No user yet" is not cached: the agent usually starts before anyone has
/// signed in, so detection is retried — at most every <see cref="RetryInterval"/>.
///
/// Usage in paths: %LOGGED_ON_USER_PROFILE%\AppData\Local\RealmJoin\Logs\*.log
/// </summary>
@@ -23,9 +26,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
// Spelled once, in Shared: the built-in diagnostics catalog uses the same token.
public const string Token = Shared.Models.DiagnosticsBuiltInSections.UserProfileToken;
/// <summary>Minimum time between two detections while no user has been found.</summary>
internal static readonly TimeSpan RetryInterval = TimeSpan.FromSeconds(30);
private static readonly object Lock = new object();
private static bool _resolved;
private static string _userProfilePath; // e.g. C:\Users\JohnDoe — null if no user detected
private static string _userProfilePath; // e.g. C:\Users\JohnDoe — null until a user is detected
private static DateTime _lastFailedDetectionUtc = DateTime.MinValue;
// Seams for tests; production uses the real detection and clock.
private static Func<string> _detector = DetectLoggedOnUserProfile;
private static Func<DateTime> _utcNow = () => DateTime.UtcNow;
/// <summary>
/// Returns the logged-on user's profile path (e.g. C:\Users\JohnDoe) or null
@@ -34,17 +44,28 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
/// </summary>
public static string GetLoggedOnUserProfilePath()
{
if (_resolved)
return _userProfilePath;
var cached = Volatile.Read(ref _userProfilePath);
if (cached != null)
return cached;
lock (Lock)
{
if (_resolved)
if (_userProfilePath != null)
return _userProfilePath;
_userProfilePath = DetectLoggedOnUserProfile();
_resolved = true;
return _userProfilePath;
// A clock that stepped backwards (common during OOBE) never delays the retry.
var now = _utcNow();
var sinceLastFailure = now - _lastFailedDetectionUtc;
if (_lastFailedDetectionUtc != DateTime.MinValue
&& sinceLastFailure >= TimeSpan.Zero && sinceLastFailure < RetryInterval)
return null;
var detected = _detector();
if (detected != null)
Volatile.Write(ref _userProfilePath, detected);
else
_lastFailedDetectionUtc = now;
return detected;
}
}
@@ -53,18 +74,26 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
/// Environment.ExpandEnvironmentVariables for standard tokens.
/// Returns null if the path contains the token but no user is logged on.
/// </summary>
public static string ExpandCustomTokens(string rawPath)
public static string ExpandCustomTokens(string rawPath) =>
ExpandCustomTokens(rawPath, ContainsUserProfileToken(rawPath) ? GetLoggedOnUserProfilePath() : null);
/// <summary>
/// Same, with the profile path the caller already resolved for its guard. Callers that
/// guard the expanded path must use this overload: while detection is still retrying, a
/// second lookup can find the user the first one missed, and the guard would then judge a
/// C:\Users path without the profile that admits it.
/// </summary>
public static string ExpandCustomTokens(string rawPath, string userProfilePath)
{
if (string.IsNullOrEmpty(rawPath))
return rawPath;
if (rawPath.IndexOf(Token, StringComparison.OrdinalIgnoreCase) >= 0)
{
var profilePath = GetLoggedOnUserProfilePath();
if (profilePath == null)
if (userProfilePath == null)
return null; // No user detected — caller should skip this path
rawPath = ReplaceCaseInsensitive(rawPath, Token, profilePath);
rawPath = ReplaceCaseInsensitive(rawPath, Token, userProfilePath);
}
return Environment.ExpandEnvironmentVariables(rawPath);
@@ -80,26 +109,37 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
}
/// <summary>
/// Resets the cached state. Only used for testing.
/// Resets the cached state and the seams. Only used for testing.
/// </summary>
internal static void Reset()
{
lock (Lock)
{
_resolved = false;
_userProfilePath = null;
_lastFailedDetectionUtc = DateTime.MinValue;
_detector = DetectLoggedOnUserProfile;
_utcNow = () => DateTime.UtcNow;
}
}
/// <summary>
/// Allows tests to inject a specific profile path without WMI.
/// Allows tests to inject a specific profile path without WMI. Null pins "no user signed in"
/// — detection keeps answering null instead of finding the developer's own session.
/// </summary>
internal static void SetForTesting(string profilePath)
{
SetDetectorForTesting(() => profilePath, () => DateTime.UtcNow);
}
/// <summary>Replaces detection and clock, clearing what was cached. Only used for testing.</summary>
internal static void SetDetectorForTesting(Func<string> detector, Func<DateTime> utcNow)
{
lock (Lock)
{
_userProfilePath = profilePath;
_resolved = true;
_userProfilePath = null;
_lastFailedDetectionUtc = DateTime.MinValue;
_detector = detector ?? throw new ArgumentNullException(nameof(detector));
_utcNow = utcNow ?? throw new ArgumentNullException(nameof(utcNow));
}
}
@@ -23,7 +23,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
// Expand custom tokens (%LOGGED_ON_USER_PROFILE%) and standard environment variables
var userProfilePath = UserProfileResolver.ContainsUserProfileToken(filePath)
? UserProfileResolver.GetLoggedOnUserProfilePath() : null;
filePath = UserProfileResolver.ExpandCustomTokens(filePath);
filePath = UserProfileResolver.ExpandCustomTokens(filePath, userProfilePath);
if (filePath == null)
return data; // Token present but no user logged on — skip silently
@@ -24,7 +24,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
// Expand custom tokens (%LOGGED_ON_USER_PROFILE%) and standard environment variables
var userProfilePath = UserProfileResolver.ContainsUserProfileToken(filePath)
? UserProfileResolver.GetLoggedOnUserProfilePath() : null;
filePath = UserProfileResolver.ExpandCustomTokens(filePath);
filePath = UserProfileResolver.ExpandCustomTokens(filePath, userProfilePath);
if (filePath == null)
return data; // Token present but no user logged on — skip silently
@@ -0,0 +1,313 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
{
/// <summary>
/// Text encoding of a log file as the logparser reads it. Chosen from the byte order mark at
/// the start of the file in <see cref="StreamReader"/>'s detection order; without one the file
/// is UTF-8, which is also how ANSI logs were always read (invalid bytes decode to U+FFFD).
/// </summary>
internal sealed class LogTextEncoding
{
public static readonly LogTextEncoding Utf8 = new LogTextEncoding("utf-8", new UTF8Encoding(false), 1, 0);
public static readonly LogTextEncoding Utf8WithBom = new LogTextEncoding("utf-8 with bom", new UTF8Encoding(false), 1, 3);
public static readonly LogTextEncoding Utf16LittleEndian = new LogTextEncoding("utf-16le", new UnicodeEncoding(false, false), 2, 2);
public static readonly LogTextEncoding Utf16BigEndian = new LogTextEncoding("utf-16be", new UnicodeEncoding(true, false), 2, 2);
public static readonly LogTextEncoding Utf32LittleEndian = new LogTextEncoding("utf-32le", new UTF32Encoding(false, false), 4, 4);
public static readonly LogTextEncoding Utf32BigEndian = new LogTextEncoding("utf-32be", new UTF32Encoding(true, false), 4, 4);
private LogTextEncoding(string name, Encoding encoding, int unitSize, int byteOrderMarkLength)
{
Name = name;
Encoding = encoding;
UnitSize = unitSize;
ByteOrderMarkLength = byteOrderMarkLength;
LineFeed = encoding.GetBytes("\n");
CarriageReturn = encoding.GetBytes("\r");
}
public string Name { get; }
public Encoding Encoding { get; }
/// <summary>Bytes per code unit; every line boundary lies on a unit boundary.</summary>
public int UnitSize { get; }
/// <summary>Length of the byte order mark at offset 0 — skipped, never part of a line.</summary>
public int ByteOrderMarkLength { get; }
public byte[] LineFeed { get; }
public byte[] CarriageReturn { get; }
public static LogTextEncoding Detect(byte[] head)
{
if (StartsWith(head, 0xEF, 0xBB, 0xBF)) return Utf8WithBom;
if (StartsWith(head, 0xFF, 0xFE, 0x00, 0x00)) return Utf32LittleEndian;
if (StartsWith(head, 0xFF, 0xFE)) return Utf16LittleEndian;
if (StartsWith(head, 0xFE, 0xFF)) return Utf16BigEndian;
if (StartsWith(head, 0x00, 0x00, 0xFE, 0xFF)) return Utf32BigEndian;
return Utf8;
}
/// <summary>The last code-unit boundary at or before <paramref name="position"/>.</summary>
public long AlignDown(long position)
{
if (position <= ByteOrderMarkLength) return position < ByteOrderMarkLength ? 0 : position;
return position - (position - ByteOrderMarkLength) % UnitSize;
}
private static bool StartsWith(byte[] bytes, params byte[] prefix)
{
if (bytes.Length < prefix.Length) return false;
for (var i = 0; i < prefix.Length; i++)
if (bytes[i] != prefix[i]) return false;
return true;
}
}
/// <summary>
/// The first bytes of a log file: they carry its byte order mark and identify the file, so a
/// file replaced under the same name is recognised even when it is already longer than the
/// position read so far.
/// </summary>
internal sealed class LogFileHead
{
internal const int MaxBytes = 4096;
private readonly byte[] _bytes;
private LogFileHead(byte[] bytes)
{
_bytes = bytes;
}
/// <summary>Up to <see cref="MaxBytes"/> from offset 0. Leaves the stream at an undefined position.</summary>
public static LogFileHead Read(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);
var buffer = new byte[(int)Math.Min(MaxBytes, stream.Length)];
var read = 0;
while (read < buffer.Length)
{
var n = stream.Read(buffer, read, buffer.Length - read);
if (n <= 0) break;
read += n;
}
if (read < buffer.Length) Array.Resize(ref buffer, read);
return new LogFileHead(buffer);
}
internal static LogFileHead FromBytes(byte[] bytes) => new LogFileHead(bytes);
public int Length => _bytes.Length;
public LogTextEncoding Encoding => LogTextEncoding.Detect(_bytes);
/// <summary>SHA-256 of the first <paramref name="length"/> bytes, Base64.</summary>
public string Hash(int length)
{
using (var sha = SHA256.Create())
return Convert.ToBase64String(sha.ComputeHash(_bytes, 0, length));
}
}
/// <summary>
/// Byte-exact line reader for the logparser collector. <see cref="Position"/> is the file
/// offset right behind the last line returned, so a caller that stops after any line can
/// resume exactly there — <see cref="StreamReader"/> only exposes its read-ahead boundary.
/// <para>
/// Line ends are those of <see cref="StreamReader.ReadLine"/>: "\r\n", "\n" and a lone "\r",
/// in code units of the file's <see cref="LogTextEncoding"/>. A "\n" directly after the start
/// position is skipped when the unit before it is "\r": the previous run ended on a "\r" whose
/// "\n" had not been written yet. A line at end of file without a line end is returned with
/// <see cref="LastLineTerminated"/> false; the caller decides whether the writer is still in
/// it. A line longer than the cap is consumed without being kept: <see cref="ReadLine"/>
/// returns an empty string and sets <see cref="LastLineTruncated"/>.
/// </para>
/// </summary>
internal sealed class LogLineReader
{
private const int ReadBufferSize = 64 * 1024;
private readonly Stream _stream;
private readonly LogTextEncoding _encoding;
private readonly int _unit;
private readonly int _maxLineBytes;
private readonly byte[] _buffer = new byte[ReadBufferSize];
private int _pos;
private int _len;
private long _bufferOffset;
private bool _eof;
private bool _skipLineFeedAfterCarriageReturn;
private byte[] _line = new byte[4096];
private int _lineLength;
/// <param name="stream">Seekable stream positioned at a code-unit boundary.</param>
public LogLineReader(Stream stream, LogTextEncoding encoding, int maxLineBytes)
{
if (stream == null) throw new ArgumentNullException(nameof(stream));
if (encoding == null) throw new ArgumentNullException(nameof(encoding));
if (maxLineBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxLineBytes));
_stream = stream;
_encoding = encoding;
_unit = encoding.UnitSize;
_maxLineBytes = maxLineBytes;
_bufferOffset = stream.Position;
_skipLineFeedAfterCarriageReturn = PrecededByCarriageReturn();
}
/// <summary>File offset of the next unread byte, exact.</summary>
public long Position => _bufferOffset + _pos;
/// <summary>File offset of the first byte of the line most recently returned.</summary>
public long LastLineStart { get; private set; }
/// <summary>False for a line that reached end of file without a line end.</summary>
public bool LastLineTerminated { get; private set; }
/// <summary>True when the last line was longer than the cap; it was consumed, not returned.</summary>
public bool LastLineTruncated { get; private set; }
/// <summary>The next line without its line end, or null at end of file.</summary>
public string ReadLine()
{
if (Position == 0 && _encoding.ByteOrderMarkLength > 0 && Ensure(_encoding.ByteOrderMarkLength))
_pos += _encoding.ByteOrderMarkLength;
if (_skipLineFeedAfterCarriageReturn)
{
_skipLineFeedAfterCarriageReturn = false;
if (Ensure(_unit) && UnitAt(_pos, _encoding.LineFeed))
_pos += _unit;
}
LastLineStart = Position;
LastLineTerminated = false;
LastLineTruncated = false;
_lineLength = 0;
while (true)
{
if (!Ensure(_unit))
{
// End of file. A partial code unit (a writer mid-character) belongs to the line.
var rest = _len - _pos;
if (rest > 0)
{
Append(_pos, rest);
_pos = _len;
}
return Position > LastLineStart ? Decode() : null;
}
// Scan the whole code units in the buffer for the next line end and take the text
// before it in one copy.
var end = _pos + (_len - _pos) / _unit * _unit;
var scan = _pos;
while (scan < end && !IsLineEnd(scan))
scan += _unit;
if (scan > _pos)
{
Append(_pos, scan - _pos);
_pos = scan;
}
if (scan == end)
continue; // no line end in the buffer yet — refill
var carriageReturn = !UnitAt(_pos, _encoding.LineFeed);
_pos += _unit;
if (carriageReturn && Ensure(_unit) && UnitAt(_pos, _encoding.LineFeed))
_pos += _unit;
LastLineTerminated = true;
return Decode();
}
}
private bool IsLineEnd(int offset)
{
if (_unit == 1)
{
var b = _buffer[offset];
return b == (byte)'\n' || b == (byte)'\r';
}
return UnitAt(offset, _encoding.LineFeed) || UnitAt(offset, _encoding.CarriageReturn);
}
private bool PrecededByCarriageReturn()
{
var start = _bufferOffset;
if (start - _unit < _encoding.ByteOrderMarkLength) return false;
var previous = new byte[_unit];
_stream.Seek(start - _unit, SeekOrigin.Begin);
var read = 0;
while (read < _unit)
{
var n = _stream.Read(previous, read, _unit - read);
if (n <= 0) break;
read += n;
}
_stream.Seek(start, SeekOrigin.Begin);
if (read < _unit) return false;
for (var i = 0; i < _unit; i++)
if (previous[i] != _encoding.CarriageReturn[i]) return false;
return true;
}
/// <summary>At least <paramref name="count"/> unread bytes in the buffer, unless the file ends first.</summary>
private bool Ensure(int count)
{
while (_len - _pos < count)
{
if (_eof) return false;
var remaining = _len - _pos;
if (_pos > 0)
{
Buffer.BlockCopy(_buffer, _pos, _buffer, 0, remaining);
_bufferOffset += _pos;
_pos = 0;
_len = remaining;
}
var read = _stream.Read(_buffer, _len, _buffer.Length - _len);
if (read <= 0)
{
_eof = true;
return _len - _pos >= count;
}
_len += read;
}
return true;
}
private bool UnitAt(int offset, byte[] unit)
{
for (var i = 0; i < _unit; i++)
if (_buffer[offset + i] != unit[i]) return false;
return true;
}
private void Append(int offset, int count)
{
var room = _maxLineBytes - _lineLength;
if (count > room)
{
LastLineTruncated = true;
count = room;
if (count <= 0) return;
}
if (_lineLength + count > _line.Length)
{
var grown = new byte[Math.Max(_line.Length * 2, _lineLength + count)];
Buffer.BlockCopy(_line, 0, grown, 0, _lineLength);
_line = grown;
}
Buffer.BlockCopy(_buffer, offset, _line, _lineLength, count);
_lineLength += count;
}
private string Decode() =>
_lineLength == 0 || LastLineTruncated ? string.Empty : _encoding.Encoding.GetString(_line, 0, _lineLength);
}
}
@@ -18,6 +18,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
{
public string CollectorType => "logparser";
/// <summary>A wildcard target reads at most this many files per run, the newest first.</summary>
internal const int MaxFilesPerRun = 20;
/// <summary>Lines one run reads from one file unless the rule sets <c>maxLines</c>.</summary>
internal const int DefaultMaxLines = 1000;
/// <summary>The IME tracker's line bound: a longer physical line is skipped, never matched.</summary>
internal const int MaxLineBytes = 32 * 1024 * 1024;
/// <summary>
/// Executes the log parser rule. Returns null because logparser emits events directly
/// via context.OnEventCollected rather than returning a single result dictionary.
@@ -34,7 +43,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
// Expand custom tokens (%LOGGED_ON_USER_PROFILE%) and standard environment variables
var userProfilePath = UserProfileResolver.ContainsUserProfileToken(filePath)
? UserProfileResolver.GetLoggedOnUserProfilePath() : null;
filePath = UserProfileResolver.ExpandCustomTokens(filePath);
filePath = UserProfileResolver.ExpandCustomTokens(filePath, userProfilePath);
if (filePath == null)
{
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
@@ -84,10 +93,19 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
if (rule.Parameters.TryGetValue("trackPosition", out trackPositionStr))
bool.TryParse(trackPositionStr, out trackPosition);
// A value that is no positive number keeps the default: a run capped at 0 lines would
// never advance its position, and the rule would read nothing for the whole session.
string maxLinesStr;
int maxLines = 1000;
int maxLines = DefaultMaxLines;
if (rule.Parameters.TryGetValue("maxLines", out maxLinesStr))
int.TryParse(maxLinesStr, out maxLines);
{
int parsedMaxLines;
if (int.TryParse(maxLinesStr, out parsedMaxLines) && parsedMaxLines > 0)
maxLines = parsedMaxLines;
else
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"maxLines '{maxLinesStr}' is not a positive number — using {DefaultMaxLines}");
}
// Determine format: "cmtrace" (default) or "text" for plain text logs
string formatStr;
@@ -144,7 +162,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
/// as the event data). Stops after <see cref="MaxTracedMatchesPerFile"/> matches.
/// </summary>
private static void TraceMatch(GatherRuleContext context, GatherRule rule, string fileName,
int lineNumber, Match match, Regex pattern, int matchNumber)
long lineNumber, Match match, Regex pattern, int matchNumber)
{
if (matchNumber > MaxTracedMatchesPerFile)
{
@@ -195,14 +213,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
try
{
// Return matched files sorted by last write time (newest first), capped at 20
// Return matched files sorted by last write time (newest first), capped at MaxFilesPerRun
var allMatches = Directory.GetFiles(directory, fileNamePart);
if (allMatches.Length > 20)
if (allMatches.Length > MaxFilesPerRun)
context.DebugLog(ruleId, GatherRuleDebugLog.StageLogParser,
$"wildcard matched {allMatches.Length} files — capped to the 20 newest");
$"wildcard matched {allMatches.Length} files — capped to the {MaxFilesPerRun} newest");
return allMatches
.OrderByDescending(f => new FileInfo(f).LastWriteTimeUtc)
.Take(20)
.Take(MaxFilesPerRun)
.ToList();
}
catch (Exception ex)
@@ -216,183 +234,248 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
private static void ProcessLogFile(string filePath, GatherRule rule, Regex pattern,
bool trackPosition, int maxLines, bool isTextMode, GatherRuleContext context)
{
var fileName = Path.GetFileName(filePath);
try
{
var fileInfo = new FileInfo(filePath);
long startPosition = trackPosition
? context.FilePositionTracker.GetSafePosition(filePath, fileInfo.Length)
: 0;
var state = context.SessionState;
var known = trackPosition ? state.PeekLogPosition(rule.RuleId, filePath) : null;
// Nothing new to read
if (startPosition >= fileInfo.Length)
// Nothing new since the last run — decided from the length alone, without opening the file.
var length = new FileInfo(filePath).Length;
if (known != null && known.Position == length)
{
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"{Path.GetFileName(filePath)}: no new content (position {startPosition} >= length {fileInfo.Length}) — trackPosition=true, nothing re-read");
$"{fileName}: no new content (position {known.Position} >= length {length}) — trackPosition=true, nothing re-read" +
(known.FromPreviousRun ? "; position saved by a previous agent run" : ""));
return;
}
// A last line without a line end is usually one its writer is still in. An interval
// rule leaves it for its next run, once. A one-shot trigger may have no next run, so it
// reads the line now but saves the position before it: the next run reads it again,
// whole — at worst a match repeats, it is never split.
var isInterval = string.Equals(rule.Trigger, "interval", StringComparison.OrdinalIgnoreCase);
var mayHoldTail = trackPosition && isInterval;
var tailReadAgainNextRun = false;
int matchCount = 0;
int linesRead = 0;
int committedLines = 0;
int parseFailCount = 0;
int timeoutCount = 0;
long endPosition = startPosition;
int oversizedCount = 0;
long startPosition;
long endPosition;
long lineNumberBase;
long fileLength;
long heldTailStart = -1;
LogFileHead head;
LogTextEncoding encoding;
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fileLength = stream.Length;
head = LogFileHead.Read(stream);
encoding = head.Encoding;
LogReadStart start;
startPosition = encoding.AlignDown(GatherRuleSessionState.ResolveStart(known, fileLength, head, out start));
lineNumberBase = start == LogReadStart.Continue ? known.LineNumber : 0;
TraceReadStart(context, rule, fileName, known, start, fileLength);
stream.Seek(startPosition, SeekOrigin.Begin);
var reader = new LogLineReader(stream, encoding, MaxLineBytes);
endPosition = startPosition;
using (var reader = new StreamReader(stream, Encoding.UTF8))
while (linesRead < maxLines)
{
string line;
while ((line = reader.ReadLine()) != null && linesRead < maxLines)
var line = reader.ReadLine();
if (line == null)
{
linesRead++;
if (isTextMode)
{
// Text mode: match regex directly against the raw line
Match match;
try
{
match = pattern.Match(line);
}
catch (RegexMatchTimeoutException)
{
timeoutCount++;
continue;
}
if (!match.Success)
continue;
var data = new Dictionary<string, object>();
foreach (var groupName in pattern.GetGroupNames())
{
if (groupName == "0") continue;
var group = match.Groups[groupName];
if (group.Success)
data[groupName] = group.Value;
}
data["logLine"] = TruncateMessage(line, 500);
data["logLineNumber"] = linesRead;
data["logFile"] = Path.GetFileName(filePath);
data["ruleId"] = rule.RuleId;
data["ruleTitle"] = rule.Title;
GatherRuleExecutor.StampRuleMarkers(rule, data);
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
? rule.OutputEventType
: "logparser_match";
var severity = GatherRuleContext.ParseSeverity(rule.OutputSeverity);
context.OnEventCollected(new EnrollmentEvent
{
SessionId = context.SessionId,
TenantId = context.TenantId,
Timestamp = DateTime.UtcNow,
EventType = eventType,
Severity = severity,
Source = GatherRuleExecutor.SourceName,
Message = $"Gather: {rule.Title}",
Data = data
});
matchCount++;
TraceMatch(context, rule, Path.GetFileName(filePath), linesRead, match, pattern, matchCount);
}
else
{
// CMTrace mode: parse line as CMTrace format, match regex against message
CmTraceLogEntry entry;
if (!CmTraceLogParser.TryParseLine(line, out entry))
{
parseFailCount++;
continue;
}
Match match;
try
{
match = pattern.Match(entry.Message);
}
catch (RegexMatchTimeoutException)
{
timeoutCount++;
continue;
}
if (!match.Success)
continue;
var data = new Dictionary<string, object>();
foreach (var groupName in pattern.GetGroupNames())
{
if (groupName == "0") continue;
var group = match.Groups[groupName];
if (group.Success)
data[groupName] = group.Value;
}
// Gather-rule logs are arbitrary files this collector does not
// tail, so no writer offset can be measured for them; the
// reader-zone fallback carries its known defect (see
// ResolveUtcAssumingReaderZone). Behaviour unchanged from before
// the parser split.
var entryUtc = entry.TimestampUtc
?? (entry.HasTimestamp
? CmTraceLogParser.ResolveUtcAssumingReaderZone(entry.LocalTimestamp)
: DateTime.UtcNow);
data["logTimestamp"] = entryUtc.ToString("o");
data["logComponent"] = entry.Component;
data["logType"] = entry.Type;
data["logMessage"] = TruncateMessage(entry.Message, 500);
data["logFile"] = Path.GetFileName(filePath);
data["ruleId"] = rule.RuleId;
data["ruleTitle"] = rule.Title;
GatherRuleExecutor.StampRuleMarkers(rule, data);
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
? rule.OutputEventType
: "logparser_match";
var severity = MapCmTraceTypeToSeverity(entry.Type, rule.OutputSeverity);
context.OnEventCollected(new EnrollmentEvent
{
SessionId = context.SessionId,
TenantId = context.TenantId,
Timestamp = entryUtc,
EventType = eventType,
Severity = severity,
Source = GatherRuleExecutor.SourceName,
Message = $"Gather: {rule.Title}",
Data = data
});
matchCount++;
TraceMatch(context, rule, Path.GetFileName(filePath), linesRead, match, pattern, matchCount);
}
// End of file. A "\n" the reader skipped behind the "\r" the previous run
// ended on is consumed too — unless a kept tail must be read again.
if (!tailReadAgainNextRun)
endPosition = reader.Position;
break;
}
// Capture the final stream position after reading
endPosition = stream.Position;
var unfinished = !reader.LastLineTerminated;
if (unfinished && mayHoldTail
&& (known == null || known.HeldTailStart != reader.LastLineStart))
{
heldTailStart = reader.LastLineStart;
break;
}
linesRead++;
var lineNumber = lineNumberBase + linesRead;
if (unfinished && trackPosition && !isInterval)
{
tailReadAgainNextRun = true;
}
else
{
endPosition = reader.Position;
committedLines = linesRead;
}
if (reader.LastLineTruncated)
{
oversizedCount++;
continue;
}
if (isTextMode)
{
// Text mode: match regex directly against the raw line
Match match;
try
{
match = pattern.Match(line);
}
catch (RegexMatchTimeoutException)
{
timeoutCount++;
continue;
}
if (!match.Success)
continue;
var data = new Dictionary<string, object>();
foreach (var groupName in pattern.GetGroupNames())
{
if (groupName == "0") continue;
var group = match.Groups[groupName];
if (group.Success)
data[groupName] = group.Value;
}
data["logLine"] = TruncateMessage(line, 500);
data["logLineNumber"] = lineNumber;
data["logFile"] = fileName;
data["ruleId"] = rule.RuleId;
data["ruleTitle"] = rule.Title;
GatherRuleExecutor.StampRuleMarkers(rule, data);
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
? rule.OutputEventType
: "logparser_match";
var severity = GatherRuleContext.ParseSeverity(rule.OutputSeverity);
context.OnEventCollected(new EnrollmentEvent
{
SessionId = context.SessionId,
TenantId = context.TenantId,
Timestamp = DateTime.UtcNow,
EventType = eventType,
Severity = severity,
Source = GatherRuleExecutor.SourceName,
Message = $"Gather: {rule.Title}",
Data = data
});
matchCount++;
TraceMatch(context, rule, fileName, lineNumber, match, pattern, matchCount);
}
else
{
// CMTrace mode: parse line as CMTrace format, match regex against message
CmTraceLogEntry entry;
if (!CmTraceLogParser.TryParseLine(line, out entry))
{
parseFailCount++;
continue;
}
Match match;
try
{
match = pattern.Match(entry.Message);
}
catch (RegexMatchTimeoutException)
{
timeoutCount++;
continue;
}
if (!match.Success)
continue;
var data = new Dictionary<string, object>();
foreach (var groupName in pattern.GetGroupNames())
{
if (groupName == "0") continue;
var group = match.Groups[groupName];
if (group.Success)
data[groupName] = group.Value;
}
// Gather-rule logs are arbitrary files this collector does not
// tail, so no writer offset can be measured for them; the
// reader-zone fallback carries its known defect (see
// ResolveUtcAssumingReaderZone). Behaviour unchanged from before
// the parser split.
var entryUtc = entry.TimestampUtc
?? (entry.HasTimestamp
? CmTraceLogParser.ResolveUtcAssumingReaderZone(entry.LocalTimestamp)
: DateTime.UtcNow);
data["logTimestamp"] = entryUtc.ToString("o");
data["logComponent"] = entry.Component;
data["logType"] = entry.Type;
data["logMessage"] = TruncateMessage(entry.Message, 500);
data["logFile"] = fileName;
data["ruleId"] = rule.RuleId;
data["ruleTitle"] = rule.Title;
GatherRuleExecutor.StampRuleMarkers(rule, data);
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
? rule.OutputEventType
: "logparser_match";
var severity = MapCmTraceTypeToSeverity(entry.Type, rule.OutputSeverity);
context.OnEventCollected(new EnrollmentEvent
{
SessionId = context.SessionId,
TenantId = context.TenantId,
Timestamp = entryUtc,
EventType = eventType,
Severity = severity,
Source = GatherRuleExecutor.SourceName,
Message = $"Gather: {rule.Title}",
Data = data
});
matchCount++;
TraceMatch(context, rule, fileName, lineNumber, match, pattern, matchCount);
}
}
}
// Saved only now, after every event of this file went out: a process that dies
// before this line repeats the file's new lines after the restart, never skips them.
if (trackPosition)
context.FilePositionTracker.SetPosition(filePath, endPosition);
state.CommitLogPosition(rule.RuleId, filePath, endPosition, lineNumberBase + committedLines, head, heldTailStart);
if (matchCount > 0)
context.Logger.Debug($"LogParser rule {rule.RuleId}: {matchCount} matches from {linesRead} lines in {Path.GetFileName(filePath)}");
context.Logger.Debug($"LogParser rule {rule.RuleId}: {matchCount} matches from {linesRead} lines in {fileName}");
// Per-file outcome — always written so a "matched 0" run is visible too.
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"{Path.GetFileName(filePath)}: read {linesRead} lines from position {startPosition}->{endPosition}, " +
$"matched {matchCount}, parseFailures={parseFailCount}, regexTimeouts={timeoutCount}, mode={(isTextMode ? "text" : "cmtrace")}");
$"{fileName}: read {linesRead} lines from position {startPosition}->{endPosition}, " +
$"matched {matchCount}, parseFailures={parseFailCount}, regexTimeouts={timeoutCount}, mode={(isTextMode ? "text" : "cmtrace")}, encoding={encoding.Name}" +
(oversizedCount > 0 ? $", skipped {oversizedCount} line(s) over {MaxLineBytes / (1024 * 1024)} MB" : ""));
if (heldTailStart >= 0)
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"{fileName}: last line has no line end yet — left for the next run, read then even if still unfinished");
else if (tailReadAgainNextRun)
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"{fileName}: last line has no line end yet — read now and again by the next run, position kept before it");
if (!isTextMode && linesRead > 0 && parseFailCount == linesRead)
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
"every line failed CMTrace parsing — if this is a plain-text log, set parameter format=text");
if (linesRead == maxLines)
if (linesRead == maxLines && endPosition < fileLength)
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"stopped at maxLines={maxLines} — remaining content is deferred to the next run");
}
@@ -403,6 +486,27 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
}
}
private static void TraceReadStart(GatherRuleContext context, GatherRule rule, string fileName,
LogPositionSnapshot known, LogReadStart start, long fileLength)
{
if (start == LogReadStart.Shrunk)
{
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"{fileName}: file is shorter than the saved position (length {fileLength} < {known.Position}) — truncated or recreated, reading from the beginning");
}
else if (start == LogReadStart.Replaced)
{
context.Logger.Info($"LogParser rule {rule.RuleId}: {fileName} was replaced since the last read — reading it from the beginning");
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"{fileName}: file start changed since the last read (replaced or rewritten) — saved position {known.Position} discarded, reading from the beginning");
}
else if (start == LogReadStart.Continue && known.FromPreviousRun)
{
context.DebugLog(rule.RuleId, GatherRuleDebugLog.StageLogParser,
$"{fileName}: continuing at position {known.Position} (after line {known.LineNumber}) saved by a previous agent run");
}
}
private static EventSeverity MapCmTraceTypeToSeverity(int cmTraceType, string ruleOverride)
{
// If the rule specifies a severity, use it
@@ -26,7 +26,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
// Expand custom tokens (%LOGGED_ON_USER_PROFILE%) and standard environment variables
var userProfilePath = UserProfileResolver.ContainsUserProfileToken(filePath)
? UserProfileResolver.GetLoggedOnUserProfilePath() : null;
filePath = UserProfileResolver.ExpandCustomTokens(filePath);
filePath = UserProfileResolver.ExpandCustomTokens(filePath, userProfilePath);
if (filePath == null)
return data; // Token present but no user logged on — skip silently
@@ -4,7 +4,6 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
@@ -19,7 +18,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
public string TenantId { get; }
public Action<EnrollmentEvent> OnEventCollected { get; }
public string ImeLogPathOverride { get; }
public LogFilePositionTracker FilePositionTracker { get; }
/// <summary>Logparser positions per (rule, file) and on_change values; survives agent restarts when persisted.</summary>
public GatherRuleSessionState SessionState { get; }
public bool UnrestrictedMode { get; set; }
/// <summary>
@@ -34,7 +36,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
string tenantId,
Action<EnrollmentEvent> onEventCollected,
string imeLogPathOverride,
LogFilePositionTracker filePositionTracker,
GatherRuleSessionState sessionState,
GatherRuleDebugLog debugLog = null)
{
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
@@ -42,7 +44,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
TenantId = tenantId ?? throw new ArgumentNullException(nameof(tenantId));
OnEventCollected = onEventCollected ?? throw new ArgumentNullException(nameof(onEventCollected));
ImeLogPathOverride = imeLogPathOverride;
FilePositionTracker = filePositionTracker ?? throw new ArgumentNullException(nameof(filePositionTracker));
SessionState = sessionState ?? throw new ArgumentNullException(nameof(sessionState));
DebugWriter = debugLog;
}
@@ -10,7 +10,6 @@ using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
@@ -38,6 +37,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
private readonly AgentLogger _logger;
private readonly GatherRuleDebugLog _debug; // null unless EnableGatherRuleDebugLog / --gather-debug-log
private readonly GatherRuleSessionState _state;
private readonly GatherRuleContext _context;
private readonly Dictionary<string, IGatherRuleCollector> _collectors;
@@ -50,12 +50,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
// Phase-scope + emit-mode state (ActivePhases / ActiveFromPhase / EmitMode on GatherRule).
// Guarded by _scopeLock; collector work always runs outside the lock. The state deliberately
// survives UpdateRules config refreshes — an agent restart causes at most one re-emit per
// on_change rule (acceptable under the per-enrollment lifecycle).
// survives UpdateRules config refreshes. Across agent restarts only the last emitted hash
// survives: it is seeded from _state and committed there after each emit, so an unchanged
// on_change result stays silent after a reboot. Phase latches, dedup sets and the
// suppression streak are process-scoped.
private readonly object _scopeLock = new object();
private EnrollmentPhase _currentPhase = EnrollmentPhase.Unknown;
private readonly HashSet<string> _fromPhaseLatched = new HashSet<string>();
private readonly Dictionary<string, string> _lastEmittedHash = new Dictionary<string, string>();
private readonly HashSet<string> _hashFromPreviousRun = new HashSet<string>();
private readonly Dictionary<string, (int Count, DateTime SinceUtc)> _suppressed =
new Dictionary<string, (int Count, DateTime SinceUtc)>();
private readonly HashSet<string> _scopeBypassLogged = new HashSet<string>();
@@ -77,9 +80,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
set { _context.UnrestrictedMode = value; }
}
/// <param name="stateDirectory">
/// Where logparser positions and on_change values are kept across agent restarts. Null keeps
/// them in memory — required for <c>--run-gather-rules</c>, which runs beside the live agent
/// under a throwaway session id and must not overwrite the session's file.
/// </param>
public GatherRuleExecutor(string sessionId, string tenantId, Action<EnrollmentEvent> onEventCollected,
AgentLogger logger, string imeLogPathOverride = null, string debugLogPath = null,
Action<string> debugEcho = null)
Action<string> debugEcho = null, string stateDirectory = null)
{
if (sessionId == null) throw new ArgumentNullException(nameof(sessionId));
if (tenantId == null) throw new ArgumentNullException(nameof(tenantId));
@@ -89,8 +97,19 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
_logger = logger;
_debug = string.IsNullOrEmpty(debugLogPath) ? null : new GatherRuleDebugLog(debugLogPath, logger, debugEcho);
var filePositionTracker = new LogFilePositionTracker();
_context = new GatherRuleContext(logger, sessionId, tenantId, onEventCollected, imeLogPathOverride, filePositionTracker, _debug);
var persistence = string.IsNullOrEmpty(stateDirectory) ? null : new GatherRuleStatePersistence(stateDirectory, logger);
_state = new GatherRuleSessionState(sessionId, persistence, logger);
_context = new GatherRuleContext(logger, sessionId, tenantId, onEventCollected, imeLogPathOverride, _state, _debug);
foreach (var hash in _state.GetEmittedHashes())
{
_lastEmittedHash[hash.Key] = hash.Value;
_hashFromPreviousRun.Add(hash.Key);
}
_logger.Info($"GatherRuleExecutor: gather state {_state.RestoreSummary}");
DebugLog(null, GatherRuleDebugLog.StageConfig, $"gather state: {_state.RestoreSummary}");
foreach (var detail in _state.RestoredDetails)
DebugLog(detail.Key, GatherRuleDebugLog.StageConfig, detail.Value);
// Register all collector strategies
var collectorList = new IGatherRuleCollector[]
@@ -480,14 +499,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
// empty result never reaches this point, so an emitOnlyIfExists miss neither
// emits nor updates the hash — composing to "one event on appearance, then
// only on change".
string emittedHash = null;
if (IsOnChangeMode(rule))
{
string hashPrefix;
int suppressedStreak;
if (!ShouldEmitOnChange(rule, result, out hashPrefix, out suppressedStreak))
bool comparedWithPreviousRun;
if (!ShouldEmitOnChange(rule, result, out emittedHash, out hashPrefix, out suppressedStreak, out comparedWithPreviousRun))
{
DebugLog(rule.RuleId, GatherRuleDebugLog.StageSuppress,
$"result unchanged (hash {hashPrefix}) — emit suppressed (on_change), suppressed streak={suppressedStreak}");
$"result unchanged (hash {hashPrefix}) — emit suppressed (on_change), suppressed streak={suppressedStreak}" +
(comparedWithPreviousRun ? "; compared with the value a previous agent run emitted" : ""));
return;
}
DebugLog(rule.RuleId, GatherRuleDebugLog.StageEmit,
@@ -524,6 +546,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
Message = $"Gather: {rule.Title}",
Data = result
});
// Committed only after the event went out: a process that dies in between emits
// the result once more after the restart instead of never.
if (emittedHash != null)
_state.CommitEmittedHash(rule.RuleId, emittedHash);
DebugLog(rule.RuleId, GatherRuleDebugLog.StageEmit,
$"emitted {eventType} (severity={severity}, {result.Count} fields)");
}
@@ -679,9 +707,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
internal bool ShouldEmitOnChange(GatherRule rule, Dictionary<string, object> result,
out string hashPrefix, out int suppressedStreak)
{
var hash = ComputeCanonicalHash(result);
string hash;
bool comparedWithPreviousRun;
return ShouldEmitOnChange(rule, result, out hash, out hashPrefix, out suppressedStreak, out comparedWithPreviousRun);
}
/// <summary>
/// Full form: <paramref name="hash"/> is the result's canonical hash, committed to the session
/// state once the event went out; <paramref name="comparedWithPreviousRun"/> says a suppression
/// compared against the value a previous agent run emitted.
/// </summary>
private bool ShouldEmitOnChange(GatherRule rule, Dictionary<string, object> result,
out string hash, out string hashPrefix, out int suppressedStreak, out bool comparedWithPreviousRun)
{
hash = ComputeCanonicalHash(result);
hashPrefix = hash.Length > 8 ? hash.Substring(0, 8) : hash;
suppressedStreak = 0;
comparedWithPreviousRun = false;
bool emit;
lock (_scopeLock)
{
@@ -693,11 +735,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
? (streak.Count + 1, streak.SinceUtc)
: (1, DateTime.UtcNow);
suppressedStreak = _suppressed[rule.RuleId].Count;
comparedWithPreviousRun = _hashFromPreviousRun.Contains(rule.RuleId);
emit = false;
}
else
{
_lastEmittedHash[rule.RuleId] = hash;
_hashFromPreviousRun.Remove(rule.RuleId);
(int Count, DateTime SinceUtc) streak;
if (_suppressed.TryGetValue(rule.RuleId, out streak) && streak.Count > 0)
{
@@ -820,6 +864,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
StopAllTimers();
_startupRulesLatch?.Dispose();
_startupRulesLatch = null;
// A rule still finishing on a pool thread keeps its in-memory state but no longer writes:
// the agent may be removing its own folder right now.
_state.Close();
}
}
}
@@ -0,0 +1,399 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
{
/// <summary>
/// Gather-rule state of one enrollment session that survives agent restarts: where each
/// logparser rule stopped reading each file, and the on_change value each rule last emitted.
/// <para>
/// Positions are kept per (rule, file) — two rules parsing the same log each read all of it.
/// Every position carries a fingerprint of the file's first bytes, so a file replaced under
/// the same name is read from the beginning even when it is already longer than the position.
/// </para>
/// <para>
/// Every commit is written to disk synchronously, AFTER the events it covers were handed on:
/// a process that dies in between repeats that one pass after the restart instead of losing it.
/// The lock guards memory and file write together and is never taken under the executor's
/// scope lock. Without a persistence (diagnostic mode, tests) the state lives in memory only.
/// </para>
/// </summary>
public sealed class GatherRuleSessionState
{
/// <summary>
/// Files remembered per rule. A run reads at most <see cref="LogParserCollector.MaxFilesPerRun"/>
/// files; the least recently touched entry beyond the cap is dropped, and its file — should it
/// come back — is simply read again.
/// </summary>
internal const int MaxLogFilesPerRule = 5 * LogParserCollector.MaxFilesPerRun;
private static readonly char[] WildcardChars = { '*', '?' };
private readonly object _gate = new object();
private readonly string _sessionId;
private readonly GatherRuleStatePersistence _persistence;
private readonly AgentLogger _logger;
private readonly Dictionary<string, Dictionary<string, Entry>> _logPositions =
new Dictionary<string, Dictionary<string, Entry>>(StringComparer.Ordinal);
private readonly Dictionary<string, string> _emittedHashes = new Dictionary<string, string>(StringComparer.Ordinal);
private readonly List<KeyValuePair<string, string>> _restoredDetails = new List<KeyValuePair<string, string>>();
private long _touchCounter;
private bool _unsaved;
private bool _saveFailureLogged;
private bool _closed;
private sealed class Entry
{
public long Position;
public long LineNumber;
public int HeadLength;
public string HeadHash;
public bool FromPreviousRun;
public long HeldTailStart = -1;
public long LastTouched;
}
public GatherRuleSessionState(string sessionId, GatherRuleStatePersistence persistence, AgentLogger logger)
{
_sessionId = sessionId ?? throw new ArgumentNullException(nameof(sessionId));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_persistence = persistence;
RestoreSummary = Restore();
}
/// <summary>One line on what the constructor found on disk — for the agent log and the debug trace.</summary>
public string RestoreSummary { get; }
/// <summary>(ruleId, message) per restored position and on_change value — for the debug trace.</summary>
internal IReadOnlyList<KeyValuePair<string, string>> RestoredDetails => _restoredDetails;
// ===== logparser positions =====
/// <summary>The recorded position of <paramref name="filePath"/> for the rule, or null when it has none.</summary>
internal LogPositionSnapshot PeekLogPosition(string ruleId, string filePath)
{
lock (_gate)
{
Dictionary<string, Entry> files;
Entry entry;
if (!_logPositions.TryGetValue(ruleId, out files) || !files.TryGetValue(filePath, out entry))
return null;
entry.LastTouched = ++_touchCounter;
return new LogPositionSnapshot(entry.Position, entry.LineNumber, entry.HeadLength, entry.HeadHash,
entry.FromPreviousRun, entry.HeldTailStart);
}
}
/// <summary>
/// Records where the rule stopped in the file and saves the state when it changed.
/// <paramref name="heldTailStart"/> (in memory only) marks an unfinished last line left for
/// the next run; -1 when none.
/// </summary>
internal void CommitLogPosition(string ruleId, string filePath, long position, long lineNumber,
LogFileHead head, long heldTailStart)
{
var headLength = head.Length;
var headHash = headLength > 0 ? head.Hash(headLength) : null;
lock (_gate)
{
Dictionary<string, Entry> files;
if (!_logPositions.TryGetValue(ruleId, out files))
{
files = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase);
_logPositions[ruleId] = files;
}
Entry entry;
var changed = false;
if (!files.TryGetValue(filePath, out entry))
{
entry = new Entry();
files[filePath] = entry;
changed = true;
}
if (changed || entry.Position != position || entry.LineNumber != lineNumber
|| entry.HeadLength != headLength || !string.Equals(entry.HeadHash, headHash, StringComparison.Ordinal))
{
entry.Position = position;
entry.LineNumber = lineNumber;
entry.HeadLength = headLength;
entry.HeadHash = headHash;
entry.FromPreviousRun = false;
changed = true;
}
entry.HeldTailStart = heldTailStart;
entry.LastTouched = ++_touchCounter;
if (files.Count > MaxLogFilesPerRule)
EvictLeastRecentlyTouched(ruleId, files);
if (changed || _unsaved)
SaveLocked();
}
}
/// <summary>
/// Where to continue reading: the recorded position while the file is still the one it was
/// recorded for, otherwise 0 with the reason.
/// </summary>
internal static long ResolveStart(LogPositionSnapshot known, long fileLength, LogFileHead head, out LogReadStart start)
{
if (known == null)
{
start = LogReadStart.FirstRead;
return 0;
}
if (fileLength < known.Position)
{
start = LogReadStart.Shrunk;
return 0;
}
if (known.HeadLength > 0
&& (head.Length < known.HeadLength
|| !string.Equals(head.Hash(known.HeadLength), known.HeadHash, StringComparison.Ordinal)))
{
start = LogReadStart.Replaced;
return 0;
}
start = LogReadStart.Continue;
return known.Position;
}
// ===== on_change values =====
/// <summary>Rule id → hash of the result the rule last emitted.</summary>
internal Dictionary<string, string> GetEmittedHashes()
{
lock (_gate)
return new Dictionary<string, string>(_emittedHashes, StringComparer.Ordinal);
}
/// <summary>Records the hash of a result that was just emitted and saves the state when it changed.</summary>
internal void CommitEmittedHash(string ruleId, string hash)
{
lock (_gate)
{
string current;
var changed = !_emittedHashes.TryGetValue(ruleId, out current)
|| !string.Equals(current, hash, StringComparison.Ordinal);
_emittedHashes[ruleId] = hash;
if (changed || _unsaved)
SaveLocked();
}
}
/// <summary>Retries a save that failed earlier, then stops writing (executor disposed).</summary>
internal void Close()
{
lock (_gate)
{
if (_unsaved)
SaveLocked();
_closed = true;
}
}
// ===== persistence =====
private void SaveLocked()
{
if (_persistence == null || _closed)
{
_unsaved = false;
return;
}
var data = new GatherRuleStateData
{
SessionId = _sessionId,
SavedAtUtc = DateTime.UtcNow,
LogPositions = _logPositions
.SelectMany(rule => rule.Value.Select(file => new { RuleId = rule.Key, Path = file.Key, Entry = file.Value }))
.OrderBy(x => x.Entry.LastTouched)
.Select(x => new GatherLogPositionData
{
RuleId = x.RuleId,
Path = x.Path,
Position = x.Entry.Position,
LineNumber = x.Entry.LineNumber,
HeadLength = x.Entry.HeadLength,
HeadHash = x.Entry.HeadHash,
})
.ToList(),
OnChangeHashes = new Dictionary<string, string>(_emittedHashes, StringComparer.Ordinal),
};
if (_persistence.Save(data))
{
_unsaved = false;
_saveFailureLogged = false;
return;
}
_unsaved = true;
if (!_saveFailureLogged)
{
_saveFailureLogged = true;
_logger.Warning($"GatherRuleSessionState: saving {_persistence.StateFilePath} failed — kept in memory, retried at the next change");
}
}
private string Restore()
{
if (_persistence == null)
return "persistence off (no state directory) — positions and on_change values live in memory only";
string discardReason;
var data = _persistence.Load(_sessionId, out discardReason);
if (data == null)
{
return discardReason == null
? "no saved state — first agent run of this session"
: $"saved state discarded ({discardReason}) — starting fresh";
}
// The file is input like any other: whatever it holds, the executor must come up. A
// failure here would otherwise stop every collector host, at every restart of the session.
try
{
return RestoreFrom(data);
}
catch (Exception ex)
{
_logPositions.Clear();
_emittedHashes.Clear();
_restoredDetails.Clear();
_logger.Warning($"GatherRuleSessionState: restoring {_persistence.StateFilePath} failed, starting fresh: {ex.Message}");
return $"saved state discarded (restore failed: {ex.Message}) — starting fresh";
}
}
private string RestoreFrom(GatherRuleStateData data)
{
var dropped = 0;
foreach (var position in data.LogPositions ?? new List<GatherLogPositionData>())
{
if (!IsValid(position))
{
dropped++;
continue;
}
Dictionary<string, Entry> files;
if (!_logPositions.TryGetValue(position.RuleId, out files))
{
files = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase);
_logPositions[position.RuleId] = files;
}
files[position.Path] = new Entry
{
Position = position.Position,
LineNumber = position.LineNumber,
HeadLength = position.HeadLength,
HeadHash = position.HeadLength > 0 ? position.HeadHash : null,
FromPreviousRun = true,
LastTouched = ++_touchCounter,
};
if (files.Count > MaxLogFilesPerRule)
EvictLeastRecentlyTouched(position.RuleId, files);
}
foreach (var hash in data.OnChangeHashes ?? new Dictionary<string, string>())
{
if (string.IsNullOrEmpty(hash.Key) || string.IsNullOrEmpty(hash.Value))
{
dropped++;
continue;
}
_emittedHashes[hash.Key] = hash.Value;
}
foreach (var rule in _logPositions)
{
foreach (var file in rule.Value)
{
_restoredDetails.Add(new KeyValuePair<string, string>(rule.Key,
$"logparser position restored: {Path.GetFileName(file.Key)} at byte {file.Value.Position}, after line {file.Value.LineNumber}"));
}
}
foreach (var hash in _emittedHashes)
{
_restoredDetails.Add(new KeyValuePair<string, string>(hash.Key,
$"on_change value restored (hash {Prefix(hash.Value)}) — an unchanged result stays silent"));
}
var positionCount = _logPositions.Sum(rule => rule.Value.Count);
return $"restored {positionCount} logparser position(s) for {_logPositions.Count} rule(s) and {_emittedHashes.Count} on_change value(s), " +
$"saved {data.SavedAtUtc:yyyy-MM-ddTHH:mm:ssZ} by a previous agent run of this session" +
(dropped > 0 ? $"; {dropped} invalid entr{(dropped == 1 ? "y" : "ies")} dropped" : "") +
" — logparser rules continue after their saved position, on_change rules stay silent until their result changes";
}
private static bool IsValid(GatherLogPositionData position)
{
if (position == null || string.IsNullOrEmpty(position.RuleId) || string.IsNullOrEmpty(position.Path))
return false;
// A real resolved path never carries these; Path APIs throw on them under .NET Framework.
if (position.Path.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || position.Path.IndexOfAny(WildcardChars) >= 0)
return false;
if (position.Position < 0 || position.LineNumber < 0)
return false;
if (position.HeadLength < 0 || position.HeadLength > LogFileHead.MaxBytes)
return false;
if (position.HeadLength > 0 && string.IsNullOrEmpty(position.HeadHash))
return false;
// Reading any byte records a non-empty head; a position without one cannot be verified.
return position.Position == 0 || position.HeadLength > 0;
}
private void EvictLeastRecentlyTouched(string ruleId, Dictionary<string, Entry> files)
{
var oldest = files.OrderBy(file => file.Value.LastTouched).First();
files.Remove(oldest.Key);
_logger.Info($"GatherRuleSessionState: rule {ruleId} tracks more than {MaxLogFilesPerRule} files — forgot the position of {Path.GetFileName(oldest.Key)}");
}
private static string Prefix(string hash) => hash.Length > 8 ? hash.Substring(0, 8) : hash;
}
/// <summary>Immutable copy of a recorded logparser position.</summary>
internal sealed class LogPositionSnapshot
{
public LogPositionSnapshot(long position, long lineNumber, int headLength, string headHash,
bool fromPreviousRun, long heldTailStart)
{
Position = position;
LineNumber = lineNumber;
HeadLength = headLength;
HeadHash = headHash;
FromPreviousRun = fromPreviousRun;
HeldTailStart = heldTailStart;
}
public long Position { get; }
public long LineNumber { get; }
public int HeadLength { get; }
public string HeadHash { get; }
/// <summary>Restored from disk and not advanced by this process yet.</summary>
public bool FromPreviousRun { get; }
/// <summary>Start of an unfinished last line left for this run by the previous one; -1 when none.</summary>
public long HeldTailStart { get; }
}
/// <summary>How <see cref="GatherRuleSessionState.ResolveStart"/> decided where reading starts.</summary>
internal enum LogReadStart
{
FirstRead,
Continue,
Shrunk,
Replaced,
}
}
@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.IO;
using AutopilotMonitor.Agent.V2.Core.Logging;
using Newtonsoft.Json;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
{
/// <summary>
/// Persists <see cref="GatherRuleSessionState"/> in the agent's state directory so one
/// enrollment's logparser positions and on_change values survive agent restarts, reboots and
/// the WhiteGlove Part 2 resume.
/// <para>
/// The state is only resumed for the SAME session id: the state directory is one fixed folder
/// that a session rotation does not clear, and the new session starts empty in the backend, so
/// it must read its logs from the beginning.
/// </para>
/// Fail-soft like <c>BandwidthStatePersistence</c>: I/O errors never throw; a missing, corrupt
/// or foreign file loads as null (fresh start — the pre-persistence behavior).
/// </summary>
public class GatherRuleStatePersistence
{
public const string FileName = "gather-rule-state.json";
private const string SourceName = "GatherRuleStatePersistence";
private readonly string _stateDirectory;
private readonly string _stateFilePath;
private readonly AgentLogger _logger;
public GatherRuleStatePersistence(string stateDirectory, AgentLogger logger)
{
_stateDirectory = Environment.ExpandEnvironmentVariables(stateDirectory);
_stateFilePath = Path.Combine(_stateDirectory, FileName);
_logger = logger;
}
public string StateFilePath => _stateFilePath;
/// <summary>
/// Loads the persisted state, or null when absent, unreadable, or written for a different
/// session. <paramref name="discardReason"/> is null when there simply was no file.
/// </summary>
public GatherRuleStateData Load(string expectedSessionId, out string discardReason)
{
discardReason = null;
if (!File.Exists(_stateFilePath)) return null;
try
{
var json = File.ReadAllText(_stateFilePath);
var state = JsonConvert.DeserializeObject<GatherRuleStateData>(json);
if (state == null || string.IsNullOrEmpty(state.SessionId))
{
discardReason = "state file empty or invalid";
_logger.Warning($"[{SourceName}] persisted state file was empty or invalid — starting fresh");
return null;
}
if (!string.Equals(state.SessionId, expectedSessionId, StringComparison.OrdinalIgnoreCase))
{
discardReason = $"saved for session {state.SessionId}, current session is {expectedSessionId}";
_logger.Warning($"[{SourceName}] persisted state belongs to session {state.SessionId}, not {expectedSessionId} — starting fresh");
return null;
}
return state;
}
catch (Exception ex)
{
discardReason = $"state file unreadable: {ex.Message}";
_logger.Warning($"[{SourceName}] failed to load persisted state, starting fresh: {ex.Message}");
return null;
}
}
/// <summary>Persists the state (atomic write via temp file). Never throws; false when the write failed.</summary>
public bool Save(GatherRuleStateData state)
{
try
{
Directory.CreateDirectory(_stateDirectory);
var tempPath = _stateFilePath + ".tmp";
File.WriteAllText(tempPath, JsonConvert.SerializeObject(state));
if (File.Exists(_stateFilePath))
{
File.Replace(tempPath, _stateFilePath, destinationBackupFileName: null, ignoreMetadataErrors: true);
}
else
{
File.Move(tempPath, _stateFilePath);
}
return true;
}
catch (Exception ex)
{
_logger.Debug($"[{SourceName}] failed to save state: {ex.Message}");
return false;
}
}
}
// ---- DTOs for state serialization ----
public class GatherRuleStateData
{
public string SessionId { get; set; }
public DateTime SavedAtUtc { get; set; }
/// <summary>Least recently used first, so a restore keeps the eviction order.</summary>
public List<GatherLogPositionData> LogPositions { get; set; }
/// <summary>Rule id → canonical hash of the result the rule last emitted (on_change).</summary>
public Dictionary<string, string> OnChangeHashes { get; set; }
}
public class GatherLogPositionData
{
public string RuleId { get; set; }
public string Path { get; set; }
/// <summary>File offset right behind the last line the rule processed.</summary>
public long Position { get; set; }
/// <summary>Lines before <see cref="Position"/> — the base for <c>logLineNumber</c>.</summary>
public long LineNumber { get; set; }
/// <summary>Bytes from the start of the file the fingerprint covers (0..4096).</summary>
public int HeadLength { get; set; }
/// <summary>SHA-256 of those bytes, Base64; null when <see cref="HeadLength"/> is 0.</summary>
public string HeadHash { get; set; }
}
}
@@ -736,7 +736,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
imeLogPathOverride: _agentConfig.ImeLogPathOverride,
unrestrictedMode: _agentConfig.UnrestrictedMode,
gatherDebugLogPath: _agentConfig.GatherRuleDebugLogPath,
timelineEvents: timelineEvents));
timelineEvents: timelineEvents,
stateDirectory: _stateDirectory));
}
else if (!string.IsNullOrEmpty(_agentConfig.GatherRuleDebugLogPath))
{
@@ -23,7 +23,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
// V1 fired these from MonitoringService on every emitted EnrollmentEvent; the first V2
// wiring subscribed to SignalIngress.SignalPosted instead, which fires at enqueue time
// with the RAW collector payload — before the reducer has applied gates like the
// RealmJoin completion gate. Consequence (session 32312a32, rsneuffen.de): a phase_change
// RealmJoin completion gate. Consequence (session 32312a32): a phase_change
// rule on FinalizingSetup fired at the raw EspPhaseChanged(FinalizingSetup) signal (ESP
// exit / Hello wizard), 7 minutes before the engine declared phase_transition(FinalizingSetup)
// on the timeline — and before the RealmJoin package wrote the registry key the rule was
@@ -47,7 +47,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
string? imeLogPathOverride,
bool unrestrictedMode = false,
string? gatherDebugLogPath = null,
TimelineEventStream? timelineEvents = null)
TimelineEventStream? timelineEvents = null,
string? stateDirectory = null)
{
if (ingress == null) throw new ArgumentNullException(nameof(ingress));
if (clock == null) throw new ArgumentNullException(nameof(clock));
@@ -66,7 +67,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
var post = new InformationalEventPost(ingress, clock, logger);
_executor = new Monitoring.Telemetry.Gather.GatherRuleExecutor(
sessionId, tenantId, evt => post.Emit(evt), logger, imeLogPathOverride,
debugLogPath: gatherDebugLogPath);
debugLogPath: gatherDebugLogPath, stateDirectory: stateDirectory);
_timelineEvents = timelineEvents;
}
@@ -230,6 +230,9 @@ namespace AutopilotMonitor.Agent.V2
logger.Info($"--run-gather-rules: debug trace -> {gatherDebugLogPath}");
if (consoleMode) Console.WriteLine($"Debug trace: {gatherDebugLogPath}");
// No stateDirectory on purpose: this mode runs beside the live agent under a
// throwaway session id and must neither resume nor overwrite the session's
// gather state (logparser positions, on_change values).
using (var executor = new GatherRuleExecutor(sessionId, tenantId, emitEvent, logger, config.ImeLogPathOverride,
debugLogPath: gatherDebugLogPath,
debugEcho: consoleMode ? (Action<string>)(line => Console.WriteLine($" {line}")) : null))
@@ -207,8 +207,8 @@ public class BuiltInRulesTests
/// Sessions 81daa77f / 75d6ae8e (2026-08-25). IME writes this line and then returns before
/// its "Completed user session" statement, so on a device with no user-targeted Win32 apps
/// it is the ONLY evidence that user-phase enforcement finished. The exact wording is
/// pinned here against the real IME line (verified against decompiled IME 1.104.102.0,
/// ApplicationPoller and AppWorkloadAbstraction) because a silent drift would bring back
/// pinned here against the real IME line (verified against IME 1.104.102.0) because a
/// silent drift would bring back
/// the 30-min esp_exit_without_completion_evidence false positive with no test failing.
/// </summary>
[Fact]
@@ -0,0 +1,24 @@
using AutopilotMonitor.Functions.Services.Vulnerability;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// <see cref="CpeMatchScorer.ProductKey"/> turns a finding's CPE ("base CPE:installed version")
/// into the product identity the exposure summary groups by.
/// </summary>
public class CpeProductKeyTests
{
[Theory]
[InlineData("cpe:2.3:a:7-zip:7-zip:24.08", "7-zip:7-zip")]
[InlineData("cpe:2.3:a:7-zip:7-zip:", "7-zip:7-zip")] // finding without a version
[InlineData("cpe:2.3:a:Microsoft:Teams:1.6.00.4472", "microsoft:teams")]
[InlineData("cpe:2.3:a:contoso:widget:*:*:*:*:*:*:*:*:1.2.3", "contoso:widget")] // custom mapping typed in full
[InlineData(@"cpe:2.3:a:microsoft:visual_c\+\+:14.0", @"microsoft:visual_c\+\+")] // CPE escapes stay part of the key
[InlineData("cpe:2.3:a:*:*:1.0", "")]
[InlineData("cpe:2.3:a", "")]
[InlineData("", "")]
[InlineData(null, "")]
public void ProductKey_IsLowerCaseVendorAndProduct(string? cpe, string expected)
=> Assert.Equal(expected, CpeMatchScorer.ProductKey(cpe));
}
@@ -122,4 +122,22 @@ public class CveIndexEntityMergeTests
Assert.Single(TableStorageService.BuildCveIndexEntities(Tenant, Session, findings));
}
[Fact]
public void Product_IsTheCpeVendorAndProduct_ofTheWinningOccurrence()
{
var zip = Finding("7-Zip 24.08 (x64 edition)", "high", Vuln("CVE-1", 7.8, "HIGH"), Vuln("CVE-2", 3.3, "LOW"));
zip["cpeUri"] = "cpe:2.3:a:7-zip:7-zip:24.08";
var teams = Finding("Microsoft Teams", "high", Vuln("CVE-1", 8.8, "HIGH"));
teams["cpeUri"] = "cpe:2.3:a:microsoft:teams:1.6.00.4472";
var noCpe = Finding("Contoso Tool", "high", Vuln("CVE-3", 7.0, "HIGH"));
var entities = TableStorageService.BuildCveIndexEntities(Tenant, Session, new List<Dictionary<string, object>> { zip, teams, noCpe });
var cve1 = entities.Single(x => x.GetString("CveId") == "CVE-1");
Assert.Equal("Microsoft Teams", cve1.GetString("SoftwareName")); // name and product move together
Assert.Equal("microsoft:teams", cve1.GetString("Product"));
Assert.Equal("7-zip:7-zip", entities.Single(x => x.GetString("CveId") == "CVE-2").GetString("Product"));
Assert.Equal("", entities.Single(x => x.GetString("CveId") == "CVE-3").GetString("Product"));
}
}
@@ -0,0 +1,352 @@
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Functions.Services.Notifications;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// A stored RuleResult keeps the rule's {{token}} template. The web and the MCP server resolve
/// it when they render; a notification has no renderer, so the backend resolves it before the
/// text leaves. Three things are pinned here: the backend resolution equals the shared cases
/// every renderer runs, no placeholder reaches a notification for any built-in rule, and the
/// cut happens after the resolution and on a text boundary.
/// </summary>
public class RuleTemplateInterpolatorTests
{
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
private const string SessionId = "0f1e2d3c-4b5a-4978-8a6b-5c4d3e2f1a0b";
private const string FailedAppName = "Contoso Productivity Suite";
// ── Shared cases (tests/fixtures/rule-template-interpolation) ─────────
private static readonly Lazy<JObject> Fixture = new(() =>
{
var path = Path.Combine(FindRepoRoot(), "tests", "fixtures", "rule-template-interpolation", "cases.json");
// No date parsing: a timestamp-looking string must stay the string the renderers see.
return JsonConvert.DeserializeObject<JObject>(
File.ReadAllText(path), new JsonSerializerSettings { DateParseHandling = DateParseHandling.None })!;
});
public static IEnumerable<object[]> CaseNames()
=> Fixture.Value["cases"]!.Select(c => new object[] { c.Value<string>("name")! });
[Theory]
[MemberData(nameof(CaseNames))]
public void Interpolate_matches_the_shared_case(string name)
{
var testCase = Fixture.Value["cases"]!.Single(c => c.Value<string>("name") == name);
var template = testCase.Value<string?>("template");
var expected = testCase.Value<string>("expected")!;
var evidence = testCase["matchedConditions"] as JObject;
// Evidence as the rule engine builds it (nested dictionaries) ...
Assert.Equal(expected, RuleTemplateInterpolator.Interpolate(template, AsDictionaries(evidence)));
// ... and as a JSON read without normalization leaves it (JSON nodes as values).
Assert.Equal(expected, RuleTemplateInterpolator.Interpolate(template, AsJsonNodes(evidence)));
}
[Fact]
public void Shared_cases_are_present_and_cover_every_auto_field()
{
Assert.True(Fixture.Value["cases"]!.Count() >= 20, "cases.json lost cases — the parity guard is only as wide as the file.");
Assert.Equal(
Fixture.Value["autoFields"]!.ToObject<string[]>()!,
RuleEngine.EvidenceAutoFields);
}
// ── Notification variant ──────────────────────────────────────────────
[Fact]
public void Notification_drops_a_list_item_whose_value_was_not_recorded()
{
var text = "Facts:\n\n- **Reason:** `{{reason}}`\n- **ESP HRESULT:** `{{errorCode}}`\n* **App:** {{appName}}\n1. step {{exitCode}}\n\nDone.";
var evidence = new Dictionary<string, object>
{
["enrollment_failed_reason"] = new Dictionary<string, object> { ["field"] = "reason", ["value"] = "hello_timeout" },
};
var rendered = RuleTemplateInterpolator.InterpolateForNotification(text, evidence);
Assert.Equal("Facts:\n\n- **Reason:** `hello_timeout`\n\nDone.", rendered);
}
[Fact]
public void Notification_replaces_an_unrecorded_value_in_running_text()
{
var rendered = RuleTemplateInterpolator.InterpolateForNotification(
"App **{{appName}}** failed with HRESULT **{{errorCode}}**.",
new Dictionary<string, object>
{
["failed_app"] = new Dictionary<string, object> { ["field"] = "appName", ["value"] = FailedAppName },
});
Assert.Equal($"App **{FailedAppName}** failed with HRESULT **–**.", rendered);
}
[Fact]
public void Notification_removes_the_sentence_about_literal_placeholders()
{
var rendered = RuleTemplateInterpolator.InterpolateForNotification(
"See ANALYZE-APP-013 for the root cause. Any field still shown as a literal `{{…}}` placeholder was simply not recorded. Check the timeline.",
new Dictionary<string, object>());
Assert.Equal("See ANALYZE-APP-013 for the root cause. Check the timeline.", rendered);
}
[Fact]
public void Notification_without_evidence_or_text_is_safe()
{
Assert.Equal(string.Empty, RuleTemplateInterpolator.InterpolateForNotification(null, null));
Assert.Equal(string.Empty, RuleTemplateInterpolator.InterpolateForNotification("", new Dictionary<string, object>()));
Assert.Equal("Reason: –", RuleTemplateInterpolator.InterpolateForNotification("Reason: {{reason}}", null));
}
[Fact]
public void Notification_collapses_the_gap_a_dropped_paragraph_leaves()
{
var rendered = RuleTemplateInterpolator.InterpolateForNotification(
"First.\n\nOnly a literal `{{…}}` remark.\n\nLast.", new Dictionary<string, object>());
Assert.Equal("First.\n\nLast.", rendered);
}
// ── No placeholder leaves the backend ─────────────────────────────────
[Fact]
public void No_builtin_rule_sends_a_placeholder_whatever_the_evidence()
{
// Worst case for every rule: nothing recorded at all. Both alert builders are the only
// paths that put a rule explanation into a notification.
var offenders = new List<string>();
var templated = 0;
foreach (var rule in BuiltInAnalyzeRules.GetAll())
{
if (rule.Explanation.Contains("{{")) templated++;
var result = new RuleResult
{
RuleId = rule.RuleId,
RuleTitle = rule.Title,
Severity = "critical",
Category = rule.Category,
Explanation = rule.Explanation,
};
var fired = NotificationAlertBuilder.BuildRuleFiredAlert(result, "DESKTOP-TEST01", "SN-0001");
var enrollment = NotificationAlertBuilder.BuildEnrollmentAlert(
"DESKTOP-TEST01", "SN-0001", null, null, success: false, failureReason: "x", duration: null);
NotificationAlertBuilder.AddRuleResultSections(enrollment, new List<RuleResult> { result });
foreach (var section in fired.Sections.Concat(enrollment.Sections))
{
if (section.Text.Contains("{{") || section.Text.Contains("}}"))
offenders.Add($"{rule.RuleId}: {section.Text}");
Assert.True(section.Text.Length <= NotificationAlertBuilder.RuleFiredExplanationMaxLength);
}
}
// Positive control: the catalog really contains templated rules, so an empty offender
// list is a statement about them and not about a catalog without placeholders.
Assert.True(templated >= 10, $"Only {templated} built-in rules carry a placeholder — did the catalog load?");
Assert.True(offenders.Count == 0, "Placeholder reached a notification:\n" + string.Join("\n", offenders));
}
// ── End to end: engine evidence → alert ───────────────────────────────
[Fact]
public async Task Rule_fired_alert_shows_the_values_the_engine_recorded()
{
var result = await RunEnrollmentFailedRuleAsync(withEspFailure: true);
var alert = NotificationAlertBuilder.BuildRuleFiredAlert(result, "DESKTOP-TEST01", "SN-0001");
var text = Assert.Single(alert.Sections).Text;
Assert.Equal(
"The Autopilot enrollment has explicitly failed.\n\n" +
"**Key facts extracted from this session's events:**\n\n" +
"- **Failure reason:** `esp_terminal_failure`\n" +
$"- **First failed app:** `{FailedAppName}`\n" +
"- **ESP failed subcategory:** `Apps`\n" +
"- **ESP HRESULT:** `0x87d1041c` …",
text);
// The stored result is untouched: the web and the MCP server still resolve the template.
Assert.Contains("{{reason}}", result.Explanation);
}
[Fact]
public async Task Rule_fired_alert_reads_evidence_that_went_through_the_table()
{
var result = await RunEnrollmentFailedRuleAsync(withEspFailure: true);
var fresh = NotificationAlertBuilder.BuildRuleFiredAlert(result, null, null).Sections.Single().Text;
// Same write and read as TableStorageService: JSON column, then nested dictionaries.
var json = JsonConvert.SerializeObject(result.MatchedConditions);
result.MatchedConditions = AsDictionaries(JObject.Parse(json))!;
Assert.Equal(fresh, NotificationAlertBuilder.BuildRuleFiredAlert(result, null, null).Sections.Single().Text);
}
[Fact]
public async Task Rule_fired_alert_omits_the_facts_a_non_esp_failure_never_had()
{
var result = await RunEnrollmentFailedRuleAsync(withEspFailure: false);
var text = Assert.Single(NotificationAlertBuilder.BuildRuleFiredAlert(result, null, null).Sections).Text;
Assert.Contains("- **Failure reason:** `hello_timeout`", text);
Assert.DoesNotContain("First failed app", text);
Assert.DoesNotContain("ESP failed subcategory", text);
Assert.DoesNotContain("ESP HRESULT:", text);
}
[Fact]
public async Task Enrollment_alert_rule_section_is_resolved_and_cut_on_a_line()
{
var result = await RunEnrollmentFailedRuleAsync(withEspFailure: true);
var alert = NotificationAlertBuilder.BuildEnrollmentAlert(
"DESKTOP-TEST01", "SN-0001", null, null, success: false, failureReason: "x", duration: null);
NotificationAlertBuilder.AddRuleResultSections(alert, new List<RuleResult> { result });
var text = Assert.Single(alert.Sections).Text;
Assert.True(text.Length <= NotificationAlertBuilder.RuleSectionExplanationMaxLength);
Assert.EndsWith("- **Failure reason:** `esp_terminal_failure` …", text);
}
// ── Cut ───────────────────────────────────────────────────────────────
[Fact]
public void Truncate_keeps_short_text()
=> Assert.Equal("short", NotificationAlertBuilder.TruncateAtBoundary("short", 300));
[Fact]
public void Truncate_prefers_a_line_break_then_a_sentence_then_a_word()
{
var lines = "First paragraph of the text.\n" + new string('a', 40);
Assert.Equal("First paragraph of the text. …", NotificationAlertBuilder.TruncateAtBoundary(lines, 50));
var sentences = "One sentence here. Another sentence that runs on and on without an end";
Assert.Equal("One sentence here. …", NotificationAlertBuilder.TruncateAtBoundary(sentences, 30));
var words = "word word word word word word word word word word";
Assert.Equal("word word word word word …", NotificationAlertBuilder.TruncateAtBoundary(words, 30));
}
[Fact]
public void Truncate_never_exceeds_the_limit_and_survives_text_without_any_boundary()
{
var unbroken = new string('x', 500);
var cut = NotificationAlertBuilder.TruncateAtBoundary(unbroken, 100);
Assert.Equal(100, cut.Length);
Assert.EndsWith(" …", cut);
}
[Fact]
public void Truncate_ignores_a_boundary_that_would_waste_most_of_the_budget()
{
var text = "Hi.\n" + string.Join(" ", Enumerable.Repeat("word", 60));
var cut = NotificationAlertBuilder.TruncateAtBoundary(text, 100);
Assert.True(cut.Length > 50, cut);
Assert.True(cut.Length <= 100);
}
[Fact]
public void Truncate_does_not_leave_a_bold_or_code_span_open()
{
var bold = "See the **App Detection Failure During ESP** rule for the cause and the **remediation steps in detail** below";
Assert.Equal("See the **App Detection Failure During ESP** rule for the cause and the remediation steps …",
NotificationAlertBuilder.TruncateAtBoundary(bold, 94));
var code = "The installer returned `1603 fatal error during installation` and stopped the whole chain";
Assert.Equal("The installer returned 1603 fatal error during …",
NotificationAlertBuilder.TruncateAtBoundary(code, 50));
}
// ── Helpers ───────────────────────────────────────────────────────────
private static async Task<RuleResult> RunEnrollmentFailedRuleAsync(bool withEspFailure)
{
var rule = BuiltInAnalyzeRules.GetAll().Single(r => r.RuleId == "ANALYZE-ENRL-001");
var events = new List<EnrollmentEvent>
{
Event("enrollment_failed", 163, new Dictionary<string, object>
{
["reason"] = withEspFailure ? "esp_terminal_failure" : "hello_timeout",
}),
};
if (withEspFailure)
{
events.Add(Event("esp_failure_settle_started", 161, new Dictionary<string, object>
{
["failedSubcategory"] = "Apps",
["errorCode"] = "0x87d1041c",
}));
events.Add(Event("app_install_failed", 158, new Dictionary<string, object>
{
["appId"] = "00000000-0000-4000-8000-000000000001",
["appName"] = FailedAppName,
["errorCode"] = "0x87d1041c",
}));
}
var ruleRepo = new Mock<IRuleRepository>();
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule> { rule });
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(new List<AnalyzeRule>());
ruleRepo.Setup(r => r.GetRuleStatesAsync(It.IsAny<string>())).ReturnsAsync(new Dictionary<string, RuleState>());
ruleRepo.Setup(r => r.GetRuleResultsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<RuleResult>());
var sessionRepo = new Mock<ISessionRepository>();
sessionRepo.Setup(s => s.GetSessionEventsStrictAsync(TenantId, SessionId, It.IsAny<int>())).ReturnsAsync(events);
var ruleService = new AnalyzeRuleService(ruleRepo.Object, NullLogger<AnalyzeRuleService>.Instance);
var engine = new RuleEngine(ruleService, ruleRepo.Object, sessionRepo.Object, NullLogger<RuleTemplateInterpolatorTests>.Instance);
var outcome = await engine.AnalyzeSessionAsync(TenantId, SessionId);
return Assert.Single(outcome.Results);
}
private static EnrollmentEvent Event(string eventType, long sequence, Dictionary<string, object> data) => new()
{
EventId = Guid.NewGuid().ToString(),
TenantId = TenantId,
SessionId = SessionId,
EventType = eventType,
Timestamp = DateTime.UtcNow,
Sequence = sequence,
Data = data,
};
private static Dictionary<string, object>? AsJsonNodes(JObject? evidence)
=> evidence?.Properties().ToDictionary(p => p.Name, p => (object)p.Value);
private static Dictionary<string, object>? AsDictionaries(JObject? evidence)
=> evidence?.Properties().ToDictionary(p => p.Name, p => Plain(p.Value)!);
private static object? Plain(JToken token) => token switch
{
JObject o => o.Properties().ToDictionary(p => p.Name, p => Plain(p.Value)!),
JArray a => a.Select(Plain).ToList(),
JValue v => v.Value,
_ => null,
};
private static string FindRepoRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null && !File.Exists(Path.Combine(dir.FullName, "AutopilotMonitor.sln")))
{
dir = dir.Parent;
}
Assert.NotNull(dir);
return dir!.FullName;
}
}
@@ -14,13 +14,14 @@ public class VulnerabilitySummaryAggregatorTests
private static CveExposureEntry Row(
string cve, string session, string severity, double score,
bool kev = false, string tenant = "t1", string software = "Acme App",
DateTime? detectedAt = null)
DateTime? detectedAt = null, string product = "")
=> new()
{
TenantId = tenant,
CveId = cve,
SessionId = session,
SoftwareName = software,
Product = product,
CvssScore = score,
CvssSeverity = severity,
IsKev = kev,
@@ -168,6 +169,245 @@ public class VulnerabilitySummaryAggregatorTests
Assert.True(r.Truncated);
Assert.Equal(365, r.WindowDays); // clamped from 9999
Assert.Empty(r.TopCves);
Assert.Empty(r.TopSoftware);
Assert.Equal(0, r.TotalAffectedSessions);
Assert.Equal(0, r.DistinctSoftware);
Assert.Equal(0, r.KevAffectedSessions);
}
[Fact]
public void TopCves_AppendKevCvesBelowTheCut_inDeviceOrder()
{
var rows = new[]
{
Row("CVE-WIDE", "s1", "High", 7.0), Row("CVE-WIDE", "s2", "High", 7.0), Row("CVE-WIDE", "s3", "High", 7.0),
Row("CVE-MID", "s1", "High", 8.0), Row("CVE-MID", "s2", "High", 8.0),
Row("CVE-KEV", "s4", "High", 7.8, kev: true),
};
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, topN: 1, days: 30, crossTenant: false, nowUtc: Now);
Assert.Equal(new[] { "CVE-WIDE", "CVE-KEV" }, r.TopCves.Select(c => c.CveId));
}
[Fact]
public void KevAdditions_AreCapped()
{
var rows = new List<CveExposureEntry> { Row("CVE-WIDE", "s1", "High", 7.0), Row("CVE-WIDE", "s2", "High", 7.0) };
rows.AddRange(Enumerable.Range(0, VulnerabilitySummaryAggregator.MaxKevAdditions + 10)
.Select(i => Row($"CVE-KEV-{i:D3}", $"k{i}", "High", 7.5, kev: true)));
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, topN: 1, days: 30, crossTenant: false, nowUtc: Now);
Assert.Equal(1 + VulnerabilitySummaryAggregator.MaxKevAdditions, r.TopCves.Count);
Assert.Equal("CVE-WIDE", r.TopCves[0].CveId);
Assert.All(r.TopCves.Skip(1), c => Assert.True(c.IsKev));
}
[Fact]
public void KevAffectedSessions_CountsDistinctSessionsWithAKevCve()
{
var rows = new[]
{
Row("CVE-K1", "s1", "High", 8.8, kev: true),
Row("CVE-K2", "s1", "High", 8.1, kev: true), // same session, counted once
Row("CVE-K2", "s2", "High", 8.1, kev: true),
Row("CVE-N", "s3", "High", 7.0),
};
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, 20, 30, false, Now);
Assert.Equal(2, r.KevAffectedSessions);
Assert.Equal(3, r.TotalAffectedSessions);
}
[Fact]
public void TopSoftware_FoldsAProductAcrossTitlesAndCves()
{
const string zip = "7-zip:7-zip";
var rows = new[]
{
Row("CVE-A", "s1", "HIGH", 7.8, software: "7-Zip 24.08 (x64 edition)", product: zip),
Row("CVE-B", "s1", "LOW", 3.3, software: "7-Zip 24.08 (x64 edition)", product: zip),
Row("CVE-A", "s2", "HIGH", 7.8, software: "7-Zip 25.01 (x64)", product: zip),
Row("CVE-A", "s3", "HIGH", 7.8, software: "7-Zip 24.08 (x64 edition)", product: zip),
Row("CVE-T", "s4", "MEDIUM", 5.0, software: "Microsoft Teams", product: "microsoft:teams"),
};
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, 20, 30, false, Now);
Assert.Equal(2, r.DistinctSoftware);
var p = r.TopSoftware[0];
Assert.Equal(zip, p.Product);
Assert.Equal("7-Zip", p.Name);
Assert.Equal(3, p.AffectedSessions);
Assert.Equal(2, p.CveCount);
Assert.Equal(0, p.KevCount);
Assert.Equal("HIGH", p.CvssSeverity);
Assert.Equal(7.8, p.CvssScore);
Assert.Equal(new[] { "7-Zip 24.08 (x64 edition)", "7-Zip 25.01 (x64)" }, p.Titles); // most sessions first
var a = p.Cves.Single(c => c.CveId == "CVE-A");
Assert.Equal(3, a.AffectedSessions);
Assert.Equal(1, p.Cves.Single(c => c.CveId == "CVE-B").AffectedSessions);
}
[Fact]
public void TopSoftware_RowWithoutProductBorrowsItFromTheSameTitle_elseUsesTheTitle()
{
var rows = new[]
{
Row("CVE-A", "s1", "High", 7.8, software: "7-Zip 24.08 (x64 edition)", product: "7-zip:7-zip"),
Row("CVE-A", "s2", "High", 7.8, software: "7-zip 24.08 (X64 Edition)"), // legacy row, same title
Row("CVE-C", "s3", "High", 7.1, software: "Contoso Tool 1.0"), // legacy row, title never seen with a product
Row("CVE-D", "s4", "High", 7.1, software: ""), // neither: left out of the product view
};
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, 20, 30, false, Now);
Assert.Equal(2, r.DistinctSoftware);
var zip = r.TopSoftware.Single(s => s.Product == "7-zip:7-zip");
Assert.Equal(2, zip.AffectedSessions);
var contoso = r.TopSoftware.Single(s => s.Product == "Contoso Tool 1.0");
Assert.Equal("Contoso Tool", contoso.Name);
Assert.Equal(3, r.DistinctCves); // the row without a title still counts as a CVE
}
[Fact]
public void TopSoftware_CarriesTheMostUrgentCvesFirst_cappedWithTheFullCount()
{
const string chrome = "google:chrome";
var act = Row("CVE-ACT", "s1", "High", 8.1, kev: true, software: "Google Chrome", product: chrome); act.Priority = "act";
var attendEpss = Row("CVE-ATT-E", "s1", "Medium", 6.5, software: "Google Chrome", product: chrome); attendEpss.Priority = "attend"; attendEpss.EpssScore = 0.4;
var attendCvss = Row("CVE-ATT-C", "s1", "Critical", 9.6, software: "Google Chrome", product: chrome); attendCvss.Priority = "attend"; attendCvss.EpssScore = 0.01;
var rows = new List<CveExposureEntry> { act, attendEpss, attendCvss };
for (var i = 0; i < 5; i++)
{
var track = Row($"CVE-TRK-{i}", "s1", "High", 7.0 + i / 10.0, software: "Google Chrome", product: chrome);
track.Priority = "track";
rows.Add(track);
}
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, 20, 30, false, Now);
var p = Assert.Single(r.TopSoftware);
Assert.Equal(8, p.CveCount);
Assert.Equal(1, p.KevCount);
Assert.Equal("act", p.Priority);
Assert.Equal("Critical", p.CvssSeverity); // worst band, with the score of that CVE
Assert.Equal(9.6, p.CvssScore);
Assert.Equal(VulnerabilitySummaryAggregator.MaxCvesPerSoftware, p.Cves.Count);
Assert.Equal(new[] { "CVE-ACT", "CVE-ATT-E", "CVE-ATT-C" }, p.Cves.Select(c => c.CveId)); // act, then EPSS before CVSS
}
[Fact]
public void TopSoftware_IsCappedIndependentlyOfTopN_plusCappedKevProducts()
{
var rows = new List<CveExposureEntry>();
for (var p = 0; p < VulnerabilitySummaryAggregator.MaxSoftware + 5; p++)
for (var s = 0; s <= p; s++) // product p has p + 1 sessions
rows.Add(Row($"CVE-P{p}", $"p{p}-s{s}", "High", 7.0, software: $"Product {p}", product: $"acme:p{p}"));
for (var k = 0; k < VulnerabilitySummaryAggregator.MaxKevSoftwareAdditions + 2; k++)
rows.Add(Row($"CVE-K{k}", $"k{k}", "High", 7.8, kev: true, software: $"Kev Product {k}", product: $"acme:k{k}"));
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, topN: 100, days: 30, crossTenant: false, nowUtc: Now);
Assert.Equal(
VulnerabilitySummaryAggregator.MaxSoftware + VulnerabilitySummaryAggregator.MaxKevSoftwareAdditions,
r.TopSoftware.Count);
Assert.Equal("acme:p24", r.TopSoftware[0].Product); // most sessions first
Assert.All(r.TopSoftware.Skip(VulnerabilitySummaryAggregator.MaxSoftware), s => Assert.True(s.KevCount > 0));
Assert.Equal(VulnerabilitySummaryAggregator.MaxSoftware + 5 + VulnerabilitySummaryAggregator.MaxKevSoftwareAdditions + 2, r.DistinctSoftware);
}
[Fact]
public void TopSoftware_AppendsProductsWithAKevCveBelowTheCut()
{
var rows = new[]
{
Row("CVE-W", "s1", "High", 7.0, software: "Wide App", product: "acme:wide"),
Row("CVE-W", "s2", "High", 7.0, software: "Wide App", product: "acme:wide"),
Row("CVE-M", "s3", "High", 9.0, software: "Mid App", product: "acme:mid"),
Row("CVE-K", "s4", "High", 7.8, kev: true, software: "WinRAR 6.22 (64-bit)", product: "rarlab:winrar"),
};
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, topN: 1, days: 30, crossTenant: false, nowUtc: Now);
Assert.Equal(new[] { "acme:wide", "rarlab:winrar" }, r.TopSoftware.Select(s => s.Product));
Assert.Equal("WinRAR", r.TopSoftware[1].Name);
Assert.Equal(3, r.DistinctSoftware);
}
[Fact]
public void BandCves_AddEachBandsTopEntriesOutsideTheList_onlyWhenAsked()
{
var rows = new List<CveExposureEntry>
{
Row("CVE-WIDE", "s1", "High", 7.0), Row("CVE-WIDE", "s2", "High", 7.0), Row("CVE-WIDE", "s3", "High", 7.0),
Row("CVE-HIGH-2", "s1", "High", 7.5), Row("CVE-HIGH-2", "s2", "High", 7.5),
Row("CVE-ATT-1", "s1", "Critical", 9.8), Row("CVE-ATT-1", "s4", "Critical", 9.8),
Row("CVE-ATT-2", "s5", "Critical", 9.1),
Row("CVE-ATT-3", "s6", "Medium", 5.0),
Row("CVE-LOW", "s7", "Low", 2.0),
};
foreach (var r in rows)
r.Priority = r.CveId.StartsWith("CVE-ATT", StringComparison.Ordinal) ? "attend" : "track";
var plain = VulnerabilitySummaryAggregator.Aggregate(rows, false, topN: 1, days: 30, crossTenant: false, nowUtc: Now);
Assert.Null(plain.BandCves);
Assert.Null(plain.BandSoftware);
var r2 = VulnerabilitySummaryAggregator.Aggregate(rows, false, topN: 1, days: 30, crossTenant: false, nowUtc: Now, perBand: 2);
Assert.Equal(new[] { "CVE-WIDE" }, r2.TopCves.Select(c => c.CveId));
// critical: ATT-1, ATT-2 · high: WIDE (listed), HIGH-2 · medium: ATT-3 · low: LOW · attend: ATT-1, ATT-2 · track: WIDE, HIGH-2
Assert.Equal(new[] { "CVE-ATT-1", "CVE-HIGH-2", "CVE-ATT-2", "CVE-ATT-3", "CVE-LOW" }, r2.BandCves!.Select(c => c.CveId));
Assert.All(r2.BandCves!, c => Assert.NotEmpty(c.SampleSoftware));
}
[Fact]
public void BandSoftware_BandsProductsByTheirWorstValues_outsideTopSoftware()
{
var wide1 = Row("CVE-W", "s1", "High", 7.0, software: "Wide App", product: "acme:wide"); wide1.Priority = "track";
var wide2 = Row("CVE-W", "s2", "High", 7.0, software: "Wide App", product: "acme:wide"); wide2.Priority = "track";
var crit = Row("CVE-C", "s3", "Critical", 9.6, software: "Edge Tool", product: "acme:edge"); crit.Priority = "attend";
var low = Row("CVE-L", "s4", "Low", 2.1, software: "Small Tool", product: "acme:small"); low.Priority = "track";
var r = VulnerabilitySummaryAggregator.Aggregate(
new[] { wide1, wide2, crit, low }, false, topN: 1, days: 30, crossTenant: false, nowUtc: Now, perBand: 1);
Assert.Equal(new[] { "acme:wide" }, r.TopSoftware.Select(s => s.Product));
// critical + attend → edge; low → small; high + track are already held by wide.
Assert.Equal(new[] { "acme:edge", "acme:small" }, r.BandSoftware!.Select(s => s.Product));
}
[Fact]
public void PerBand_IsClamped()
{
var rows = Enumerable.Range(0, VulnerabilitySummaryAggregator.MaxPerBand + 10)
.Select(i => Row($"CVE-{i:D3}", $"s{i}", "Medium", 5.0))
.ToList();
var r = VulnerabilitySummaryAggregator.Aggregate(rows, false, topN: 1, days: 30, crossTenant: false, nowUtc: Now, perBand: 999);
Assert.Equal(VulnerabilitySummaryAggregator.MaxPerBand - 1, r.BandCves!.Count); // the band's first entry is already listed
}
[Theory]
[InlineData("7-Zip", "7-Zip 24.08 (x64 edition)", "7-Zip 25.01 (x64)", "7-Zip 26.00 (x64 edition)")]
[InlineData("Cisco Secure Client", "Cisco Secure Client - AnyConnect VPN ", "Cisco Secure Client - Cloud Management")]
[InlineData("Microsoft Teams", "Microsoft Teams", "MSTeams", "Teams Machine-Wide Installer")]
[InlineData("Microsoft Teams", "Microsoft Teams", "Microsoft 365 Apps")] // one shared word is not a name
[InlineData("WinRAR", "WinRAR 6.22 (64-bit)")]
[InlineData("Mozilla Firefox", "Mozilla Firefox (x64 en-US)")]
[InlineData("Google Chrome", "Google Chrome 127.0.6533.74")]
[InlineData("Microsoft Office 2016", "Microsoft Office 2016")] // a bare year or major version stays
[InlineData("PowerShell 7-x64", "PowerShell 7-x64")]
[InlineData("Contoso Agent", "Contoso Agent v2.4.1 x64")]
[InlineData("1.2.3", "1.2.3")] // never stripped to nothing
public void DisplayName_UsesSharedWordsOrTheMostCommonTitle_withoutVersionAndArchitecture(string expected, params string[] titles)
=> Assert.Equal(expected, VulnerabilitySummaryAggregator.DisplayName(titles));
[Fact]
public void DisplayName_OfNoTitlesIsEmpty()
=> Assert.Equal("", VulnerabilitySummaryAggregator.DisplayName(Array.Empty<string>()));
}
@@ -655,12 +655,12 @@ public class VulnerabilityWireParityTests
}
// ---- GetVulnerabilitySummary / GetGlobalVulnerabilitySummary -------------------------
// The endpoint always serialized the named CveExposureSummary record (never anonymous);
// it only gained the IApiResponse marker. The anonymous side here replicates the record's
// established wire shape to pin key names, order and the TotalAffectedTenants omission.
// The endpoint always serialized the named CveExposureSummary record (never anonymous).
// The anonymous side pins the wire shape: key names, order and the TotalAffectedTenants /
// EpssScore omission. D-307 added distinctSoftware, kevAffectedSessions and topSoftware.
[Fact]
public void CveExposureSummary_wire_shape_is_unchanged_by_the_IApiResponse_marker()
public void CveExposureSummary_pins_the_cross_tenant_wire_shape()
{
var breakdown = new SeverityBreakdown { Critical = 1, High = 2, Medium = 0, Low = 0 };
var priorities = new PriorityBreakdown { Act = 1, Attend = 1, Track = 1 };
@@ -686,10 +686,32 @@ public class VulnerabilityWireParityTests
totalAffectedSessions = 11,
totalAffectedTenants = (int?)3,
distinctCves = 3,
distinctSoftware = 2,
kevCves = 1,
kevAffectedSessions = 7,
severityBreakdown = breakdown,
priorityBreakdown = priorities,
topCves,
topSoftware = new[]
{
new
{
product = "7-zip:7-zip",
name = "7-Zip",
affectedSessions = 7,
cveCount = 2,
kevCount = 1,
cvssSeverity = "critical",
cvssScore = 9.8,
priority = "act",
titles = new[] { "7-Zip 24.08 (x64)", "7-Zip 25.01 (x64)" },
cves = new object[]
{
new { cveId = "CVE-2026-12345", cvssSeverity = "critical", cvssScore = 9.8, isKev = true, epssScore = (double?)0.94, priority = "act", affectedSessions = 7 },
new { cveId = "CVE-2026-23456", cvssSeverity = "low", cvssScore = 3.3, isKev = false, epssScore = (double?)null, priority = "track", affectedSessions = 2 },
},
},
},
truncated = false,
},
new CveExposureSummary
@@ -698,10 +720,88 @@ public class VulnerabilityWireParityTests
TotalAffectedSessions = 11,
TotalAffectedTenants = 3,
DistinctCves = 3,
DistinctSoftware = 2,
KevCves = 1,
KevAffectedSessions = 7,
SeverityBreakdown = breakdown,
PriorityBreakdown = priorities,
TopCves = topCves,
TopSoftware = new List<TopSoftware>
{
new TopSoftware
{
Product = "7-zip:7-zip",
Name = "7-Zip",
AffectedSessions = 7,
CveCount = 2,
KevCount = 1,
CvssSeverity = "critical",
CvssScore = 9.8,
Priority = "act",
Titles = new List<string> { "7-Zip 24.08 (x64)", "7-Zip 25.01 (x64)" },
Cves = new List<SoftwareCve>
{
new SoftwareCve { CveId = "CVE-2026-12345", CvssSeverity = "critical", CvssScore = 9.8, IsKev = true, EpssScore = 0.94, Priority = "act", AffectedSessions = 7 },
new SoftwareCve { CveId = "CVE-2026-23456", CvssSeverity = "low", CvssScore = 3.3, IsKev = false, EpssScore = null, Priority = "track", AffectedSessions = 2 },
},
},
},
Truncated = false,
});
}
[Fact]
public void CveExposureSummary_carries_the_band_lists_after_topSoftware_when_requested()
{
var breakdown = new SeverityBreakdown { Critical = 1, High = 1, Medium = 0, Low = 0 };
var priorities = new PriorityBreakdown { Act = 0, Attend = 1, Track = 1 };
var wide = new TopCve
{
CveId = "CVE-2026-11111", CvssSeverity = "HIGH", CvssScore = 7.5, IsKev = false, EpssScore = 0.01,
Priority = "track", AffectedSessions = 40, SampleSoftware = new List<string> { "Contoso Agent 2.1" },
};
var attend = new TopCve
{
CveId = "CVE-2026-22222", CvssSeverity = "CRITICAL", CvssScore = 9.6, IsKev = false, EpssScore = null,
Priority = "attend", AffectedSessions = 2, SampleSoftware = new List<string> { "Contoso Viewer 1.0" },
};
var topCves = new List<TopCve> { wide };
var topSoftware = new List<TopSoftware>();
var bandCves = new List<TopCve> { attend };
var bandSoftware = new List<TopSoftware>();
AssertParity(
new
{
windowDays = 30,
totalAffectedSessions = 42,
distinctCves = 2,
distinctSoftware = 2,
kevCves = 0,
kevAffectedSessions = 0,
severityBreakdown = breakdown,
priorityBreakdown = priorities,
topCves,
topSoftware,
bandCves,
bandSoftware,
truncated = false,
},
new CveExposureSummary
{
WindowDays = 30,
TotalAffectedSessions = 42,
TotalAffectedTenants = null,
DistinctCves = 2,
DistinctSoftware = 2,
KevCves = 0,
KevAffectedSessions = 0,
SeverityBreakdown = breakdown,
PriorityBreakdown = priorities,
TopCves = topCves,
TopSoftware = topSoftware,
BandCves = bandCves,
BandSoftware = bandSoftware,
Truncated = false,
});
}
@@ -712,6 +812,7 @@ public class VulnerabilityWireParityTests
var breakdown = new SeverityBreakdown { Critical = 0, High = 0, Medium = 0, Low = 0 };
var priorities = new PriorityBreakdown { Act = 0, Attend = 0, Track = 0 };
var topCves = new List<TopCve>();
var topSoftware = new List<TopSoftware>();
AssertParity(
new
@@ -720,10 +821,13 @@ public class VulnerabilityWireParityTests
totalAffectedSessions = 0,
totalAffectedTenants = (int?)null,
distinctCves = 0,
distinctSoftware = 0,
kevCves = 0,
kevAffectedSessions = 0,
severityBreakdown = breakdown,
priorityBreakdown = priorities,
topCves,
topSoftware,
truncated = true,
},
new CveExposureSummary
@@ -732,10 +836,13 @@ public class VulnerabilityWireParityTests
TotalAffectedSessions = 0,
TotalAffectedTenants = null,
DistinctCves = 0,
DistinctSoftware = 0,
KevCves = 0,
KevAffectedSessions = 0,
SeverityBreakdown = breakdown,
PriorityBreakdown = priorities,
TopCves = topCves,
TopSoftware = topSoftware,
Truncated = true,
});
}
@@ -7,7 +7,7 @@ using AutopilotMonitor.Shared.Models.Vulnerability;
namespace AutopilotMonitor.Functions.Functions.Vulnerability
{
// The wire types (CveExposureSummary, SeverityBreakdown, TopCve) live in
// The wire types (CveExposureSummary, SeverityBreakdown, TopCve, TopSoftware) live in
// AutopilotMonitor.Shared.Models/VulnerabilityApiModels.cs so the manifest export sees them.
/// <summary>
@@ -17,6 +17,38 @@ namespace AutopilotMonitor.Functions.Functions.Vulnerability
/// </summary>
public static class VulnerabilitySummaryAggregator
{
// The caps keep the response under the MCP tool's 50k-character result cap at topN = 100
// (a TopCve is ~210 characters, a TopSoftware entry ~800); the MCP passes it through verbatim.
/// <summary>
/// Cap on the KEV CVEs appended below the topN cut. Known-exploited CVEs are "patch first"
/// whatever their device count, so a list ranked by devices must not drop them.
/// </summary>
public const int MaxKevAdditions = 25;
/// <summary>Products ranked by devices, before the KEV additions (the list is min(topN, this) long).</summary>
public const int MaxSoftware = 20;
/// <summary>Cap on the products with a KEV CVE appended below the product cut.</summary>
public const int MaxKevSoftwareAdditions = 10;
/// <summary>CVEs carried per product entry; <see cref="TopSoftware.CveCount"/> keeps the full count.</summary>
public const int MaxCvesPerSoftware = 3;
/// <summary>Raw titles carried per product entry.</summary>
public const int MaxTitlesPerSoftware = 3;
/// <summary>
/// Upper bound of the per-band representatives (<see cref="CveExposureSummary.BandCves"/>).
/// Only the portal asks for them; the MCP tool never does, so its response stays within its cap.
/// </summary>
public const int MaxPerBand = 25;
private static readonly HashSet<string> ArchitectureTokens = new(StringComparer.OrdinalIgnoreCase)
{
"x64", "x86", "amd64", "arm64", "64-bit", "32-bit",
};
private static int SeverityRank(string? severity) => severity?.Trim().ToLowerInvariant() switch
{
"critical" => 4,
@@ -26,15 +58,39 @@ namespace AutopilotMonitor.Functions.Functions.Vulnerability
_ => 0,
};
private static string SeverityKey(int rank) => rank switch
{
4 => "critical",
3 => "high",
2 => "medium",
1 => "low",
_ => string.Empty,
};
private static string PriorityKey(string? priority) => CvePriority.Rank(priority) switch
{
3 => CvePriority.Act,
2 => CvePriority.Attend,
1 => CvePriority.Track,
_ => string.Empty,
};
/// <param name="perBand">
/// When above 0, the summary also carries <see cref="CveExposureSummary.BandCves"/> and
/// <see cref="CveExposureSummary.BandSoftware"/>: per severity and priority band its top
/// entries outside the lists, so a band filter never comes up empty while the band has entries.
/// </param>
public static CveExposureSummary Aggregate(
IReadOnlyList<CveExposureEntry> rows,
bool truncated,
int topN,
int days,
bool crossTenant,
DateTime nowUtc)
DateTime nowUtc,
int perBand = 0)
{
if (topN < 1) topN = 1;
perBand = Math.Clamp(perBand, 0, MaxPerBand);
var windowDays = Math.Clamp(days, 1, 365);
var cutoff = nowUtc.AddDays(-windowDays);
@@ -44,73 +100,62 @@ namespace AutopilotMonitor.Functions.Functions.Vulnerability
var inWindow = rows
.Where(r => !r.DetectedAt.HasValue || r.DetectedAt.Value >= cutoff)
.ToList();
var withCve = inWindow.Where(r => !string.IsNullOrEmpty(r.CveId)).ToList();
var groups = inWindow
var cves = withCve
.GroupBy(r => r.CveId, StringComparer.OrdinalIgnoreCase)
.Where(g => !string.IsNullOrEmpty(g.Key))
.Select(g =>
{
var topSeverityRow = g.OrderByDescending(r => SeverityRank(r.CvssSeverity)).First();
return new
{
CveId = g.Key,
Severity = topSeverityRow.CvssSeverity,
SeverityRank = SeverityRank(topSeverityRow.CvssSeverity),
CvssScore = g.Max(r => r.CvssScore),
IsKev = g.Any(r => r.IsKev),
// Max over a nullable ignores nulls and yields null when nothing is scored.
EpssScore = g.Max(r => r.EpssScore),
Priority = g.Select(r => r.Priority)
.Aggregate(string.Empty, (best, p) => CvePriority.Rank(p) > CvePriority.Rank(best) ? p : best),
AffectedSessions = g.Select(r => r.SessionId)
.Where(s => !string.IsNullOrEmpty(s))
.Distinct(StringComparer.OrdinalIgnoreCase).Count(),
SampleSoftware = g.Select(r => r.SoftwareName)
.Where(s => !string.IsNullOrEmpty(s))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase)
.Take(3).ToList(),
};
})
.Select(g => FoldCve(g.Key, g.ToList()))
.ToList();
var topCves = groups
var rankedCves = cves
.OrderByDescending(c => c.AffectedSessions)
.ThenByDescending(c => c.CvssScore)
.ThenBy(c => c.CveId, StringComparer.OrdinalIgnoreCase)
.Take(topN)
.Select(c => new TopCve
{
CveId = c.CveId,
CvssSeverity = c.Severity,
CvssScore = c.CvssScore,
IsKev = c.IsKev,
EpssScore = c.EpssScore,
Priority = c.Priority,
AffectedSessions = c.AffectedSessions,
SampleSoftware = c.SampleSoftware,
})
.ToList();
var listedCves = WithKevAdditions(rankedCves, topN, c => c.IsKev, MaxKevAdditions);
var software = FoldSoftware(withCve);
var rankedSoftware = software
.OrderByDescending(s => s.AffectedSessions)
.ThenByDescending(s => CvePriority.Rank(s.Priority))
.ThenByDescending(s => s.CvssScore)
.ThenBy(s => s.Name, StringComparer.OrdinalIgnoreCase)
.ThenBy(s => s.Product, StringComparer.OrdinalIgnoreCase)
.ToList();
var topSoftware = WithKevAdditions(
rankedSoftware, Math.Min(topN, MaxSoftware), s => s.KevCount > 0, MaxKevSoftwareAdditions);
// A product is banded by its worst values, the only ones it carries.
List<TopCve>? bandCves = null;
List<TopSoftware>? bandSoftware = null;
if (perBand > 0)
{
bandCves = BandRepresentatives(
rankedCves, listedCves, perBand,
c => SeverityKey(c.SeverityRank), c => PriorityKey(c.Priority))
.Select(ToTopCve)
.ToList();
bandSoftware = BandRepresentatives(
rankedSoftware, topSoftware, perBand,
s => SeverityKey(SeverityRank(s.CvssSeverity)), s => PriorityKey(s.Priority));
}
var breakdown = new SeverityBreakdown
{
Critical = groups.Count(c => c.SeverityRank == 4),
High = groups.Count(c => c.SeverityRank == 3),
Medium = groups.Count(c => c.SeverityRank == 2),
Low = groups.Count(c => c.SeverityRank == 1),
Critical = cves.Count(c => c.SeverityRank == 4),
High = cves.Count(c => c.SeverityRank == 3),
Medium = cves.Count(c => c.SeverityRank == 2),
Low = cves.Count(c => c.SeverityRank == 1),
};
var priorities = new PriorityBreakdown
{
Act = groups.Count(c => CvePriority.Rank(c.Priority) == CvePriority.Rank(CvePriority.Act)),
Attend = groups.Count(c => CvePriority.Rank(c.Priority) == CvePriority.Rank(CvePriority.Attend)),
Track = groups.Count(c => CvePriority.Rank(c.Priority) == CvePriority.Rank(CvePriority.Track)),
Act = cves.Count(c => CvePriority.Rank(c.Priority) == CvePriority.Rank(CvePriority.Act)),
Attend = cves.Count(c => CvePriority.Rank(c.Priority) == CvePriority.Rank(CvePriority.Attend)),
Track = cves.Count(c => CvePriority.Rank(c.Priority) == CvePriority.Rank(CvePriority.Track)),
};
var totalAffectedSessions = inWindow.Select(r => r.SessionId)
.Where(s => !string.IsNullOrEmpty(s))
.Distinct(StringComparer.OrdinalIgnoreCase).Count();
int? totalAffectedTenants = crossTenant
? inWindow.Select(r => r.TenantId)
.Where(t => !string.IsNullOrEmpty(t))
@@ -120,15 +165,267 @@ namespace AutopilotMonitor.Functions.Functions.Vulnerability
return new CveExposureSummary
{
WindowDays = windowDays,
TotalAffectedSessions = totalAffectedSessions,
TotalAffectedSessions = DistinctSessions(inWindow),
TotalAffectedTenants = totalAffectedTenants,
DistinctCves = groups.Count,
KevCves = groups.Count(c => c.IsKev),
DistinctCves = cves.Count,
DistinctSoftware = software.Count,
KevCves = cves.Count(c => c.IsKev),
KevAffectedSessions = DistinctSessions(withCve.Where(r => r.IsKev)),
SeverityBreakdown = breakdown,
PriorityBreakdown = priorities,
TopCves = topCves,
TopCves = listedCves.Select(ToTopCve).ToList(),
TopSoftware = topSoftware,
BandCves = bandCves,
BandSoftware = bandSoftware,
Truncated = truncated,
};
}
private static TopCve ToTopCve(CveFold c) => new()
{
CveId = c.CveId,
CvssSeverity = c.Severity,
CvssScore = c.CvssScore,
IsKev = c.IsKev,
EpssScore = c.EpssScore,
Priority = c.Priority,
AffectedSessions = c.AffectedSessions,
SampleSoftware = c.Rows.Select(r => r.SoftwareName)
.Where(s => !string.IsNullOrEmpty(s))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(s => s, StringComparer.OrdinalIgnoreCase)
.Take(3).ToList(),
};
/// <summary>
/// For every band of every banding (severity, priority): the band's first
/// <paramref name="perBand"/> entries of the ranked list, minus the entries already
/// <paramref name="listed"/>. Entries without a band add nothing; the ranked order is kept.
/// </summary>
internal static List<T> BandRepresentatives<T>(
IReadOnlyList<T> ranked,
IEnumerable<T> listed,
int perBand,
params Func<T, string>[] bandings) where T : class
{
var alreadyListed = new HashSet<T>(listed, ReferenceEqualityComparer.Instance);
var picked = new SortedSet<int>();
foreach (var bandOf in bandings)
{
var taken = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < ranked.Count; i++)
{
var band = bandOf(ranked[i]);
if (string.IsNullOrEmpty(band)) continue;
taken.TryGetValue(band, out var count);
if (count >= perBand) continue;
taken[band] = count + 1;
if (!alreadyListed.Contains(ranked[i])) picked.Add(i);
}
}
return picked.Select(i => ranked[i]).ToList();
}
/// <summary>
/// The first <paramref name="topN"/> entries of a ranked list plus the KEV entries below the
/// cut (at most <paramref name="maxAdditions"/>). The input order is kept, so a list ranked by
/// affected sessions stays ranked.
/// </summary>
internal static List<T> WithKevAdditions<T>(IReadOnlyList<T> ranked, int topN, Func<T, bool> isKev, int maxAdditions)
=> ranked.Take(topN)
.Concat(ranked.Skip(topN).Where(isKev).Take(maxAdditions))
.ToList();
/// <summary>
/// Display name for a product from its detected titles, most sessions first: the leading
/// words every title shares when that is at least two words, else the most common title.
/// A trailing version or architecture suffix is dropped ("7-Zip 24.08 (x64 edition)" →
/// "7-Zip"); a name that would end up empty keeps its title.
/// </summary>
internal static string DisplayName(IReadOnlyList<string> titles)
{
var cleaned = titles.Select(t => t?.Trim() ?? string.Empty).Where(t => t.Length > 0).ToList();
if (cleaned.Count == 0) return string.Empty;
var words = cleaned.Select(t => t.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)).ToList();
var shared = 0;
while (shared < words[0].Length
&& words.All(w => w.Length > shared && string.Equals(w[shared], words[0][shared], StringComparison.OrdinalIgnoreCase)))
shared++;
var prefix = TrimTrailingSeparators(words[0].Take(shared).ToList());
var baseName = cleaned.Count > 1 && prefix.Count >= 2 ? string.Join(" ", prefix) : cleaned[0];
var stripped = StripVersionSuffix(baseName);
return stripped.Length > 0 ? stripped : baseName;
}
private static string StripVersionSuffix(string name)
{
var current = name.Trim();
while (true)
{
var before = current;
// A trailing parenthetical: "(x64 edition)", "(64-bit)", "(x64 en-US)".
if (current.EndsWith(")", StringComparison.Ordinal))
{
var open = current.LastIndexOf('(');
if (open > 0) current = current.Substring(0, open).TrimEnd();
}
var tokens = current.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).ToList();
if (tokens.Count > 1 && (IsVersionToken(tokens[^1]) || ArchitectureTokens.Contains(tokens[^1])))
tokens.RemoveAt(tokens.Count - 1);
current = string.Join(" ", TrimTrailingSeparators(tokens));
if (current == before) return current;
}
}
/// <summary>"24.08", "v1.2.3", "127.0.6533.74" — dotted digits, optional leading v. A bare integer ("2016", "7") is part of the name.</summary>
private static bool IsVersionToken(string token)
{
var s = token.StartsWith("v", StringComparison.OrdinalIgnoreCase) ? token.Substring(1) : token;
if (s.Length < 3 || !char.IsDigit(s[0]) || !char.IsDigit(s[^1])) return false;
var dots = 0;
foreach (var ch in s)
{
if (ch == '.') dots++;
else if (!char.IsDigit(ch)) return false;
}
return dots > 0;
}
private static List<string> TrimTrailingSeparators(List<string> tokens)
{
var list = tokens.ToList();
while (list.Count > 0)
{
var last = list[^1].TrimEnd('-', ':', ',', '|', '/', '–', '—');
if (last.Length == 0) { list.RemoveAt(list.Count - 1); continue; }
list[^1] = last;
break;
}
return list;
}
private static int DistinctSessions(IEnumerable<CveExposureEntry> rows)
=> rows.Select(r => r.SessionId)
.Where(s => !string.IsNullOrEmpty(s))
.Distinct(StringComparer.OrdinalIgnoreCase).Count();
private static CveFold FoldCve(string cveId, List<CveExposureEntry> rows)
{
var topSeverityRow = rows.OrderByDescending(r => SeverityRank(r.CvssSeverity)).First();
return new CveFold(
CveId: cveId,
Severity: topSeverityRow.CvssSeverity,
SeverityRank: SeverityRank(topSeverityRow.CvssSeverity),
CvssScore: rows.Max(r => r.CvssScore),
IsKev: rows.Any(r => r.IsKev),
// Max over a nullable ignores nulls and yields null when nothing is scored.
EpssScore: rows.Max(r => r.EpssScore),
Priority: rows.Select(r => r.Priority)
.Aggregate(string.Empty, (best, p) => CvePriority.Rank(p) > CvePriority.Rank(best) ? p : best),
AffectedSessions: DistinctSessions(rows),
Rows: rows);
}
/// <summary>
/// Folds the rows per product. A row without a product (written before the index carried
/// it, or a finding without a CPE) borrows the product of another row with the same title —
/// so the transition converges as new sessions are correlated — and otherwise is keyed by
/// its title. Rows with neither are left out of the product view.
/// </summary>
private static List<TopSoftware> FoldSoftware(List<CveExposureEntry> rows)
{
var productByTitle = rows
.Where(r => !string.IsNullOrEmpty(r.Product) && !string.IsNullOrWhiteSpace(r.SoftwareName))
.GroupBy(r => r.SoftwareName.Trim(), StringComparer.OrdinalIgnoreCase)
.ToDictionary(
g => g.Key,
g => g.GroupBy(r => r.Product, StringComparer.OrdinalIgnoreCase)
.OrderByDescending(p => p.Count())
.ThenBy(p => p.Key, StringComparer.OrdinalIgnoreCase)
.First().Key,
StringComparer.OrdinalIgnoreCase);
string ProductKey(CveExposureEntry r)
{
if (!string.IsNullOrEmpty(r.Product)) return r.Product;
var title = r.SoftwareName?.Trim() ?? string.Empty;
return title.Length > 0 && productByTitle.TryGetValue(title, out var product) ? product : title;
}
return rows
.Select(r => (Row: r, Key: ProductKey(r)))
.Where(x => x.Key.Length > 0)
.GroupBy(x => x.Key, x => x.Row, StringComparer.OrdinalIgnoreCase)
.Select(g =>
{
var productRows = g.ToList();
var productCves = productRows
.GroupBy(r => r.CveId, StringComparer.OrdinalIgnoreCase)
.Select(cg => FoldCve(cg.Key, cg.ToList()))
.ToList();
var worst = productCves
.OrderByDescending(c => c.SeverityRank)
.ThenByDescending(c => c.CvssScore)
.First();
var titles = productRows
.Where(r => !string.IsNullOrWhiteSpace(r.SoftwareName))
.GroupBy(r => r.SoftwareName.Trim(), StringComparer.OrdinalIgnoreCase)
.Select(tg => (Title: tg.Key, Sessions: DistinctSessions(tg)))
.OrderByDescending(t => t.Sessions)
.ThenBy(t => t.Title, StringComparer.OrdinalIgnoreCase)
.Select(t => t.Title)
.ToList();
return new TopSoftware
{
Product = g.Key,
Name = DisplayName(titles),
AffectedSessions = DistinctSessions(productRows),
CveCount = productCves.Count,
KevCount = productCves.Count(c => c.IsKev),
CvssSeverity = worst.Severity,
CvssScore = worst.CvssScore,
Priority = productCves.Select(c => c.Priority)
.Aggregate(string.Empty, (best, p) => CvePriority.Rank(p) > CvePriority.Rank(best) ? p : best),
Titles = titles.Take(MaxTitlesPerSoftware).ToList(),
Cves = productCves
.OrderByDescending(c => CvePriority.Rank(c.Priority))
.ThenByDescending(c => c.EpssScore ?? -1)
.ThenByDescending(c => c.CvssScore)
.ThenByDescending(c => c.AffectedSessions)
.ThenBy(c => c.CveId, StringComparer.OrdinalIgnoreCase)
.Take(MaxCvesPerSoftware)
.Select(c => new SoftwareCve
{
CveId = c.CveId,
CvssSeverity = c.Severity,
CvssScore = c.CvssScore,
IsKev = c.IsKev,
EpssScore = c.EpssScore,
Priority = c.Priority,
AffectedSessions = c.AffectedSessions,
})
.ToList(),
};
})
.ToList();
}
/// <summary>One CVE folded across its rows (the whole scope, or one product's rows).</summary>
private sealed record CveFold(
string CveId,
string Severity,
int SeverityRank,
double CvssScore,
bool IsKev,
double? EpssScore,
string Priority,
int AffectedSessions,
List<CveExposureEntry> Rows);
}
}
@@ -34,7 +34,7 @@ namespace AutopilotMonitor.Functions.Functions.Vulnerability
}
/// <summary>
/// GET /api/metrics/vulnerability?days=30&topN=20
/// GET /api/metrics/vulnerability?days=30&topN=20&perBand=10
/// Fleet vulnerability summary for the caller's tenant (MemberRead).
/// </summary>
[Function("GetVulnerabilitySummary")]
@@ -47,7 +47,7 @@ namespace AutopilotMonitor.Functions.Functions.Vulnerability
}
/// <summary>
/// GET /api/global/metrics/vulnerability?days=30&topN=20&tenantId=...
/// GET /api/global/metrics/vulnerability?days=30&topN=20&perBand=10&tenantId=...
/// Cross-tenant summary (Global Admin). With tenantId, scopes to one tenant.
/// </summary>
[Function("GetGlobalVulnerabilitySummary")]
@@ -67,14 +67,17 @@ namespace AutopilotMonitor.Functions.Functions.Vulnerability
var query = req.Query;
var days = QueryParams.Int(query["days"], @default: 30, min: 1, max: 365);
var topN = QueryParams.Int(query["topN"], @default: 20, min: 1, max: 100);
// Per-band representatives for the portal's band filters; callers that omit it
// (the MCP tool) get the lists without them.
var perBand = QueryParams.Int(query["perBand"], @default: 0, min: 0, max: VulnerabilitySummaryAggregator.MaxPerBand);
_logger.LogInformation(
"Vulnerability summary requested (scope={Scope}, days={Days}, topN={TopN})",
crossTenant ? "cross-tenant" : tenantId, days, topN);
"Vulnerability summary requested (scope={Scope}, days={Days}, topN={TopN}, perBand={PerBand})",
crossTenant ? "cross-tenant" : tenantId, days, topN, perBand);
var (rows, truncated) = await _sessionRepo.ScanCveIndexAsync(tenantId, MaxScanRows);
var summary = VulnerabilitySummaryAggregator.Aggregate(
rows, truncated, topN, days, crossTenant, DateTime.UtcNow);
rows, truncated, topN, days, crossTenant, DateTime.UtcNow, perBand);
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(summary);
@@ -233,13 +233,9 @@ namespace AutopilotMonitor.Functions.Services.Notifications
},
};
if (!string.IsNullOrEmpty(result.Explanation))
{
var explanation = result.Explanation.Length > 300
? result.Explanation[..300] + "..."
: result.Explanation;
var explanation = RenderExplanation(result, RuleFiredExplanationMaxLength);
if (explanation.Length > 0)
alert.Sections.Add(new NotificationSection { Title = "Explanation", Text = explanation });
}
if (!string.IsNullOrEmpty(sessionUrl))
alert.Actions.Add(new NotificationAction { Type = "openUrl", Title = "Open session", Url = sessionUrl });
@@ -273,18 +269,77 @@ namespace AutopilotMonitor.Functions.Services.Notifications
_ => "\ud83d\udfe1"
};
var explanation = r.Explanation?.Length > 200
? r.Explanation[..200] + "..."
: r.Explanation ?? "";
alert.Sections.Add(new NotificationSection
{
Title = $"{emoji} {r.RuleTitle}",
Text = explanation
Text = RenderExplanation(r, RuleSectionExplanationMaxLength)
});
}
}
internal const int RuleFiredExplanationMaxLength = 300;
internal const int RuleSectionExplanationMaxLength = 200;
/// <summary>
/// A stored <see cref="RuleResult.Explanation"/> is the rule's template. Tokens are
/// resolved BEFORE the cut: cutting first would split a placeholder or spend the
/// budget on placeholder names instead of the values.
/// </summary>
private static string RenderExplanation(RuleResult result, int maxLength)
=> TruncateAtBoundary(
RuleTemplateInterpolator.InterpolateForNotification(result.Explanation, result.MatchedConditions),
maxLength);
/// <summary>
/// Shortens to at most <paramref name="maxLength"/> characters at the last line break
/// inside the limit, else the last sentence end, else the last word. A boundary in the
/// first half of the limit is not taken, so the cut never throws away most of the budget.
/// A bold or code span the cut left open is closed by dropping its opening marker.
/// </summary>
internal static string TruncateAtBoundary(string text, int maxLength)
{
const string marker = " …";
if (text.Length <= maxLength)
return text;
var window = text[..(maxLength - marker.Length)];
var floor = window.Length / 2;
var cut = window.LastIndexOf('\n');
if (cut < floor)
{
cut = -1;
for (var i = window.Length - 2; i >= floor; i--)
{
if (window[i] is '.' or '!' or '?' && char.IsWhiteSpace(window[i + 1]))
{
cut = i + 1;
break;
}
}
}
if (cut < floor)
cut = window.LastIndexOf(' ');
if (cut < floor)
cut = window.Length;
var kept = DropUnpairedMarker(DropUnpairedMarker(window[..cut], "**"), "`");
return kept.TrimEnd() + marker;
}
private static string DropUnpairedMarker(string text, string markdownMarker)
{
var count = 0;
var last = -1;
for (var i = text.IndexOf(markdownMarker, StringComparison.Ordinal); i >= 0;
i = text.IndexOf(markdownMarker, i + markdownMarker.Length, StringComparison.Ordinal))
{
count++;
last = i;
}
return count % 2 == 0 ? text : text.Remove(last, markdownMarker.Length);
}
/// <summary>
/// Builds a notification alert for an SLA breach. Dispatches on
/// <paramref name="breachType"/>: <c>SuccessRate</c>, <c>Duration</c>, or <c>AppInstall</c>.
@@ -1307,6 +1307,17 @@ namespace AutopilotMonitor.Functions.Services
return (true, primary);
}
/// <summary>
/// Same-event fields copied into every evidence entry. Whitelist: short identifiers only;
/// errorDetail/message are excluded (can be multi-KB). Every renderer resolves these as
/// <c>{{token}}</c> — the web, the MCP server and <see cref="RuleTemplateInterpolator"/>
/// carry the same list, pinned by tests/fixtures/rule-template-interpolation/cases.json.
/// </summary>
internal static readonly IReadOnlyList<string> EvidenceAutoFields = new[]
{
"appId", "appName", "errorPatternId", "errorCode", "exitCode", "status", "timeoutHours"
};
/// <summary>
/// Adds slim identifying data fields from an event to the evidence dictionary with a prefix.
/// Free-text fields like <c>errorDetail</c> (often a stack trace) and <c>message</c> are
@@ -1317,10 +1328,7 @@ namespace AutopilotMonitor.Functions.Services
{
if (evt.Data == null) return;
// Whitelist: short identifiers only. errorDetail/message removed (can be multi-KB).
var knownFields = new[] { "appId", "appName", "errorPatternId", "errorCode", "exitCode", "status", "timeoutHours" };
foreach (var field in knownFields)
foreach (var field in EvidenceAutoFields)
{
var val = GetDataFieldValue(evt, field);
if (val != null)
@@ -0,0 +1,199 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using AutopilotMonitor.Shared.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AutopilotMonitor.Functions.Services
{
/// <summary>
/// Resolves the <c>{{token}}</c> placeholders of a rule's explanation/remediation text from a
/// result's <see cref="RuleResult.MatchedConditions"/>. A stored <see cref="RuleResult"/> keeps
/// the rule's raw template; the web (<c>lib/interpolateRuleTemplate.ts</c>) and the MCP server
/// (<c>src/interpolate-rule-template.ts</c>) resolve it when they render. This is the backend
/// copy for text that leaves without passing either of them (notifications).
/// <para>
/// Resolution order, identical in all three and pinned by
/// <c>tests/fixtures/rule-template-interpolation/cases.json</c>:
/// </para>
/// <list type="number">
/// <item>an evidence entry whose <c>field</c> equals the token (the last such entry wins);</item>
/// <item>a same-event auto-field named like the token (<see cref="RuleEngine.EvidenceAutoFields"/>;
/// the first non-empty one wins, which pins it to the rule's earliest matched condition);</item>
/// <item>an evidence entry whose signal name equals the token;</item>
/// <item>otherwise the token stays as written.</item>
/// </list>
/// </summary>
public static class RuleTemplateInterpolator
{
/// <summary>Shown in a notification where running text names a value that was not recorded.</summary>
internal const string NotRecorded = "–";
private static readonly Regex TokenRegex = new Regex(
@"\{\{\s*([a-zA-Z0-9_]+)\s*\}\}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex ListItemRegex = new Regex(
@"^\s*(?:[-*+]|\d+[.)])\s+", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex SentenceBreakRegex = new Regex(
@"(?<=[.!?])\s+", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex BlankRunRegex = new Regex(
@"\n{3,}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>
/// Replaces every resolvable token; an unresolved one stays literal, exactly as the web
/// and the MCP server render it.
/// </summary>
public static string Interpolate(string? text, IReadOnlyDictionary<string, object>? matchedConditions)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
var lookup = Lookup.From(matchedConditions);
return TokenRegex.Replace(text, m => lookup.Resolve(m.Groups[1].Value) ?? m.Value);
}
/// <summary>
/// Interpolation for text that leaves the backend as a notification. The recipient has no
/// renderer and no footnote explaining a literal placeholder, so none may survive: a list
/// item whose token was not recorded is dropped, a token in running text becomes
/// <see cref="NotRecorded"/>, and a sentence that talks about literal placeholders is removed.
/// </summary>
public static string InterpolateForNotification(string? text, IReadOnlyDictionary<string, object>? matchedConditions)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
var lookup = Lookup.From(matchedConditions);
var lines = new List<string>();
foreach (var line in text.Replace("\r\n", "\n").Split('\n'))
{
var unresolved = false;
var rendered = TokenRegex.Replace(line, m =>
{
var value = lookup.Resolve(m.Groups[1].Value);
if (value != null)
return value;
unresolved = true;
return NotRecorded;
});
if (unresolved && ListItemRegex.IsMatch(line))
continue;
if (rendered.Contains("{{", StringComparison.Ordinal))
{
rendered = string.Join(" ", SentenceBreakRegex.Split(rendered)
.Where(sentence => !sentence.Contains("{{", StringComparison.Ordinal)));
if (rendered.Length == 0)
continue;
}
lines.Add(rendered);
}
return BlankRunRegex.Replace(string.Join("\n", lines), "\n\n").Trim();
}
private sealed class Lookup
{
private readonly Dictionary<string, string> _byField = new Dictionary<string, string>(StringComparer.Ordinal);
private readonly Dictionary<string, string> _byAutoField = new Dictionary<string, string>(StringComparer.Ordinal);
private readonly Dictionary<string, string> _bySignal = new Dictionary<string, string>(StringComparer.Ordinal);
public string? Resolve(string token)
{
if (_byField.TryGetValue(token, out var value)) return value;
if (_byAutoField.TryGetValue(token, out value)) return value;
if (_bySignal.TryGetValue(token, out value)) return value;
return null;
}
public static Lookup From(IReadOnlyDictionary<string, object>? matchedConditions)
{
var lookup = new Lookup();
if (matchedConditions == null || matchedConditions.Count == 0)
return lookup;
// Evidence arrives in two shapes: nested dictionaries straight from the rule engine,
// or whatever the table read produced. Going through JSON gives both the form the
// web and the MCP server see. JsonSerializer.Create() ignores the process-wide
// default settings, so a naming strategy configured there cannot rename the keys.
JObject root;
try
{
root = JObject.FromObject(matchedConditions, JsonSerializer.Create());
}
catch (Exception)
{
// Evidence that cannot be serialized resolves nothing; the text is still sent.
return lookup;
}
foreach (var property in root.Properties())
{
if (property.Value is not JObject evidence)
{
if (property.Value is JValue scalar && scalar.Type != JTokenType.Null && scalar.Type != JTokenType.Undefined)
lookup._bySignal[property.Name] = Format(scalar);
continue;
}
var hasValue = evidence.TryGetValue("value", out var valueToken);
if (hasValue)
{
if (evidence["field"] is JValue { Type: JTokenType.String } field)
lookup._byField[(string)field.Value!] = Format(valueToken);
lookup._bySignal[property.Name] = Format(valueToken);
}
foreach (var autoField in RuleEngine.EvidenceAutoFields)
{
if (lookup._byAutoField.ContainsKey(autoField))
continue;
var formatted = Format(evidence[autoField]);
if (formatted.Length > 0)
lookup._byAutoField[autoField] = formatted;
}
}
return lookup;
}
// Mirrors the TypeScript formatValue: strings as they are, numbers and booleans the
// way JavaScript prints them, anything structured as compact JSON.
private static string Format(JToken? token)
{
if (token == null)
return string.Empty;
switch (token.Type)
{
case JTokenType.Null:
case JTokenType.Undefined:
return string.Empty;
case JTokenType.String:
return (string)((JValue)token).Value!;
case JTokenType.Boolean:
return (bool)token ? "true" : "false";
case JTokenType.Integer:
return Convert.ToString(((JValue)token).Value, CultureInfo.InvariantCulture) ?? string.Empty;
case JTokenType.Float:
return Convert.ToDouble(((JValue)token).Value, CultureInfo.InvariantCulture)
.ToString(CultureInfo.InvariantCulture);
case JTokenType.Object:
case JTokenType.Array:
return token.ToString(Formatting.None);
default:
// Date, Guid, TimeSpan, Uri: their JSON string form without the quotes.
return token.ToString(Formatting.None).Trim('"');
}
}
}
}
}
@@ -291,8 +291,9 @@ namespace AutopilotMonitor.Functions.Services
/// <summary>
/// Collapses report findings to one entity per CVE. Merge rule: the occurrence with the
/// highest CVSS score supplies score/severity/software name (ties keep report order),
/// IsKev is OR-ed, OverallRisk is the highest risk level seen across occurrences.
/// highest CVSS score supplies score/severity/software name/product (ties keep report
/// order), IsKev is OR-ed, OverallRisk is the highest risk level seen across occurrences.
/// Product is the finding's CPE "vendor:product" (<see cref="Vulnerability.CpeMatchScorer.ProductKey"/>).
/// </summary>
internal static List<TableEntity> BuildCveIndexEntities(string tenantId, string sessionId, List<Dictionary<string, object>> findings)
{
@@ -302,6 +303,7 @@ namespace AutopilotMonitor.Functions.Services
foreach (var finding in findings)
{
var softwareName = finding.TryGetValue("softwareName", out var sn) ? sn?.ToString() ?? "" : "";
var product = Vulnerability.CpeMatchScorer.ProductKey(finding.TryGetValue("cpeUri", out var cu) ? cu?.ToString() : null);
var overallRisk = finding.TryGetValue("riskLevel", out var rl) ? rl?.ToString() ?? "" : "";
if (!finding.TryGetValue("vulnerabilities", out var vulnsObj) || vulnsObj == null) continue;
@@ -330,6 +332,7 @@ namespace AutopilotMonitor.Functions.Services
existing["CvssScore"] = cvssScore;
existing["CvssSeverity"] = cvssSeverity;
existing["SoftwareName"] = softwareName;
existing["Product"] = product;
}
existing["IsKev"] = existing.GetBoolean("IsKev") == true || isKev;
if (epssScore.HasValue && epssScore.Value > (existing.GetDouble("EpssScore") ?? -1))
@@ -347,6 +350,7 @@ namespace AutopilotMonitor.Functions.Services
["TenantId"] = tenantId,
["CveId"] = cveId,
["SoftwareName"] = softwareName,
["Product"] = product,
["CvssScore"] = cvssScore,
["CvssSeverity"] = cvssSeverity,
["IsKev"] = isKev,
@@ -1380,7 +1384,7 @@ namespace AutopilotMonitor.Functions.Services
var select = new[]
{
"SessionId", "TenantId", "CveId", "SoftwareName",
"SessionId", "TenantId", "CveId", "SoftwareName", "Product",
"CvssScore", "CvssSeverity", "IsKev", "EpssScore", "Priority", "OverallRisk", "DetectedAt",
};
@@ -1406,6 +1410,7 @@ namespace AutopilotMonitor.Functions.Services
CveId = e.GetString("CveId") ?? string.Empty,
SessionId = e.GetString("SessionId") ?? e.RowKey,
SoftwareName = e.GetString("SoftwareName") ?? string.Empty,
Product = e.GetString("Product") ?? string.Empty,
CvssScore = e.GetDouble("CvssScore") ?? 0,
CvssSeverity = e.GetString("CvssSeverity") ?? string.Empty,
IsKev = e.GetBoolean("IsKev") ?? false,
@@ -148,6 +148,23 @@ namespace AutopilotMonitor.Functions.Services.Vulnerability
return (parts[2], parts[3], parts[4]);
}
/// <summary>
/// Product identity of a CPE 2.3 name as "vendor:product" in lower case
/// ("cpe:2.3:a:7-zip:7-zip:24.08" → "7-zip:7-zip"); empty when the name has no concrete
/// vendor and product. CveIndex rows carry it so the exposure summary can fold every title
/// and version of one product together.
/// </summary>
public static string ProductKey(string? cpeName)
{
var parts = ParseCpeComponents(cpeName ?? "");
if (parts == null) return "";
var (_, vendor, product) = parts.Value;
if (!IsConcrete(vendor) || !IsConcrete(product)) return "";
return $"{vendor}:{product}".ToLowerInvariant();
static bool IsConcrete(string value) => value.Length > 0 && value != "*" && value != "-";
}
/// <summary>
/// Build a CpeMappingEntry from an NVD CPE entry for saving as a custom mapping.
/// </summary>
+3 -3
View File
@@ -2284,9 +2284,9 @@
"license": "MIT"
},
"node_modules/fast-uri": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz",
"integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==",
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
"funding": [
{
"type": "github",
@@ -10,9 +10,7 @@ import { describe, it, expect } from 'vitest';
import { scanUntilMatch } from '../client.js';
import {
isKnownEventType,
isGatherOutputEventType,
isFilterableEventType,
assertKnownEventType,
withEventTypeNote,
assertKnownDevicePropertyKeys,
eventTypePrefixOf,
ALL_DEVICE_PROPERTY_KEYS,
@@ -146,50 +144,59 @@ describe('scanUntilMatch', () => {
});
});
describe('event-type validation', () => {
it('accepts known event types', () => {
describe('event-type filter', () => {
it('keeps isKnownEventType strict: built-in types only', () => {
expect(isKnownEventType('app_install_failed')).toBe(true);
expect(isKnownEventType('enrollment_failed')).toBe(true);
expect(() => assertKnownEventType('app_install_failed')).not.toThrow();
});
it('rejects an unknown event type with a helpful, suggestion-bearing error', () => {
expect(isKnownEventType('made_up_type')).toBe(false);
expect(() => assertKnownEventType('app_install_fialed')).toThrow(/event_types catalog/);
// "app_install_fialed" shares the "app" token → at least one suggestion surfaces.
expect(() => assertKnownEventType('app_install_fialed')).toThrow(/Did you mean/);
});
it('accepts the hybrid user-affinity types added to the catalog', () => {
expect(isKnownEventType('gather_result')).toBe(true);
for (const t of ['desktop_real_user_detected', 'desktop_excluded_user', 'ime_user_token_acquired', 'entra_user_affinity_pending', 'device_registration_event']) {
expect(isKnownEventType(t), t).toBe(true);
expect(() => assertKnownEventType(t)).not.toThrow();
}
});
it('lets gather-rule output types through the filter gate without cataloguing them', () => {
// Built-in and tenant-authored outputEventType values are rule data, never catalogued.
for (const t of ['gather_dsregcmd_status', 'gather_custom_anything']) {
expect(isGatherOutputEventType(t), t).toBe(true);
expect(isFilterableEventType(t), t).toBe(true);
expect(() => assertKnownEventType(t)).not.toThrow();
// The strict predicate stays strict: rule-validation uses it as "is a built-in type".
// Gather-rule output types are rule data, never catalogued — rule-validation relies on this.
for (const t of ['gather_dsregcmd_status', 'HPiA-UpdateStatus', 'made_up_type']) {
expect(isKnownEventType(t), t).toBe(false);
}
// Catalogued code-emitted gather_* lifecycle types are known AND filterable.
expect(isKnownEventType('gather_result')).toBe(true);
expect(isFilterableEventType('gather_result')).toBe(true);
});
it('requires a non-empty suffix after the gather_ prefix', () => {
expect(isGatherOutputEventType('gather_')).toBe(false);
expect(isFilterableEventType('gather_')).toBe(false);
expect(() => assertKnownEventType('gather_')).toThrow(/event_types catalog/);
it('passes a result for a built-in type through unchanged, even when empty', () => {
const empty = { success: true, count: 0, events: [] };
expect(withEventTypeNote(empty, 'app_install_failed', true)).toBe(empty);
});
it('still rejects a typo that only resembles the gather_ prefix', () => {
expect(isFilterableEventType('gathre_dsregcmd_status')).toBe(false);
expect(() => assertKnownEventType('gathre_dsregcmd_status')).toThrow(/Unknown eventType "gathre_dsregcmd_status" — it is not in the event_types catalog/);
it('passes events of a gather rule\'s own type through unchanged, whatever its spelling', () => {
// Regression anchor: "HPiA-UpdateStatus" was rejected because it is neither catalogued nor gather_-prefixed.
for (const t of ['HPiA-UpdateStatus', 'CustomNetworkStatus', 'gather_dsregcmd_status']) {
const page = { success: true, count: 1, events: [{ eventType: t }] };
expect(withEventTypeNote(page, t, true), t).toBe(page);
}
});
it('marks an exhausted empty result for an uncatalogued type and names close built-in types', () => {
const res = withEventTypeNote({ success: true, count: 0, events: [] }, 'app_install_fialed', true);
expect(res.eventTypeNote).toMatch(/"app_install_fialed" is not a built-in event type and no event of it was found/);
// "app_install_fialed" shares the "app" token → at least one suggestion surfaces.
expect(res.eventTypeNote).toMatch(/Closest built-in types: .*app_/);
});
it('leaves a page alone that is not the final answer yet', () => {
expect(withEventTypeNote({ count: 0, events: [], nextLink: '/x?continuation=t' }, 'custom', true).eventTypeNote).toBeUndefined();
expect(withEventTypeNote({ count: 0, events: [], moreToScan: true }, 'custom', true).eventTypeNote).toBeUndefined();
});
it('stays silent when the type was not the only filter of a first call', () => {
// Another filter (severity, source, time) or an earlier page of the sweep may explain the
// emptiness — blaming the type would steer the reader towards a typo that is not there.
expect(withEventTypeNote({ count: 0, events: [] }, 'HPiA-UpdateStatus', false).eventTypeNote).toBeUndefined();
});
it('recognises the sessions[] shape of search_sessions_by_event', () => {
expect(withEventTypeNote({ success: true, count: 0, sessions: [] }, 'HPiA-UpdateStatus', true).eventTypeNote)
.toMatch(/not a built-in event type/);
});
it('does nothing without an eventType filter', () => {
const empty = { count: 0, events: [] };
expect(withEventTypeNote(empty, undefined, true)).toBe(empty);
});
});
@@ -0,0 +1,101 @@
/**
* eventType filters accept a gather rule's own output type. Regression anchor: get_session_events
* rejected "HPiA-UpdateStatus" — a tenant rule's outputEventType — because it is neither catalogued
* nor gather_-prefixed, so the rule's events could not be filtered at all. An empty result for an
* uncatalogued type is marked instead of rejected up front.
*
* Pure unit tests: fetch is stubbed and the registered tool handlers are invoked directly.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { McpServer } from '@modelcontextprotocol/server';
import { registerTools } from '../tools.js';
import { runWithCaller } from '../client.js';
type ToolHandler = (args: Record<string, unknown>, extra: unknown) => Promise<{
content?: Array<{ type: string; text?: string }>;
isError?: boolean;
}>;
const SESSION = 'e259c121-1234-4abc-9def-0123456789ab';
const GA = { token: 'ga', isGlobalAdmin: true };
const extra = { signal: new AbortController().signal };
function handlerFor(name: string): ToolHandler {
const server = new McpServer({ name: 'test', version: '0.0.0' });
registerTools(server, undefined, undefined, undefined, true, true, false);
const registry = (server as unknown as { _registeredTools: Record<string, { handler: ToolHandler }> })._registeredTools;
const tool = registry[name];
if (!tool) throw new Error(`tool ${name} not registered`);
return tool.handler;
}
function stubFetch(body: Record<string, unknown>): { urls: string[] } {
const urls: string[] = [];
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
urls.push(decodeURIComponent(String(url)));
return { ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) } as unknown as Response;
}));
return { urls };
}
function resultJson(r: { content?: Array<{ text?: string }> }): Record<string, unknown> {
return JSON.parse((r.content ?? []).map((c) => c.text ?? '').join('')) as Record<string, unknown>;
}
afterEach(() => vi.unstubAllGlobals());
describe('eventType filter with a gather rule\'s own output type', () => {
it('get_session_events filters by the custom type and returns its events unmarked', async () => {
const { urls } = stubFetch({ success: true, count: 1, events: [{ eventType: 'HPiA-UpdateStatus', sequence: 69 }] });
const result = await runWithCaller(GA, () => handlerFor('get_session_events')({ sessionId: SESSION, eventType: 'HPiA-UpdateStatus' }, extra));
expect(result.isError).toBeFalsy();
expect(urls[0]).toContain('eventType=HPiA-UpdateStatus');
const body = resultJson(result);
expect(body.count).toBe(1);
expect(body).not.toHaveProperty('eventTypeNote');
});
it('an empty result for an uncatalogued type carries the note instead of passing as "nothing happened"', async () => {
stubFetch({ success: true, count: 0, events: [] });
const result = await runWithCaller(GA, () => handlerFor('get_session_events')({ sessionId: SESSION, eventType: 'app_install_fialed' }, extra));
expect(result.isError).toBeFalsy();
expect(String(resultJson(result).eventTypeNote)).toMatch(/"app_install_fialed" is not a built-in event type.*Closest built-in types/);
});
it('no note when severity, not the type, may have emptied the result, or on a continued sweep', async () => {
stubFetch({ success: true, count: 0, events: [] });
const filtered = await runWithCaller(GA, () => handlerFor('get_session_events')(
{ sessionId: SESSION, eventType: 'HPiA-UpdateStatus', severity: 'Error' }, extra));
expect(resultJson(filtered)).not.toHaveProperty('eventTypeNote');
const continued = await runWithCaller(GA, () => handlerFor('search_sessions_by_event')(
{ eventType: 'HPiA-UpdateStatus', continuation: '/api/global/search/sessions-by-event?eventType=HPiA-UpdateStatus&continuation=tok' }, extra));
expect(resultJson(continued)).not.toHaveProperty('eventTypeNote');
});
it('a built-in type keeps a plain empty result', async () => {
stubFetch({ success: true, count: 0, events: [] });
const result = await runWithCaller(GA, () => handlerFor('get_session_events')({ sessionId: SESSION, eventType: 'app_install_failed' }, extra));
expect(resultJson(result)).not.toHaveProperty('eventTypeNote');
});
it('search_sessions_by_event and query_raw_events accept the custom type too', async () => {
stubFetch({ success: true, count: 0, sessions: [] });
const bySession = await runWithCaller(GA, () => handlerFor('search_sessions_by_event')({ eventType: 'CustomNetworkStatus' }, extra));
expect(bySession.isError).toBeFalsy();
expect(String(resultJson(bySession).eventTypeNote)).toMatch(/not a built-in event type/);
const { urls } = stubFetch({ success: true, count: 1, events: [{ EventType: 'CustomNetworkStatus' }] });
const raw = await runWithCaller(GA, () => handlerFor('query_raw_events')({ eventType: 'CustomNetworkStatus' }, extra));
expect(raw.isError).toBeFalsy();
expect(urls[0]).toContain('eventType=CustomNetworkStatus');
expect(resultJson(raw)).not.toHaveProperty('eventTypeNote');
});
});
@@ -1,5 +1,45 @@
import { describe, it, expect } from 'vitest';
import { interpolateRuleTemplate, interpolateAnalysisResults } from '../interpolate-rule-template.js';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
interpolateRuleTemplate,
interpolateAnalysisResults,
RULE_TEMPLATE_AUTO_FIELDS,
} from '../interpolate-rule-template.js';
interface SharedCase {
name: string;
template: string | null;
matchedConditions: Record<string, unknown> | null;
expected: string;
}
/** tests/fixtures/rule-template-interpolation at the repo root — the cases every renderer runs. */
function loadSharedCases(): { autoFields: string[]; cases: SharedCase[] } {
let dir = dirname(fileURLToPath(import.meta.url));
while (!existsSync(join(dir, 'AutopilotMonitor.sln'))) {
const parent = dirname(dir);
if (parent === dir) throw new Error('repository root (AutopilotMonitor.sln) not found');
dir = parent;
}
return JSON.parse(
readFileSync(join(dir, 'tests', 'fixtures', 'rule-template-interpolation', 'cases.json'), 'utf8'),
);
}
describe('interpolateRuleTemplate — shared cases (web = MCP = backend)', () => {
const shared = loadSharedCases();
it('has cases and the same auto-field list as the rule engine', () => {
expect(shared.cases.length).toBeGreaterThanOrEqual(20);
expect([...RULE_TEMPLATE_AUTO_FIELDS]).toEqual(shared.autoFields);
});
it.each(shared.cases.map((c) => [c.name, c] as const))('%s', (_name, c) => {
expect(interpolateRuleTemplate(c.template, c.matchedConditions)).toBe(c.expected);
});
});
describe('interpolateRuleTemplate', () => {
// Shape of a real ANALYZE-ENRL-001 matchedConditions map (the case from the
@@ -680,7 +680,7 @@ const defaultPageFetcher: PageFetcher = (path) => apiFetch<Record<string, unknow
const ITEM_ARRAY_KEYS = ['events', 'sessions', 'items', 'results'] as const;
/** Find the first array-valued envelope field — the page's item list. */
function extractItems(page: Record<string, unknown>): unknown[] | undefined {
export function extractItems(page: Record<string, unknown>): unknown[] | undefined {
for (const key of ITEM_ARRAY_KEYS) {
const v = page[key];
if (Array.isArray(v)) return v;
@@ -1247,10 +1247,21 @@ export interface CveExposureSummary {
/** Distinct affected tenants; null (key omitted) on tenant-scoped reads. */
totalAffectedTenants?: number;
distinctCves: number;
/** Distinct affected products, grouped as in TopSoftware, with at least one CVE in the window. */
distinctSoftware: number;
kevCves: number;
/** Distinct affected sessions that carry at least one CISA KEV (known-exploited) CVE. */
kevAffectedSessions: number;
severityBreakdown: SeverityBreakdown;
priorityBreakdown: PriorityBreakdown;
/** The topN CVEs by affected sessions, plus the KEV CVEs that rank below them (at most 25 extra), all ordered by affected sessions. The list can therefore be longer than topN. */
topCves: TopCve[];
/** The top min(topN, 20) products by affected sessions, plus the products with a KEV CVE that rank below them (at most 10 extra), ordered by affected sessions. */
topSoftware: TopSoftware[];
/** For list filters: per CVSS severity band and per priority band, the band's top CVEs by affected sessions that TopCves does not already hold (at most perBand per band). Only on request (perBand above 0, which the portal sends); null (key omitted) otherwise. */
bandCves?: TopCve[];
/** The same for products, banded by their most severe CVE and their highest priority, minus the entries of TopSoftware. Only on request; null (key omitted) otherwise. */
bandSoftware?: TopSoftware[];
truncated: boolean;
}
@@ -4477,6 +4488,17 @@ export interface SleepSpan {
kind: string;
}
/** One CVE of a TopSoftware entry; AffectedSessions counts that product's sessions only. */
export interface SoftwareCve {
cveId: string;
cvssSeverity: string;
cvssScore: number;
isKev: boolean;
epssScore?: number;
priority: string;
affectedSessions: number;
}
/** Shared response of GET vulnerability/software-inventory (Global Admin, ?tenantId=) and GET metrics/software-inventory (caller's own tenant): the raw SoftwareInventory rows plus matched/unmatched counts. Consumed by the MCP get_software_inventory tool — key names are part of that contract. */
export interface SoftwareInventoryResponse {
success: boolean;
@@ -5214,6 +5236,26 @@ export interface TopFailingApp {
successRate: number;
}
/** One affected product: every CveIndex row of the product folded together. Severity, score and priority are the worst values across its CVEs; AffectedSessions counts distinct sessions. */
export interface TopSoftware {
/** Grouping key: the CPE "vendor:product" the correlation matched (e.g. "7-zip:7-zip"). A row written before the index carried it borrows the product of another row with the same title; failing that, its raw title is the key. */
product: string;
/** Display name derived from the detected titles (shared leading words, or the most common title without its version and architecture). */
name: string;
affectedSessions: number;
cveCount: number;
kevCount: number;
/** Highest CVSS severity band across the product's CVEs. */
cvssSeverity: string;
cvssScore: number;
/** Highest act/attend/track band across the product's CVEs (empty when only legacy rows carry it). */
priority: string;
/** Raw display names the product was detected under, most sessions first (at most 3). */
titles: string[];
/** The product's most urgent CVEs (priority, then EPSS, then CVSS), at most 3; CveCount is the full count. */
cves: SoftwareCve[];
}
/** One serial-number bucket in the GetTpmPssUnsupported aggregation. All values are self-reported by devices through the unauthenticated distress channel — UNVERIFIED. */
export interface TpmPssUnsupportedItem {
serialNumber: string;
@@ -8,15 +8,33 @@
* Keep the resolution order in lock-step with the web copy:
* 1. matchedConditions entry whose `field` equals `token`.
* 2. matchedConditions entry carrying a whitelisted same-event auto-field
* named `token` (backend `AddDataFieldsToEvidence`: appId, appName,
* errorPatternId, errorCode, exitCode, status). First non-empty wins so the
* named `token` (`RULE_TEMPLATE_AUTO_FIELDS`). First non-empty wins so the
* value pins to the rule's required-condition event.
* 3. matchedConditions entry whose key (signal name) equals `token`.
* 4. Unresolved tokens are left untouched so authors notice the typo (and the
* reworded ANALYZE-ENRL-001 footnote explains a genuinely-absent field).
*
* Token chars: [a-zA-Z0-9_]. Whitespace inside the braces is tolerated.
*
* Web, MCP and the backend (notifications) all run the cases in
* `tests/fixtures/rule-template-interpolation/cases.json` at the repo root.
*/
/**
* Mirror of the backend evidence auto-capture whitelist (`RuleEngine.EvidenceAutoFields`).
* Explicit list keeps a rogue evidence key (e.g. accidental `description`) from shadowing
* a token. Also the list validate_rule lints tokens against.
*/
export const RULE_TEMPLATE_AUTO_FIELDS = [
'appId',
'appName',
'errorPatternId',
'errorCode',
'exitCode',
'status',
'timeoutHours',
] as const;
export function interpolateRuleTemplate(
text: string | null | undefined,
matchedConditions: Record<string, unknown> | null | undefined
@@ -28,10 +46,6 @@ export function interpolateRuleTemplate(
const byAutoField = new Map<string, string>();
const bySignal = new Map<string, string>();
// Mirror of the backend AddDataFieldsToEvidence whitelist. Explicit list keeps a
// rogue evidence key (e.g. accidental `description`) from shadowing a token.
const AUTO_FIELDS = ['appId', 'appName', 'errorPatternId', 'errorCode', 'exitCode', 'status'];
for (const [signal, evidence] of Object.entries(matchedConditions)) {
if (!evidence || typeof evidence !== 'object') {
if (evidence != null) bySignal.set(signal, formatValue(evidence));
@@ -44,7 +58,7 @@ export function interpolateRuleTemplate(
if ('value' in e) {
bySignal.set(signal, formatValue(e.value));
}
for (const af of AUTO_FIELDS) {
for (const af of RULE_TEMPLATE_AUTO_FIELDS) {
if (byAutoField.has(af)) continue;
const v = e[af];
if (v != null && v !== '') byAutoField.set(af, formatValue(v));
@@ -4,6 +4,7 @@
* (MCP-protocol resources) and the `get_resource` tool (workaround for
* stateless-HTTP MCP clients whose resource discovery is broken).
*/
import { extractItems } from './client.js';
import { DIAG_ZIP_MAP } from './diag-zip-map.js';
import { RULE_AUTHORING_GUIDE } from './rule-authoring-guide.js';
import { GATHER_RULE_SCHEMA, ANALYZE_RULE_SCHEMA, RULE_GUARDRAILS } from './rule-authoring.generated.js';
@@ -19,7 +20,7 @@ import {
// (all catalog values ∪ INTERNAL_EVENT_TYPES) === the C# const values. When the
// agent adds a new event type to Constants.EventTypes, add it to a group here too.
// Gather-rule output types ("gather_dsregcmd_status", ...) are rule data, not code-emitted
// types, and stay OUT of the catalog on purpose — see isGatherOutputEventType below.
// types, and stay OUT of the catalog on purpose — see withEventTypeNote below.
export const EVENT_TYPES_CATALOG = {
phase_events: [
'phase_transition',
@@ -357,38 +358,20 @@ export const DEVICE_PROPERTIES_CATALOG = {
//
// Without these, an invalid eventType / deviceProperties key produces the SAME
// `count: 0` as a genuine miss, so "bad filter" is indistinguishable from "no
// matches". The search tools call these to reject a typo with a clear, correctable
// error instead of a silent empty result.
// matches". The tools reject a deviceProperties typo with a clear error and mark an
// empty result for an uncatalogued eventType with a correctable note.
/** Set form of ALL_EVENT_TYPES for O(1) membership checks. */
const EVENT_TYPE_SET = new Set<string>(ALL_EVENT_TYPES);
/** True if `s` is a known event type (public catalog ∪ internal). */
/**
* True if `s` is a built-in event type (public catalog ∪ internal). Strict on purpose:
* rule-validation relies on it for its outputEventType collision check.
*/
export function isKnownEventType(s: string): boolean {
return EVENT_TYPE_SET.has(s);
}
/**
* Gather-rule output types (`outputEventType`, e.g. "gather_dsregcmd_status") are rule
* DATA — built-in and tenant-authored — not code-emitted types, so they are deliberately
* NOT catalogued: D-072 scopes the catalog to `Constants.EventTypes`, and the C# guard
* test excludes gather outputs for the same reason. They are real events on the wire
* nonetheless, so the filter gate lets any `gather_`-prefixed type (with a non-empty
* suffix) through — the same "a valid prefix passes even when the full key is
* uncatalogued" stance as assertKnownDevicePropertyKeys. Kept apart from
* isKnownEventType, whose strict "is a built-in type" meaning rule-validation relies
* on for its outputEventType collision check.
*/
const GATHER_OUTPUT_PREFIX = 'gather_';
export function isGatherOutputEventType(s: string): boolean {
return s.startsWith(GATHER_OUTPUT_PREFIX) && s.length > GATHER_OUTPUT_PREFIX.length;
}
/** True if `s` is accepted as an eventType filter: catalogued, internal, or a gather-rule output. */
export function isFilterableEventType(s: string): boolean {
return isKnownEventType(s) || isGatherOutputEventType(s);
}
/**
* Every catalogued deviceProperties key, flattened across event-type groups
* (excluding the `_usage` doc block). This is a CURATED subset — not exhaustive —
@@ -415,19 +398,35 @@ function suggestEventTypes(input: string): string[] {
}
/**
* Throws a descriptive Error if `eventType` is neither a known type nor a
* gather-rule output (see isFilterableEventType). The thrown message routes
* through the tools' `toolError` handler so the model gets an actionable
* correction instead of a misleading empty result.
* eventType filters take ANY type and pass it on as given. Gather-rule output types
* (`outputEventType`, e.g. "gather_dsregcmd_status", "HPiA-UpdateStatus") are rule DATA — built-in
* and tenant-authored — so they are deliberately NOT catalogued (D-072), yet they are real events
* on the wire, and the portal suggests free names like "CustomNetworkStatus". A gate on the catalog
* (or on a naming prefix) locked those out. What the gate protected — a typo must not read as
* "nothing happened" — this note keeps: when the uncatalogued type was the only filter of a first
* call and the answer is an exhausted empty result, it says so and names the closest built-in
* types. With other filters or on a continued sweep the emptiness proves nothing about the type,
* and non-empty or still-continuable pages pass unchanged.
*/
export function assertKnownEventType(eventType: string): void {
if (isFilterableEventType(eventType)) return;
export function withEventTypeNote<T extends object>(
data: T,
eventType: string | undefined,
soleFilterOfFirstCall: boolean,
): T & { eventTypeNote?: string } {
const page = data as Record<string, unknown>;
if (!eventType || !soleFilterOfFirstCall || isKnownEventType(eventType) || page.nextLink || page.moreToScan) return data;
const items = extractItems(page);
const empty = typeof page.count === 'number' ? page.count === 0 : items !== undefined && items.length === 0;
if (!empty) return data;
const suggestions = suggestEventTypes(eventType);
const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(', ')}?` : '';
throw new Error(
`Unknown eventType "${eventType}" — it is not in the event_types catalog.${hint} ` +
'Call get_resource(name="event_types") for the full list of valid event types.',
);
const hint = suggestions.length > 0 ? ` Closest built-in types: ${suggestions.join(', ')}.` : '';
return {
...data,
eventTypeNote:
`"${eventType}" is not a built-in event type and no event of it was found here. Gather rules emit their own ` +
`output types (outputEventType) — check the spelling against the rule.${hint} ` +
'Built-in types: get_resource(name="event_types").',
};
}
/**
@@ -250,7 +250,7 @@ export const RULE_AUTHORING_GUIDE = {
'explanation and remediation text may contain {{token}} placeholders, resolved from the ' +
'matched evidence at display time: first a matched condition whose dataField equals the ' +
'token, then the auto-captured fields appId / appName / errorPatternId / errorCode / ' +
'exitCode / status from the matched events, then a condition SIGNAL name. Unresolved tokens ' +
'exitCode / status / timeoutHours from the matched events, then a condition SIGNAL name. Unresolved tokens ' +
'stay visible as {{token}} so typos are noticeable. test_analyze_rule returns the ' +
'interpolated preview for a real session.',
markSessionAsFailed:
@@ -27,6 +27,7 @@ import addFormatsModule from 'ajv-formats';
const addFormats = addFormatsModule as unknown as (ajv: Ajv2020) => void;
import { GATHER_RULE_SCHEMA, ANALYZE_RULE_SCHEMA, RULE_GUARDRAILS } from './rule-authoring.generated.js';
import { isKnownEventType } from './resource-catalog.js';
import { RULE_TEMPLATE_AUTO_FIELDS } from './interpolate-rule-template.js';
export type FindingLevel = 'error' | 'warning' | 'info';
@@ -274,9 +275,8 @@ function checkGatherTarget(collectorType: string, target: string): ValidationFin
// ── Analyze-rule semantic lint ──────────────────────────────────────────────
/** Mirrors the backend evidence auto-capture whitelist (AddDataFieldsToEvidence) and
* the interpolation resolution order (interpolate-rule-template.ts). */
const AUTO_FIELDS = ['appId', 'appName', 'errorPatternId', 'errorCode', 'exitCode', 'status'];
/** The auto-captured fields a token may resolve to — the interpolator's own list. */
const AUTO_FIELDS = RULE_TEMPLATE_AUTO_FIELDS;
/** The only condition strings EvaluateConfidenceFactor parses — anything else is
* silently false in production. Exact spacing matters. */
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/server';
import { z } from 'zod';
import { apiFetch, buildQuery, DEFAULT_FIRST_PAGE_SIZE, effectivePageSize, enforceDelegatedTenant, enforceDelegatedTenantForPage, followNextLink, getCallerUpnDomain, getDelegatedTenantIds, getHomeTenantId, pageSizeForCall, pickGlobalOrTenantPath, scanUntilMatch, scanWithTimeoutFallback, jsonBody } from '../client.js';
import { withToolTelemetry } from '../telemetry.js';
import { getResourceContent, assertKnownEventType, RESOURCE_NAMES } from '../resource-catalog.js';
import { getResourceContent, withEventTypeNote, RESOURCE_NAMES } from '../resource-catalog.js';
import { READ_ONLY, READ_ONLY_OPEN, MUTATING, MAX_RESULT_SIZE_CHARS, LEAN_RAW_EVENT_FIELDS, LEAN_RAW_EVENT_OMISSION, leanFieldSelection, toolResultText, SessionIdSchema, TenantGuidSchema, tenantIdDescription, pageSizeDescription, CONTINUATION_DESCRIPTION, daysDescription } from './shared.js';
import { toolError } from './error-handler.js';
import { API_BASE_URL } from '../config.js';
@@ -1473,8 +1473,9 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
'PartitionKey/RowKey/Timestamp. Deliberately unenriched: DataJson is the raw stored string (not parsed), ' +
'Severity/Phase are raw ints, no decoded error meanings; for the enriched stream use get_session_events or ' +
'search_events. Use it when search_events does not cover the time range or session scope, or for exact ' +
'event-type filtering across many sessions. eventType is validated against the event_types catalog (a typo ' +
'is rejected, not an empty result). With a filter the tool auto-scans past empty pages: "count": 0 without ' +
'event-type filtering across many sessions. eventType may also be a gather rule\'s own outputEventType; an empty ' +
'first-page result for a type outside the event_types catalog carries eventTypeNote with the closest built-in ' +
'types. With a filter the tool auto-scans past empty pages: "count": 0 without ' +
'nextLink means no matches; "moreToScan": true means the per-call scan budget was hit — continue with nextLink. ' +
'pageSize is the index-scan cadence (one indexed session can contribute several events, so a page may hold ' +
'more than pageSize). A page that ends early carries "partial": true — nothing is missing up to its nextLink. ' +
@@ -1513,7 +1514,6 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
// Default projection follows intent — see leanFieldSelection (DataJson is the raw payload column).
const { fields, leanDefaultApplied } = leanFieldSelection(explicitFields, continuation, targeted, LEAN_RAW_EVENT_FIELDS);
const tenantId = enforceDelegatedTenantForPage(rawTenantId, continuation);
if (eventType) assertKnownEventType(eventType);
const basePath = pickGlobalOrTenantPath('/api/global/raw/events', '/api/raw/events', tenantId);
const path = followNextLink(
basePath,
@@ -1526,7 +1526,11 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
// forward so the model isn't misled by an empty-but-continuable page. The server
// bounds each page by its own scan budget; should a call still time out, retry once
// with a halved pageSize on the same cursor instead of failing identically twice.
const data = await scanWithTimeoutFallback(path, basePath, effectivePageSize(pageSize, continuation));
const data = withEventTypeNote(
await scanWithTimeoutFallback(path, basePath, effectivePageSize(pageSize, continuation)),
eventType,
!continuation && !severity && !source && !startedAfter && !startedBefore,
);
// Announce the omission in-band so a reader of the result knows DataJson exists and how to get it.
return toolResultText(leanDefaultApplied ? { ...data, ...LEAN_RAW_EVENT_OMISSION } : data, MAX_RESULT_SIZE_CHARS.events);
} catch (error: unknown) {
@@ -1967,15 +1971,17 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
title: 'Vulnerability Summary',
description:
'Get a fleet-wide vulnerability exposure summary aggregated from detected CVEs: total affected devices, ' +
'distinct CVE count, KEV (CISA Known-Exploited) count, a severity breakdown, a priority breakdown ' +
'(act/attend/track counts over every CVE in the window), and the top CVEs ranked by how ' +
'many devices they affect. Each top CVE carries cvssScore/cvssSeverity, isKev, epssScore (FIRST EPSS ' +
'distinct CVE and product counts, KEV (CISA Known-Exploited) count and the devices carrying one, a severity breakdown, ' +
'a priority breakdown (act/attend/track counts over every CVE in the window), the top CVEs ranked by how ' +
'many devices they affect (every KEV CVE is added even below topN), and topSoftware: the most exposed products ' +
'(grouped by CPE vendor:product, KEV products always added) with devices, CVE and KEV counts, worst severity and ' +
'priority, and their most urgent CVEs. Each CVE carries cvssScore/cvssSeverity, isKev, epssScore (FIRST EPSS ' +
'probability of exploitation within 30 days, 0-1, null when unscored) and priority ("act" = in CISA KEV, ' +
'"attend" = EPSS >= 0.1 or CVSS >= 9.0, "track" = everything else) — rank remediation by priority, then EPSS, ' +
'not by CVSS alone. ' +
(ga ? 'The cross-tenant overview also returns the affected tenant count. ' : '') +
'Use this to answer "how exposed is the fleet / this ' +
'tenant?" and "which CVEs affect the most devices?" — for the device list of a single CVE use search_sessions_by_cve. ' +
'tenant?", "which CVEs affect the most devices?" and "which software to update first?" — for the device list of a single CVE use search_sessions_by_cve. ' +
'If "truncated" is true, the underlying index scan hit its cap and counts are a lower bound (narrow with tenantId). ' +
'Requires vulnerability scanning to be enabled (an empty summary means no findings, not necessarily "not affected").',
inputSchema: {
@@ -1983,7 +1989,7 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
days: z.coerce.number().int().min(1).max(365).optional().default(30)
.describe(daysDescription(30, 365, 'Filters CVEs by detection time.')),
topN: z.coerce.number().int().min(1).max(100).optional().default(20)
.describe('How many top CVEs to return, ranked by affected device count (1-100, default 20).'),
.describe('How many top CVEs to return, ranked by affected device count (1-100, default 20); also sizes topSoftware (at most 20).'),
},
annotations: READ_ONLY,
},
@@ -5,7 +5,7 @@ import { withToolTelemetry } from '../telemetry.js';
import { READ_ONLY, MAX_RESULT_SIZE_CHARS, LEAN_EVENT_FIELDS, LEAN_EVENT_OMISSION, leanFieldSelection, SUMMARY_EVENT_FIELDS, toolResultText, SessionIdSchema, isBenignHealthDetectionReport, tenantIdDescription, pageSizeDescription, CONTINUATION_DESCRIPTION, daysDescription } from './shared.js';
import { toolError } from './error-handler.js';
import { lookupErrorCode } from '../error-code-catalog.js';
import { assertKnownEventType, assertKnownDevicePropertyKeys } from '../resource-catalog.js';
import { withEventTypeNote, assertKnownDevicePropertyKeys } from '../resource-catalog.js';
import { interpolateAnalysisResults } from '../interpolate-rule-template.js';
import { buildSessionCoverage } from '../session-coverage.js';
import { API_BASE_URL } from '../config.js';
@@ -220,10 +220,10 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
title: 'Search Sessions by Event',
description:
'Find sessions that contain a given event type, read from the event-type index (e.g. every session with ' +
'app_install_failed or enrollment_failed). eventType is validated against the event_types catalog; an unknown ' +
'type is rejected, not an empty result.',
'app_install_failed or enrollment_failed). eventType may also be a gather rule\'s own outputEventType; an empty ' +
'first-page result for a type outside the event_types catalog carries eventTypeNote with the closest built-in types.',
inputSchema: {
eventType: z.string().describe('Event type string from get_resource(name="event_types") (e.g. "app_install_failed", "enrollment_failed")'),
eventType: z.string().describe('Event type from get_resource(name="event_types") (e.g. "app_install_failed", "enrollment_failed"), or a gather rule\'s own outputEventType'),
tenantId: z.string().optional().describe(tenantIdDescription(ga, delegated)),
pageSize: z.coerce.number().int().min(1).max(1000).optional()
.describe(pageSizeDescription(DEFAULT_FIRST_PAGE_SIZE, 1000, 'Raise it for full sweeps.')),
@@ -237,9 +237,8 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
const pageSize = pageSizeForCall(args.pageSize, continuation, DEFAULT_FIRST_PAGE_SIZE);
const tenantId = enforceDelegatedTenantForPage(rawTenantId, continuation);
// eventType is the sole filter and is applied server-side (EventTypeIndex OData),
// so an empty page never carries a nextLink — no auto-exhaust needed. But validate
// the type so a typo is a clear error rather than a silent empty result.
assertKnownEventType(eventType);
// so an empty page never carries a nextLink — no auto-exhaust needed. An empty result
// for an uncatalogued type says so, so a typo does not read as "no such sessions".
const basePath = pickGlobalOrTenantPath('/api/global/search/sessions-by-event', '/api/search/sessions-by-event', tenantId);
const path = followNextLink(
basePath,
@@ -248,7 +247,7 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
{ pageSize },
);
const data = await apiFetch<SessionListResponse>(path);
return toolResultText(data, MAX_RESULT_SIZE_CHARS.indexSessions);
return toolResultText(withEventTypeNote(data, eventType, !continuation), MAX_RESULT_SIZE_CHARS.indexSessions);
} catch (error: unknown) {
return toolError('search_sessions_by_event', args, error);
}
@@ -393,8 +392,8 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
title: 'Get Session Events',
description:
'RAW EVENT RETRIEVAL (fallback when ranked search_events misses, or when every event of one session is needed ' +
'in chronological sequence). Filter by eventType (validated against the event_types catalog; an unknown type is ' +
'rejected, not an empty result), severity or source (app name). An unfiltered read omits the per-event "data" ' +
'in chronological sequence). Filter by eventType (built-in, or a gather rule\'s own outputEventType; an empty first-page ' +
'result for a type outside the event_types catalog carries eventTypeNote), severity or source (app name). An unfiltered read omits the per-event "data" ' +
'payload by default and says so in omittedFields; a filtered read includes it (see fields). ' +
'Filters are applied after the partition read, so the tool scans forward past empty pages: "count": 0 without ' +
'nextLink means no matching events; "moreToScan": true means the per-call scan budget was hit — pass the ' +
@@ -402,7 +401,7 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
inputSchema: {
sessionId: SessionIdSchema.describe('Session UUID'),
tenantId: z.string().optional().describe(sessionTenantIdDescription),
eventType: z.string().optional().describe('Only events of this type; values from get_resource(name="event_types")'),
eventType: z.string().optional().describe('Only events of this type: a value from get_resource(name="event_types"), or a gather rule\'s own outputEventType'),
severity: z.enum(EVENT_SEVERITIES).optional(),
source: z.string().optional().describe('Filter by event source/app name (e.g. "MicrosoftTeams")'),
fields: z.string().optional()
@@ -420,7 +419,6 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
// Default projection follows intent — see leanFieldSelection.
const { fields, leanDefaultApplied } = leanFieldSelection(explicitFields, continuation, Boolean(eventType || severity || source), LEAN_EVENT_FIELDS);
const tenantId = enforceDelegatedTenantForPage(rawTenantId, continuation);
if (eventType) assertKnownEventType(eventType);
const basePath = `/api/sessions/${sessionId}/events`;
const path = followNextLink(
basePath,
@@ -432,7 +430,11 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
// event partition, so a page can be empty while matches sit on a later page.
// Auto-exhaust forward so the model isn't misled by an empty-but-continuable page;
// a timeout is retried once with a halved pageSize on the same cursor.
const data = await scanWithTimeoutFallback(path, basePath, effectivePageSize(pageSize, continuation));
const data = withEventTypeNote(
await scanWithTimeoutFallback(path, basePath, effectivePageSize(pageSize, continuation)),
eventType,
!continuation && !severity && !source,
);
// Announce the omission in-band so a reader of the result knows the payload exists and how to get it.
return toolResultText(leanDefaultApplied ? { ...data, ...LEAN_EVENT_OMISSION } : data, MAX_RESULT_SIZE_CHARS.events);
} catch (error: unknown) {
@@ -807,7 +809,7 @@ export function registerSessionTools(server: McpServer, ga: boolean, delegated:
'are EXPECTED (>= expectedHitRate on the baseline); and the open drift alerts (an expected pattern that ' +
'matched in none of >= minCandidateSessions sessions on a newer version — Microsoft probably changed the log ' +
'wording). On an alert: search_sessions with imeAgentVersion=<version> -> get_session_diagnostics on a session ' +
'with a package -> validate the pattern against the real IME log -> compare with the IME decompile -> fix it ' +
'with a package -> validate the pattern against the real IME log -> fix it ' +
'in rules/ime-log-patterns. Only sessions that reached a terminal run report a histogram (crashes/kills are ' +
'excluded from the denominator). catalog says where the shipped-pattern list comes from (the last GitHub ' +
'reseed or the deployed backend build) and when it was written.',
@@ -7,7 +7,7 @@ namespace AutopilotMonitor.Shared.Models
/// <c>EventIngestProcessor</c> when an <c>ime_agent_version</c> event carries a version
/// the platform has never seen before (RecordImeVersionAsync insert succeeded). The
/// worker downloads the IME installer and archives it into the <c>ime-archive</c> blob
/// container so every fleet-observed IME build stays available for later decompilation
/// container so every fleet-observed IME build stays available for later analysis
/// and build-to-build diffing, even after Microsoft's versionless CDN URL has moved on.
/// </summary>
public sealed class ImeMsiArchiveEnvelope
@@ -14,6 +14,8 @@ namespace AutopilotMonitor.Shared.Models.Vulnerability
public string CveId { get; set; } = string.Empty;
public string SessionId { get; set; } = string.Empty;
public string SoftwareName { get; set; } = string.Empty;
/// <summary>CPE "vendor:product" the correlation matched; empty on legacy rows and findings without a CPE.</summary>
public string Product { get; set; } = string.Empty;
public double CvssScore { get; set; }
public string CvssSeverity { get; set; } = string.Empty;
public bool IsKev { get; set; }
@@ -334,10 +334,43 @@ namespace AutopilotMonitor.Shared.Models
public int? TotalAffectedTenants { get; set; }
public int DistinctCves { get; set; }
/// <summary>Distinct affected products, grouped as in <see cref="TopSoftware"/>, with at least one CVE in the window.</summary>
public int DistinctSoftware { get; set; }
public int KevCves { get; set; }
/// <summary>Distinct affected sessions that carry at least one CISA KEV (known-exploited) CVE.</summary>
public int KevAffectedSessions { get; set; }
public SeverityBreakdown SeverityBreakdown { get; set; } = default!;
public PriorityBreakdown PriorityBreakdown { get; set; } = default!;
/// <summary>
/// The topN CVEs by affected sessions, plus the KEV CVEs that rank below them (at most 25
/// extra), all ordered by affected sessions. The list can therefore be longer than topN.
/// </summary>
public IReadOnlyList<TopCve> TopCves { get; set; } = default!;
/// <summary>
/// The top min(topN, 20) products by affected sessions, plus the products with a KEV CVE
/// that rank below them (at most 10 extra), ordered by affected sessions.
/// </summary>
public IReadOnlyList<TopSoftware> TopSoftware { get; set; } = default!;
/// <summary>
/// For list filters: per CVSS severity band and per priority band, the band's top CVEs by
/// affected sessions that <see cref="TopCves"/> does not already hold (at most perBand per
/// band). Only on request (perBand above 0, which the portal sends); null (key omitted) otherwise.
/// </summary>
public IReadOnlyList<TopCve>? BandCves { get; set; }
/// <summary>
/// The same for products, banded by their most severe CVE and their highest priority, minus
/// the entries of <see cref="TopSoftware"/>. Only on request; null (key omitted) otherwise.
/// </summary>
public IReadOnlyList<TopSoftware>? BandSoftware { get; set; }
public bool Truncated { get; set; }
}
@@ -383,6 +416,56 @@ namespace AutopilotMonitor.Shared.Models
public IReadOnlyList<string> SampleSoftware { get; set; } = default!;
}
/// <summary>
/// One affected product: every CveIndex row of the product folded together. Severity, score
/// and priority are the worst values across its CVEs; <see cref="AffectedSessions"/> counts
/// distinct sessions.
/// </summary>
// Declaration order == wire order.
public class TopSoftware
{
/// <summary>
/// Grouping key: the CPE "vendor:product" the correlation matched (e.g. "7-zip:7-zip").
/// A row written before the index carried it borrows the product of another row with the
/// same title; failing that, its raw title is the key.
/// </summary>
public string Product { get; set; } = default!;
/// <summary>Display name derived from the detected titles (shared leading words, or the most common title without its version and architecture).</summary>
public string Name { get; set; } = default!;
public int AffectedSessions { get; set; }
public int CveCount { get; set; }
public int KevCount { get; set; }
/// <summary>Highest CVSS severity band across the product's CVEs.</summary>
public string CvssSeverity { get; set; } = default!;
public double CvssScore { get; set; }
/// <summary>Highest act/attend/track band across the product's CVEs (empty when only legacy rows carry it).</summary>
public string Priority { get; set; } = default!;
/// <summary>Raw display names the product was detected under, most sessions first (at most 3).</summary>
public IReadOnlyList<string> Titles { get; set; } = default!;
/// <summary>The product's most urgent CVEs (priority, then EPSS, then CVSS), at most 3; <see cref="CveCount"/> is the full count.</summary>
public IReadOnlyList<SoftwareCve> Cves { get; set; } = default!;
}
/// <summary>One CVE of a <see cref="TopSoftware"/> entry; <see cref="AffectedSessions"/> counts that product's sessions only.</summary>
// Declaration order == wire order.
public class SoftwareCve
{
public string CveId { get; set; } = default!;
public string CvssSeverity { get; set; } = default!;
public double CvssScore { get; set; }
public bool IsKev { get; set; }
public double? EpssScore { get; set; }
public string Priority { get; set; } = default!;
public int AffectedSessions { get; set; }
}
// ── Request bodies ──
/// <summary>Body of POST vulnerability/cpe-mapping/auto-resolve.</summary>
@@ -82,7 +82,7 @@ export const ABOUT_FAQ: AboutFaqItem[] = [
{
question: "Can I ask an AI assistant about my enrollments?",
answer:
"Yes. Autopilot Monitor exposes a Model Context Protocol (MCP) server. Connect Claude Desktop, VS Code with Claude, or any MCP client that supports Streamable HTTP with OAuth, and ask questions like \"show me all failed enrollments from the last 24 hours\" or \"why did this session fail?\". Access follows your portal role and is scoped to your tenant, with usage limits tied to the tenant's plan.",
"Yes. Autopilot Monitor exposes a Model Context Protocol (MCP) server. Connect Claude, ChatGPT, VS Code with GitHub Copilot, or a command-line client such as Claude Code, Codex or Gemini CLI, and ask questions like \"show me all failed enrollments from the last 24 hours\" or \"why did this session fail?\". An AI client your organization hosts itself is registered once by a Tenant Admin. Access follows your portal role, with usage limits tied to the tenant's plan.",
},
{
question: "Who builds and operates Autopilot Monitor?",
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { SITE_URL } from "@/utils/config";
import { OPEN_GRAPH_BASE, TWITTER_BASE } from "@/lib/siteMetadata";
export const metadata: Metadata = {
title: "About – Real-Time Windows Autopilot Monitoring",
@@ -26,12 +27,14 @@ export const metadata: Metadata = {
"Autopilot Monitor overview",
],
openGraph: {
...OPEN_GRAPH_BASE,
title: "About Autopilot Monitor – Real-Time Windows Autopilot Monitoring",
description:
"Free, open-source real-time monitoring and troubleshooting for Windows Autopilot enrollments. Track every phase, run analyze rules, and resolve issues faster — built by Oliver Kieselbach.",
url: `${SITE_URL}/about`,
},
twitter: {
...TWITTER_BASE,
title: "About Autopilot Monitor – Real-Time Windows Autopilot Monitoring",
description:
"Free, open-source real-time monitoring and troubleshooting for Windows Autopilot enrollments. Track every phase, run analyze rules, and resolve issues faster.",
@@ -9,6 +9,7 @@ import { fromWireAdminConfiguration, type AdminConfiguration } from "@/types/adm
import { saveAdminConfigChanges } from "@/lib/adminConfigSave";
import { useCanMutatePlatform } from "@/hooks/useCanMutatePlatform";
import { SectionCardHeader } from "@/components/SectionCardHeader";
import { useFetchProgress } from "@/hooks/useFetchProgress";
import type {
AdminConfiguration as WireAdminConfiguration,
CveExposureSummary,
@@ -78,6 +79,9 @@ export function VulnerabilityDataSection({
const [summary, setSummary] = useState<CveExposureSummary | null>(null);
const [summaryDays, setSummaryDays] = useState(30);
const [loadingSummary, setLoadingSummary] = useState(false);
// Same cross-tenant scan as the Software tab's "All tenants" view, so they share the estimate.
const summaryProgress = useFetchProgress("vulnExposure.all.lastFetchMs");
const { begin: summaryProgressBegin, finish: summaryProgressFinish } = summaryProgress;
const refreshSyncStatus = useCallback(async () => {
try {
@@ -124,15 +128,20 @@ export function VulnerabilityDataSection({
const refreshSummary = useCallback(async () => {
setLoadingSummary(true);
summaryProgressBegin();
let succeeded = false;
try {
setSummary(await fetchJson<CveExposureSummary>(api.metrics.globalVulnerability(summaryDays, 10), getAccessToken));
// perBand 10: the band filters of the panel need each band's top entries (bandCves/bandSoftware).
setSummary(await fetchJson<CveExposureSummary>(api.metrics.globalVulnerability(summaryDays, 10, undefined, 10), getAccessToken));
succeeded = true;
} catch {
// Non-critical: the overview is auxiliary; config + sync still render.
setSummary(null);
} finally {
summaryProgressFinish(succeeded);
setLoadingSummary(false);
}
}, [getAccessToken, summaryDays]);
}, [getAccessToken, summaryDays, summaryProgressBegin, summaryProgressFinish]);
useEffect(() => {
const run = async () => {
@@ -640,7 +649,8 @@ export function VulnerabilityDataSection({
<VulnerabilityExposurePanel
title="Fleet Vulnerability Exposure"
summary={summary}
loading={loadingSummary && !summary}
loading={loadingSummary}
progress={{ elapsedMs: summaryProgress.elapsedMs, estimateMs: summaryProgress.estimateMs }}
showTenantCount
days={summaryDays}
onDaysChange={setSummaryDays}
@@ -112,7 +112,7 @@ export function SectionImePatternHealth() {
<h3 className="text-sm font-semibold text-gray-900">Open drift alerts</h3>
<p className="text-xs text-gray-500 mb-3">
One <span className="font-mono">ImePatternDriftSuspected</span> ops event per version × pattern. Next step: pull a diagnostics package of a session on that IME version,
validate the pattern against the real log, compare with the IME decompile, fix the pattern under{" "}
validate the pattern against the real log, fix the pattern under{" "}
<Link href="/ime-log-patterns" className="text-green-700 hover:text-green-800">IME Log Patterns</Link>.
</p>
<ul className="divide-y divide-gray-100">
@@ -0,0 +1,42 @@
import type { Metadata } from "next";
import { SITE_URL } from "@/utils/config";
import { OPEN_GRAPH_BASE, TWITTER_BASE } from "@/lib/siteMetadata";
const SHARE_TITLE = "AI Analysis for Windows Autopilot – Bring Your Own AI";
const SHARE_DESCRIPTION =
"Ask your Autopilot enrollments anything in Claude, ChatGPT, VS Code, a terminal agent or a self-hosted client. Read-only, Microsoft sign-in, included in every plan.";
export const metadata: Metadata = {
title: "AI Analysis – Ask Your Autopilot Enrollments",
description:
"Connect Claude, ChatGPT, VS Code with GitHub Copilot, a terminal agent or a self-hosted client to the Autopilot Monitor MCP server and ask about your Windows Autopilot enrollments in plain language. Read-only, Microsoft sign-in, included in every plan.",
keywords: [
"Windows Autopilot AI analysis",
"Autopilot MCP server",
"Model Context Protocol Intune",
"Intune AI assistant",
"Claude Autopilot troubleshooting",
"ChatGPT Intune enrollment",
"GitHub Copilot MCP Intune",
"Autopilot enrollment root cause AI",
"bring your own AI",
],
openGraph: {
...OPEN_GRAPH_BASE,
title: SHARE_TITLE,
description: SHARE_DESCRIPTION,
url: `${SITE_URL}/ai`,
},
twitter: {
...TWITTER_BASE,
title: SHARE_TITLE,
description: SHARE_DESCRIPTION,
},
alternates: {
canonical: `${SITE_URL}/ai`,
},
};
export default function AiLayout({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
@@ -0,0 +1,32 @@
import { LandingNavbar } from "../../components/landing/LandingNavbar";
import { SiteFooter } from "../../components/SiteFooter";
import { MarketingTracker } from "../../components/MarketingTracker";
import { AiHero } from "../../components/ai/AiHero";
import { StructuredFacts } from "../../components/ai/StructuredFacts";
import { QuestionsSection } from "../../components/ai/QuestionsSection";
import { ArchitectureSection } from "../../components/ai/ArchitectureSection";
import { ConnectSection } from "../../components/ai/ConnectSection";
import { ClosingCta } from "../../components/ai/ClosingCta";
/**
* AI analysis with MCP: what you can ask, where the model runs, how to connect. Every claim on the
* page must hold against the MCP access model and the customer docs (D-305).
*/
export default function AiPage() {
return (
<div className="landing-v2 min-h-screen bg-[var(--lp-bg)]">
<MarketingTracker page="ai">
<LandingNavbar />
<main>
<AiHero />
<StructuredFacts />
<QuestionsSection />
<ArchitectureSection />
<ConnectSection />
<ClosingCta />
</main>
<SiteFooter />
</MarketingTracker>
</div>
);
}
@@ -10,8 +10,11 @@ import type { SoftwareTabScope, TimeRange } from "./types";
import { rangeToDays } from "./types";
import { ApiError, fetchJson } from "@/lib/apiClient";
import { notifyApiError } from "@/contexts/NotificationContext";
import { useFetchProgress } from "@/hooks/useFetchProgress";
const TOP_N = 20;
/** Per severity/priority band, its top entries outside the lists, so every band filter shows something. */
const PER_BAND = 10;
export default function VulnerabilitiesTab({ scope, timeRange }: { scope: SoftwareTabScope; timeRange: TimeRange }) {
const { getAccessToken } = useAuth();
@@ -24,18 +27,25 @@ export default function VulnerabilitiesTab({ scope, timeRange }: { scope: Softwa
// GA without a specific tenant selected sees the cross-tenant aggregate (incl. affected tenants).
const showTenantCount = isGlobalAdmin && !selectedTenantId;
// The cross-tenant scan takes far longer than one tenant's, so each keeps its own estimate.
const progress = useFetchProgress(showTenantCount ? "vulnExposure.all.lastFetchMs" : "vulnExposure.tenant.lastFetchMs");
const { begin: progressBegin, finish: progressFinish } = progress;
useEffect(() => {
if (!scopeInitialized) return;
let cancelled = false;
const days = rangeToDays(timeRange);
const run = async () => {
let succeeded = false;
try {
setLoading(true);
const url = scopedApi.vulnerability(scope, days, TOP_N);
progressBegin();
const url = scopedApi.vulnerability(scope, days, TOP_N, PER_BAND);
const summary = await fetchJson<CveExposureSummary>(url, getAccessToken);
if (cancelled) return;
setSummary(summary);
succeeded = true;
} catch (err) {
if (cancelled) return;
if (err instanceof ApiError) {
@@ -45,7 +55,11 @@ export default function VulnerabilitiesTab({ scope, timeRange }: { scope: Softwa
notifyApiError(addNotification, "Backend Not Reachable", err, "vuln-exposure-error", "Unable to load vulnerability exposure.");
}
} finally {
if (!cancelled) setLoading(false);
// A cancelled run leaves the progress to the run that replaced it.
if (!cancelled) {
progressFinish(succeeded);
setLoading(false);
}
}
};
@@ -54,5 +68,12 @@ export default function VulnerabilitiesTab({ scope, timeRange }: { scope: Softwa
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scopeInitialized, scopeKey, timeRange]);
return <VulnerabilityExposurePanel summary={summary} loading={loading} showTenantCount={showTenantCount} />;
return (
<VulnerabilityExposurePanel
summary={summary}
loading={loading}
showTenantCount={showTenantCount}
progress={{ elapsedMs: progress.elapsedMs, estimateMs: progress.estimateMs }}
/>
);
}
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { SITE_URL } from "@/utils/config";
import { OPEN_GRAPH_BASE, TWITTER_BASE } from "@/lib/siteMetadata";
export const metadata: Metadata = {
title: "Get Pro – Purchase Options",
@@ -13,12 +14,14 @@ export const metadata: Metadata = {
"Windows Autopilot monitoring Pro",
],
openGraph: {
...OPEN_GRAPH_BASE,
title: "Get Pro – Autopilot Monitor",
description:
"How to purchase Autopilot Monitor Pro: through Microsoft Marketplace or online via Cleverbridge.",
url: `${SITE_URL}/buy`,
},
twitter: {
...TWITTER_BASE,
title: "Get Pro – Autopilot Monitor",
description:
"How to purchase Autopilot Monitor Pro: through Microsoft Marketplace or online via Cleverbridge.",
@@ -382,7 +382,7 @@ function HomeContent() {
</div>
</div>
<a
href="/settings"
href="/settings/"
className="shrink-0 inline-flex items-center gap-2 bg-white text-red-700 font-semibold text-sm px-4 py-2 rounded-lg hover:bg-red-50 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -0,0 +1,29 @@
"use client";
import type { MouseEvent, ReactNode } from "react";
import { trackEvent } from "@/lib/appInsights";
import { EVENT_FOLLOWUP_CLICKED, trackIdOf } from "../eventClicks";
/**
* Sends one App Insights event per click on an element marked data-track="<id>".
* Delegated from this one wrapper, so the page itself stays a server component.
*/
export function EventClickTracker({
event,
className,
children,
}: {
event: string;
className?: string;
children: ReactNode;
}) {
const onClick = (e: MouseEvent<HTMLDivElement>) => {
const button = trackIdOf(e.target as Element);
if (button) trackEvent(EVENT_FOLLOWUP_CLICKED, { event, button });
};
return (
<div className={className} onClick={onClick}>
{children}
</div>
);
}
@@ -0,0 +1,234 @@
import type { Metadata } from "next";
import type { ReactNode } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { BrandMark } from "@/components/BrandMark";
import { GitHubStarLink } from "@/components/GitHubStarLink";
import { SiteFooter } from "@/components/SiteFooter";
import { CUSTOMER_QUOTE } from "@/components/landing/customerQuote";
import { DOCS_URL, sitePageUrl } from "@/utils/config";
import {
COMMUNITY_COMPANIONS,
EVENT_PAGE_ROBOTS,
FOLLOWUP_EVENTS,
WALKTHROUGH_EMAIL,
findFollowupEvent,
walkthroughMailto,
type EventArt,
} from "../events";
import { EventClickTracker } from "./EventClickTracker";
// Static export: prerender exactly the listed events; any other slug is a build-time 404.
export const dynamicParams = false;
export function generateStaticParams() {
return FOLLOWUP_EVENTS.map((event) => ({ slug: event.slug }));
}
type PageProps = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const event = findFollowupEvent((await params).slug);
if (!event) return {};
const url = sitePageUrl(`/events/${event.slug}`);
const description = `Your follow-up from ${event.name}: try Autopilot Monitor for free, get a walkthrough, or read the docs.`;
return {
title: event.name,
description,
robots: EVENT_PAGE_ROBOTS,
openGraph: { title: `${event.name} – Autopilot Monitor`, description, url },
alternates: { canonical: url },
};
}
const PRIMARY_BUTTON =
"inline-flex items-center justify-center min-h-[44px] px-5 rounded-lg bg-[var(--lp-accent-ink)] hover:brightness-110 text-white text-[15px] font-semibold shadow-sm transition-all";
const SECONDARY_BUTTON =
"inline-flex items-center justify-center min-h-[44px] px-5 rounded-lg border border-[var(--lp-line)] bg-[var(--lp-surface)] hover:bg-[var(--lp-surface-2)] text-[var(--lp-ink)] text-[15px] font-semibold transition-colors";
export default async function EventFollowupPage({ params }: PageProps) {
const event = findFollowupEvent((await params).slug);
if (!event) notFound();
return (
<div className="landing-v2 min-h-screen bg-[var(--lp-bg)] flex flex-col">
<EventClickTracker event={event.slug} className="flex-1 flex flex-col">
<header className="border-b border-[var(--lp-line-soft)] bg-[var(--lp-surface)]">
<div className="max-w-6xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between gap-4">
<Link href="/" prefetch={false} data-track="logo" className="flex items-center gap-2.5">
<BrandMark className="w-6 h-6" />
<span className="text-[15px] font-bold tracking-tight text-[var(--lp-ink)] whitespace-nowrap">
Autopilot Monitor
</span>
</Link>
<Link
href="/get-started"
prefetch={false}
data-track="header_get_started"
className="px-4 py-2 rounded-lg bg-[var(--lp-accent-ink)] hover:brightness-110 text-white text-sm font-semibold shadow-sm transition-all whitespace-nowrap"
>
Get started
</Link>
</div>
</header>
<main className="flex-1">
<section className="px-4 sm:px-6 pt-12 sm:pt-16 pb-10">
<div className="max-w-6xl mx-auto flex items-center gap-6">
<div className="flex-1 min-w-0">
<p className="text-xs font-semibold uppercase tracking-[0.22em] text-[var(--lp-accent-ink)]">{event.name}</p>
<h1 className="mt-4 text-[34px] sm:text-5xl lg:text-6xl font-bold tracking-tight leading-[1.05] text-[var(--lp-ink)] text-balance">
Thanks for stopping by.
</h1>
<p className="mt-4 max-w-xl text-[17px] sm:text-xl leading-relaxed text-[var(--lp-ink-soft)]">
Three ways to keep going. Pick the one that fits your week.
</p>
</div>
{event.art && <ArtImage art={event.art.hero} className="w-[104px] sm:w-[180px] lg:w-[250px]" />}
</div>
</section>
<section className="px-4 sm:px-6 pb-16 sm:pb-20">
<div className="max-w-6xl mx-auto grid gap-5 md:grid-cols-3">
<ActionCard icon={<ArrowIcon />} title="Try it today">
<p className={CARD_TEXT}>
The Community plan is the full product, free. Sign in, assign one script in Intune, and watch your first
enrollment live.
</p>
<Link href="/get-started" prefetch={false} data-track="get_started" className={PRIMARY_BUTTON}>
Get started
</Link>
</ActionCard>
<ActionCard icon={<MailIcon />} title="Get a walkthrough">
<p className={CARD_TEXT}>
30 minutes with {event.walkthroughWith}. Your scenarios, your questions.
</p>
<a href={walkthroughMailto(event)} data-track="walkthrough_email" className={SECONDARY_BUTTON}>
Request a walkthrough
</a>
{/* mailto: does nothing without a mail client, so the address stays readable and copyable */}
<span className="-mt-1 text-center text-[13px] text-[var(--lp-ink-soft)] select-all">{WALKTHROUGH_EMAIL}</span>
</ActionCard>
<ActionCard icon={<BookIcon />} title="Read the docs">
<p className={CARD_TEXT}>
From the first deployment to analyze rules and connecting your AI assistant, step by step.
</p>
<a href={DOCS_URL} target="_blank" rel="noopener noreferrer" data-track="docs" className={SECONDARY_BUTTON}>
Read the docs
</a>
</ActionCard>
</div>
</section>
<section className="px-4 sm:px-6 py-14 bg-[var(--lp-surface)] border-y border-[var(--lp-line-soft)]">
<div className="max-w-6xl mx-auto flex flex-wrap items-center justify-between gap-x-12 gap-y-8">
<figure className="flex-1 basis-[420px] min-w-0 max-w-2xl">
<blockquote className="text-2xl sm:text-[28px] font-semibold tracking-tight leading-snug text-[var(--lp-ink)] text-balance">
&ldquo;{CUSTOMER_QUOTE.text}&rdquo;
</blockquote>
<figcaption className="mt-3 text-sm text-[var(--lp-ink-soft)]">{CUSTOMER_QUOTE.attribution}</figcaption>
</figure>
<div>
<p className="text-sm text-[var(--lp-ink-soft)]">Seeing the same in your tenant? Leave a star.</p>
<div className="mt-2.5 flex items-start gap-1.5">
{event.art && <ArtImage art={event.art.starPointer} className="w-[58px] sm:w-[72px]" />}
{/* The offset puts the button's middle on the pointing finger at both art widths */}
<span data-track="github_star" className={event.art ? "sm:mt-[5px]" : undefined}>
<GitHubStarLink label="Star on GitHub" />
</span>
</div>
</div>
</div>
</section>
<section className="px-4 sm:px-6 py-14">
<div className="max-w-6xl mx-auto">
<h2 className="text-2xl font-bold tracking-tight text-[var(--lp-ink)]">Looking for other cool Intune companions?</h2>
<p className="mt-2 text-[15px] text-[var(--lp-ink-soft)]">Check out these free community editions as well.</p>
<div className="mt-6 grid gap-4 sm:grid-cols-2">
{COMMUNITY_COMPANIONS.map((companion) => (
<a
key={companion.id}
href={companion.href}
target="_blank"
rel="noopener noreferrer"
data-track={companion.id}
className="flex items-center gap-4 rounded-xl border border-[var(--lp-line)] bg-[var(--lp-surface)] px-5 py-4 hover:border-[var(--lp-accent-line)] transition-colors"
>
<span className="flex-1 min-w-0">
<span className="block font-semibold text-[var(--lp-ink)]">{companion.name}</span>
<span className="mt-1 block text-sm leading-relaxed text-[var(--lp-ink-soft)]">{companion.description}</span>
</span>
<svg className="w-[18px] h-[18px] shrink-0 text-[var(--lp-accent-ink)]" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M7 17L17 7M9 7h8v8" />
</svg>
</a>
))}
</div>
</div>
</section>
</main>
</EventClickTracker>
<SiteFooter />
</div>
);
}
const CARD_TEXT = "flex-1 text-[15px] leading-relaxed text-[var(--lp-ink-soft)]";
function ActionCard({ icon, title, children }: { icon: ReactNode; title: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-3.5 rounded-2xl border border-[var(--lp-line)] bg-[var(--lp-surface)] p-7 shadow-xl shadow-black/[0.04]">
<span className="inline-flex w-10 h-10 items-center justify-center rounded-[10px] bg-[var(--lp-accent-soft)] text-[var(--lp-accent-ink)]">
{icon}
</span>
<h2 className="text-xl font-bold text-[var(--lp-ink)]">{title}</h2>
{children}
</div>
);
}
/** Event artwork is decorative: the eyebrow already names the event. */
function ArtImage({ art, className }: { art: EventArt; className: string }) {
return (
// Static export: next/image is not configured, plain img is intentional.
// eslint-disable-next-line @next/next/no-img-element
<img src={art.src} width={art.width} height={art.height} alt="" decoding="async" className={`${className} h-auto shrink-0`} />
);
}
function CardIcon({ children }: { children: ReactNode }) {
return (
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
{children}
</svg>
);
}
function ArrowIcon() {
return (
<CardIcon>
<path d="M5 12h14M13 6l6 6-6 6" />
</CardIcon>
);
}
function MailIcon() {
return (
<CardIcon>
<rect x="3" y="5" width="18" height="14" rx="2" />
<path d="M3 7l9 6 9-6" />
</CardIcon>
);
}
function BookIcon() {
return (
<CardIcon>
<path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z" />
<path d="M4 21V5M8 7h7" />
</CardIcon>
);
}
@@ -0,0 +1,114 @@
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { renderToStaticMarkup } from "react-dom/server";
import robots from "../../robots";
import sitemap from "../../sitemap";
import EventFollowupPage, { generateMetadata, generateStaticParams } from "../[slug]/page";
import { COMMUNITY_COMPANIONS, FOLLOWUP_EVENTS, WALKTHROUGH_EMAIL, walkthroughMailto } from "../events";
import { trackIdOf } from "../eventClicks";
import { sitePageUrl } from "@/utils/config";
/**
* Event follow-up pages are reached only through the follow-up email: never indexed, never
* listed for crawlers, and every call to action counted by one click event (data-track).
*/
const WEB_ROOT = join(__dirname, "..", "..", "..");
const params = (slug: string) => ({ params: Promise.resolve({ slug }) });
async function renderEventPage(slug: string): Promise<string> {
return renderToStaticMarkup(await EventFollowupPage(params(slug)));
}
/** Width and height from a PNG's IHDR chunk. */
function pngSize(publicPath: string): { width: number; height: number } {
const bytes = readFileSync(join(WEB_ROOT, "public", publicPath));
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
}
describe("event follow-up pages", () => {
it("prerender exactly the listed events, with unique URL-safe slugs", () => {
const slugs = FOLLOWUP_EVENTS.map((e) => e.slug);
expect(slugs.length).toBeGreaterThan(0);
expect(new Set(slugs).size).toBe(slugs.length);
for (const slug of slugs) expect(slug).toMatch(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
expect(generateStaticParams()).toEqual(slugs.map((slug) => ({ slug })));
});
it("are noindex/nofollow with their own canonical URL", async () => {
for (const event of FOLLOWUP_EVENTS) {
const metadata = await generateMetadata(params(event.slug));
expect(metadata.robots).toEqual({ index: false, follow: false, googleBot: { index: false, follow: false } });
expect(metadata.alternates?.canonical).toBe(sitePageUrl(`/events/${event.slug}`));
expect(metadata.title).toBe(event.name);
}
});
it("stay out of the sitemap, robots.txt and llms.txt", () => {
expect(sitemap().filter((entry) => entry.url.includes("/events"))).toEqual([]);
for (const rule of [robots().rules].flat()) {
expect([rule.allow ?? []].flat().filter((path) => path.startsWith("/events"))).toEqual([]);
// A disallow would hide the noindex tag from crawlers.
expect([rule.disallow ?? []].flat().filter((path) => path.startsWith("/events"))).toEqual([]);
}
expect(readFileSync(join(WEB_ROOT, "public", "llms.txt"), "utf-8")).not.toContain("/events");
});
it("declare the real size of their artwork", () => {
for (const event of FOLLOWUP_EVENTS) {
for (const art of event.art ? [event.art.hero, event.art.starPointer] : []) {
expect(pngSize(art.src), art.src).toEqual({ width: art.width, height: art.height });
}
}
});
it("mark every call to action for the click event", async () => {
for (const event of FOLLOWUP_EVENTS) {
const html = await renderEventPage(event.slug);
// SiteFooter carries the marketing ids of the shared footer (footer_*); it sits outside the
// event tracker, so those clicks never become event_followup_clicked.
const ids = [...html.matchAll(/data-track="([^"]+)"/g)].map((m) => m[1]).filter((id) => !id.startsWith("footer_"));
expect(ids.sort()).toEqual(
[
"logo",
"header_get_started",
"get_started",
"walkthrough_email",
"docs",
"github_star",
...COMMUNITY_COMPANIONS.map((c) => c.id),
].sort(),
);
expect(html).toContain(`href="${walkthroughMailto(event).replace(/&/g, "&amp;")}"`);
expect(html).toContain(WALKTHROUGH_EMAIL);
for (const companion of COMMUNITY_COMPANIONS) expect(html).toContain(`href="${companion.href}"`);
}
});
it("name the event in the walkthrough mail subject", () => {
expect(walkthroughMailto(FOLLOWUP_EVENTS[0])).toBe(
`mailto:${WALKTHROUGH_EMAIL}?subject=Walkthrough%20request%20-%20${encodeURIComponent(FOLLOWUP_EVENTS[0].name)}`,
);
});
});
describe("trackIdOf", () => {
const element = (track: string | null) => ({
closest: (selector: string) => {
expect(selector).toBe("[data-track]");
return track === null ? null : { getAttribute: () => track };
},
});
it("reads the id of the nearest marked element", () => {
expect(trackIdOf(element("docs"))).toBe("docs");
});
it("ignores clicks outside any marked element, an empty id, and a missing target", () => {
expect(trackIdOf(element(null))).toBeNull();
expect(trackIdOf(element(""))).toBeNull();
expect(trackIdOf(null)).toBeNull();
});
});
@@ -0,0 +1,4 @@
/** The one custom event the event follow-up pages send: properties `event` (slug) and `button`. */
export const EVENT_FOLLOWUP_CLICKED = "event_followup_clicked";
export { trackIdOf } from "@/lib/clickTracking";
@@ -0,0 +1,68 @@
/**
* Event follow-up pages (/events/<slug>/): unlisted pages reached only through the
* follow-up email after an event. They stay out of the sitemap, robots.txt and llms.txt
* and are marked noindex (events.guard.test.ts pins all four).
*/
export interface EventArt {
src: string;
width: number;
height: number;
}
export interface FollowupEvent {
/** URL segment: /events/<slug>/. It is in sent emails, so never rename or reuse one. */
slug: string;
/** The event's name as attendees know it. */
name: string;
/** Who runs the walkthrough: a person's name, or "us". */
walkthroughWith: string;
/** Event artwork beside the hero and pointing at the GitHub star. */
art?: { hero: EventArt; starPointer: EventArt };
}
export const WALKTHROUGH_EMAIL = "support@autopilotmonitor.com";
/** Robots metadata of every event page. Not a robots.txt disallow: crawlers would then never see it. */
export const EVENT_PAGE_ROBOTS = {
index: false,
follow: false,
googleBot: { index: false, follow: false },
} as const;
export const FOLLOWUP_EVENTS: readonly FollowupEvent[] = [
{
slug: "wpns-2026",
name: "Workplace Ninja Summit 2026",
walkthroughWith: "Oliver Kieselbach",
art: {
hero: { src: "/events/wpns/ninja-crouch.png", width: 500, height: 482 },
starPointer: { src: "/events/wpns/ninja-pointing.png", width: 144, height: 121 },
},
},
];
/** Other tools from the same team that come in a free community edition. */
export const COMMUNITY_COMPANIONS = [
{
id: "scepman_ce",
name: "SCEPman Community Edition",
description: "Free certificate authority for Intune, running in your own Azure tenant.",
href: "https://docs.scepman.com/editions",
},
{
id: "myworkid_ce",
name: "MyWorkID Community Edition",
description: "Self-service Temporary Access Pass, password reset and user verification for Entra ID.",
href: "https://www.glueckkanja.com/en/security/my-work-id",
},
] as const;
export function findFollowupEvent(slug: string): FollowupEvent | undefined {
return FOLLOWUP_EVENTS.find((event) => event.slug === slug);
}
/** The mailto: link behind "Request a walkthrough", subject naming the event. */
export function walkthroughMailto(event: FollowupEvent): string {
return `mailto:${WALKTHROUGH_EMAIL}?subject=${encodeURIComponent(`Walkthrough request - ${event.name}`)}`;
}
@@ -210,7 +210,7 @@ export default function GeographicPerformancePage() {
<div className="text-sm font-medium text-amber-800">Geo-Location collection is disabled</div>
<div className="text-sm text-amber-700 mt-0.5">
New sessions will not collect location data. Enable geo-location in{" "}
<a href="/settings" className="underline hover:text-amber-900">Configuration</a>{" "}
<a href="/settings/" className="underline hover:text-amber-900">Configuration</a>{" "}
to start collecting geographic data for future enrollments.
</div>
</div>
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { LandingNavbar } from "../../components/landing/LandingNavbar";
import { SignupConsentCta } from "../../components/landing/SignupConsentCta";
import { SiteFooter } from "../../components/SiteFooter";
import { MarketingTracker } from "../../components/MarketingTracker";
import { DOCS_URL, SITE_URL } from "@/utils/config";
export const metadata: Metadata = {
@@ -49,69 +50,73 @@ const STEPS = [
export default function GetStartedPage() {
return (
<div className="landing-v2 min-h-screen bg-[var(--lp-bg)] flex flex-col">
<LandingNavbar />
<MarketingTracker page="get_started">
<LandingNavbar />
<main className="flex-1 px-6 pt-16 sm:pt-20 pb-20">
<div className="max-w-3xl mx-auto">
<p className="text-[11px] font-semibold uppercase tracking-[0.24em] text-[var(--lp-ink-faint)]">
Get started
</p>
<h1 className="mt-4 text-4xl sm:text-5xl font-bold tracking-tight text-[var(--lp-ink)] leading-[1.08] text-balance">
From sign-in to your first live enrollment.
</h1>
<p className="mt-4 text-lg text-[var(--lp-ink-soft)] leading-relaxed max-w-xl">
Five steps, no infrastructure on your side. Most teams see their first live session
the same day.
</p>
<main className="flex-1 px-6 pt-16 sm:pt-20 pb-20">
<div className="max-w-3xl mx-auto">
<p className="text-[11px] font-semibold uppercase tracking-[0.24em] text-[var(--lp-ink-faint)]">
Get started
</p>
<h1 className="mt-4 text-4xl sm:text-5xl font-bold tracking-tight text-[var(--lp-ink)] leading-[1.08] text-balance">
From sign-in to your first live enrollment.
</h1>
<p className="mt-4 text-lg text-[var(--lp-ink-soft)] leading-relaxed max-w-xl">
Five steps, no infrastructure on your side. Most teams see their first live session
the same day.
</p>
{/* Step sequence */}
<div className="relative mt-12">
<div className="absolute left-[15px] top-3 bottom-3 w-px bg-[var(--lp-line)]" aria-hidden="true" />
<ol className="space-y-8">
{STEPS.map((step, i) => (
<li key={step.title} className="relative pl-14">
<span className="absolute left-0 top-0 w-8 h-8 rounded-full bg-[var(--lp-accent)] text-white text-sm font-bold flex items-center justify-center">
{i + 1}
</span>
<div className="flex items-baseline gap-3 flex-wrap">
<h2 className="text-lg font-semibold text-[var(--lp-ink)]">{step.title}</h2>
<span className="text-[11px] font-medium px-2 py-0.5 rounded-full bg-[var(--lp-accent-soft)] text-[var(--lp-accent-ink)]">
{step.note}
{/* Step sequence */}
<div data-track-section="steps" className="relative mt-12">
<div className="absolute left-[15px] top-3 bottom-3 w-px bg-[var(--lp-line)]" aria-hidden="true" />
<ol className="space-y-8">
{STEPS.map((step, i) => (
<li key={step.title} className="relative pl-14">
<span className="absolute left-0 top-0 w-8 h-8 rounded-full bg-[var(--lp-accent)] text-white text-sm font-bold flex items-center justify-center">
{i + 1}
</span>
</div>
<p className="mt-1.5 text-[15px] text-[var(--lp-ink-soft)] leading-relaxed">{step.description}</p>
</li>
))}
</ol>
<div className="flex items-baseline gap-3 flex-wrap">
<h2 className="text-lg font-semibold text-[var(--lp-ink)]">{step.title}</h2>
<span className="text-[11px] font-medium px-2 py-0.5 rounded-full bg-[var(--lp-accent-soft)] text-[var(--lp-accent-ink)]">
{step.note}
</span>
</div>
<p className="mt-1.5 text-[15px] text-[var(--lp-ink-soft)] leading-relaxed">{step.description}</p>
</li>
))}
</ol>
</div>
{/* CTA — sign-in waits for the Terms + DPA tick */}
<SignupConsentCta>
<a
href={DOCS_URL}
data-track="get_started_docs"
target="_blank"
rel="noopener noreferrer"
className="px-7 py-3 rounded-lg border border-[var(--lp-line)] bg-[var(--lp-surface)] text-[var(--lp-ink)] font-semibold hover:border-[var(--lp-ink-faint)] transition-colors"
>
Read the docs
</a>
</SignupConsentCta>
<p className="mt-6 text-sm text-[var(--lp-ink-faint)] leading-relaxed max-w-xl">
When you need more later: the{" "}
<a
href="/plans/"
data-track="get_started_pro_plan"
className="text-[var(--lp-accent-ink)] hover:opacity-80 underline"
>
Pro plan
</a>{" "}
adds SLAs, support commitments, MSP delegation, higher operating limits and more —
same service, nothing to migrate.
</p>
</div>
</main>
{/* CTA — sign-in waits for the Terms + DPA tick */}
<SignupConsentCta>
<a
href={DOCS_URL}
target="_blank"
rel="noopener noreferrer"
className="px-7 py-3 rounded-lg border border-[var(--lp-line)] bg-[var(--lp-surface)] text-[var(--lp-ink)] font-semibold hover:border-[var(--lp-ink-faint)] transition-colors"
>
Read the docs
</a>
</SignupConsentCta>
<p className="mt-6 text-sm text-[var(--lp-ink-faint)] leading-relaxed max-w-xl">
When you need more later: the{" "}
<a
href="/plans"
className="text-[var(--lp-accent-ink)] hover:opacity-80 underline"
>
Pro plan
</a>{" "}
adds SLAs, support commitments, MSP delegation, higher operating limits and more —
same service, nothing to migrate.
</p>
</div>
</main>
<SiteFooter />
<SiteFooter />
</MarketingTracker>
</div>
);
}
@@ -48,12 +48,20 @@ html {
--lp-accent-line: rgba(51, 177, 97, 0.35);
--lp-warn: #d97706;
--lp-warn-soft: rgba(217, 119, 6, 0.1);
/* Warning text on light surfaces: --lp-warn is too light for body-size text (contrast) */
--lp-warn-ink: #b45309;
--lp-danger: #dc2626;
/* GitHub star glyph only (GitHubStarLink) — never text or a fill */
--lp-star: #eab308;
/* Terminal is dark in both themes */
--lp-term-bg: #0d1424;
--lp-term-deep: #0a101d;
--lp-term-line: #22304a;
--lp-term-ink: #d6e1f0;
--lp-term-faint: #7b8ba3;
--lp-term-ok: #55c57f;
--lp-term-warn: #f5a623;
--lp-term-high: #ff9d66;
}
.dark {
@@ -72,7 +80,9 @@ html {
--lp-accent-line: rgba(59, 192, 108, 0.4);
--lp-warn: #f5a623;
--lp-warn-soft: rgba(245, 166, 35, 0.12);
--lp-warn-ink: #f5a623;
--lp-danger: #f87171;
--lp-star: #facc15;
}
body {
@@ -761,7 +771,9 @@ html.auth-pending .landing-v2::after {
--lp-accent-line: rgba(51, 177, 97, 0.35);
--lp-warn: #d97706;
--lp-warn-soft: rgba(217, 119, 6, 0.1);
--lp-warn-ink: #b45309;
--lp-danger: #dc2626;
--lp-star: #eab308;
}
/* Neutralize the global .dark utility overrides inside the light-only
@@ -888,6 +900,72 @@ html.auth-pending .landing-v2::after {
}
}
/* ===== AI page data-path diagram (components/ai/DataPath.tsx) =====
The nodes stack on phones and sit in one row from lg, so every link turns with them. The
conversation link draws its dashes with a gradient: a thin dashed border with a radius renders as
a solid line, and the link must keep the data links' box or the dots have no track to run on. */
.ai-flow-line {
position: relative;
flex-shrink: 0;
width: 2px;
height: 56px;
border-radius: 2px;
background: var(--lp-accent);
}
.ai-flow-line--talk {
border-radius: 0;
background: repeating-linear-gradient(to bottom, var(--lp-ink-faint) 0 4px, transparent 4px 8px);
}
.ai-flow-dot {
position: absolute;
left: -3px;
top: 0;
width: 8px;
height: 8px;
border-radius: 9999px;
background: var(--lp-accent);
box-shadow: 0 0 0 3px rgba(51, 177, 97, 0.18);
animation: aiFlowDown 2.4s linear infinite;
}
.ai-flow-dot--back {
animation-name: aiFlowUp;
animation-delay: -1.2s;
background: var(--lp-accent-ink);
}
.ai-flow-line--talk .ai-flow-dot {
background: var(--lp-ink-faint);
box-shadow: 0 0 0 3px rgba(156, 163, 175, 0.2);
}
@keyframes aiFlowDown { from { top: -4px; } to { top: calc(100% - 4px); } }
@keyframes aiFlowUp { from { top: calc(100% - 4px); } to { top: -4px; } }
@keyframes aiFlowRight { from { left: -4px; } to { left: calc(100% - 4px); } }
@keyframes aiFlowLeft { from { left: calc(100% - 4px); } to { left: -4px; } }
@media (min-width: 1024px) {
.ai-flow-line {
width: 100%;
height: 2px;
}
.ai-flow-line--talk {
background: repeating-linear-gradient(to right, var(--lp-ink-faint) 0 6px, transparent 6px 12px);
}
.ai-flow-dot {
top: -3px;
left: 0;
animation-name: aiFlowRight;
}
.ai-flow-dot--back {
animation-name: aiFlowLeft;
}
}
@media (prefers-reduced-motion: reduce) {
.ai-flow-dot {
animation: none;
}
.ai-flow-dot--back {
display: none;
}
}
/* ===== FEEDBACK BUBBLE ANIMATION ===== */
@keyframes fadeInUp {
from {
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { SITE_URL } from "@/utils/config";
import { OPEN_GRAPH_BASE, TWITTER_BASE } from "@/lib/siteMetadata";
export const metadata: Metadata = {
title: "Help & Support – How to Get Help",
@@ -14,12 +15,14 @@ export const metadata: Metadata = {
"Oliver Kieselbach",
],
openGraph: {
...OPEN_GRAPH_BASE,
title: "Help & Support – Autopilot Monitor",
description:
"How to get help with Autopilot Monitor: open a GitHub issue or reach out directly on LinkedIn.",
url: `${SITE_URL}/help`,
},
twitter: {
...TWITTER_BASE,
title: "Help & Support – Autopilot Monitor",
description:
"How to get help with Autopilot Monitor: open a GitHub issue or reach out directly on LinkedIn.",
+15 -10
View File
@@ -7,8 +7,10 @@ import { Story } from "../components/landing/Story";
import { CapabilitiesStrip } from "../components/landing/CapabilitiesStrip";
import { Comparison } from "../components/landing/Comparison";
import { HowItWorks } from "../components/landing/HowItWorks";
import { Testimonials } from "../components/landing/Testimonials";
import { FinalCta } from "../components/landing/FinalCta";
import { SiteFooter } from "../components/SiteFooter";
import { MarketingTracker } from "../components/MarketingTracker";
/**
* Landing page v2 — a scroll story of one enrollment.
@@ -21,16 +23,19 @@ export default function LandingPage() {
<div className="landing-v2 min-h-screen bg-[var(--lp-bg)]">
{/* Client component: handles auth redirect + loading overlay */}
<AuthGate />
<LandingNavbar />
<Hero />
<StatsBand />
<JustAsk />
<Story />
<CapabilitiesStrip />
<Comparison />
<HowItWorks />
<FinalCta />
<SiteFooter />
<MarketingTracker page="landing">
<LandingNavbar />
<Hero />
<StatsBand />
<JustAsk />
<Story />
<CapabilitiesStrip />
<Comparison />
<HowItWorks />
<Testimonials />
<FinalCta />
<SiteFooter />
</MarketingTracker>
</div>
);
}
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { SITE_URL } from "@/utils/config";
import { OPEN_GRAPH_BASE, TWITTER_BASE } from "@/lib/siteMetadata";
export const metadata: Metadata = {
title: "Plans – Community & Pro",
@@ -14,12 +15,14 @@ export const metadata: Metadata = {
"Autopilot monitoring MSP",
],
openGraph: {
...OPEN_GRAPH_BASE,
title: "Plans – Autopilot Monitor",
description:
"Community is the full product and free — and stays free. Pro adds extended retention, higher limits, MSP delegation, and priority support.",
url: `${SITE_URL}/plans`,
},
twitter: {
...TWITTER_BASE,
title: "Plans – Autopilot Monitor",
description:
"Community is the full product and free — and stays free. Pro adds extended retention, higher limits, MSP delegation, and priority support.",
@@ -1,11 +1,13 @@
import type { Metadata } from "next";
import { SITE_URL } from "@/utils/config";
import { OPEN_GRAPH_BASE } from "@/lib/siteMetadata";
export const metadata: Metadata = {
title: "Privacy Policy",
description:
"Privacy Policy for Autopilot Monitor. Learn how we collect, store, and protect your data when using the Windows Autopilot monitoring platform.",
openGraph: {
...OPEN_GRAPH_BASE,
title: "Privacy Policy | Autopilot Monitor",
description:
"Privacy Policy for Autopilot Monitor. Learn how we collect, store, and protect your data.",
+1 -1
View File
@@ -5,7 +5,7 @@ import type { MetadataRoute } from "next";
import { SITE_URL } from "@/utils/config";
// Public marketing / legal pages.
const PUBLIC_PATHS = ["/", "/about", "/buy", "/get-started", "/help", "/plans", "/privacy", "/terms"];
const PUBLIC_PATHS = ["/", "/about", "/ai", "/buy", "/get-started", "/help", "/plans", "/privacy", "/terms"];
// Authenticated portal routes: nothing to index, and the static shell would
// only ever render a sign-in redirect.
@@ -8,6 +8,7 @@ import { apiErrorText, fetchJson, fetchOk, jsonBody } from "@/lib/apiClient";
import { api } from "@/lib/api";
import { SectionCardHeader } from "@/components/SectionCardHeader";
import { DOCS_PATHS } from "@/lib/docsPaths";
import { useCopy } from "@/hooks/useCopy";
import { MCP_SERVER_URL } from "@/utils/config";
import type {
CreateMcpClientRegistrationRequest,
@@ -21,20 +22,6 @@ function formatDay(iso: string | undefined | null): string {
return Number.isNaN(d.getTime()) ? "—" : d.toLocaleDateString();
}
function useCopy() {
const [copied, setCopied] = useState<string | null>(null);
const copy = useCallback(async (value: string, key: string) => {
try {
await navigator.clipboard.writeText(value);
setCopied(key);
setTimeout(() => setCopied(null), 2000);
} catch {
setCopied(null);
}
}, []);
return { copied, copy };
}
/**
* Settings → Tenant → AI Integration. Part 1 explains the normal connection (Claude, ChatGPT, VS Code and
* other supported AI clients: add the server URL, sign in — nothing to register here). Part 2, for Tenant
@@ -33,6 +33,12 @@ export default function sitemap(): MetadataRoute.Sitemap {
changeFrequency: "monthly",
priority: 0.7,
},
{
url: sitePageUrl("/ai"),
lastModified: lastmod("/ai"),
changeFrequency: "monthly",
priority: 0.7,
},
{
url: sitePageUrl("/get-started"),
lastModified: lastmod("/get-started"),
@@ -1,11 +1,13 @@
import type { Metadata } from "next";
import { SITE_URL } from "@/utils/config";
import { OPEN_GRAPH_BASE } from "@/lib/siteMetadata";
export const metadata: Metadata = {
title: "Terms of Use",
description:
"Terms of Use for Autopilot Monitor. Read the usage terms, conditions, and acceptable use policies for the Windows Autopilot monitoring and troubleshooting platform.",
openGraph: {
...OPEN_GRAPH_BASE,
title: "Terms of Use | Autopilot Monitor",
description: "Terms of Use for Autopilot Monitor. Read the usage terms, conditions, and acceptable use policies for the monitoring platform.",
url: `${SITE_URL}/terms`,
@@ -103,7 +103,7 @@ export default function TermsPage() {
<h2 className="text-lg font-semibold text-gray-900">Intellectual Property &amp; Licensing</h2>
<div className="space-y-2 text-gray-700">
<p><strong>Open source.</strong> The Autopilot Monitor source code is published on <a href="https://github.com/okieselbach/AutopilotMonitor" target="_blank" rel="noopener noreferrer" className="text-[var(--lp-accent-ink)] hover:opacity-80 underline">GitHub</a> under the licence stated in that repository. That licence governs the code — it does not grant rights to the hosted service, its infrastructure, its data, or the Autopilot Monitor name and branding.</p>
<p><strong>Your data stays yours.</strong> Enrollment telemetry, configuration, and diagnostics belong to your organization. Using the service grants only the rights needed to operate it for you, as described in the <a href="/privacy" className="text-[var(--lp-accent-ink)] hover:opacity-80 underline">Privacy Policy</a>.</p>
<p><strong>Your data stays yours.</strong> Enrollment telemetry, configuration, and diagnostics belong to your organization. Using the service grants only the rights needed to operate it for you, as described in the <a href="/privacy/" className="text-[var(--lp-accent-ink)] hover:opacity-80 underline">Privacy Policy</a>.</p>
<p><strong>Rules you contribute</strong> are covered by the licence grant described under &quot;Your Data, Suspension and Termination&quot; below.</p>
<p><strong>Third-party components</strong> remain the property of their respective owners and are used under their own licences; see the attributions below.</p>
</div>
@@ -149,7 +149,7 @@ export default function TermsPage() {
<div className="bg-[var(--lp-surface)] border border-[var(--lp-line-soft)] rounded-xl p-6 space-y-4">
<h2 className="text-lg font-semibold text-gray-900">Your Data, Suspension and Termination</h2>
<div className="space-y-2 text-gray-700">
<p><strong>Ownership.</strong> Your enrollment telemetry remains yours. Autopilot Monitor processes it to provide the service, as described in the <a href="/privacy" className="text-[var(--lp-accent-ink)] hover:opacity-80 underline">Privacy Policy</a>.</p>
<p><strong>Ownership.</strong> Your enrollment telemetry remains yours. Autopilot Monitor processes it to provide the service, as described in the <a href="/privacy/" className="text-[var(--lp-accent-ink)] hover:opacity-80 underline">Privacy Policy</a>.</p>
<p><strong>Your controls.</strong> You set the retention period, delete individual sessions, and offboard your tenant entirely at any time — no support ticket required.</p>
<p><strong>Rules you contribute.</strong> Analyze rules, gather rules, and IME log patterns you author are detection definitions, not device data. By creating them you grant a non-exclusive, royalty-free right to retain them and to include them in the shared community rule pool, so that other organizations can benefit from a detection you built. This is the reciprocal side of a product whose built-in rules are community-maintained. You keep the right to use your own rules however you like, and you can request removal from the pool at any time.</p>
<p><strong>Suspension.</strong> Access may be suspended where use threatens the integrity, security, or availability of the service or of other tenants — for example abusive request volumes or attempts to reach other tenants&apos; data. Where circumstances permit, notice is given first.</p>
@@ -7,6 +7,7 @@
* The bar is capped at 95% — it never claims "done" before the response actually lands.
*
* CalculatingCard: full-page card (page-level loading states).
* CalculatingDialog: the same card without the page, for a tab whose header stays visible.
* CalculatingInline: compact block for in-place placeholders (tab/table bodies).
*/
@@ -58,27 +59,34 @@ export function CalculatingInline({
);
}
export function CalculatingCard({
title,
subtitle,
elapsedMs,
estimateMs,
}: {
interface CalculatingDialogProps {
title: string;
subtitle: string;
elapsedMs: number;
estimateMs: number;
}) {
}
/**
* The loading dialog itself (spinner, title, subtitle, progress) without a page around it, for
* a tab or section whose header stays visible while its body aggregates.
*/
export function CalculatingDialog({ title, subtitle, elapsedMs, estimateMs }: CalculatingDialogProps) {
return (
<div className="min-h-screen bg-[var(--lp-bg)] flex items-center justify-center p-4">
<div className="bg-white rounded-lg shadow-xl p-8 max-w-md w-full">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600 mx-auto"></div>
<h2 className="mt-4 text-xl font-semibold text-gray-900">{title}</h2>
<p className="mt-2 text-sm text-gray-600">{subtitle}</p>
<ProgressBarWithCaption elapsedMs={elapsedMs} estimateMs={estimateMs} />
</div>
<div className="bg-white rounded-lg shadow-xl p-8 max-w-md w-full">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600 mx-auto"></div>
<h2 className="mt-4 text-xl font-semibold text-gray-900">{title}</h2>
<p className="mt-2 text-sm text-gray-600">{subtitle}</p>
<ProgressBarWithCaption elapsedMs={elapsedMs} estimateMs={estimateMs} />
</div>
</div>
);
}
export function CalculatingCard(props: CalculatingDialogProps) {
return (
<div className="min-h-screen bg-[var(--lp-bg)] flex items-center justify-center p-4">
<CalculatingDialog {...props} />
</div>
);
}
@@ -0,0 +1,8 @@
/** The GitHub mark (Octicon), inherits the text color. */
export function GitHubIcon({ className = "w-4 h-4" }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
</svg>
);
}
@@ -0,0 +1,47 @@
import { GITHUB_REPO_URL, GITHUB_STARS, formatStarCount } from "@/utils/githubStars";
import { GitHubIcon } from "./GitHubIcon";
/**
* "Star us" pill for the public surface: [GitHub mark] label │ ★ count.
* The counter segment only renders when the deploy baked a star count in (utils/githubStars.ts).
* No hooks, so server components (Testimonials) and client components (LandingNavbar) share it.
*/
export function GitHubStarLink({
label,
track,
labelClassName,
}: {
label: string;
/** data-track id for the anonymous marketing click count (components/MarketingTracker.tsx). */
track?: string;
/** Lets a tight bar hide the word at some widths; the aria-label still names the link. */
labelClassName?: string;
}) {
return (
<a
href={GITHUB_REPO_URL}
data-track={track}
target="_blank"
rel="noopener noreferrer"
aria-label={
GITHUB_STARS !== null
? `Star Autopilot Monitor on GitHub (${GITHUB_STARS} stars)`
: "Star Autopilot Monitor on GitHub"
}
className="inline-flex items-stretch h-8 rounded-lg border border-[var(--lp-line)] bg-[var(--lp-surface)] text-[13px] font-medium text-[var(--lp-ink-soft)] hover:text-[var(--lp-ink)] hover:border-[var(--lp-ink-faint)] transition-colors overflow-hidden whitespace-nowrap"
>
<span className="inline-flex items-center gap-1.5 px-2.5">
<GitHubIcon className="w-[15px] h-[15px]" />
<span className={labelClassName}>{label}</span>
</span>
{GITHUB_STARS !== null && (
<span className="inline-flex items-center gap-1 px-2.5 border-l border-[var(--lp-line)] bg-[var(--lp-surface-2)] font-semibold text-[var(--lp-ink)]">
<svg className="w-3 h-3 text-[var(--lp-star)]" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 2.5l2.94 5.96 6.56.95-4.75 4.63 1.12 6.54L12 17.5l-5.87 3.08 1.12-6.54L2.5 9.41l6.56-.95z" />
</svg>
{formatStarCount(GITHUB_STARS)}
</span>
)}
</a>
);
}
@@ -0,0 +1,54 @@
"use client";
import { useEffect, useRef, type MouseEvent, type ReactNode } from "react";
import { trackEvent } from "@/lib/appInsights";
import {
MARKETING_CTA_CLICKED,
MARKETING_SECTION_VIEWED,
isSectionSeen,
trackIdOf,
} from "@/lib/clickTracking";
const THRESHOLDS = [0, 0.1, 0.2, 1 / 3];
/**
* Anonymous usage counts for one public marketing page: one event per click on an element marked
* data-track="<id>", and one per section marked data-track-section="<id>" the first time it is
* seen in this page load. `display: contents` keeps the page layout as it is, and the sections
* stay server components.
*/
export function MarketingTracker({ page, children }: { page: string; children: ReactNode }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const root = ref.current;
if (!root || typeof IntersectionObserver === "undefined") return;
const seen = new Set<string>();
const observer = new IntersectionObserver(
entries => {
for (const entry of entries) {
const section = (entry.target as HTMLElement).dataset.trackSection;
if (!section || seen.has(section) || !entry.isIntersecting) continue;
if (!isSectionSeen(entry.intersectionRatio, entry.intersectionRect.height, window.innerHeight)) continue;
seen.add(section);
observer.unobserve(entry.target);
trackEvent(MARKETING_SECTION_VIEWED, { page, section });
}
},
{ threshold: THRESHOLDS }
);
root.querySelectorAll<HTMLElement>("[data-track-section]").forEach(el => observer.observe(el));
return () => observer.disconnect();
}, [page]);
const onClick = (e: MouseEvent<HTMLDivElement>) => {
const button = trackIdOf(e.target as Element);
if (button) trackEvent(MARKETING_CTA_CLICKED, { page, button });
};
return (
<div ref={ref} className="contents" onClick={onClick}>
{children}
</div>
);
}
@@ -1,38 +1,41 @@
import { DOCS_URL } from "@/utils/config";
import { GITHUB_REPO_URL } from "@/utils/githubStars";
import { BrandMark } from "./BrandMark";
import { GitHubIcon } from "./GitHubIcon";
const LINK_COLUMNS = [
{
title: "Product",
links: [
{ label: "The Story", href: "/#story" },
{ label: "Capabilities", href: "/#features" },
{ label: "Compare", href: "/#comparison" },
{ label: "Plans", href: "/plans" },
{ label: "The Story", href: "/#story", track: "story" },
{ label: "Capabilities", href: "/#features", track: "capabilities" },
{ label: "Compare", href: "/#comparison", track: "compare" },
{ label: "AI analysis", href: "/ai/", track: "ai" },
{ label: "Plans", href: "/plans/", track: "plans" },
],
},
{
title: "Resources",
links: [
{ label: "Documentation", href: DOCS_URL, external: true },
{ label: "Help & Support", href: "/help" },
{ label: "Feedback", href: "https://github.com/okieselbach/AutopilotMonitor/issues", external: true },
{ label: "GitHub", href: "https://github.com/okieselbach/AutopilotMonitor", external: true },
{ label: "Documentation", href: DOCS_URL, external: true, track: "docs" },
{ label: "Help & Support", href: "/help/", track: "help" },
{ label: "Feedback", href: "https://github.com/okieselbach/AutopilotMonitor/issues", external: true, track: "feedback" },
{ label: "GitHub", href: GITHUB_REPO_URL, external: true, track: "github" },
],
},
{
title: "Company",
links: [
{ label: "About", href: "/about" },
{ label: "glueckkanja AG", href: "https://www.glueckkanja.com", external: true },
{ label: "About", href: "/about/", track: "about" },
{ label: "glueckkanja AG", href: "https://www.glueckkanja.com", external: true, track: "glueckkanja" },
],
},
{
title: "Legal",
links: [
{ label: "Privacy Policy", href: "/privacy" },
{ label: "Terms of Use", href: "/terms" },
{ label: "Imprint", href: "https://www.glueckkanja.com/en/imprint", external: true },
{ label: "Privacy Policy", href: "/privacy/", track: "privacy" },
{ label: "Terms of Use", href: "/terms/", track: "terms" },
{ label: "Imprint", href: "https://www.glueckkanja.com/en/imprint", external: true, track: "imprint" },
],
},
];
@@ -61,6 +64,7 @@ export function SiteFooter() {
<div className="flex items-center gap-3">
<a
href="https://www.linkedin.com/in/oliver-kieselbach/"
data-track="footer_linkedin"
target="_blank"
rel="noopener noreferrer"
className="text-[var(--lp-ink-faint)] hover:text-[var(--lp-accent-ink)] transition-colors"
@@ -71,15 +75,14 @@ export function SiteFooter() {
</svg>
</a>
<a
href="https://github.com/okieselbach/AutopilotMonitor"
href={GITHUB_REPO_URL}
data-track="footer_github_icon"
target="_blank"
rel="noopener noreferrer"
className="text-[var(--lp-ink-faint)] hover:text-[var(--lp-ink)] transition-colors"
title="GitHub"
>
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
</svg>
<GitHubIcon className="w-4 h-4" />
</a>
</div>
</div>
@@ -97,6 +100,7 @@ export function SiteFooter() {
<a
href={link.href}
{...(link.external ? { target: "_blank", rel: "noopener noreferrer" } : {})}
data-track={`footer_${link.track}`}
className="text-xs text-[var(--lp-ink-faint)] hover:text-[var(--lp-accent-ink)] transition-colors"
>
{link.label}
@@ -110,22 +114,11 @@ export function SiteFooter() {
</div>
{/* Bottom bar */}
<div className="mt-10 pt-5 border-t border-[var(--lp-line-soft)] flex flex-col sm:flex-row items-center justify-between gap-2">
<div className="mt-10 pt-5 border-t border-[var(--lp-line-soft)] text-center sm:text-left">
<p className="text-[11px] text-[var(--lp-ink-faint)]">
&copy; 2026 Autopilot Monitor. Built with ❤️ by Oliver Kieselbach.{" "}
<span className="inline-block">Hosted on Azure by glueckkanja AG.</span>
</p>
<p className="text-[11px] text-[var(--lp-ink-faint)]">
Open source. Star us on{" "}
<a
href="https://github.com/okieselbach/AutopilotMonitor"
target="_blank"
rel="noopener noreferrer"
className="text-[var(--lp-ink-soft)] hover:text-[var(--lp-accent-ink)] transition-colors"
>
GitHub
</a>
</p>
</div>
</div>
</footer>
@@ -1,18 +1,12 @@
"use client";
import { useState } from "react";
import type { CveExposureSummary, TopCve } from "@/utils/wire-types.generated";
import {
severityChipClass,
priorityChipClass,
KEV_BADGE_CLASS,
CONTEXT_PILL_CLASS,
formatEpss,
epssTitle,
priorityLabel,
PRIORITY_TITLE,
} from "@/lib/vulnerabilitySeverity";
import TruncatedLabel from "@/components/TruncatedLabel";
import type { CveExposureSummary } from "@/utils/wire-types.generated";
import { toggleFilter, type ExposureFilter } from "@/lib/vulnerabilityExposure";
import { CalculatingDialog } from "@/components/CalculatingCard";
import ExposureKpiRow from "@/components/vulnerability/ExposureKpiRow";
import SeverityPriorityCard from "@/components/vulnerability/SeverityPriorityCard";
import MostExposedCard from "@/components/vulnerability/MostExposedCard";
interface Props {
summary: CveExposureSummary | null;
@@ -24,27 +18,18 @@ interface Props {
onDaysChange?: (days: number) => void;
onRefresh?: () => void;
refreshing?: boolean;
/** Header title; the header row renders only with a title or controls. */
title?: string;
/** Elapsed/estimate of the running fetch (useFetchProgress); without it the loading state is plain text. */
progress?: { elapsedMs: number; estimateMs: number };
}
/**
* One active list filter: a severity band or a priority band, both lower-case wire values.
* Chips toggle it; clicking the active chip again clears it.
*/
type ListFilter = { kind: "severity" | "priority"; value: string } | null;
function matchesFilter(c: TopCve, filter: ListFilter): boolean {
if (!filter) return true;
const actual = filter.kind === "severity" ? c.cvssSeverity : c.priority;
return (actual || "").toLowerCase() === filter.value;
}
/**
* Read-only fleet/tenant vulnerability exposure: affected-device, CVE and priority KPIs, a
* severity and a priority breakdown (both filter the list), and the top CVEs ranked by affected
* devices. Shared by the GA admin section and the tenant-facing Software › Vulnerabilities tab so
* both render identical chips/CVE rows. The breakdown counts cover every CVE in the window while
* the list is top-N, so a filter can legitimately leave the list empty.
* Read-only fleet/tenant vulnerability exposure: headline KPIs, a severity donut and the
* remediation-priority ladder (both filter the list), and the most exposed products or CVEs.
* Shared by the tenant-facing Software › Vulnerabilities tab and the GA admin section. The
* breakdown counts cover every CVE in the window; the lists hold the entries on the most
* devices, every known-exploited entry and, under a filter, the band's own top entries.
*/
export default function VulnerabilityExposurePanel({
summary,
@@ -54,35 +39,98 @@ export default function VulnerabilityExposurePanel({
onDaysChange,
onRefresh,
refreshing = false,
title = "Vulnerability Exposure",
title,
progress,
}: Props) {
const [filter, setFilter] = useState<ExposureFilter>(null);
const hasFindings = summary != null && summary.distinctCves > 0;
const [filter, setFilter] = useState<ListFilter>(null);
const showHeader = title != null || onDaysChange != null || onRefresh != null;
const progressPercent = progress ? Math.min(95, (progress.elapsedMs / progress.estimateMs) * 100) : 0;
const toggleFilter = (kind: "severity" | "priority", value: string) =>
setFilter((prev) => (prev && prev.kind === kind && prev.value === value ? null : { kind, value }));
let body;
if (!hasFindings && loading) {
// Nothing worth keeping on screen: the loading dialog of the other aggregation pages.
body = progress ? (
<div className="flex justify-center py-10" aria-busy="true">
<CalculatingDialog
title="Calculating vulnerability exposure…"
subtitle={
showTenantCount
? "Aggregating the detected CVEs, affected devices and software across all tenants."
: "Aggregating the detected CVEs, affected devices and software."
}
elapsedMs={progress.elapsedMs}
estimateMs={progress.estimateMs}
/>
</div>
) : (
<div className="bg-white rounded-lg shadow p-8 text-center text-sm text-gray-500" aria-busy="true">
Loading…
</div>
);
} else if (!hasFindings) {
body = (
<div className="bg-white rounded-lg shadow p-8 text-center text-sm text-gray-500">
No vulnerability findings in this window. An empty result means no detected CVEs; it does not by itself confirm
the fleet is unaffected, because vulnerability scanning must be enabled.
</div>
);
} else {
// While a new window or scope loads, the previous figures stay (dimmed) so the lens, sort
// and open rows survive the refetch; a slim bar above them shows the fetch is alive.
body = (
<div aria-busy={loading} className="space-y-4">
{loading && progress && (
<div
role="progressbar"
aria-label="Updating vulnerability exposure"
aria-valuenow={Math.round(progressPercent)}
aria-valuemin={0}
aria-valuemax={100}
className="h-1 w-full overflow-hidden rounded-full bg-gray-200"
>
<div
className="h-full rounded-full bg-blue-600 transition-all duration-500 motion-reduce:transition-none"
style={{ width: `${progressPercent}%` }}
/>
</div>
)}
<div className={`space-y-4 ${loading ? "opacity-60" : ""}`}>
<ExposureKpiRow summary={summary!} showTenantCount={showTenantCount} />
const isActive = (kind: "severity" | "priority", value: string) =>
filter != null && filter.kind === kind && filter.value === value;
<div className="grid grid-cols-1 items-start gap-6 lg:grid-cols-5">
<SeverityPriorityCard
summary={summary!}
filter={filter}
onToggle={(kind, value) => setFilter((prev) => toggleFilter(prev, kind, value))}
/>
<MostExposedCard summary={summary!} filter={filter} onClearFilter={() => setFilter(null)} />
</div>
const visibleCves = hasFindings ? summary!.topCves.filter((c) => matchesFilter(c, filter)) : [];
const filterLabel = filter
? filter.kind === "priority"
? priorityLabel(filter.value) ?? filter.value
: filter.value.charAt(0).toUpperCase() + filter.value.slice(1)
: null;
<p className="text-xs text-gray-500">
CVSS from NVD, confirmed exploitation from the CISA KEV catalog, exploitation probability from FIRST EPSS.
</p>
{summary!.truncated && (
<p className="text-xs text-amber-700 dark:text-amber-400">
Counts are a lower bound: the underlying scan hit its cap. Narrow the window for exact figures.
</p>
)}
</div>
</div>
);
}
return (
<div className="bg-emerald-50 dark:bg-gray-700 border border-emerald-200 dark:border-emerald-600 rounded-lg p-4">
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
<h3 className="text-sm font-medium text-emerald-900 dark:text-emerald-100">{title}</h3>
{(onDaysChange || onRefresh) && (
<div className="space-y-4">
{showHeader && (
<div className="flex flex-wrap items-center justify-between gap-2">
{title ? <h3 className="text-base font-semibold text-gray-900">{title}</h3> : <span />}
<div className="flex items-center gap-2">
{onDaysChange && (
<select
value={days}
onChange={(e) => onDaysChange(Number(e.target.value))}
className="text-xs rounded-md border border-emerald-300 dark:border-emerald-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 px-2 py-1 focus:outline-none focus:ring-2 focus:ring-emerald-500"
className="rounded-md border border-gray-300 bg-white px-2 py-1 text-xs text-gray-900 focus:outline-none focus:ring-2 focus:ring-green-500"
aria-label="Time window in days"
>
<option value={7}>Last 7 days</option>
@@ -96,175 +144,15 @@ export default function VulnerabilityExposurePanel({
type="button"
onClick={onRefresh}
disabled={refreshing}
className="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md text-emerald-700 dark:text-emerald-300 border border-emerald-400 dark:border-emerald-600 hover:bg-emerald-100 dark:hover:bg-emerald-900/30 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
className="inline-flex items-center rounded-md border border-gray-300 bg-white px-2.5 py-1 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
>
{refreshing ? "Refreshing..." : "Refresh"}
</button>
)}
</div>
)}
</div>
{loading ? (
<div className="py-6 text-center text-sm text-emerald-800 dark:text-emerald-200">Loading…</div>
) : !hasFindings ? (
<div className="py-6 text-center text-sm text-emerald-800 dark:text-emerald-200">
No vulnerability findings in this window. An empty result means no detected CVEs — it does
not by itself confirm the fleet is unaffected (vulnerability scanning must be enabled).
</div>
) : (
<div className="space-y-4">
{/* KPI tiles — the priority ladder (Act = KEV by definition, Attend = next tier) sits next to the totals */}
<div className={`grid grid-cols-2 ${showTenantCount ? "sm:grid-cols-5" : "sm:grid-cols-4"} gap-3`}>
<Kpi value={summary!.totalAffectedSessions} label="Affected devices" />
<Kpi value={summary!.distinctCves} label="Distinct CVEs" />
<Kpi value={summary!.priorityBreakdown.act} label="Act (Known-Exploited)" title={PRIORITY_TITLE} />
<Kpi value={summary!.priorityBreakdown.attend} label="Attend" title={PRIORITY_TITLE} />
{showTenantCount && <Kpi value={summary!.totalAffectedTenants ?? 0} label="Affected tenants" />}
</div>
{/* Severity + priority breakdowns — every chip filters the list below */}
<div className="flex flex-wrap items-center gap-2">
{([
["Critical", summary!.severityBreakdown.critical],
["High", summary!.severityBreakdown.high],
["Medium", summary!.severityBreakdown.medium],
["Low", summary!.severityBreakdown.low],
] as Array<[string, number]>).map(([label, count]) => (
<FilterChip
key={label}
label={label}
count={count}
className={severityChipClass(label)}
active={isActive("severity", label.toLowerCase())}
onClick={() => toggleFilter("severity", label.toLowerCase())}
title={`Show only ${label} CVEs`}
/>
))}
<span className="w-px h-4 bg-emerald-300 dark:bg-emerald-700 mx-1" aria-hidden="true" />
{([
["Act", summary!.priorityBreakdown.act],
["Attend", summary!.priorityBreakdown.attend],
["Track", summary!.priorityBreakdown.track],
] as Array<[string, number]>).map(([label, count]) => (
<FilterChip
key={label}
label={label}
count={count}
className={priorityChipClass(label)}
active={isActive("priority", label.toLowerCase())}
onClick={() => toggleFilter("priority", label.toLowerCase())}
title={PRIORITY_TITLE}
/>
))}
</div>
{/* Top CVEs */}
<div>
<div className="flex flex-wrap items-center gap-2 mb-2">
<span className="text-xs font-medium text-emerald-800 dark:text-emerald-200">Top CVEs by affected devices</span>
{filterLabel && (
<>
<span className="text-xs text-emerald-700 dark:text-emerald-300">· {filterLabel} only</span>
<button
type="button"
onClick={() => setFilter(null)}
className="text-xs text-emerald-700 dark:text-emerald-300 underline hover:text-emerald-900 dark:hover:text-emerald-100"
>
Clear filter
</button>
</>
)}
</div>
{visibleCves.length === 0 ? (
<div className="py-4 text-center text-xs text-emerald-800 dark:text-emerald-200">
None of the top {summary!.topCves.length} CVEs is {filterLabel}. The chip counts cover every CVE in the
window; the list shows only the CVEs affecting the most devices.
</div>
) : (
<div className="space-y-1.5">
{visibleCves.map((c) => (
<div key={c.cveId} className="flex items-center justify-between gap-3 bg-white dark:bg-gray-800 border border-emerald-100 dark:border-emerald-800 rounded-md px-3 py-2">
<div className="min-w-0">
<div className="flex items-center gap-2">
<a href={`https://nvd.nist.gov/vuln/detail/${encodeURIComponent(c.cveId)}`} target="_blank" rel="noopener noreferrer"
className="font-mono text-xs text-emerald-700 dark:text-emerald-300 underline hover:text-emerald-900 dark:hover:text-emerald-100">
{c.cveId}
</a>
<span className={`inline-flex items-center px-1.5 py-0.5 rounded border text-[10px] font-medium ${severityChipClass(c.cvssSeverity)}`}>
{c.cvssSeverity || "Unknown"}{c.cvssScore > 0 ? ` ${c.cvssScore.toFixed(1)}` : ""}
</span>
{c.isKev && (
<span className={`inline-flex items-center px-1.5 py-0.5 rounded border text-[10px] font-semibold ${KEV_BADGE_CLASS}`}>KEV</span>
)}
{c.epssScore != null && (
<span className={CONTEXT_PILL_CLASS} title={epssTitle(c.epssScore)}>{formatEpss(c.epssScore)}</span>
)}
{priorityLabel(c.priority) && (
<span className={CONTEXT_PILL_CLASS} title={PRIORITY_TITLE}>{priorityLabel(c.priority)}</span>
)}
</div>
{c.sampleSoftware.length > 0 && (
<TruncatedLabel text={c.sampleSoftware.join(", ")} className="block text-[11px] text-gray-500 dark:text-gray-400 mt-0.5" />
)}
</div>
<div className="text-right flex-shrink-0">
<div className="text-sm font-semibold text-emerald-900 dark:text-emerald-100">{c.affectedSessions.toLocaleString()}</div>
<div className="text-[10px] text-emerald-700 dark:text-emerald-300">devices</div>
</div>
</div>
))}
</div>
)}
</div>
{summary!.truncated && (
<div className="text-[11px] text-amber-700 dark:text-amber-400">
Counts are a lower bound — the underlying scan hit its cap. Narrow the window for exact figures.
</div>
)}
</div>
)}
{body}
</div>
);
}
function Kpi({ value, label, title }: { value: number; label: string; title?: string }) {
return (
<div className="bg-white dark:bg-gray-800 border border-emerald-200 dark:border-emerald-700 rounded-lg p-3" title={title}>
<div className="text-2xl font-bold text-emerald-900 dark:text-emerald-100">{value.toLocaleString()}</div>
<div className="text-xs text-emerald-700 dark:text-emerald-300 mt-0.5">{label}</div>
</div>
);
}
/** A breakdown chip that doubles as a list-filter toggle; the active one carries a ring. */
function FilterChip({
label,
count,
className,
active,
onClick,
title,
}: {
label: string;
count: number;
className: string;
active: boolean;
onClick: () => void;
title: string;
}) {
return (
<button
type="button"
onClick={onClick}
aria-pressed={active}
title={title}
className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full border text-xs font-medium transition-shadow ${className} ${
active ? "ring-2 ring-emerald-500 ring-offset-1 ring-offset-emerald-50 dark:ring-offset-gray-700" : "hover:ring-1 hover:ring-emerald-400"
}`}
>
{label}: {count.toLocaleString()}
</button>
);
}
@@ -0,0 +1,68 @@
import { describe, it, expect, vi, beforeAll, afterAll } from "vitest";
import { createElement, type ComponentType } from "react";
import { renderToStaticMarkup } from "react-dom/server";
// LandingNavbar and LoginButton read the auth context; the public pages render signed out.
vi.mock("@/contexts/AuthContext", () => ({
useAuth: () => ({ login: async () => undefined, isAuthenticated: false, user: null, getAccessToken: async () => null }),
}));
// AuthGate only redirects signed-in visitors (it needs the app router) and renders no links.
vi.mock("@/components/landing/AuthGate", () => ({ AuthGate: () => null }));
import LandingPage from "@/app/page";
import GetStartedPage from "@/app/get-started/page";
import AiPage from "@/app/ai/page";
import AboutPage from "@/app/about/page";
import PlansPage from "@/app/plans/page";
import BuyPage from "@/app/buy/page";
import HelpPage from "@/app/help/page";
import PrivacyPage from "@/app/privacy/page";
import TermsPage from "@/app/terms/page";
/**
* The export serves each page as <path>/index.html, and the host answers a link without the
* trailing slash with a 301 first. <Link> appends the slash itself; a plain <a> has to carry it.
*/
const PAGES: Record<string, ComponentType> = {
landing: LandingPage,
"get-started": GetStartedPage,
ai: AiPage,
about: AboutPage,
plans: PlansPage,
buy: BuyPage,
help: HelpPage,
privacy: PrivacyPage,
terms: TermsPage,
};
// The build inlines trailingSlash as __NEXT_TRAILING_SLASH; without it <Link> would drop the slash here.
beforeAll(() => {
process.env.__NEXT_TRAILING_SLASH = "true";
});
afterAll(() => {
delete process.env.__NEXT_TRAILING_SLASH;
});
const internalHrefs = (html: string) => [...html.matchAll(/<a\b[^>]*?\shref="(\/[^"]*)"/g)].map(m => m[1]);
/** A page path without its trailing slash; the root and files such as /llms.txt are exempt. */
const missesSlash = (href: string) => {
const path = href.split(/[?#]/)[0];
return path !== "/" && !path.endsWith("/") && !/\.[a-z0-9]+$/i.test(path);
};
describe("marketing page links", () => {
for (const [name, Page] of Object.entries(PAGES)) {
it(`${name}: every internal link ends with a slash`, () => {
const hrefs = internalHrefs(renderToStaticMarkup(createElement(Page)));
expect(hrefs.length).toBeGreaterThan(0);
expect(hrefs.filter(missesSlash)).toEqual([]);
});
}
it("treats a bare page path as missing its slash, the root and files not", () => {
expect(["/plans", "/terms#cookies", "/help?x=1"].map(missesSlash)).toEqual([true, true, true]);
expect(["/plans/", "/", "/#story", "/llms.txt", "/ai/#architecture"].map(missesSlash)).toEqual([false, false, false, false, false]);
});
});
@@ -0,0 +1,96 @@
import { describe, it, expect, vi } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { createElement, type ComponentType } from "react";
import { renderToStaticMarkup } from "react-dom/server";
// LandingNavbar and LoginButton read the auth context; the public pages render signed out.
vi.mock("@/contexts/AuthContext", () => ({
useAuth: () => ({ login: async () => undefined, isAuthenticated: false, user: null, getAccessToken: async () => null }),
}));
// AuthGate only redirects signed-in visitors (it needs the app router) and renders no links.
vi.mock("@/components/landing/AuthGate", () => ({ AuthGate: () => null }));
import LandingPage from "@/app/page";
import GetStartedPage from "@/app/get-started/page";
import AiPage from "@/app/ai/page";
import robots from "@/app/robots";
import sitemap from "@/app/sitemap";
import { QUESTIONS } from "@/components/ai/questions";
import { TRACK_ID_PATTERN, isSectionSeen, trackIdOf } from "@/lib/clickTracking";
import { sitePageUrl } from "@/utils/config";
/**
* The UX report counts clicks and section views on the marketing pages (D-305). A link or button
* without a data-track id is invisible there, so every one carries an id; the What's new bell is
* the exception, it sends whats_new_opened itself.
*/
const render = (Page: ComponentType) => renderToStaticMarkup(createElement(Page));
const trackIds = (html: string) => [...html.matchAll(/data-track="([^"]+)"/g)].map(m => m[1]);
const sectionIds = (html: string) => [...html.matchAll(/data-track-section="([^"]+)"/g)].map(m => m[1]);
const untracked = (html: string) =>
[...html.matchAll(/<(?:a|button)\b[^>]*>/g)]
.map(m => m[0])
.filter(tag => !/\sdata-track="/.test(tag) && !/aria-label="What&#x27;s new"/.test(tag));
const PAGES: { name: string; Page: ComponentType; sections: string[] }[] = [
{
name: "landing",
Page: LandingPage,
sections: ["hero", "stats", "just_ask", "story", "capabilities", "comparison", "how_it_works", "testimonials", "final_cta"],
},
{ name: "get-started", Page: GetStartedPage, sections: ["steps", "signup"] },
{ name: "ai", Page: AiPage, sections: ["hero", "structured", "questions", "architecture", "connect", "closing"] },
];
describe("marketing page tracking", () => {
for (const { name, Page, sections } of PAGES) {
it(`${name}: every link and button carries a valid, unique data-track id`, () => {
const html = render(Page);
expect(untracked(html)).toEqual([]);
const ids = trackIds(html);
for (const id of ids) expect(id).toMatch(TRACK_ID_PATTERN);
expect(ids.filter((id, i) => ids.indexOf(id) !== i)).toEqual([]);
});
it(`${name}: marks its sections`, () => {
expect(sectionIds(render(Page))).toEqual(sections);
});
}
it("the landing links to the AI page from the navbar, Then just ask and the footer", () => {
const ids = trackIds(render(LandingPage));
expect(ids).toEqual(expect.arrayContaining(["nav_ai", "just_ask_ai", "footer_ai"]));
});
it("the AI page carries every question text in its static HTML", () => {
const html = render(AiPage);
const escape = (text: string) => text.replace(/&/g, "&amp;").replace(/'/g, "&#x27;");
for (const q of QUESTIONS) expect(html, q.id).toContain(escape(q.text));
});
it("the AI page is in the sitemap, robots.txt and llms.txt", () => {
expect(sitemap().map(e => e.url)).toContain(sitePageUrl("/ai"));
const allow = robots().rules;
expect(Array.isArray(allow) ? allow[0].allow : allow.allow).toContain("/ai");
const llms = readFileSync(join(__dirname, "..", "..", "public", "llms.txt"), "utf-8");
expect(llms).toContain(sitePageUrl("/ai"));
});
});
describe("clickTracking helpers", () => {
it("reads the id of the nearest marked element", () => {
const target = { closest: (selector: string) => (selector === "[data-track]" ? { getAttribute: () => "nav_ai" } : null) };
expect(trackIdOf(target)).toBe("nav_ai");
expect(trackIdOf({ closest: () => null })).toBeNull();
expect(trackIdOf(null)).toBeNull();
});
it("counts a section once a third is visible, or half the viewport for tall sections", () => {
expect(isSectionSeen(0.34, 100, 800)).toBe(true);
expect(isSectionSeen(0.2, 420, 800)).toBe(true);
expect(isSectionSeen(0.2, 200, 800)).toBe(false);
expect(isSectionSeen(0, 0, 0)).toBe(false);
});
});

Some files were not shown because too many files have changed in this diff Show More