mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-24 20:53:06 +00:00
Compare commits
173 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8cb5d42edc | |||
| fa637369e1 | |||
| edf30d35e0 | |||
| 3b4228e3a1 | |||
| a029d69d5e | |||
| daae1ce1fa | |||
| d90cf24508 | |||
| 32f1fd4132 | |||
| ffb09e60fa | |||
| f920b6228e | |||
| 1765773116 | |||
| 5c7295019b | |||
| a0ad769231 | |||
| 64da9f850b | |||
| 5dae21968b | |||
| 59897dfbd8 | |||
| f4551ea1ed | |||
| e816c92b88 | |||
| a16a70fba5 | |||
| 1b2bdd8f35 | |||
| 942bd86238 | |||
| 7a920049ca | |||
| 2eeb4da950 | |||
| 20a80cbdc6 | |||
| c59e65ee0a | |||
| 89aa9e1f10 | |||
| 2d3700cfaf | |||
| 5a182f3f16 | |||
| 889b843d6d | |||
| 9b91119239 | |||
| 1e74d67da9 | |||
| ed013bbdda | |||
| 4b40619d1d | |||
| 3ce1f2b036 | |||
| 673f045212 | |||
| df640e3684 | |||
| 59bea9d888 | |||
| e2c91afda2 | |||
| eb47c4d69a | |||
| 91d56f2bbb | |||
| 12b847360c | |||
| 2e736f40ad | |||
| 9c3e5ecb30 | |||
| 27ce316206 | |||
| 7280b61d28 | |||
| 79f1ecd378 | |||
| b6791d37e0 | |||
| 4f1b4f8c03 | |||
| 869580c9df | |||
| 1a96cd20da | |||
| 8e637cf86a | |||
| 93c6e1facb | |||
| 4a4bbc056a | |||
| c59b366560 | |||
| d0aded5401 | |||
| 8f9c683b7c | |||
| e82878af57 | |||
| d60e858e95 | |||
| f6ce9ae0a0 | |||
| b4f26401f5 | |||
| 2b5004fb33 | |||
| 00f4cb1f26 | |||
| e091e50862 | |||
| 27ce07b111 | |||
| f06fe5afc0 | |||
| 37e920237c | |||
| 7279650772 | |||
| d8ab70b166 | |||
| fb8703a4c6 | |||
| ac3fa8b2b6 | |||
| efcb4f9ca1 | |||
| 7a7a31e8e3 | |||
| 3fdcbabd48 | |||
| b2e8c7627f | |||
| bd08d13011 | |||
| 10c69f592e | |||
| fe0b2dc7fe | |||
| a0f007fd43 | |||
| 1b27babd17 | |||
| 100d2242fa | |||
| 089b1b38fd | |||
| ac465839a5 | |||
| ef280b7bb5 | |||
| 233737f333 | |||
| 909904e928 | |||
| 59ab47de8c | |||
| f252a0709f | |||
| d6d9638981 | |||
| 020248fbda | |||
| a06a0dbfff | |||
| 96c24e0688 | |||
| c156350183 | |||
| 15b25ff509 | |||
| 5163d7d6a0 | |||
| 9fd343d328 | |||
| aef88f3337 | |||
| 12af1d6c76 | |||
| 5433bff3db | |||
| 355509aa7c | |||
| 7fb78a7e29 | |||
| bfd8d58142 | |||
| 8ad472d1bc | |||
| fc5e2cd751 | |||
| 9540791441 | |||
| 058da1627f | |||
| cb9b3fe404 | |||
| 12315b2f2d | |||
| 0a4a051866 | |||
| f47d961947 | |||
| c701d0d694 | |||
| d4a3edf849 | |||
| e164eac1eb | |||
| c81591b498 | |||
| d8c03d9d95 | |||
| ffb133f0b9 | |||
| b3fe321f0d | |||
| 69d210c51d | |||
| 06a88e9897 | |||
| aee30f68e8 | |||
| 3db9a884de | |||
| 0037b8cb12 | |||
| 205b13dbb9 | |||
| b938a03367 | |||
| d474c2be9f | |||
| 96390beeb9 | |||
| fe63a0a352 | |||
| 2e36e9c234 | |||
| b83aa6d97d | |||
| f42fcbcb3c | |||
| f70ba354f8 | |||
| fc17047290 | |||
| 7bbc2cbddf | |||
| 9a78daa880 | |||
| 5d532d3dbc | |||
| a22c26eb9d | |||
| b84c467255 | |||
| 53124e94a6 | |||
| 838068fd31 | |||
| 71282f3556 | |||
| 7080dcc45a | |||
| 5a62714dc2 | |||
| c930d18f1e | |||
| 583c81c9a8 | |||
| 483ec8b8e0 | |||
| 328446864a | |||
| 106480ef52 | |||
| d3a45f958d | |||
| 6657c6b9c0 | |||
| 6c5e2fd921 | |||
| 65842b87bf | |||
| b323c52364 | |||
| 321a6efc81 | |||
| 5ecb2a998b | |||
| bb6df93b51 | |||
| 096a049deb | |||
| b9caf524c3 | |||
| 197de1d718 | |||
| 18d4f08f2b | |||
| ddf450d87d | |||
| e3b2113365 | |||
| 6a85f45604 | |||
| a2d1aedcad | |||
| e955faa97e | |||
| 2b755bf99a | |||
| ce1162a055 | |||
| 447786b447 | |||
| 2b4dbe087a | |||
| 6804bcfd4e | |||
| d2221eb0b9 | |||
| 9ac6de7c7d | |||
| f5613be495 | |||
| 819b6c8e4f | |||
| 9c1fb07f33 |
@@ -30,6 +30,7 @@
|
||||
- Stage explicit file lists; never `git add -A` or a directory. Pushing is the user's call.
|
||||
- New API responses need a typed DTO plus the parity fact. MCP vocabularies are generated from the wire types, never retyped.
|
||||
- Every route belongs in the route policy catalog; every new event type goes into the MCP resource catalog.
|
||||
- Workflow files under `.github/` go through zizmor before they are committed (`zizmor .` from the repository root, findings from severity low on): fix every finding or ignore it in `zizmor.yml` with a reason. The `zizmor` job in `action-pins.yml` runs the same check on every push.
|
||||
- The about, terms and privacy pages under `src/Web/autopilot-monitor-web/app/` state facts customers rely on: verify every claim against the code before writing it and update them in the same change as the fact they describe.
|
||||
|
||||
## Code Quality
|
||||
|
||||
+1
-1
Submodule .claude/commands updated: b390397891...2ace35ae7d
@@ -1,8 +1,8 @@
|
||||
# CodeQL configuration.
|
||||
#
|
||||
# The default query suites stay active — this file only filters out two C# queries
|
||||
# that fire structurally on this codebase, where the flagged behavior is the feature,
|
||||
# not a defect:
|
||||
# The default query suites stay active — this file only filters out queries that
|
||||
# fire structurally on this codebase, where the flagged behavior is the feature
|
||||
# or the protection exists in a form the query cannot see:
|
||||
#
|
||||
# cs/exposure-of-sensitive-information
|
||||
# Audit and operational logs record WHO performed an action (actor UPN / email)
|
||||
@@ -15,10 +15,20 @@
|
||||
# key. The IP is an identifier for throttling, not a secret at rest; storing it in
|
||||
# the in-memory / table rate-limit key is by design.
|
||||
#
|
||||
# js/missing-rate-limiting
|
||||
# Only the MCP server has Express routes. Every one that does work is throttled by
|
||||
# our own limiters (oauthRateLimit / oauthTokenRateLimit on /oauth/*, accessGuard
|
||||
# on /mcp); /health and the OAuth discovery documents return static JSON.
|
||||
# The query only recognizes limiters from npm packages (express-rate-limit and
|
||||
# similar) and flags a route handler as soon as it calls a function named
|
||||
# like *auth*, *login* or *verify*. So it reports throttled and unthrottled
|
||||
# routes the same way, and every alert it ever raised was a false positive. The
|
||||
# coverage check it stood in for is a test: every OAuth router route must carry
|
||||
# a limiter or be named as exempt (MCP oauth-rate-limit.test.ts).
|
||||
#
|
||||
# Genuine one-off false positives from OTHER queries (e.g. an open-redirect the taint
|
||||
# model can't see is allow-listed, a rate-limited route it doesn't recognize) are
|
||||
# dismissed individually in the Security tab so those queries stay sharp — they are
|
||||
# NOT suppressed here.
|
||||
# model can't see is allow-listed) are dismissed individually in the Security tab so
|
||||
# those queries stay sharp — they are NOT suppressed here.
|
||||
#
|
||||
# Log-injection (cs/log-forging) is deliberately NOT filtered: user-controlled values
|
||||
# are sanitized at the sink via Helpers/LogSanitizer, so the query stays useful for
|
||||
@@ -29,3 +39,5 @@ query-filters:
|
||||
id: cs/exposure-of-sensitive-information
|
||||
- exclude:
|
||||
id: cs/cleartext-storage-of-sensitive-information
|
||||
- exclude:
|
||||
id: js/missing-rate-limiting
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
version: 2
|
||||
|
||||
# Cooldown: a version is proposed only once it has been public for 7 days, so a
|
||||
# release that is yanked or found malicious within its first week never reaches a
|
||||
# PR. Security updates are exempt from the cooldown by Dependabot's own rules.
|
||||
#
|
||||
# Grouping: every ecosystem gets one batched PR for minor/patch version
|
||||
# updates and one batched PR for security updates. Groups apply to version
|
||||
# updates only by default, so the security-updates groups are declared
|
||||
@@ -10,6 +14,8 @@ updates:
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
dotnet:
|
||||
@@ -23,6 +29,8 @@ updates:
|
||||
directory: /src/Web/autopilot-monitor-web
|
||||
schedule:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
web:
|
||||
@@ -41,6 +49,8 @@ updates:
|
||||
directory: /src/McpServer/autopilot-monitor-mcp
|
||||
schedule:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
mcp:
|
||||
@@ -55,6 +65,22 @@ updates:
|
||||
- dependency-name: '*'
|
||||
update-types: ['version-update:semver-major']
|
||||
|
||||
# Validator tooling for rules/ (ajv-cli); combine-rules.yml installs it from this
|
||||
# lockfile with contents:write in hand, so the pins must not go stale.
|
||||
- package-ecosystem: npm
|
||||
directory: /rules/scripts
|
||||
schedule:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
rules-tooling:
|
||||
patterns: ['*']
|
||||
rules-tooling-security:
|
||||
applies-to: security-updates
|
||||
patterns: ['*']
|
||||
|
||||
# Every action is referenced by commit SHA with the version in a trailing comment;
|
||||
# action-pins.yml fails any workflow change that reintroduces a mutable tag. Dependabot
|
||||
# is what keeps those pins current: it rewrites the SHA and the comment together, so the
|
||||
@@ -63,6 +89,8 @@ updates:
|
||||
directory: /
|
||||
schedule:
|
||||
interval: monthly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
groups:
|
||||
actions:
|
||||
patterns: ['*']
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
name: Action Pin Gate
|
||||
name: Workflow gates
|
||||
|
||||
# Two checks over the workflow files themselves:
|
||||
# * verify-pins -- every third-party action is referenced by a full commit SHA plus a
|
||||
# version comment (stricter than zizmor's unpinned-uses audit).
|
||||
# * zizmor -- static analysis of every workflow (permissions, credential
|
||||
# persistence, template injection, ...). Configuration and the
|
||||
# reasoned ignores live in zizmor.yml at the repository root; the
|
||||
# same run is expected locally before a workflow change is committed.
|
||||
#
|
||||
# Every third-party action must be referenced by a full commit SHA, never by a tag.
|
||||
# Tags are mutable: whoever controls an action repository can repoint v4 at new code,
|
||||
# and that code runs inside jobs that hold the code-signing identity, the storage
|
||||
@@ -8,7 +16,8 @@ name: Action Pin Gate
|
||||
#
|
||||
# Lives in its own workflow rather than in ci.yml: CI deliberately ignores changes to
|
||||
# the other workflow files, so a guard placed there would stay silent for exactly the
|
||||
# commits it needs to inspect.
|
||||
# commits it needs to inspect. Dependabot's action-pin PRs are the main customer: they
|
||||
# rewrite workflow files without anyone running zizmor locally.
|
||||
#
|
||||
# Like CI, this reports rather than blocks: main is deliberately unprotected, so a red
|
||||
# run is a signal to act on, not a merge barrier. Making it binding means adding
|
||||
@@ -22,10 +31,10 @@ name: Action Pin Gate
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['.github/workflows/**']
|
||||
paths: ['.github/workflows/**', '.github/dependabot.yml', 'zizmor.yml']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['.github/workflows/**']
|
||||
paths: ['.github/workflows/**', '.github/dependabot.yml', 'zizmor.yml']
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -37,15 +46,18 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Every third-party action is pinned to a SHA
|
||||
run: |
|
||||
set -uo pipefail
|
||||
failed=0
|
||||
while IFS=: read -r file line ref; do
|
||||
# Reusable workflows from this repository move with the commit that calls
|
||||
# them, so there is nothing to pin.
|
||||
case "$ref" in ./*) continue ;; esac
|
||||
# Reusable workflows from this repository (workspace-relative ./ or the
|
||||
# self-repository form $/) move with the commit that calls them, so there is
|
||||
# nothing to pin.
|
||||
case "$ref" in ./*|\$/*) continue ;; esac
|
||||
|
||||
if [[ "$ref" =~ ^[^@]+@[0-9a-f]{40}[[:space:]]+#[[:space:]]*[^[:space:]] ]]; then
|
||||
printf 'ok %s:%s %s\n' "$file" "$line" "$ref"
|
||||
@@ -68,3 +80,24 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
echo "All action references are pinned to commit SHAs."
|
||||
|
||||
zizmor:
|
||||
name: zizmor audit
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write # SARIF upload: findings land in the Code scanning tab next to CodeQL
|
||||
actions: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# zizmor itself is version-pinned like every other tool here; bump it together with
|
||||
# the local install so the gate and the pre-commit run agree on the finding set.
|
||||
# Informational findings (template expansion of our own step outputs in pwsh) are
|
||||
# visible locally but do not fail the gate.
|
||||
- uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4
|
||||
with:
|
||||
version: 1.30.1
|
||||
min-severity: low
|
||||
|
||||
@@ -19,6 +19,8 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Pester 5+
|
||||
shell: powershell
|
||||
|
||||
@@ -73,6 +73,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Every released build is signed; a missing variable stops the run before a build
|
||||
# number is burnt.
|
||||
@@ -91,7 +93,7 @@ jobs:
|
||||
# are bound to the ref, so this job must never be given an `environment:` -- that would
|
||||
# change the OIDC subject claim and break both logins.
|
||||
- name: Login to Azure (code-signing identity)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
@@ -114,7 +116,7 @@ jobs:
|
||||
# well inside the token lifetime. Only the legacy mirror still needs a SAS: that account
|
||||
# lives in the pre-migration tenant, where this principal has no identity.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
|
||||
@@ -41,6 +41,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# The loader executes as SYSTEM on every enrolling device — a parse error or
|
||||
# non-ASCII mojibake (PS 5.1 codepage roulette) must fail the build, not the fleet.
|
||||
@@ -86,7 +88,7 @@ jobs:
|
||||
# are bound to the ref, so this job must never be given an `environment:` -- that would
|
||||
# change the OIDC subject claim and break both logins.
|
||||
- name: Login to Azure (code-signing identity)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
@@ -105,7 +107,7 @@ jobs:
|
||||
|
||||
# The blob upload below is authorized by this federated identity, not by a SAS.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
|
||||
@@ -24,6 +24,7 @@ on:
|
||||
- 'infra/**'
|
||||
- '.claude/**'
|
||||
- '.gitmodules'
|
||||
- 'zizmor.yml'
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
@@ -57,6 +58,7 @@ on:
|
||||
- 'infra/**'
|
||||
- '.claude/**'
|
||||
- '.gitmodules'
|
||||
- 'zizmor.yml'
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
@@ -97,6 +99,8 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
|
||||
with:
|
||||
@@ -128,6 +132,8 @@ jobs:
|
||||
working-directory: src/Web/autopilot-monitor-web
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
@@ -162,6 +168,8 @@ jobs:
|
||||
working-directory: src/McpServer/autopilot-monitor-mcp
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
@@ -196,6 +204,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
@@ -217,6 +227,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
|
||||
@@ -17,6 +17,7 @@ on:
|
||||
- 'infra/**'
|
||||
- '.claude/**'
|
||||
- '.gitmodules'
|
||||
- 'zizmor.yml'
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
@@ -48,6 +49,7 @@ on:
|
||||
- 'infra/**'
|
||||
- '.claude/**'
|
||||
- '.gitmodules'
|
||||
- 'zizmor.yml'
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
@@ -103,6 +105,8 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
|
||||
if: matrix.language == 'csharp'
|
||||
@@ -110,7 +114,7 @@ jobs:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
|
||||
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
@@ -121,6 +125,6 @@ jobs:
|
||||
run: dotnet build AutopilotMonitor.sln --configuration Release
|
||||
|
||||
- name: Analyze
|
||||
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
|
||||
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
|
||||
with:
|
||||
category: /language:${{ matrix.language }}
|
||||
|
||||
@@ -30,11 +30,16 @@ jobs:
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
# Exact versions and no lifecycle scripts: this job holds contents:write and pushes to
|
||||
# Lockfile and no lifecycle scripts: this job holds contents:write and pushes to
|
||||
# main, so an install-time script from a hijacked package would run with a token that
|
||||
# can rewrite the repository. ajv is pure JS and needs no install hooks.
|
||||
- name: Install ajv-cli
|
||||
run: npm install -g --ignore-scripts ajv-cli@5.0.0 ajv-formats@3.0.1
|
||||
# can rewrite the repository. rules/scripts/package-lock.json pins ajv-cli, ajv-formats
|
||||
# and every transitive package (Dependabot keeps it current); ajv is pure JS and
|
||||
# needs no install hooks.
|
||||
- name: Install ajv-cli from the lockfile
|
||||
working-directory: rules/scripts
|
||||
run: |
|
||||
npm ci --ignore-scripts
|
||||
echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Validate Gather Rules
|
||||
run: |
|
||||
|
||||
@@ -20,9 +20,11 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
|
||||
@@ -27,6 +27,8 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# The published customer documentation lives in its own PUBLIC repo and is
|
||||
# baked into the image as the search_docs corpus (see the Dockerfile). No
|
||||
@@ -38,6 +40,7 @@ jobs:
|
||||
- name: Check out documentation bundle
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
repository: autopilotmonitor/autopilotmonitor-docs
|
||||
path: mcp-docs
|
||||
|
||||
@@ -46,7 +49,7 @@ jobs:
|
||||
run: echo "sha=$(git -C mcp-docs rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
@@ -77,7 +80,7 @@ jobs:
|
||||
"short_sha=$shortSha" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: Login to ACR
|
||||
run: az acr login --name ${{ env.ACR_NAME }}
|
||||
run: az acr login --name "$ACR_NAME"
|
||||
|
||||
- name: Build and push container image
|
||||
run: |
|
||||
@@ -87,17 +90,17 @@ jobs:
|
||||
--build-arg BUILD_NUMBER=${{ steps.version.outputs.build_number }} \
|
||||
--build-arg BUILD_COMMIT=${{ steps.version.outputs.short_sha }} \
|
||||
--build-arg BUILD_UTC=${{ steps.version.outputs.build_utc }} \
|
||||
-t ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }}:${{ env.IMAGE_TAG }} \
|
||||
-t ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }}:latest \
|
||||
-t "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME:$IMAGE_TAG" \
|
||||
-t "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME:latest" \
|
||||
.
|
||||
docker push ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }} --all-tags
|
||||
docker push "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME" --all-tags
|
||||
|
||||
- name: Deploy to Container App
|
||||
run: |
|
||||
az containerapp update \
|
||||
--name ${{ env.CONTAINER_APP_NAME }} \
|
||||
--resource-group ${{ env.RESOURCE_GROUP }} \
|
||||
--image ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }}:${{ env.IMAGE_TAG }}
|
||||
--name "$CONTAINER_APP_NAME" \
|
||||
--resource-group "$RESOURCE_GROUP" \
|
||||
--image "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME:$IMAGE_TAG"
|
||||
|
||||
# `az containerapp update` returns once the revision is provisioned, not once
|
||||
# it serves traffic — and with minReplicas=0 the first request also pays a cold
|
||||
|
||||
@@ -37,13 +37,14 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
lfs: false
|
||||
fetch-depth: 0 # Full history needed for git-based sitemap lastmod dates
|
||||
|
||||
# Only the version manifest at the very end needs Azure; logging in here rather than
|
||||
# next to that step keeps a credential problem from surfacing after a live deploy.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
@@ -58,6 +59,7 @@ jobs:
|
||||
- name: Check out documentation bundle
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
repository: autopilotmonitor/autopilotmonitor-docs
|
||||
path: whats-new-docs
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -3,6 +3,9 @@ name: IndexNow Notify (Bing/Yandex)
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
# The job only talks to public endpoints; it never needs a repository token.
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
name: Federated login + read check
|
||||
steps:
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
|
||||
@@ -25,5 +25,6 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# $/ is the self-repository form: this repository at the running commit.
|
||||
gates:
|
||||
uses: ./.github/workflows/bootstrap-script-gates.yml
|
||||
uses: $/.github/workflows/bootstrap-script-gates.yml
|
||||
|
||||
@@ -26,7 +26,6 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # OIDC federated login for the storage writes (secret-less)
|
||||
|
||||
# Shared with build-agent.yml: a script publish and an agent release both touch
|
||||
# version.json, and the bootstrapVersion read-modify-write must not interleave with the
|
||||
@@ -46,15 +45,24 @@ env:
|
||||
CODE_SIGN_TIMESTAMP_URL: http://timestamp.acs.microsoft.com
|
||||
|
||||
jobs:
|
||||
# $/ is the self-repository form: this repository at the running commit, never a
|
||||
# path some earlier step could have written to the workspace.
|
||||
gates:
|
||||
uses: ./.github/workflows/bootstrap-script-gates.yml
|
||||
uses: $/.github/workflows/bootstrap-script-gates.yml
|
||||
|
||||
publish:
|
||||
name: Publish to the download alias
|
||||
needs: gates
|
||||
runs-on: windows-latest
|
||||
# Job-scoped: only the publish job federates to Azure, the gates job never holds an
|
||||
# OIDC token it does not need.
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # OIDC federated login for the storage writes (secret-less)
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Check code-signing configuration
|
||||
shell: pwsh
|
||||
@@ -70,7 +78,7 @@ jobs:
|
||||
# both federated credentials are bound to the ref, so this job must never carry a
|
||||
# GitHub `environment:`.
|
||||
- name: Login to Azure (code-signing identity)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
@@ -91,7 +99,7 @@ jobs:
|
||||
# runs the same publisher with -DryRun and deliberately without a login -- a dry run
|
||||
# must never need Azure credentials.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
|
||||
+1
-1
Submodule infra updated: 742249e7e3...be0165a223
+1
-1
Submodule internal updated: 6c79026c33...c2cf529c83
@@ -2,10 +2,10 @@
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-OFFICE-001",
|
||||
"title": "Microsoft 365 Apps Install Failed",
|
||||
"description": "Detects when the Microsoft 365 Apps (Office Click-to-Run) background install did not reach completion. The V2 OfficeInstallDetector watches the C2R client directly (registry + process) and emits office_install_failed when the install scenario was abandoned (worker gone and streaming never finished) or a C2R failure code was observed. This catches Office failures that the Intune integrated app type hides, because IME reports the app done within 1-2 minutes while C2R keeps installing in the background.",
|
||||
"description": "Detects when the Microsoft 365 Apps (Office Click-to-Run) install failed. The V2 OfficeInstallDetector watches the C2R client directly (registry, Delivery Optimization, process) and emits office_install_failed when the C2R INSTALL scenario records an error code. Completion is proven by the core Office binaries on disk; an install window that closes without that proof ends silently, never as a failure. This catches Office failures the deployment status hides: the Intune built-in app type is marked done once the configuration is delivered, and a Win32 or RealmJoin package once its installer exits, while C2R keeps installing in the background.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -39,12 +39,12 @@
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 40,
|
||||
"explanation": "The Microsoft 365 Apps (Office Click-to-Run) install did not finish.\n\nThe OfficeInstallDetector watches the C2R client directly and reports the real background install lifecycle. The Intune \"integrated\" Microsoft 365 Apps app type only pushes the configuration XML and starts the C2R bootstrapper, so IME marks the app done within 1-2 minutes while C2R keeps streaming and laying down the product for several more minutes. This event means C2R activity ended (the OfficeC2RClient worker exited and the install scenario cleared) without the StreamingFinished flag being set, or a C2R failure code was observed.\n\nReview the office_install_failed event payload: `products`, `channel`, `phase`, `streamingFinished`, `errorCode` (best-effort — may be empty) and `durationSeconds`.",
|
||||
"explanation": "The Microsoft 365 Apps (Office Click-to-Run) install failed.\n\nThe OfficeInstallDetector watches the C2R client directly and reports the real install lifecycle, however it was started. The Intune built-in Microsoft 365 Apps app type delivers the configuration through the Office CSP and lets the device start C2R; a Win32 or RealmJoin package runs the Office Deployment Tool. Either way the deployment is marked done before C2R has finished laying down the product. This event means C2R recorded an error code in its INSTALL scenario before the core Office apps were on disk.\n\nReview the office_install_failed event payload: `products`, `channel`, `errorCode`, `errorSource` (the C2R registry value that carried the code) and `durationSeconds`.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Investigate the Office C2R install failure",
|
||||
"steps": [
|
||||
"Open the office_install_failed event and review products, channel, phase, streamingFinished and errorCode",
|
||||
"Open the office_install_failed event and review products, channel, errorCode and errorSource",
|
||||
"Check the Click-to-Run logs on the device (%windir%\\Temp and %temp%, files named <MachineName>-yyyymmdd-nnnn.log) for the failing operation",
|
||||
"Verify the device had network reachability to the Office CDN / Microsoft Connected Cache during the enrollment window",
|
||||
"Confirm the Intune Microsoft 365 Apps app configuration (products, channel, architecture) matches what the device can install",
|
||||
|
||||
+4
-4
@@ -3246,10 +3246,10 @@
|
||||
{
|
||||
"ruleId": "ANALYZE-OFFICE-001",
|
||||
"title": "Microsoft 365 Apps Install Failed",
|
||||
"description": "Detects when the Microsoft 365 Apps (Office Click-to-Run) background install did not reach completion. The V2 OfficeInstallDetector watches the C2R client directly (registry + process) and emits office_install_failed when the install scenario was abandoned (worker gone and streaming never finished) or a C2R failure code was observed. This catches Office failures that the Intune integrated app type hides, because IME reports the app done within 1-2 minutes while C2R keeps installing in the background.",
|
||||
"description": "Detects when the Microsoft 365 Apps (Office Click-to-Run) install failed. The V2 OfficeInstallDetector watches the C2R client directly (registry, Delivery Optimization, process) and emits office_install_failed when the C2R INSTALL scenario records an error code. Completion is proven by the core Office binaries on disk; an install window that closes without that proof ends silently, never as a failure. This catches Office failures the deployment status hides: the Intune built-in app type is marked done once the configuration is delivered, and a Win32 or RealmJoin package once its installer exits, while C2R keeps installing in the background.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -3283,12 +3283,12 @@
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 40,
|
||||
"explanation": "The Microsoft 365 Apps (Office Click-to-Run) install did not finish.\n\nThe OfficeInstallDetector watches the C2R client directly and reports the real background install lifecycle. The Intune \"integrated\" Microsoft 365 Apps app type only pushes the configuration XML and starts the C2R bootstrapper, so IME marks the app done within 1-2 minutes while C2R keeps streaming and laying down the product for several more minutes. This event means C2R activity ended (the OfficeC2RClient worker exited and the install scenario cleared) without the StreamingFinished flag being set, or a C2R failure code was observed.\n\nReview the office_install_failed event payload: `products`, `channel`, `phase`, `streamingFinished`, `errorCode` (best-effort — may be empty) and `durationSeconds`.",
|
||||
"explanation": "The Microsoft 365 Apps (Office Click-to-Run) install failed.\n\nThe OfficeInstallDetector watches the C2R client directly and reports the real install lifecycle, however it was started. The Intune built-in Microsoft 365 Apps app type delivers the configuration through the Office CSP and lets the device start C2R; a Win32 or RealmJoin package runs the Office Deployment Tool. Either way the deployment is marked done before C2R has finished laying down the product. This event means C2R recorded an error code in its INSTALL scenario before the core Office apps were on disk.\n\nReview the office_install_failed event payload: `products`, `channel`, `errorCode`, `errorSource` (the C2R registry value that carried the code) and `durationSeconds`.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Investigate the Office C2R install failure",
|
||||
"steps": [
|
||||
"Open the office_install_failed event and review products, channel, phase, streamingFinished and errorCode",
|
||||
"Open the office_install_failed event and review products, channel, errorCode and errorSource",
|
||||
"Check the Click-to-Run logs on the device (%windir%\\Temp and %temp%, files named <MachineName>-yyyymmdd-nnnn.log) for the failing operation",
|
||||
"Verify the device had network reachability to the Office CDN / Microsoft Connected Cache during the enrollment window",
|
||||
"Confirm the Intune Microsoft 365 Apps app configuration (products, channel, architecture) matches what the device can install",
|
||||
|
||||
+24
-8
@@ -34,6 +34,14 @@
|
||||
"description": "Captures the exit code of a health-script execution. Feeds the early-signal slot consumed by HS-COMPLIANCE so the user sees the real exit code (not just the inferred 0/1) before HS-NEW-RESULT arrives.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "HS-INVOCATION",
|
||||
"category": "always",
|
||||
"pattern": "^\"[^\"]{0,260}\\\\agentexecutor\\.exe\"\\s+-(?<kind>remediationScript)\\s",
|
||||
"action": "agentInvocationArgument",
|
||||
"description": "The IME service's command line for a health-script executor, written by the health-script worker to IntuneManagementExtension.log and HealthScripts.log right before 'Launch powershell executor in ... session'. Opens an invocation that owns nothing, so the launch line the same worker writes next never sets the context of the platform script whose run is in flight in the IME log. The platform-script command line ('-powershell') does not match.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "HS-NEW-RESULT",
|
||||
"category": "always",
|
||||
@@ -646,6 +654,22 @@
|
||||
"description": "Detects WinGet app installation progress with Operation Phase = Installing (format variant 2).",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "PS-AGENT-ARG",
|
||||
"category": "always",
|
||||
"pattern": "^Adding argument (?<kind>[A-Za-z0-9]+) with value ",
|
||||
"action": "agentInvocationArgument",
|
||||
"description": "The first argument line of every AgentExecutor.exe invocation (powershell, remediationScript, detectionScript, requirementScript, ...). Opens the invocation that owns the policyId-less exit/output lines following it in AgentExecutor.log; PS-AGENT-SCRIPT-START upgrades a powershell invocation to its platform script. Also keeps the tracker's overwrite check active while the invocation runs.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "PS-AGENT-COMPLETED",
|
||||
"category": "always",
|
||||
"pattern": "^Agent executor completed\\.",
|
||||
"action": "agentExecutorCompleted",
|
||||
"description": "Last line of an AgentExecutor.exe invocation. Closes the invocation's ownership of the exit/output lines in AgentExecutor.log and triggers the tracker's overwrite check: the executor wrote its end block at its own stream position, which may lie behind the tracker's bookmark when another process appended meanwhile.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "PS-AGENT-ERROR",
|
||||
"category": "always",
|
||||
@@ -708,14 +732,6 @@
|
||||
"description": "Captures whether a PowerShell script runs in machine (System) or user session context.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "PS-SCRIPT-EXITCODE",
|
||||
"category": "always",
|
||||
"pattern": "^Powershell execution is done, exitCode = (?<exitCode>-?\\d+)",
|
||||
"action": "scriptExitCode",
|
||||
"description": "Captures the PowerShell exit code when script execution completes in the IME log.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "PS-SCRIPT-GENERATED",
|
||||
"category": "always",
|
||||
|
||||
@@ -300,6 +300,7 @@
|
||||
"script_completed",
|
||||
"script_failed",
|
||||
"script_timeout_suspected",
|
||||
"script_recurrence_summary",
|
||||
"esp_phase_changed",
|
||||
"ime_agent_version",
|
||||
"ime_token_failure",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "../schema/ime-log-pattern.schema.json",
|
||||
"patternId": "HS-INVOCATION",
|
||||
"category": "always",
|
||||
"pattern": "^\"[^\"]{0,260}\\\\agentexecutor\\.exe\"\\s+-(?<kind>remediationScript)\\s",
|
||||
"action": "agentInvocationArgument",
|
||||
"description": "The IME service's command line for a health-script executor, written by the health-script worker to IntuneManagementExtension.log and HealthScripts.log right before 'Launch powershell executor in ... session'. Opens an invocation that owns nothing, so the launch line the same worker writes next never sets the context of the platform script whose run is in flight in the IME log. The platform-script command line ('-powershell') does not match.",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "../schema/ime-log-pattern.schema.json",
|
||||
"patternId": "PS-AGENT-ARG",
|
||||
"category": "always",
|
||||
"pattern": "^Adding argument (?<kind>[A-Za-z0-9]+) with value ",
|
||||
"action": "agentInvocationArgument",
|
||||
"description": "The first argument line of every AgentExecutor.exe invocation (powershell, remediationScript, detectionScript, requirementScript, ...). Opens the invocation that owns the policyId-less exit/output lines following it in AgentExecutor.log; PS-AGENT-SCRIPT-START upgrades a powershell invocation to its platform script. Also keeps the tracker's overwrite check active while the invocation runs.",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "../schema/ime-log-pattern.schema.json",
|
||||
"patternId": "PS-AGENT-COMPLETED",
|
||||
"category": "always",
|
||||
"pattern": "^Agent executor completed\\.",
|
||||
"action": "agentExecutorCompleted",
|
||||
"description": "Last line of an AgentExecutor.exe invocation. Closes the invocation's ownership of the exit/output lines in AgentExecutor.log and triggers the tracker's overwrite check: the executor wrote its end block at its own stream position, which may lie behind the tracker's bookmark when another process appended meanwhile.",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"$schema": "../schema/ime-log-pattern.schema.json",
|
||||
"patternId": "PS-SCRIPT-EXITCODE",
|
||||
"category": "always",
|
||||
"pattern": "^Powershell execution is done, exitCode = (?<exitCode>-?\\d+)",
|
||||
"action": "scriptExitCode",
|
||||
"description": "Captures the PowerShell exit code when script execution completes in the IME log.",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -71,6 +71,8 @@
|
||||
"scriptOutput",
|
||||
"scriptCompleted",
|
||||
"resetPlatformScriptContext",
|
||||
"agentInvocationArgument",
|
||||
"agentExecutorCompleted",
|
||||
"healthScriptResult",
|
||||
"healthScriptDetectionResult",
|
||||
"captureExitCode",
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# ajv-cli declares ts-node as a peer dependency it never needs for JSON schemas; do not
|
||||
# pull ts-node + typescript into a job that pushes to main.
|
||||
legacy-peer-deps=true
|
||||
Generated
+315
@@ -0,0 +1,315 @@
|
||||
{
|
||||
"name": "autopilot-monitor-rules-tooling",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "autopilot-monitor-rules-tooling",
|
||||
"devDependencies": {
|
||||
"ajv-cli": "5.0.0",
|
||||
"ajv-formats": "3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "8.20.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
|
||||
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"fast-uri": "^3.0.1",
|
||||
"json-schema-traverse": "^1.0.0",
|
||||
"require-from-string": "^2.0.2"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/epoberezkin"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv-cli": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv-cli/-/ajv-cli-5.0.0.tgz",
|
||||
"integrity": "sha512-LY4m6dUv44HTyhV+u2z5uX4EhPYTM38Iv1jdgDJJJCyOOuqB8KtZEGjPZ2T+sh5ZIJrXUfgErYx/j3gLd3+PlQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ajv": "^8.0.0",
|
||||
"fast-json-patch": "^2.0.0",
|
||||
"glob": "^7.1.0",
|
||||
"js-yaml": "^3.14.0",
|
||||
"json-schema-migrate": "^2.0.0",
|
||||
"json5": "^2.1.3",
|
||||
"minimist": "^1.2.0"
|
||||
},
|
||||
"bin": {
|
||||
"ajv": "dist/index.js"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ts-node": ">=9.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ts-node": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/ajv-formats": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
|
||||
"integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ajv": "^8.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ajv": "^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ajv": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
|
||||
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"sprintf-js": "~1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.21",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
|
||||
"integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0",
|
||||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/esprima": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
|
||||
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"bin": {
|
||||
"esparse": "bin/esparse.js",
|
||||
"esvalidate": "bin/esvalidate.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-deep-equal": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-json-patch": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-3.1.1.tgz",
|
||||
"integrity": "sha512-vf6IHUX2SBcA+5/+4883dsIjpBTqmfBjmYiWK1savxQmFk4JfBMLa7ynTYOs1Rolp/T1betJxHiGD3g1Mn8lUQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.8",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
|
||||
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/fs.realpath": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
||||
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "7.2.3",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
"inflight": "^1.0.4",
|
||||
"inherits": "2",
|
||||
"minimatch": "^3.1.1",
|
||||
"once": "^1.3.0",
|
||||
"path-is-absolute": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/inflight": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
|
||||
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"once": "^1.3.0",
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "3.15.2",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz",
|
||||
"integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^1.0.7",
|
||||
"esprima": "^4.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"js-yaml": "bin/js-yaml.js"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-migrate": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-migrate/-/json-schema-migrate-2.0.0.tgz",
|
||||
"integrity": "sha512-r38SVTtojDRp4eD6WsCqiE0eNDt4v1WalBXb9cyZYw9ai5cGtBwzRNWjHzJl38w6TxFkXAIA7h+fyX3tnrAFhQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ajv": "^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/json5": {
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
|
||||
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"json5": "lib/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
|
||||
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^1.1.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/once": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/path-is-absolute": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
|
||||
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-from-string": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
||||
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sprintf-js": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
|
||||
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/wrappy": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "autopilot-monitor-rules-tooling",
|
||||
"private": true,
|
||||
"description": "Validator tooling for rules/ - combine-rules.yml installs from the lockfile so nothing unpinned reaches a job that pushes to main.",
|
||||
"devDependencies": {
|
||||
"ajv-cli": "5.0.0",
|
||||
"ajv-formats": "3.0.1"
|
||||
},
|
||||
"overrides": {
|
||||
"fast-json-patch": "3.1.1"
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,9 @@
|
||||
Cloud PCs are never Autopilot-registered, so this enables agent monitoring
|
||||
of Cloud PC first-connect enrollment)
|
||||
- IntuneDeviceBinding -> DeviceManagementManagedDevices.Read.All
|
||||
(cert-to-device binding: verifies that the Intune device id carried in the
|
||||
agent's client certificate is a device THIS tenant actually enrolled --
|
||||
currently a Global-Admin-only preview that records telemetry and does not
|
||||
block enrollment)
|
||||
(Intune Enrollment Validation: accepts devices enrolled in THIS tenant's
|
||||
Intune, matched by the Intune device id in the agent's client certificate,
|
||||
without Autopilot registration, corporate identifier or device association)
|
||||
- All -> every optional permission above, in one run
|
||||
(also works with -Revoke to remove all optional grants at once)
|
||||
|
||||
@@ -76,15 +75,17 @@
|
||||
.NOTES
|
||||
Requires:
|
||||
- Microsoft.Graph.Authentication PowerShell module (auto-installs if missing).
|
||||
- Sign-in as Global Administrator OR Privileged Role Administrator OR Cloud Application Administrator.
|
||||
- Sign-in as Global Administrator OR Privileged Role Administrator (with PIM, activate the
|
||||
role first). Only these roles may assign Microsoft Graph application permissions;
|
||||
Application Administrator and Cloud Application Administrator are not enough.
|
||||
- The Autopilot Monitor app must be admin-consented in your tenant first
|
||||
(its service principal must exist before grants can be added).
|
||||
|
||||
Sign-in behaviour:
|
||||
In Azure Cloud Shell the script signs in via the ambient identity endpoint (a delegated
|
||||
token for the already-signed-in user) - no device-code prompt, which Conditional Access
|
||||
policies commonly block. Outside Cloud Shell it falls back to a normal interactive
|
||||
Microsoft Graph sign-in. -TenantId only applies to the interactive fallback.
|
||||
- The Autopilot Monitor app must be admin-consented in your tenant first
|
||||
(its service principal must exist before grants can be added).
|
||||
|
||||
After granting:
|
||||
The Autopilot Monitor backend may cache an older token for up to ~1 hour. Use the
|
||||
@@ -140,6 +141,36 @@ if ($PSCmdlet.ParameterSetName -eq 'ByFeatures') {
|
||||
# ---- Constants ----
|
||||
$MicrosoftGraphAppId = '00000003-0000-0000-c000-000000000000'
|
||||
|
||||
# ---- Graph failure details ----
|
||||
# Invoke-MgGraphRequest puts only "Response status code does not indicate success: ..." into the
|
||||
# exception message. Graph's own error (code + message) is the response body in ErrorDetails,
|
||||
# behind the request line, the status line and the headers. Some headers carry JSON themselves
|
||||
# (x-ms-ags-diagnostic), so the body is taken from behind the blank line that ends the headers.
|
||||
function Get-GraphFailure {
|
||||
param([System.Management.Automation.ErrorRecord]$ErrorRecord)
|
||||
|
||||
$status = 0
|
||||
if ($ErrorRecord.Exception.PSObject.Properties['Response'] -and $ErrorRecord.Exception.Response) {
|
||||
$status = [int]$ErrorRecord.Exception.Response.StatusCode
|
||||
}
|
||||
|
||||
$text = $ErrorRecord.Exception.Message
|
||||
if ($ErrorRecord.ErrorDetails -and $ErrorRecord.ErrorDetails.Message) {
|
||||
$body = ($ErrorRecord.ErrorDetails.Message -split '\r?\n\r?\n', 2)[-1].Trim()
|
||||
if ($body.StartsWith('{')) {
|
||||
try {
|
||||
$graphError = ($body | ConvertFrom-Json).error
|
||||
if ($graphError.code) { $text = "$($graphError.code): $($graphError.message)" }
|
||||
}
|
||||
catch {
|
||||
# Not a Graph JSON body - keep the exception message.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[pscustomobject]@{ Status = $status; Text = $text }
|
||||
}
|
||||
|
||||
# ---- Pre-flight: module ----
|
||||
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
|
||||
Write-Host "[Setup] Microsoft.Graph.Authentication not installed. Installing for current user..." -ForegroundColor Yellow
|
||||
@@ -189,7 +220,7 @@ Write-Host "[Auth] Granted scopes: $($ctx.Scopes -join ', ')"
|
||||
# carries a fixed scope set (incl. Directory.AccessAsUser.All) instead of the requested scopes,
|
||||
# and its effective rights follow the signed-in user's directory role.
|
||||
if (-not $identityConnected -and -not ($ctx.Scopes -contains 'AppRoleAssignment.ReadWrite.All')) {
|
||||
Write-Warning "Scope 'AppRoleAssignment.ReadWrite.All' was NOT granted. The signed-in user likely lacks the required role (Global Admin / Privileged Role Admin / Cloud App Admin)."
|
||||
Write-Warning "Scope 'AppRoleAssignment.ReadWrite.All' was NOT granted. The signed-in user likely lacks the required role (Global Administrator or Privileged Role Administrator)."
|
||||
if (-not $VerifyOnly) { return }
|
||||
}
|
||||
|
||||
@@ -263,6 +294,7 @@ $action = if ($Revoke) { 'Revoke' } else { 'Grant' }
|
||||
Write-Host "[4/4] $action mode - processing $($Permissions.Count) permission(s)..." -ForegroundColor Cyan
|
||||
|
||||
$results = @()
|
||||
$graphForbidden = $false
|
||||
foreach ($permName in $Permissions) {
|
||||
$appRole = $graphSp.appRoles | Where-Object {
|
||||
$_.value -eq $permName -and $_.allowedMemberTypes -contains 'Application'
|
||||
@@ -289,7 +321,9 @@ foreach ($permName in $Permissions) {
|
||||
$results += [pscustomobject]@{ Permission = $permName; Status = 'Revoked' }
|
||||
}
|
||||
catch {
|
||||
Write-Warning " [FAIL] '$permName' revoke failed: $($_.Exception.Message)"
|
||||
$failure = Get-GraphFailure $_
|
||||
if ($failure.Status -eq 403) { $graphForbidden = $true }
|
||||
Write-Warning " [FAIL] '$permName' revoke failed: $($failure.Text)"
|
||||
$results += [pscustomobject]@{ Permission = $permName; Status = 'Failed' }
|
||||
}
|
||||
}
|
||||
@@ -316,7 +350,9 @@ foreach ($permName in $Permissions) {
|
||||
$results += [pscustomobject]@{ Permission = $permName; Status = 'Granted' }
|
||||
}
|
||||
catch {
|
||||
Write-Warning " [FAIL] '$permName' grant failed: $($_.Exception.Message)"
|
||||
$failure = Get-GraphFailure $_
|
||||
if ($failure.Status -eq 403) { $graphForbidden = $true }
|
||||
Write-Warning " [FAIL] '$permName' grant failed: $($failure.Text)"
|
||||
$results += [pscustomobject]@{ Permission = $permName; Status = 'Failed' }
|
||||
}
|
||||
}
|
||||
@@ -325,6 +361,9 @@ foreach ($permName in $Permissions) {
|
||||
Write-Host ""
|
||||
Write-Host "=========== Summary ===========" -ForegroundColor Cyan
|
||||
$results | Format-Table -AutoSize | Out-Host
|
||||
if ($graphForbidden) {
|
||||
Write-Warning "Microsoft Graph refused the change (403): the signed-in account may not manage Microsoft Graph application permissions. Sign in as Global Administrator or Privileged Role Administrator (with PIM, activate the role first) and run the script again."
|
||||
}
|
||||
Write-Host ""
|
||||
Write-Host "Note: token-cached backends may need up to ~1h to see the new permission set." -ForegroundColor Yellow
|
||||
Write-Host " Use 'Refresh permission status' in the admin UI to apply changes immediately." -ForegroundColor Yellow
|
||||
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
|
||||
{
|
||||
/// <summary>
|
||||
/// A configured diagnostics entry is resolved to the folder and pattern that get
|
||||
/// enumerated, and the guard judges exactly that folder. The cases below pin the
|
||||
/// property that matters: no spelling of an allowed entry ever selects its parent.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticsPathGuardsTests
|
||||
{
|
||||
private const string TestProfile = @"C:\Users\TestUser";
|
||||
|
||||
private static readonly Func<string, bool> IsDirectory = _ => true;
|
||||
private static readonly Func<string, bool> IsNotDirectory = _ => false;
|
||||
|
||||
private static DiagnosticsPathGuards.CollectionTarget Resolve(
|
||||
string path,
|
||||
bool includeSubfolders = false,
|
||||
bool unrestrictedMode = false,
|
||||
string? userProfilePath = null,
|
||||
Func<string, bool>? directoryExists = null)
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.TryResolveCollectionTarget(
|
||||
path, includeSubfolders, unrestrictedMode, userProfilePath!, directoryExists ?? IsDirectory, out var target));
|
||||
return target;
|
||||
}
|
||||
|
||||
private static void AssertRefused(
|
||||
string path,
|
||||
bool unrestrictedMode = false,
|
||||
string? userProfilePath = null,
|
||||
Func<string, bool>? directoryExists = null)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.TryResolveCollectionTarget(
|
||||
path, true, unrestrictedMode, userProfilePath!, directoryExists ?? IsDirectory, out var target));
|
||||
Assert.Null(target);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ folder entries
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Windows\Logs")]
|
||||
[InlineData(@"C:\Windows\Logs\")]
|
||||
[InlineData(@"C:\Windows\SetupDiag")]
|
||||
[InlineData(@"C:\ProgramData\AutopilotMonitor")]
|
||||
[InlineData(@"C:\ProgramData\Microsoft\DiagnosticLogCSP")]
|
||||
public void Folder_entry_collects_from_itself_never_from_its_parent(string configured)
|
||||
{
|
||||
var target = Resolve(configured, includeSubfolders: true);
|
||||
|
||||
Assert.Equal(configured.TrimEnd('\\'), target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*", target.Pattern);
|
||||
Assert.True(target.Recurse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Trailing_separator_means_folder_even_when_the_folder_does_not_exist_yet()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Logs\NotThereYet\", directoryExists: IsNotDirectory);
|
||||
|
||||
Assert.Equal(@"C:\Windows\Logs\NotThereYet", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*", target.Pattern);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Folder_name_with_a_dot_is_still_a_folder()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Logs\vendor.v2");
|
||||
|
||||
Assert.Equal(@"C:\Windows\Logs\vendor.v2", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*", target.Pattern);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ wildcard entries
|
||||
|
||||
[Fact]
|
||||
public void Wildcard_entry_collects_the_pattern_from_its_validated_parent()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Panther\*.log", includeSubfolders: true);
|
||||
|
||||
Assert.Equal(@"C:\Windows\Panther", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*.log", target.Pattern);
|
||||
Assert.True(target.Recurse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wildcard_beside_an_allowlisted_file_is_refused()
|
||||
{
|
||||
// Only ReportingEvents.log is on the allowlist, not the folder it lives in.
|
||||
AssertRefused(@"C:\Windows\SoftwareDistribution\*.log");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ file entries
|
||||
|
||||
[Fact]
|
||||
public void File_entry_never_recurses_because_its_folder_was_not_validated()
|
||||
{
|
||||
var target = Resolve(
|
||||
@"C:\Windows\SoftwareDistribution\ReportingEvents.log",
|
||||
includeSubfolders: true,
|
||||
directoryExists: IsNotDirectory);
|
||||
|
||||
Assert.Equal(@"C:\Windows\SoftwareDistribution", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("ReportingEvents.log", target.Pattern);
|
||||
Assert.False(target.Recurse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_path_without_a_dot_is_one_file_name_not_a_wildcard_on_the_parent()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Logs\nodot", includeSubfolders: true, directoryExists: IsNotDirectory);
|
||||
|
||||
Assert.Equal(@"C:\Windows\Logs", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("nodot", target.Pattern);
|
||||
Assert.False(target.Recurse);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ refusals
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Windows")]
|
||||
[InlineData(@"C:\ProgramData")]
|
||||
[InlineData(@"C:\ProgramData\Microsoft")]
|
||||
[InlineData(@"C:\Windows\Logs\..\System32")]
|
||||
[InlineData(@"C:\Windows\LogsEvil")]
|
||||
[InlineData("")]
|
||||
public void Paths_outside_the_allowlist_are_refused(string configured)
|
||||
{
|
||||
AssertRefused(configured);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Users")]
|
||||
[InlineData(@"C:\Users\TestUser\Documents")]
|
||||
[InlineData(@"C:\Windows\System32\config")]
|
||||
[InlineData(@"C:\Windows\System32\config\*")]
|
||||
public void Hard_blocks_hold_in_unrestricted_mode(string configured)
|
||||
{
|
||||
AssertRefused(configured, unrestrictedMode: true);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ user-profile token
|
||||
|
||||
[Fact]
|
||||
public void Expanded_token_path_outside_AppData_is_refused_even_in_unrestricted_mode()
|
||||
{
|
||||
// The service expands %LOGGED_ON_USER_PROFILE% before the guard sees the path; an
|
||||
// unexpanded token is not under C:\Users lexically and used to slip past the block.
|
||||
AssertRefused(TestProfile + @"\Documents", unrestrictedMode: true, userProfilePath: TestProfile);
|
||||
AssertRefused(TestProfile + @"\Documents\*.txt", unrestrictedMode: true, userProfilePath: TestProfile);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Expanded_token_path_on_the_profile_allowlist_is_admitted_in_restricted_mode()
|
||||
{
|
||||
var target = Resolve(
|
||||
TestProfile + @"\AppData\Local\RealmJoin\Logs\*.log",
|
||||
userProfilePath: TestProfile);
|
||||
|
||||
Assert.Equal(TestProfile + @"\AppData\Local\RealmJoin\Logs", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*.log", target.Pattern);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Profile_path_without_the_token_stays_blocked()
|
||||
{
|
||||
AssertRefused(TestProfile + @"\AppData\Local\RealmJoin\Logs\*.log", userProfilePath: null);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ recursion guard
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Users")]
|
||||
[InlineData(@"C:\Users\TestUser")]
|
||||
[InlineData(@"C:\Windows\System32\config")]
|
||||
[InlineData(@"C:\Windows\System32\config\RegBack")]
|
||||
public void Recursion_never_enters_a_hard_blocked_subtree_in_unrestricted_mode(string directory)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.IsDirectoryEnterable(directory, unrestrictedMode: true, userProfilePath: null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Recursion_enters_ordinary_subfolders()
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.IsDirectoryEnterable(@"C:\Windows\System32\drivers", unrestrictedMode: true, userProfilePath: null));
|
||||
Assert.True(DiagnosticsPathGuards.IsDirectoryEnterable(@"C:\Windows\Logs\CBS", unrestrictedMode: false, userProfilePath: null));
|
||||
Assert.False(DiagnosticsPathGuards.IsDirectoryEnterable(@"C:\Windows\System32\drivers", unrestrictedMode: false, userProfilePath: null));
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -186,5 +186,20 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
DateTime resolved;
|
||||
Assert.False(sut.TryResolveUtc(Source, UtcNow, out resolved));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(3610.39, true, 4)] // session 4377911b: +1 h on a 10 s script
|
||||
[InlineData(61203.0, true, 68)] // 17 h on a 3 s script
|
||||
[InlineData(7205.66, true, 8)] // session cbaed57b: +2 h
|
||||
[InlineData(-3596.0, true, 4)] // the same error on the start end
|
||||
[InlineData(26.4, false, 0)] // a run time below one grid step
|
||||
[InlineData(1030.0, false, 1)] // 17 min 10 s: residual past the tolerance
|
||||
[InlineData(900.0, true, 1)] // exactly one step — a genuine 15-minute run reads the same, the caller needs mixed provenance too
|
||||
public void A_grid_sized_span_is_the_signature_of_an_offset_error(double seconds, bool onGrid, int expectedSteps)
|
||||
{
|
||||
int steps;
|
||||
Assert.Equal(onGrid, CmTraceOffsetCalibrator.IsOnOffsetGrid(TimeSpan.FromSeconds(seconds), out steps));
|
||||
if (onGrid) Assert.Equal(expectedSteps, steps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+537
@@ -0,0 +1,537 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Session 46749560: IME's trace listener writes every log through one FileMode.Append
|
||||
/// stream per process, so a process that resumes logging after another one appended
|
||||
/// overwrites those bytes at its own stale position. The tracker had read the first version
|
||||
/// and never saw the second — 6 of 16 script results and 4 of 16 executor end blocks were
|
||||
/// lost while the final files looked intact. These tests drive that exact write pattern
|
||||
/// (positional overwrite behind the bookmark) against the two multi-writer logs and pin the
|
||||
/// contract: unchanged bytes never rewind, changed bytes are processed exactly once, and the
|
||||
/// executor lines a rewind uncovers belong to the invocation that owns their file position.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerOverwriteRewindTests
|
||||
{
|
||||
private static readonly DateTime T0 = new DateTime(2026, 9, 10, 19, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
private static List<ImeLogPattern> MarkerPatterns() => new List<ImeLogPattern>
|
||||
{
|
||||
new ImeLogPattern
|
||||
{
|
||||
PatternId = "T-MARK", Category = "always", Enabled = true,
|
||||
Pattern = @"^marker (?<n>\d+)", Action = "noop",
|
||||
Parameters = new Dictionary<string, string>(),
|
||||
},
|
||||
};
|
||||
|
||||
private static readonly string[] ScriptPatternIds =
|
||||
{
|
||||
"PS-AGENT-INVOCATION", "PS-AGENT-ARG", "PS-AGENT-SCRIPT-START", "PS-AGENT-EXITCODE",
|
||||
"PS-AGENT-OUTPUT", "PS-AGENT-COMPLETED", "PS-SCRIPT-GENERATED", "PS-SCRIPT-CONTEXT", "PS-SCRIPT-RESULT",
|
||||
};
|
||||
|
||||
/// <summary>The shipped pattern JSON — the same source combine.js embeds — so the contract is the real one.</summary>
|
||||
private static List<ImeLogPattern> ScriptPatterns()
|
||||
{
|
||||
DirectoryInfo? dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
string? patternDir = null;
|
||||
while (dir != null)
|
||||
{
|
||||
var candidate = Path.Combine(dir.FullName, "rules", "ime-log-patterns");
|
||||
if (Directory.Exists(candidate)) { patternDir = candidate; break; }
|
||||
dir = dir.Parent;
|
||||
}
|
||||
Assert.NotNull(patternDir);
|
||||
|
||||
var byId = new Dictionary<string, ImeLogPattern>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var file in Directory.GetFiles(patternDir, "*.json"))
|
||||
{
|
||||
var pattern = JsonConvert.DeserializeObject<ImeLogPattern>(File.ReadAllText(file));
|
||||
if (pattern?.PatternId != null) byId[pattern.PatternId] = pattern;
|
||||
}
|
||||
return ScriptPatternIds.Select(id =>
|
||||
{
|
||||
Assert.True(byId.TryGetValue(id, out var p), $"Shipped IME pattern '{id}' not found under {patternDir}.");
|
||||
return p!;
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static string Entry(string message, string thread = "1")
|
||||
=> $"<![LOG[{message}]LOG]!><time=\"12:00:00.0000000\" date=\"9-10-2026\" component=\"X\" context=\"\" type=\"1\" thread=\"{thread}\" file=\"\">\r\n";
|
||||
|
||||
private const string PlatformId = "d39eeef3-e88e-41a0-82d7-5e28ee7b5acf";
|
||||
private const string PlatformStartLine =
|
||||
@"Adding argument powershell with value C:\Program Files (x86)\Microsoft Intune Management Extension\Policies\Scripts\73d664e4-0886-4a73-b745-c694da45ddb4_d39eeef3-e88e-41a0-82d7-5e28ee7b5acf.ps1 to the named argument list.";
|
||||
private const string DetectionStartLine =
|
||||
@"Adding argument detectionScript with value C:\Windows\IMECache\DetectionScripts\App_cc46aa62-e93a-41a1-bdd0-44f57e92a66d.ps1 to the named argument list.";
|
||||
private const string GeneratedLine =
|
||||
@"Script file C:\Program Files (x86)\Microsoft Intune Management Extension\Policies\Scripts\73d664e4-0886-4a73-b745-c694da45ddb4_d39eeef3-e88e-41a0-82d7-5e28ee7b5acf.ps1 is generated.";
|
||||
private const string ResultLine =
|
||||
"[PowerShell] User Id = 73d664e4-0886-4a73-b745-c694da45ddb4, Policy id = " + PlatformId + ", policy result = Success";
|
||||
|
||||
private sealed class Harness : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
private readonly string _matchLog;
|
||||
private readonly List<ImeLogPattern> _patterns;
|
||||
public ImeLogTracker Tracker { get; private set; }
|
||||
public DateTime Now { get; set; } = T0;
|
||||
public string LogName { get; }
|
||||
public string LogPath => Path.Combine(_tmp.Path, LogName);
|
||||
public string StateDir { get; }
|
||||
public List<ScriptExecutionState> Completed { get; } = new List<ScriptExecutionState>();
|
||||
|
||||
public Harness(string logName, List<ImeLogPattern> patterns)
|
||||
{
|
||||
LogName = logName;
|
||||
_patterns = patterns;
|
||||
var logDir = Path.Combine(_tmp.Path, "agent");
|
||||
Directory.CreateDirectory(logDir);
|
||||
_matchLog = Path.Combine(logDir, "ime-pattern-matches.log");
|
||||
StateDir = Path.Combine(_tmp.Path, "state");
|
||||
Tracker = Build();
|
||||
}
|
||||
|
||||
private ImeLogTracker Build()
|
||||
{
|
||||
var t = new ImeLogTracker(_tmp.Path, _patterns, new AgentLogger(Path.Combine(_tmp.Path, "agent"), AgentLogLevel.Debug),
|
||||
matchLogPath: _matchLog, stateDirectory: StateDir);
|
||||
t.UtcNowProvider = () => Now;
|
||||
t.OnScriptCompleted = s => Completed.Add(s);
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>Agent restart: dispose, rebuild over the same state directory, restore the bookmark.</summary>
|
||||
public void Restart()
|
||||
{
|
||||
Tracker.SaveStateForTest();
|
||||
Tracker.Dispose();
|
||||
Tracker = Build();
|
||||
Tracker.LoadStateForTest();
|
||||
}
|
||||
|
||||
public void Append(string text) => File.AppendAllText(LogPath, text, new UTF8Encoding(false));
|
||||
|
||||
/// <summary>What IME's stale writer does: write at its own position, over whatever is there.</summary>
|
||||
public void Overwrite(long offset, string text)
|
||||
{
|
||||
using (var fs = new FileStream(LogPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
|
||||
{
|
||||
fs.Seek(offset, SeekOrigin.Begin);
|
||||
var bytes = new UTF8Encoding(false).GetBytes(text);
|
||||
fs.Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public long Length => new FileInfo(LogPath).Length;
|
||||
|
||||
public Task Pass(CancellationToken token = default) => Tracker.CheckLogFilesAsync(token);
|
||||
|
||||
/// <summary>Marker numbers matched so far, in match order.</summary>
|
||||
public List<int> Matched()
|
||||
{
|
||||
if (!File.Exists(_matchLog)) return new List<int>();
|
||||
return File.ReadAllLines(_matchLog)
|
||||
.Select(l => Regex.Match(l, @"\[T-MARK\] <!\[LOG\[marker (\d+)"))
|
||||
.Where(m => m.Success).Select(m => int.Parse(m.Groups[1].Value)).ToList();
|
||||
}
|
||||
|
||||
public ImeTrackerHealth Health => Tracker.GetHealthSnapshot();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Marker-level contract on AgentExecutor.log
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task Unchanged_bytes_never_rewind_however_often_they_are_verified()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + "<![LOG[marker 2\nsecond line\n]LOG]!><time=\"12:00:00.0000000\" date=\"9-10-2026\" component=\"X\" context=\"\" type=\"1\" thread=\"1\" file=\"\">\r\n" + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3 }, h.Matched());
|
||||
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddSeconds(2);
|
||||
await h.Pass();
|
||||
}
|
||||
|
||||
Assert.Equal(new[] { 1, 2, 3 }, h.Matched());
|
||||
Assert.Equal(0, h.Health.OverwriteRewinds);
|
||||
Assert.Equal(5, h.Health.VerifyPasses);
|
||||
Assert.Equal(3, h.Tracker.LedgerEntryCountForTest("AgentExecutor.log"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Non_multi_writer_files_keep_no_ledger_and_are_never_verified()
|
||||
{
|
||||
using var h = new Harness("AppWorkload.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2"));
|
||||
await h.Pass();
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddSeconds(2);
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(new[] { 1, 2 }, h.Matched());
|
||||
Assert.Equal(0, h.Tracker.LedgerEntryCountForTest("AppWorkload.log"));
|
||||
Assert.Equal(0, h.Health.VerifyPasses);
|
||||
Assert.Equal(0, h.Health.VerifiedBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Block_written_over_read_bytes_is_processed_once_and_the_surviving_tail_is_not_repeated()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
var one = Entry("marker 1");
|
||||
h.Append(one + Entry("marker 2") + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3 }, h.Matched());
|
||||
|
||||
// A stale writer lays two entries over the first two (same length: marker 3 survives
|
||||
// intact at its old offset). No growth, no fragment — only the end signal finds it.
|
||||
h.Overwrite(0, Entry("marker 7") + Entry("marker 8"));
|
||||
Assert.Equal(3 * one.Length, h.Length);
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(new[] { 1, 2, 3, 7, 8 }, h.Matched());
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
Assert.Equal(3 * one.Length, h.Health.OverwriteBytesReprocessed);
|
||||
Assert.Equal(3, h.Tracker.LedgerEntryCountForTest("AgentExecutor.log"));
|
||||
|
||||
// Nothing left to find.
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddSeconds(2);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3, 7, 8 }, h.Matched());
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Block_that_cuts_an_old_entry_leaves_a_fragment_that_is_never_matched()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2") + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
|
||||
// Longer than two old entries, shorter than three: the tail of marker 3's line survives
|
||||
// as a fragment behind the new block.
|
||||
h.Overwrite(0, Entry("marker 7") + Entry("marker 8 is a little longer"));
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(new[] { 1, 2, 3, 7, 8 }, h.Matched());
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Guard_zone_catches_a_short_block_when_the_file_grows_without_any_signal()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2") + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
|
||||
// Same-length replacement of marker 1 (no fragment), then an ordinary append by
|
||||
// another writer: the growth pass re-checks the last 4 KB and finds the change.
|
||||
h.Overwrite(0, Entry("marker 7"));
|
||||
h.Append(Entry("marker 4"));
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(new[] { 1, 2, 3, 7, 4 }, h.Matched());
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
Assert.Equal(1, h.Health.VerifyPasses); // the full check that follows a guard hit
|
||||
Assert.True(h.Health.VerifiedBytes > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Guard_hit_rewinds_to_the_true_start_of_the_block_not_the_guard_zone()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
// ~6 KB of entries so the guard zone covers only the last few.
|
||||
var sb = new StringBuilder();
|
||||
for (var i = 1; i <= 60; i++) sb.Append(Entry($"marker {i}"));
|
||||
h.Append(sb.ToString());
|
||||
await h.Pass();
|
||||
Assert.Equal(60, h.Matched().Count);
|
||||
|
||||
// A block over everything plus one more entry: the guard sees a change at its
|
||||
// zone start, the full check must place the rewind at offset 0.
|
||||
var block = new StringBuilder();
|
||||
for (var i = 101; i <= 161; i++) block.Append(Entry($"marker {i}"));
|
||||
h.Overwrite(0, block.ToString());
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
|
||||
var matched = h.Matched();
|
||||
Assert.Equal(60 + 61, matched.Count);
|
||||
Assert.Equal(Enumerable.Range(101, 61), matched.Skip(60));
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fragment_at_the_bookmark_triggers_the_check_when_no_ledger_entry_starts_in_the_guard_zone()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
var one = Entry("marker 1");
|
||||
var big = Entry("marker 2 " + new string('x', 6000));
|
||||
h.Append(one + big);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2 }, h.Matched());
|
||||
|
||||
// The 6 KB entry is the last ledger entry and starts before the 4 KB guard zone, so
|
||||
// the guard has nothing to check. The stale writer's block is longer than that entry:
|
||||
// the pass after it starts mid-line — a fragment — and must not match it raw.
|
||||
h.Overwrite(one.Length, Entry("marker 7 " + new string('y', 3000)) + Entry("marker 8 " + new string('z', 3100)));
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2 }, h.Matched());
|
||||
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 7, 8 }, h.Matched());
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Hidden_block_is_found_by_the_cadence_while_a_script_is_in_flight_and_the_cadence_is_throttled()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2") + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
|
||||
// A platform script is pending → contention. First pass in contention verifies at once.
|
||||
h.Tracker.SeedPendingPlatformScriptForTesting("policyX", exitCode: null, exitObservedAtUtc: null, startedAtUtc: T0);
|
||||
h.Now = T0.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Equal(1, h.Health.VerifyPasses);
|
||||
|
||||
// Same-length replacement, no growth, no signal: only the cadence can find it —
|
||||
// and not before a second has passed since the last verification.
|
||||
h.Overwrite(0, Entry("marker 7"));
|
||||
h.Now = T0.AddMilliseconds(500);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3 }, h.Matched());
|
||||
Assert.Equal(1, h.Health.VerifyPasses);
|
||||
|
||||
h.Now = T0.AddMilliseconds(1200);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3, 7 }, h.Matched());
|
||||
Assert.Equal(2, h.Health.VerifyPasses);
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Without_contention_or_signal_nothing_is_verified()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2"));
|
||||
await h.Pass();
|
||||
|
||||
for (var i = 0; i < 20; i++)
|
||||
{
|
||||
h.Now = h.Now.AddSeconds(1);
|
||||
await h.Pass();
|
||||
}
|
||||
|
||||
Assert.Equal(0, h.Health.VerifyPasses);
|
||||
Assert.Equal(0, h.Health.VerifiedBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Restart_seeds_the_ledger_so_an_overwrite_after_the_restart_is_still_found()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2") + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
h.Restart();
|
||||
Assert.Equal(0, h.Tracker.LedgerEntryCountForTest("AgentExecutor.log"));
|
||||
|
||||
// First pass after the restart: nothing new to read, but the ledger is seeded from
|
||||
// the bytes behind the persisted bookmark.
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Equal(3, h.Tracker.LedgerEntryCountForTest("AgentExecutor.log"));
|
||||
|
||||
h.Overwrite(0, Entry("marker 7"));
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(new[] { 1, 2, 3, 7 }, h.Matched());
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
|
||||
// The counter is part of the persisted health.
|
||||
h.Restart();
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rollover_clears_the_ledger_and_the_new_file_is_read_without_a_false_rewind()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2") + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
|
||||
File.WriteAllText(h.LogPath, Entry("marker 7") + Entry("marker 8"), new UTF8Encoding(false));
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3, 7, 8 }, h.Matched());
|
||||
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddSeconds(2);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3, 7, 8 }, h.Matched());
|
||||
Assert.Equal(0, h.Health.OverwriteRewinds);
|
||||
Assert.Equal(2, h.Tracker.LedgerEntryCountForTest("AgentExecutor.log"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cancelled_pass_does_not_lose_a_pending_check()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", MarkerPatterns());
|
||||
h.Append(Entry("marker 1") + Entry("marker 2") + Entry("marker 3"));
|
||||
await h.Pass();
|
||||
h.Overwrite(0, Entry("marker 7") + Entry("marker 8"));
|
||||
h.Tracker.RequestOverwriteCheckForTest();
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
|
||||
using (var cts = new CancellationTokenSource())
|
||||
{
|
||||
cts.Cancel();
|
||||
await h.Pass(cts.Token);
|
||||
}
|
||||
|
||||
// The cancelled pass touched nothing after the rewind; the next one reads it all.
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Equal(new[] { 1, 2, 3, 7, 8 }, h.Matched());
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// The field scenario with the shipped patterns
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task Executor_end_block_written_over_a_detection_invocation_belongs_to_its_own_script()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", ScriptPatterns());
|
||||
|
||||
// Executor E starts its platform script and waits for PowerShell.
|
||||
h.Append(Entry("ExecutorLog AgentExecutor gets invoked") + Entry(PlatformStartLine) + Entry("[Executor] created powershell with process id 12708"));
|
||||
await h.Pass();
|
||||
var executorPosition = h.Length;
|
||||
|
||||
// Detection executor D appends its whole run while E waits — the tracker reads it.
|
||||
var detectionBlock = Entry("ExecutorLog AgentExecutor gets invoked") + Entry(DetectionStartLine)
|
||||
+ Entry("Powershell exit code is 3") + Entry("write output done. output = detected nothing, error = ")
|
||||
+ Entry("Agent executor completed.") + Entry(@"Writing result: False to resultFilePath: C:\x\App_cc46aa62.txt");
|
||||
h.Append(detectionBlock);
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
|
||||
// E ends: its end block lands at its own stale position, over D's lines.
|
||||
var endBlock = Entry("Powershell exit code is 0") + Entry("write output done. output = Hello from E, error = ") + Entry("Agent executor completed.");
|
||||
Assert.True(endBlock.Length < detectionBlock.Length);
|
||||
h.Overwrite(executorPosition, endBlock);
|
||||
|
||||
// Nothing visible signalled the end; the cadence (E is pending) finds the block.
|
||||
h.Now = h.Now.AddSeconds(1.5);
|
||||
await h.Pass();
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
|
||||
// IME's result line (in the other file) completes the script with E's own data.
|
||||
h.Tracker.ProcessLogMessageForTest(ResultLine);
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal(PlatformId, script.PolicyId);
|
||||
Assert.Equal("Success", script.Result);
|
||||
Assert.Equal("ime_policy_result", script.ResultSource);
|
||||
Assert.Equal(0, script.ExitCode);
|
||||
Assert.Equal("Hello from E", script.Stdout);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Detection_exit_lines_read_before_the_overwrite_never_reach_the_platform_script()
|
||||
{
|
||||
using var h = new Harness("AgentExecutor.log", ScriptPatterns());
|
||||
h.Append(Entry("ExecutorLog AgentExecutor gets invoked") + Entry(PlatformStartLine) + Entry("[Executor] created powershell with process id 1"));
|
||||
await h.Pass();
|
||||
h.Append(Entry("ExecutorLog AgentExecutor gets invoked") + Entry(DetectionStartLine)
|
||||
+ Entry("Powershell exit code is 3") + Entry("write output done. output = detected nothing, error = ") + Entry("Agent executor completed."));
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
|
||||
// The platform result arrives without any end block ever becoming visible: held for
|
||||
// the grace, then emitted — the detection's exit code 3 must not stand in.
|
||||
h.Tracker.ProcessLogMessageForTest(ResultLine);
|
||||
Assert.Empty(h.Completed);
|
||||
h.Now = h.Now.Add(ImeLogTracker.PlatformScriptEndBlockGrace);
|
||||
h.Tracker.FlushPendingPlatformScriptResults(h.Now);
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal("Success", script.Result);
|
||||
Assert.Null(script.ExitCode);
|
||||
Assert.Null(script.Stdout);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ime_result_line_hidden_by_an_executor_start_line_is_recovered_from_the_ime_log()
|
||||
{
|
||||
using var h = new Harness("IntuneManagementExtension.log", ScriptPatterns());
|
||||
h.Append(Entry(GeneratedLine, "17") + Entry("Launch powershell executor in user session", "17") + Entry("process id = 10608", "17"));
|
||||
await h.Pass();
|
||||
var servicePosition = h.Length;
|
||||
|
||||
// The executor process appends its telemetry start line at the true end of file.
|
||||
h.Append(Entry("[Telemetry] Telemetry is enabled. Starting mananger...", "1"));
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Empty(h.Completed);
|
||||
|
||||
// The service's first write after the script wait lands at ITS position — over the
|
||||
// executor's line; the block is longer, so the pass sees a fragment at the bookmark.
|
||||
h.Overwrite(servicePosition, Entry("Execution is done, collecting result", "17") + Entry(ResultLine, "17") + Entry("[PowerShell] Success, Result details length: 315", "17"));
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
h.Now = h.Now.AddMilliseconds(100);
|
||||
await h.Pass();
|
||||
Assert.Equal(1, h.Health.OverwriteRewinds);
|
||||
|
||||
// Recovered on the IME side alone (this harness has no AgentExecutor.log): held for
|
||||
// the end block, emitted without an exit code after the grace.
|
||||
Assert.Empty(h.Completed);
|
||||
h.Now = h.Now.Add(ImeLogTracker.PlatformScriptEndBlockGrace);
|
||||
h.Tracker.FlushPendingPlatformScriptResults(h.Now);
|
||||
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal(PlatformId, script.PolicyId);
|
||||
Assert.Equal("Success", script.Result);
|
||||
Assert.Equal("ime_policy_result", script.ResultSource);
|
||||
Assert.Equal("User", script.RunContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
-3
@@ -36,8 +36,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
// silently passing against a stale inline copy.
|
||||
private static readonly string[] RequiredPatternIds =
|
||||
{
|
||||
"PS-AGENT-INVOCATION", "PS-AGENT-SCRIPT-START", "PS-AGENT-EXITCODE",
|
||||
"PS-AGENT-OUTPUT", "PS-SCRIPT-RESULT",
|
||||
"PS-AGENT-INVOCATION", "PS-AGENT-ARG", "PS-AGENT-SCRIPT-START", "PS-AGENT-EXITCODE",
|
||||
"PS-AGENT-OUTPUT", "PS-AGENT-COMPLETED", "PS-SCRIPT-GENERATED", "PS-SCRIPT-CONTEXT",
|
||||
"PS-SCRIPT-RESULT", "HS-INVOCATION",
|
||||
};
|
||||
|
||||
private static List<ImeLogPattern> ScriptPatterns()
|
||||
@@ -83,6 +84,24 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
private const string RemediationStartLine =
|
||||
@"Adding argument remediationScript with value C:\Windows\IMECache\HealthScripts\446f0450-d0ee-404c-8dc0-a74123bde31f_1\detect.ps1 to the named argument list.";
|
||||
|
||||
private const string ImeLog = "IntuneManagementExtension.log";
|
||||
private const string HealthLog = "HealthScripts.log";
|
||||
private const string ExecutorLog = "AgentExecutor.log";
|
||||
|
||||
private const string PlatformGeneratedLine =
|
||||
@"Script file C:\Program Files (x86)\Microsoft Intune Management Extension\Policies\Scripts\00000000-0000-0000-0000-000000000000_c3e0124c-4936-4bfd-afcc-c7fe1d84d104.ps1 is generated";
|
||||
|
||||
private static readonly string PlatformResultLine =
|
||||
$"[PowerShell] User Id = 00000000-0000-0000-0000-000000000000, Policy id = {PlatformId}, policy result = Success";
|
||||
|
||||
// The health-script worker (IME AgentCommon ScriptWorker) writes its command line, the launch
|
||||
// line and the exit line to IntuneManagementExtension.log AND HealthScripts.log — session
|
||||
// 24dc69d1 (IME 1.105.152.0), where the exit line pre-filled a pending platform script's exit
|
||||
// code and the launch line its context.
|
||||
private const string HealthScriptCommandLine =
|
||||
@"""C:\Program Files (x86)\Microsoft Intune Management Extension\agentexecutor.exe"" -remediationScript """"C:\WINDOWS\IMECache\HealthScripts\446f0450-d0ee-404c-8dc0-a74123bde31f_1\detect.ps1"""" ""C:\WINDOWS\IMECache\HealthScripts\446f0450-d0ee-404c-8dc0-a74123bde31f_1\detect.ps1.result"" 60";
|
||||
private const string HealthScriptExitLine = "Powershell execution is done, exitCode = 5";
|
||||
|
||||
private static ImeLogTracker BuildTracker(TempDirectory tmp, out List<ScriptExecutionState> emitted)
|
||||
{
|
||||
var captured = new List<ScriptExecutionState>();
|
||||
@@ -111,9 +130,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
tracker.ProcessLogMessageForTest("Powershell exit code is 0");
|
||||
tracker.ProcessLogMessageForTest("write output done. output = [Compliant] No Classic Teams found, error = ");
|
||||
|
||||
// Authoritative IME result for the PLATFORM script (keyed by policyId).
|
||||
// Authoritative IME result for the PLATFORM script (keyed by policyId). Its own end
|
||||
// block never comes here, so the result is held until the shutdown flush — which must
|
||||
// not pick up the remediation's exit/output either.
|
||||
tracker.ProcessLogMessageForTest(
|
||||
$"[PowerShell] User Id = 00000000-0000-0000-0000-000000000000, Policy id = {PlatformId}, policy result = Failed");
|
||||
Assert.Empty(emitted);
|
||||
tracker.FlushPendingPlatformScriptResults(System.DateTime.UtcNow, force: true);
|
||||
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Equal(PlatformId, script.PolicyId);
|
||||
@@ -145,5 +168,100 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
Assert.Equal(0, script.ExitCode);
|
||||
Assert.Equal("Hello from c3e0124c", script.Stdout);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Health-script lines never feed a platform slot (session 24dc69d1)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void No_shipped_pattern_reads_the_health_script_workers_exit_line()
|
||||
{
|
||||
// "Powershell execution is done, exitCode = N" is the health-script worker's line only;
|
||||
// as PS-SCRIPT-EXITCODE (no scriptType) it pre-filled the exit code of whichever platform
|
||||
// script was pending, which then emitted without waiting for its own end block.
|
||||
foreach (var file in Directory.GetFiles(FindRulesPatternDir(), "*.json"))
|
||||
{
|
||||
var pattern = JsonConvert.DeserializeObject<ImeLogPattern>(File.ReadAllText(file))!;
|
||||
Assert.False(System.Text.RegularExpressions.Regex.IsMatch(HealthScriptExitLine, pattern.Pattern),
|
||||
$"{pattern.PatternId} matches the health-script worker's exit line");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Health_script_exit_line_in_the_ime_log_never_pre_fills_the_platform_slot()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var tracker = BuildTracker(tmp, out var emitted);
|
||||
|
||||
tracker.ProcessLogMessageForTest(PlatformGeneratedLine, sourceFileName: ImeLog);
|
||||
// A health script that ran in parallel finishes: its exit line lands inside the platform
|
||||
// run's window (c81b8053 had "exit code 0" before its executor even started).
|
||||
tracker.ProcessLogMessageForTest(HealthScriptExitLine, sourceFileName: ImeLog);
|
||||
tracker.ProcessLogMessageForTest(PlatformResultLine, sourceFileName: ImeLog);
|
||||
|
||||
// No exit code of its own → held for the end block, never emitted with the health script's 5.
|
||||
Assert.Empty(emitted);
|
||||
tracker.FlushPendingPlatformScriptResults(DateTime.UtcNow, force: true);
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Null(script.ExitCode);
|
||||
Assert.Equal("Success", script.Result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Health_script_launch_line_in_the_ime_log_does_not_flip_the_platform_context()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var tracker = BuildTracker(tmp, out var emitted);
|
||||
|
||||
tracker.ProcessLogMessageForTest(PlatformGeneratedLine, sourceFileName: ImeLog);
|
||||
tracker.ProcessLogMessageForTest("Launch powershell executor in user session", sourceFileName: ImeLog);
|
||||
// The health-script worker launches its executor while the platform script runs: its
|
||||
// command line opens an invocation that owns nothing, so its launch line stays there.
|
||||
tracker.ProcessLogMessageForTest(HealthScriptCommandLine, sourceFileName: ImeLog);
|
||||
tracker.ProcessLogMessageForTest("Launch powershell executor in machine session", sourceFileName: ImeLog);
|
||||
tracker.ProcessLogMessageForTest(PlatformResultLine, sourceFileName: ImeLog);
|
||||
tracker.FlushPendingPlatformScriptResults(DateTime.UtcNow, force: true);
|
||||
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Equal("User", script.RunContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lines_from_the_health_scripts_log_never_resolve_to_a_platform_script()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var tracker = BuildTracker(tmp, out var emitted);
|
||||
|
||||
tracker.ProcessLogMessageForTest("ExecutorLog AgentExecutor gets invoked", sourceFileName: ExecutorLog);
|
||||
tracker.ProcessLogMessageForTest(PlatformStartLine, sourceFileName: ExecutorLog);
|
||||
// HealthScripts.log never carries a platform marker — the run in flight is not the
|
||||
// fallback owner of the lines there.
|
||||
tracker.ProcessLogMessageForTest("Launch powershell executor in machine session", sourceFileName: HealthLog);
|
||||
tracker.ProcessLogMessageForTest(PlatformResultLine, sourceFileName: ImeLog);
|
||||
tracker.FlushPendingPlatformScriptResults(DateTime.UtcNow, force: true);
|
||||
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Null(script.RunContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Context_line_after_an_ime_log_rollover_still_finds_the_run_in_flight()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var tracker = BuildTracker(tmp, out var emitted);
|
||||
|
||||
tracker.ProcessLogMessageForTest(PlatformGeneratedLine, sourceFileName: ImeLog);
|
||||
tracker.ProcessLogMessageForTest("ExecutorLog AgentExecutor gets invoked", sourceFileName: ExecutorLog);
|
||||
tracker.ProcessLogMessageForTest(PlatformStartLine, sourceFileName: ExecutorLog);
|
||||
// IME rolls the log over between its two lines: the fresh file has no markers, but
|
||||
// platform runs open there — the run in flight still owns the context line.
|
||||
tracker.ClearInvocationMarkersForTest(ImeLog);
|
||||
tracker.ProcessLogMessageForTest("Launch powershell executor in user session", sourceFileName: ImeLog);
|
||||
tracker.ProcessLogMessageForTest(PlatformResultLine, sourceFileName: ImeLog);
|
||||
tracker.FlushPendingPlatformScriptResults(DateTime.UtcNow, force: true);
|
||||
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Equal("User", script.RunContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-11
@@ -39,7 +39,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
tracker.SeedPendingPlatformScriptForTesting("dece354a", exitCode: 0, exitObservedAtUtc: observedAt, stdout: "Script start.\nScript end.");
|
||||
|
||||
// Well past the grace window — should emit.
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Equal("dece354a", script.PolicyId);
|
||||
@@ -60,11 +60,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
tracker.SeedPendingPlatformScriptForTesting("60b43a2e", exitCode: 0, exitObservedAtUtc: observedAt);
|
||||
|
||||
// Inside the grace window — IME might still log its result; do not emit yet.
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(5));
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(5));
|
||||
Assert.Empty(emitted);
|
||||
|
||||
// Past the grace window — emit.
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
Assert.Single(emitted);
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
tracker.SeedPendingPlatformScriptForTesting("846cea22", exitCode: 0, exitObservedAtUtc: observedAt);
|
||||
|
||||
// Shutdown flush right after exit — grace not elapsed, but force emits anyway.
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(1), force: true);
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(1), force: true);
|
||||
|
||||
Assert.Single(emitted);
|
||||
}
|
||||
@@ -92,7 +92,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
|
||||
tracker.SeedPendingPlatformScriptForTesting("bad5c0de", exitCode: 1, exitObservedAtUtc: observedAt);
|
||||
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Equal(1, script.ExitCode);
|
||||
@@ -109,7 +109,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
// Started but no exit code yet → still running, must not be emitted even on force flush.
|
||||
tracker.SeedPendingPlatformScriptForTesting("running", exitCode: null, exitObservedAtUtc: null);
|
||||
|
||||
tracker.FlushStalePlatformScriptResults(DateTime.UtcNow, force: true);
|
||||
tracker.FlushPendingPlatformScriptResults(DateTime.UtcNow, force: true);
|
||||
|
||||
Assert.Empty(emitted);
|
||||
}
|
||||
@@ -122,7 +122,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
var observedAt = new DateTime(2026, 6, 19, 12, 59, 4, DateTimeKind.Utc);
|
||||
|
||||
tracker.SeedPendingPlatformScriptForTesting("dece354a", exitCode: 0, exitObservedAtUtc: observedAt);
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
Assert.Single(emitted);
|
||||
|
||||
// IME finally logs its PS-SCRIPT-RESULT line — must NOT produce a second event.
|
||||
@@ -138,7 +138,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
var observedAt = new DateTime(2026, 6, 19, 12, 59, 4, DateTimeKind.Utc);
|
||||
|
||||
tracker.SeedPendingPlatformScriptForTesting("dece354a", exitCode: 0, exitObservedAtUtc: observedAt);
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
|
||||
// The exit-observed timestamp must travel on the emitted state so the adapter can bind
|
||||
// the event to it instead of an unrelated "last matched" line parsed during the grace.
|
||||
@@ -156,14 +156,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
|
||||
// Run 1 of policy X — fallback emits.
|
||||
tracker.SeedPendingPlatformScriptForTesting("policyX", exitCode: 0, exitObservedAtUtc: firstRun);
|
||||
tracker.FlushStalePlatformScriptResults(firstRun.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(firstRun.AddSeconds(20));
|
||||
Assert.Single(emitted);
|
||||
|
||||
// Run 2 of the SAME policy later in the same agent lifetime (IME re-evaluation / retry)
|
||||
// must NOT be deduped away — the fresh start clears the prior emitted-marker.
|
||||
var secondRun = firstRun.AddMinutes(30);
|
||||
tracker.SeedPendingPlatformScriptForTesting("policyX", exitCode: 0, exitObservedAtUtc: secondRun);
|
||||
tracker.FlushStalePlatformScriptResults(secondRun.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(secondRun.AddSeconds(20));
|
||||
Assert.Equal(2, emitted.Count);
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
Assert.Equal("ime_policy_result", script.ResultSource);
|
||||
|
||||
// Later fallback pass must find nothing pending → no duplicate.
|
||||
tracker.FlushStalePlatformScriptResults(observedAt.AddSeconds(20));
|
||||
tracker.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
Assert.Single(emitted);
|
||||
}
|
||||
}
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// The poll loop's timing maxima (session c3ecb568: the loop was not scheduled for 26 s at
|
||||
/// 100 % VM CPU and nothing in the telemetry could show it): the longest pass and the
|
||||
/// longest pause between two passes, on a monotonic clock, restart-safe like the other
|
||||
/// health counters.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerPollTimingTests
|
||||
{
|
||||
/// <summary>Monotonic readings the tracker takes at the start and the end of every pass.</summary>
|
||||
private sealed class Clock
|
||||
{
|
||||
private readonly Queue<long> _readings = new Queue<long>();
|
||||
public void Enqueue(params long[] ms) { foreach (var m in ms) _readings.Enqueue(m); }
|
||||
public long Next() => _readings.Dequeue();
|
||||
}
|
||||
|
||||
private static ImeLogTracker Build(TempDirectory tmp, Clock clock)
|
||||
{
|
||||
var tracker = new ImeLogTracker(tmp.Path, new List<ImeLogPattern>(), new AgentLogger(tmp.Path, AgentLogLevel.Info), stateDirectory: tmp.Path);
|
||||
tracker.MonotonicMillisProvider = clock.Next;
|
||||
return tracker;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Longest_pass_and_longest_pause_are_kept_as_session_maxima()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var clock = new Clock();
|
||||
var tracker = Build(tmp, clock);
|
||||
|
||||
// Pass 1 takes 30 ms; the loop is not scheduled again for 26.1 s; pass 2 takes 10 ms,
|
||||
// pass 3 follows after the normal 100 ms.
|
||||
clock.Enqueue(0, 30, 26130, 26140, 26240, 26245);
|
||||
await tracker.RunPollPassAsync(CancellationToken.None);
|
||||
await tracker.RunPollPassAsync(CancellationToken.None);
|
||||
await tracker.RunPollPassAsync(CancellationToken.None);
|
||||
|
||||
var health = tracker.GetHealthSnapshot();
|
||||
Assert.Equal(30, health.PassMaxMs);
|
||||
Assert.Equal(26100, health.PassGapMaxMs);
|
||||
tracker.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_fresh_tracker_reports_zero()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var tracker = Build(tmp, new Clock());
|
||||
|
||||
var health = tracker.GetHealthSnapshot();
|
||||
Assert.Equal(0, health.PassMaxMs);
|
||||
Assert.Equal(0, health.PassGapMaxMs);
|
||||
tracker.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Maxima_survive_a_restart_and_are_never_lowered()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var clock = new Clock();
|
||||
var tracker1 = Build(tmp, clock);
|
||||
clock.Enqueue(0, 40, 5140, 5150);
|
||||
await tracker1.RunPollPassAsync(CancellationToken.None);
|
||||
await tracker1.RunPollPassAsync(CancellationToken.None);
|
||||
tracker1.SaveStateForTest();
|
||||
tracker1.Dispose();
|
||||
|
||||
var tracker2 = Build(tmp, clock);
|
||||
tracker2.LoadStateForTest();
|
||||
Assert.Equal(40, tracker2.GetHealthSnapshot().PassMaxMs);
|
||||
Assert.Equal(5100, tracker2.GetHealthSnapshot().PassGapMaxMs);
|
||||
|
||||
// The first pass after a restart has no pause to measure; a calmer session afterwards
|
||||
// never lowers what the session already saw.
|
||||
clock.Enqueue(6000, 6010, 6110, 6115);
|
||||
await tracker2.RunPollPassAsync(CancellationToken.None);
|
||||
await tracker2.RunPollPassAsync(CancellationToken.None);
|
||||
var health = tracker2.GetHealthSnapshot();
|
||||
Assert.Equal(40, health.PassMaxMs);
|
||||
Assert.Equal(5100, health.PassGapMaxMs);
|
||||
tracker2.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// The IME result waits for its executor end block (session e7f3c910): PS-SCRIPT-RESULT can
|
||||
/// reach the tracker before the AgentExecutor.log end block of the same run — an overwritten
|
||||
/// block is recovered one pass after the result that triggers the ledger check, the
|
||||
/// AgentExecutor.log read of a pass may precede the exit line by milliseconds, or the poll
|
||||
/// loop stalled. Emitting at once lost the exit code and, when the late start line reopened
|
||||
/// the slot, produced a fallback duplicate 15 s later.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerResultHoldTests
|
||||
{
|
||||
private static readonly DateTime T0 = new DateTime(2026, 9, 10, 22, 13, 35, DateTimeKind.Utc);
|
||||
|
||||
private sealed class Harness : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
public ImeLogTracker Tracker { get; private set; }
|
||||
public DateTime Now { get; set; } = T0;
|
||||
public List<ScriptExecutionState> Completed { get; } = new List<ScriptExecutionState>();
|
||||
public List<ScriptStartedInfo> Started { get; } = new List<ScriptStartedInfo>();
|
||||
|
||||
public Harness() { Tracker = Build(); }
|
||||
|
||||
private ImeLogTracker Build()
|
||||
{
|
||||
var t = new ImeLogTracker(_tmp.Path, new List<ImeLogPattern>(), new AgentLogger(_tmp.Path, AgentLogLevel.Info), stateDirectory: _tmp.Path);
|
||||
t.UtcNowProvider = () => Now;
|
||||
t.OnScriptCompleted = s => Completed.Add(s);
|
||||
t.OnScriptStarted = s => Started.Add(s);
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>Agent restart over the same state directory.</summary>
|
||||
public void Restart()
|
||||
{
|
||||
Tracker.SaveStateForTest();
|
||||
Tracker.Dispose();
|
||||
Tracker = Build();
|
||||
Tracker.LoadStateForTest();
|
||||
}
|
||||
|
||||
/// <summary>A start line (IME "Script file … is generated" or the executor's argument line) with its source timestamp.</summary>
|
||||
public void Start(string id, DateTime lineTs)
|
||||
{
|
||||
Tracker.LastMatchedLogTimestamp = lineTs;
|
||||
Tracker.NextTestEntry();
|
||||
Tracker.HandlePlatformScriptStarted(id);
|
||||
}
|
||||
|
||||
public void Result(string id, DateTime lineTs, string result = "Success")
|
||||
=> Tracker.CompletePlatformScriptFromImeResultForTesting(id, result, lineTs);
|
||||
|
||||
public void Exit(string id, DateTime lineTs, int exitCode = 0)
|
||||
=> Tracker.RecordPlatformScriptExitCodeForTesting(id, exitCode, lineTs);
|
||||
|
||||
/// <summary>The end-of-pass flush at the harness clock.</summary>
|
||||
public void Flush(bool force = false) => Tracker.FlushPendingPlatformScriptResults(Now, force);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Result_before_the_end_block_is_held_and_emits_once_with_the_exit_code()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("376ee51a", T0);
|
||||
h.Now = T0.AddSeconds(2);
|
||||
h.Result("376ee51a", T0.AddSeconds(2));
|
||||
Assert.Empty(h.Completed);
|
||||
h.Now = T0.AddSeconds(2.1);
|
||||
h.Flush();
|
||||
Assert.Empty(h.Completed);
|
||||
|
||||
// The end block surfaces on the next pass (ledger rewind or plain read lag).
|
||||
h.Exit("376ee51a", T0.AddSeconds(1.99));
|
||||
h.Now = T0.AddSeconds(2.2);
|
||||
h.Flush();
|
||||
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal(0, script.ExitCode);
|
||||
Assert.Equal("Success", script.Result);
|
||||
Assert.Equal("ime_policy_result", script.ResultSource);
|
||||
Assert.Equal(T0.AddSeconds(2), script.ResultObservedAtUtc);
|
||||
Assert.Equal("PS-SCRIPT-RESULT", script.ResultPatternId);
|
||||
Assert.Equal(T0, script.StartedAtUtc);
|
||||
|
||||
// Nothing fires twice: later passes, a repeated result line, the 15 s fallback window.
|
||||
h.Now = T0.AddSeconds(30);
|
||||
h.Flush();
|
||||
h.Result("376ee51a", T0.AddSeconds(2));
|
||||
Assert.Single(h.Completed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Result_with_the_end_block_already_read_emits_at_once()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("847da54e", T0);
|
||||
h.Exit("847da54e", T0.AddSeconds(2.3));
|
||||
h.Now = T0.AddSeconds(2.31);
|
||||
h.Result("847da54e", T0.AddSeconds(2.31));
|
||||
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal(0, script.ExitCode);
|
||||
Assert.Null(script.ResultHeldSinceUtc);
|
||||
Assert.Equal(T0.AddSeconds(2.31), script.ResultObservedAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Held_result_emits_without_exit_code_after_the_grace()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("784fcaf5", T0);
|
||||
h.Now = T0.AddSeconds(2);
|
||||
h.Result("784fcaf5", T0.AddSeconds(2));
|
||||
|
||||
h.Now = T0.AddSeconds(2).Add(ImeLogTracker.PlatformScriptEndBlockGrace).AddMilliseconds(-100);
|
||||
h.Flush();
|
||||
Assert.Empty(h.Completed);
|
||||
|
||||
h.Now = T0.AddSeconds(2).Add(ImeLogTracker.PlatformScriptEndBlockGrace);
|
||||
h.Flush();
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Null(script.ExitCode);
|
||||
Assert.Equal("Success", script.Result);
|
||||
Assert.Equal("ime_policy_result", script.ResultSource);
|
||||
|
||||
// An exit line surfacing after the emit is dropped — no second event, no fallback.
|
||||
h.Exit("784fcaf5", T0.AddSeconds(1.99));
|
||||
h.Now = T0.AddSeconds(40);
|
||||
h.Flush();
|
||||
Assert.Single(h.Completed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Shutdown_flush_emits_a_held_result_at_once()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("a52e4f47", T0);
|
||||
h.Now = T0.AddSeconds(2);
|
||||
h.Result("a52e4f47", T0.AddSeconds(2), "Failed");
|
||||
Assert.Empty(h.Completed);
|
||||
|
||||
h.Flush(force: true);
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal("Failed", script.Result);
|
||||
Assert.Null(script.ExitCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Late_start_line_of_an_emitted_run_opens_no_new_run()
|
||||
{
|
||||
// Session e7f3c910, 376ee51a: the result was emitted, THEN the executor's start and
|
||||
// exit lines of the same run were read (a 2 s poll stall) — the start opened a second
|
||||
// slot and the exit code became a fallback duplicate 15 s later.
|
||||
using var h = new Harness();
|
||||
h.Start("376ee51a", T0);
|
||||
h.Exit("376ee51a", T0.AddSeconds(1.99));
|
||||
h.Now = T0.AddSeconds(2);
|
||||
h.Result("376ee51a", T0.AddSeconds(2));
|
||||
Assert.Single(h.Completed);
|
||||
Assert.Single(h.Started);
|
||||
|
||||
h.Start("376ee51a", T0.AddMilliseconds(300));
|
||||
Assert.Single(h.Started);
|
||||
h.Exit("376ee51a", T0.AddSeconds(1.99));
|
||||
h.Now = T0.AddSeconds(30);
|
||||
h.Flush();
|
||||
Assert.Single(h.Completed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Start_line_newer_than_the_emitted_result_is_the_next_run()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("338d9434", T0);
|
||||
h.Exit("338d9434", T0.AddSeconds(1));
|
||||
h.Now = T0.AddSeconds(1);
|
||||
h.Result("338d9434", T0.AddSeconds(1));
|
||||
Assert.Single(h.Completed);
|
||||
|
||||
// IME re-runs the policy after the user signed in.
|
||||
h.Start("338d9434", T0.AddMinutes(7));
|
||||
Assert.Equal(2, h.Started.Count);
|
||||
h.Exit("338d9434", T0.AddMinutes(7).AddSeconds(3));
|
||||
h.Now = T0.AddMinutes(7).AddSeconds(3);
|
||||
h.Result("338d9434", T0.AddMinutes(7).AddSeconds(3));
|
||||
Assert.Equal(2, h.Completed.Count);
|
||||
Assert.Equal(T0.AddMinutes(7), h.Completed[1].StartedAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Newer_start_line_closes_a_held_result_and_starts_the_next_run()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("c81b8053", T0);
|
||||
h.Now = T0.AddSeconds(2);
|
||||
h.Result("c81b8053", T0.AddSeconds(2));
|
||||
Assert.Empty(h.Completed);
|
||||
|
||||
// The end block never surfaced before the policy ran again.
|
||||
h.Start("c81b8053", T0.AddSeconds(4));
|
||||
var first = Assert.Single(h.Completed);
|
||||
Assert.Null(first.ExitCode);
|
||||
Assert.Equal(T0, first.StartedAtUtc);
|
||||
Assert.Equal(2, h.Started.Count);
|
||||
|
||||
h.Exit("c81b8053", T0.AddSeconds(6));
|
||||
h.Now = T0.AddSeconds(6);
|
||||
h.Result("c81b8053", T0.AddSeconds(6));
|
||||
Assert.Equal(2, h.Completed.Count);
|
||||
Assert.Equal(0, h.Completed[1].ExitCode);
|
||||
Assert.Equal(T0.AddSeconds(4), h.Completed[1].StartedAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Result_without_a_start_takes_the_recovered_start_line_and_end_block()
|
||||
{
|
||||
// Both the start block and the end block were hidden when the result arrived; the
|
||||
// ledger rewind the result triggers brings both back on the next pass.
|
||||
using var h = new Harness();
|
||||
h.Now = T0.AddSeconds(2);
|
||||
h.Result("d39eeef3", T0.AddSeconds(2));
|
||||
Assert.Empty(h.Completed);
|
||||
|
||||
h.Start("d39eeef3", T0);
|
||||
Assert.Empty(h.Started);
|
||||
h.Exit("d39eeef3", T0.AddSeconds(1.99));
|
||||
h.Now = T0.AddSeconds(2.2);
|
||||
h.Flush();
|
||||
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal(T0, script.StartedAtUtc);
|
||||
Assert.Equal(0, script.ExitCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Held_result_survives_a_restart()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("832e27bc", T0);
|
||||
h.Now = T0.AddSeconds(2);
|
||||
h.Result("832e27bc", T0.AddSeconds(2));
|
||||
h.Restart();
|
||||
Assert.Empty(h.Completed);
|
||||
|
||||
h.Exit("832e27bc", T0.AddSeconds(1.99));
|
||||
h.Now = T0.AddSeconds(2.5);
|
||||
h.Flush();
|
||||
var script = Assert.Single(h.Completed);
|
||||
Assert.Equal(0, script.ExitCode);
|
||||
Assert.Equal(T0.AddSeconds(2), script.ResultObservedAtUtc);
|
||||
Assert.Equal("PS-SCRIPT-RESULT", script.ResultPatternId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Emitted_marker_keeps_the_run_timestamp_across_a_restart()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Start("89b3cbcd", T0);
|
||||
h.Exit("89b3cbcd", T0.AddSeconds(1));
|
||||
h.Now = T0.AddSeconds(1);
|
||||
h.Result("89b3cbcd", T0.AddSeconds(1));
|
||||
h.Restart();
|
||||
|
||||
h.Start("89b3cbcd", T0.AddMilliseconds(500)); // late line of the emitted run
|
||||
Assert.Single(h.Started);
|
||||
h.Start("89b3cbcd", T0.AddMinutes(5)); // the next run
|
||||
Assert.Equal(2, h.Started.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Marker_list_from_an_older_state_file_still_dedups()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var persistence = new ImeTrackerStatePersistence(tmp.Path, new AgentLogger(tmp.Path, AgentLogLevel.Info));
|
||||
persistence.Save(new ImeTrackerStateData { PlatformScriptResultEmitted = new List<string> { "policyZ" } });
|
||||
|
||||
var completed = new List<ScriptExecutionState>();
|
||||
var started = new List<ScriptStartedInfo>();
|
||||
var tracker = new ImeLogTracker(tmp.Path, new List<ImeLogPattern>(), new AgentLogger(tmp.Path, AgentLogLevel.Info), stateDirectory: tmp.Path);
|
||||
tracker.OnScriptCompleted = s => completed.Add(s);
|
||||
tracker.OnScriptStarted = s => started.Add(s);
|
||||
tracker.LoadStateForTest();
|
||||
|
||||
tracker.CompletePlatformScriptFromImeResultForTesting("policyZ", "Success", T0);
|
||||
Assert.Empty(completed);
|
||||
|
||||
// Without a timestamp on the marker every start line is a new run, as before.
|
||||
tracker.LastMatchedLogTimestamp = T0;
|
||||
tracker.HandlePlatformScriptStarted("policyZ");
|
||||
Assert.Single(started);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Emitted_marker_is_capped_at_the_clock_so_the_next_run_still_opens_a_slot()
|
||||
{
|
||||
// Session 4377911b: the result line was re-read after an overwrite rewind and resolved
|
||||
// in the reader's zone, one hour ahead of the clock. Stored uncapped, that stamp made
|
||||
// the genuine second run's start line read as a late line of the first run and its
|
||||
// result a duplicate.
|
||||
using var h = new Harness();
|
||||
h.Start("d94468af", T0.AddSeconds(-10));
|
||||
h.Result("d94468af", T0.AddHours(1));
|
||||
h.Exit("d94468af", T0.AddSeconds(-1));
|
||||
h.Flush();
|
||||
Assert.Single(h.Completed);
|
||||
|
||||
// The second run, two minutes later on the clock — still "before" the uncapped stamp.
|
||||
h.Now = T0.AddMinutes(2);
|
||||
h.Start("d94468af", h.Now.AddSeconds(-5));
|
||||
h.Result("d94468af", h.Now.AddSeconds(-1));
|
||||
h.Exit("d94468af", h.Now.AddSeconds(-2));
|
||||
h.Flush();
|
||||
|
||||
Assert.Equal(2, h.Completed.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
-5
@@ -41,7 +41,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
// Run 1: exit code seen, shutdown force-flush emits the fallback completion.
|
||||
var tracker1 = BuildTracker(tmp, out var emitted1);
|
||||
tracker1.SeedPendingPlatformScriptForTesting("policyA", exitCode: 0, exitObservedAtUtc: observedAt);
|
||||
tracker1.FlushStalePlatformScriptResults(observedAt.AddSeconds(1), force: true);
|
||||
tracker1.FlushPendingPlatformScriptResults(observedAt.AddSeconds(1), force: true);
|
||||
Assert.Single(emitted1);
|
||||
tracker1.SaveStateForTest();
|
||||
|
||||
@@ -68,7 +68,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
// Restarted tracker continues the grace window instead of dropping the script.
|
||||
var tracker2 = BuildTracker(tmp, out var emitted2);
|
||||
tracker2.LoadStateForTest();
|
||||
tracker2.FlushStalePlatformScriptResults(observedAt.AddSeconds(20));
|
||||
tracker2.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
|
||||
var script = Assert.Single(emitted2);
|
||||
Assert.Equal("policyB", script.PolicyId);
|
||||
@@ -84,7 +84,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
|
||||
var tracker1 = BuildTracker(tmp, out _);
|
||||
tracker1.SeedPendingPlatformScriptForTesting("policyC", exitCode: 0, exitObservedAtUtc: observedAt);
|
||||
tracker1.FlushStalePlatformScriptResults(observedAt.AddSeconds(1), force: true);
|
||||
tracker1.FlushPendingPlatformScriptResults(observedAt.AddSeconds(1), force: true);
|
||||
tracker1.SaveStateForTest();
|
||||
|
||||
// Restart, then a genuine RE-RUN of the same policy (fresh start clears the marker).
|
||||
@@ -109,8 +109,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
var tracker = BuildTracker(tmp, out var emitted);
|
||||
tracker.LoadStateForTest(); // must not throw
|
||||
|
||||
// Degrades to pre-fix behavior: no markers restored, normal emission works.
|
||||
// Degrades to pre-fix behavior: no markers restored, normal emission works (the
|
||||
// result waits for its end block until the shutdown flush).
|
||||
tracker.CompletePlatformScriptFromImeResultForTesting("policyD", "Success");
|
||||
tracker.FlushPendingPlatformScriptResults(DateTime.UtcNow, force: true);
|
||||
Assert.Single(emitted);
|
||||
}
|
||||
|
||||
@@ -128,8 +130,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
tracker.CompletePlatformScriptFromImeResultForTesting("policyE", "Failed", run2Start.AddMinutes(-5));
|
||||
Assert.Empty(emitted);
|
||||
|
||||
// Run 2's own result (newer than its start) still emits normally.
|
||||
// Run 2's own result (newer than its start) still emits normally — held for the end
|
||||
// block until the shutdown flush, since none is seeded here.
|
||||
tracker.CompletePlatformScriptFromImeResultForTesting("policyE", "Success", run2Start.AddMinutes(2));
|
||||
tracker.FlushPendingPlatformScriptResults(run2Start.AddMinutes(2), force: true);
|
||||
var script = Assert.Single(emitted);
|
||||
Assert.Equal("Success", script.Result);
|
||||
Assert.Equal(run2Start, script.StartedAtUtc);
|
||||
@@ -150,5 +154,45 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
Assert.False(tracker2.TryClaimScriptTimeoutSuspected("policyF")); // cross-restart dedup
|
||||
Assert.True(tracker2.TryClaimScriptTimeoutSuspected("policyG")); // other policies unaffected
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Line_provenance_of_a_pending_script_survives_restart()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var observedAt = new DateTime(2026, 9, 17, 13, 20, 7, DateTimeKind.Utc);
|
||||
var start = new CmTraceLineProvenance
|
||||
{
|
||||
SourceLocalTs = new DateTime(2026, 9, 17, 15, 19, 57, DateTimeKind.Unspecified),
|
||||
Origin = CmTraceOffsetOrigin.LineAnchored,
|
||||
OffsetMinutes = 120,
|
||||
MeasuredWriterOffsetMinutes = 120,
|
||||
SourceFileName = "IntuneManagementExtension.log",
|
||||
};
|
||||
var exit = new CmTraceLineProvenance
|
||||
{
|
||||
SourceLocalTs = new DateTime(2026, 9, 17, 15, 20, 7, DateTimeKind.Unspecified),
|
||||
Origin = CmTraceOffsetOrigin.None,
|
||||
OffsetMinutes = 60,
|
||||
SourceFileName = "AgentExecutor.log",
|
||||
};
|
||||
|
||||
var tracker1 = BuildTracker(tmp, out _);
|
||||
tracker1.SeedPendingPlatformScriptForTesting("policyH", exitCode: 0, exitObservedAtUtc: observedAt,
|
||||
startedAtUtc: observedAt.AddSeconds(-10), startedAtProvenance: start, exitProvenance: exit);
|
||||
tracker1.SaveStateForTest();
|
||||
|
||||
var tracker2 = BuildTracker(tmp, out var emitted2);
|
||||
tracker2.LoadStateForTest();
|
||||
tracker2.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
|
||||
|
||||
var script = Assert.Single(emitted2);
|
||||
Assert.Equal(CmTraceOffsetOrigin.LineAnchored, script.StartedAtProvenance.Origin);
|
||||
Assert.Equal(120, script.StartedAtProvenance.OffsetMinutes);
|
||||
Assert.Equal(start.SourceLocalTs, script.StartedAtProvenance.SourceLocalTs);
|
||||
Assert.Equal(DateTimeKind.Unspecified, script.StartedAtProvenance.SourceLocalTs!.Value.Kind); // no zone was ever attached
|
||||
Assert.Equal("AgentExecutor.log", script.ExitProvenance.SourceFileName);
|
||||
Assert.Equal(60, script.ExitProvenance.OffsetMinutes);
|
||||
Assert.Null(script.ResultProvenance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// IME re-runs health-script policies on its own schedule for as long as the device is up.
|
||||
/// A session that waited days for its user reported every hourly run of every policy
|
||||
/// (field: 9 policies × 94 runs in one session). The gate emits the first run and every
|
||||
/// changed result, counts the rest, and keeps the start/result pairing intact that the
|
||||
/// running indicators rely on.
|
||||
/// </summary>
|
||||
public sealed class RecurringScriptGateTests
|
||||
{
|
||||
private const string Policy = "11111111-2222-3333-4444-555555555555";
|
||||
private static readonly DateTime T0 = new DateTime(2026, 9, 16, 20, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static ScriptExecutionState Early(string compliance, int exit = 0, string? stderr = null) =>
|
||||
new ScriptExecutionState
|
||||
{
|
||||
PolicyId = Policy, ScriptType = "remediation", ScriptPart = "detection",
|
||||
ComplianceResult = compliance, ExitCode = exit, Stderr = stderr, DurationBasis = "script_runtime",
|
||||
};
|
||||
|
||||
private static ScriptExecutionState Consolidated(string compliance, int exit = 0, int status = 1) =>
|
||||
new ScriptExecutionState
|
||||
{
|
||||
PolicyId = Policy, ScriptType = "remediation", ScriptPart = "detection",
|
||||
ComplianceResult = compliance, ExitCode = exit, RemediationStatus = status,
|
||||
DurationBasis = "cycle_including_reporting_latency",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void First_run_emits_start_and_result()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
|
||||
Assert.True(gate.OnStart(Policy, T0, "6", "HS-SCRIPT-START"));
|
||||
Assert.True(gate.OnResult(Early("True"), T0.AddSeconds(5), out var released));
|
||||
Assert.Null(released);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repeated_result_is_counted_and_its_start_stays_held()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "HS-SCRIPT-START");
|
||||
gate.OnResult(Early("True"), T0.AddSeconds(5), out _);
|
||||
|
||||
Assert.False(gate.OnStart(Policy, T0.AddHours(1), "6", "HS-SCRIPT-START"));
|
||||
Assert.False(gate.OnResult(Early("True"), T0.AddHours(1).AddSeconds(5), out var released));
|
||||
Assert.Null(released);
|
||||
|
||||
var summary = Assert.Single(gate.TakeSummaries());
|
||||
Assert.Equal(2, summary.RunsObserved);
|
||||
Assert.Equal(1, summary.RunsCollapsed);
|
||||
Assert.Equal(1, summary.CollapsedResults);
|
||||
Assert.Equal(T0.AddHours(1).AddSeconds(5), summary.LastCollapsedAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Changed_result_releases_the_held_start_with_its_own_timestamp()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "HS-SCRIPT-START");
|
||||
gate.OnResult(Early("True"), T0.AddSeconds(5), out _);
|
||||
|
||||
var secondStart = T0.AddHours(1);
|
||||
gate.OnStart(Policy, secondStart, "6", "HS-SCRIPT-START");
|
||||
Assert.True(gate.OnResult(Early("False", exit: 1), secondStart.AddSeconds(5), out var released));
|
||||
|
||||
Assert.NotNull(released);
|
||||
Assert.Equal(Policy, released.PolicyId);
|
||||
Assert.Equal(secondStart, released.SourceTimestampUtc);
|
||||
Assert.Equal("HS-SCRIPT-START", released.PatternId);
|
||||
Assert.Equal("6", released.PolicyType);
|
||||
Assert.Empty(gate.TakeSummaries());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void New_stderr_counts_as_a_changed_result()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "p");
|
||||
gate.OnResult(Early("True"), T0, out _);
|
||||
|
||||
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
|
||||
Assert.True(gate.OnResult(Early("True", stderr: "Get-ChildItem : path not found"), T0.AddHours(1), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Early_signal_and_consolidated_result_do_not_overwrite_each_other()
|
||||
{
|
||||
// Both describe the detection phase, but only the consolidated one knows
|
||||
// RemediationStatus. Sharing one signature slot would make every run look changed.
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "p");
|
||||
Assert.True(gate.OnResult(Early("True"), T0, out _));
|
||||
Assert.True(gate.OnResult(Consolidated("True"), T0.AddMinutes(1), out _));
|
||||
|
||||
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
|
||||
Assert.False(gate.OnResult(Early("True"), T0.AddHours(1), out _));
|
||||
Assert.False(gate.OnResult(Consolidated("True"), T0.AddHours(1).AddMinutes(1), out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Held_start_without_result_is_released_only_after_the_grace()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "p");
|
||||
gate.OnResult(Early("True"), T0, out _);
|
||||
var heldAt = T0.AddHours(1);
|
||||
gate.OnStart(Policy, heldAt, "6", "p");
|
||||
|
||||
Assert.Empty(gate.ReleaseStartsWithoutResult(heldAt.AddMinutes(29), TimeSpan.FromMinutes(30)));
|
||||
|
||||
var released = Assert.Single(gate.ReleaseStartsWithoutResult(heldAt.AddMinutes(31), TimeSpan.FromMinutes(30)));
|
||||
Assert.Equal(heldAt, released.SourceTimestampUtc);
|
||||
Assert.Empty(gate.ReleaseStartsWithoutResult(heldAt.AddHours(2), TimeSpan.FromMinutes(30)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Held_start_whose_result_was_collapsed_is_never_released_as_unfinished()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "p");
|
||||
gate.OnResult(Early("True"), T0, out _);
|
||||
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
|
||||
gate.OnResult(Early("True"), T0.AddHours(1), out _);
|
||||
|
||||
Assert.Empty(gate.ReleaseStartsWithoutResult(T0.AddDays(1), TimeSpan.FromMinutes(30)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Run_superseded_by_the_next_start_counts_as_without_result()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "p");
|
||||
gate.OnResult(Early("True"), T0, out _);
|
||||
gate.OnStart(Policy, T0.AddHours(1), "6", "p"); // no result
|
||||
gate.OnStart(Policy, T0.AddHours(2), "6", "p");
|
||||
gate.OnResult(Early("True"), T0.AddHours(2), out _);
|
||||
|
||||
var summary = Assert.Single(gate.TakeSummaries());
|
||||
Assert.Equal(3, summary.RunsObserved);
|
||||
Assert.Equal(1, summary.RunsWithoutResult);
|
||||
Assert.Equal(1, summary.RunsCollapsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Summary_reports_growth_only()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "p");
|
||||
gate.OnResult(Early("True"), T0, out _);
|
||||
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
|
||||
gate.OnResult(Early("True"), T0.AddHours(1), out _);
|
||||
|
||||
Assert.Single(gate.TakeSummaries());
|
||||
Assert.Empty(gate.TakeSummaries());
|
||||
|
||||
gate.OnStart(Policy, T0.AddHours(2), "6", "p");
|
||||
gate.OnResult(Early("True"), T0.AddHours(2), out _);
|
||||
Assert.Equal(2, Assert.Single(gate.TakeSummaries()).RunsCollapsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void State_round_trips_through_json()
|
||||
{
|
||||
var gate = new RecurringScriptGate();
|
||||
gate.OnStart(Policy, T0, "6", "p");
|
||||
gate.OnResult(Early("True"), T0, out _);
|
||||
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
|
||||
|
||||
var json = JsonConvert.SerializeObject(gate.ToPersisted());
|
||||
var restored = new RecurringScriptGate();
|
||||
restored.Restore(JsonConvert.DeserializeObject<Dictionary<string, RecurringScriptPolicyState>>(json));
|
||||
|
||||
// The restored gate still knows the last report and still holds the second start.
|
||||
Assert.True(restored.OnResult(Early("False", exit: 1), T0.AddHours(1).AddSeconds(5), out var released));
|
||||
Assert.Equal(T0.AddHours(1), released.SourceTimestampUtc);
|
||||
}
|
||||
|
||||
// ── Through the tracker ───────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly List<ScriptStartedInfo> Started = new List<ScriptStartedInfo>();
|
||||
public readonly List<ScriptExecutionState> Completed = new List<ScriptExecutionState>();
|
||||
public readonly List<ScriptRecurrenceSummary> Summaries = new List<ScriptRecurrenceSummary>();
|
||||
public readonly ImeLogTracker Tracker;
|
||||
|
||||
public Rig(TempDirectory tmp)
|
||||
{
|
||||
Tracker = new ImeLogTracker(
|
||||
logFolder: tmp.Path,
|
||||
patterns: new List<ImeLogPattern>(),
|
||||
logger: new AgentLogger(tmp.Path, AgentLogLevel.Info),
|
||||
stateDirectory: tmp.Path);
|
||||
Tracker.OnScriptStarted = Started.Add;
|
||||
Tracker.OnScriptCompleted = Completed.Add;
|
||||
Tracker.OnScriptRecurrenceSummary = Summaries.Add;
|
||||
}
|
||||
|
||||
public void Run(DateTime startedAtUtc, string compliance)
|
||||
{
|
||||
Tracker.HandleHealthScriptStartForTest(Policy, startedAtUtc);
|
||||
Tracker.HandleHealthScriptDetectionResultForTest(Policy, compliance, "pre", exitCode: compliance == "True" ? 0 : 1);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tracker_collapses_repeats_across_a_restart_and_reports_them_on_stop()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
|
||||
var first = new Rig(tmp);
|
||||
first.Run(T0, "True");
|
||||
first.Run(T0.AddHours(1), "True");
|
||||
Assert.Single(first.Started);
|
||||
Assert.Single(first.Completed);
|
||||
first.Tracker.SaveStateForTest();
|
||||
|
||||
// Restart (reboot kill, WhiteGlove Part 2): the last report and the counter are back.
|
||||
var second = new Rig(tmp);
|
||||
second.Tracker.LoadStateForTest();
|
||||
second.Run(T0.AddHours(2), "True");
|
||||
Assert.Empty(second.Started);
|
||||
Assert.Empty(second.Completed);
|
||||
|
||||
second.Run(T0.AddHours(3), "False");
|
||||
var start = Assert.Single(second.Started);
|
||||
Assert.Equal(T0.AddHours(3), start.SourceTimestampUtc);
|
||||
Assert.Equal("False", Assert.Single(second.Completed).ComplianceResult);
|
||||
|
||||
second.Tracker.FlushRecurringScripts(T0.AddHours(4), shuttingDown: true);
|
||||
var summary = Assert.Single(second.Summaries);
|
||||
Assert.Equal(4, summary.RunsObserved);
|
||||
Assert.Equal(2, summary.RunsCollapsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tracker_leaves_platform_scripts_alone()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var rig = new Rig(tmp);
|
||||
var observedAt = T0;
|
||||
|
||||
for (var run = 0; run < 2; run++)
|
||||
{
|
||||
rig.Tracker.SeedPendingPlatformScriptForTesting("platformA", exitCode: 0, exitObservedAtUtc: observedAt.AddMinutes(run * 10));
|
||||
rig.Tracker.CompletePlatformScriptFromImeResultForTesting("platformA", "Success", observedAt.AddMinutes(run * 10 + 1));
|
||||
}
|
||||
|
||||
Assert.Equal(2, rig.Completed.Count(s => s.ScriptType == "platform"));
|
||||
rig.Tracker.FlushRecurringScripts(T0.AddDays(1), shuttingDown: true);
|
||||
Assert.Empty(rig.Summaries);
|
||||
}
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
#nullable enable
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.Agent.V2.Core.Configuration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Transport;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
|
||||
{
|
||||
/// <summary>
|
||||
/// The hard-blocked event-log channels (Security, PowerShell, Sysmon) are unreadable through
|
||||
/// the diagnostics package as well — by path, by wildcard, by resolved channel, and in
|
||||
/// unrestricted mode. Before this the block held only in the event-log collector.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticsEventLogBlockTests
|
||||
{
|
||||
private const string WinevtLogs = @"C:\Windows\System32\winevt\Logs";
|
||||
|
||||
// A channel no machine has: the export fails and the packager falls back to the raw copy.
|
||||
private const string HarmlessChannel = "AutopilotMonitor-Tests-NoSuchChannel/Operational";
|
||||
|
||||
[Theory]
|
||||
[InlineData("Security.evtx")]
|
||||
[InlineData("security.EVTX")]
|
||||
[InlineData("Microsoft-Windows-PowerShell%4Operational.evtx")]
|
||||
[InlineData("Microsoft-Windows-PowerShell%4Admin.evtx")]
|
||||
[InlineData("Windows PowerShell.evtx")]
|
||||
[InlineData("Microsoft-Windows-Sysmon%4Operational.evtx")]
|
||||
[InlineData("Archive-Security-2026-09-21-10-15-30-123.evtx")]
|
||||
[InlineData("Archive-Microsoft-Windows-PowerShell%4Operational-2026-09-21-10-15-30-123.evtx")]
|
||||
public void Hard_blocked_channel_files_are_recognised_by_name(string fileName)
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.IsHardBlockedEventLogFile(Path.Combine(WinevtLogs, fileName)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("System.evtx")]
|
||||
[InlineData("Application.evtx")]
|
||||
[InlineData("SecurityAudit.evtx")]
|
||||
[InlineData("Security.log")]
|
||||
[InlineData("Microsoft-Windows-Security-Mitigations%4KernelMode.evtx")]
|
||||
// Same boundary as the collector: only '/' continues a blocked channel name.
|
||||
[InlineData("Microsoft-Windows-PowerShell-DesiredStateConfiguration-FileDownloadManager%4Operational.evtx")]
|
||||
[InlineData("Archive-System-2026-09-21-10-15-30-123.evtx")]
|
||||
public void Other_files_are_not_mistaken_for_a_blocked_channel(string fileName)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.IsHardBlockedEventLogFile(Path.Combine(WinevtLogs, fileName)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Path_guard_refuses_a_blocked_channel_file_in_every_mode(bool unrestrictedMode)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(
|
||||
WinevtLogs + @"\Security.evtx", unrestrictedMode));
|
||||
Assert.False(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(
|
||||
WinevtLogs + @"\Microsoft-Windows-PowerShell%4Operational.evtx", unrestrictedMode));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Path_guard_still_admits_other_channels_and_wildcards()
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(WinevtLogs + @"\System.evtx"));
|
||||
// Undecidable on the string — the packager filters per file (tests below).
|
||||
Assert.True(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(WinevtLogs + @"\*.evtx"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Security", true)]
|
||||
[InlineData("Microsoft-Windows-PowerShell/Operational", true)]
|
||||
[InlineData(" Windows PowerShell ", true)]
|
||||
[InlineData("Microsoft-Windows-Sysmon/Operational", true)]
|
||||
[InlineData("System", false)]
|
||||
[InlineData("", false)]
|
||||
[InlineData(null, false)]
|
||||
public void Channel_block_is_one_matcher_for_collector_and_package(string? channel, bool blocked)
|
||||
{
|
||||
Assert.Equal(blocked, GatherRuleGuards.IsHardBlockedEventLogChannel(channel!));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ packager ----
|
||||
|
||||
// %TEMP% lives under C:\Users, which the path guard blocks in every mode, so the
|
||||
// configured folder sits beside the test assembly and the run is unrestricted — which
|
||||
// is also the strongest form of the claim: not even unrestricted mode collects these.
|
||||
private sealed class EvtxFolder : System.IDisposable
|
||||
{
|
||||
public string Path { get; } = System.IO.Path.Combine(
|
||||
System.AppContext.BaseDirectory, "diag-evtx-" + System.Guid.NewGuid().ToString("N"));
|
||||
|
||||
public EvtxFolder(params string[] fileNames)
|
||||
{
|
||||
Directory.CreateDirectory(Path);
|
||||
foreach (var name in fileNames)
|
||||
File.WriteAllBytes(System.IO.Path.Combine(Path, name), new byte[] { 1, 2, 3 });
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Path, recursive: true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static DiagnosticsPackageService BuildService(
|
||||
TempDirectory scratch, string configuredPath, System.Func<string, string> channelResolver)
|
||||
{
|
||||
var logger = new AgentLogger(Directory.CreateDirectory(Path.Combine(scratch.Path, "logs")).FullName);
|
||||
var apiClient = new BackendApiClient(
|
||||
httpClient: new System.Net.Http.HttpClient(),
|
||||
baseUrl: "http://localhost",
|
||||
manufacturer: string.Empty,
|
||||
model: string.Empty,
|
||||
serialNumber: string.Empty,
|
||||
useBootstrapTokenAuth: false,
|
||||
bootstrapToken: null,
|
||||
agentVersion: "0.0.0",
|
||||
logger: logger);
|
||||
|
||||
var cfg = new AgentConfiguration
|
||||
{
|
||||
SessionId = "S1",
|
||||
TenantId = "T1",
|
||||
ApiBaseUrl = "http://localhost",
|
||||
UnrestrictedMode = true,
|
||||
};
|
||||
cfg.DiagnosticsLogPaths.Add(new DiagnosticsLogPath { Path = configuredPath });
|
||||
|
||||
string Sub(string name) => Directory.CreateDirectory(Path.Combine(scratch.Path, name)).FullName;
|
||||
return new DiagnosticsPackageService(
|
||||
cfg,
|
||||
logger,
|
||||
apiClient,
|
||||
agentLogFolderOverride: Sub("agentlogs"),
|
||||
imeLogFolderOverride: Sub("ime"),
|
||||
agentStateFolderOverride: Sub("state"),
|
||||
agentSpoolFolderOverride: Sub("spool"),
|
||||
agentDataFolderOverride: Sub("data"),
|
||||
sectionFolderOverrides: null,
|
||||
devicePreparationProbe: () => false)
|
||||
{
|
||||
EventLogChannelResolver = channelResolver,
|
||||
};
|
||||
}
|
||||
|
||||
private static List<string> ZipEntryNames(byte[] bytes)
|
||||
{
|
||||
using var ms = new MemoryStream(bytes);
|
||||
using var archive = new ZipArchive(ms, ZipArchiveMode.Read);
|
||||
return archive.Entries.Select(e => e.FullName).ToList();
|
||||
}
|
||||
|
||||
private static string ReadManifest(byte[] bytes)
|
||||
{
|
||||
using var ms = new MemoryStream(bytes);
|
||||
using var archive = new ZipArchive(ms, ZipArchiveMode.Read);
|
||||
using var reader = new StreamReader(archive.GetEntry("package-manifest.txt")!.Open());
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wildcard_entry_skips_blocked_channel_files_and_keeps_the_rest()
|
||||
{
|
||||
using var scratch = new TempDirectory();
|
||||
using var folder = new EvtxFolder(
|
||||
"Security.evtx", "Microsoft-Windows-PowerShell%4Operational.evtx", "Setup.evtx");
|
||||
|
||||
var service = BuildService(scratch, Path.Combine(folder.Path, "*.evtx"), _ => HarmlessChannel);
|
||||
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: false);
|
||||
|
||||
var entries = ZipEntryNames(bytes);
|
||||
Assert.Contains(entries, e => e.EndsWith("/Setup.evtx"));
|
||||
Assert.DoesNotContain(entries, e => e.EndsWith("Security.evtx"));
|
||||
Assert.DoesNotContain(entries, e => e.Contains("PowerShell"));
|
||||
|
||||
var manifest = ReadManifest(bytes);
|
||||
Assert.Contains("BLOCKED (event-log channel guard", manifest);
|
||||
Assert.Contains("Security.evtx", manifest);
|
||||
Assert.Equal(2, service.LastPackaging!.ProblemsByKind["path-guard"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void File_with_a_harmless_name_is_blocked_when_it_resolves_to_a_blocked_channel()
|
||||
{
|
||||
// A channel is free to write to any file name; and the resolver's naming fallback
|
||||
// maps a stray file onto a live channel. The export must never read that channel.
|
||||
using var scratch = new TempDirectory();
|
||||
using var folder = new EvtxFolder("Harmless.evtx");
|
||||
|
||||
var service = BuildService(scratch, Path.Combine(folder.Path, "Harmless.evtx"), _ => "Security");
|
||||
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: false);
|
||||
|
||||
Assert.DoesNotContain(ZipEntryNames(bytes), e => e.EndsWith("Harmless.evtx"));
|
||||
Assert.Contains("BLOCKED (event-log channel guard, channel 'Security')", ReadManifest(bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
+85
@@ -206,6 +206,91 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
|
||||
Assert.Contains($"BLOCKED (path guard): {configuredPath}", manifest);
|
||||
}
|
||||
|
||||
// %TEMP% lives under C:\Users, which the guard blocks in every mode — the positive
|
||||
// configured-path cases run beside the test assembly, in unrestricted mode.
|
||||
private sealed class ConfiguredPathTree : System.IDisposable
|
||||
{
|
||||
public string Root { get; } = Path.Combine(
|
||||
System.AppContext.BaseDirectory, "diag-paths-" + System.Guid.NewGuid().ToString("N"));
|
||||
public string Logs => Path.Combine(Root, "Logs");
|
||||
|
||||
public ConfiguredPathTree()
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(Logs, "sub"));
|
||||
File.WriteAllText(Path.Combine(Root, "parent-only.txt"), "not configured");
|
||||
File.WriteAllText(Path.Combine(Logs, "app.log"), "configured");
|
||||
File.WriteAllText(Path.Combine(Logs, "sub", "app.log"), "below");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Root, recursive: true); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("\\")]
|
||||
public void BuildArchiveBytes_folder_entry_collects_the_folder_not_its_parent(string trailing)
|
||||
{
|
||||
using var rig = new Rig();
|
||||
using var tree = new ConfiguredPathTree();
|
||||
|
||||
var bytes = rig.Build(cfg =>
|
||||
{
|
||||
cfg.UnrestrictedMode = true;
|
||||
cfg.DiagnosticsLogPaths.Add(new AutopilotMonitor.Shared.Models.DiagnosticsLogPath
|
||||
{
|
||||
Path = tree.Logs + trailing,
|
||||
IncludeSubfolders = true,
|
||||
});
|
||||
})
|
||||
.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var entries = ZipEntryNames(bytes);
|
||||
Assert.Contains("AdditionalLogs/Logs/app.log", entries);
|
||||
Assert.Contains("AdditionalLogs/Logs/sub/app.log", entries);
|
||||
Assert.DoesNotContain(entries, e => e.EndsWith("parent-only.txt"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_file_entry_ignores_include_subfolders()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
using var tree = new ConfiguredPathTree();
|
||||
|
||||
var bytes = rig.Build(cfg =>
|
||||
{
|
||||
cfg.UnrestrictedMode = true;
|
||||
cfg.DiagnosticsLogPaths.Add(new AutopilotMonitor.Shared.Models.DiagnosticsLogPath
|
||||
{
|
||||
Path = Path.Combine(tree.Logs, "app.log"),
|
||||
IncludeSubfolders = true,
|
||||
});
|
||||
})
|
||||
.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var entries = ZipEntryNames(bytes);
|
||||
Assert.Contains("AdditionalLogs/Logs/app.log", entries);
|
||||
Assert.DoesNotContain("AdditionalLogs/Logs/sub/app.log", entries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnumerateFilesNoReparseDirs_asks_the_guard_before_entering_a_subfolder()
|
||||
{
|
||||
using var tree = new ConfiguredPathTree();
|
||||
var refused = new List<string>();
|
||||
|
||||
var files = DiagnosticsPackageService.EnumerateFilesNoReparseDirs(
|
||||
tree.Root, "*", recurse: true,
|
||||
mayEnterDirectory: dir => !dir.EndsWith("sub"),
|
||||
refusedDirectories: refused);
|
||||
|
||||
Assert.Contains(Path.Combine(tree.Logs, "app.log"), files);
|
||||
Assert.DoesNotContain(Path.Combine(tree.Logs, "sub", "app.log"), files);
|
||||
Assert.Equal(new[] { Path.Combine(tree.Logs, "sub") }, refused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_excludes_top_level_session_id_and_bootstrap_config()
|
||||
{
|
||||
|
||||
+137
-2
@@ -59,9 +59,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
public void ClassifyEnforcementState_bands(int state, string expected)
|
||||
=> Assert.Equal(expected, ImeRegistryAppStateObserver.ClassifyEnforcementState(state));
|
||||
|
||||
// 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).
|
||||
[Theory]
|
||||
[InlineData(1000, "installed")]
|
||||
[InlineData(1999, "installed")]
|
||||
[InlineData(1002, "installed")]
|
||||
[InlineData(1004, "installed")]
|
||||
[InlineData(1001, "installing")]
|
||||
[InlineData(1003, "installing")]
|
||||
[InlineData(1005, null)]
|
||||
[InlineData(1999, null)]
|
||||
[InlineData(3000, "failed")]
|
||||
[InlineData(2000, "notApplicable")]
|
||||
[InlineData(2999, "notApplicable")]
|
||||
@@ -72,6 +80,35 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
public void ClassifyStatusServiceStatus_bands(int status, string? expected)
|
||||
=> Assert.Equal(expected, ImeRegistryAppStateObserver.ClassifyStatusServiceStatus(status));
|
||||
|
||||
[Fact]
|
||||
public void TryParseRegistryDateTime_reads_both_ime_shapes_as_utc()
|
||||
{
|
||||
// ExecutionDeadlineTime: DateTime.ToString(InvariantCulture), UTC without a kind marker.
|
||||
var deadline = ImeRegistryAppStateObserver.TryParseRegistryDateTime("09/23/2026 18:00:00");
|
||||
Assert.Equal(new DateTime(2026, 9, 23, 18, 0, 0, DateTimeKind.Utc), deadline);
|
||||
Assert.Equal(DateTimeKind.Utc, deadline!.Value.Kind);
|
||||
|
||||
// DeferUntilTime: round-trip "o" with trailing Z.
|
||||
var until = ImeRegistryAppStateObserver.TryParseRegistryDateTime("2026-09-23T10:30:00.0000000Z");
|
||||
Assert.Equal(new DateTime(2026, 9, 23, 10, 30, 0, DateTimeKind.Utc), until);
|
||||
Assert.Equal(DateTimeKind.Utc, until!.Value.Kind);
|
||||
|
||||
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime(null));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime(""));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime("not a date"));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime(42));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryReadBool_parses_registry_strings_only()
|
||||
{
|
||||
Assert.True(ImeRegistryAppStateObserver.TryReadBool("True"));
|
||||
Assert.False(ImeRegistryAppStateObserver.TryReadBool("false"));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TryReadBool("yes"));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TryReadBool(1));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TryReadBool(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TerminalOutcome_prefers_enforcement_state_then_status_service()
|
||||
{
|
||||
@@ -88,6 +125,49 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(enforcementState: 3000)));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(statusServiceStatus: 2500)));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry()));
|
||||
// Installing (1001) / InstallingPendingReboot (1003) share the 1000 band but are not terminal.
|
||||
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(statusServiceStatus: 1001)));
|
||||
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(enforcementState: 2009, statusServiceStatus: 1003)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangedFields_reports_wait_state_triggers_only()
|
||||
{
|
||||
var prev = Entry(enforcementState: 2009);
|
||||
var next = Entry(enforcementState: 2009,
|
||||
installDeadlineUtc: T0.AddHours(2),
|
||||
deferralsUsed: 1, deferralMaxDeferrals: 3, deferUntilUtc: T0.AddMinutes(30), deferralAutoDeferred: false);
|
||||
|
||||
Assert.Equal(new[] { "installDeadline", "deferralsUsed", "deferUntil" },
|
||||
ImeRegistryAppStateObserver.ChangedFields(prev, next));
|
||||
|
||||
// MaxDeferrals / AutoDeferred alone are data, not a transition.
|
||||
var sameCounters = Entry(enforcementState: 2009,
|
||||
installDeadlineUtc: T0.AddHours(2),
|
||||
deferralsUsed: 1, deferralMaxDeferrals: 5, deferUntilUtc: T0.AddMinutes(30), deferralAutoDeferred: true);
|
||||
Assert.Empty(ImeRegistryAppStateObserver.ChangedFields(next, sameCounters));
|
||||
|
||||
// A cleared deadline is a transition too (IME clears it when the next download starts).
|
||||
Assert.Equal(new[] { "installDeadline" },
|
||||
ImeRegistryAppStateObserver.ChangedFields(
|
||||
Entry(installDeadlineUtc: T0.AddHours(2)), Entry()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DescribeWaitState_texts()
|
||||
{
|
||||
Assert.Equal(string.Empty, ImeRegistryAppStateObserver.DescribeWaitState(Entry(enforcementState: 2009)));
|
||||
Assert.Equal(", downloaded, install deadline 2026-08-18 10:00 UTC",
|
||||
ImeRegistryAppStateObserver.DescribeWaitState(Entry(installDeadlineUtc: T0.AddHours(2))));
|
||||
Assert.Equal(", deferred by user 1/3 until 2026-08-18 08:30 UTC",
|
||||
ImeRegistryAppStateObserver.DescribeWaitState(Entry(
|
||||
deferralsUsed: 1, deferralMaxDeferrals: 3, deferUntilUtc: T0.AddMinutes(30), deferralAutoDeferred: false)));
|
||||
Assert.Equal(", auto-deferred 2/3",
|
||||
ImeRegistryAppStateObserver.DescribeWaitState(Entry(
|
||||
deferralsUsed: 2, deferralMaxDeferrals: 3, deferralAutoDeferred: true)));
|
||||
// Zero deferrals used is not a deferral; a missing max falls back to the bare count.
|
||||
Assert.Equal(string.Empty, ImeRegistryAppStateObserver.DescribeWaitState(Entry(deferralsUsed: 0, deferralMaxDeferrals: 3)));
|
||||
Assert.Equal(", deferred by user 1", ImeRegistryAppStateObserver.DescribeWaitState(Entry(deferralsUsed: 1)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -184,6 +264,54 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
Assert.Equal("success", evt.Payload["enforcementClass"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wait_state_changes_emit_state_events_with_data_and_text()
|
||||
{
|
||||
var (sink, clock, observer) = CreateObserver(trackerApps: null);
|
||||
var current = Snapshot((App1, 2009, null));
|
||||
|
||||
using (new ImeRegistryAppStateObserver.ScopedSnapshotOverride(() => current))
|
||||
{
|
||||
observer.Tick("baseline");
|
||||
|
||||
// Download finished, IME parks the app until its install deadline (1.106 ExecutionDeadlineTime).
|
||||
var withDeadline = Snapshot((App1, 2009, null));
|
||||
withDeadline.Entries.Values.Single().InstallDeadlineUtc = T0.AddHours(2);
|
||||
current = withDeadline;
|
||||
observer.Tick("registry_change");
|
||||
|
||||
// A required app hits a running process and the user defers (1.105 app-in-use deferral).
|
||||
var deferred = Snapshot((App1, 2014, null));
|
||||
var entry = deferred.Entries.Values.Single();
|
||||
entry.InstallDeadlineUtc = T0.AddHours(2);
|
||||
entry.DeferralsUsed = 1;
|
||||
entry.DeferralMaxDeferrals = 3;
|
||||
entry.DeferUntilUtc = T0.AddMinutes(30);
|
||||
entry.DeferralAutoDeferred = false;
|
||||
current = deferred;
|
||||
observer.Tick("registry_change");
|
||||
}
|
||||
|
||||
var events = Events(sink, SharedEventTypes.RegistryAppState);
|
||||
Assert.Equal(2, events.Count);
|
||||
|
||||
var deadlineEvent = events[0];
|
||||
Assert.Equal("installDeadline", deadlineEvent.Payload!["changedFields"]);
|
||||
Assert.Equal("2026-08-18T10:00:00.0000000Z", deadlineEvent.Payload["installDeadlineUtc"]);
|
||||
Assert.DoesNotContain("deferralsUsed", deadlineEvent.Payload.Keys);
|
||||
Assert.Contains("-> inProgress, downloaded, install deadline 2026-08-18 10:00 UTC",
|
||||
deadlineEvent.Payload[SignalPayloadKeys.Message]);
|
||||
|
||||
var deferralEvent = events[1];
|
||||
Assert.Equal("enforcementState,deferralsUsed,deferUntil", deferralEvent.Payload!["changedFields"]);
|
||||
Assert.Equal("2014", deferralEvent.Payload["enforcementState"]);
|
||||
Assert.Equal("1", deferralEvent.Payload["deferralsUsed"]);
|
||||
Assert.Equal("3", deferralEvent.Payload["deferralMaxDeferrals"]);
|
||||
Assert.Equal("2026-08-18T08:30:00.0000000Z", deferralEvent.Payload["deferUntilUtc"]);
|
||||
Assert.Equal("false", deferralEvent.Payload["deferralAutoDeferred"]);
|
||||
Assert.Contains("deferred by user 1/3 until 2026-08-18 08:30 UTC", deferralEvent.Payload[SignalPayloadKeys.Message]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NonEmpty_baseline_emits_one_summary_with_counts()
|
||||
{
|
||||
@@ -331,7 +459,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
|
||||
private static AppRegistryEntry Entry(
|
||||
int? enforcementState = null, long? errorCode = null, int? exitCode = null,
|
||||
int? statusServiceStatus = null, bool espTracked = false, string? espPhase = null)
|
||||
int? statusServiceStatus = null, bool espTracked = false, string? espPhase = null,
|
||||
DateTime? installDeadlineUtc = null, int? deferralsUsed = null, int? deferralMaxDeferrals = null,
|
||||
DateTime? deferUntilUtc = null, bool? deferralAutoDeferred = null)
|
||||
{
|
||||
var entry = new AppRegistryEntry($"{ImeRegistrySnapshot.DeviceContext}|{App1}", ImeRegistrySnapshot.DeviceContext, App1);
|
||||
entry.EnforcementState = enforcementState;
|
||||
@@ -340,6 +470,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
entry.StatusServiceStatus = statusServiceStatus;
|
||||
entry.EspTracked = espTracked;
|
||||
entry.EspPhase = espPhase;
|
||||
entry.InstallDeadlineUtc = installDeadlineUtc;
|
||||
entry.DeferralsUsed = deferralsUsed;
|
||||
entry.DeferralMaxDeferrals = deferralMaxDeferrals;
|
||||
entry.DeferUntilUtc = deferUntilUtc;
|
||||
entry.DeferralAutoDeferred = deferralAutoDeferred;
|
||||
return entry;
|
||||
}
|
||||
|
||||
|
||||
+17
@@ -83,6 +83,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
using var f = new Fixture();
|
||||
Assert.False(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
Assert.Null(f.Tracker.AccountSetupProgressIfRead);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -97,6 +98,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
// Read and untouched — the only state the WhiteGlove sealing gate treats as "false".
|
||||
Assert.False(f.Tracker.AccountSetupProgressIfRead);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -108,6 +111,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.True(f.Tracker.HasAccountSetupProgress);
|
||||
Assert.True(f.Tracker.AccountSetupProgressIfRead);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -138,5 +142,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyDeviceSetupRead_AccountSetupProgressIsUnknown()
|
||||
{
|
||||
// Adversarial for the WhiteGlove sealing gate: the tracker holds DeviceSetup data but
|
||||
// has not read the AccountSetup category — that must be "unknown", never "untouched".
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status",
|
||||
"{\"categoryState\":\"inProgress\",\"DeviceSetup.AppsSubcategory\":{\"subcategoryState\":\"inProgress\"}}");
|
||||
|
||||
Assert.Null(f.Tracker.AccountSetupProgressIfRead);
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+34
@@ -20,6 +20,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
|
||||
private sealed class FakeApiClient : BackendApiClient
|
||||
{
|
||||
public readonly List<TimeSpan?> Timeouts = new List<TimeSpan?>();
|
||||
public readonly List<AgentErrorReport> Reports = new List<AgentErrorReport>();
|
||||
public readonly Queue<bool> Results = new Queue<bool>();
|
||||
|
||||
public FakeApiClient() : base(
|
||||
@@ -40,6 +41,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
|
||||
public override Task<bool> ReportAgentErrorAsync(AgentErrorReport report, TimeSpan? timeout = null)
|
||||
{
|
||||
Timeouts.Add(timeout);
|
||||
Reports.Add(report);
|
||||
return Task.FromResult(Results.Count > 0 && Results.Dequeue());
|
||||
}
|
||||
}
|
||||
@@ -139,5 +141,37 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
|
||||
|
||||
Assert.Equal(2, client.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Session_age_is_carried_in_the_report_and_absent_by_default()
|
||||
{
|
||||
// One reporter per report: a delivered report starts the 10-minute cooldown.
|
||||
var client = new FakeApiClient();
|
||||
client.Results.Enqueue(true);
|
||||
client.Results.Enqueue(true);
|
||||
|
||||
await Reporter(client).TrySendAsync(AgentErrorType.SessionAgeEmergencyBreak, "m", sessionAgeHours: 478.2);
|
||||
await Reporter(client).TrySendAsync(AgentErrorType.ConfigFetchFailed, "m");
|
||||
|
||||
Assert.Equal(2, client.Reports.Count);
|
||||
Assert.Equal(478.2, client.Reports[0].SessionAgeHours);
|
||||
Assert.Null(client.Reports[1].SessionAgeHours);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Prior_registration_failure_is_carried_in_the_report_and_absent_by_default()
|
||||
{
|
||||
var client = new FakeApiClient();
|
||||
client.Results.Enqueue(true);
|
||||
client.Results.Enqueue(true);
|
||||
var record = new RegistrationFailureSummary { FailedRuns = 2, Outcome = "Failed", NetworkLinkUpAtEnd = false };
|
||||
|
||||
await Reporter(client).TrySendAsync(AgentErrorType.SessionAgeEmergencyBreak, "m", priorRegistrationFailure: record);
|
||||
await Reporter(client).TrySendAsync(AgentErrorType.ConfigFetchFailed, "m");
|
||||
|
||||
Assert.Equal(2, client.Reports.Count);
|
||||
Assert.Same(record, client.Reports[0].PriorRegistrationFailure);
|
||||
Assert.Null(client.Reports[1].PriorRegistrationFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Transport;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
|
||||
{
|
||||
/// <summary>
|
||||
/// Response parsers of the geo providers. Addresses come from the RFC 5737 documentation
|
||||
/// ranges — never real ones.
|
||||
/// </summary>
|
||||
public class GeoLocationServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void ParseDoGeo_maps_country_and_egress_ip_and_ignores_the_do_service_fields()
|
||||
{
|
||||
var json = JObject.Parse(@"{
|
||||
""ExternalIpAddress"": ""203.0.113.7"",
|
||||
""CountryCode"": ""DE"",
|
||||
""KeyValue_EndpointFullUri"": ""https://kv601.prod.do.dsp.mp.microsoft.com/all"",
|
||||
""Version"": ""26A6D4D6994E8DA5"",
|
||||
""CacheId"": ""7"",
|
||||
""ContentCert"": false,
|
||||
""DownloadModeFailSafe"": """"
|
||||
}");
|
||||
|
||||
var result = GeoLocationService.ParseDoGeo(json);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("DE", result.Country);
|
||||
Assert.Equal("203.0.113.7", result.Ip);
|
||||
Assert.Equal("do-geo", result.Source);
|
||||
Assert.Null(result.Region);
|
||||
Assert.Null(result.City);
|
||||
Assert.Null(result.Loc);
|
||||
Assert.Null(result.Timezone);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"{ ""ExternalIpAddress"": ""203.0.113.7"" }")]
|
||||
[InlineData(@"{ ""ExternalIpAddress"": ""203.0.113.7"", ""CountryCode"": """" }")]
|
||||
public void ParseDoGeo_without_country_is_a_failure(string body)
|
||||
{
|
||||
Assert.Null(GeoLocationService.ParseDoGeo(JObject.Parse(body)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseIpInfo_maps_all_fields()
|
||||
{
|
||||
var json = JObject.Parse(@"{
|
||||
""ip"": ""198.51.100.4"", ""city"": ""Stuttgart"", ""region"": ""Baden-Wurttemberg"",
|
||||
""country"": ""DE"", ""loc"": ""48.7823,9.1770"", ""timezone"": ""Europe/Berlin""
|
||||
}");
|
||||
|
||||
var result = GeoLocationService.ParseIpInfo(json);
|
||||
|
||||
Assert.Equal("DE", result.Country);
|
||||
Assert.Equal("Baden-Wurttemberg", result.Region);
|
||||
Assert.Equal("Stuttgart", result.City);
|
||||
Assert.Equal("48.7823,9.1770", result.Loc);
|
||||
Assert.Equal("Europe/Berlin", result.Timezone);
|
||||
Assert.Equal("198.51.100.4", result.Ip);
|
||||
Assert.Equal("ipinfo", result.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseIfConfigCo_joins_coordinates_and_leaves_loc_empty_without_them()
|
||||
{
|
||||
var withCoords = GeoLocationService.ParseIfConfigCo(JObject.Parse(@"{
|
||||
""ip"": ""198.51.100.4"", ""country_iso"": ""DE"", ""region_name"": ""Bavaria"",
|
||||
""city"": ""Munich"", ""latitude"": 48.13, ""longitude"": 11.58, ""time_zone"": ""Europe/Berlin""
|
||||
}"));
|
||||
var withoutCoords = GeoLocationService.ParseIfConfigCo(JObject.Parse(@"{ ""country_iso"": ""DE"" }"));
|
||||
|
||||
Assert.Equal("48.13,11.58", withCoords.Loc);
|
||||
Assert.Equal("DE", withCoords.Country);
|
||||
Assert.Equal("Bavaria", withCoords.Region);
|
||||
Assert.Equal("ifconfig.co", withCoords.Source);
|
||||
Assert.Equal("", withoutCoords.Loc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Describe_skips_the_parts_a_provider_did_not_return()
|
||||
{
|
||||
Assert.Equal("Stuttgart, BW, DE", new GeoLocationResult { City = "Stuttgart", Region = "BW", Country = "DE" }.Describe());
|
||||
Assert.Equal("DE", new GeoLocationResult { Country = "DE", Region = "" }.Describe());
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -162,6 +162,28 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
Assert.Equal(SessionStage.AwaitingHello, result.InitialState.Stage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Clean_snapshot_of_a_rotated_session_adopts_the_current_session_id()
|
||||
{
|
||||
// SESSION-OWNER-BINDING: the backend refused the persisted session id at registration,
|
||||
// the agent rotated, and the snapshot on disk still names the old session. The
|
||||
// enrollment state carries over; the session id must be the current one.
|
||||
using var rig = new Rig();
|
||||
var saved = DecisionState.CreateInitial("S-REFUSED", TenantId)
|
||||
.ToBuilder()
|
||||
.WithStage(SessionStage.EspAccountSetup)
|
||||
.WithStepIndex(7)
|
||||
.WithLastAppliedSignalOrdinal(6)
|
||||
.Build();
|
||||
SeedSnapshot(rig, saved);
|
||||
|
||||
var result = rig.Recover();
|
||||
|
||||
Assert.Equal(SessionId, result.InitialState.SessionId);
|
||||
Assert.Equal(SessionStage.EspAccountSetup, result.InitialState.Stage);
|
||||
Assert.Equal(7, result.InitialState.StepIndex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Snapshot_plus_pending_tail_replays_tail_onto_snapshot()
|
||||
{
|
||||
|
||||
+18
@@ -37,6 +37,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
[InlineData("modern_deployment_log")]
|
||||
// Environment observation — battery drain on an idle device must not reset idle clocks.
|
||||
[InlineData("power_state_change")]
|
||||
// A flapping link is environment too: it must neither keep the collectors awake nor
|
||||
// reset the stall clock of the enrollment it is stalling.
|
||||
[InlineData("network_state_change")]
|
||||
[InlineData("network_connectivity_check")]
|
||||
// Bookkeeping of health-script runs that were deliberately not reported.
|
||||
[InlineData("script_recurrence_summary")]
|
||||
// Agent health / control / transport — not device/enrollment progress (P2).
|
||||
[InlineData("collector_degraded")]
|
||||
[InlineData("telemetry_upload_poisoned")]
|
||||
@@ -67,6 +73,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
Assert.True(SignalActivityClassifier.IsRealActivity(DecisionSignalKind.InformationalEvent, payload));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
// Only the link-change pair is exempt. The device-info snapshots are emitted at start
|
||||
// and at the end, not per flap, and stay activity.
|
||||
[InlineData("network_interface_info")]
|
||||
[InlineData("wifi_signal_info")]
|
||||
[InlineData("network_bandwidth_estimate")]
|
||||
public void Other_network_events_remain_activity(string eventType)
|
||||
{
|
||||
var payload = new Dictionary<string, string> { [SignalPayloadKeys.EventType] = eventType };
|
||||
Assert.True(SignalActivityClassifier.IsRealActivity(DecisionSignalKind.InformationalEvent, payload));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
// Genuine ModernDeployment warnings/errors stay real activity — only the Info/Debug
|
||||
// `modern_deployment_log` forwarding is excluded.
|
||||
|
||||
+83
@@ -118,5 +118,88 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
|
||||
Assert.Throws<ArgumentNullException>(
|
||||
() => BackendSessionRegistration.Register(config, auth, http, "1.0", consoleMode: false, logger: null));
|
||||
}
|
||||
|
||||
// ============================================================ failed-registration record
|
||||
|
||||
[Fact]
|
||||
public void RecordRegistrationRun_records_a_failed_run_with_its_window_and_bounded_error()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var persistence = new SessionIdPersistence(tmp.Path);
|
||||
var started = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
BackendSessionRegistration.RecordRegistrationRun(
|
||||
persistence, SessionRegistrationResult.Failed(new string('e', 1000)),
|
||||
started, started.AddSeconds(1204.46), linkUpAtStart: false, linkUpAtEnd: true,
|
||||
configFetchOutcome: "UsedDefaults", logger: NewLogger(tmp.Path));
|
||||
|
||||
var record = persistence.LoadRegistrationFailure();
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(1, record!.FailedRuns);
|
||||
Assert.Equal("Failed", record.Outcome);
|
||||
Assert.Equal(BackendSessionRegistration.MaxRecordedErrorLength, record.LastError!.Length);
|
||||
Assert.False(record.NetworkLinkUpAtStart);
|
||||
Assert.True(record.NetworkLinkUpAtEnd);
|
||||
Assert.Equal(1204.5, record.AttemptWindowSeconds);
|
||||
Assert.Equal("UsedDefaults", record.ConfigFetchOutcome);
|
||||
Assert.Equal(started.AddSeconds(1204.46), record.LastFailedAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordRegistrationRun_records_auth_failures_and_clears_on_success()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var persistence = new SessionIdPersistence(tmp.Path);
|
||||
var at = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
BackendSessionRegistration.RecordRegistrationRun(
|
||||
persistence, SessionRegistrationResult.AuthFailed(401, "unauthorized"),
|
||||
at, at.AddSeconds(3), true, true, "Succeeded", NewLogger(tmp.Path));
|
||||
Assert.Equal("AuthFailed", persistence.LoadRegistrationFailure()!.Outcome);
|
||||
|
||||
BackendSessionRegistration.RecordRegistrationRun(
|
||||
persistence, SessionRegistrationResult.Succeeded(new RegisterSessionResponse { Success = true }),
|
||||
at, at.AddSeconds(1), true, true, "Succeeded", NewLogger(tmp.Path));
|
||||
Assert.Null(persistence.LoadRegistrationFailure());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecordRegistrationRun_without_persistence_is_a_no_op()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
BackendSessionRegistration.RecordRegistrationRun(
|
||||
null, SessionRegistrationResult.Failed("x"), DateTime.UtcNow, DateTime.UtcNow,
|
||||
null, null, null, NewLogger(tmp.Path));
|
||||
}
|
||||
|
||||
// ============================================================ emergency-break message
|
||||
|
||||
[Fact]
|
||||
public void Break_message_names_failed_registrations_in_invariant_culture()
|
||||
{
|
||||
var previous = System.Threading.Thread.CurrentThread.CurrentCulture;
|
||||
try
|
||||
{
|
||||
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
|
||||
var record = new RegistrationFailureSummary { FailedRuns = 3, Outcome = "Failed", NetworkLinkUpAtEnd = false };
|
||||
|
||||
var message = EmergencyBreakReporter.BuildMessage(478.2, 48, record);
|
||||
|
||||
Assert.Contains("session age 478.2h (cap 48h)", message);
|
||||
Assert.EndsWith(" 3 earlier start(s) failed to register (last: Failed, network link at end: down).", message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
System.Threading.Thread.CurrentThread.CurrentCulture = previous;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Break_message_without_record_keeps_the_historical_text()
|
||||
{
|
||||
Assert.Equal(
|
||||
"Agent absolute session-age emergency break fired at session age 50.0h (cap 48h) — cleaning up and exiting.",
|
||||
EmergencyBreakReporter.BuildMessage(50.0, 48, null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,6 +149,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
|
||||
persistence.SaveSessionCreatedAt(DateTime.UtcNow.AddHours(-100));
|
||||
|
||||
var stateDir = Path.Combine(tmp.Path, "State");
|
||||
double? reportedAgeHours = null;
|
||||
|
||||
var tripped = AutopilotMonitor.Agent.V2.Program.CheckSessionAgeEmergencyBreak(
|
||||
dataDirectory: tmp.Path,
|
||||
@@ -157,9 +158,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
|
||||
selfDestructOnComplete: false,
|
||||
cleanupServiceFactory: null,
|
||||
logger: logger,
|
||||
consoleMode: false);
|
||||
consoleMode: false,
|
||||
onBreakFired: ageHours => reportedAgeHours = ageHours);
|
||||
|
||||
Assert.True(tripped);
|
||||
// The measured age reaches the break report (the backend cannot derive it).
|
||||
Assert.NotNull(reportedAgeHours);
|
||||
Assert.InRange(reportedAgeHours.Value, 99.9, 100.1);
|
||||
// Marker must have been written so the next restart exits cleanly.
|
||||
Assert.True(File.Exists(Path.Combine(stateDir, "enrollment-complete.marker")));
|
||||
// Session must have been cleared.
|
||||
@@ -302,6 +307,114 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
|
||||
Assert.False(File.Exists(path));
|
||||
}
|
||||
|
||||
// ================================================================= Multi-instance guard
|
||||
|
||||
private static AutopilotMonitor.Agent.V2.Program.AgentProcessFact Proc(int pid, int sessionId)
|
||||
=> new AutopilotMonitor.Agent.V2.Program.AgentProcessFact(pid, sessionId);
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_ignores_a_same_named_process_in_a_user_session()
|
||||
{
|
||||
// The agent (pid 100, session 0) starts while a standard user keeps a process with
|
||||
// the agent's image name resident in their own session. It must not block the start.
|
||||
var matches = new[] { Proc(100, 0), Proc(200, 1) };
|
||||
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(7)]
|
||||
[InlineData(-1)]
|
||||
public void FindSiblingAgentPid_ignores_every_session_but_zero(int sessionId)
|
||||
{
|
||||
var matches = new[] { Proc(100, 0), Proc(200, sessionId) };
|
||||
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_reports_a_second_runtime_in_session_zero()
|
||||
{
|
||||
// Self-update restart while the old runtime is still alive — the single-agent
|
||||
// invariant the guard exists for.
|
||||
var matches = new[] { Proc(100, 0), Proc(300, 0) };
|
||||
|
||||
Assert.Equal(300, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_never_reports_the_caller_itself()
|
||||
{
|
||||
var matches = new[] { Proc(100, 0) };
|
||||
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_skips_user_session_processes_listed_before_the_runtime()
|
||||
{
|
||||
// Install-mode launch verification: a user-session process enumerated first must not
|
||||
// be reported as the launched runtime.
|
||||
var matches = new[] { Proc(200, 1), Proc(201, 2), Proc(100, 0), Proc(300, 0) };
|
||||
|
||||
Assert.Equal(300, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_blocks_an_interactive_start_next_to_the_session_zero_runtime()
|
||||
{
|
||||
// --console run from an admin prompt (session 1) while the Scheduled Task runtime is up.
|
||||
var matches = new[] { Proc(100, 1), Proc(300, 0) };
|
||||
|
||||
Assert.Equal(300, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_returns_zero_for_no_matches()
|
||||
{
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(
|
||||
new AutopilotMonitor.Agent.V2.Program.AgentProcessFact[0], ownPid: 100));
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(null, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotProcessesByName_reads_pid_and_session_of_the_running_test_host()
|
||||
{
|
||||
using var self = System.Diagnostics.Process.GetCurrentProcess();
|
||||
|
||||
var facts = AutopilotMonitor.Agent.V2.Program.SnapshotProcessesByName(self.ProcessName);
|
||||
|
||||
var own = Assert.Single(facts, f => f.Pid == self.Id);
|
||||
Assert.Equal(self.SessionId, own.SessionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotProcessesByName_reads_the_session_of_system_owned_processes_without_access_rights()
|
||||
{
|
||||
// Positive control for the fail-open direction: the session id comes from the process
|
||||
// snapshot, not from an opened handle, so even an unprivileged caller reads it for
|
||||
// SYSTEM-owned service hosts. A skipped process would let a real sibling go unseen.
|
||||
var expected = System.Diagnostics.Process.GetProcessesByName("svchost");
|
||||
foreach (var p in expected) p.Dispose();
|
||||
|
||||
var facts = AutopilotMonitor.Agent.V2.Program.SnapshotProcessesByName("svchost");
|
||||
|
||||
Assert.NotEmpty(facts);
|
||||
Assert.All(facts, f => Assert.True(f.Pid > 0));
|
||||
Assert.Contains(facts, f => f.SessionId == 0);
|
||||
// Service hosts come and go; a wholesale access failure would drop (nearly) all of them.
|
||||
Assert.True(facts.Count >= expected.Length / 2,
|
||||
$"Snapshot returned {facts.Count} of ~{expected.Length} svchost processes.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotProcessesByName_returns_empty_for_an_unknown_name()
|
||||
{
|
||||
Assert.Empty(AutopilotMonitor.Agent.V2.Program.SnapshotProcessesByName("no-such-process-" + Guid.NewGuid().ToString("N")));
|
||||
}
|
||||
|
||||
// ================================================================= Crash log writer
|
||||
|
||||
[Fact]
|
||||
|
||||
+16
@@ -62,6 +62,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
|
||||
Assert.Equal("ipinfo.io", evt.Data["source"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildGeoEvent_country_only_location_has_no_empty_parts_in_message()
|
||||
{
|
||||
var loc = new GeoLocationResult { Country = "DE", Source = "do-geo" };
|
||||
|
||||
var evt = StartupEnvironmentProbes.BuildGeoEvent(Config(), loc);
|
||||
|
||||
Assert.Equal("Device location: DE (via do-geo)", evt.Message);
|
||||
Assert.Equal("DE", evt.Data["country"]);
|
||||
Assert.Equal("do-geo", evt.Data["source"]);
|
||||
}
|
||||
|
||||
// ================================================================= Outbound IP
|
||||
|
||||
[Fact]
|
||||
@@ -98,6 +110,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
|
||||
PrimaryError = "connection refused",
|
||||
PrimaryRetryError = "DNS failure",
|
||||
FallbackError = "timeout",
|
||||
DoGeoError = "HTTP 403 (Forbidden)",
|
||||
};
|
||||
|
||||
var evt = StartupEnvironmentProbes.BuildGeoFailureEvent(cfg, attempt);
|
||||
@@ -108,6 +121,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
|
||||
Assert.Equal("connection refused", evt.Data["primaryError"]);
|
||||
Assert.Equal("DNS failure", evt.Data["primaryRetryError"]);
|
||||
Assert.Equal("timeout", evt.Data["fallbackError"]);
|
||||
Assert.Equal("HTTP 403 (Forbidden)", evt.Data["doGeoError"]);
|
||||
Assert.Equal("do-geo", evt.Data["lastResortProvider"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -119,6 +134,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
|
||||
Assert.Equal("unknown", evt.Data["primaryError"]);
|
||||
Assert.Equal("unknown", evt.Data["primaryRetryError"]);
|
||||
Assert.Equal("unknown", evt.Data["fallbackError"]);
|
||||
Assert.Equal("unknown", evt.Data["doGeoError"]);
|
||||
}
|
||||
|
||||
// ================================================================= Timezone
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.IO;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Security;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Security
|
||||
@@ -234,5 +235,78 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Security
|
||||
Assert.False(File.Exists(Path.Combine(tmp.Path, "session.created")));
|
||||
Assert.False(File.Exists(Path.Combine(tmp.Path, "whiteglove.complete")));
|
||||
}
|
||||
|
||||
// ============================================================ failed-registration record
|
||||
|
||||
private static RegistrationFailureSummary FailedRun(DateTime at, string outcome = "Failed", bool? linkUpAtEnd = false) =>
|
||||
new RegistrationFailureSummary
|
||||
{
|
||||
FailedRuns = 1,
|
||||
FirstFailedAtUtc = at,
|
||||
LastFailedAtUtc = at,
|
||||
Outcome = outcome,
|
||||
LastError = "No such host is known.",
|
||||
NetworkLinkUpAtStart = false,
|
||||
NetworkLinkUpAtEnd = linkUpAtEnd,
|
||||
AttemptWindowSeconds = 91.3,
|
||||
ConfigFetchOutcome = "UsedDefaults",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void RecordRegistrationFailure_counts_runs_keeps_the_first_time_and_describes_the_latest_run()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var sut = new SessionIdPersistence(tmp.Path);
|
||||
var first = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
|
||||
var second = new DateTime(2026, 9, 12, 7, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
Assert.Null(sut.LoadRegistrationFailure());
|
||||
sut.RecordRegistrationFailure(FailedRun(first));
|
||||
sut.RecordRegistrationFailure(FailedRun(second, outcome: "AuthFailed", linkUpAtEnd: true));
|
||||
|
||||
// A fresh instance reads it back from disk, as the next boot's emergency break does.
|
||||
var record = new SessionIdPersistence(tmp.Path).LoadRegistrationFailure();
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(2, record!.FailedRuns);
|
||||
Assert.Equal(first, record.FirstFailedAtUtc);
|
||||
Assert.Equal(second, record.LastFailedAtUtc);
|
||||
Assert.Equal("AuthFailed", record.Outcome);
|
||||
Assert.True(record.NetworkLinkUpAtEnd);
|
||||
Assert.Equal(91.3, record.AttemptWindowSeconds);
|
||||
Assert.Equal("UsedDefaults", record.ConfigFetchOutcome);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Registration_failure_record_is_cleared_by_success_delete_and_rotate()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var sut = new SessionIdPersistence(tmp.Path);
|
||||
sut.GetOrCreate();
|
||||
var at = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
sut.RecordRegistrationFailure(FailedRun(at));
|
||||
sut.ClearRegistrationFailure();
|
||||
Assert.Null(sut.LoadRegistrationFailure());
|
||||
|
||||
sut.RecordRegistrationFailure(FailedRun(at));
|
||||
sut.Rotate();
|
||||
Assert.Null(sut.LoadRegistrationFailure());
|
||||
|
||||
sut.RecordRegistrationFailure(FailedRun(at));
|
||||
sut.Delete();
|
||||
Assert.Null(sut.LoadRegistrationFailure());
|
||||
Assert.False(File.Exists(Path.Combine(tmp.Path, "registration-failure.json")));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not json")]
|
||||
[InlineData("{\"FailedRuns\":0}")]
|
||||
public void LoadRegistrationFailure_reports_nothing_for_a_corrupt_or_empty_record(string content)
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
File.WriteAllText(Path.Combine(tmp.Path, "registration-failure.json"), content);
|
||||
|
||||
Assert.Null(new SessionIdPersistence(tmp.Path).LoadRegistrationFailure());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+80
@@ -137,6 +137,86 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Security
|
||||
Assert.Equal(originalSessionId, result.RotatedFromSessionId);
|
||||
}
|
||||
|
||||
private static BackendRefusalException TenantConflict()
|
||||
=> new BackendRefusalException("Backend returned 409 Conflict with error code session_owner_mismatch.", 409,
|
||||
AutopilotMonitor.Shared.Constants.AgentErrorCodes.SessionOwnerMismatch);
|
||||
|
||||
[Fact]
|
||||
public async Task Tenant_conflict_409_rotates_once_like_an_owner_mismatch()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var logger = NewLogger(tmp);
|
||||
var config = NewConfig();
|
||||
var originalSessionId = config.SessionId;
|
||||
var rotatedTo = Guid.NewGuid().ToString();
|
||||
var seenSessionIds = new System.Collections.Generic.List<string>();
|
||||
|
||||
var apiClient = new FakeApiClient(
|
||||
attempt => attempt == 1
|
||||
? throw TenantConflict()
|
||||
: new RegisterSessionResponse { Success = true, SessionId = rotatedTo, ValidatedBy = ValidatorType.AutopilotV1 },
|
||||
onRegister: r => seenSessionIds.Add(r.SessionId));
|
||||
|
||||
var tracker = new AuthFailureTracker(maxFailures: 5, timeoutMinutes: 0,
|
||||
clock: SystemClock.Instance, logger: logger);
|
||||
|
||||
var result = await SessionRegistrationHelper.RegisterWithRetryAsync(
|
||||
apiClient, config, agentVersion: "0.0.0", logger: logger,
|
||||
authFailureTracker: tracker,
|
||||
backoffDelay: _ => throw new InvalidOperationException("rotation must retry without backoff"),
|
||||
networkLinkWait: _ => Task.CompletedTask,
|
||||
rotateSession: () => { config.SessionId = rotatedTo; return rotatedTo; });
|
||||
|
||||
Assert.Equal(SessionRegistrationOutcome.Succeeded, result.Outcome);
|
||||
Assert.Equal(new[] { originalSessionId, rotatedTo }, seenSessionIds);
|
||||
Assert.Equal(originalSessionId, result.RotatedFromSessionId);
|
||||
Assert.Equal(0, tracker.ConsecutiveFailures);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Coded_refusal_after_rotation_fails_without_retry_or_auth_failure()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var logger = NewLogger(tmp);
|
||||
var config = NewConfig();
|
||||
|
||||
var apiClient = new FakeApiClient(_ => throw TenantConflict());
|
||||
var tracker = new AuthFailureTracker(maxFailures: 5, timeoutMinutes: 0,
|
||||
clock: SystemClock.Instance, logger: logger);
|
||||
|
||||
var result = await SessionRegistrationHelper.RegisterWithRetryAsync(
|
||||
apiClient, config, agentVersion: "0.0.0", logger: logger,
|
||||
authFailureTracker: tracker,
|
||||
backoffDelay: _ => throw new InvalidOperationException("a coded refusal must not be retried"),
|
||||
networkLinkWait: _ => Task.CompletedTask,
|
||||
rotateSession: () => { config.SessionId = Guid.NewGuid().ToString(); return config.SessionId; });
|
||||
|
||||
Assert.Equal(SessionRegistrationOutcome.Failed, result.Outcome);
|
||||
Assert.Equal(2, apiClient.CallCount);
|
||||
Assert.Equal(0, tracker.ConsecutiveFailures);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rotation_hook_failure_on_a_tenant_conflict_fails_without_auth_failure()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var logger = NewLogger(tmp);
|
||||
var config = NewConfig();
|
||||
|
||||
var apiClient = new FakeApiClient(_ => throw TenantConflict());
|
||||
var tracker = new AuthFailureTracker(maxFailures: 5, timeoutMinutes: 0,
|
||||
clock: SystemClock.Instance, logger: logger);
|
||||
|
||||
var result = await SessionRegistrationHelper.RegisterWithRetryAsync(
|
||||
apiClient, config, agentVersion: "0.0.0", logger: logger,
|
||||
authFailureTracker: tracker, networkLinkWait: _ => Task.CompletedTask,
|
||||
rotateSession: () => throw new IOException("disk full"));
|
||||
|
||||
Assert.Equal(SessionRegistrationOutcome.Failed, result.Outcome);
|
||||
Assert.Equal(1, apiClient.CallCount);
|
||||
Assert.Equal(0, tracker.ConsecutiveFailures);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Second_owner_mismatch_after_rotation_is_an_auth_failure()
|
||||
{
|
||||
|
||||
+46
@@ -99,6 +99,52 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
Assert.Equal(DecisionSignalKind.WhiteGloveShellCoreSuccess, posted.Kind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, "true")]
|
||||
[InlineData(false, "false")]
|
||||
public void WhiteGloveEvent_stamps_read_AccountSetup_progress_on_payload_and_evidence(bool progress, string expected)
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var adapter = new EspAndHelloTrackerAdapter(
|
||||
f.Coordinator, f.Ingress, f.Clock, accountSetupProgressProbe: () => progress);
|
||||
|
||||
adapter.TriggerWhiteGloveFromTest();
|
||||
|
||||
var posted = Assert.Single(f.Ingress.Posted);
|
||||
Assert.Equal(expected, posted.Payload![SignalPayloadKeys.AccountSetupProgress]);
|
||||
Assert.Equal(expected, posted.Evidence.DerivationInputs![SignalPayloadKeys.AccountSetupProgress]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WhiteGloveEvent_with_unread_AccountSetup_registry_sends_no_progress_key()
|
||||
{
|
||||
// Unknown must keep the sealing classifier's AccountSetup excluder — the payload key
|
||||
// is absent, the evidence records why.
|
||||
using var f = new Fixture();
|
||||
using var adapter = new EspAndHelloTrackerAdapter(
|
||||
f.Coordinator, f.Ingress, f.Clock, accountSetupProgressProbe: () => null);
|
||||
|
||||
adapter.TriggerWhiteGloveFromTest();
|
||||
|
||||
var posted = Assert.Single(f.Ingress.Posted);
|
||||
Assert.True(posted.Payload == null || !posted.Payload.ContainsKey(SignalPayloadKeys.AccountSetupProgress));
|
||||
Assert.Equal("unread", posted.Evidence.DerivationInputs![SignalPayloadKeys.AccountSetupProgress]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WhiteGloveEvent_default_probe_on_unstarted_coordinator_reports_unread()
|
||||
{
|
||||
// Production probe: the provisioning tracker does not exist before Start (and never on
|
||||
// Device Preparation) — that is "unread", not "untouched".
|
||||
using var f = new Fixture();
|
||||
using var adapter = new EspAndHelloTrackerAdapter(f.Coordinator, f.Ingress, f.Clock);
|
||||
|
||||
adapter.TriggerWhiteGloveFromTest();
|
||||
|
||||
var posted = Assert.Single(f.Ingress.Posted);
|
||||
Assert.True(posted.Payload == null || !posted.Payload.ContainsKey(SignalPayloadKeys.AccountSetupProgress));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EspFailureEvent_emits_EspTerminalFailure_with_merged_subSource_annotation()
|
||||
{
|
||||
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
{
|
||||
/// <summary>
|
||||
/// A script run duration is the span between two CMTrace lines, each resolved on its own zone
|
||||
/// belief. When the beliefs differ the span is a whole number of offset-grid steps plus the run
|
||||
/// time, not the run time: session 4377911b read a 10 s script as 3610 s (start line-anchored
|
||||
/// +120, result re-read after an overwrite rewind in the reader's zone +60 and rejected as
|
||||
/// ahead of the clock), a fleet tenant read 2–9 s scripts as 17 h every day. The adapter judges
|
||||
/// the pair from the provenance bound to each line and omits the span rather than lie.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerAdapterDurationProvenanceTests
|
||||
{
|
||||
private const string ServiceLog = "IntuneManagementExtension.log";
|
||||
private const string ExecutorLog = "AgentExecutor.log";
|
||||
|
||||
private static CmTraceLineProvenance Line(
|
||||
DateTime resolvedUtc, int offsetMinutes, CmTraceOffsetOrigin origin,
|
||||
string file = ServiceLog, string? anchor = null, int? measured = null) =>
|
||||
new CmTraceLineProvenance
|
||||
{
|
||||
// The writer's local time is the resolved value with the applied offset put back.
|
||||
SourceLocalTs = DateTime.SpecifyKind(resolvedUtc.AddMinutes(offsetMinutes), DateTimeKind.Unspecified),
|
||||
Origin = origin,
|
||||
OffsetMinutes = offsetMinutes,
|
||||
EraAnchorKind = anchor,
|
||||
MeasuredWriterOffsetMinutes = measured,
|
||||
SourceFileName = file,
|
||||
};
|
||||
|
||||
private static ScriptExecutionState Platform(string policyId, DateTime startedAtUtc, CmTraceLineProvenance start,
|
||||
DateTime? resultObservedAtUtc = null, CmTraceLineProvenance? result = null, string outcome = "Success", int exitCode = 0) =>
|
||||
new ScriptExecutionState
|
||||
{
|
||||
PolicyId = policyId,
|
||||
ScriptType = "platform",
|
||||
ExitCode = exitCode,
|
||||
Result = outcome,
|
||||
ResultSource = "ime_policy_result",
|
||||
StartedAtUtc = startedAtUtc,
|
||||
StartedAtProvenance = start,
|
||||
ResultObservedAtUtc = resultObservedAtUtc,
|
||||
ResultProvenance = result,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Rejected_result_line_against_a_line_anchored_start_omits_the_span()
|
||||
{
|
||||
// Session 4377911b, script d94468af: start 15:19:57.005 local, self-anchored (+120);
|
||||
// result 15:20:07.391 local, re-read after a rewind and resolved in the reader's
|
||||
// zone (+60) → 14:20:07Z, one hour ahead of the clock. The raw pair reads 3610 s.
|
||||
var clockNow = new DateTime(2026, 9, 17, 13, 20, 7, 437, DateTimeKind.Utc);
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var startUtc = new DateTime(2026, 9, 17, 13, 19, 57, 5, DateTimeKind.Utc);
|
||||
var resultRaw = new DateTime(2026, 9, 17, 14, 20, 7, 391, DateTimeKind.Utc);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("d94468af",
|
||||
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored, measured: 120),
|
||||
resultRaw, Line(resultRaw, 60, CmTraceOffsetOrigin.None, measured: 120)));
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.Equal(clockNow, info.OccurredAtUtc); // stamp: clamped to the clock
|
||||
Assert.Equal("true", info.Payload!["derivedTimestamp"]);
|
||||
Assert.Equal(resultRaw.ToString("o"), info.Payload["rejectedSourceTimestamp"]);
|
||||
Assert.False(info.Payload.ContainsKey("durationSeconds"));
|
||||
Assert.False(info.Payload.ContainsKey("durationBasis"));
|
||||
Assert.Equal("rejected-endpoint", info.Payload["durationSuppressedReason"]);
|
||||
Assert.Equal("unverified", info.Payload["durationProvenance"]);
|
||||
// The end line's own provenance and the start line's, side by side.
|
||||
Assert.Equal("reader-zone-fallback", info.Payload["sourceOffsetOrigin"]);
|
||||
Assert.Equal("60", info.Payload["sourceOffsetMinutes"]);
|
||||
Assert.Equal("120", info.Payload["measuredWriterOffsetMinutes"]);
|
||||
Assert.Equal("2026-09-17T15:20:07.3910000", info.Payload["sourceLocalTs"]);
|
||||
Assert.Equal("line-anchored", info.Payload["startSourceOffsetOrigin"]);
|
||||
Assert.Equal("120", info.Payload["startSourceOffsetMinutes"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rejected_era_anchored_result_of_a_failed_script_omits_the_span_and_the_timeout_verdict()
|
||||
{
|
||||
// Fleet shape (script_failed, daily in one tenant): result era-anchored at −420 (the
|
||||
// OOBE default zone's era) on a line written under +600 → 17 h ahead of the clock;
|
||||
// the 61203 s "run" of a 3 s script fired script_timeout_suspected every day.
|
||||
var clockNow = new DateTime(2026, 9, 21, 1, 30, 13, DateTimeKind.Utc);
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var startUtc = clockNow.AddSeconds(-8);
|
||||
var resultRaw = clockNow.AddSeconds(-5).AddHours(17);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("88d406eb",
|
||||
startUtc, Line(startUtc, 600, CmTraceOffsetOrigin.LineAnchored),
|
||||
resultRaw, Line(resultRaw, -420, CmTraceOffsetOrigin.EraAnchored, anchor: "bootstrap-policy-result", measured: 600),
|
||||
outcome: "Failed"));
|
||||
|
||||
var failed = f.InfoEvent(SharedEventTypes.ScriptFailed);
|
||||
Assert.Equal("rejected-endpoint", failed.Payload!["durationSuppressedReason"]);
|
||||
Assert.False(failed.Payload.ContainsKey("durationSeconds"));
|
||||
Assert.Equal("era-anchored", failed.Payload["sourceOffsetOrigin"]);
|
||||
Assert.Equal("bootstrap-policy-result", failed.Payload["sourceOffsetAnchor"]);
|
||||
Assert.Empty(f.InfoEvents(SharedEventTypes.ScriptTimeoutSuspected));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mixed_pair_on_the_offset_grid_omits_the_span_even_when_nothing_was_rejected()
|
||||
{
|
||||
// Session cbaed57b: start from AgentExecutor.log in the reader's zone (+120, two
|
||||
// hours too early), result era-anchored at 0 in the service log → 7205 s.
|
||||
var clockNow = new DateTime(2026, 9, 11, 8, 48, 25, DateTimeKind.Utc);
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var resultUtc = clockNow.AddSeconds(-1);
|
||||
var startUtc = resultUtc.AddSeconds(-7205);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("846cea22",
|
||||
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.None, file: ExecutorLog),
|
||||
resultUtc, Line(resultUtc, 0, CmTraceOffsetOrigin.EraAnchored, anchor: "bootstrap-policy-result")));
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.False(info.Payload!.ContainsKey("derivedTimestamp"));
|
||||
Assert.False(info.Payload.ContainsKey("durationSeconds"));
|
||||
Assert.Equal("offset-grid", info.Payload["durationSuppressedReason"]);
|
||||
Assert.Equal("unverified", info.Payload["durationProvenance"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mixed_pair_off_the_grid_keeps_the_span_as_unverified()
|
||||
{
|
||||
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var resultUtc = clockNow.AddSeconds(-1);
|
||||
var startUtc = resultUtc.AddSeconds(-26);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("f6f67f79",
|
||||
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored),
|
||||
resultUtc, Line(resultUtc, 120, CmTraceOffsetOrigin.None)));
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.Equal("26.00", info.Payload!["durationSeconds"]);
|
||||
Assert.Equal("script_runtime", info.Payload["durationBasis"]);
|
||||
Assert.Equal("unverified", info.Payload["durationProvenance"]);
|
||||
Assert.False(info.Payload.ContainsKey("durationSuppressedReason"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Two_line_anchored_ends_on_the_grid_are_a_verified_fifteen_minute_run()
|
||||
{
|
||||
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var resultUtc = clockNow.AddSeconds(-1);
|
||||
var startUtc = resultUtc.AddSeconds(-900);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("11111111",
|
||||
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored),
|
||||
resultUtc, Line(resultUtc, 120, CmTraceOffsetOrigin.LineAnchored)));
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.Equal("900.00", info.Payload!["durationSeconds"]);
|
||||
Assert.Equal("verified", info.Payload["durationProvenance"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Two_fallback_ends_from_the_same_file_share_their_error_and_stay_measurable()
|
||||
{
|
||||
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var resultUtc = clockNow.AddSeconds(-1);
|
||||
var startUtc = resultUtc.AddSeconds(-900);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("22222222",
|
||||
startUtc, Line(startUtc, 60, CmTraceOffsetOrigin.None),
|
||||
resultUtc, Line(resultUtc, 60, CmTraceOffsetOrigin.None)));
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.Equal("900.00", info.Payload!["durationSeconds"]);
|
||||
Assert.Equal("verified", info.Payload["durationProvenance"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Two_fallback_ends_from_different_files_are_different_writers()
|
||||
{
|
||||
// Same reader zone applied to both, but the executor child process and the service
|
||||
// can hold different beliefs (cbaed57b) — a grid-sized span is not trusted.
|
||||
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var resultUtc = clockNow.AddSeconds(-1);
|
||||
var startUtc = resultUtc.AddSeconds(-900);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("33333333",
|
||||
startUtc, Line(startUtc, 60, CmTraceOffsetOrigin.None, file: ExecutorLog),
|
||||
resultUtc, Line(resultUtc, 60, CmTraceOffsetOrigin.None)));
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.False(info.Payload!.ContainsKey("durationSeconds"));
|
||||
Assert.Equal("offset-grid", info.Payload["durationSuppressedReason"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Without_provenance_the_pair_is_taken_as_before()
|
||||
{
|
||||
// States from before the field (persisted by an older agent) and synthetic events:
|
||||
// no snapshot on either end, the 30-minute Failed run still reads as a timeout.
|
||||
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
f.Tracker.LastMatchedLogTimestamp = clockNow.AddSeconds(-1);
|
||||
adapter.TriggerScriptCompletedFromTest(new ScriptExecutionState
|
||||
{
|
||||
PolicyId = "44444444",
|
||||
ScriptType = "platform",
|
||||
ExitCode = 0,
|
||||
Result = "Failed",
|
||||
StartedAtUtc = clockNow.AddSeconds(-1801),
|
||||
});
|
||||
|
||||
var failed = f.InfoEvent(SharedEventTypes.ScriptFailed);
|
||||
Assert.Equal("1800.00", failed.Payload!["durationSeconds"]);
|
||||
Assert.False(failed.Payload.ContainsKey("durationProvenance"));
|
||||
Assert.False(failed.Payload.ContainsKey("durationSuppressedReason"));
|
||||
Assert.Single(f.InfoEvents(SharedEventTypes.ScriptTimeoutSuspected));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Negative_grid_sized_span_from_a_future_shifted_start_is_named_not_dropped_silently()
|
||||
{
|
||||
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var resultUtc = clockNow.AddSeconds(-1);
|
||||
var startUtc = resultUtc.AddSeconds(3595); // resolved one hour ahead of its real instant
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(Platform("55555555",
|
||||
startUtc, Line(startUtc, 60, CmTraceOffsetOrigin.None),
|
||||
resultUtc, Line(resultUtc, 120, CmTraceOffsetOrigin.LineAnchored)));
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.False(info.Payload!.ContainsKey("durationSeconds"));
|
||||
Assert.Equal("offset-grid", info.Payload["durationSuppressedReason"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Health_script_cycle_is_judged_the_same_way()
|
||||
{
|
||||
// HS-SCRIPT-START self-anchored, HS-NEW-RESULT re-read in the reader's zone and
|
||||
// rejected: the cycle duration is omitted, the compliance verdict stays.
|
||||
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
|
||||
using var f = new ImeLogTrackerAdapterFixture(clockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var startUtc = clockNow.AddSeconds(-40);
|
||||
var resultRaw = clockNow.AddSeconds(-2).AddHours(1);
|
||||
|
||||
adapter.TriggerScriptCompletedFromTest(new ScriptExecutionState
|
||||
{
|
||||
PolicyId = "66666666",
|
||||
ScriptType = "remediation",
|
||||
ScriptPart = "detection",
|
||||
ExitCode = 0,
|
||||
ComplianceResult = "True",
|
||||
StartedAtUtc = startUtc,
|
||||
StartedAtProvenance = Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored),
|
||||
ResultObservedAtUtc = resultRaw,
|
||||
ResultProvenance = Line(resultRaw, 60, CmTraceOffsetOrigin.None),
|
||||
DurationBasis = "cycle_including_reporting_latency",
|
||||
});
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.Equal("True", info.Payload!["complianceResult"]);
|
||||
Assert.False(info.Payload.ContainsKey("durationSeconds"));
|
||||
Assert.Equal("rejected-endpoint", info.Payload["durationSuppressedReason"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -247,6 +247,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
|
||||
f.Tracker.LastMatchedLogTimestamp = ClockNow;
|
||||
f.Tracker.CompletePlatformScriptFromImeResultForTesting("beef7777", "Success", ClockNow);
|
||||
// No end block is seeded — the held result goes out with the shutdown flush.
|
||||
f.Tracker.FlushPendingPlatformScriptResults(f.Clock.UtcNow, force: true);
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
// Without the hardening the slot kept the 7-day-old start: the duration would have
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
{
|
||||
/// <summary>
|
||||
/// A held platform-script completion (IME result read before the executor end block) is
|
||||
/// emitted at the end of a later pass, when the tracker's "last matched" line is an unrelated
|
||||
/// one — the event stays bound to the result line's timestamp and pattern.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerAdapterResultHoldTests
|
||||
{
|
||||
private static readonly DateTime ClockNow = new DateTime(2026, 9, 10, 22, 13, 40, DateTimeKind.Utc);
|
||||
|
||||
[Fact]
|
||||
public void Held_completion_is_bound_to_the_result_line_not_to_the_last_matched_one()
|
||||
{
|
||||
using var f = new ImeLogTrackerAdapterFixture(ClockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var startTs = ClockNow.AddSeconds(-95);
|
||||
var resultTs = ClockNow.AddSeconds(-3);
|
||||
|
||||
f.Tracker.LastMatchedLogTimestamp = startTs;
|
||||
f.Tracker.HandlePlatformScriptStarted("376ee51a");
|
||||
|
||||
f.Tracker.LastMatchedLogTimestamp = resultTs;
|
||||
f.Tracker.LastMatchedPatternId = "PS-SCRIPT-RESULT";
|
||||
f.Tracker.CompletePlatformScriptFromImeResultForTesting("376ee51a", "Success", resultTs);
|
||||
Assert.Empty(f.InfoEvents(SharedEventTypes.ScriptCompleted));
|
||||
|
||||
// Other lines were matched before the end block was read and the pass ended.
|
||||
f.Tracker.LastMatchedLogTimestamp = ClockNow.AddSeconds(-1);
|
||||
f.Tracker.LastMatchedPatternId = "IME-DOWNLOADING";
|
||||
f.Tracker.RecordPlatformScriptExitCodeForTesting("376ee51a", 0, resultTs.AddMilliseconds(-8));
|
||||
f.Tracker.FlushPendingPlatformScriptResults(f.Clock.UtcNow);
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.Equal(resultTs, info.OccurredAtUtc);
|
||||
Assert.Equal("PS-SCRIPT-RESULT", info.Payload!["patternId"]);
|
||||
Assert.Equal("0", info.Payload["exitCode"]);
|
||||
Assert.Equal("ime_policy_result", info.Payload["resultSource"]);
|
||||
Assert.Equal("92.00", info.Payload["durationSeconds"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Held_completion_carries_the_provenance_of_its_result_line()
|
||||
{
|
||||
using var f = new ImeLogTrackerAdapterFixture(ClockNow);
|
||||
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
|
||||
|
||||
var startTs = ClockNow.AddSeconds(-95);
|
||||
var resultTs = ClockNow.AddSeconds(-3);
|
||||
|
||||
// Start and result lines both self-anchored (+120).
|
||||
f.Tracker.LastMatchedLogTimestamp = startTs;
|
||||
f.Tracker.LastMatchedSourceLocalTimestamp = DateTime.SpecifyKind(startTs.AddMinutes(120), DateTimeKind.Unspecified);
|
||||
f.Tracker.LastMatchedSourceOffsetOrigin = CmTraceOffsetOrigin.LineAnchored;
|
||||
f.Tracker.LastMatchedSourceOffsetMinutes = 120;
|
||||
f.Tracker.HandlePlatformScriptStarted("376ee51a");
|
||||
|
||||
f.Tracker.LastMatchedLogTimestamp = resultTs;
|
||||
f.Tracker.LastMatchedSourceLocalTimestamp = DateTime.SpecifyKind(resultTs.AddMinutes(120), DateTimeKind.Unspecified);
|
||||
f.Tracker.LastMatchedPatternId = "PS-SCRIPT-RESULT";
|
||||
f.Tracker.CompletePlatformScriptFromImeResultForTesting("376ee51a", "Success", resultTs);
|
||||
|
||||
// By the time the held completion is emitted, the last matched line is an unrelated
|
||||
// one resolved in the reader's zone.
|
||||
f.Tracker.LastMatchedLogTimestamp = ClockNow.AddSeconds(-1);
|
||||
f.Tracker.LastMatchedSourceLocalTimestamp = DateTime.SpecifyKind(ClockNow.AddSeconds(-1).AddMinutes(60), DateTimeKind.Unspecified);
|
||||
f.Tracker.LastMatchedSourceOffsetOrigin = CmTraceOffsetOrigin.None;
|
||||
f.Tracker.LastMatchedSourceOffsetMinutes = 60;
|
||||
f.Tracker.LastMatchedPatternId = "IME-DOWNLOADING";
|
||||
f.Tracker.RecordPlatformScriptExitCodeForTesting("376ee51a", 0, resultTs.AddMilliseconds(-8));
|
||||
f.Tracker.FlushPendingPlatformScriptResults(f.Clock.UtcNow);
|
||||
|
||||
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
|
||||
Assert.Equal("line-anchored", info.Payload!["sourceOffsetOrigin"]);
|
||||
Assert.Equal("120", info.Payload["sourceOffsetMinutes"]);
|
||||
Assert.Equal(resultTs.AddMinutes(120).ToString("yyyy-MM-ddTHH:mm:ss.fffffff"), info.Payload["sourceLocalTs"]);
|
||||
Assert.Equal("line-anchored", info.Payload["startSourceOffsetOrigin"]);
|
||||
Assert.Equal("120", info.Payload["startSourceOffsetMinutes"]);
|
||||
Assert.Equal("92.00", info.Payload["durationSeconds"]);
|
||||
Assert.Equal("verified", info.Payload["durationProvenance"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
@@ -564,6 +564,37 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Termination
|
||||
Assert.False(File.Exists(Path.Combine(rig.StateDir, "enrollment-complete.marker")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_whiteglove_part1_writes_marker_before_the_later_exit_steps()
|
||||
{
|
||||
// The technician's reseal can kill the process anywhere after the seal. The marker
|
||||
// is what lets the next boot skip the 48-hour break and resume Part 2, so it must
|
||||
// exist before collectors stop, diagnostics upload, grace and drain run.
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.WhiteGloveSealed }.Build();
|
||||
bool? markerPresentAtCollectorStop = null;
|
||||
rig.StopPeripheralCollectorsHook = () => markerPresentAtCollectorStop = rig.SessionPersistence.IsWhiteGloveResume();
|
||||
|
||||
rig.Build().Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.WhiteGloveSealed));
|
||||
|
||||
Assert.True(markerPresentAtCollectorStop, "whiteglove.complete must be written before the peripheral collectors are stopped.");
|
||||
var emitted = rig.EmittedEventTypes.ToList();
|
||||
Assert.True(emitted.IndexOf("agent_shutting_down") >= 0, "agent_shutting_down must still be emitted.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_non_whiteglove_termination_never_writes_the_marker()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
|
||||
|
||||
rig.Build().Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
|
||||
|
||||
Assert.False(rig.SessionPersistence.IsWhiteGloveResume());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_whiteglove_part1_stops_collectors_before_emitting_part1_complete()
|
||||
{
|
||||
|
||||
+29
@@ -88,6 +88,35 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
Assert.Null(ex.ErrorCode);
|
||||
}
|
||||
|
||||
// ── coded 409: a refusal, never an auth failure ─────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Coded_409_is_a_refusal_not_an_auth_failure()
|
||||
{
|
||||
using var client = BuildClient(
|
||||
HttpStatusCode.Conflict,
|
||||
"{\"success\":false,\"message\":\"Session id is already registered to another tenant\",\"errorCode\":\"session_owner_mismatch\"}",
|
||||
"application/json");
|
||||
|
||||
var ex = await Assert.ThrowsAsync<BackendRefusalException>(
|
||||
() => client.RegisterSessionAsync(new AutopilotMonitor.Shared.Models.SessionRegistration()));
|
||||
|
||||
Assert.Equal(409, ex.StatusCode);
|
||||
Assert.Equal("session_owner_mismatch", ex.ErrorCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Uncoded_409_stays_a_plain_http_error()
|
||||
{
|
||||
using var client = BuildClient(
|
||||
HttpStatusCode.Conflict,
|
||||
"{\"success\":false,\"message\":\"A diagnostics package with this name already exists\"}",
|
||||
"application/json");
|
||||
|
||||
await Assert.ThrowsAsync<HttpRequestException>(
|
||||
() => client.GetDiagnosticsUploadUrlAsync("tenant-1", "session-1", "package.zip"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null)]
|
||||
[InlineData("", null)]
|
||||
|
||||
+24
-1
@@ -33,6 +33,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
private readonly Stream _stream;
|
||||
private readonly int _maxLineBytes;
|
||||
private readonly bool _hashLines;
|
||||
private readonly byte[] _readBuffer = new byte[ReadBufferSize];
|
||||
private int _readPos;
|
||||
private int _readLen;
|
||||
@@ -41,21 +42,32 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
private byte[] _line = new byte[4096];
|
||||
private int _lineLen;
|
||||
private ulong _lineHash;
|
||||
|
||||
/// <param name="stream">Seekable stream positioned at the first byte to read.</param>
|
||||
/// <param name="maxLineBytes">Upper bound of bytes kept per line; the remainder is discarded.</param>
|
||||
public BoundedLineReader(Stream stream, int maxLineBytes)
|
||||
/// <param name="hashLines">Fingerprint the raw bytes of every line (<see cref="LastLineHash"/>) — the
|
||||
/// tracker's byte ledger needs it for multi-writer files only.</param>
|
||||
public BoundedLineReader(Stream stream, int maxLineBytes, bool hashLines = false)
|
||||
{
|
||||
if (stream == null) throw new ArgumentNullException(nameof(stream));
|
||||
if (maxLineBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxLineBytes));
|
||||
_stream = stream;
|
||||
_maxLineBytes = maxLineBytes;
|
||||
_hashLines = hashLines;
|
||||
_readBufferFileOffset = stream.Position;
|
||||
}
|
||||
|
||||
/// <summary>Cap in bytes applied to every line.</summary>
|
||||
public int MaxLineBytes => _maxLineBytes;
|
||||
|
||||
/// <summary>
|
||||
/// FNV-1a 64 over the bytes the most recently returned line was decoded from (BOM and
|
||||
/// line terminator excluded; the capped prefix of a truncated line). Zero unless the
|
||||
/// reader was created with hashing on.
|
||||
/// </summary>
|
||||
public ulong LastLineHash => _lineHash;
|
||||
|
||||
/// <summary>Absolute file offset of the next unread byte (exact — no decoder read-ahead).</summary>
|
||||
public long Position => _readBufferFileOffset + _readPos;
|
||||
|
||||
@@ -78,6 +90,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
LastLineTerminated = false;
|
||||
LastLineTruncated = false;
|
||||
_lineLen = 0;
|
||||
_lineHash = _hashLines ? Fnv1a64.OffsetBasis : 0UL;
|
||||
var sawAnyByte = false;
|
||||
|
||||
while (true)
|
||||
@@ -154,6 +167,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// tail (and thus any CR) discarded, so the check is skipped there.
|
||||
if (LastLineTerminated && !LastLineTruncated && len > 0 && _line[start + len - 1] == (byte)'\r')
|
||||
len--;
|
||||
if (_hashLines)
|
||||
{
|
||||
// Fingerprint exactly the bytes the string is decoded from, so a tail that was
|
||||
// first read unterminated and later gained its CRLF hashes the same.
|
||||
var h = Fnv1a64.OffsetBasis;
|
||||
var end = start + len;
|
||||
for (var i = start; i < end; i++)
|
||||
h = (h ^ _line[i]) * Fnv1a64.Prime;
|
||||
_lineHash = h;
|
||||
}
|
||||
return len == 0 ? string.Empty : Encoding.UTF8.GetString(_line, start, len);
|
||||
}
|
||||
}
|
||||
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
using System.Text;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>FNV-1a 64-bit — the entry fingerprint used by the tracker's byte ledger.</summary>
|
||||
internal static class Fnv1a64
|
||||
{
|
||||
public const ulong OffsetBasis = 14695981039346656037UL;
|
||||
public const ulong Prime = 1099511628211UL;
|
||||
|
||||
public static ulong Fold(ulong hash, ulong value) => (hash ^ value) * Prime;
|
||||
}
|
||||
|
||||
/// <summary>One assembled CMTrace entry: its byte range in the file, the fingerprint of those bytes and the text.</summary>
|
||||
internal struct AssembledEntry
|
||||
{
|
||||
public long Offset;
|
||||
public int Length;
|
||||
public ulong Hash;
|
||||
public string Text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns physical lines into CMTrace entries: a line is one entry, unless it opens
|
||||
/// <c><![LOG[</c> without its <c>]LOG]!></c> close — then the continuation lines up to the
|
||||
/// closing one belong to it. Oversized lines and capped entries are dropped together with
|
||||
/// their remaining continuation lines, so no fragment is ever matched as an entry.
|
||||
/// <para>
|
||||
/// The read loop and the ledger verification (<c>ImeLogTracker.Overwrite.cs</c>) both feed
|
||||
/// this class, which is what makes their entry boundaries — and therefore the fingerprints
|
||||
/// they compare — identical by construction.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal sealed class CmTraceEntryAssembler
|
||||
{
|
||||
public enum Outcome
|
||||
{
|
||||
/// <summary>The line was absorbed into an open multiline entry.</summary>
|
||||
Buffered,
|
||||
/// <summary>An entry is complete.</summary>
|
||||
Entry,
|
||||
/// <summary>A line over the byte cap was dropped (its entry with it).</summary>
|
||||
OversizedDropped,
|
||||
/// <summary>An open multiline entry hit the line/char cap and was dropped.</summary>
|
||||
CapDropped,
|
||||
/// <summary>A continuation line of a dropped entry was skipped.</summary>
|
||||
Skipped,
|
||||
}
|
||||
|
||||
private const string LogOpen = "<![LOG[";
|
||||
private const string LogClose = "]LOG]!>";
|
||||
|
||||
private readonly int _maxLines;
|
||||
private readonly int _maxChars;
|
||||
|
||||
private StringBuilder _buffer;
|
||||
private int _lineCount;
|
||||
private long _entryStart;
|
||||
private ulong _entryHash;
|
||||
private bool _skippingDroppedEntry;
|
||||
|
||||
public CmTraceEntryAssembler(int maxMultiLineBufferLines, int maxEntryBytes)
|
||||
{
|
||||
_maxLines = maxMultiLineBufferLines;
|
||||
_maxChars = maxEntryBytes;
|
||||
}
|
||||
|
||||
/// <summary>True while a multiline entry is being assembled.</summary>
|
||||
public bool HasOpenEntry => _buffer != null;
|
||||
|
||||
/// <summary>File offset of the open multiline entry (valid while <see cref="HasOpenEntry"/>).</summary>
|
||||
public long OpenEntryStart => _entryStart;
|
||||
|
||||
/// <summary>Line count of the entry dropped by the last <see cref="Outcome.CapDropped"/>.</summary>
|
||||
public int DroppedLines { get; private set; }
|
||||
|
||||
/// <summary>Char count of the entry dropped by the last <see cref="Outcome.CapDropped"/>.</summary>
|
||||
public int DroppedChars { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Feeds one physical line. <paramref name="lineStart"/> / <paramref name="positionAfter"/>
|
||||
/// are the line's file offsets (start, next unread byte), <paramref name="lineHash"/> the
|
||||
/// reader's raw-byte fingerprint of the line.
|
||||
/// </summary>
|
||||
public Outcome Feed(string line, long lineStart, long positionAfter, bool truncated, ulong lineHash, out AssembledEntry entry)
|
||||
{
|
||||
entry = default(AssembledEntry);
|
||||
|
||||
if (truncated)
|
||||
{
|
||||
// The capped prefix only tells whether the line opened an entry whose remaining
|
||||
// lines must be skipped rather than matched as raw text.
|
||||
if (_buffer != null)
|
||||
{
|
||||
_buffer = null;
|
||||
_lineCount = 0;
|
||||
_skippingDroppedEntry = true;
|
||||
}
|
||||
else if (line.StartsWith(LogOpen) && !line.Contains(LogClose))
|
||||
{
|
||||
_skippingDroppedEntry = true;
|
||||
}
|
||||
return Outcome.OversizedDropped;
|
||||
}
|
||||
|
||||
if (_skippingDroppedEntry)
|
||||
{
|
||||
// A line opening a new entry ends the skip and is processed itself — checked
|
||||
// BEFORE the close-tag test, because a complete single-line entry contains both.
|
||||
if (line.StartsWith(LogOpen))
|
||||
_skippingDroppedEntry = false;
|
||||
else
|
||||
{
|
||||
if (line.Contains(LogClose)) _skippingDroppedEntry = false;
|
||||
return Outcome.Skipped;
|
||||
}
|
||||
}
|
||||
|
||||
if (_buffer != null)
|
||||
{
|
||||
_buffer.Append('\n').Append(line);
|
||||
_lineCount++;
|
||||
_entryHash = Fnv1a64.Fold(_entryHash, lineHash);
|
||||
|
||||
if (line.Contains(LogClose))
|
||||
{
|
||||
entry = new AssembledEntry
|
||||
{
|
||||
Offset = _entryStart,
|
||||
Length = (int)(positionAfter - _entryStart),
|
||||
Hash = _entryHash,
|
||||
Text = _buffer.ToString(),
|
||||
};
|
||||
_buffer = null;
|
||||
_lineCount = 0;
|
||||
return Outcome.Entry;
|
||||
}
|
||||
|
||||
if (_lineCount >= _maxLines || _buffer.Length >= _maxChars)
|
||||
{
|
||||
DroppedLines = _lineCount;
|
||||
DroppedChars = _buffer.Length;
|
||||
_buffer = null;
|
||||
_lineCount = 0;
|
||||
_skippingDroppedEntry = true;
|
||||
return Outcome.CapDropped;
|
||||
}
|
||||
|
||||
return Outcome.Buffered;
|
||||
}
|
||||
|
||||
if (line.StartsWith(LogOpen) && !line.Contains(LogClose))
|
||||
{
|
||||
_buffer = new StringBuilder(line);
|
||||
_lineCount = 1;
|
||||
_entryStart = lineStart;
|
||||
_entryHash = lineHash;
|
||||
return Outcome.Buffered;
|
||||
}
|
||||
|
||||
entry = new AssembledEntry
|
||||
{
|
||||
Offset = lineStart,
|
||||
Length = (int)(positionAfter - lineStart),
|
||||
Hash = lineHash,
|
||||
Text = line,
|
||||
};
|
||||
return Outcome.Entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// How ONE CMTrace line's UTC value was arrived at, captured at the line itself.
|
||||
/// <para>
|
||||
/// The tracker exposes the provenance of the line it matched last. A consumer that acts later —
|
||||
/// a platform-script result held for its executor end block, a run duration spanning a start
|
||||
/// line and a result line — must describe ITS line, not whichever line happened to be matched
|
||||
/// last, so the snapshot travels on <see cref="ScriptExecutionState"/> (persisted as a plain
|
||||
/// DTO; null on state files written before it existed).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class CmTraceLineProvenance
|
||||
{
|
||||
/// <summary>
|
||||
/// The line's local time exactly as the writer wrote it (Kind Unspecified, no zone). Null
|
||||
/// when the value did not come from a CMTrace line at all (clock fallback).
|
||||
/// </summary>
|
||||
public DateTime? SourceLocalTs { get; set; }
|
||||
|
||||
/// <summary>How the offset applied to <see cref="SourceLocalTs"/> was obtained.</summary>
|
||||
public CmTraceOffsetOrigin Origin { get; set; }
|
||||
|
||||
/// <summary>The offset that was applied, in minutes (local = UTC + offset).</summary>
|
||||
public int? OffsetMinutes { get; set; }
|
||||
|
||||
/// <summary>For <see cref="CmTraceOffsetOrigin.EraAnchored"/>: which anchor established the era's offset.</summary>
|
||||
public string EraAnchorKind { get; set; }
|
||||
|
||||
/// <summary>What the calibrator measured for the source file — observational, never applied.</summary>
|
||||
public int? MeasuredWriterOffsetMinutes { get; set; }
|
||||
|
||||
/// <summary>Name of the log file the line was read from — the closest thing to a writer identity the tracker has.</summary>
|
||||
public string SourceFileName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True when the applied offset was ASSUMED for this line rather than declared by the
|
||||
/// writer or measured against the agent clock: the reader's own zone (fallback), a writer
|
||||
/// era's anchor, or the retired per-file calibration. A clock-derived value (no source
|
||||
/// timestamp) sits on the true UTC axis and is not an assumption.
|
||||
/// </summary>
|
||||
public bool IsAssumed()
|
||||
{
|
||||
if (!SourceLocalTs.HasValue) return false;
|
||||
switch (Origin)
|
||||
{
|
||||
case CmTraceOffsetOrigin.Bias:
|
||||
case CmTraceOffsetOrigin.LineAnchored:
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -159,6 +159,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a span between two resolved lines is the signature of a wrong offset on one
|
||||
/// of them rather than of elapsed time: a zone error is always a whole number of grid
|
||||
/// steps, so a span within <see cref="MaxGridResidual"/> of k × <see cref="OffsetGrid"/>
|
||||
/// (k ≥ 1) reads as an offset error plus a run time of seconds. Sign is ignored — a wrong
|
||||
/// offset on the START end produces the same magnitude with the opposite sign.
|
||||
/// </summary>
|
||||
internal static bool IsOnOffsetGrid(TimeSpan span, out int gridSteps)
|
||||
{
|
||||
var magnitude = span.Duration();
|
||||
gridSteps = (int)Math.Round(magnitude.TotalMinutes / OffsetGrid.TotalMinutes, MidpointRounding.AwayFromZero);
|
||||
if (gridSteps < 1) return false;
|
||||
|
||||
var nearest = TimeSpan.FromMinutes(gridSteps * OffsetGrid.TotalMinutes);
|
||||
return (magnitude - nearest).Duration() <= MaxGridResidual;
|
||||
}
|
||||
|
||||
public bool TryCalibrate(string sourceKey, DateTime localTimestamp, DateTime agentUtcNow)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sourceKey)) return false;
|
||||
|
||||
+358
-190
@@ -222,20 +222,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// PowerShell script tracking handlers
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
// Returns the current platform-script accumulator, or null when no platform script is active.
|
||||
// Health-script (remediation) state is no longer tracked line-by-line — the HS-NEW-RESULT
|
||||
// pattern delivers the full pre-detection / remediation / post-detection JSON in one shot
|
||||
// via HandleHealthScriptResult. The platform branch keeps its line-by-line accumulator
|
||||
// because PS-* patterns (PS-SCRIPT-CONTEXT / PS-SCRIPT-EXITCODE / PS-AGENT-OUTPUT / …) still
|
||||
// arrive across multiple log lines.
|
||||
private ScriptExecutionState GetCurrentPlatformScript()
|
||||
{
|
||||
if (!string.IsNullOrEmpty(_lastPlatformScriptPolicyId) &&
|
||||
_pendingPlatformScripts.TryGetValue(_lastPlatformScriptPolicyId, out var state))
|
||||
return state;
|
||||
return null;
|
||||
}
|
||||
|
||||
private void HandleScriptStarted(Match match, Dictionary<string, string> parameters)
|
||||
{
|
||||
var id = match.Groups["id"]?.Value;
|
||||
@@ -266,10 +252,22 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// duration when the consolidated [HS] new result line arrives (the slot above is
|
||||
// cleared by the early-signal HS-COMPLIANCE handler, so timing lives in its own
|
||||
// map). Prefer the source CMTrace timestamp; latest start wins on a policy re-run.
|
||||
_healthScriptStartTimes[id] = LastMatchedLogTimestamp ?? DateTime.UtcNow;
|
||||
var startedAtUtc = LastMatchedLogTimestamp ?? UtcNowProvider();
|
||||
_healthScriptStartTimes[id] = (startedAtUtc, CaptureLastMatchedProvenance());
|
||||
_logger.Info($"ImeLogTracker: health script started: {id}");
|
||||
try { OnScriptStarted?.Invoke(new ScriptStartedInfo { PolicyId = id, ScriptType = "remediation", PolicyType = policyType }); }
|
||||
catch (Exception ex) { _logger.Warning($"ImeLogTracker: OnScriptStarted handler threw: {ex.Message}"); }
|
||||
|
||||
// A replayed line of a previous enrollment bypasses the recurrence gate: the
|
||||
// adapter drops its event, and a dropped run must not count as the policy's
|
||||
// first report.
|
||||
if (!_currentLineIsHistoricReplay
|
||||
&& !_recurringScripts.OnStart(id, startedAtUtc, policyType, LastMatchedPatternId))
|
||||
{
|
||||
_stateDirty = true;
|
||||
_logger.Debug($"ImeLogTracker: health script {id} is a recurring policy — start held until its result is known");
|
||||
return;
|
||||
}
|
||||
_stateDirty = true;
|
||||
RaiseScriptStarted(new ScriptStartedInfo { PolicyId = id, ScriptType = "remediation", PolicyType = policyType });
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -282,27 +280,61 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// a regex Match).
|
||||
internal void HandlePlatformScriptStarted(string id, string source = null)
|
||||
{
|
||||
// Stale-slot hardening (session eaf3d8c4): a replayed start line from a previous
|
||||
// enrollment whose matching result never appeared (script was mid-run when that
|
||||
// enrollment ended) leaves a pending slot with a days-old StartedAtUtc. When the
|
||||
// same policy genuinely re-runs now, the fresh start must begin a NEW execution —
|
||||
// otherwise the ancient start pairs with the fresh completion and the duration
|
||||
// lies. > 24 h mirrors the adapter's source-timestamp staleness clamp.
|
||||
var currentStartTs = LastMatchedLogTimestamp ?? DateTime.UtcNow;
|
||||
if (_pendingPlatformScripts.TryGetValue(id, out var pendingSlot)
|
||||
&& pendingSlot.StartedAtUtc.HasValue
|
||||
&& currentStartTs - pendingSlot.StartedAtUtc.Value > TimeSpan.FromHours(24))
|
||||
var currentStartTs = LastMatchedLogTimestamp ?? UtcNowProvider();
|
||||
var currentStartProvenance = CaptureLastMatchedProvenance();
|
||||
|
||||
// A start line older than the result this policy already emitted is the late start
|
||||
// line of THAT run: its AgentExecutor block surfaced after the IME result — the two
|
||||
// files are read in turn (AgentExecutor.log first, but a script's exit line and IME's
|
||||
// result line are 8–30 ms apart), a ledger rewind recovered the block, or the poll
|
||||
// loop stalled (session e7f3c910: the late line opened a second slot, cleared the
|
||||
// emitted-marker and turned the exit code that followed into a fallback duplicate
|
||||
// 15 s later). It owns the lines behind it in its file and opens nothing. Strictly
|
||||
// older: a start line at the result's own timestamp is the next run (source lines
|
||||
// never tie; a low-resolution clock in a test may).
|
||||
if (_platformScriptResultEmitted.TryGetValue(id, out var emittedResultTs) && currentStartTs < emittedResultTs)
|
||||
{
|
||||
_logger.Debug($"ImeLogTracker: discarding stale pending platform-script slot for {id} (started {pendingSlot.StartedAtUtc:o})");
|
||||
_pendingPlatformScripts.Remove(id);
|
||||
RecordInvocationMarker(id, isClose: false);
|
||||
NoteInvocationActivity();
|
||||
_logger.Debug($"ImeLogTracker: platform script start line for {id} (source: {source ?? "ime"}) predates its emitted result — late line of that run, not a new one");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_pendingPlatformScripts.TryGetValue(id, out var pendingSlot))
|
||||
{
|
||||
if (pendingSlot.StartedAtUtc.HasValue && currentStartTs - pendingSlot.StartedAtUtc.Value > TimeSpan.FromHours(24))
|
||||
{
|
||||
// Stale-slot hardening (session eaf3d8c4): a replayed start line from a previous
|
||||
// enrollment whose matching result never appeared (script was mid-run when that
|
||||
// enrollment ended) leaves a pending slot with a days-old StartedAtUtc. When the
|
||||
// same policy genuinely re-runs now, the fresh start must begin a NEW execution —
|
||||
// otherwise the ancient start pairs with the fresh completion and the duration
|
||||
// lies. > 24 h mirrors the adapter's source-timestamp staleness clamp.
|
||||
_logger.Debug($"ImeLogTracker: discarding stale pending platform-script slot for {id} (started {pendingSlot.StartedAtUtc:o})");
|
||||
_pendingPlatformScripts.Remove(id);
|
||||
}
|
||||
else if (pendingSlot.Result != null && pendingSlot.ResultObservedAtUtc.HasValue && currentStartTs >= pendingSlot.ResultObservedAtUtc.Value)
|
||||
{
|
||||
// The held run is over — a start line at or after its result is the next run.
|
||||
// Emit what the held run has; its end block did not surface in time.
|
||||
EmitPlatformScriptResult(pendingSlot, "the next run of this policy started");
|
||||
}
|
||||
else if (!pendingSlot.StartedAtUtc.HasValue)
|
||||
{
|
||||
// The slot was opened by its result while the start block was still hidden;
|
||||
// the recovered start line dates the run.
|
||||
pendingSlot.StartedAtUtc = currentStartTs;
|
||||
pendingSlot.StartedAtProvenance = currentStartProvenance;
|
||||
_stateDirty = true;
|
||||
}
|
||||
}
|
||||
if (!_pendingPlatformScripts.ContainsKey(id))
|
||||
{
|
||||
// A fresh start for this policy (no pending entry) begins a NEW execution.
|
||||
// Clear any emitted-marker from a prior run so IME re-evaluations / retries of
|
||||
// the same platform-script policy within one agent lifetime are not silently
|
||||
// deduped away. Within a single run the start always precedes exit/result, so
|
||||
// this never clears the current run's own marker.
|
||||
// deduped away. A start line of the emitted run itself never reaches this point
|
||||
// (the guard above), so this never clears the current run's own marker.
|
||||
_platformScriptResultEmitted.Remove(id);
|
||||
_pendingPlatformScripts[id] = new ScriptExecutionState
|
||||
{
|
||||
@@ -313,6 +345,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Set only at slot creation: the start line fires twice (agentexecutor + ime
|
||||
// source) but the earliest wins.
|
||||
StartedAtUtc = currentStartTs,
|
||||
StartedAtProvenance = currentStartProvenance,
|
||||
};
|
||||
// Live "running" indicator — same signal health scripts emit. Gated on slot
|
||||
// creation so the duplicate start line (agentexecutor + ime source) doesn't
|
||||
@@ -320,7 +353,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
try { OnScriptStarted?.Invoke(new ScriptStartedInfo { PolicyId = id, ScriptType = "platform" }); }
|
||||
catch (Exception ex) { _logger.Warning($"ImeLogTracker: OnScriptStarted handler threw: {ex.Message}"); }
|
||||
}
|
||||
_lastPlatformScriptPolicyId = id;
|
||||
RecordInvocationMarker(id, isClose: false);
|
||||
NoteInvocationActivity();
|
||||
// Started lines fire twice per script (agentexecutor + ime source) and carry no
|
||||
// outcome — the matching `platform script completed` line below carries result+exit
|
||||
// and stays on Info. Keep starts on Debug so Info reflects script outcomes only.
|
||||
@@ -329,42 +363,55 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
// Routes line-by-line script-data handlers (context / exitCode / output) to the right
|
||||
// accumulator based on the pattern's scriptType parameter. Health-script lines feed the
|
||||
// single-slot _pendingHealthScript; platform-script lines feed _pendingPlatformScripts.
|
||||
// single-slot _pendingHealthScript (the HS-NEW-RESULT JSON delivers the full cycle in one
|
||||
// shot; the slot only enriches the early HS-COMPLIANCE signal). Platform-script lines feed
|
||||
// _pendingPlatformScripts, and the slot that owns a line is decided by file position (see
|
||||
// ImeLogTracker.Overwrite.cs), never by which script happened to start last.
|
||||
private ScriptExecutionState GetCurrentScriptForLineUpdate(Dictionary<string, string> parameters)
|
||||
=> GetCurrentScriptForLineUpdate(parameters, out _);
|
||||
|
||||
// ownerPolicyId names the platform script that owns the line by file position even when
|
||||
// its pending slot is gone (the completion was already emitted); null for health-script
|
||||
// lines and for lines no platform invocation owns.
|
||||
private ScriptExecutionState GetCurrentScriptForLineUpdate(Dictionary<string, string> parameters, out string ownerPolicyId)
|
||||
{
|
||||
var scriptType = parameters != null && parameters.TryGetValue("scriptType", out var st) ? st : null;
|
||||
return string.Equals(scriptType, "remediation", StringComparison.OrdinalIgnoreCase)
|
||||
? _pendingHealthScript
|
||||
: GetCurrentPlatformScript();
|
||||
if (string.Equals(scriptType, "remediation", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ownerPolicyId = null;
|
||||
return _pendingHealthScript;
|
||||
}
|
||||
return ResolvePlatformScriptForCurrentEntry(out ownerPolicyId);
|
||||
}
|
||||
|
||||
// Session 6b4993e5 fix — platform-script stdout/exit cross-contamination.
|
||||
//
|
||||
// AgentExecutor.exe hosts BOTH platform scripts (…\Policies\Scripts\<id>.ps1) and
|
||||
// proactive-remediation scripts (…\IMECache\HealthScripts\<id>\detect.ps1), and writes
|
||||
// their lines interleaved into the shared AgentExecutor.log. The policyId-less
|
||||
// PS-AGENT-EXITCODE ("Powershell exit code is N") and PS-AGENT-OUTPUT ("write output
|
||||
// done. output = …") lines are routed to whichever platform script
|
||||
// _lastPlatformScriptPolicyId points at. A remediation invocation's start
|
||||
// ("Adding argument remediationScript …") does NOT match PS-AGENT-SCRIPT-START, so it
|
||||
// never moves the pointer — its exit/output then bleed into the last-started PLATFORM
|
||||
// script's slot (observed: platform c3e0124c emitted result=Failed but with exit 0 +
|
||||
// stdout "[Compliant] No Classic Teams found" — the Teams remediation's output).
|
||||
//
|
||||
// Each AgentExecutor process logs "ExecutorLog AgentExecutor gets invoked" first, so a
|
||||
// new banner means the previous invocation's line-capture context is over. Clearing the
|
||||
// pointer here scopes line-capture to a single invocation: the immediately following
|
||||
// "Adding argument powershell …\Policies\Scripts\<id>.ps1" (PS-AGENT-SCRIPT-START)
|
||||
// re-establishes it for a platform invocation, while a remediation invocation leaves it
|
||||
// null so its exit/output are dropped (the remediation's authoritative data still
|
||||
// arrives via HS-NEW-RESULT). The platform script's final result is unaffected — it is
|
||||
// keyed by policyId via PS-SCRIPT-RESULT, not by this pointer.
|
||||
private void HandleAgentExecutorInvocationBoundary()
|
||||
// AgentExecutor.exe hosts platform scripts (…\Policies\Scripts\<id>.ps1) as well as
|
||||
// detection, requirement and proactive-remediation scripts, and its policyId-less
|
||||
// PS-AGENT-EXITCODE / PS-AGENT-OUTPUT lines belong to whichever invocation owns that
|
||||
// file position. The banner closes the previous invocation; the argument line that
|
||||
// follows opens the next one — as a platform script when PS-AGENT-SCRIPT-START matched
|
||||
// it, otherwise as an invocation whose exit/output are not captured (a remediation's
|
||||
// authoritative data arrives via HS-NEW-RESULT; session 6b4993e5 saw its output bleed
|
||||
// into a platform slot). "Agent executor completed" closes the invocation again.
|
||||
private void HandleAgentExecutorInvocation()
|
||||
{
|
||||
if (_lastPlatformScriptPolicyId == null) return;
|
||||
_logger.Debug(
|
||||
$"ImeLogTracker: AgentExecutor invocation boundary — clearing platform-script line-capture pointer (was {_lastPlatformScriptPolicyId}).");
|
||||
_lastPlatformScriptPolicyId = null;
|
||||
RecordInvocationMarker(null, isClose: true);
|
||||
NoteInvocationActivity();
|
||||
}
|
||||
|
||||
private void HandleAgentInvocationArgument(string kind)
|
||||
{
|
||||
RecordInvocationMarker(null, isClose: false);
|
||||
NoteInvocationActivity();
|
||||
if (!string.IsNullOrEmpty(kind) && !string.Equals(kind, "powershell", StringComparison.OrdinalIgnoreCase))
|
||||
_logger.Debug($"ImeLogTracker: AgentExecutor invocation of kind '{kind}' — exit/output lines not captured as a platform script");
|
||||
}
|
||||
|
||||
private void HandleAgentExecutorCompleted()
|
||||
{
|
||||
RecordInvocationMarker(null, isClose: true);
|
||||
// The end block was written at the executor's own stream position — if that lay
|
||||
// behind the bookmark, the ledger check on the next pass finds it.
|
||||
RequestOverwriteCheck();
|
||||
}
|
||||
|
||||
private void HandleScriptContext(Match match, Dictionary<string, string> parameters)
|
||||
@@ -372,6 +419,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
var context = match.Groups["context"]?.Value;
|
||||
if (string.IsNullOrEmpty(context)) return;
|
||||
|
||||
NoteInvocationActivity();
|
||||
var runContext = string.Equals(context, "machine", StringComparison.OrdinalIgnoreCase) ? "System" : "User";
|
||||
var script = GetCurrentScriptForLineUpdate(parameters);
|
||||
if (script != null)
|
||||
@@ -386,18 +434,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
var exitCodeStr = match.Groups["exitCode"]?.Value;
|
||||
if (string.IsNullOrEmpty(exitCodeStr) || !int.TryParse(exitCodeStr, out var exitCode)) return;
|
||||
|
||||
var script = GetCurrentScriptForLineUpdate(parameters);
|
||||
var script = GetCurrentScriptForLineUpdate(parameters, out var ownerPolicyId);
|
||||
if (script != null)
|
||||
ApplyExitCode(script, exitCode, LastMatchedLogTimestamp ?? UtcNowProvider(), CaptureLastMatchedProvenance());
|
||||
else if (ownerPolicyId != null)
|
||||
_logger.Debug($"ImeLogTracker: exit code {exitCode} belongs to platform script {ownerPolicyId}, whose completion was already emitted — dropped");
|
||||
// An exit code means the executor just wrote its end block and IME is about to
|
||||
// write the result — both land at a stale stream position when another process
|
||||
// appended meanwhile. Check the ledgers on the next pass.
|
||||
RequestOverwriteCheck();
|
||||
}
|
||||
|
||||
private void ApplyExitCode(ScriptExecutionState script, int exitCode, DateTime observedAtUtc, CmTraceLineProvenance exitProvenance)
|
||||
{
|
||||
script.ExitCode = exitCode;
|
||||
// Stamp when we learned the script's exit code so the deadline-based fallback
|
||||
// (FlushPendingPlatformScriptResults) can fire if IME never logs its authoritative
|
||||
// PS-SCRIPT-RESULT line in time. Prefer the source CMTrace timestamp (already
|
||||
// UTC-normalized by the parser) so replayed log content is dated correctly. The
|
||||
// line's provenance rides along: the fallback emit is bound to this line.
|
||||
if (string.Equals(script.ScriptType, "platform", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
script.ExitCode = exitCode;
|
||||
// Stamp when we learned the script's exit code so the deadline-based fallback
|
||||
// (FlushStalePlatformScriptResults) can fire if IME never logs its authoritative
|
||||
// PS-SCRIPT-RESULT line in time. Prefer the source CMTrace timestamp (already
|
||||
// UTC-normalized by the parser) so replayed log content is dated correctly.
|
||||
if (string.Equals(script.ScriptType, "platform", StringComparison.OrdinalIgnoreCase))
|
||||
script.ExitObservedAtUtc = LastMatchedLogTimestamp ?? DateTime.UtcNow;
|
||||
_logger.Debug($"ImeLogTracker: script exit code {exitCode} for {script.PolicyId}");
|
||||
script.ExitObservedAtUtc = observedAtUtc;
|
||||
script.ExitProvenance = exitProvenance;
|
||||
}
|
||||
_logger.Debug($"ImeLogTracker: script exit code {exitCode} for {script.PolicyId}");
|
||||
}
|
||||
|
||||
private void HandleScriptOutput(Match match, Dictionary<string, string> parameters)
|
||||
@@ -446,22 +507,36 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
if (string.IsNullOrEmpty(id)) return;
|
||||
|
||||
// Dedup: the deadline-based fallback (FlushStalePlatformScriptResults) may already have
|
||||
CompletePlatformScriptFromImeResult(id, result, LastMatchedLogTimestamp, LastMatchedPatternId, CaptureLastMatchedProvenance());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The authoritative IME <c>PS-SCRIPT-RESULT</c> line of a platform script. Emits at once
|
||||
/// when the executor end block (exit code, output) has been read already — the normal
|
||||
/// order of the two files — and otherwise holds the completion: the end block reaches the
|
||||
/// tracker after the result whenever a concurrent writer overwrote it (the check this
|
||||
/// result triggers recovers it one pass later), when the AgentExecutor.log read of a pass
|
||||
/// simply preceded the exit line by a few milliseconds, or when the poll loop stalled.
|
||||
/// Emitting immediately lost the exit code in all three cases and, once the late start
|
||||
/// line reopened the slot, produced a fallback duplicate (session e7f3c910).
|
||||
/// <see cref="FlushPendingPlatformScriptResults"/> emits the held completion.
|
||||
/// </summary>
|
||||
internal void CompletePlatformScriptFromImeResult(string policyId, string result, DateTime? resultLineTimestampUtc, string patternId, CmTraceLineProvenance resultProvenance)
|
||||
{
|
||||
// Dedup: the deadline-based fallback (FlushPendingPlatformScriptResults) may already have
|
||||
// emitted this script from its AgentExecutor exit code because IME's authoritative
|
||||
// PS-SCRIPT-RESULT line arrived late. The fallback carries the same exit code + stdout,
|
||||
// so re-emitting here would duplicate the timeline entry and inflate counts. Drop the
|
||||
// now-redundant pending entry and skip.
|
||||
if (_platformScriptResultEmitted.Contains(id))
|
||||
if (_platformScriptResultEmitted.ContainsKey(policyId))
|
||||
{
|
||||
_logger.Debug($"ImeLogTracker: platform script {id} PS-SCRIPT-RESULT arrived after fallback emit — skipping duplicate");
|
||||
_pendingPlatformScripts.Remove(id);
|
||||
if (string.Equals(_lastPlatformScriptPolicyId, id, StringComparison.OrdinalIgnoreCase))
|
||||
_lastPlatformScriptPolicyId = null;
|
||||
_logger.Debug($"ImeLogTracker: platform script {policyId} PS-SCRIPT-RESULT arrived after fallback emit — skipping duplicate");
|
||||
_pendingPlatformScripts.Remove(policyId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Merge with pending AgentExecutor data if available
|
||||
if (_pendingPlatformScripts.TryGetValue(id, out var script))
|
||||
if (_pendingPlatformScripts.TryGetValue(policyId, out var script))
|
||||
{
|
||||
// Stale-result guard: on an intra-lifetime re-run of the same policy, run 1's
|
||||
// late PS-SCRIPT-RESULT can arrive after run 2's start line already created a
|
||||
@@ -471,10 +546,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// line in the source log, so a result older than the pending slot's start
|
||||
// belongs to a previous run — drop it and keep the live slot intact.
|
||||
if (script.StartedAtUtc.HasValue
|
||||
&& LastMatchedLogTimestamp.HasValue
|
||||
&& LastMatchedLogTimestamp.Value < script.StartedAtUtc.Value)
|
||||
&& resultLineTimestampUtc.HasValue
|
||||
&& resultLineTimestampUtc.Value < script.StartedAtUtc.Value)
|
||||
{
|
||||
_logger.Debug($"ImeLogTracker: platform script {id} result predates the current run's start — stale result from a previous run, skipping");
|
||||
_logger.Debug($"ImeLogTracker: platform script {policyId} result predates the current run's start — stale result from a previous run, skipping");
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -482,70 +557,119 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
script = new ScriptExecutionState
|
||||
{
|
||||
PolicyId = id,
|
||||
PolicyId = policyId,
|
||||
ScriptType = "platform"
|
||||
};
|
||||
_pendingPlatformScripts[policyId] = script;
|
||||
}
|
||||
|
||||
script.Result = result;
|
||||
script.ResultSource = "ime_policy_result";
|
||||
|
||||
_logger.Info($"ImeLogTracker: platform script completed: {id}, result={result}, exit={script.ExitCode}");
|
||||
|
||||
EmitScriptEvent(script);
|
||||
_platformScriptResultEmitted.Add(id);
|
||||
_pendingPlatformScripts.Remove(id);
|
||||
script.ResultObservedAtUtc = resultLineTimestampUtc ?? UtcNowProvider();
|
||||
script.ResultProvenance = resultProvenance;
|
||||
script.ResultPatternId = patternId;
|
||||
_stateDirty = true;
|
||||
|
||||
if (script.ExitCode.HasValue)
|
||||
{
|
||||
EmitPlatformScriptResult(script);
|
||||
}
|
||||
else
|
||||
{
|
||||
script.ResultHeldSinceUtc = UtcNowProvider();
|
||||
_logger.Debug($"ImeLogTracker: platform script {policyId} result={result} seen before its executor end block — holding the completion up to {PlatformScriptEndBlockGrace.TotalSeconds:F0}s for the exit code");
|
||||
}
|
||||
// The result block is IME's first write after the script wait — the executor's end
|
||||
// block in the other file may have landed behind the bookmark at the same time.
|
||||
RequestOverwriteCheck();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one emit path for platform-script completions (IME result, held result, exit-code
|
||||
/// fallback): event, emitted-marker with the run's source timestamp, slot closed.
|
||||
/// </summary>
|
||||
private void EmitPlatformScriptResult(ScriptExecutionState script, string note = null)
|
||||
{
|
||||
_logger.Info($"ImeLogTracker: platform script completed: {script.PolicyId}, result={script.Result}, exit={script.ExitCode}{(note != null ? $" ({note})" : string.Empty)}");
|
||||
EmitScriptEvent(script);
|
||||
// The run's source stamp, capped at the clock: a result line cannot be read before it
|
||||
// was written, so a stamp ahead of the clock is a wrong zone assumption on that line
|
||||
// (a rewound result resolved in the reader's zone, session 4377911b: +1 h). Left
|
||||
// uncapped, the marker made the genuine NEXT run's start line read as a late line of
|
||||
// this run and its result a duplicate.
|
||||
var runStamp = script.ResultObservedAtUtc ?? script.ExitObservedAtUtc ?? UtcNowProvider();
|
||||
var nowUtc = UtcNowProvider();
|
||||
_platformScriptResultEmitted[script.PolicyId] = runStamp > nowUtc ? nowUtc : runStamp;
|
||||
_pendingPlatformScripts.Remove(script.PolicyId);
|
||||
_stateDirty = true;
|
||||
if (string.Equals(_lastPlatformScriptPolicyId, id, StringComparison.OrdinalIgnoreCase))
|
||||
_lastPlatformScriptPolicyId = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grace period after a platform script's AgentExecutor exit code is observed before
|
||||
/// <see cref="FlushStalePlatformScriptResults"/> emits a completion from that exit code.
|
||||
/// IME logs its authoritative <c>PS-SCRIPT-RESULT</c> line within ~1 s of exit on healthy
|
||||
/// reporting cycles, so 15 s lets the normal path win virtually always — the fallback is a
|
||||
/// true safety net for the case where IME has not flushed its batch-send to the Microsoft
|
||||
/// service before the (often short) Autopilot enrollment ends and the agent terminates.
|
||||
/// <see cref="FlushPendingPlatformScriptResults"/> emits a completion from that exit code.
|
||||
/// IME logs its authoritative <c>PS-SCRIPT-RESULT</c> line within ~1 s of exit; when it
|
||||
/// is missing after 15 s it was hidden by a concurrent writer (the ledger check in
|
||||
/// <c>ImeLogTracker.Overwrite.cs</c> recovers that line) or the enrollment ended before
|
||||
/// IME wrote it — this fallback is the safety net for the remaining cases.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan PlatformScriptResultGrace = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>
|
||||
/// Policy IDs of platform scripts already emitted (via either the authoritative
|
||||
/// PS-SCRIPT-RESULT path or the exit-code fallback). Guards against double emission when
|
||||
/// both fire for the same script.
|
||||
/// How long an IME result waits for the executor end block of its run before the
|
||||
/// completion goes out without an exit code. An overwritten end block surfaces on the
|
||||
/// pass after the result (100 ms, the result triggers the ledger check); a stalled poll
|
||||
/// loop was measured at 2 s (session e7f3c910, VM at 100 % CPU). Well below the 15 s
|
||||
/// exit-code fallback, and the event keeps the result line's timestamp — only its
|
||||
/// delivery waits.
|
||||
/// </summary>
|
||||
private readonly HashSet<string> _platformScriptResultEmitted =
|
||||
new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
internal static readonly TimeSpan PlatformScriptEndBlockGrace = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// Emits a <c>script_completed</c>/<c>script_failed</c> for every pending platform script
|
||||
/// that has a known AgentExecutor exit code but whose IME <c>PS-SCRIPT-RESULT</c> line has
|
||||
/// not arrived within <see cref="PlatformScriptResultGrace"/>. Without this, scripts that
|
||||
/// completed shortly before the agent terminates are silently dropped (the
|
||||
/// <c>_pendingPlatformScripts</c> buffer is neither persisted nor flushed on dispose), so a
|
||||
/// device that ran N platform scripts could surface only the long-running one that happened
|
||||
/// to get its IME result logged in time. Result is derived from the exit code (0 → Success,
|
||||
/// else Failed) and tagged <c>resultSource=agentexecutor_fallback</c> so the data is honest
|
||||
/// about its provenance.
|
||||
/// <para>
|
||||
/// Runs on the single-threaded polling loop (no locking needed, same as the handlers).
|
||||
/// <paramref name="force"/> bypasses the grace check for the final pass on shutdown.
|
||||
/// </para>
|
||||
/// Platform scripts already emitted (via the authoritative PS-SCRIPT-RESULT path or the
|
||||
/// exit-code fallback), keyed by policy id with the source timestamp of the emitted run
|
||||
/// (the result line, or the exit line for a fallback emit). Guards against double emission
|
||||
/// when both paths fire for the same script, and tells a late start line of the emitted
|
||||
/// run from the start of the next run.
|
||||
/// </summary>
|
||||
internal void FlushStalePlatformScriptResults(DateTime nowUtc, bool force = false)
|
||||
private readonly Dictionary<string, DateTime> _platformScriptResultEmitted =
|
||||
new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// End-of-pass emit for pending platform scripts, two cases:
|
||||
/// <list type="bullet">
|
||||
/// <item>A held IME result (<see cref="ScriptExecutionState.ResultHeldSinceUtc"/>) goes
|
||||
/// out once its executor end block has been read — the block arrives within one pass, so
|
||||
/// stdout/stderr are in by now — or after <see cref="PlatformScriptEndBlockGrace"/>.</item>
|
||||
/// <item>A script with a known AgentExecutor exit code but no IME <c>PS-SCRIPT-RESULT</c>
|
||||
/// line within <see cref="PlatformScriptResultGrace"/> is emitted from the exit code
|
||||
/// (0 → Success, else Failed), tagged <c>resultSource=agentexecutor_fallback</c> so the
|
||||
/// data is honest about its provenance. Without this, scripts that completed shortly
|
||||
/// before the agent terminates were silently dropped.</item>
|
||||
/// </list>
|
||||
/// Runs on the single-threaded polling loop (no locking needed, same as the handlers).
|
||||
/// <paramref name="force"/> bypasses both grace checks for the final pass on shutdown.
|
||||
/// </summary>
|
||||
internal void FlushPendingPlatformScriptResults(DateTime nowUtc, bool force = false)
|
||||
{
|
||||
if (_pendingPlatformScripts.Count == 0) return;
|
||||
|
||||
List<string> toRemove = null;
|
||||
foreach (var kv in _pendingPlatformScripts)
|
||||
var fallbackEmitted = false;
|
||||
foreach (var script in _pendingPlatformScripts.Values.ToList())
|
||||
{
|
||||
var script = kv.Value;
|
||||
|
||||
// Already emitted by the authoritative path — just drop the stale buffer entry.
|
||||
if (_platformScriptResultEmitted.Contains(script.PolicyId))
|
||||
if (_platformScriptResultEmitted.ContainsKey(script.PolicyId))
|
||||
{
|
||||
(toRemove ??= new List<string>()).Add(kv.Key);
|
||||
_pendingPlatformScripts.Remove(script.PolicyId);
|
||||
_stateDirty = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (script.Result != null)
|
||||
{
|
||||
if (script.ExitCode.HasValue)
|
||||
EmitPlatformScriptResult(script, "executor end block read after the result");
|
||||
else if (force || !script.ResultHeldSinceUtc.HasValue || nowUtc - script.ResultHeldSinceUtc.Value >= PlatformScriptEndBlockGrace)
|
||||
EmitPlatformScriptResult(script, $"no executor end block within {PlatformScriptEndBlockGrace.TotalSeconds:F0}s{(force ? ", shutdown flush" : string.Empty)}");
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -560,35 +684,20 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
script.Result = script.ExitCode.Value == 0 ? "Success" : "Failed";
|
||||
script.ResultSource = "agentexecutor_fallback";
|
||||
|
||||
_logger.Info(
|
||||
$"ImeLogTracker: platform script {script.PolicyId} result not seen within " +
|
||||
$"{PlatformScriptResultGrace.TotalSeconds:F0}s{(force ? " (shutdown flush)" : "")} — " +
|
||||
$"emitting from AgentExecutor exit code {script.ExitCode.Value} (fallback)");
|
||||
|
||||
EmitScriptEvent(script);
|
||||
_platformScriptResultEmitted.Add(script.PolicyId);
|
||||
(toRemove ??= new List<string>()).Add(kv.Key);
|
||||
EmitPlatformScriptResult(script,
|
||||
$"result not seen within {PlatformScriptResultGrace.TotalSeconds:F0}s{(force ? ", shutdown flush" : string.Empty)} — emitted from AgentExecutor exit code {script.ExitCode.Value} (fallback)");
|
||||
fallbackEmitted = true;
|
||||
}
|
||||
|
||||
if (toRemove != null)
|
||||
{
|
||||
// The flush can fire on a quiet polling cycle (grace expiry with no new log
|
||||
// lines), where nothing else marks state dirty — the emitted-markers must reach
|
||||
// the state file before a restart or the restarted tracker re-emits (H1).
|
||||
_stateDirty = true;
|
||||
foreach (var key in toRemove)
|
||||
{
|
||||
_pendingPlatformScripts.Remove(key);
|
||||
if (string.Equals(_lastPlatformScriptPolicyId, key, StringComparison.OrdinalIgnoreCase))
|
||||
_lastPlatformScriptPolicyId = null;
|
||||
}
|
||||
}
|
||||
// The fallback is an end signal like the others: the result line it stood in for
|
||||
// may sit overwritten behind the bookmark of the other file.
|
||||
if (fallbackEmitted) RequestOverwriteCheck();
|
||||
}
|
||||
|
||||
/// <summary>Test seam: inject a pending platform script as if AgentExecutor.log had reported
|
||||
/// its start + exit code, without an IME PS-SCRIPT-RESULT line.</summary>
|
||||
internal void SeedPendingPlatformScriptForTesting(string policyId, int? exitCode, DateTime? exitObservedAtUtc, string stdout = null, DateTime? startedAtUtc = null)
|
||||
internal void SeedPendingPlatformScriptForTesting(string policyId, int? exitCode, DateTime? exitObservedAtUtc, string stdout = null, DateTime? startedAtUtc = null,
|
||||
CmTraceLineProvenance startedAtProvenance = null, CmTraceLineProvenance exitProvenance = null)
|
||||
{
|
||||
// Mirrors a fresh execution start: a new run clears any prior emitted-marker (see
|
||||
// HandleScriptStarted) so re-runs of the same policy within one lifetime emit again.
|
||||
@@ -601,50 +710,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ExitObservedAtUtc = exitObservedAtUtc,
|
||||
Stdout = stdout,
|
||||
StartedAtUtc = startedAtUtc,
|
||||
StartedAtProvenance = startedAtProvenance,
|
||||
ExitProvenance = exitProvenance,
|
||||
};
|
||||
_lastPlatformScriptPolicyId = policyId;
|
||||
NextTestEntry();
|
||||
RecordInvocationMarker(policyId, isClose: false);
|
||||
}
|
||||
|
||||
/// <summary>Test seam: simulate the authoritative IME PS-SCRIPT-RESULT path for a platform
|
||||
/// script (same code as <see cref="HandleScriptCompleted"/> minus regex extraction).
|
||||
/// <paramref name="resultLineTimestampUtc"/> stands in for the CMTrace timestamp of the
|
||||
/// PS-SCRIPT-RESULT line (production reads it via <see cref="LastMatchedLogTimestamp"/>).</summary>
|
||||
internal void CompletePlatformScriptFromImeResultForTesting(string policyId, string result, DateTime? resultLineTimestampUtc = null)
|
||||
/// <summary>Test seam: the authoritative IME PS-SCRIPT-RESULT path for a platform script
|
||||
/// (the production handler minus regex extraction). <paramref name="resultLineTimestampUtc"/>
|
||||
/// stands in for the CMTrace timestamp of the PS-SCRIPT-RESULT line (production reads it
|
||||
/// via <see cref="LastMatchedLogTimestamp"/>, the fallback here).</summary>
|
||||
internal void CompletePlatformScriptFromImeResultForTesting(string policyId, string result, DateTime? resultLineTimestampUtc = null, CmTraceLineProvenance resultProvenance = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(policyId)) return;
|
||||
CompletePlatformScriptFromImeResult(policyId, result, resultLineTimestampUtc ?? LastMatchedLogTimestamp, "PS-SCRIPT-RESULT", resultProvenance ?? CaptureLastMatchedProvenance());
|
||||
}
|
||||
|
||||
if (_platformScriptResultEmitted.Contains(policyId))
|
||||
{
|
||||
_pendingPlatformScripts.Remove(policyId);
|
||||
if (string.Equals(_lastPlatformScriptPolicyId, policyId, StringComparison.OrdinalIgnoreCase))
|
||||
_lastPlatformScriptPolicyId = null;
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the AgentExecutor exit-code line of a pending platform script (the
|
||||
/// production handler minus regex extraction and positional ownership).</summary>
|
||||
internal void RecordPlatformScriptExitCodeForTesting(string policyId, int exitCode, DateTime observedAtUtc, CmTraceLineProvenance exitProvenance = null)
|
||||
{
|
||||
if (_pendingPlatformScripts.TryGetValue(policyId, out var script))
|
||||
{
|
||||
// Mirror of HandleScriptCompleted's stale-result guard: a result older than the
|
||||
// pending slot's start belongs to a previous run of the same policy.
|
||||
if (script.StartedAtUtc.HasValue
|
||||
&& resultLineTimestampUtc.HasValue
|
||||
&& resultLineTimestampUtc.Value < script.StartedAtUtc.Value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
script = new ScriptExecutionState { PolicyId = policyId, ScriptType = "platform" };
|
||||
}
|
||||
|
||||
script.Result = result;
|
||||
script.ResultSource = "ime_policy_result";
|
||||
EmitScriptEvent(script);
|
||||
_platformScriptResultEmitted.Add(policyId);
|
||||
_pendingPlatformScripts.Remove(policyId);
|
||||
if (string.Equals(_lastPlatformScriptPolicyId, policyId, StringComparison.OrdinalIgnoreCase))
|
||||
_lastPlatformScriptPolicyId = null;
|
||||
_stateDirty = true;
|
||||
ApplyExitCode(script, exitCode, observedAtUtc, exitProvenance);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -720,8 +808,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// HS-NEW-RESULT path whose end stamp includes IME's batched reporting latency.
|
||||
// Peek only: HS-NEW-RESULT still consumes + removes the entry for cycle timing.
|
||||
StartedAtUtc = _healthScriptStartTimes.TryGetValue(id, out var earlyStart)
|
||||
? earlyStart
|
||||
? earlyStart.Utc
|
||||
: (DateTime?)null,
|
||||
StartedAtProvenance = _healthScriptStartTimes.TryGetValue(id, out var earlyStartProvenance)
|
||||
? earlyStartProvenance.Provenance
|
||||
: null,
|
||||
// The HS-COMPLIANCE line is the end of this phase; emitted synchronously, so the
|
||||
// last matched line is it.
|
||||
ResultProvenance = CaptureLastMatchedProvenance(),
|
||||
DurationBasis = "script_runtime",
|
||||
};
|
||||
|
||||
@@ -736,6 +830,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
_pendingHealthScript = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test seam: a health-script start line for <paramref name="id"/> stamped
|
||||
/// <paramref name="startedAtUtc"/>, without driving the regex pipeline.
|
||||
/// </summary>
|
||||
internal void HandleHealthScriptStartForTest(string id, DateTime startedAtUtc)
|
||||
{
|
||||
LastMatchedLogTimestamp = startedAtUtc;
|
||||
var match = System.Text.RegularExpressions.Regex.Match(id ?? string.Empty, @"(?<id>.+)");
|
||||
HandleScriptStarted(match, new Dictionary<string, string> { ["scriptType"] = "remediation" });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test seam: simulates the full HS-SCRIPT-START → HS-RUN-CONTEXT / HS-EXITCODE /
|
||||
/// HS-STDOUT / HS-STDERR → HS-COMPLIANCE sequence by directly populating the
|
||||
@@ -779,10 +884,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// HS-SCRIPT-START line had been observed, so a subsequent
|
||||
/// <see cref="HandleHealthScriptResultJson"/> surfaces a run duration without driving the
|
||||
/// full regex pipeline.</summary>
|
||||
internal void SeedHealthScriptStartForTesting(string policyId, DateTime startedAtUtc)
|
||||
internal void SeedHealthScriptStartForTesting(string policyId, DateTime startedAtUtc, CmTraceLineProvenance provenance = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(policyId)) return;
|
||||
_healthScriptStartTimes[policyId] = startedAtUtc;
|
||||
_healthScriptStartTimes[policyId] = (startedAtUtc, provenance);
|
||||
}
|
||||
|
||||
private void HandleHealthScriptResult(Match match, Dictionary<string, string> parameters)
|
||||
@@ -794,6 +899,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
return;
|
||||
}
|
||||
HandleHealthScriptResultJson(json);
|
||||
// A remediation executor just ended too — its end block may sit behind the bookmark.
|
||||
RequestOverwriteCheck();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -837,10 +944,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// emitted phase events — the remediation analog of platform-script timing. Consumed +
|
||||
// removed so a later re-run of the same policy re-times from its own start. Null when
|
||||
// the start line was never seen in the agent's window (e.g. a replayed result).
|
||||
DateTime? cycleStartedAtUtc = _healthScriptStartTimes.TryGetValue(policyId, out var hsStart)
|
||||
? hsStart
|
||||
: (DateTime?)null;
|
||||
var hasCycleStart = _healthScriptStartTimes.TryGetValue(policyId, out var hsStart);
|
||||
DateTime? cycleStartedAtUtc = hasCycleStart ? hsStart.Utc : (DateTime?)null;
|
||||
var cycleStartProvenance = hasCycleStart ? hsStart.Provenance : null;
|
||||
_healthScriptStartTimes.Remove(policyId);
|
||||
// Every phase ends on this HS-NEW-RESULT line.
|
||||
var resultProvenance = CaptureLastMatchedProvenance();
|
||||
|
||||
// Common metadata — applied to every emitted phase event.
|
||||
var remediationStatus = TryGetInt(root, "RemediationStatus");
|
||||
@@ -880,7 +989,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
targetType: targetType,
|
||||
errorCode: errorCode,
|
||||
errorDetails: errorDetails,
|
||||
startedAtUtc: cycleStartedAtUtc);
|
||||
startedAtUtc: cycleStartedAtUtc,
|
||||
startedAtProvenance: cycleStartProvenance,
|
||||
resultProvenance: resultProvenance);
|
||||
// complianceResult mirrors the legacy HS-COMPLIANCE event semantics: True when the
|
||||
// pre-detection script reported compliant (exit 0), False otherwise.
|
||||
detection.ComplianceResult = firstDetectExit == 0 ? "True" : (firstDetectExit.HasValue ? "False" : null);
|
||||
@@ -904,7 +1015,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
targetType: targetType,
|
||||
errorCode: errorCode,
|
||||
errorDetails: errorDetails,
|
||||
startedAtUtc: cycleStartedAtUtc);
|
||||
startedAtUtc: cycleStartedAtUtc,
|
||||
startedAtProvenance: cycleStartProvenance,
|
||||
resultProvenance: resultProvenance);
|
||||
// No complianceResult on the remediation phase — there is nothing to be compliant about.
|
||||
EmitScriptEvent(remediation);
|
||||
}
|
||||
@@ -926,7 +1039,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
targetType: targetType,
|
||||
errorCode: errorCode,
|
||||
errorDetails: errorDetails,
|
||||
startedAtUtc: cycleStartedAtUtc);
|
||||
startedAtUtc: cycleStartedAtUtc,
|
||||
startedAtProvenance: cycleStartProvenance,
|
||||
resultProvenance: resultProvenance);
|
||||
postDetection.ComplianceResult = lastDetectExit == 0 ? "True" : (lastDetectExit.HasValue ? "False" : null);
|
||||
EmitScriptEvent(postDetection);
|
||||
}
|
||||
@@ -949,7 +1064,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
int? targetType,
|
||||
int? errorCode,
|
||||
string errorDetails,
|
||||
DateTime? startedAtUtc) =>
|
||||
DateTime? startedAtUtc,
|
||||
CmTraceLineProvenance startedAtProvenance,
|
||||
CmTraceLineProvenance resultProvenance) =>
|
||||
new ScriptExecutionState
|
||||
{
|
||||
PolicyId = policyId,
|
||||
@@ -966,6 +1083,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Cycle start (HS-SCRIPT-START). Every phase carries the same cycle start so the
|
||||
// adapter computes the total run duration; the Web surfaces it once at card level.
|
||||
StartedAtUtc = startedAtUtc,
|
||||
StartedAtProvenance = startedAtProvenance,
|
||||
ResultProvenance = resultProvenance,
|
||||
// End stamp is the HS-NEW-RESULT line — written only after IME's batched report
|
||||
// to the service, so this duration overstates the actual script execution time.
|
||||
DurationBasis = "cycle_including_reporting_latency"
|
||||
@@ -992,9 +1111,58 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
private void EmitScriptEvent(ScriptExecutionState script)
|
||||
{
|
||||
if (script == null || string.IsNullOrEmpty(script.PolicyId)) return;
|
||||
|
||||
// Health scripts recur for as long as the device is up; platform scripts run once.
|
||||
if (string.Equals(script.ScriptType, "remediation", StringComparison.OrdinalIgnoreCase)
|
||||
&& !_currentLineIsHistoricReplay)
|
||||
{
|
||||
var emit = _recurringScripts.OnResult(script, LastMatchedLogTimestamp ?? UtcNowProvider(), out var releasedStart);
|
||||
_stateDirty = true;
|
||||
if (!emit)
|
||||
{
|
||||
_logger.Debug($"ImeLogTracker: health script {script.PolicyId} {script.ScriptPart} repeats its last reported result — counted, not emitted");
|
||||
return;
|
||||
}
|
||||
if (releasedStart != null) RaiseScriptStarted(releasedStart);
|
||||
}
|
||||
|
||||
OnScriptCompleted?.Invoke(script);
|
||||
}
|
||||
|
||||
private void RaiseScriptStarted(ScriptStartedInfo info)
|
||||
{
|
||||
try { OnScriptStarted?.Invoke(info); }
|
||||
catch (Exception ex) { _logger.Warning($"ImeLogTracker: OnScriptStarted handler threw: {ex.Message}"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A held start whose run produced no result for <see cref="HeldScriptStartGrace"/> is
|
||||
/// emitted after all: the script did not finish. On shutdown the shorter
|
||||
/// <see cref="HeldScriptStartShutdownGrace"/> applies — a start read moments before the
|
||||
/// stop stays held for the next run of this session instead of reading as unfinished.
|
||||
/// </summary>
|
||||
internal void FlushRecurringScripts(DateTime nowUtc, bool shuttingDown)
|
||||
{
|
||||
var released = _recurringScripts.ReleaseStartsWithoutResult(
|
||||
nowUtc, shuttingDown ? HeldScriptStartShutdownGrace : HeldScriptStartGrace);
|
||||
foreach (var start in released) RaiseScriptStarted(start);
|
||||
|
||||
if (shuttingDown)
|
||||
{
|
||||
foreach (var summary in _recurringScripts.TakeSummaries())
|
||||
{
|
||||
try { OnScriptRecurrenceSummary?.Invoke(summary); }
|
||||
catch (Exception ex) { _logger.Warning($"ImeLogTracker: OnScriptRecurrenceSummary handler threw: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
|
||||
if (_recurringScripts.ConsumeDirty()) _stateDirty = true;
|
||||
}
|
||||
|
||||
// IME aborts a health script after roughly 30 minutes.
|
||||
internal static readonly TimeSpan HeldScriptStartGrace = TimeSpan.FromMinutes(30);
|
||||
internal static readonly TimeSpan HeldScriptStartShutdownGrace = TimeSpan.FromMinutes(5);
|
||||
|
||||
private static string TruncateOutput(string output)
|
||||
{
|
||||
if (string.IsNullOrEmpty(output) || output.Length <= MaxScriptOutputLength)
|
||||
|
||||
+275
-243
@@ -78,243 +78,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
try
|
||||
{
|
||||
var fileInfo = new FileInfo(filePath);
|
||||
if (!fileInfo.Exists) continue;
|
||||
|
||||
// Captured BEFORE MarkChecked below stamps this pass. Growth measured
|
||||
// against a previously observed state is what makes this pass's lines valid
|
||||
// "written now" anchors — for the per-file measurement AND per-line anchoring.
|
||||
var hadPreviousObservation = _positionTracker.HasSeen(filePath);
|
||||
var lastCheckedUtc = _positionTracker.GetLastCheckedUtc(filePath);
|
||||
var passNowUtc = UtcNowProvider();
|
||||
|
||||
var startPos = _positionTracker.GetSafePosition(filePath, fileInfo.Length);
|
||||
|
||||
// Every look counts, including "no new data" and an empty first sight: the
|
||||
// NEXT pass's freshness window is measured from here. Restored bookmarks
|
||||
// deliberately carry no LastCheckedUtc — the first pass after a restart reads
|
||||
// downtime backlog and must never count as fresh.
|
||||
_positionTracker.MarkChecked(filePath, passNowUtc);
|
||||
|
||||
if (startPos >= fileInfo.Length)
|
||||
{
|
||||
// M2: guard the interpolated string so it isn't built every 100 ms tick
|
||||
// (per file) when Trace is off — which is the production default (Info).
|
||||
if (_logger.LogLevel >= AgentLogLevel.Trace)
|
||||
_logger.Trace($"ImeLogTracker: {Path.GetFileName(filePath)} — no new data (pos={startPos}, size={fileInfo.Length})");
|
||||
continue;
|
||||
}
|
||||
if (_logger.LogLevel >= AgentLogLevel.Trace)
|
||||
_logger.Trace($"ImeLogTracker: reading {Path.GetFileName(filePath)} from pos {startPos} (size={fileInfo.Length}, delta={fileInfo.Length - startPos})");
|
||||
|
||||
_currentSourceFileName = Path.GetFileName(filePath);
|
||||
_currentPassLinesAreFresh = hadPreviousObservation
|
||||
&& lastCheckedUtc > DateTime.MinValue
|
||||
&& (passNowUtc - lastCheckedUtc) <= FreshLineMaxAge;
|
||||
|
||||
// Newest bias-less line of this pass — the calibration anchor. Bias-carrying
|
||||
// lines are skipped: they already state the writer's offset, so they need no
|
||||
// measurement and must not overwrite one.
|
||||
CmTraceLogEntry calibrationAnchor = null;
|
||||
|
||||
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
stream.Seek(startPos, SeekOrigin.Begin);
|
||||
|
||||
var reader = new BoundedLineReader(stream, MaxEntryBytes);
|
||||
var stats = new PassStats();
|
||||
|
||||
// Buffer for multiline CMTrace entries (e.g. AgentExecutor.log
|
||||
// "write output done. output = ..." spans many lines)
|
||||
StringBuilder multiLineBuffer = null;
|
||||
int multiLineCount = 0;
|
||||
// Set after a capped entry is dropped: its remaining physical lines
|
||||
// are skipped instead of being matched as raw text, until the entry
|
||||
// closes or a new entry begins (so no real entry is lost).
|
||||
bool skippingDroppedEntry = false;
|
||||
// File offset where the entry currently being assembled/processed
|
||||
// begins — the bookmark to fall back to when that entry is NOT
|
||||
// consumed (cancellation, or a held-back unterminated tail).
|
||||
long entryStart = startPos;
|
||||
// Where the next pass resumes. EOF unless an entry is left unconsumed.
|
||||
long resumePos;
|
||||
|
||||
while (true)
|
||||
{
|
||||
// CancellationToken.None: cancellation is honoured by the explicit
|
||||
// check below (exact bookmark) rather than by an exception out of
|
||||
// the read, which the poll loop would log as an error.
|
||||
var line = await reader.ReadLineAsync(CancellationToken.None);
|
||||
if (line == null)
|
||||
{
|
||||
// EOF. An in-flight multiline entry here is an entry the writer
|
||||
// has not finished — hold it back (see HoldBackTail) instead of
|
||||
// dropping it and raw-matching its remaining lines next pass.
|
||||
if (multiLineBuffer != null && HoldBackTail(filePath, entryStart, fileInfo.Length, passNowUtc))
|
||||
{
|
||||
_heldTailCount++;
|
||||
resumePos = entryStart;
|
||||
break;
|
||||
}
|
||||
resumePos = reader.Position;
|
||||
break;
|
||||
}
|
||||
|
||||
if (token.IsCancellationRequested)
|
||||
{
|
||||
// Exact bookmark: nothing of this line (or of the multiline
|
||||
// entry it belongs to) has been handled.
|
||||
resumePos = multiLineBuffer != null ? entryStart : reader.LastLineStart;
|
||||
break;
|
||||
}
|
||||
|
||||
if (multiLineBuffer == null)
|
||||
entryStart = reader.LastLineStart;
|
||||
|
||||
_linesRead++;
|
||||
|
||||
// A physical line over the cap is never matched: its captures would be
|
||||
// cut and the regexes would run over attacker-sized input. The capped
|
||||
// prefix is enough to tell whether it opened an entry whose remaining
|
||||
// lines must be skipped rather than raw-matched.
|
||||
if (reader.LastLineTruncated)
|
||||
{
|
||||
stats.OversizedLines++;
|
||||
_oversizedLines++;
|
||||
if (multiLineBuffer != null)
|
||||
{
|
||||
multiLineBuffer = null;
|
||||
multiLineCount = 0;
|
||||
skippingDroppedEntry = true;
|
||||
}
|
||||
else if (line.StartsWith("<![LOG[") && !line.Contains("]LOG]!>"))
|
||||
{
|
||||
skippingDroppedEntry = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!reader.LastLineTerminated && multiLineBuffer == null
|
||||
&& HoldBackTail(filePath, reader.LastLineStart, fileInfo.Length, passNowUtc))
|
||||
{
|
||||
// Unterminated single line at EOF: the writer is mid-line.
|
||||
_heldTailCount++;
|
||||
resumePos = reader.LastLineStart;
|
||||
break;
|
||||
}
|
||||
|
||||
if (skippingDroppedEntry)
|
||||
{
|
||||
// A line opening a new entry ends the skip and is processed
|
||||
// itself — checked BEFORE the close-tag test, because a complete
|
||||
// single-line entry contains both and must not be consumed as
|
||||
// the dropped entry's close.
|
||||
if (line.StartsWith("<![LOG["))
|
||||
skippingDroppedEntry = false;
|
||||
else
|
||||
{
|
||||
if (line.Contains("]LOG]!>")) skippingDroppedEntry = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Multiline CMTrace buffering ---
|
||||
// CMTrace entries: <![LOG[message]LOG]!><time=...>
|
||||
// When message contains newlines, the entry spans multiple lines.
|
||||
// We buffer until we find the closing ]LOG]!> tag.
|
||||
if (multiLineBuffer != null)
|
||||
{
|
||||
// Continuing a multiline entry
|
||||
multiLineBuffer.Append('\n').Append(line);
|
||||
multiLineCount++;
|
||||
|
||||
if (line.Contains("]LOG]!>"))
|
||||
{
|
||||
// Entry complete — use the assembled line
|
||||
line = multiLineBuffer.ToString();
|
||||
multiLineBuffer = null;
|
||||
multiLineCount = 0;
|
||||
}
|
||||
else if (multiLineCount >= MaxMultiLineBufferLines || multiLineBuffer.Length >= MaxEntryBytes)
|
||||
{
|
||||
// Safety limit — discard to bound memory and parser work. Warning
|
||||
// (not Debug) so a capped entry is visible in the client log at the
|
||||
// default level: a real IME entry this large would be news.
|
||||
_logger.Warning($"ImeLogTracker: discarding multiline CMTrace buffer in {Path.GetFileName(filePath)} after {multiLineCount} lines / {multiLineBuffer.Length} chars (cap {MaxMultiLineBufferLines} lines / {MaxEntryBytes} chars) — entry dropped");
|
||||
multiLineBuffer = null;
|
||||
multiLineCount = 0;
|
||||
skippingDroppedEntry = true;
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Still accumulating — read next line
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (line.StartsWith("<![LOG[") && !line.Contains("]LOG]!>"))
|
||||
{
|
||||
// Start of a multiline CMTrace entry
|
||||
multiLineBuffer = new StringBuilder(line);
|
||||
multiLineCount = 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Normal processing (single-line or completed multiline) ---
|
||||
CmTraceLogEntry entry;
|
||||
string messageToMatch;
|
||||
_currentEntryOffset = entryStart;
|
||||
if (CmTraceLogParser.TryParseLine(line, out entry))
|
||||
{
|
||||
messageToMatch = entry.Message;
|
||||
if (entry.HasTimestamp && !entry.BiasMinutes.HasValue)
|
||||
calibrationAnchor = entry;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Non-CMTrace line - match raw
|
||||
messageToMatch = line;
|
||||
entry = null;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(messageToMatch)) continue;
|
||||
|
||||
// Simulation mode delay
|
||||
if (SimulationMode && entry != null)
|
||||
{
|
||||
await ApplySimulationDelay(ResolveEntryUtc(entry), token);
|
||||
}
|
||||
|
||||
MatchLine(filePath, line, messageToMatch, entry, stats);
|
||||
}
|
||||
|
||||
ClearHeldTailIfConsumed(filePath, resumePos);
|
||||
_positionTracker.SetPosition(filePath, resumePos);
|
||||
_stateDirty = true;
|
||||
backlogBytes += Math.Max(0, fileInfo.Length - resumePos);
|
||||
|
||||
// One line per pass and file, never per hostile line: the counters are
|
||||
// the operator's only trace that matching was skipped or cut short.
|
||||
if (stats.RegexTimeouts > 0 || stats.BudgetBreaks > 0 || stats.OversizedLines > 0)
|
||||
{
|
||||
_logger.Warning(
|
||||
$"ImeLogTracker: {Path.GetFileName(filePath)} pass skipped work — " +
|
||||
$"oversizedLines={stats.OversizedLines} (cap {MaxEntryBytes} bytes), " +
|
||||
$"regexTimeouts={stats.RegexTimeouts}, lineBudgetBreaks={stats.BudgetBreaks}" +
|
||||
(stats.FirstSkippedPatternId != null ? $", firstSkippedPattern={stats.FirstSkippedPatternId}" : string.Empty));
|
||||
RaiseTrackerDegradedOnce(Path.GetFileName(filePath), stats.FirstSkippedPatternId);
|
||||
}
|
||||
|
||||
// Calibrate AFTER the pass: this pass's lines were resolved with the
|
||||
// offset established previously, at most one poll (100 ms) old. Buffering
|
||||
// the pass to calibrate first is not an option — the first pass of
|
||||
// AppWorkload.log can be hundreds of MB. The cost is a warm-up of one
|
||||
// growing pass, during which lines fall back to the reader zone and are
|
||||
// flagged as such.
|
||||
if (hadPreviousObservation && calibrationAnchor != null)
|
||||
CalibrateFrom(_currentSourceFileName, Path.GetFileName(filePath), calibrationAnchor);
|
||||
_currentEntryOffset = -1;
|
||||
}
|
||||
backlogBytes += await ProcessFileAsync(filePath, token);
|
||||
}
|
||||
catch (FileNotFoundException) { }
|
||||
catch (IOException ex)
|
||||
@@ -330,6 +94,246 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One pass over one file: the bytes behind the bookmark, on a multi-writer file preceded
|
||||
/// by the overwrite check that may move the bookmark back first (see
|
||||
/// <c>ImeLogTracker.Overwrite.cs</c>). Returns the file's remaining backlog in bytes.
|
||||
/// </summary>
|
||||
private async Task<long> ProcessFileAsync(string filePath, CancellationToken token)
|
||||
{
|
||||
var fileInfo = new FileInfo(filePath);
|
||||
if (!fileInfo.Exists) return 0;
|
||||
|
||||
// Captured BEFORE MarkChecked below stamps this pass. Growth measured
|
||||
// against a previously observed state is what makes this pass's lines valid
|
||||
// "written now" anchors — for the per-file measurement AND per-line anchoring.
|
||||
var hadPreviousObservation = _positionTracker.HasSeen(filePath);
|
||||
var lastCheckedUtc = _positionTracker.GetLastCheckedUtc(filePath);
|
||||
var passNowUtc = UtcNowProvider();
|
||||
|
||||
var startPos = _positionTracker.GetSafePosition(filePath, fileInfo.Length);
|
||||
|
||||
// Every look counts, including "no new data" and an empty first sight: the
|
||||
// NEXT pass's freshness window is measured from here. Restored bookmarks
|
||||
// deliberately carry no LastCheckedUtc — the first pass after a restart reads
|
||||
// downtime backlog and must never count as fresh.
|
||||
_positionTracker.MarkChecked(filePath, passNowUtc);
|
||||
|
||||
var fileName = Path.GetFileName(filePath);
|
||||
var ledger = IsMultiWriterLogFile(fileName) ? GetLedger(fileName) : null;
|
||||
|
||||
// Set by a rewind: entries that still read unchanged behind the old bookmark are
|
||||
// skipped, and nothing below the old bookmark is fresh or a calibration anchor.
|
||||
HashSet<LedgerEntry> rewoundEntries = null;
|
||||
long oldBookmark = -1;
|
||||
|
||||
if (ledger != null)
|
||||
{
|
||||
var rewindTo = await PrepareLedgerAsync(filePath, fileName, ledger, startPos, passNowUtc, token);
|
||||
if (rewindTo >= 0)
|
||||
{
|
||||
rewoundEntries = ApplyRewind(filePath, fileName, ledger, rewindTo, startPos);
|
||||
oldBookmark = startPos;
|
||||
startPos = rewindTo;
|
||||
}
|
||||
}
|
||||
|
||||
if (startPos >= fileInfo.Length)
|
||||
{
|
||||
// M2: guard the interpolated string so it isn't built every 100 ms tick
|
||||
// (per file) when Trace is off — which is the production default (Info).
|
||||
if (_logger.LogLevel >= AgentLogLevel.Trace)
|
||||
_logger.Trace($"ImeLogTracker: {fileName} — no new data (pos={startPos}, size={fileInfo.Length})");
|
||||
return 0;
|
||||
}
|
||||
if (_logger.LogLevel >= AgentLogLevel.Trace)
|
||||
_logger.Trace($"ImeLogTracker: reading {fileName} from pos {startPos} (size={fileInfo.Length}, delta={fileInfo.Length - startPos})");
|
||||
|
||||
_currentSourceFileName = fileName;
|
||||
var passLinesAreFresh = hadPreviousObservation
|
||||
&& lastCheckedUtc > DateTime.MinValue
|
||||
&& (passNowUtc - lastCheckedUtc) <= FreshLineMaxAge;
|
||||
_currentPassLinesAreFresh = passLinesAreFresh;
|
||||
|
||||
// Newest bias-less line of this pass — the calibration anchor. Bias-carrying
|
||||
// lines are skipped: they already state the writer's offset, so they need no
|
||||
// measurement and must not overwrite one.
|
||||
CmTraceLogEntry calibrationAnchor = null;
|
||||
|
||||
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
// Guard zone: the file grew and is open anyway — re-check the entries just behind
|
||||
// the bookmark, where a stale writer's block lands when it is short.
|
||||
if (ledger != null && rewoundEntries == null && ledger.Entries.Count > 0)
|
||||
{
|
||||
var guardFrom = ledger.OffsetOfEntryAtOrAfter(startPos - OverwriteGuardBytes);
|
||||
if (guardFrom >= 0 && guardFrom < startPos)
|
||||
{
|
||||
var divergence = await FindOverwriteAsync(stream, ledger, guardFrom, startPos, token);
|
||||
_verifiedBytes += startPos - guardFrom;
|
||||
if (divergence >= 0)
|
||||
{
|
||||
// The guard saw only the tail of the ledger; the block may start earlier.
|
||||
var earliest = await FindOverwriteAsync(stream, ledger, ledger.StartOffset, startPos, token);
|
||||
_verifiedBytes += startPos - ledger.StartOffset;
|
||||
_verifyPasses++;
|
||||
if (earliest >= 0) divergence = earliest;
|
||||
rewoundEntries = ApplyRewind(filePath, fileName, ledger, divergence, startPos);
|
||||
oldBookmark = startPos;
|
||||
startPos = divergence;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stream.Seek(startPos, SeekOrigin.Begin);
|
||||
|
||||
var reader = new BoundedLineReader(stream, MaxEntryBytes, hashLines: ledger != null);
|
||||
var assembler = new CmTraceEntryAssembler(MaxMultiLineBufferLines, MaxEntryBytes);
|
||||
var stats = new PassStats();
|
||||
var firstEntry = true;
|
||||
// Where the next pass resumes. EOF unless an entry is left unconsumed.
|
||||
long resumePos;
|
||||
|
||||
while (true)
|
||||
{
|
||||
// CancellationToken.None: cancellation is honoured by the explicit
|
||||
// check below (exact bookmark) rather than by an exception out of
|
||||
// the read, which the poll loop would log as an error.
|
||||
var line = await reader.ReadLineAsync(CancellationToken.None);
|
||||
if (line == null)
|
||||
{
|
||||
// EOF. An in-flight multiline entry here is an entry the writer
|
||||
// has not finished — hold it back (see HoldBackTail) instead of
|
||||
// dropping it and raw-matching its remaining lines next pass.
|
||||
if (assembler.HasOpenEntry && HoldBackTail(filePath, assembler.OpenEntryStart, fileInfo.Length, passNowUtc))
|
||||
{
|
||||
_heldTailCount++;
|
||||
resumePos = assembler.OpenEntryStart;
|
||||
break;
|
||||
}
|
||||
resumePos = reader.Position;
|
||||
break;
|
||||
}
|
||||
|
||||
if (token.IsCancellationRequested)
|
||||
{
|
||||
// Exact bookmark: nothing of this line (or of the multiline
|
||||
// entry it belongs to) has been handled.
|
||||
resumePos = assembler.HasOpenEntry ? assembler.OpenEntryStart : reader.LastLineStart;
|
||||
break;
|
||||
}
|
||||
|
||||
_linesRead++;
|
||||
|
||||
if (!reader.LastLineTruncated && !reader.LastLineTerminated && !assembler.HasOpenEntry
|
||||
&& HoldBackTail(filePath, reader.LastLineStart, fileInfo.Length, passNowUtc))
|
||||
{
|
||||
// Unterminated single line at EOF: the writer is mid-line.
|
||||
_heldTailCount++;
|
||||
resumePos = reader.LastLineStart;
|
||||
break;
|
||||
}
|
||||
|
||||
AssembledEntry entry;
|
||||
var outcome = assembler.Feed(line, reader.LastLineStart, reader.Position, reader.LastLineTruncated, reader.LastLineHash, out entry);
|
||||
if (outcome == CmTraceEntryAssembler.Outcome.OversizedDropped)
|
||||
{
|
||||
// A physical line over the cap is never matched: its captures would be
|
||||
// cut and the regexes would run over attacker-sized input.
|
||||
stats.OversizedLines++;
|
||||
_oversizedLines++;
|
||||
continue;
|
||||
}
|
||||
if (outcome == CmTraceEntryAssembler.Outcome.CapDropped)
|
||||
{
|
||||
// Warning (not Debug) so a capped entry is visible in the client log at the
|
||||
// default level: a real IME entry this large would be news.
|
||||
_logger.Warning($"ImeLogTracker: discarding multiline CMTrace buffer in {fileName} after {assembler.DroppedLines} lines / {assembler.DroppedChars} chars (cap {MaxMultiLineBufferLines} lines / {MaxEntryBytes} chars) — entry dropped");
|
||||
continue;
|
||||
}
|
||||
if (outcome != CmTraceEntryAssembler.Outcome.Entry) continue;
|
||||
|
||||
if (firstEntry)
|
||||
{
|
||||
firstEntry = false;
|
||||
// A fragment right at the bookmark of a multi-writer file (the previous
|
||||
// entry ended exactly here, this one does not open an entry) is the tail of
|
||||
// a block a stale writer laid over already-read bytes: verify before reading on.
|
||||
if (ledger != null && rewoundEntries == null && entry.Offset == ledger.EndOffset
|
||||
&& ledger.LastFragmentOffset != entry.Offset && !entry.Text.StartsWith("<![LOG["))
|
||||
{
|
||||
ledger.VerifyRequested = true;
|
||||
ledger.LastFragmentOffset = entry.Offset;
|
||||
resumePos = entry.Offset;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ledger != null) ledger.Record(entry);
|
||||
if (rewoundEntries != null && rewoundEntries.Contains(new LedgerEntry { Offset = entry.Offset, Hash = entry.Hash }))
|
||||
continue; // unchanged behind the old bookmark — processed before the rewind
|
||||
|
||||
_currentPassLinesAreFresh = passLinesAreFresh && entry.Offset >= oldBookmark;
|
||||
|
||||
// --- Normal processing (single-line or completed multiline) ---
|
||||
CmTraceLogEntry parsed;
|
||||
string messageToMatch;
|
||||
_currentEntryOffset = entry.Offset;
|
||||
if (CmTraceLogParser.TryParseLine(entry.Text, out parsed))
|
||||
{
|
||||
messageToMatch = parsed.Message;
|
||||
if (parsed.HasTimestamp && !parsed.BiasMinutes.HasValue && entry.Offset >= oldBookmark)
|
||||
calibrationAnchor = parsed;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Non-CMTrace line - match raw
|
||||
messageToMatch = entry.Text;
|
||||
parsed = null;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(messageToMatch)) continue;
|
||||
|
||||
// Simulation mode delay
|
||||
if (SimulationMode && parsed != null)
|
||||
{
|
||||
await ApplySimulationDelay(ResolveEntryUtc(parsed), token);
|
||||
}
|
||||
|
||||
MatchLine(filePath, entry.Text, messageToMatch, parsed, stats);
|
||||
}
|
||||
|
||||
ClearHeldTailIfConsumed(filePath, resumePos);
|
||||
_positionTracker.SetPosition(filePath, resumePos);
|
||||
_stateDirty = true;
|
||||
if (ledger != null) ledger.TrimBelow(RetentionFloor(fileName, resumePos));
|
||||
|
||||
// One line per pass and file, never per hostile line: the counters are
|
||||
// the operator's only trace that matching was skipped or cut short.
|
||||
if (stats.RegexTimeouts > 0 || stats.BudgetBreaks > 0 || stats.OversizedLines > 0)
|
||||
{
|
||||
_logger.Warning(
|
||||
$"ImeLogTracker: {fileName} pass skipped work — " +
|
||||
$"oversizedLines={stats.OversizedLines} (cap {MaxEntryBytes} bytes), " +
|
||||
$"regexTimeouts={stats.RegexTimeouts}, lineBudgetBreaks={stats.BudgetBreaks}" +
|
||||
(stats.FirstSkippedPatternId != null ? $", firstSkippedPattern={stats.FirstSkippedPatternId}" : string.Empty));
|
||||
RaiseTrackerDegradedOnce(fileName, stats.FirstSkippedPatternId);
|
||||
}
|
||||
|
||||
// Calibrate AFTER the pass: this pass's lines were resolved with the
|
||||
// offset established previously, at most one poll (100 ms) old. Buffering
|
||||
// the pass to calibrate first is not an option — the first pass of
|
||||
// AppWorkload.log can be hundreds of MB. The cost is a warm-up of one
|
||||
// growing pass, during which lines fall back to the reader zone and are
|
||||
// flagged as such.
|
||||
if (hadPreviousObservation && calibrationAnchor != null)
|
||||
CalibrateFrom(_currentSourceFileName, fileName, calibrationAnchor);
|
||||
_currentEntryOffset = -1;
|
||||
|
||||
return Math.Max(0, fileInfo.Length - resumePos);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PassStats
|
||||
{
|
||||
public int RegexTimeouts;
|
||||
@@ -501,6 +505,21 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
"imetokenfailure",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Snapshot of the last matched line's provenance, for a consumer that acts later than
|
||||
/// the match (a held platform-script result, a run duration across two lines) and must
|
||||
/// describe THAT line rather than whichever line is matched by then.
|
||||
/// </summary>
|
||||
internal CmTraceLineProvenance CaptureLastMatchedProvenance() => new CmTraceLineProvenance
|
||||
{
|
||||
SourceLocalTs = LastMatchedSourceLocalTimestamp,
|
||||
Origin = LastMatchedSourceOffsetOrigin,
|
||||
OffsetMinutes = LastMatchedSourceOffsetMinutes,
|
||||
EraAnchorKind = LastMatchedEraAnchorKind,
|
||||
MeasuredWriterOffsetMinutes = LastMatchedMeasuredWriterOffsetMinutes,
|
||||
SourceFileName = _currentSourceFileName,
|
||||
};
|
||||
|
||||
private void HandlePatternMatch(CompiledPattern pattern, Match match, string message, CmTraceLogEntry entry)
|
||||
{
|
||||
LastMatchedPatternId = pattern.PatternId;
|
||||
@@ -547,6 +566,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// replays historic logs on purpose and bypasses the guard.
|
||||
var isStaleReplayLine = !SimulationMode && entry != null
|
||||
&& (UtcNowProvider() - NormalizeUtc(ResolveEntryUtc(entry))) > HistoricReplayThreshold;
|
||||
_currentLineIsHistoricReplay = isStaleReplayLine;
|
||||
if (isStaleReplayLine && AppMutatingActions.Contains(pattern.Action?.ToLower() ?? string.Empty))
|
||||
{
|
||||
_logger.Debug($"ImeLogTracker: skipped app action '{pattern.Action}' for historic line ({ResolveEntryUtc(entry):o})");
|
||||
@@ -828,10 +848,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
break;
|
||||
|
||||
case "resetplatformscriptcontext":
|
||||
// Session 6b4993e5 fix: a fresh AgentExecutor invocation banner
|
||||
// ("ExecutorLog AgentExecutor gets invoked") ends the previous
|
||||
// invocation's line-capture context. See HandleAgentExecutorInvocationBoundary.
|
||||
HandleAgentExecutorInvocationBoundary();
|
||||
// "ExecutorLog AgentExecutor gets invoked": a new process — the executor
|
||||
// lines that follow belong to its own argument line, never to the
|
||||
// previous invocation (session 6b4993e5).
|
||||
HandleAgentExecutorInvocation();
|
||||
break;
|
||||
|
||||
case "agentinvocationargument":
|
||||
HandleAgentInvocationArgument(match.Groups["kind"]?.Value);
|
||||
break;
|
||||
|
||||
case "agentexecutorcompleted":
|
||||
HandleAgentExecutorCompleted();
|
||||
break;
|
||||
|
||||
case "healthscriptresult":
|
||||
@@ -859,11 +887,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// <c>_activePatterns</c> → <see cref="HandlePatternMatch"/>). Lets unit tests drive the
|
||||
/// script / app handlers deterministically without writing CMTrace files or spinning the
|
||||
/// poller. <paramref name="sourceTimestampUtc"/> populates the entry timestamp some
|
||||
/// handlers read via <see cref="LastMatchedLogTimestamp"/>.
|
||||
/// handlers read via <see cref="LastMatchedLogTimestamp"/>. <paramref name="sourceFileName"/>
|
||||
/// names the log the line comes from — positional ownership is per file — and stays in
|
||||
/// effect for later calls; omitted, the line lands in the test file.
|
||||
/// </summary>
|
||||
internal void ProcessLogMessageForTest(string message, DateTime? sourceTimestampUtc = null)
|
||||
internal void ProcessLogMessageForTest(string message, DateTime? sourceTimestampUtc = null, string sourceFileName = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(message)) return;
|
||||
if (sourceFileName != null) _currentSourceFileName = sourceFileName;
|
||||
NextTestEntry();
|
||||
// The test seam hands in an already-resolved UTC instant, so it takes the same route a
|
||||
// writer-declared bias does: TimestampUtc set, no zone left to guess.
|
||||
var entry = sourceTimestampUtc.HasValue
|
||||
|
||||
+490
@@ -0,0 +1,490 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Partial: overwrite-aware tailing of the two IME logs that several processes append to.
|
||||
/// <para>
|
||||
/// IME's trace listener opens each log once per process with FileMode.Append and
|
||||
/// FileShare.ReadWrite and writes at its own stream position afterwards. AgentExecutor.exe
|
||||
/// (two processes per user-context script, one per detection or remediation script) has such
|
||||
/// a listener on AgentExecutor.log AND on IntuneManagementExtension.log. Whenever one process
|
||||
/// resumes writing after another one appended, it overwrites those bytes: the final file
|
||||
/// holds the last writer, while a tailer that trusts its bookmark read the first version and
|
||||
/// never sees the second (session 46749560: 6 of 16 script results, 4 of 16 exit blocks).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// So the bytes behind the bookmark are not immutable. The tracker keeps a fingerprint ledger
|
||||
/// of every entry it read from these files, re-verifies it while script invocations are in
|
||||
/// flight or right after a signal that a stale writer just wrote, and on the first changed
|
||||
/// entry rewinds the bookmark — processing only entries it has not processed before.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public partial class ImeLogTracker
|
||||
{
|
||||
/// <summary>Live logs with more than one writing process; archived rotations are closed files.</summary>
|
||||
internal static readonly string[] MultiWriterLogFiles = { "AgentExecutor.log", "IntuneManagementExtension.log" };
|
||||
|
||||
/// <summary>Ledger depth behind the bookmark while no script is in flight.</summary>
|
||||
internal const int LedgerRetentionBytes = 1024 * 1024;
|
||||
|
||||
/// <summary>Hard cap on the ledger depth, whatever is in flight.</summary>
|
||||
internal const int LedgerMaxBytes = 4 * 1024 * 1024;
|
||||
|
||||
/// <summary>Entries this close to the bookmark are re-checked on every pass that found growth (the file is open anyway).</summary>
|
||||
internal const int OverwriteGuardBytes = 4 * 1024;
|
||||
|
||||
/// <summary>After a restart the ledger is seeded from this many bytes before the persisted bookmark.</summary>
|
||||
internal const int RestartSeedBytes = 64 * 1024;
|
||||
|
||||
/// <summary>Verification work per second while in contention — a deep ledger is checked less often, never skipped.</summary>
|
||||
internal const long VerifyBudgetBytesPerSecond = 256 * 1024;
|
||||
|
||||
internal static readonly TimeSpan VerifyMinInterval = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>How long an observed invocation keeps the files in contention on its own (detection executors have no pending slot).</summary>
|
||||
internal static readonly TimeSpan InvocationContentionWindow = TimeSpan.FromSeconds(120);
|
||||
|
||||
/// <summary>A pending script older than this no longer holds the files in contention.</summary>
|
||||
internal static readonly TimeSpan MaxPendingScriptContention = TimeSpan.FromHours(2);
|
||||
|
||||
private const int MaxInvocationMarkersPerFile = 512;
|
||||
private const string TestSourceFileName = "TEST.log";
|
||||
private const string LogOpenTag = "<![LOG[";
|
||||
|
||||
/// <summary>One processed entry: where it starts, how far it reaches, what its bytes hashed to.</summary>
|
||||
internal struct LedgerEntry : IEquatable<LedgerEntry>
|
||||
{
|
||||
public long Offset;
|
||||
public int Length;
|
||||
public ulong Hash;
|
||||
|
||||
// Identity is (offset, hash): a tail first read unterminated and later completed
|
||||
// keeps its hash but grows by its terminator.
|
||||
public bool Equals(LedgerEntry other) => Offset == other.Offset && Hash == other.Hash;
|
||||
public override bool Equals(object obj) => obj is LedgerEntry other && Equals(other);
|
||||
public override int GetHashCode() => unchecked(((int)Offset * 397) ^ (int)Hash ^ (int)(Hash >> 32));
|
||||
}
|
||||
|
||||
internal sealed class FileLedger
|
||||
{
|
||||
public readonly List<LedgerEntry> Entries = new List<LedgerEntry>();
|
||||
public bool VerifyRequested;
|
||||
public DateTime NextCadenceVerifyUtc = DateTime.MinValue;
|
||||
public long LastFragmentOffset = -1;
|
||||
public bool Seeded;
|
||||
public bool RewindLogged;
|
||||
|
||||
public long StartOffset => Entries.Count > 0 ? Entries[0].Offset : -1;
|
||||
public long EndOffset => Entries.Count > 0 ? Entries[Entries.Count - 1].Offset + Entries[Entries.Count - 1].Length : -1;
|
||||
|
||||
public int IndexOfFirstAtOrAfter(long offset)
|
||||
{
|
||||
int lo = 0, hi = Entries.Count;
|
||||
while (lo < hi)
|
||||
{
|
||||
var mid = (lo + hi) >> 1;
|
||||
if (Entries[mid].Offset < offset) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/// <summary>Entry offset at or after <paramref name="offset"/>, or -1.</summary>
|
||||
public long OffsetOfEntryAtOrAfter(long offset)
|
||||
{
|
||||
var idx = IndexOfFirstAtOrAfter(offset);
|
||||
return idx < Entries.Count ? Entries[idx].Offset : -1;
|
||||
}
|
||||
|
||||
public void Record(AssembledEntry e)
|
||||
{
|
||||
var idx = IndexOfFirstAtOrAfter(e.Offset);
|
||||
if (idx < Entries.Count) Entries.RemoveRange(idx, Entries.Count - idx);
|
||||
Entries.Add(new LedgerEntry { Offset = e.Offset, Length = e.Length, Hash = e.Hash });
|
||||
}
|
||||
|
||||
/// <summary>Drops everything from <paramref name="offset"/> on and returns it — the entries a rewind must not process twice.</summary>
|
||||
public HashSet<LedgerEntry> TruncateFrom(long offset)
|
||||
{
|
||||
var idx = IndexOfFirstAtOrAfter(offset);
|
||||
var removed = new HashSet<LedgerEntry>();
|
||||
for (var i = idx; i < Entries.Count; i++) removed.Add(Entries[i]);
|
||||
if (idx < Entries.Count) Entries.RemoveRange(idx, Entries.Count - idx);
|
||||
return removed;
|
||||
}
|
||||
|
||||
public void TrimBelow(long floor)
|
||||
{
|
||||
var idx = IndexOfFirstAtOrAfter(floor);
|
||||
if (idx > 0) Entries.RemoveRange(0, idx);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
Entries.Clear();
|
||||
LastFragmentOffset = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Keyed by file name (unique within the log folder). Poll thread only.
|
||||
private readonly Dictionary<string, FileLedger> _ledgers = new Dictionary<string, FileLedger>(StringComparer.OrdinalIgnoreCase);
|
||||
private DateTime _contentionUntilUtc = DateTime.MinValue;
|
||||
|
||||
// Cumulative, restart-safe like the other health counters.
|
||||
private long _overwriteRewinds;
|
||||
private long _overwriteBytesReprocessed;
|
||||
private long _verifyPasses;
|
||||
private long _verifiedBytes;
|
||||
|
||||
internal static bool IsMultiWriterLogFile(string fileName)
|
||||
{
|
||||
foreach (var f in MultiWriterLogFiles)
|
||||
if (string.Equals(f, fileName, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private FileLedger GetLedger(string fileName)
|
||||
{
|
||||
FileLedger ledger;
|
||||
if (!_ledgers.TryGetValue(fileName, out ledger))
|
||||
{
|
||||
ledger = new FileLedger();
|
||||
_ledgers[fileName] = ledger;
|
||||
}
|
||||
return ledger;
|
||||
}
|
||||
|
||||
/// <summary>A stale writer writes exactly when its script ends: every end signal asks both files for a check on the next pass.</summary>
|
||||
private void RequestOverwriteCheck()
|
||||
{
|
||||
foreach (var ledger in _ledgers.Values) ledger.VerifyRequested = true;
|
||||
}
|
||||
|
||||
private void NoteInvocationActivity()
|
||||
{
|
||||
_contentionUntilUtc = UtcNowProvider() + InvocationContentionWindow;
|
||||
}
|
||||
|
||||
private bool InContention(DateTime nowUtc)
|
||||
{
|
||||
if (nowUtc < _contentionUntilUtc || _pendingHealthScript != null) return true;
|
||||
foreach (var script in _pendingPlatformScripts.Values)
|
||||
{
|
||||
if (script.Result != null) continue;
|
||||
if (!script.StartedAtUtc.HasValue || nowUtc - script.StartedAtUtc.Value < MaxPendingScriptContention) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs before a multi-writer file is read: rollover reset, restart seeding, then the
|
||||
/// overwrite check when one is due. Returns the offset to rewind to, or -1.
|
||||
/// </summary>
|
||||
private async Task<long> PrepareLedgerAsync(string filePath, string fileName, FileLedger ledger, long bookmark, DateTime nowUtc, CancellationToken token)
|
||||
{
|
||||
if (ledger.Entries.Count > 0 && bookmark < ledger.EndOffset)
|
||||
{
|
||||
// The bookmark moved below what was read: the file was replaced (rollover).
|
||||
ledger.Clear();
|
||||
InvalidateInvocationMarkersFrom(fileName, 0);
|
||||
}
|
||||
|
||||
if (!ledger.Seeded)
|
||||
{
|
||||
ledger.Seeded = true;
|
||||
if (ledger.Entries.Count == 0 && bookmark > 0)
|
||||
await SeedLedgerAsync(filePath, ledger, bookmark, token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var due = ledger.VerifyRequested || (InContention(nowUtc) && nowUtc >= ledger.NextCadenceVerifyUtc);
|
||||
if (!due || ledger.Entries.Count == 0) return -1;
|
||||
|
||||
var from = ledger.StartOffset;
|
||||
var bytes = bookmark - from;
|
||||
if (bytes <= 0)
|
||||
{
|
||||
ledger.VerifyRequested = false;
|
||||
return -1;
|
||||
}
|
||||
|
||||
long divergence;
|
||||
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
divergence = await FindOverwriteAsync(stream, ledger, from, bookmark, token).ConfigureAwait(false);
|
||||
if (token.IsCancellationRequested) return -1;
|
||||
|
||||
ledger.VerifyRequested = false;
|
||||
var paceSeconds = Math.Max(VerifyMinInterval.TotalSeconds, (double)bytes / VerifyBudgetBytesPerSecond);
|
||||
ledger.NextCadenceVerifyUtc = nowUtc.AddSeconds(paceSeconds);
|
||||
_verifyPasses++;
|
||||
_verifiedBytes += bytes;
|
||||
return divergence;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-reads [fromOffset, toOffset) with the read loop's assembler and compares against the
|
||||
/// ledger. Returns the offset of the first entry whose bytes changed — a ledger entry not
|
||||
/// reproduced, or an entry the ledger never had — or -1 when everything reads as before.
|
||||
/// </summary>
|
||||
private async Task<long> FindOverwriteAsync(FileStream stream, FileLedger ledger, long fromOffset, long toOffset, CancellationToken token)
|
||||
{
|
||||
var entries = ledger.Entries;
|
||||
var idx = ledger.IndexOfFirstAtOrAfter(fromOffset);
|
||||
if (idx >= entries.Count) return -1;
|
||||
|
||||
stream.Seek(entries[idx].Offset, SeekOrigin.Begin);
|
||||
var reader = new BoundedLineReader(stream, MaxEntryBytes, hashLines: true);
|
||||
var assembler = new CmTraceEntryAssembler(MaxMultiLineBufferLines, MaxEntryBytes);
|
||||
|
||||
while (reader.Position < toOffset)
|
||||
{
|
||||
var line = await reader.ReadLineAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
if (line == null) break;
|
||||
if (token.IsCancellationRequested) return -1;
|
||||
|
||||
AssembledEntry e;
|
||||
if (assembler.Feed(line, reader.LastLineStart, reader.Position, reader.LastLineTruncated, reader.LastLineHash, out e)
|
||||
!= CmTraceEntryAssembler.Outcome.Entry)
|
||||
continue;
|
||||
if (e.Offset >= toOffset) break;
|
||||
|
||||
if (idx < entries.Count && entries[idx].Offset < e.Offset) return entries[idx].Offset;
|
||||
if (idx < entries.Count && entries[idx].Offset == e.Offset)
|
||||
{
|
||||
if (entries[idx].Hash != e.Hash) return e.Offset;
|
||||
idx++;
|
||||
continue;
|
||||
}
|
||||
return e.Offset; // an entry the ledger never had: the bytes changed here
|
||||
}
|
||||
|
||||
return idx < entries.Count && entries[idx].Offset < toOffset ? entries[idx].Offset : -1;
|
||||
}
|
||||
|
||||
/// <summary>After a restart the ledger is empty: fingerprint the entries just behind the persisted bookmark without processing them.</summary>
|
||||
private async Task SeedLedgerAsync(string filePath, FileLedger ledger, long bookmark, CancellationToken token)
|
||||
{
|
||||
var from = Math.Max(0, bookmark - RestartSeedBytes);
|
||||
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
stream.Seek(from, SeekOrigin.Begin);
|
||||
var reader = new BoundedLineReader(stream, MaxEntryBytes, hashLines: true);
|
||||
var assembler = new CmTraceEntryAssembler(MaxMultiLineBufferLines, MaxEntryBytes);
|
||||
var aligned = from == 0;
|
||||
while (reader.Position < bookmark)
|
||||
{
|
||||
var line = await reader.ReadLineAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
if (line == null || token.IsCancellationRequested) break;
|
||||
if (!aligned)
|
||||
{
|
||||
// The seek may have landed mid-entry: wait for an entry boundary.
|
||||
if (!line.StartsWith(LogOpenTag)) continue;
|
||||
aligned = true;
|
||||
}
|
||||
AssembledEntry e;
|
||||
if (assembler.Feed(line, reader.LastLineStart, reader.Position, reader.LastLineTruncated, reader.LastLineHash, out e)
|
||||
== CmTraceEntryAssembler.Outcome.Entry
|
||||
&& e.Offset + e.Length <= bookmark)
|
||||
ledger.Record(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves the bookmark back to the first changed entry; returns the entries to skip if they still read unchanged behind it.</summary>
|
||||
private HashSet<LedgerEntry> ApplyRewind(string filePath, string fileName, FileLedger ledger, long rewindTo, long bookmark)
|
||||
{
|
||||
var removed = ledger.TruncateFrom(rewindTo);
|
||||
_positionTracker.SetPosition(filePath, rewindTo);
|
||||
_heldTails.Remove(filePath);
|
||||
InvalidateInvocationMarkersFrom(fileName, rewindTo);
|
||||
_overwriteRewinds++;
|
||||
_overwriteBytesReprocessed += bookmark - rewindTo;
|
||||
|
||||
var message = $"ImeLogTracker: {fileName} changed behind the bookmark at offset {rewindTo} " +
|
||||
$"(a concurrent writer overwrote already-read bytes) — rewinding {bookmark - rewindTo} bytes";
|
||||
if (!ledger.RewindLogged)
|
||||
{
|
||||
ledger.RewindLogged = true;
|
||||
_logger.Info(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Debug(message);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
private long RetentionFloor(string fileName, long bookmark)
|
||||
{
|
||||
var floor = bookmark - LedgerRetentionBytes;
|
||||
var oldest = OldestPendingScriptMarkerOffset(fileName);
|
||||
if (oldest >= 0 && oldest < floor) floor = oldest;
|
||||
var hardFloor = bookmark - LedgerMaxBytes;
|
||||
return floor < hardFloor ? hardFloor : floor;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Invocation markers: who owns the policyId-less executor lines at a file position
|
||||
// -----------------------------------------------------------------------
|
||||
//
|
||||
// AgentExecutor.log carries "Powershell exit code is N" / "write output done" without a
|
||||
// policy id. Their owner is decided by FILE POSITION, not by the order lines were read:
|
||||
// an executor writes its end block at its own stream position, i.e. directly after its
|
||||
// own start block in the final bytes, so the nearest preceding invocation marker names
|
||||
// it — and stays right after a rewind re-reads that region. A marker is a platform start
|
||||
// (policy id), some other invocation (detection, remediation, requirement: null) or a
|
||||
// close ("gets invoked" banner, "Agent executor completed").
|
||||
|
||||
private sealed class InvocationMarker
|
||||
{
|
||||
public long Offset;
|
||||
public string PolicyId;
|
||||
public bool IsClose;
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, List<InvocationMarker>> _invocationMarkers =
|
||||
new Dictionary<string, List<InvocationMarker>>(StringComparer.OrdinalIgnoreCase);
|
||||
private InvocationMarker _lastPlatformMarker;
|
||||
// Files a platform run has opened in (PS-AGENT-SCRIPT-START in AgentExecutor.log,
|
||||
// PS-SCRIPT-GENERATED in IntuneManagementExtension.log). Survives a rollover of the
|
||||
// file's markers: the fallback below is meant for exactly that file.
|
||||
private readonly HashSet<string> _platformMarkerFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
private long _testEntryOrdinal;
|
||||
|
||||
private void RecordInvocationMarker(string policyId, bool isClose)
|
||||
{
|
||||
if (_currentEntryOffset < 0) return;
|
||||
var file = _currentSourceFileName ?? TestSourceFileName;
|
||||
List<InvocationMarker> list;
|
||||
if (!_invocationMarkers.TryGetValue(file, out list))
|
||||
{
|
||||
list = new List<InvocationMarker>();
|
||||
_invocationMarkers[file] = list;
|
||||
}
|
||||
|
||||
if (list.Count > 0 && list[list.Count - 1].Offset == _currentEntryOffset)
|
||||
{
|
||||
// Two patterns on one line: the platform start outranks the generic argument line.
|
||||
var last = list[list.Count - 1];
|
||||
if (!isClose && policyId != null)
|
||||
{
|
||||
last.PolicyId = policyId;
|
||||
last.IsClose = false;
|
||||
_lastPlatformMarker = last;
|
||||
_platformMarkerFiles.Add(file);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (list.Count >= MaxInvocationMarkersPerFile) list.RemoveAt(0);
|
||||
var marker = new InvocationMarker { Offset = _currentEntryOffset, PolicyId = policyId, IsClose = isClose };
|
||||
list.Add(marker);
|
||||
if (!isClose && policyId != null)
|
||||
{
|
||||
_lastPlatformMarker = marker;
|
||||
_platformMarkerFiles.Add(file);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The pending platform script that owns the entry being processed, or null.
|
||||
/// <paramref name="ownerPolicyId"/> names the owning platform script even when its slot is
|
||||
/// gone (completion already emitted); null when no platform invocation owns the entry.
|
||||
/// </summary>
|
||||
private ScriptExecutionState ResolvePlatformScriptForCurrentEntry(out string ownerPolicyId)
|
||||
{
|
||||
ownerPolicyId = null;
|
||||
var file = _currentSourceFileName ?? TestSourceFileName;
|
||||
InvocationMarker marker = null;
|
||||
List<InvocationMarker> list = null;
|
||||
if (_currentEntryOffset >= 0 && _invocationMarkers.TryGetValue(file, out list))
|
||||
{
|
||||
for (var i = list.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (list[i].Offset <= _currentEntryOffset)
|
||||
{
|
||||
marker = list[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A file without any marker resolves to the platform run in flight only when platform
|
||||
// runs open in that file at all — IntuneManagementExtension.log right after a rollover
|
||||
// cleared its markers, AgentExecutor.log likewise. HealthScripts.log and the app logs
|
||||
// never carry a platform marker: their launch and exit lines belong to health scripts
|
||||
// and detection scripts, never to the platform script that happens to be pending
|
||||
// (session 24dc69d1: the health-script worker's exit line pre-filled a platform slot's
|
||||
// exit code, its launch line the slot's context).
|
||||
if (marker == null && (list == null || list.Count == 0) && _platformMarkerFiles.Contains(file)) marker = _lastPlatformMarker;
|
||||
if (marker == null || marker.IsClose || marker.PolicyId == null) return null;
|
||||
|
||||
ownerPolicyId = marker.PolicyId;
|
||||
ScriptExecutionState state;
|
||||
return _pendingPlatformScripts.TryGetValue(marker.PolicyId, out state) ? state : null;
|
||||
}
|
||||
|
||||
private void InvalidateInvocationMarkersFrom(string fileName, long offset)
|
||||
{
|
||||
List<InvocationMarker> list;
|
||||
if (!_invocationMarkers.TryGetValue(fileName, out list) || list.Count == 0) return;
|
||||
var removedLast = false;
|
||||
for (var i = list.Count - 1; i >= 0 && list[i].Offset >= offset; i--)
|
||||
{
|
||||
if (ReferenceEquals(list[i], _lastPlatformMarker)) removedLast = true;
|
||||
list.RemoveAt(i);
|
||||
}
|
||||
if (removedLast)
|
||||
{
|
||||
_lastPlatformMarker = null;
|
||||
for (var i = list.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!list[i].IsClose && list[i].PolicyId != null)
|
||||
{
|
||||
_lastPlatformMarker = list[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long OldestPendingScriptMarkerOffset(string fileName)
|
||||
{
|
||||
List<InvocationMarker> list;
|
||||
if (!_invocationMarkers.TryGetValue(fileName, out list)) return -1;
|
||||
long oldest = -1;
|
||||
foreach (var marker in list)
|
||||
{
|
||||
if (marker.IsClose || marker.PolicyId == null || !_pendingPlatformScripts.ContainsKey(marker.PolicyId)) continue;
|
||||
if (oldest < 0 || marker.Offset < oldest) oldest = marker.Offset;
|
||||
}
|
||||
return oldest;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Test seams
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/// <summary>Same effect as an end signal: both multi-writer ledgers are verified on the next pass.</summary>
|
||||
internal void RequestOverwriteCheckForTest() => RequestOverwriteCheck();
|
||||
|
||||
/// <summary>What a rollover of the file does to its invocation markers.</summary>
|
||||
internal void ClearInvocationMarkersForTest(string fileName) => InvalidateInvocationMarkersFrom(fileName, 0);
|
||||
|
||||
internal int LedgerEntryCountForTest(string fileName)
|
||||
{
|
||||
FileLedger ledger;
|
||||
return _ledgers.TryGetValue(fileName, out ledger) ? ledger.Entries.Count : 0;
|
||||
}
|
||||
|
||||
/// <summary>Gives a seam-fed message a file position of its own so positional attribution behaves like in a real pass.</summary>
|
||||
internal void NextTestEntry()
|
||||
{
|
||||
if (_currentSourceFileName == null) _currentSourceFileName = TestSourceFileName;
|
||||
_currentEntryOffset = ++_testEntryOrdinal * 4096;
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
-22
@@ -181,7 +181,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// arrive across multiple log entries and IME may interleave platform scripts).
|
||||
private readonly Dictionary<string, ScriptExecutionState> _pendingPlatformScripts =
|
||||
new Dictionary<string, ScriptExecutionState>(StringComparer.OrdinalIgnoreCase);
|
||||
private string _lastPlatformScriptPolicyId;
|
||||
|
||||
// Health-script (remediation) line-by-line accumulator — single slot because IME
|
||||
// executes health scripts SEQUENTIALLY within a session (verified across multiple
|
||||
@@ -193,14 +192,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// UI dedupe (dataCompleteness scoring).
|
||||
private ScriptExecutionState _pendingHealthScript;
|
||||
|
||||
// Collapses recurring health-script runs; persisted with the file positions.
|
||||
private readonly RecurringScriptGate _recurringScripts = new RecurringScriptGate();
|
||||
|
||||
// Set for the duration of one pattern dispatch: the matched line is older than
|
||||
// HistoricReplayThreshold, so the adapter drops whatever it produces.
|
||||
private bool _currentLineIsHistoricReplay;
|
||||
|
||||
// Cycle start timestamps for health (remediation) scripts, keyed by policyId. Captured
|
||||
// from the HS-SCRIPT-START line ([HS] ProcessScript) so the consolidated HS-NEW-RESULT
|
||||
// emit can surface the cycle's total run duration (start → result) on its phase events —
|
||||
// the remediation-script analog of the platform-script StartedAtUtc timing. Kept in a
|
||||
// dedicated map (not on _pendingHealthScript) because the early-signal HS-COMPLIANCE
|
||||
// handler clears that slot before HS-NEW-RESULT arrives. Consumed + removed on result emit.
|
||||
private readonly Dictionary<string, DateTime> _healthScriptStartTimes =
|
||||
new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
|
||||
// The start line's provenance rides along so the adapter can tell whether start and result
|
||||
// were resolved on the same zone assumption before it subtracts them.
|
||||
private readonly Dictionary<string, (DateTime Utc, CmTraceLineProvenance Provenance)> _healthScriptStartTimes =
|
||||
new Dictionary<string, (DateTime Utc, CmTraceLineProvenance Provenance)>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// Restart-safe dedup for the adapter's one-shot script_timeout_suspected Warning.
|
||||
// Owned by the tracker (not the adapter) solely so it rides the persisted state file —
|
||||
@@ -337,7 +345,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
private int _unanchoredPatterns;
|
||||
private int _filesTailed;
|
||||
private long _backlogBytes;
|
||||
// Poll-loop timing (restart-safe maxima on a monotonic clock): the longest pass and the
|
||||
// longest pause between passes — see ImeTrackerHealth.PassMaxMs / PassGapMaxMs.
|
||||
private long _passMaxMs;
|
||||
private long _passGapMaxMs;
|
||||
private long _lastPassEndMs = -1;
|
||||
private string _imeAgentVersionSeen;
|
||||
|
||||
/// <summary>Monotonic milliseconds for the poll-loop timing; tests substitute a counter.</summary>
|
||||
internal Func<long> MonotonicMillisProvider { get; set; } = () => Stopwatch.GetTimestamp() * 1000 / Stopwatch.Frequency;
|
||||
private bool _trackerDegradedFired;
|
||||
private readonly Dictionary<string, int> _patternHits = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
@@ -367,6 +383,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
FilesTailed = _filesTailed,
|
||||
BacklogBytes = _backlogBytes,
|
||||
ImeAgentVersion = _imeAgentVersionSeen,
|
||||
OverwriteRewinds = _overwriteRewinds,
|
||||
OverwriteBytesReprocessed = _overwriteBytesReprocessed,
|
||||
VerifyPasses = _verifyPasses,
|
||||
VerifiedBytes = _verifiedBytes,
|
||||
PassMaxMs = _passMaxMs,
|
||||
PassGapMaxMs = _passGapMaxMs,
|
||||
PatternHits = new Dictionary<string, int>(_patternHits, StringComparer.OrdinalIgnoreCase),
|
||||
};
|
||||
}
|
||||
@@ -485,6 +507,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// </summary>
|
||||
public Action<ScriptStartedInfo> OnScriptStarted { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Fires when the tracker stops, once per health-script policy whose repeated runs were
|
||||
/// counted instead of emitted since the last summary (see <see cref="RecurringScriptGate"/>).
|
||||
/// </summary>
|
||||
public Action<ScriptRecurrenceSummary> OnScriptRecurrenceSummary { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Fires on every pattern match with the matched <c>PatternId</c>. Plan §4.x M4.4.4.
|
||||
/// Invoked by <c>HandlePatternMatch</c> after <see cref="LastMatchedPatternId"/> is
|
||||
@@ -951,18 +979,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
try
|
||||
{
|
||||
await CheckLogFilesAsync(token);
|
||||
|
||||
// Safety net: emit completions for platform scripts whose AgentExecutor
|
||||
// exit code we already have but whose authoritative IME PS-SCRIPT-RESULT
|
||||
// line never arrived within the grace period. Runs on this same loop
|
||||
// thread (no locking) so it observes the buffer right after parsing.
|
||||
FlushStalePlatformScriptResults(DateTime.UtcNow);
|
||||
|
||||
// Token-failure grace window: fires only when the failure stayed
|
||||
// unresolved (no IME-TOKEN-SUCCESS) for the whole window. Runs after
|
||||
// the drain so a success later in the same batch clears first.
|
||||
CheckPendingTokenFailure(DateTime.UtcNow);
|
||||
await RunPollPassAsync(token);
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (Exception ex)
|
||||
@@ -985,12 +1002,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
try { await Task.Delay(_pollingIntervalMs, token); } catch (OperationCanceledException) { break; }
|
||||
}
|
||||
|
||||
// Final pass: force-flush any platform script that completed within the last grace
|
||||
// window before shutdown (exit code known, IME result still pending). Best-effort —
|
||||
// emits only while callbacks are still wired (i.e. the adapter hasn't been disposed).
|
||||
try { FlushStalePlatformScriptResults(DateTime.UtcNow, force: true); }
|
||||
// Final pass: force-flush any platform script still waiting for the other file
|
||||
// (a held IME result, or an exit code whose IME result is still pending).
|
||||
// Best-effort — emits only while callbacks are still wired (i.e. the adapter
|
||||
// hasn't been disposed).
|
||||
try { FlushPendingPlatformScriptResults(UtcNowProvider(), force: true); }
|
||||
catch (Exception ex) { _logger.Warning($"ImeLogTracker: shutdown script flush failed: {ex.Message}"); }
|
||||
|
||||
try { FlushRecurringScripts(UtcNowProvider(), shuttingDown: true); }
|
||||
catch (Exception ex) { _logger.Warning($"ImeLogTracker: shutdown recurring-script flush failed: {ex.Message}"); }
|
||||
|
||||
// Final state save on shutdown
|
||||
if (_stateDirty)
|
||||
{
|
||||
@@ -1002,6 +1023,37 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
}, token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One poll pass, timed: the file reads, then the platform-script completions that wait
|
||||
/// for the other file (an IME result held for its executor end block, the exit-code
|
||||
/// fallback for a result IME never logged), then the token-failure grace window — all on
|
||||
/// this one loop thread, no locking, so the flushes observe the buffers right after
|
||||
/// parsing. The longest pass and the longest pause since the previous pass ended are the
|
||||
/// session's <see cref="ImeTrackerHealth.PassMaxMs"/> / <see cref="ImeTrackerHealth.PassGapMaxMs"/>.
|
||||
/// </summary>
|
||||
internal async Task RunPollPassAsync(CancellationToken token)
|
||||
{
|
||||
var startMs = MonotonicMillisProvider();
|
||||
if (_lastPassEndMs >= 0 && startMs - _lastPassEndMs > _passGapMaxMs)
|
||||
{
|
||||
_passGapMaxMs = startMs - _lastPassEndMs;
|
||||
_stateDirty = true;
|
||||
}
|
||||
|
||||
await CheckLogFilesAsync(token);
|
||||
FlushPendingPlatformScriptResults(UtcNowProvider());
|
||||
FlushRecurringScripts(UtcNowProvider(), shuttingDown: false);
|
||||
CheckPendingTokenFailure(UtcNowProvider());
|
||||
|
||||
var endMs = MonotonicMillisProvider();
|
||||
if (endMs - startMs > _passMaxMs)
|
||||
{
|
||||
_passMaxMs = endMs - startMs;
|
||||
_stateDirty = true;
|
||||
}
|
||||
_lastPassEndMs = endMs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the background polling task
|
||||
/// </summary>
|
||||
@@ -1100,10 +1152,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// (the in-memory marker set started empty). Old state files have null here —
|
||||
// degrades to the pre-fix behavior, no crash.
|
||||
_platformScriptResultEmitted.Clear();
|
||||
if (state.PlatformScriptResultEmitted != null)
|
||||
if (state.PlatformScriptResultEmittedAt != null)
|
||||
{
|
||||
foreach (var kv in state.PlatformScriptResultEmittedAt)
|
||||
_platformScriptResultEmitted[kv.Key] = kv.Value;
|
||||
}
|
||||
else if (state.PlatformScriptResultEmitted != null)
|
||||
{
|
||||
// State files from before the marker carried the run's timestamp: the dedup
|
||||
// works as before, the late-start-line guard never fires for these runs.
|
||||
foreach (var id in state.PlatformScriptResultEmitted)
|
||||
_platformScriptResultEmitted.Add(id);
|
||||
_platformScriptResultEmitted[id] = DateTime.MinValue;
|
||||
}
|
||||
|
||||
_pendingPlatformScripts.Clear();
|
||||
@@ -1123,6 +1182,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
_scriptTimeoutSuspectedPosted.Add(id);
|
||||
}
|
||||
|
||||
_recurringScripts.Restore(state.RecurringScripts);
|
||||
|
||||
// Health counters + histogram: a restart (or WhiteGlove Part 2) must report the
|
||||
// whole session, not only the lines seen since the last start. Null on state files
|
||||
// written before these fields existed → counters start at zero.
|
||||
@@ -1140,6 +1201,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
HealthScriptResultParseFailures = state.Health.HealthScriptResultParseFailures;
|
||||
_imeAgentVersionSeen = state.Health.ImeAgentVersion;
|
||||
_trackerDegradedFired = state.Health.TrackerDegradedFired;
|
||||
_overwriteRewinds = state.Health.OverwriteRewinds;
|
||||
_overwriteBytesReprocessed = state.Health.OverwriteBytesReprocessed;
|
||||
_verifyPasses = state.Health.VerifyPasses;
|
||||
_verifiedBytes = state.Health.VerifiedBytes;
|
||||
_passMaxMs = state.Health.PassMaxMs;
|
||||
_passGapMaxMs = state.Health.PassGapMaxMs;
|
||||
}
|
||||
if (state.PatternHits != null)
|
||||
{
|
||||
@@ -1190,9 +1257,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
// H1 (delta review 2026-07-02): platform-script dedup markers + pending buffer
|
||||
// must survive restarts — see the LoadState comment for the duplicate scenario.
|
||||
PlatformScriptResultEmitted = _platformScriptResultEmitted.ToList(),
|
||||
PlatformScriptResultEmittedAt = new Dictionary<string, DateTime>(_platformScriptResultEmitted, StringComparer.OrdinalIgnoreCase),
|
||||
PendingPlatformScripts = _pendingPlatformScripts.Values.ToList(),
|
||||
ScriptTimeoutSuspectedPosted = _scriptTimeoutSuspectedPosted.ToList(),
|
||||
RecurringScripts = _recurringScripts.ToPersisted(),
|
||||
};
|
||||
|
||||
lock (_healthLock)
|
||||
@@ -1209,6 +1277,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
HealthScriptResultParseFailures = HealthScriptResultParseFailures,
|
||||
ImeAgentVersion = _imeAgentVersionSeen,
|
||||
TrackerDegradedFired = _trackerDegradedFired,
|
||||
OverwriteRewinds = _overwriteRewinds,
|
||||
OverwriteBytesReprocessed = _overwriteBytesReprocessed,
|
||||
VerifyPasses = _verifyPasses,
|
||||
VerifiedBytes = _verifiedBytes,
|
||||
PassMaxMs = _passMaxMs,
|
||||
PassGapMaxMs = _passGapMaxMs,
|
||||
};
|
||||
state.PatternHits = new Dictionary<string, int>(_patternHits, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
+35
@@ -46,6 +46,41 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// <summary>IME version as logged by IME itself ("Agent version is: …"), null until seen.</summary>
|
||||
public string ImeAgentVersion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Times the bookmark of a multi-writer log (AgentExecutor.log, IntuneManagementExtension.log)
|
||||
/// was moved back because bytes behind it had been overwritten by a concurrent IME
|
||||
/// process. Expected nonzero whenever user-context scripts or detection scripts ran —
|
||||
/// recovered data, not skipped work.
|
||||
/// </summary>
|
||||
public long OverwriteRewinds { get; set; }
|
||||
|
||||
/// <summary>Bytes re-read by those rewinds (only entries that changed are processed again).</summary>
|
||||
public long OverwriteBytesReprocessed { get; set; }
|
||||
|
||||
/// <summary>Full ledger verifications run (cadence while scripts are in flight, end signals, fragments).</summary>
|
||||
public long VerifyPasses { get; set; }
|
||||
|
||||
/// <summary>Bytes re-read for verification, guard-zone checks included — the cost of the overwrite detection.</summary>
|
||||
public long VerifiedBytes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Longest single poll pass this session (one <c>CheckLogFilesAsync</c> plus the
|
||||
/// flushes), milliseconds on a monotonic clock. A pass spends its time in the file
|
||||
/// reads, the ledger verifications and the regex matching; the fleet baseline is well
|
||||
/// under 100 ms.
|
||||
/// </summary>
|
||||
public long PassMaxMs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Longest pause between the end of one poll pass and the start of the next this
|
||||
/// session, milliseconds. The loop sleeps 100 ms between passes and saves its state now
|
||||
/// and then; anything far above that is the loop not being scheduled — session c3ecb568
|
||||
/// lost 26 s this way at 100 % VM CPU while the rest of the agent kept running. Late
|
||||
/// reading, not lost data: every event keeps its log line's own timestamp, and a
|
||||
/// result read before its executor end block waits for it.
|
||||
/// </summary>
|
||||
public long PassGapMaxMs { get; set; }
|
||||
|
||||
/// <summary>Match count per enabled pattern ID — every enabled pattern is present, zeros included.</summary>
|
||||
public IReadOnlyDictionary<string, int> PatternHits { get; set; }
|
||||
|
||||
|
||||
+20
@@ -142,10 +142,22 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// continues its grace window after the restart instead of being silently dropped.
|
||||
// ScriptExecutionState is a plain DTO, serialized directly (no mapping layer needed).
|
||||
// All three are null on state files from before this fix — LoadState treats null as empty.
|
||||
// Read-only migration input: state files written before the marker carried the run's
|
||||
// source timestamp (agents up to 2.0.1458). Never written any more.
|
||||
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
|
||||
public List<string> PlatformScriptResultEmitted { get; set; }
|
||||
// Policy id → source timestamp of the emitted run (its result line; the exit line for a
|
||||
// fallback emit): the dedup marker plus the reference that tells a late start line of
|
||||
// that run from the start of the next one.
|
||||
public Dictionary<string, DateTime> PlatformScriptResultEmittedAt { get; set; }
|
||||
public List<ScriptExecutionState> PendingPlatformScripts { get; set; }
|
||||
public List<string> ScriptTimeoutSuspectedPosted { get; set; }
|
||||
|
||||
// Recurring health-script runs collapsed per policy. Saved in the same write as
|
||||
// FilePositions on purpose: after a hard kill both fall back together, so re-read lines
|
||||
// are counted again instead of twice. Null on older state files → empty.
|
||||
public Dictionary<string, RecurringScriptPolicyState> RecurringScripts { get; set; }
|
||||
|
||||
// Cumulative tracker health + per-pattern histogram (ime_pattern_hits / ime_tracker_degraded,
|
||||
// 2026-08-30). Restart-safe on purpose: WhiteGlove Part 2 reports the whole session and the
|
||||
// one-shot degraded event must not fire twice. Null on older state files → zero.
|
||||
@@ -165,6 +177,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
public int HealthScriptResultParseFailures { get; set; }
|
||||
public string ImeAgentVersion { get; set; }
|
||||
public bool TrackerDegradedFired { get; set; }
|
||||
// Overwrite detection counters (null-defaulting on older state files).
|
||||
public long OverwriteRewinds { get; set; }
|
||||
public long OverwriteBytesReprocessed { get; set; }
|
||||
public long VerifyPasses { get; set; }
|
||||
public long VerifiedBytes { get; set; }
|
||||
// Poll-loop timing maxima (null-defaulting on older state files).
|
||||
public long PassMaxMs { get; set; }
|
||||
public long PassGapMaxMs { get; set; }
|
||||
}
|
||||
|
||||
public class PackageStateData
|
||||
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Collapses recurring health-script (proactive remediation) runs. IME re-runs every assigned
|
||||
/// policy on its own schedule for as long as the device is up; an enrollment that waits for
|
||||
/// its user for days would otherwise report every hourly run of every policy. A policy's
|
||||
/// first run and every run whose result differs from the last reported one are emitted in
|
||||
/// full; runs that repeat the last reported result are only counted and surface once per
|
||||
/// policy as a recurrence summary.
|
||||
/// <para>
|
||||
/// The start signal of an already known policy is held until its result is known, because
|
||||
/// the running indicators (web panel, session coverage) pair a start with a later result of
|
||||
/// the same policy — a start whose result was collapsed would read as "still running".
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The state is part of the tracker state file and is saved in the same write as the file
|
||||
/// positions: after a hard kill both fall back together, the lines after the last save are
|
||||
/// read again and counted again — nothing is lost and nothing counts twice.
|
||||
/// </para>
|
||||
/// Not thread-safe: called from the tracker's single poll thread only.
|
||||
/// </summary>
|
||||
public sealed class RecurringScriptGate
|
||||
{
|
||||
private readonly Dictionary<string, RecurringScriptPolicyState> _policies =
|
||||
new Dictionary<string, RecurringScriptPolicyState>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>True when any call changed persisted state since the last <see cref="ConsumeDirty"/>.</summary>
|
||||
private bool _dirty;
|
||||
|
||||
public bool ConsumeDirty()
|
||||
{
|
||||
var wasDirty = _dirty;
|
||||
_dirty = false;
|
||||
return wasDirty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A start line was read. Returns <c>true</c> when the start signal is emitted right away
|
||||
/// (first run of the policy); <c>false</c> when it is held until the run's result is known.
|
||||
/// </summary>
|
||||
public bool OnStart(string policyId, DateTime startedAtUtc, string policyType, string patternId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(policyId)) return true;
|
||||
|
||||
var isKnown = _policies.TryGetValue(policyId, out var state);
|
||||
if (!isKnown)
|
||||
{
|
||||
state = new RecurringScriptPolicyState();
|
||||
_policies[policyId] = state;
|
||||
}
|
||||
|
||||
CloseHeldRun(state);
|
||||
state.RunsObserved++;
|
||||
_dirty = true;
|
||||
|
||||
if (!isKnown) return true;
|
||||
|
||||
state.HeldStartAtUtc = startedAtUtc;
|
||||
state.HeldStartPolicyType = policyType;
|
||||
state.HeldStartPatternId = patternId;
|
||||
state.HeldRunSawResult = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A result (one phase event) is about to be emitted. Returns <c>true</c> to emit it; when
|
||||
/// the run's start was held, <paramref name="releasedStart"/> carries the start signal to
|
||||
/// emit first. Returns <c>false</c> when the result repeats the last reported one.
|
||||
/// </summary>
|
||||
public bool OnResult(ScriptExecutionState script, DateTime observedAtUtc, out ScriptStartedInfo releasedStart)
|
||||
{
|
||||
releasedStart = null;
|
||||
if (script == null || string.IsNullOrEmpty(script.PolicyId)) return true;
|
||||
|
||||
if (!_policies.TryGetValue(script.PolicyId, out var state))
|
||||
{
|
||||
state = new RecurringScriptPolicyState();
|
||||
_policies[script.PolicyId] = state;
|
||||
}
|
||||
|
||||
var key = SignatureKey(script);
|
||||
var signature = Signature(script);
|
||||
_dirty = true;
|
||||
|
||||
if (state.Signatures.TryGetValue(key, out var last) && string.Equals(last, signature, StringComparison.Ordinal))
|
||||
{
|
||||
state.CollapsedResults++;
|
||||
if (!state.FirstCollapsedAtUtc.HasValue) state.FirstCollapsedAtUtc = observedAtUtc;
|
||||
state.LastCollapsedAtUtc = observedAtUtc;
|
||||
if (state.HeldStartAtUtc.HasValue) state.HeldRunSawResult = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
state.Signatures[key] = signature;
|
||||
releasedStart = ReleaseHeldStart(script.PolicyId, state);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Start signals that were held for at least <paramref name="minAge"/> without any result:
|
||||
/// the script did not finish, which is exactly what the running indicators are for.
|
||||
/// </summary>
|
||||
public List<ScriptStartedInfo> ReleaseStartsWithoutResult(DateTime nowUtc, TimeSpan minAge)
|
||||
{
|
||||
var released = new List<ScriptStartedInfo>();
|
||||
foreach (var kv in _policies)
|
||||
{
|
||||
var state = kv.Value;
|
||||
if (!state.HeldStartAtUtc.HasValue || state.HeldRunSawResult) continue;
|
||||
if (nowUtc - state.HeldStartAtUtc.Value < minAge) continue;
|
||||
released.Add(ReleaseHeldStart(kv.Key, state));
|
||||
_dirty = true;
|
||||
}
|
||||
return released;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One summary per policy whose collapsed-run count grew since the last summary. Marks
|
||||
/// the reported count, so a later stop of the same session only reports new growth.
|
||||
/// </summary>
|
||||
public List<ScriptRecurrenceSummary> TakeSummaries()
|
||||
{
|
||||
var summaries = new List<ScriptRecurrenceSummary>();
|
||||
foreach (var kv in _policies)
|
||||
{
|
||||
var state = kv.Value;
|
||||
var collapsedRuns = state.RunsCollapsed + (state.HeldStartAtUtc.HasValue && state.HeldRunSawResult ? 1 : 0);
|
||||
if (collapsedRuns <= state.RunsCollapsedAtLastSummary) continue;
|
||||
|
||||
summaries.Add(new ScriptRecurrenceSummary
|
||||
{
|
||||
PolicyId = kv.Key,
|
||||
RunsObserved = state.RunsObserved,
|
||||
RunsCollapsed = collapsedRuns,
|
||||
RunsWithoutResult = state.RunsWithoutResult,
|
||||
CollapsedResults = state.CollapsedResults,
|
||||
FirstCollapsedAtUtc = state.FirstCollapsedAtUtc,
|
||||
LastCollapsedAtUtc = state.LastCollapsedAtUtc,
|
||||
});
|
||||
state.RunsCollapsedAtLastSummary = collapsedRuns;
|
||||
_dirty = true;
|
||||
}
|
||||
return summaries;
|
||||
}
|
||||
|
||||
public Dictionary<string, RecurringScriptPolicyState> ToPersisted() =>
|
||||
new Dictionary<string, RecurringScriptPolicyState>(_policies, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public void Restore(Dictionary<string, RecurringScriptPolicyState> persisted)
|
||||
{
|
||||
_policies.Clear();
|
||||
if (persisted == null) return;
|
||||
foreach (var kv in persisted)
|
||||
{
|
||||
if (string.IsNullOrEmpty(kv.Key) || kv.Value == null) continue;
|
||||
if (kv.Value.Signatures == null)
|
||||
kv.Value.Signatures = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
_policies[kv.Key] = kv.Value;
|
||||
}
|
||||
}
|
||||
|
||||
// A held run ends when the next start of the policy arrives: all its results repeated the
|
||||
// last report (collapsed), or it never produced one.
|
||||
private static void CloseHeldRun(RecurringScriptPolicyState state)
|
||||
{
|
||||
if (!state.HeldStartAtUtc.HasValue) return;
|
||||
if (state.HeldRunSawResult) state.RunsCollapsed++;
|
||||
else state.RunsWithoutResult++;
|
||||
ClearHeldStart(state);
|
||||
}
|
||||
|
||||
private static ScriptStartedInfo ReleaseHeldStart(string policyId, RecurringScriptPolicyState state)
|
||||
{
|
||||
if (!state.HeldStartAtUtc.HasValue) return null;
|
||||
var info = new ScriptStartedInfo
|
||||
{
|
||||
PolicyId = policyId,
|
||||
ScriptType = "remediation",
|
||||
PolicyType = state.HeldStartPolicyType,
|
||||
SourceTimestampUtc = state.HeldStartAtUtc,
|
||||
PatternId = state.HeldStartPatternId,
|
||||
};
|
||||
ClearHeldStart(state);
|
||||
return info;
|
||||
}
|
||||
|
||||
private static void ClearHeldStart(RecurringScriptPolicyState state)
|
||||
{
|
||||
state.HeldStartAtUtc = null;
|
||||
state.HeldStartPolicyType = null;
|
||||
state.HeldStartPatternId = null;
|
||||
state.HeldRunSawResult = false;
|
||||
}
|
||||
|
||||
// The early compliance signal and the consolidated result of one phase differ in
|
||||
// completeness (only the latter knows RemediationStatus); keyed apart, or the two would
|
||||
// overwrite each other's signature on every run and nothing would ever collapse.
|
||||
private static string SignatureKey(ScriptExecutionState script) =>
|
||||
(script.ScriptPart ?? string.Empty) + "|" + (script.DurationBasis ?? string.Empty);
|
||||
|
||||
private static string Signature(ScriptExecutionState script)
|
||||
{
|
||||
var culture = CultureInfo.InvariantCulture;
|
||||
return string.Join("|",
|
||||
script.ComplianceResult ?? string.Empty,
|
||||
script.ExitCode.HasValue ? script.ExitCode.Value.ToString(culture) : string.Empty,
|
||||
string.IsNullOrWhiteSpace(script.Stderr) ? "0" : "1",
|
||||
script.RemediationStatus.HasValue ? script.RemediationStatus.Value.ToString(culture) : string.Empty,
|
||||
script.ErrorCode.HasValue ? script.ErrorCode.Value.ToString(culture) : string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Persisted per-policy state of <see cref="RecurringScriptGate"/>.</summary>
|
||||
public class RecurringScriptPolicyState
|
||||
{
|
||||
/// <summary>Last reported result per phase and signal kind.</summary>
|
||||
public Dictionary<string, string> Signatures { get; set; } = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Start lines read for the policy.</summary>
|
||||
public int RunsObserved { get; set; }
|
||||
|
||||
/// <summary>Runs whose every result repeated the last reported one.</summary>
|
||||
public int RunsCollapsed { get; set; }
|
||||
|
||||
/// <summary>Runs that were followed by the next start without any result in between.</summary>
|
||||
public int RunsWithoutResult { get; set; }
|
||||
|
||||
/// <summary>Phase events that were not emitted.</summary>
|
||||
public int CollapsedResults { get; set; }
|
||||
|
||||
public DateTime? FirstCollapsedAtUtc { get; set; }
|
||||
public DateTime? LastCollapsedAtUtc { get; set; }
|
||||
|
||||
public DateTime? HeldStartAtUtc { get; set; }
|
||||
public string HeldStartPolicyType { get; set; }
|
||||
public string HeldStartPatternId { get; set; }
|
||||
public bool HeldRunSawResult { get; set; }
|
||||
|
||||
public int RunsCollapsedAtLastSummary { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="RecurringScriptGate"/> collapsed for one policy.</summary>
|
||||
public class ScriptRecurrenceSummary
|
||||
{
|
||||
public string PolicyId { get; set; }
|
||||
public int RunsObserved { get; set; }
|
||||
public int RunsCollapsed { get; set; }
|
||||
public int RunsWithoutResult { get; set; }
|
||||
public int CollapsedResults { get; set; }
|
||||
public DateTime? FirstCollapsedAtUtc { get; set; }
|
||||
public DateTime? LastCollapsedAtUtc { get; set; }
|
||||
}
|
||||
}
|
||||
+54
-1
@@ -29,6 +29,15 @@ public class ScriptExecutionState
|
||||
/// </summary>
|
||||
public System.DateTime? StartedAtUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Provenance of <see cref="StartedAtUtc"/>: how the start line's offset was obtained. Paired
|
||||
/// with <see cref="ResultProvenance"/> / <see cref="ExitProvenance"/> by the adapter to decide
|
||||
/// whether a run duration is measurable — two lines resolved on different zone assumptions
|
||||
/// differ by whole offset-grid steps, not by run time (session 4377911b: a 10 s script read
|
||||
/// as 3610 s). Null when the start was never observed or on state files from before the field.
|
||||
/// </summary>
|
||||
public CmTraceLineProvenance StartedAtProvenance { get; set; }
|
||||
|
||||
/// <summary>"detection", "remediation", or "post-detection" (remediation scripts only).</summary>
|
||||
public string ScriptPart { get; set; }
|
||||
|
||||
@@ -61,11 +70,45 @@ public class ScriptExecutionState
|
||||
/// <summary>
|
||||
/// UTC timestamp at which the AgentExecutor.log exit-code line for this platform script was
|
||||
/// observed. Drives the deadline check in
|
||||
/// <see cref="ImeLogTracker.FlushStalePlatformScriptResults"/> — set only on the platform path
|
||||
/// <see cref="ImeLogTracker.FlushPendingPlatformScriptResults"/> — set only on the platform path
|
||||
/// (PS-AGENT exit code); null until an exit code is seen.
|
||||
/// </summary>
|
||||
public System.DateTime? ExitObservedAtUtc { get; set; }
|
||||
|
||||
/// <summary>Provenance of the exit-code line behind <see cref="ExitObservedAtUtc"/> (the fallback emit's end).</summary>
|
||||
public CmTraceLineProvenance ExitProvenance { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Source (CMTrace) timestamp of the IME <c>PS-SCRIPT-RESULT</c> line that delivered
|
||||
/// <see cref="Result"/> (platform scripts, <c>ime_policy_result</c> only). The emitted event is
|
||||
/// bound to it — the emit may happen passes later (see <see cref="ResultHeldSinceUtc"/>), when
|
||||
/// the tracker's "last matched" line is an unrelated one. Also the reference a later start line
|
||||
/// of the same policy is compared against: a start older than the emitted result is the late
|
||||
/// start line of that run, not a new run.
|
||||
/// </summary>
|
||||
public System.DateTime? ResultObservedAtUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Provenance of the line that delivered <see cref="Result"/> — bound here for the same reason
|
||||
/// as <see cref="ResultObservedAtUtc"/>: a held completion is emitted passes later, when the
|
||||
/// tracker's "last matched" provenance describes an unrelated line. For health scripts the
|
||||
/// result line of the phase (HS-COMPLIANCE early signal or HS-NEW-RESULT).
|
||||
/// </summary>
|
||||
public CmTraceLineProvenance ResultProvenance { get; set; }
|
||||
|
||||
/// <summary>Pattern id of the line that delivered <see cref="Result"/> (surfaced as <c>patternId</c> on the event).</summary>
|
||||
public string ResultPatternId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Wall-clock time (agent UTC) at which the IME result was seen while the executor end block
|
||||
/// (exit code, stdout, stderr) had not been read yet. The tracker holds the emit until the end
|
||||
/// block arrives — an overwritten block surfaces one pass later through the ledger rewind that
|
||||
/// the result itself triggers, and the AgentExecutor.log read can simply lag behind the IME log
|
||||
/// read — or until <c>ImeLogTracker.PlatformScriptEndBlockGrace</c> elapsed. Null when the
|
||||
/// result was not held.
|
||||
/// </summary>
|
||||
public System.DateTime? ResultHeldSinceUtc { get; set; }
|
||||
|
||||
/// <summary>"True" or "False" compliance result (remediation detection / post-detection only).</summary>
|
||||
public string ComplianceResult { get; set; }
|
||||
|
||||
@@ -119,4 +162,14 @@ public class ScriptStartedInfo
|
||||
|
||||
/// <summary>Numeric IME PolicyType from the start line (captured as string), e.g. "6" for health scripts.</summary>
|
||||
public string PolicyType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Source timestamp of the start line when the signal is emitted later than it was read
|
||||
/// (a held start of a recurring health script, see <see cref="RecurringScriptGate"/>). Null
|
||||
/// for a start emitted while its own line is the tracker's last matched one.
|
||||
/// </summary>
|
||||
public System.DateTime? SourceTimestampUtc { get; set; }
|
||||
|
||||
/// <summary>Pattern id of the start line; set together with <see cref="SourceTimestampUtc"/>.</summary>
|
||||
public string PatternId { get; set; }
|
||||
}
|
||||
|
||||
+7
@@ -216,6 +216,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress => _provisioningTracker?.HasAccountSetupProgress ?? false;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ProvisioningStatusTracker.AccountSetupProgressIfRead"/>; <c>null</c> also when
|
||||
/// the provisioning tracker is not running (Device Preparation, before Start). Stamped on
|
||||
/// the WhiteGloveShellCoreSuccess signal for the sealing classifier.
|
||||
/// </summary>
|
||||
public bool? AccountSetupProgressIfRead => _provisioningTracker?.AccountSetupProgressIfRead;
|
||||
|
||||
/// <summary>
|
||||
/// True once WhiteGlove start has been detected (EventID 509 or persisted from prior run).
|
||||
/// Forwarded from ModernDeploymentTracker.
|
||||
|
||||
+126
-6
@@ -24,10 +24,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
/// <item><c>EspTrackingWin32Apps\<userGuid>\<appGuid>_<rev></c> — which apps IME
|
||||
/// registered for ESP tracking and in which phase.</item>
|
||||
/// <item><c>SideCarPolicies\StatusServiceReports\<userGuid>\<appId></c> — the exact
|
||||
/// AppInstallStatusReport the ESP page renders (Status 1000=Installed .. 3000=Failed).</item>
|
||||
/// AppInstallStatusReport the ESP page renders (Status 1000=Installed, 1001=Installing,
|
||||
/// 1003=InstallingPendingReboot, 2000=NotApplicable, 3000=Failed).</item>
|
||||
/// <item><c>Win32Apps\OperationalState\<userGuid>\<appGuid></c> (bare GUIDs) — IME's
|
||||
/// per-app operational state: the install deadline a downloaded app is waiting for
|
||||
/// (<c>ExecutionDeadlineTime</c>, IME 1.106+) and the app-in-use deferral counters
|
||||
/// (<c>DeferralsUsed</c>, <c>DeferUntilTime</c>, ..., IME 1.105+).</item>
|
||||
/// </list>
|
||||
/// The observer is snapshot-and-diff driven (RegistryWatcher gives key-scope edges only,
|
||||
/// coalesced — a per-write parse is impossible by design): every tick re-reads the three
|
||||
/// coalesced — a per-write parse is impossible by design): every tick re-reads the four
|
||||
/// surfaces and emits <c>registry_app_state</c> on real field changes. Pre-existing state at
|
||||
/// agent start is the silent baseline — Win32Apps keys survive re-enrollments, so replaying
|
||||
/// them as fresh events would be the registry twin of the historic-IME-replay bug.
|
||||
@@ -162,6 +167,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
ReadWin32Apps(root, snapshot);
|
||||
ReadEspTracking(root, snapshot);
|
||||
ReadStatusServiceReports(root, snapshot);
|
||||
ReadOperationalState(root, snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@@ -250,6 +256,42 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
}
|
||||
|
||||
// Only the two wait states are read; the download/execution bookkeeping next to them
|
||||
// (DownloadStatus, DownloadStartTime, ExecutionStatus, ...) duplicates the log narrative
|
||||
// and would double the event volume without adding a state the timeline lacks.
|
||||
private static void ReadOperationalState(RegistryKey root, ImeRegistrySnapshot snapshot)
|
||||
{
|
||||
using var operational = root.OpenSubKey(@"Win32Apps\OperationalState");
|
||||
if (operational == null) return;
|
||||
|
||||
foreach (var userName in operational.GetSubKeyNames())
|
||||
{
|
||||
if (!LooksLikeGuid(userName)) continue;
|
||||
using var userKey = operational.OpenSubKey(userName);
|
||||
if (userKey == null) continue;
|
||||
|
||||
foreach (var appKeyName in userKey.GetSubKeyNames())
|
||||
{
|
||||
var appId = ExtractAppId(appKeyName);
|
||||
if (appId == null) continue;
|
||||
|
||||
using var appKey = userKey.OpenSubKey(appKeyName);
|
||||
if (appKey == null) continue;
|
||||
|
||||
var deadline = TryParseRegistryDateTime(appKey.GetValue("ExecutionDeadlineTime"));
|
||||
var deferralsUsed = TryReadInt(appKey.GetValue("DeferralsUsed"));
|
||||
if (deadline == null && deferralsUsed == null) continue; // no wait state — no entry of its own
|
||||
|
||||
var entry = snapshot.GetOrAdd(userName, appId);
|
||||
entry.InstallDeadlineUtc = deadline;
|
||||
entry.DeferralsUsed = deferralsUsed;
|
||||
entry.DeferralMaxDeferrals = TryReadInt(appKey.GetValue("DeferralMaxDeferrals"));
|
||||
entry.DeferUntilUtc = TryParseRegistryDateTime(appKey.GetValue("DeferUntilTime"));
|
||||
entry.DeferralAutoDeferred = TryReadBool(appKey.GetValue("DeferralAutoDeferred"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── pure helpers (unit-tested directly) ─────────────────────────────────
|
||||
|
||||
internal static bool LooksLikeGuid(string name) =>
|
||||
@@ -301,6 +343,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool? TryReadBool(object? value) =>
|
||||
value is string s && bool.TryParse(s, out var parsed) ? parsed : (bool?)null;
|
||||
|
||||
/// <summary>
|
||||
/// OperationalState timestamps are UTC but stored in two InvariantCulture shapes:
|
||||
/// <c>ExecutionDeadlineTime</c> as <c>MM/dd/yyyy HH:mm:ss</c> without a kind marker,
|
||||
/// <c>DeferUntilTime</c> round-trip ("o", trailing Z). Both come back as UTC here.
|
||||
/// </summary>
|
||||
internal static DateTime? TryParseRegistryDateTime(object? value)
|
||||
{
|
||||
if (!(value is string s) || string.IsNullOrWhiteSpace(s)) return null;
|
||||
return DateTime.TryParse(s, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed)
|
||||
? parsed
|
||||
: (DateTime?)null;
|
||||
}
|
||||
|
||||
/// <summary>StateMessageEnforcementState bands (verified against decompiled IME 1.97/1.104).</summary>
|
||||
internal static string ClassifyEnforcementState(int state)
|
||||
{
|
||||
@@ -312,15 +371,59 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
/// <summary>AppInstallStatus (StatusService/ESP page): 1000er = installed, 3000 = failed.</summary>
|
||||
/// <summary>
|
||||
/// AppInstallStatus as IME writes it to StatusServiceReports (unchanged IME 1.50 .. 1.106):
|
||||
/// 1000 Installed, 1001 Installing, 1002 InstalledButDependenciesNotPresent,
|
||||
/// 1003 InstallingPendingReboot, 1004 InstalledPendingReboot, 2000 NotApplicable, 3000 Failed.
|
||||
/// The 1000 band is NOT uniformly terminal — IME maps every InProgress enforcement state to
|
||||
/// 1001 — so the mapping is explicit and an unknown value is not judged.
|
||||
/// </summary>
|
||||
internal static string? ClassifyStatusServiceStatus(int status)
|
||||
{
|
||||
if (status >= 1000 && status < 2000) return "installed";
|
||||
if (status == 3000) return "failed";
|
||||
switch (status)
|
||||
{
|
||||
case 1000:
|
||||
case 1002:
|
||||
case 1004:
|
||||
return "installed";
|
||||
case 1001:
|
||||
case 1003:
|
||||
return "installing";
|
||||
case 3000:
|
||||
return "failed";
|
||||
}
|
||||
if (status >= 2000 && status < 3000) return "notApplicable";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Human-readable suffix for the two IME wait states (install deadline, app-in-use
|
||||
/// deferral); empty when neither applies. Culture-invariant on purpose — the agent runs
|
||||
/// under whatever culture the SYSTEM account carries.
|
||||
/// </summary>
|
||||
internal static string DescribeWaitState(AppRegistryEntry entry)
|
||||
{
|
||||
var parts = new List<string>(2);
|
||||
if (entry.InstallDeadlineUtc is DateTime deadline)
|
||||
parts.Add("downloaded, install deadline " + FormatUtcMinute(deadline));
|
||||
|
||||
if (entry.DeferralsUsed is int used && used > 0)
|
||||
{
|
||||
var kind = entry.DeferralAutoDeferred == true ? "auto-deferred" : "deferred by user";
|
||||
var count = entry.DeferralMaxDeferrals is int max
|
||||
? used.ToString(CultureInfo.InvariantCulture) + "/" + max.ToString(CultureInfo.InvariantCulture)
|
||||
: used.ToString(CultureInfo.InvariantCulture);
|
||||
parts.Add(entry.DeferUntilUtc is DateTime until
|
||||
? kind + " " + count + " until " + FormatUtcMinute(until)
|
||||
: kind + " " + count);
|
||||
}
|
||||
|
||||
return parts.Count == 0 ? string.Empty : ", " + string.Join(", ", parts);
|
||||
}
|
||||
|
||||
private static string FormatUtcMinute(DateTime utc) =>
|
||||
utc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC";
|
||||
|
||||
internal static List<AppRegistryChange> DiffSnapshots(ImeRegistrySnapshot previous, ImeRegistrySnapshot next)
|
||||
{
|
||||
var changes = new List<AppRegistryChange>();
|
||||
@@ -343,6 +446,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
if (prev?.StatusServiceStatus != next.StatusServiceStatus) changed.Add("statusServiceStatus");
|
||||
if ((prev?.EspTracked ?? false) != next.EspTracked) changed.Add("espTracked");
|
||||
if (!string.Equals(prev?.EspPhase, next.EspPhase, StringComparison.OrdinalIgnoreCase)) changed.Add("espPhase");
|
||||
// Wait states: the deadline and each recorded deferral are transitions worth an event;
|
||||
// MaxDeferrals / AutoDeferred only travel along as data.
|
||||
if (prev?.InstallDeadlineUtc != next.InstallDeadlineUtc) changed.Add("installDeadline");
|
||||
if (prev?.DeferralsUsed != next.DeferralsUsed) changed.Add("deferralsUsed");
|
||||
if (prev?.DeferUntilUtc != next.DeferUntilUtc) changed.Add("deferUntil");
|
||||
return changed;
|
||||
}
|
||||
|
||||
@@ -445,6 +553,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
if (e.EspTracked) data["espTracked"] = "true";
|
||||
if (!string.IsNullOrEmpty(e.EspPhase)) data["espPhase"] = e.EspPhase!;
|
||||
if (e.InstallDeadlineUtc is DateTime deadline) data["installDeadlineUtc"] = deadline.ToString("o", CultureInfo.InvariantCulture);
|
||||
if (e.DeferralsUsed is int used) data["deferralsUsed"] = used.ToString(CultureInfo.InvariantCulture);
|
||||
if (e.DeferralMaxDeferrals is int max) data["deferralMaxDeferrals"] = max.ToString(CultureInfo.InvariantCulture);
|
||||
if (e.DeferUntilUtc is DateTime until) data["deferUntilUtc"] = until.ToString("o", CultureInfo.InvariantCulture);
|
||||
if (e.DeferralAutoDeferred is bool auto) data["deferralAutoDeferred"] = auto ? "true" : "false";
|
||||
|
||||
var summary = data.TryGetValue("enforcementClass", out var encls) ? encls
|
||||
: data.TryGetValue("statusServiceClass", out var sscls) ? sscls
|
||||
@@ -453,7 +566,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
_post.Emit(
|
||||
eventType: SharedEventTypes.RegistryAppState,
|
||||
source: SourceLabel,
|
||||
message: $"Registry app state: {e.AppId} ({(e.UserContext == ImeRegistrySnapshot.DeviceContext ? "device" : "user")}) -> {summary}",
|
||||
message: $"Registry app state: {e.AppId} ({(e.UserContext == ImeRegistrySnapshot.DeviceContext ? "device" : "user")}) -> {summary}{DescribeWaitState(e)}",
|
||||
severity: EventSeverity.Info,
|
||||
data: data,
|
||||
occurredAtUtc: nowUtc);
|
||||
@@ -625,6 +738,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
public int? StatusServiceStatus { get; set; }
|
||||
public bool EspTracked { get; set; }
|
||||
public string? EspPhase { get; set; }
|
||||
|
||||
// Win32Apps\OperationalState — the two IME wait states (all UTC).
|
||||
public DateTime? InstallDeadlineUtc { get; set; }
|
||||
public int? DeferralsUsed { get; set; }
|
||||
public int? DeferralMaxDeferrals { get; set; }
|
||||
public DateTime? DeferUntilUtc { get; set; }
|
||||
public bool? DeferralAutoDeferred { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class AppRegistryChange
|
||||
|
||||
+19
-6
@@ -254,16 +254,27 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
/// host to tell the real user-ESP page exit from the Device→Account handoff exit; not a
|
||||
/// completion input.
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress
|
||||
public bool HasAccountSetupProgress => AccountSetupProgressIfRead == true;
|
||||
|
||||
/// <summary>
|
||||
/// Tri-state form of <see cref="HasAccountSetupProgress"/>: <c>null</c> until the tracker
|
||||
/// has actually read AccountSetup subcategories (not started yet, category not written,
|
||||
/// empty), otherwise whether one has left <c>notStarted</c>. The WhiteGlove sealing
|
||||
/// classifier treats only a read <c>false</c> as "user ESP untouched" — an unread
|
||||
/// registry must never pass for an untouched one.
|
||||
/// </summary>
|
||||
public bool? AccountSetupProgressIfRead
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
if (_lastSubcategoryStates == null)
|
||||
return false;
|
||||
if (!_lastSubcategoryStates.TryGetValue("AccountSetupCategory.Status", out var subs) || subs == null)
|
||||
return false;
|
||||
return null;
|
||||
if (!_lastSubcategoryStates.TryGetValue("AccountSetupCategory.Status", out var subs)
|
||||
|| subs == null
|
||||
|| subs.Count == 0)
|
||||
return null;
|
||||
foreach (var state in subs.Values)
|
||||
{
|
||||
if (!string.Equals(state, "notStarted", StringComparison.OrdinalIgnoreCase))
|
||||
@@ -279,7 +290,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
/// with subcategoryState=succeeded. NOT a WhiteGlove indicator: on Win11 25H2 (build
|
||||
/// 26200+) Windows writes this property as a trivially-succeeding step in EVERY
|
||||
/// enrollment (validated 2026-08-18 — user-driven sessions f475e697/c601a24b/4219203f
|
||||
/// all carry it). Kept for observability only (whiteglove_signal_* raw dumps); must not
|
||||
/// all carry it). Kept for observability only (save_result_step_* raw dumps); must not
|
||||
/// be used for classification. Reliable WhiteGlove anchors are ModernDeployment
|
||||
/// EventID 509 and the Shell-Core WhiteGlove-success events.
|
||||
/// </summary>
|
||||
@@ -966,8 +977,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
_logger.Info($"ProvisioningStatusTracker: SaveWhiteGloveSuccessResult state " +
|
||||
$"transition: {previousState} -> {state}");
|
||||
|
||||
// Neutral trigger name: the step exists in every 25H2 enrollment,
|
||||
// and "whiteglove_*" was read as a pre-provisioning signal.
|
||||
EmitRawRegistryDump(categoryLabel, jsonValue,
|
||||
$"whiteglove_signal_{state}");
|
||||
$"save_result_step_{state}");
|
||||
|
||||
if (string.Equals(state, "succeeded", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
|
||||
+70
-28
@@ -99,7 +99,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
|
||||
/// <summary>
|
||||
/// Packaging problems that are not cap skips, per kind: <c>path-guard</c> (configured path
|
||||
/// refused), <c>no-user-session</c> (user-profile token without a signed-in user),
|
||||
/// or hard-blocked event log refused),<c>no-user-session</c> (user-profile token without a signed-in user),
|
||||
/// <c>folder-rejected</c>, <c>enumerate</c>, <c>open</c>, <c>copy</c>.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, int> ProblemsByKind { get; set; } = Empty;
|
||||
@@ -145,6 +145,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// exact point production is exposed. Null in production.
|
||||
internal Action<string> BeforeSourceFileOpen { get; set; }
|
||||
|
||||
// Test seam: which channel writes to an .evtx file. Production asks the registered
|
||||
// channels; a test cannot register one.
|
||||
internal Func<string, string> EventLogChannelResolver { get; set; } = ResolveChannelForEvtxFile;
|
||||
|
||||
// Tracks per-build inclusion totals + skip reasons. Threaded through every
|
||||
// AddLogFiles call so caps are global across all sections, not per section.
|
||||
private sealed class BudgetTracker
|
||||
@@ -462,17 +466,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// 3. Configured additional log paths (global + tenant, validated by guards)
|
||||
foreach (var entry in _configuration.DiagnosticsLogPaths ?? new System.Collections.Generic.List<Shared.Models.DiagnosticsLogPath>())
|
||||
{
|
||||
// Resolve %LOGGED_ON_USER_PROFILE% token and get profile path for guard exception
|
||||
// The profile path only lifts the C:\Users block for entries that use the token.
|
||||
var userProfilePath = UserProfileResolver.ContainsUserProfileToken(entry.Path)
|
||||
? UserProfileResolver.GetLoggedOnUserProfilePath() : null;
|
||||
|
||||
if (!DiagnosticsPathGuards.IsDiagnosticsPathAllowed(entry.Path, _configuration.UnrestrictedMode, userProfilePath))
|
||||
{
|
||||
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
|
||||
ManifestLine($"BLOCKED (path guard): {entry.Path}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
continue;
|
||||
}
|
||||
// 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);
|
||||
if (expandedPath == null)
|
||||
{
|
||||
@@ -481,13 +480,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
tracker.RecordProblem("no-user-session");
|
||||
continue;
|
||||
}
|
||||
var folder = Path.GetDirectoryName(expandedPath);
|
||||
var pattern = Path.GetFileName(expandedPath);
|
||||
if (string.IsNullOrEmpty(folder)) continue;
|
||||
if (string.IsNullOrEmpty(pattern) || !pattern.Contains(".")) pattern = "*";
|
||||
var zipFolder = $"AdditionalLogs/{Path.GetFileName(folder)}";
|
||||
ManifestLine($"CONFIGURED PATH: '{entry.Path}' -> folder='{folder}' pattern='{pattern}'");
|
||||
AddLogFiles(archive, folder, zipFolder, pattern, tracker, entry.IncludeSubfolders);
|
||||
|
||||
// The guard validates the folder that gets enumerated — never a path
|
||||
// derived from the validated one afterwards.
|
||||
if (!DiagnosticsPathGuards.TryResolveCollectionTarget(
|
||||
expandedPath, entry.IncludeSubfolders, _configuration.UnrestrictedMode, userProfilePath, out var target))
|
||||
{
|
||||
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
|
||||
ManifestLine($"BLOCKED (path guard): {entry.Path}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
continue;
|
||||
}
|
||||
|
||||
var unrestrictedMode = _configuration.UnrestrictedMode;
|
||||
var zipFolder = $"AdditionalLogs/{Path.GetFileName(target.Folder)}";
|
||||
ManifestLine($"CONFIGURED PATH: '{entry.Path}' -> folder='{target.Folder}' pattern='{target.Pattern}' recursive={target.Recurse}");
|
||||
AddLogFiles(archive, target.Folder, zipFolder, target.Pattern, tracker, target.Recurse,
|
||||
dir => DiagnosticsPathGuards.IsDirectoryEnterable(dir, unrestrictedMode, userProfilePath));
|
||||
}
|
||||
|
||||
// Packaging manifest — always written, even when empty of problems, so its
|
||||
@@ -617,14 +626,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// Recursive enumeration that skips reparse-point directories. Materializes the
|
||||
// result into a list so the caller can iterate without holding a directory handle.
|
||||
// Errors during enumeration are swallowed (logged via _logger by the caller).
|
||||
private static List<string> EnumerateFilesNoReparseDirs(string folder, string pattern, bool recurse)
|
||||
// mayEnterDirectory (configured paths only) is asked for every subdirectory before the
|
||||
// walk descends: a hard-blocked subtree can sit below a folder that passed the guard.
|
||||
internal static List<string> EnumerateFilesNoReparseDirs(string folder, string pattern, bool recurse,
|
||||
Func<string, bool> mayEnterDirectory, List<string> refusedDirectories)
|
||||
{
|
||||
var result = new List<string>();
|
||||
CollectFilesNoReparseDirs(folder, pattern, recurse, result);
|
||||
CollectFilesNoReparseDirs(folder, pattern, recurse, mayEnterDirectory, refusedDirectories, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void CollectFilesNoReparseDirs(string folder, string pattern, bool recurse, List<string> result)
|
||||
private static void CollectFilesNoReparseDirs(string folder, string pattern, bool recurse,
|
||||
Func<string, bool> mayEnterDirectory, List<string> refusedDirectories, List<string> result)
|
||||
{
|
||||
string[] files;
|
||||
try { files = Directory.GetFiles(folder, pattern, SearchOption.TopDirectoryOnly); }
|
||||
@@ -643,12 +656,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
try { attrs = File.GetAttributes(sub); }
|
||||
catch { continue; }
|
||||
if (IsReparsePoint(attrs)) continue;
|
||||
CollectFilesNoReparseDirs(sub, pattern, recurse: true, result);
|
||||
if (mayEnterDirectory != null && !mayEnterDirectory(sub))
|
||||
{
|
||||
refusedDirectories.Add(sub);
|
||||
continue;
|
||||
}
|
||||
CollectFilesNoReparseDirs(sub, pattern, recurse: true, mayEnterDirectory, refusedDirectories, result);
|
||||
}
|
||||
}
|
||||
|
||||
private void AddLogFiles(ZipArchive archive, string sourceFolder, string zipFolder, string searchPattern,
|
||||
BudgetTracker tracker, bool includeSubfolders = false)
|
||||
BudgetTracker tracker, bool includeSubfolders = false, Func<string, bool> mayEnterDirectory = null)
|
||||
{
|
||||
// The folder stays pinned (open handle) for this whole section. The path guards and
|
||||
// the enumeration below only ever judge path strings; every byte that reaches the
|
||||
@@ -673,9 +691,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
}
|
||||
|
||||
List<string> files;
|
||||
var refusedDirectories = new List<string>();
|
||||
try
|
||||
{
|
||||
files = EnumerateFilesNoReparseDirs(pinned.LexicalPath, searchPattern, includeSubfolders);
|
||||
files = EnumerateFilesNoReparseDirs(pinned.LexicalPath, searchPattern, includeSubfolders,
|
||||
mayEnterDirectory, refusedDirectories);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -685,6 +705,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
return;
|
||||
}
|
||||
|
||||
// Expected outcome, not a packaging problem: the subtree is off limits by design.
|
||||
foreach (var refused in refusedDirectories)
|
||||
{
|
||||
_logger.Info($"Diagnostics subfolder skipped by guard: {refused}");
|
||||
ManifestLine($"SKIPPED DIR (path guard): {refused}");
|
||||
}
|
||||
|
||||
if (files.Count == 0)
|
||||
ManifestLine($"NO MATCH: {sourceFolder} pattern '{searchPattern}'");
|
||||
|
||||
@@ -704,7 +731,22 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// the tenant-configured BootstrapperAgent channel never made it into the ZIP.
|
||||
if (file.EndsWith(".evtx", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
tempExport = TryExportEventLogChannel(file);
|
||||
// Hard-blocked channels are refused for every source and in every mode,
|
||||
// by file name AND by the channel the export would read: the path guard
|
||||
// cannot judge what a wildcard or folder entry resolves to, and the %4
|
||||
// fallback of the resolver turns a "Security.evtx" in any allowed folder
|
||||
// into the live Security channel.
|
||||
var channel = EventLogChannelResolver(file);
|
||||
if (DiagnosticsPathGuards.IsHardBlockedEventLogFile(file) ||
|
||||
GatherRuleGuards.IsHardBlockedEventLogChannel(channel))
|
||||
{
|
||||
_logger.Warning($"Event log blocked by channel guard (channel '{channel}'): {file}");
|
||||
ManifestLine($"BLOCKED (event-log channel guard, channel '{channel}'): {file}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
return;
|
||||
}
|
||||
|
||||
tempExport = TryExportEventLogChannel(file, channel);
|
||||
if (tempExport == null)
|
||||
{
|
||||
// Export failed (channel not resolvable / wevtutil error) — fall through
|
||||
@@ -850,16 +892,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
/// <summary>
|
||||
/// Exports the event-log channel behind a winevt .evtx file to a temp copy via
|
||||
/// <c>wevtutil epl</c> (active channels hold their file exclusively locked, so a raw
|
||||
/// copy fails). Channel resolution happens against the registered channels — see
|
||||
/// <see cref="ResolveChannelForEvtxFile"/>. Returns the temp file path (caller deletes)
|
||||
/// or null when the export failed.
|
||||
/// copy fails). The caller resolved <paramref name="channel"/> against the registered
|
||||
/// channels — see <see cref="ResolveChannelForEvtxFile"/> — and checked it against the
|
||||
/// hard-blocked channels. Returns the temp file path (caller deletes) or null when the
|
||||
/// export failed.
|
||||
/// </summary>
|
||||
private string TryExportEventLogChannel(string evtxPath)
|
||||
private string TryExportEventLogChannel(string evtxPath, string channel)
|
||||
{
|
||||
string tempPath = null;
|
||||
try
|
||||
{
|
||||
var channel = ResolveChannelForEvtxFile(evtxPath);
|
||||
tempPath = Path.Combine(Path.GetTempPath(), $"am-evtx-{Guid.NewGuid():N}.evtx");
|
||||
var psi = new System.Diagnostics.ProcessStartInfo
|
||||
{
|
||||
|
||||
+209
-45
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
{
|
||||
@@ -124,51 +125,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
if (IsSymlinkOrReparsePoint(normalizedDir))
|
||||
return false;
|
||||
|
||||
// C:\Users block always applies (even in unrestricted mode)
|
||||
// Exception: paths under <userProfilePath>\AppData\Local or AppData\Roaming
|
||||
// are allowed when the %LOGGED_ON_USER_PROFILE% token was used.
|
||||
if (normalizedDir.StartsWith(BlockedUsersPrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == BlockedUsersPrefix.Length ||
|
||||
normalizedDir[BlockedUsersPrefix.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
if (!GatherRuleGuards.IsUserProfileSubpathAllowed(normalizedDir, userProfilePath))
|
||||
return false;
|
||||
}
|
||||
|
||||
// Additional hard-blocked paths (even in unrestricted mode)
|
||||
foreach (var blocked in AdditionalHardBlockedPrefixes)
|
||||
{
|
||||
var normalizedBlocked = Path.GetFullPath(blocked);
|
||||
if (normalizedDir.StartsWith(normalizedBlocked, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == normalizedBlocked.Length ||
|
||||
normalizedDir[normalizedBlocked.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// In unrestricted mode, everything except hard-blocked paths is allowed
|
||||
if (unrestrictedMode)
|
||||
return true;
|
||||
|
||||
foreach (var prefix in AllowedDiagnosticsPathPrefixes)
|
||||
{
|
||||
var normalizedPrefix = Path.GetFullPath(prefix);
|
||||
if (normalizedDir.StartsWith(normalizedPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Segment-bounded: next char must be '\' or end-of-string
|
||||
if (normalizedDir.Length == normalizedPrefix.Length ||
|
||||
normalizedDir[normalizedPrefix.Length] == Path.DirectorySeparatorChar)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vendor folders under the signed-in user's profile — same allowlist the file
|
||||
// collectors use, since it answers the same question: which folders below a
|
||||
// profile carry enrollment-relevant logs rather than the user's own data.
|
||||
return GatherRuleGuards.IsUserProfilePathOnAllowlist(normalizedDir, userProfilePath);
|
||||
return IsNormalizedPathAllowed(normalizedDir, unrestrictedMode, userProfilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -177,6 +134,213 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the package actually reads for one configured entry: every file matching
|
||||
/// <see cref="Pattern"/> in <see cref="Folder"/>, optionally below it.
|
||||
/// </summary>
|
||||
public sealed class CollectionTarget
|
||||
{
|
||||
public CollectionTarget(string folder, string pattern, bool recurse)
|
||||
{
|
||||
Folder = folder;
|
||||
Pattern = pattern;
|
||||
Recurse = recurse;
|
||||
}
|
||||
|
||||
/// <summary>Full path without a trailing separator (drive roots keep theirs).</summary>
|
||||
public string Folder { get; }
|
||||
public string Pattern { get; }
|
||||
public bool Recurse { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a configured entry to the folder and pattern that get enumerated, and
|
||||
/// validates exactly that. Returns false when the guard refuses the entry.
|
||||
///
|
||||
/// <paramref name="expandedPath"/> must already have the %LOGGED_ON_USER_PROFILE% token
|
||||
/// resolved: validating the raw token would judge a different path than the one read.
|
||||
///
|
||||
/// A wildcard in the last segment selects files in its parent folder. A trailing
|
||||
/// separator or an existing directory selects every file in that folder. Anything else
|
||||
/// names one file — validated as that file and never recursed, because its parent
|
||||
/// folder has not passed the guard. The filesystem decides folder-vs-file, never the
|
||||
/// spelling of the last segment.
|
||||
/// </summary>
|
||||
public static bool TryResolveCollectionTarget(
|
||||
string expandedPath,
|
||||
bool includeSubfolders,
|
||||
bool unrestrictedMode,
|
||||
string userProfilePath,
|
||||
out CollectionTarget target)
|
||||
=> TryResolveCollectionTarget(
|
||||
expandedPath, includeSubfolders, unrestrictedMode, userProfilePath, Directory.Exists, out target);
|
||||
|
||||
internal static bool TryResolveCollectionTarget(
|
||||
string expandedPath,
|
||||
bool includeSubfolders,
|
||||
bool unrestrictedMode,
|
||||
string userProfilePath,
|
||||
Func<string, bool> directoryExists,
|
||||
out CollectionTarget target)
|
||||
{
|
||||
target = null;
|
||||
if (string.IsNullOrWhiteSpace(expandedPath))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var expanded = Environment.ExpandEnvironmentVariables(expandedPath.Trim());
|
||||
var lastSegment = Path.GetFileName(expanded);
|
||||
|
||||
if (lastSegment.Contains('*') || lastSegment.Contains('?'))
|
||||
{
|
||||
var parent = Path.GetDirectoryName(expanded);
|
||||
if (string.IsNullOrEmpty(parent))
|
||||
return false;
|
||||
var folder = TrimTrailingSeparators(Path.GetFullPath(parent));
|
||||
if (!IsDiagnosticsPathAllowed(folder, unrestrictedMode, userProfilePath))
|
||||
return false;
|
||||
target = new CollectionTarget(folder, lastSegment, includeSubfolders);
|
||||
return true;
|
||||
}
|
||||
|
||||
var full = TrimTrailingSeparators(Path.GetFullPath(expanded));
|
||||
if (!IsDiagnosticsPathAllowed(full, unrestrictedMode, userProfilePath))
|
||||
return false;
|
||||
|
||||
if (lastSegment.Length == 0 || directoryExists(full))
|
||||
{
|
||||
target = new CollectionTarget(full, "*", includeSubfolders);
|
||||
return true;
|
||||
}
|
||||
|
||||
var fileFolder = Path.GetDirectoryName(full);
|
||||
if (string.IsNullOrEmpty(fileFolder))
|
||||
return false;
|
||||
target = new CollectionTarget(fileFolder, Path.GetFileName(full), recurse: false);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
target = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Guard for every subdirectory a recursive collection is about to enter. The start
|
||||
/// folder passed <see cref="IsDiagnosticsPathAllowed(string, bool, string)"/>, but a
|
||||
/// hard-blocked subtree can sit below an allowed folder (unrestricted mode, drive
|
||||
/// root). Lexical only: reparse points are skipped by the enumeration and refused
|
||||
/// again on the handle that is read.
|
||||
/// </summary>
|
||||
public static bool IsDirectoryEnterable(string directory, bool unrestrictedMode, string userProfilePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(directory))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return IsNormalizedPathAllowed(Path.GetFullPath(directory), unrestrictedMode, userProfilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string TrimTrailingSeparators(string fullPath)
|
||||
{
|
||||
var root = Path.GetPathRoot(fullPath);
|
||||
var trimmed = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
return root != null && trimmed.Length < root.Length ? root : trimmed;
|
||||
}
|
||||
|
||||
// Hard blocks, then (restricted mode) the allowlists — on an already normalized path.
|
||||
private static bool IsNormalizedPathAllowed(string normalizedDir, bool unrestrictedMode, string userProfilePath)
|
||||
{
|
||||
// C:\Users block always applies (even in unrestricted mode)
|
||||
// Exception: paths under <userProfilePath>\AppData\Local or AppData\Roaming
|
||||
// are allowed when the %LOGGED_ON_USER_PROFILE% token was used.
|
||||
if (normalizedDir.StartsWith(BlockedUsersPrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == BlockedUsersPrefix.Length ||
|
||||
normalizedDir[BlockedUsersPrefix.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
if (!GatherRuleGuards.IsUserProfileSubpathAllowed(normalizedDir, userProfilePath))
|
||||
return false;
|
||||
}
|
||||
|
||||
// Additional hard-blocked paths (even in unrestricted mode)
|
||||
foreach (var blocked in AdditionalHardBlockedPrefixes)
|
||||
{
|
||||
var normalizedBlocked = Path.GetFullPath(blocked);
|
||||
if (normalizedDir.StartsWith(normalizedBlocked, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == normalizedBlocked.Length ||
|
||||
normalizedDir[normalizedBlocked.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Hard-blocked event logs (even in unrestricted mode). Only a path that names the
|
||||
// file is caught here; a wildcard or folder entry is judged per file by
|
||||
// DiagnosticsPackageService, which is the enforcement point.
|
||||
if (IsHardBlockedEventLogFile(normalizedDir))
|
||||
return false;
|
||||
|
||||
// In unrestricted mode, everything except hard-blocked paths is allowed
|
||||
if (unrestrictedMode)
|
||||
return true;
|
||||
|
||||
foreach (var prefix in AllowedDiagnosticsPathPrefixes)
|
||||
{
|
||||
var normalizedPrefix = Path.GetFullPath(prefix);
|
||||
if (normalizedDir.StartsWith(normalizedPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Segment-bounded: next char must be '\' or end-of-string
|
||||
if (normalizedDir.Length == normalizedPrefix.Length ||
|
||||
normalizedDir[normalizedPrefix.Length] == Path.DirectorySeparatorChar)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vendor folders under the signed-in user's profile — same allowlist the file
|
||||
// collectors use, since it answers the same question: which folders below a
|
||||
// profile carry enrollment-relevant logs rather than the user's own data.
|
||||
return GatherRuleGuards.IsUserProfilePathOnAllowlist(normalizedDir, userProfilePath);
|
||||
}
|
||||
|
||||
// Windows archives a full channel as "Archive-<file name>-yyyy-MM-dd-HH-mm-ss-fff.evtx".
|
||||
private static readonly Regex ArchivedEventLogRegex = new Regex(
|
||||
@"^Archive-(.+)-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}-\d{3}$",
|
||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// True when the .evtx file name belongs to one of
|
||||
/// <see cref="GatherRuleGuards.HardBlockedEventLogChannels"/> — live file
|
||||
/// ("Microsoft-Windows-PowerShell%4Operational.evtx", where %4 encodes '/') or
|
||||
/// archived copy. Judges the NAME only; a channel may write to a file that does not
|
||||
/// follow the convention, so the packager also checks the channel it resolved.
|
||||
/// </summary>
|
||||
internal static bool IsHardBlockedEventLogFile(string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
return false;
|
||||
|
||||
var name = Path.GetFileName(path);
|
||||
if (!name.EndsWith(".evtx", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
var stem = name.Substring(0, name.Length - ".evtx".Length);
|
||||
var archived = ArchivedEventLogRegex.Match(stem);
|
||||
if (archived.Success)
|
||||
stem = archived.Groups[1].Value;
|
||||
|
||||
return GatherRuleGuards.IsHardBlockedEventLogChannel(stem.Replace("%4", "/"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether any component of the path (directories or file) is a symlink,
|
||||
/// junction, or other reparse point. Returns true if a reparse point is detected.
|
||||
|
||||
+16
-5
@@ -451,11 +451,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
var trimmed = channel.Trim();
|
||||
|
||||
// Hard blocks apply even in unrestricted mode
|
||||
foreach (var blocked in HardBlockedEventLogChannels)
|
||||
{
|
||||
if (MatchesChannel(trimmed, blocked))
|
||||
return false;
|
||||
}
|
||||
if (IsHardBlockedEventLogChannel(trimmed))
|
||||
return false;
|
||||
|
||||
if (unrestrictedMode)
|
||||
return true;
|
||||
@@ -463,6 +460,20 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
return AllowedEventLogChannels.Any(allowed => MatchesChannel(trimmed, allowed));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the channel is one of <see cref="HardBlockedEventLogChannels"/>. Every
|
||||
/// path that can read an event log asks here — the event-log collector and the
|
||||
/// diagnostics package alike — so the block cannot hold in one and leak through another.
|
||||
/// </summary>
|
||||
internal static bool IsHardBlockedEventLogChannel(string channel)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(channel))
|
||||
return false;
|
||||
|
||||
var trimmed = channel.Trim();
|
||||
return HardBlockedEventLogChannels.Any(blocked => MatchesChannel(trimmed, blocked));
|
||||
}
|
||||
|
||||
private static bool MatchesChannel(string channel, string prefix)
|
||||
=> channel.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(channel.Length == prefix.Length || channel[prefix.Length] == '/');
|
||||
|
||||
+6
@@ -209,6 +209,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
|
||||
data["ime_line_budget_breaks"] = health.BudgetBreaks;
|
||||
data["ime_held_tails"] = health.HeldTails;
|
||||
data["ime_unanchored_patterns"] = health.UnanchoredPatterns;
|
||||
data["ime_overwrite_rewinds"] = health.OverwriteRewinds;
|
||||
data["ime_overwrite_bytes_reprocessed"] = health.OverwriteBytesReprocessed;
|
||||
data["ime_verify_passes"] = health.VerifyPasses;
|
||||
data["ime_verified_bytes"] = health.VerifiedBytes;
|
||||
data["ime_pass_max_ms"] = health.PassMaxMs;
|
||||
data["ime_pass_gap_max_ms"] = health.PassGapMaxMs;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -237,6 +237,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
using (response)
|
||||
{
|
||||
await ThrowOnAuthFailureAsync(response).ConfigureAwait(false);
|
||||
await ThrowOnCodedConflictAsync(response).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var responseJson = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
@@ -338,6 +339,38 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
errorCode: errorCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws <see cref="BackendRefusalException"/> for a 409 whose JSON body carries a
|
||||
/// machine-readable <c>errorCode</c> — register-session answers
|
||||
/// <c>session_owner_mismatch</c> when another tenant claimed the session id, which no retry
|
||||
/// can clear but a session rotation can. A 409 without a code falls through to
|
||||
/// <c>EnsureSuccessStatusCode</c> as before.
|
||||
/// </summary>
|
||||
private static async Task ThrowOnCodedConflictAsync(HttpResponseMessage response)
|
||||
{
|
||||
if (response.StatusCode != System.Net.HttpStatusCode.Conflict)
|
||||
return;
|
||||
|
||||
string body = null;
|
||||
try
|
||||
{
|
||||
body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// No body, no code — the generic 409 handling applies.
|
||||
}
|
||||
|
||||
var errorCode = TryExtractErrorCode(body);
|
||||
if (errorCode == null)
|
||||
return;
|
||||
|
||||
throw new BackendRefusalException(
|
||||
$"Backend returned 409 Conflict with error code {errorCode}.",
|
||||
(int)response.StatusCode,
|
||||
errorCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pulls <c>errorCode</c> out of a backend JSON error body. Tolerant: any parse failure
|
||||
/// or a non-string value yields null, never an exception.
|
||||
@@ -471,4 +504,24 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
ErrorCode = errorCode;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Thrown when the backend refuses a request on a non-auth status (409) with a machine-readable
|
||||
/// code from Shared <c>Constants.AgentErrorCodes</c>. Unlike <see cref="BackendAuthException"/>
|
||||
/// it says nothing about the device's authorization and must never feed the auth-failure tracker.
|
||||
/// </summary>
|
||||
public class BackendRefusalException : Exception
|
||||
{
|
||||
/// <summary>HTTP status code returned by the backend (409).</summary>
|
||||
public int StatusCode { get; }
|
||||
|
||||
/// <summary>Machine-readable code from the backend's JSON body (never null).</summary>
|
||||
public string ErrorCode { get; }
|
||||
|
||||
public BackendRefusalException(string message, int statusCode, string errorCode) : base(message)
|
||||
{
|
||||
StatusCode = statusCode;
|
||||
ErrorCode = errorCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
/// exist for callers whose process is about to exit and cannot come back later
|
||||
/// (emergency break): retries stay INSIDE the one reservation, so they never
|
||||
/// multiply against the per-session budget.
|
||||
///
|
||||
/// <paramref name="sessionAgeHours"/> is the emergency break's measured session age
|
||||
/// (<see cref="AgentErrorReport.SessionAgeHours"/>) and <paramref name="priorRegistrationFailure"/>
|
||||
/// its record of earlier starts that never registered
|
||||
/// (<see cref="AgentErrorReport.PriorRegistrationFailure"/>); null for every other error type.
|
||||
/// </summary>
|
||||
public virtual async Task TrySendAsync(
|
||||
AgentErrorType errorType,
|
||||
@@ -87,7 +92,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
long? sequenceNumber = null,
|
||||
int attempts = 1,
|
||||
TimeSpan? perAttemptTimeout = null,
|
||||
TimeSpan? retryDelay = null)
|
||||
TimeSpan? retryDelay = null,
|
||||
double? sessionAgeHours = null,
|
||||
RegistrationFailureSummary priorRegistrationFailure = null)
|
||||
{
|
||||
// Deduplicate by error type + status code: same failure category sent only once per session.
|
||||
// All anti-flood checks are protected by a lock to prevent race conditions when
|
||||
@@ -135,6 +142,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
Message = message,
|
||||
HttpStatusCode = httpStatusCode,
|
||||
SequenceNumber = sequenceNumber,
|
||||
SessionAgeHours = sessionAgeHours,
|
||||
PriorRegistrationFailure = priorRegistrationFailure,
|
||||
AgentVersion = _agentVersion,
|
||||
Timestamp = DateTime.UtcNow
|
||||
};
|
||||
|
||||
+87
-68
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -25,6 +26,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
/// </summary>
|
||||
public string Ip { get; set; }
|
||||
|
||||
/// <summary>"City, Region, Country" without the parts a provider did not return.</summary>
|
||||
public string Describe() =>
|
||||
string.Join(", ", new[] { City, Region, Country }.Where(p => !string.IsNullOrEmpty(p)));
|
||||
|
||||
public Dictionary<string, object> ToDictionary()
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
@@ -45,6 +50,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
public string PrimaryError { get; set; }
|
||||
public string PrimaryRetryError { get; set; }
|
||||
public string FallbackError { get; set; }
|
||||
public string DoGeoError { get; set; }
|
||||
}
|
||||
|
||||
public static class GeoLocationService
|
||||
@@ -52,6 +58,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(5);
|
||||
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(2);
|
||||
|
||||
internal const string IpInfoUrl = "https://ipinfo.io/json";
|
||||
internal const string IfConfigCoUrl = "https://ifconfig.co/json";
|
||||
|
||||
/// <summary>
|
||||
/// Delivery Optimization's own geo endpoint. Country and egress IP only (no region, city,
|
||||
/// coordinates or timezone), but it is part of the Windows Update / DO endpoint set that
|
||||
/// Autopilot needs anyway, so it stays reachable in networks that block public geo services.
|
||||
/// </summary>
|
||||
internal const string DoGeoUrl = "https://geo.prod.do.dsp.mp.microsoft.com/geo";
|
||||
|
||||
// Static HttpClient to avoid socket exhaustion from repeated short-lived instances.
|
||||
// HttpClient is designed to be reused across requests.
|
||||
private static readonly HttpClient SharedHttpClient = CreateSharedHttpClient();
|
||||
@@ -68,7 +84,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
var attempt = new GeoLocationAttemptResult();
|
||||
|
||||
// Try ipinfo.io first
|
||||
var (result, error) = await TryIpInfo(logger);
|
||||
var (result, error) = await TryProvider("ipinfo.io", IpInfoUrl, ParseIpInfo, logger);
|
||||
if (result != null)
|
||||
{
|
||||
attempt.Location = result;
|
||||
@@ -80,7 +96,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
logger?.Info($"GeoLocation: Retrying ipinfo.io after {RetryDelay.TotalSeconds}s...");
|
||||
await Task.Delay(RetryDelay);
|
||||
|
||||
(result, error) = await TryIpInfo(logger);
|
||||
(result, error) = await TryProvider("ipinfo.io", IpInfoUrl, ParseIpInfo, logger);
|
||||
if (result != null)
|
||||
{
|
||||
attempt.Location = result;
|
||||
@@ -89,7 +105,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
attempt.PrimaryRetryError = error;
|
||||
|
||||
// Fallback to ifconfig.co
|
||||
(result, error) = await TryIfConfigCo(logger);
|
||||
(result, error) = await TryProvider("ifconfig.co", IfConfigCoUrl, ParseIfConfigCo, logger);
|
||||
if (result != null)
|
||||
{
|
||||
attempt.Location = result;
|
||||
@@ -97,108 +113,111 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
|
||||
}
|
||||
attempt.FallbackError = error;
|
||||
|
||||
// Last resort: Delivery Optimization geo — country only, but better than no location
|
||||
(result, error) = await TryProvider("do-geo", DoGeoUrl, ParseDoGeo, logger);
|
||||
if (result != null)
|
||||
{
|
||||
attempt.Location = result;
|
||||
return attempt;
|
||||
}
|
||||
attempt.DoGeoError = error;
|
||||
|
||||
logger?.Warning("GeoLocation: All providers failed, skipping location event");
|
||||
return attempt;
|
||||
}
|
||||
|
||||
private static async Task<(GeoLocationResult result, string error)> TryIpInfo(AgentLogger logger)
|
||||
private static async Task<(GeoLocationResult result, string error)> TryProvider(
|
||||
string name, string url, Func<JObject, GeoLocationResult> parse, AgentLogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger?.Info("GeoLocation: Querying ipinfo.io...");
|
||||
logger?.Info($"GeoLocation: Querying {name}...");
|
||||
|
||||
using (var httpResponse = await SharedHttpClient.GetAsync("https://ipinfo.io/json"))
|
||||
using (var httpResponse = await SharedHttpClient.GetAsync(url))
|
||||
{
|
||||
if (!httpResponse.IsSuccessStatusCode)
|
||||
{
|
||||
var error = $"HTTP {(int)httpResponse.StatusCode} ({httpResponse.ReasonPhrase})";
|
||||
logger?.Warning($"GeoLocation: ipinfo.io failed: {error}");
|
||||
logger?.Warning($"GeoLocation: {name} failed: {error}");
|
||||
return (null, error);
|
||||
}
|
||||
|
||||
var response = await httpResponse.Content.ReadAsStringAsync();
|
||||
var json = JObject.Parse(response);
|
||||
|
||||
var result = new GeoLocationResult
|
||||
var result = parse(JObject.Parse(response));
|
||||
if (result == null)
|
||||
{
|
||||
Country = json.Value<string>("country"),
|
||||
Region = json.Value<string>("region"),
|
||||
City = json.Value<string>("city"),
|
||||
Loc = json.Value<string>("loc"),
|
||||
Timezone = json.Value<string>("timezone"),
|
||||
Ip = json.Value<string>("ip"),
|
||||
Source = "ipinfo"
|
||||
};
|
||||
var error = "No country in response";
|
||||
logger?.Warning($"GeoLocation: {name} failed: {error}");
|
||||
return (null, error);
|
||||
}
|
||||
|
||||
logger?.Info($"GeoLocation: ipinfo.io returned {result.City}, {result.Region}, {result.Country}");
|
||||
logger?.Info($"GeoLocation: {name} returned {result.Describe()}");
|
||||
return (result, null);
|
||||
}
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
var error = "Timeout (5s)";
|
||||
logger?.Warning($"GeoLocation: ipinfo.io failed: {error}");
|
||||
var error = $"Timeout ({RequestTimeout.TotalSeconds}s)";
|
||||
logger?.Warning($"GeoLocation: {name} failed: {error}");
|
||||
return (null, error);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var error = ex.Message;
|
||||
logger?.Warning($"GeoLocation: ipinfo.io failed: {error}");
|
||||
logger?.Warning($"GeoLocation: {name} failed: {error}");
|
||||
return (null, error);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<(GeoLocationResult result, string error)> TryIfConfigCo(AgentLogger logger)
|
||||
internal static GeoLocationResult ParseIpInfo(JObject json) =>
|
||||
new GeoLocationResult
|
||||
{
|
||||
Country = json.Value<string>("country"),
|
||||
Region = json.Value<string>("region"),
|
||||
City = json.Value<string>("city"),
|
||||
Loc = json.Value<string>("loc"),
|
||||
Timezone = json.Value<string>("timezone"),
|
||||
Ip = json.Value<string>("ip"),
|
||||
Source = "ipinfo"
|
||||
};
|
||||
|
||||
internal static GeoLocationResult ParseIfConfigCo(JObject json)
|
||||
{
|
||||
try
|
||||
var latitude = json.Value<string>("latitude") ?? "";
|
||||
var longitude = json.Value<string>("longitude") ?? "";
|
||||
var loc = !string.IsNullOrEmpty(latitude) && !string.IsNullOrEmpty(longitude)
|
||||
? $"{latitude},{longitude}"
|
||||
: "";
|
||||
|
||||
return new GeoLocationResult
|
||||
{
|
||||
logger?.Info("GeoLocation: Falling back to ifconfig.co...");
|
||||
Country = json.Value<string>("country_iso"),
|
||||
Region = json.Value<string>("region_name"),
|
||||
City = json.Value<string>("city"),
|
||||
Loc = loc,
|
||||
Timezone = json.Value<string>("time_zone"),
|
||||
Ip = json.Value<string>("ip"),
|
||||
Source = "ifconfig.co"
|
||||
};
|
||||
}
|
||||
|
||||
using (var httpResponse = await SharedHttpClient.GetAsync("https://ifconfig.co/json"))
|
||||
{
|
||||
if (!httpResponse.IsSuccessStatusCode)
|
||||
{
|
||||
var error = $"HTTP {(int)httpResponse.StatusCode} ({httpResponse.ReasonPhrase})";
|
||||
logger?.Warning($"GeoLocation: ifconfig.co failed: {error}");
|
||||
return (null, error);
|
||||
}
|
||||
/// <summary>
|
||||
/// The DO geo response carries DO service configuration next to the geo fields; only
|
||||
/// <c>CountryCode</c> and <c>ExternalIpAddress</c> are location data. Without a country
|
||||
/// the response is worthless as a location, so it counts as a failure (null).
|
||||
/// </summary>
|
||||
internal static GeoLocationResult ParseDoGeo(JObject json)
|
||||
{
|
||||
var country = json.Value<string>("CountryCode");
|
||||
if (string.IsNullOrEmpty(country))
|
||||
return null;
|
||||
|
||||
var response = await httpResponse.Content.ReadAsStringAsync();
|
||||
var json = JObject.Parse(response);
|
||||
|
||||
var latitude = json.Value<string>("latitude") ?? "";
|
||||
var longitude = json.Value<string>("longitude") ?? "";
|
||||
var loc = !string.IsNullOrEmpty(latitude) && !string.IsNullOrEmpty(longitude)
|
||||
? $"{latitude},{longitude}"
|
||||
: "";
|
||||
|
||||
var result = new GeoLocationResult
|
||||
{
|
||||
Country = json.Value<string>("country_iso"),
|
||||
Region = json.Value<string>("region_name"),
|
||||
City = json.Value<string>("city"),
|
||||
Loc = loc,
|
||||
Timezone = json.Value<string>("time_zone"),
|
||||
Ip = json.Value<string>("ip"),
|
||||
Source = "ifconfig.co"
|
||||
};
|
||||
|
||||
logger?.Info($"GeoLocation: ifconfig.co returned {result.City}, {result.Region}, {result.Country}");
|
||||
return (result, null);
|
||||
}
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
return new GeoLocationResult
|
||||
{
|
||||
var error = "Timeout (5s)";
|
||||
logger?.Warning($"GeoLocation: ifconfig.co failed: {error}");
|
||||
return (null, error);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var error = ex.Message;
|
||||
logger?.Warning($"GeoLocation: ifconfig.co failed: {error}");
|
||||
return (null, error);
|
||||
}
|
||||
Country = country,
|
||||
Ip = json.Value<string>("ExternalIpAddress"),
|
||||
Source = "do-geo"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,7 +420,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// Re-stamp AgentBootUtc so the current run's deadlines floor at "now" — the
|
||||
// persisted boot anchor is from the prior run and using it would let replayed
|
||||
// tail signals arm deadlines that are already past-due (premature fire).
|
||||
seed = loadedState.ToBuilder().WithAgentBootUtc(agentBootUtc).Build();
|
||||
// Re-stamp SessionId too: after a session rotation at registration
|
||||
// (SESSION-OWNER-BINDING) the snapshot still names the refused session, and the
|
||||
// timeline emitter takes each event's SessionId from this state.
|
||||
var seedBuilder = loadedState.ToBuilder().WithAgentBootUtc(agentBootUtc);
|
||||
seedBuilder.SessionId = sessionId;
|
||||
seed = seedBuilder.Build();
|
||||
signalsToReplay = CollectSignalLogTailAfter(signalLog, loadedState.LastAppliedSignalOrdinal);
|
||||
branchTag = signalsToReplay.Count > 0 ? "b-tail-replay" : "b-snapshot-current";
|
||||
}
|
||||
|
||||
@@ -61,6 +61,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// detection — the exact scenario the power watcher exists to observe.
|
||||
SharedConstants.EventTypes.PowerStateChange,
|
||||
|
||||
// Same for the network link: a dock or access point that flaps for hours (field:
|
||||
// 288 lost/connected pairs in 11 h, each with its connectivity check) is not
|
||||
// enrollment progress. Counted as activity it kept the periodic collectors running
|
||||
// for the whole episode and hid the stall it was causing, because every flap reset
|
||||
// the stall clock. Progress that follows a reconnect arrives as its own download,
|
||||
// app or phase event.
|
||||
SharedConstants.EventTypes.NetworkStateChange,
|
||||
SharedConstants.EventTypes.NetworkConnectivityCheck,
|
||||
|
||||
// Same reasoning for the system timeline watcher: a clock step, a wake from standby,
|
||||
// or a backfilled episode at agent start is environment observation and must not
|
||||
// reset the idle/stall clocks.
|
||||
@@ -81,6 +90,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// says something about the agent, not about the device's enrollment progress.
|
||||
SharedConstants.EventTypes.ImeTrackerDegraded,
|
||||
SharedConstants.EventTypes.ImePatternHits,
|
||||
// Bookkeeping of runs that were deliberately not reported as activity.
|
||||
SharedConstants.EventTypes.ScriptRecurrenceSummary,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -18,7 +18,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Runtime
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item><b>device_location</b> (or <c>agent_trace</c> on failure) — IP-based geo via
|
||||
/// <see cref="GeoLocationService"/>. Skipped when <c>EnableGeoLocation=false</c>.</item>
|
||||
/// <see cref="GeoLocationService"/>. Skipped when <c>EnableGeoLocation=false</c>. The
|
||||
/// last-resort provider (DO geo) yields a country-only location without timezone.</item>
|
||||
/// <item><b>timezone_auto_set</b> — only when <c>EnableTimezoneAutoSet=true</c> AND the
|
||||
/// geo lookup returned an IANA timezone. Uses <see cref="TimezoneService"/> (tzutil).</item>
|
||||
/// <item><b>ntp_time_check</b> — NTP offset from <c>NtpServer</c> (default time.windows.com).
|
||||
@@ -225,7 +226,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Runtime
|
||||
Source = "StartupEnvironmentProbes",
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Message = $"Device location: {location.City}, {location.Region}, {location.Country} (via {location.Source})",
|
||||
Message = $"Device location: {location.Describe()} (via {location.Source})",
|
||||
Data = location.ToDictionary(),
|
||||
ImmediateUpload = true,
|
||||
};
|
||||
@@ -266,8 +267,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Runtime
|
||||
{ "primaryError", attempt?.PrimaryError ?? "unknown" },
|
||||
{ "primaryRetryError", attempt?.PrimaryRetryError ?? "unknown" },
|
||||
{ "fallbackError", attempt?.FallbackError ?? "unknown" },
|
||||
{ "doGeoError", attempt?.DoGeoError ?? "unknown" },
|
||||
{ "primaryProvider", "ipinfo.io" },
|
||||
{ "fallbackProvider", "ifconfig.co" },
|
||||
{ "lastResortProvider", "do-geo" },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
{
|
||||
@@ -22,6 +24,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
private readonly string _sessionFilePath;
|
||||
private readonly string _sessionCreatedFilePath;
|
||||
private readonly string _whiteGloveMarkerPath;
|
||||
private readonly string _registrationFailurePath;
|
||||
private readonly object _lockObject = new object();
|
||||
|
||||
public SessionIdPersistence(string dataDirectory)
|
||||
@@ -35,6 +38,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
_sessionFilePath = Path.Combine(dataDirectory, "session.id");
|
||||
_sessionCreatedFilePath = Path.Combine(dataDirectory, "session.created");
|
||||
_whiteGloveMarkerPath = Path.Combine(dataDirectory, "whiteglove.complete");
|
||||
_registrationFailurePath = Path.Combine(dataDirectory, "registration-failure.json");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -164,6 +168,55 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
lock (_lockObject) TryDelete(_whiteGloveMarkerPath, logger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Folds one failed registration run into <c>registration-failure.json</c>: the run
|
||||
/// counter grows, the first failure time is kept, everything else describes the latest
|
||||
/// run. A run that never registers exits and leaves nothing else behind — the emergency
|
||||
/// break reads this file so the backend learns why the session never appeared.
|
||||
/// Best-effort; never throws.
|
||||
/// </summary>
|
||||
public void RecordRegistrationFailure(RegistrationFailureSummary latestRun, AgentLogger logger = null)
|
||||
{
|
||||
if (latestRun == null) return;
|
||||
lock (_lockObject)
|
||||
{
|
||||
try
|
||||
{
|
||||
var previous = LoadRegistrationFailureInternal();
|
||||
var merged = new RegistrationFailureSummary
|
||||
{
|
||||
FailedRuns = (previous?.FailedRuns ?? 0) + 1,
|
||||
FirstFailedAtUtc = previous?.FirstFailedAtUtc ?? latestRun.LastFailedAtUtc,
|
||||
LastFailedAtUtc = latestRun.LastFailedAtUtc,
|
||||
Outcome = latestRun.Outcome,
|
||||
LastError = latestRun.LastError,
|
||||
NetworkLinkUpAtStart = latestRun.NetworkLinkUpAtStart,
|
||||
NetworkLinkUpAtEnd = latestRun.NetworkLinkUpAtEnd,
|
||||
AttemptWindowSeconds = latestRun.AttemptWindowSeconds,
|
||||
ConfigFetchOutcome = latestRun.ConfigFetchOutcome,
|
||||
};
|
||||
File.WriteAllText(_registrationFailurePath, JsonConvert.SerializeObject(merged));
|
||||
logger?.Info($"SessionIdPersistence: recorded failed registration run #{merged.FailedRuns}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger?.Warning($"SessionIdPersistence: RecordRegistrationFailure failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The failed-registration record since the last success, or <c>null</c> (none, unreadable).</summary>
|
||||
public RegistrationFailureSummary LoadRegistrationFailure()
|
||||
{
|
||||
lock (_lockObject) return LoadRegistrationFailureInternal();
|
||||
}
|
||||
|
||||
/// <summary>Drops the failed-registration record — called once registration succeeds.</summary>
|
||||
public void ClearRegistrationFailure(AgentLogger logger = null)
|
||||
{
|
||||
lock (_lockObject) TryDelete(_registrationFailurePath, logger);
|
||||
}
|
||||
|
||||
/// <summary>Deletes the persisted SessionId. Next <see cref="GetOrCreate"/> starts a fresh session.</summary>
|
||||
public void Delete(AgentLogger logger = null)
|
||||
{
|
||||
@@ -172,6 +225,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
TryDelete(_sessionFilePath, logger);
|
||||
TryDelete(_sessionCreatedFilePath, logger);
|
||||
TryDelete(_whiteGloveMarkerPath, logger);
|
||||
TryDelete(_registrationFailurePath, logger);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,11 +245,28 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
var fresh = Guid.NewGuid().ToString();
|
||||
WriteAtomic(fresh, logger);
|
||||
SaveSessionCreatedAtInternal(DateTime.UtcNow);
|
||||
// Earlier failed runs belonged to the refused session id.
|
||||
TryDelete(_registrationFailurePath, logger);
|
||||
logger?.Info($"SessionIdPersistence: rotated SessionId to {fresh}.");
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
private RegistrationFailureSummary LoadRegistrationFailureInternal()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_registrationFailurePath)) return null;
|
||||
var record = JsonConvert.DeserializeObject<RegistrationFailureSummary>(File.ReadAllText(_registrationFailurePath));
|
||||
return record != null && record.FailedRuns > 0 ? record : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Corrupt record: report nothing rather than a half-read account.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDelete(string path, AgentLogger logger)
|
||||
{
|
||||
try { if (File.Exists(path)) File.Delete(path); }
|
||||
|
||||
@@ -34,13 +34,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
/// <see cref="AuthFailureTracker"/> (which fires the first-failure distress + may trip
|
||||
/// the shutdown threshold) and return <see cref="SessionRegistrationOutcome.AuthFailed"/>
|
||||
/// without retrying — the backend has definitively rejected the device cert.</item>
|
||||
/// <item>Exception to the above — a 403 carrying error code
|
||||
/// <item>Exception to the above — a 403 or 409 carrying error code
|
||||
/// <c>session_owner_mismatch</c> (SESSION-OWNER-BINDING): the persisted SessionId names a
|
||||
/// session bound to another device identity (typically an Intune re-enrollment without a
|
||||
/// wipe, where <c>session.id</c> survived but the certificate identity changed). That is
|
||||
/// not an auth failure: the session is rotated through <c>rotateSession</c> and
|
||||
/// registration retried exactly once. The tracker is NOT fed — five of these would
|
||||
/// otherwise soft-shutdown a perfectly authorized agent.</item>
|
||||
/// session that is not this device's — bound to another device identity (403, typically an
|
||||
/// Intune re-enrollment without a wipe, where <c>session.id</c> survived but the certificate
|
||||
/// identity changed) or claimed by another tenant (409). That is not an auth failure: the
|
||||
/// session is rotated through <c>rotateSession</c> and registration retried exactly once.
|
||||
/// The tracker is NOT fed — five of these would otherwise soft-shutdown a perfectly
|
||||
/// authorized agent.</item>
|
||||
/// <item>Any other coded 409 (<see cref="BackendRefusalException"/>) → <see cref="SessionRegistrationOutcome.Failed"/>
|
||||
/// without retrying — a refusal with a code does not clear by waiting.</item>
|
||||
/// <item>Any other exception on the last attempt → <see cref="EmergencyReporter.TrySendAsync"/>
|
||||
/// with <c>AgentErrorType.RegisterSessionFailed</c> so operators see the final cause.</item>
|
||||
/// </list>
|
||||
@@ -113,14 +116,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
lastError = response?.Message ?? "(null response)";
|
||||
logger.Warning($"Session registration failed: {lastError}");
|
||||
}
|
||||
catch (BackendAuthException ex) when (
|
||||
ex.ErrorCode == Constants.AgentErrorCodes.SessionOwnerMismatch
|
||||
catch (Exception ex) when (
|
||||
IsSessionOwnerMismatch(ex)
|
||||
&& rotateSession != null
|
||||
&& rotatedFromSessionId == null)
|
||||
{
|
||||
// SESSION-OWNER-BINDING: the id on disk belongs to a session this device
|
||||
// identity does not own. Become a new session and register once more —
|
||||
// immediately, no backoff, no auth-failure bookkeeping.
|
||||
// SESSION-OWNER-BINDING: the id on disk names a session this device does not
|
||||
// own. Become a new session and register once more — immediately, no backoff,
|
||||
// no auth-failure bookkeeping.
|
||||
rotatedFromSessionId = registration.SessionId;
|
||||
string newSessionId;
|
||||
try
|
||||
@@ -130,15 +133,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
catch (Exception rotateEx)
|
||||
{
|
||||
logger.Error($"Session owner mismatch reported by backend but session rotation failed: {rotateEx.Message}", rotateEx);
|
||||
authFailureTracker?.RecordFailure(ex.StatusCode, "agent/register-session", ex.EndpointUnavailable);
|
||||
return SessionRegistrationResult.AuthFailed(ex.StatusCode, ex.Message);
|
||||
if (ex is BackendAuthException authEx)
|
||||
{
|
||||
authFailureTracker?.RecordFailure(authEx.StatusCode, "agent/register-session", authEx.EndpointUnavailable);
|
||||
return SessionRegistrationResult.AuthFailed(authEx.StatusCode, authEx.Message);
|
||||
}
|
||||
return SessionRegistrationResult.Failed(ex.Message);
|
||||
}
|
||||
logger.Warning(
|
||||
$"Backend refused registration with {Constants.AgentErrorCodes.SessionOwnerMismatch}: session {rotatedFromSessionId} " +
|
||||
$"is bound to another device identity (re-enrollment without wipe?). Rotated to {newSessionId}; re-registering.");
|
||||
$"is not this device's (bound to another device identity after a re-enrollment without wipe, or claimed by another tenant). " +
|
||||
$"Rotated to {newSessionId}; re-registering.");
|
||||
registration = BuildRegistration(agentConfig, agentVersion, deviceHardware);
|
||||
continue;
|
||||
}
|
||||
catch (BackendRefusalException ex)
|
||||
{
|
||||
logger.Error($"Session registration refused ({ex.StatusCode}, {ex.ErrorCode}): {ex.Message}");
|
||||
return SessionRegistrationResult.Failed(ex.Message);
|
||||
}
|
||||
catch (BackendAuthException ex)
|
||||
{
|
||||
logger.Error($"Session registration authentication failed ({ex.StatusCode}): {ex.Message}");
|
||||
@@ -195,6 +208,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
return SessionRegistrationResult.Failed(lastError ?? "max retries exceeded");
|
||||
}
|
||||
|
||||
private static bool IsSessionOwnerMismatch(Exception ex)
|
||||
{
|
||||
var code = (ex as BackendAuthException)?.ErrorCode ?? (ex as BackendRefusalException)?.ErrorCode;
|
||||
return code == Constants.AgentErrorCodes.SessionOwnerMismatch;
|
||||
}
|
||||
|
||||
/// <summary>V1 parity exponential backoff: 2^attempt seconds.</summary>
|
||||
private static Task DefaultBackoffDelay(int attempt)
|
||||
=> Task.Delay(((int)Math.Pow(2, attempt)) * 1000);
|
||||
|
||||
+24
-3
@@ -24,7 +24,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
/// <list type="bullet">
|
||||
/// <item><c>HelloCompleted</c> → <see cref="DecisionSignalKind.HelloResolved"/></item>
|
||||
/// <item><c>FinalizingSetupPhaseTriggered</c> → <see cref="DecisionSignalKind.EspPhaseChanged"/> (phase=FinalizingSetup)</item>
|
||||
/// <item><c>WhiteGloveCompleted</c> → <see cref="DecisionSignalKind.WhiteGloveShellCoreSuccess"/></item>
|
||||
/// <item><c>WhiteGloveCompleted</c> → <see cref="DecisionSignalKind.WhiteGloveShellCoreSuccess"/> (payload: registry AccountSetup progress at that moment)</item>
|
||||
/// <item><c>EspFailureDetected</c> → <see cref="DecisionSignalKind.EspTerminalFailure"/> (merged aus ShellCore + Provisioning)</item>
|
||||
/// <item><c>DeviceSetupProvisioningComplete</c> → <see cref="DecisionSignalKind.DeviceSetupProvisioningComplete"/></item>
|
||||
/// <item><c>AccountSetupProvisioningComplete</c> → <see cref="DecisionSignalKind.AccountSetupProvisioningComplete"/> (session 330f73f3 fix — strong AccountSetup-done gate)</item>
|
||||
@@ -46,6 +46,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
private readonly EspAndHelloTracker _coordinator;
|
||||
private readonly ISignalIngressSink _ingress;
|
||||
private readonly IClock _clock;
|
||||
private readonly Func<bool?> _accountSetupProgressProbe;
|
||||
|
||||
private bool _helloPosted;
|
||||
private bool _helloWizardStartedPosted;
|
||||
@@ -60,11 +61,14 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
public EspAndHelloTrackerAdapter(
|
||||
EspAndHelloTracker coordinator,
|
||||
ISignalIngressSink ingress,
|
||||
IClock clock)
|
||||
IClock clock,
|
||||
Func<bool?>? accountSetupProgressProbe = null)
|
||||
{
|
||||
_coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator));
|
||||
_ingress = ingress ?? throw new ArgumentNullException(nameof(ingress));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
// Test seam; production reads the provisioning tracker's registry-derived flag.
|
||||
_accountSetupProgressProbe = accountSetupProgressProbe ?? (() => _coordinator.AccountSetupProgressIfRead);
|
||||
|
||||
_coordinator.HelloCompleted += OnHelloCompleted;
|
||||
_coordinator.FinalizingSetupPhaseTriggered += OnFinalizing;
|
||||
@@ -216,13 +220,29 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (_whiteGloveSuccessPosted) return;
|
||||
_whiteGloveSuccessPosted = true;
|
||||
|
||||
// Registry AccountSetup progress at the moment of the success page. The sealing
|
||||
// classifier lifts its AccountSetup excluder only on an explicit "false" — IME logs
|
||||
// AccountSetup from the device session once the device apps are done, which is no
|
||||
// user activity. Sampled here so replay reads it from the SignalLog (L.2/L.5). An
|
||||
// unread registry sends no key: unknown must keep the excluder, never lift it.
|
||||
var progress = _accountSetupProgressProbe();
|
||||
var progressText = progress.HasValue ? (progress.Value ? "true" : "false") : null;
|
||||
|
||||
var now = ResolveOccurredAt(out var derivedFromClock);
|
||||
var derivationInputs = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["subSource"] = "ShellCoreTracker",
|
||||
[SignalPayloadKeys.AccountSetupProgress] = progressText ?? "unread",
|
||||
};
|
||||
TagDerivedTimestamp(derivationInputs, derivedFromClock);
|
||||
|
||||
var payload = progressText == null
|
||||
? null
|
||||
: new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
[SignalPayloadKeys.AccountSetupProgress] = progressText,
|
||||
};
|
||||
|
||||
_ingress.Post(
|
||||
kind: DecisionSignalKind.WhiteGloveShellCoreSuccess,
|
||||
occurredAtUtc: now,
|
||||
@@ -231,7 +251,8 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
kind: EvidenceKind.Derived,
|
||||
identifier: DetectorId,
|
||||
summary: "WhiteGlove sealing success (coordinator-forwarded)",
|
||||
derivationInputs: derivationInputs));
|
||||
derivationInputs: derivationInputs),
|
||||
payload: payload);
|
||||
}
|
||||
|
||||
private void EmitEspFailure(EspFailureDetectedEventArgs args)
|
||||
|
||||
@@ -94,6 +94,8 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
private readonly Action<AppPackageState, DateTime?> _ourOnDoTelemetryReceived;
|
||||
private readonly Action<ScriptExecutionState> _ourOnScriptCompleted;
|
||||
private readonly Action<ScriptStartedInfo> _ourOnScriptStarted;
|
||||
private readonly Action<ScriptRecurrenceSummary>? _prevOnScriptRecurrenceSummary;
|
||||
private readonly Action<ScriptRecurrenceSummary> _ourOnScriptRecurrenceSummary;
|
||||
private readonly Action<string, string> _ourOnImeTokenFailure;
|
||||
|
||||
// Dedup state for DecisionSignals.
|
||||
@@ -195,6 +197,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
_prevOnDoTelemetryReceived = _tracker.OnDoTelemetryReceived;
|
||||
_prevOnScriptCompleted = _tracker.OnScriptCompleted;
|
||||
_prevOnScriptStarted = _tracker.OnScriptStarted;
|
||||
_prevOnScriptRecurrenceSummary = _tracker.OnScriptRecurrenceSummary;
|
||||
_prevOnImeTokenFailure = _tracker.OnImeTokenFailure;
|
||||
_prevOnTrackerDegraded = _tracker.OnTrackerDegraded;
|
||||
|
||||
@@ -209,6 +212,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
_ourOnDoTelemetryReceived = OnDoTelemetryReceived;
|
||||
_ourOnScriptCompleted = OnScriptCompleted;
|
||||
_ourOnScriptStarted = OnScriptStarted;
|
||||
_ourOnScriptRecurrenceSummary = OnScriptRecurrenceSummary;
|
||||
_ourOnImeTokenFailure = OnImeTokenFailure;
|
||||
|
||||
_tracker.OnEspPhaseChanged = _ourOnEspPhaseChanged;
|
||||
@@ -219,6 +223,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
_tracker.OnDoTelemetryReceived = _ourOnDoTelemetryReceived;
|
||||
_tracker.OnScriptCompleted = _ourOnScriptCompleted;
|
||||
_tracker.OnScriptStarted = _ourOnScriptStarted;
|
||||
_tracker.OnScriptRecurrenceSummary = _ourOnScriptRecurrenceSummary;
|
||||
_tracker.OnImeTokenFailure = _ourOnImeTokenFailure;
|
||||
_tracker.OnTrackerDegraded = _ourOnTrackerDegraded;
|
||||
}
|
||||
@@ -245,6 +250,8 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
_tracker.OnScriptCompleted = _prevOnScriptCompleted;
|
||||
if (ReferenceEquals(_tracker.OnScriptStarted, _ourOnScriptStarted))
|
||||
_tracker.OnScriptStarted = _prevOnScriptStarted;
|
||||
if (ReferenceEquals(_tracker.OnScriptRecurrenceSummary, _ourOnScriptRecurrenceSummary))
|
||||
_tracker.OnScriptRecurrenceSummary = _prevOnScriptRecurrenceSummary;
|
||||
if (ReferenceEquals(_tracker.OnImeTokenFailure, _ourOnImeTokenFailure))
|
||||
_tracker.OnImeTokenFailure = _prevOnImeTokenFailure;
|
||||
}
|
||||
@@ -297,6 +304,12 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
EmitScriptStarted(info);
|
||||
}
|
||||
|
||||
private void OnScriptRecurrenceSummary(ScriptRecurrenceSummary summary)
|
||||
{
|
||||
_prevOnScriptRecurrenceSummary?.Invoke(summary);
|
||||
EmitScriptRecurrenceSummary(summary);
|
||||
}
|
||||
|
||||
private void OnImeTokenFailure(string errorCode, string message)
|
||||
{
|
||||
_prevOnImeTokenFailure?.Invoke(errorCode, message);
|
||||
@@ -448,31 +461,35 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
/// no second clock frame, so there is nothing to record.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
private void TagDerivedTimestamp(IDictionary<string, string> data, bool derivedFromClock, DateTime? rawSourceTs)
|
||||
private void TagDerivedTimestamp(IDictionary<string, string> data, bool derivedFromClock, DateTime? rawSourceTs, CmTraceLineProvenance? lineProvenance = null)
|
||||
{
|
||||
var culture = System.Globalization.CultureInfo.InvariantCulture;
|
||||
|
||||
var sourceLocal = _tracker.LastMatchedSourceLocalTimestamp;
|
||||
// The line the event is bound to. Callers that emit later than the match (a held
|
||||
// platform-script result) pass the snapshot taken at their line; everyone else is
|
||||
// emitting while its line is still the last matched one.
|
||||
var line = lineProvenance ?? _tracker.CaptureLastMatchedProvenance();
|
||||
var sourceLocal = line.SourceLocalTs;
|
||||
if (sourceLocal.HasValue)
|
||||
{
|
||||
// No zone suffix: the value genuinely carries none, and formatting one in would
|
||||
// re-introduce the very assumption this whole change removes.
|
||||
data["sourceLocalTs"] = sourceLocal.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffffff", culture);
|
||||
data["sourceOffsetOrigin"] = OriginTag(_tracker.LastMatchedSourceOffsetOrigin);
|
||||
data["sourceOffsetOrigin"] = OriginTag(line.Origin);
|
||||
|
||||
var offsetMinutes = _tracker.LastMatchedSourceOffsetMinutes;
|
||||
var offsetMinutes = line.OffsetMinutes;
|
||||
if (offsetMinutes.HasValue)
|
||||
data["sourceOffsetMinutes"] = offsetMinutes.Value.ToString(culture);
|
||||
|
||||
// Which era anchor the offset came from — forensics for the era-anchored origin.
|
||||
var anchorKind = _tracker.LastMatchedEraAnchorKind;
|
||||
var anchorKind = line.EraAnchorKind;
|
||||
if (!string.IsNullOrEmpty(anchorKind))
|
||||
data["sourceOffsetAnchor"] = anchorKind;
|
||||
|
||||
// Observational only — what the calibrator measured, which since the 2026-08-20
|
||||
// revert is deliberately NOT what was applied. Kept separate so the two can never
|
||||
// be read as the same thing.
|
||||
var measured = _tracker.LastMatchedMeasuredWriterOffsetMinutes;
|
||||
var measured = line.MeasuredWriterOffsetMinutes;
|
||||
if (measured.HasValue)
|
||||
data["measuredWriterOffsetMinutes"] = measured.Value.ToString(culture);
|
||||
}
|
||||
@@ -1254,23 +1271,25 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (!string.IsNullOrEmpty(script.Stdout)) data["stdout"] = script.Stdout!;
|
||||
if (!string.IsNullOrEmpty(script.Stderr)) data["stderr"] = script.Stderr!;
|
||||
|
||||
// The exit-code fallback emits asynchronously to log parsing, so the tracker's
|
||||
// "last matched" pattern/timestamp belong to an unrelated later line. Bind the event to
|
||||
// the script's own exit-observed timestamp and omit the misleading patternId instead.
|
||||
// A platform-script completion is bound to the script's own line, not to the tracker's
|
||||
// "last matched" one: the exit-code fallback emits a grace period after its exit line,
|
||||
// and an IME result held for its executor end block emits at the end of a later pass —
|
||||
// by then LastMatched* name an unrelated line. The fallback carries no patternId (no
|
||||
// line delivered its result). Health scripts carry neither stamp and stay on the last
|
||||
// matched line, which IS their result line.
|
||||
var isFallback = string.Equals(script.ResultSource, "agentexecutor_fallback", StringComparison.Ordinal);
|
||||
if (!isFallback)
|
||||
{
|
||||
var patternId = _tracker.LastMatchedPatternId;
|
||||
var patternId = script.ResultPatternId ?? _tracker.LastMatchedPatternId;
|
||||
if (!string.IsNullOrEmpty(patternId)) data["patternId"] = patternId!;
|
||||
}
|
||||
|
||||
bool derivedFromClock;
|
||||
DateTime? rawSourceTs;
|
||||
DateTime now;
|
||||
if (isFallback && script.ExitObservedAtUtc.HasValue)
|
||||
now = ResolveOccurredAt(script.ExitObservedAtUtc, out derivedFromClock, out rawSourceTs);
|
||||
else
|
||||
now = ResolveOccurredAt(out derivedFromClock, out rawSourceTs);
|
||||
var sourceTs = isFallback ? script.ExitObservedAtUtc : script.ResultObservedAtUtc;
|
||||
var now = sourceTs.HasValue
|
||||
? ResolveOccurredAt(sourceTs, out derivedFromClock, out rawSourceTs)
|
||||
: ResolveOccurredAt(out derivedFromClock, out rawSourceTs);
|
||||
|
||||
// Historic replay (a previous enrollment's log) — do not emit at all. The early
|
||||
// return also skips MaybeEmitBootstrapDetected / MaybeEmitScriptTimeoutSuspected,
|
||||
@@ -1278,7 +1297,11 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (SuppressIfHistoricReplay(derivedFromClock, rawSourceTs, eventType, script.PolicyId))
|
||||
return;
|
||||
|
||||
TagDerivedTimestamp(data, derivedFromClock, rawSourceTs);
|
||||
// The line that delivered the result is bound on the state (D-247), so a completion
|
||||
// emitted passes later still describes ITS line. Null (states from before the field,
|
||||
// synthetic tests) falls back to the tracker's last matched line as before.
|
||||
var endProvenance = isFallback ? script.ExitProvenance : script.ResultProvenance;
|
||||
TagDerivedTimestamp(data, derivedFromClock, rawSourceTs, endProvenance);
|
||||
|
||||
// Per-script run duration (start line → this completion). Surfaced on every
|
||||
// script completion so the UI can flag slow / inefficient scripts, not just timed-out
|
||||
@@ -1286,11 +1309,13 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
// against clock skew between the (possibly clock-derived) completion stamp and start.
|
||||
//
|
||||
// When the completion timestamp was clock-derived because the source line's timestamp
|
||||
// was rejected (future-skew CMTrace clock jump — the stale case never reaches here),
|
||||
// `now` lives on the clock's timeline while StartedAtUtc was captured RAW from the
|
||||
// source log. Mixing the two produced absurd durations (session eaf3d8c4: 170 h), so
|
||||
// the duration uses the raw source pair — both ends on the same timeline, the
|
||||
// difference is the true runtime. The event stamp stays `now` (timeline position).
|
||||
// was rejected (future-skew — the stale case never reaches here), `now` lives on the
|
||||
// clock's timeline while StartedAtUtc was captured RAW from the source log. Mixing the
|
||||
// two produced absurd durations (session eaf3d8c4: 170 h), so the span is taken from
|
||||
// the raw source pair. That pair is a run time only when both lines were resolved on
|
||||
// the same zone belief — JudgeDurationPair decides, from the provenance bound to each
|
||||
// line, whether the span is verified, unverified, or an offset error to omit (session
|
||||
// 4377911b: a 10 s script read as 3610 s). The event stamp stays `now`.
|
||||
//
|
||||
// L19 (delta review 2026-07-02): the same field name carries two different semantics —
|
||||
// start→own-end-signal (≈ script runtime) vs HS-SCRIPT-START→HS-NEW-RESULT (the whole
|
||||
@@ -1302,15 +1327,26 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
var completionForDuration = derivedFromClock && rawSourceTs.HasValue
|
||||
? NormalizeUtc(rawSourceTs.Value)
|
||||
: now;
|
||||
TimeSpan? measurableDuration = null;
|
||||
if (script.StartedAtUtc.HasValue)
|
||||
{
|
||||
var durationSeconds = (completionForDuration - script.StartedAtUtc.Value).TotalSeconds;
|
||||
var span = completionForDuration - script.StartedAtUtc.Value;
|
||||
var verdict = JudgeDurationPair(script.StartedAtProvenance, endProvenance,
|
||||
endStampRejected: derivedFromClock && rawSourceTs.HasValue, span, out var suppressedReason);
|
||||
if (verdict != DurationPairVerdict.Unknown)
|
||||
data["durationProvenance"] = verdict == DurationPairVerdict.Verified ? "verified" : "unverified";
|
||||
|
||||
if (verdict == DurationPairVerdict.Suppressed)
|
||||
{
|
||||
data["durationSuppressedReason"] = suppressedReason!;
|
||||
}
|
||||
// Plausibility backstop: IME's script execution timeout is ~30 min; anything above
|
||||
// 24 h is a cross-run artifact (e.g. a stale pending start slot from a previous
|
||||
// enrollment paired with a fresh completion) — omit rather than lie.
|
||||
if (durationSeconds >= 0 && durationSeconds <= StaleSourceThreshold.TotalSeconds)
|
||||
else if (span >= TimeSpan.Zero && span <= StaleSourceThreshold)
|
||||
{
|
||||
data["durationSeconds"] = durationSeconds.ToString("F2", culture);
|
||||
measurableDuration = span;
|
||||
data["durationSeconds"] = span.TotalSeconds.ToString("F2", culture);
|
||||
data["durationBasis"] = script.DurationBasis
|
||||
?? (IsRemediation(script.ScriptType)
|
||||
? "cycle_including_reporting_latency"
|
||||
@@ -1318,6 +1354,18 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
}
|
||||
}
|
||||
|
||||
// The start line's provenance, next to the end line's (sourceOffset*), so the pair can
|
||||
// be judged downstream as well.
|
||||
var startProvenance = script.StartedAtProvenance;
|
||||
if (startProvenance != null && startProvenance.SourceLocalTs.HasValue)
|
||||
{
|
||||
data["startSourceOffsetOrigin"] = OriginTag(startProvenance.Origin);
|
||||
if (startProvenance.OffsetMinutes.HasValue)
|
||||
data["startSourceOffsetMinutes"] = startProvenance.OffsetMinutes.Value.ToString(culture);
|
||||
if (!string.IsNullOrEmpty(startProvenance.EraAnchorKind))
|
||||
data["startSourceOffsetAnchor"] = startProvenance.EraAnchorKind;
|
||||
}
|
||||
|
||||
var label = IsRemediation(script.ScriptType) ? "Remediation script" : "Platform script";
|
||||
var shortId = script.PolicyId.Length >= 8 ? script.PolicyId.Substring(0, 8) : script.PolicyId;
|
||||
string messageCore;
|
||||
@@ -1360,7 +1408,51 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
$"ImeAdapter: script completed policyId={shortId} type={script.ScriptType ?? "?"} result={script.Result ?? "?"} exit={(script.ExitCode.HasValue ? script.ExitCode.Value.ToString() : "n/a")}");
|
||||
|
||||
MaybeEmitBootstrapDetected(script, now);
|
||||
MaybeEmitScriptTimeoutSuspected(script, now, completionForDuration);
|
||||
MaybeEmitScriptTimeoutSuspected(script, now, measurableDuration);
|
||||
}
|
||||
|
||||
internal enum DurationPairVerdict { Unknown, Verified, Unverified, Suppressed }
|
||||
|
||||
/// <summary>
|
||||
/// Whether the span between a start line and an end line measures elapsed time.
|
||||
/// <para>
|
||||
/// Each CMTrace line is resolved on its own zone belief: declared or measured (bias,
|
||||
/// line-anchored, or the clock itself) — or ASSUMED (the reader's zone, a writer era's
|
||||
/// anchor). Two measured ends sit on the true UTC axis; two assumed ends resolved with the
|
||||
/// same offset from the same file share their error, which cancels (D-191). Any other pair
|
||||
/// is unverified, and its span is omitted when the end stamp was rejected as ahead of the
|
||||
/// clock — its assumption is proven wrong and the raw pair inherits the error (session
|
||||
/// 4377911b: a 10 s script read as 3610 s) — or when the span sits on the 15-minute offset
|
||||
/// grid, the signature of a wrong assumption on either end (session cbaed57b: 7200 s). A
|
||||
/// missing snapshot (state files from before the field, synthetic tests) leaves the rule
|
||||
/// off and the pair treated as before.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal static DurationPairVerdict JudgeDurationPair(
|
||||
CmTraceLineProvenance? start, CmTraceLineProvenance? end, bool endStampRejected, TimeSpan span, out string? suppressedReason)
|
||||
{
|
||||
suppressedReason = null;
|
||||
if (start == null || end == null) return DurationPairVerdict.Unknown;
|
||||
|
||||
var startAssumed = start.IsAssumed();
|
||||
var endAssumed = end.IsAssumed();
|
||||
var sameTimeline = (!startAssumed && !endAssumed)
|
||||
|| (startAssumed && endAssumed
|
||||
&& start.OffsetMinutes == end.OffsetMinutes
|
||||
&& string.Equals(start.SourceFileName, end.SourceFileName, StringComparison.OrdinalIgnoreCase));
|
||||
if (sameTimeline) return DurationPairVerdict.Verified;
|
||||
|
||||
if (endStampRejected)
|
||||
{
|
||||
suppressedReason = "rejected-endpoint";
|
||||
return DurationPairVerdict.Suppressed;
|
||||
}
|
||||
if (CmTraceOffsetCalibrator.IsOnOffsetGrid(span, out _))
|
||||
{
|
||||
suppressedReason = "offset-grid";
|
||||
return DurationPairVerdict.Suppressed;
|
||||
}
|
||||
return DurationPairVerdict.Unverified;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1372,19 +1464,19 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
/// late start / pre-failed ESP. Advisory only: no state mutation, the underlying
|
||||
/// <c>script_failed</c> is still emitted separately. Health (remediation) scripts are
|
||||
/// excluded — they re-run on their own cadence and have a different timeout regime.
|
||||
/// <paramref name="durationEndUtc"/> is the timeline-consistent completion for duration
|
||||
/// math (raw source ts on rejected-timestamp emissions); <paramref name="occurredAtUtc"/>
|
||||
/// stamps the emitted event.
|
||||
/// <paramref name="measurableDuration"/> is the run duration the completion event carries —
|
||||
/// null when it was omitted (no start line, implausible span, or a start/end pair resolved
|
||||
/// on different zone assumptions: the fleet's daily 17 h "timeouts" of 2–9 s scripts were
|
||||
/// offset errors); <paramref name="occurredAtUtc"/> stamps the emitted event.
|
||||
/// </summary>
|
||||
private void MaybeEmitScriptTimeoutSuspected(ScriptExecutionState script, DateTime occurredAtUtc, DateTime durationEndUtc)
|
||||
private void MaybeEmitScriptTimeoutSuspected(ScriptExecutionState script, DateTime occurredAtUtc, TimeSpan? measurableDuration)
|
||||
{
|
||||
if (IsRemediation(script.ScriptType)) return; // platform scripts only
|
||||
if (!script.StartedAtUtc.HasValue) return; // no start ⇒ no duration
|
||||
if (!measurableDuration.HasValue) return; // no measurable duration ⇒ no verdict
|
||||
if (!string.Equals(script.Result, "Failed", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var duration = durationEndUtc - script.StartedAtUtc.Value;
|
||||
var duration = measurableDuration.Value;
|
||||
if (duration < ScriptTimeoutSuspectedThreshold) return;
|
||||
if (duration > StaleSourceThreshold) return; // implausible — cross-run artifact, not a hung script
|
||||
|
||||
if (!_tracker.TryClaimScriptTimeoutSuspected(script.PolicyId)) return; // restart-safe dedup per policyId (persisted tracker state)
|
||||
|
||||
@@ -1462,10 +1554,13 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
};
|
||||
if (!string.IsNullOrEmpty(info.ScriptType)) data["scriptType"] = info.ScriptType!;
|
||||
if (!string.IsNullOrEmpty(info.PolicyType)) data["policyType"] = info.PolicyType!;
|
||||
var patternId = _tracker.LastMatchedPatternId;
|
||||
// A held start of a recurring health script arrives with its own line's stamp and
|
||||
// pattern — by now the tracker's "last matched" line is the result line.
|
||||
var wasHeld = info.SourceTimestampUtc.HasValue;
|
||||
var patternId = wasHeld ? info.PatternId : _tracker.LastMatchedPatternId;
|
||||
if (!string.IsNullOrEmpty(patternId)) data["patternId"] = patternId!;
|
||||
|
||||
var now = ResolveOccurredAt(out var derivedFromClock, out var rawSourceTs);
|
||||
var now = ResolveOccurredAt(info.SourceTimestampUtc, out var derivedFromClock, out var rawSourceTs);
|
||||
|
||||
// Historic replay — suppressing here also kills the immediateUpload flood the
|
||||
// replayed batch caused (session eaf3d8c4: 3× ingress_backpressure).
|
||||
@@ -1483,13 +1578,42 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
message: $"{label} {shortId}: started",
|
||||
// Live UI indicator — flush immediately so the running card appears within seconds,
|
||||
// not at the next batch boundary (which would defeat the purpose of a live signal).
|
||||
immediateUpload: true,
|
||||
// A held start is no longer live and rides the normal batch.
|
||||
immediateUpload: !wasHeld,
|
||||
data: data,
|
||||
occurredAtUtc: now);
|
||||
|
||||
_logger?.Debug($"ImeAdapter: script started policyId={shortId} type={info.ScriptType ?? "?"} policyType={info.PolicyType ?? "?"}");
|
||||
}
|
||||
|
||||
private void EmitScriptRecurrenceSummary(ScriptRecurrenceSummary summary)
|
||||
{
|
||||
if (summary == null || string.IsNullOrEmpty(summary.PolicyId)) return;
|
||||
|
||||
var culture = System.Globalization.CultureInfo.InvariantCulture;
|
||||
var data = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["policyId"] = summary.PolicyId,
|
||||
["scriptType"] = "remediation",
|
||||
["runsObserved"] = summary.RunsObserved.ToString(culture),
|
||||
["runsCollapsed"] = summary.RunsCollapsed.ToString(culture),
|
||||
["runsWithoutResult"] = summary.RunsWithoutResult.ToString(culture),
|
||||
["collapsedResults"] = summary.CollapsedResults.ToString(culture),
|
||||
};
|
||||
if (summary.FirstCollapsedAtUtc.HasValue)
|
||||
data["firstCollapsedAt"] = NormalizeUtc(summary.FirstCollapsedAtUtc.Value).ToString("o", culture);
|
||||
if (summary.LastCollapsedAtUtc.HasValue)
|
||||
data["lastCollapsedAt"] = NormalizeUtc(summary.LastCollapsedAtUtc.Value).ToString("o", culture);
|
||||
|
||||
var shortId = summary.PolicyId.Length >= 8 ? summary.PolicyId.Substring(0, 8) : summary.PolicyId;
|
||||
_post.Emit(
|
||||
eventType: SharedEventTypes.ScriptRecurrenceSummary,
|
||||
source: SourceLabel,
|
||||
message: $"Health script {shortId}: {summary.RunsCollapsed} further run(s) repeated the last reported result",
|
||||
severity: EventSeverity.Info,
|
||||
data: data);
|
||||
}
|
||||
|
||||
private static bool IsRemediation(string? scriptType) =>
|
||||
string.Equals(scriptType, "remediation", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
|
||||
+17
-2
@@ -169,6 +169,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
_logger.Info(
|
||||
$"EnrollmentTerminationHandler: handling Terminated (reason={args.Reason}, outcome={args.Outcome}, stage={args.StageName}).");
|
||||
|
||||
// The seal is already persisted in the decision snapshot. The marker goes down
|
||||
// before anything else: the technician's reseal can kill this process at any
|
||||
// later step, and a missing marker makes the next boot run the 48-hour break
|
||||
// against the Part-1 session age instead of resuming Part 2.
|
||||
if (isWhiteGlovePart1)
|
||||
{
|
||||
TrySaveWhiteGloveComplete();
|
||||
}
|
||||
|
||||
var state = TryGetCurrentState();
|
||||
|
||||
// M4.6.δ — shutdown analyzers run BEFORE the dialog / diagnostics upload so
|
||||
@@ -254,7 +263,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
|
||||
// WhiteGlove Part-1 exit: keep the session alive, but announce the handoff so
|
||||
// the timeline clearly marks the transition. The `whiteglove.complete` marker
|
||||
// lets the next agent boot classify itself as a Part-2 resume.
|
||||
// (written at the top of this handler) lets the next agent boot classify itself
|
||||
// as a Part-2 resume.
|
||||
if (isWhiteGlovePart1)
|
||||
{
|
||||
// Stop peripheral collectors BEFORE the Part-1-complete marker so their
|
||||
@@ -298,7 +308,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
DelayLateEventGrace();
|
||||
DrainSpool();
|
||||
|
||||
TrySaveWhiteGloveComplete();
|
||||
// Option 2 (WG Part 1 graceful-exit hardening, 2026-04-30): write the
|
||||
// clean-exit marker BEFORE _signalShutdown returns control to the main
|
||||
// thread. The AppDomain.ProcessExit handler still writes it as a second
|
||||
@@ -584,6 +593,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
["heldTails"] = health.HeldTails,
|
||||
["unanchoredPatterns"] = health.UnanchoredPatterns,
|
||||
["hsParseFailures"] = health.HealthScriptResultParseFailures,
|
||||
["overwriteRewinds"] = health.OverwriteRewinds,
|
||||
["overwriteBytesReprocessed"] = health.OverwriteBytesReprocessed,
|
||||
["verifyPasses"] = health.VerifyPasses,
|
||||
["verifiedBytes"] = health.VerifiedBytes,
|
||||
["passMaxMs"] = health.PassMaxMs,
|
||||
["passGapMaxMs"] = health.PassGapMaxMs,
|
||||
["agentVersion"] = _agentVersion ?? string.Empty,
|
||||
};
|
||||
if (!string.IsNullOrEmpty(health.ImeAgentVersion))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.Eventing.Reader;
|
||||
using System.IO;
|
||||
@@ -41,17 +42,31 @@ namespace AutopilotMonitor.Agent.V2
|
||||
|
||||
// ----------------------------------------------------------------- Multi-instance guard
|
||||
|
||||
/// <summary>Pid and terminal-services session of one name-matched process.</summary>
|
||||
internal readonly struct AgentProcessFact
|
||||
{
|
||||
public AgentProcessFact(int pid, int sessionId)
|
||||
{
|
||||
Pid = pid;
|
||||
SessionId = sessionId;
|
||||
}
|
||||
|
||||
public int Pid { get; }
|
||||
public int SessionId { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> when another process with the same filename (module name) is alive.
|
||||
/// Race-safe by design: we count processes sharing our name; if 1, only we exist.
|
||||
/// <c>true</c> when another agent runtime is alive. A process name is not a protected
|
||||
/// namespace — any user session can run a binary named like the agent — so a name match
|
||||
/// only counts in session 0. Every runtime start (Scheduled Task, WMI launch, self-update
|
||||
/// restart) lands there, and a standard user cannot start a process in it.
|
||||
/// </summary>
|
||||
internal static bool IsAnotherAgentInstanceRunning()
|
||||
{
|
||||
try
|
||||
{
|
||||
var self = Process.GetCurrentProcess();
|
||||
var siblings = Process.GetProcessesByName(self.ProcessName);
|
||||
return siblings.Length > 1;
|
||||
using (var self = Process.GetCurrentProcess())
|
||||
return FindSiblingAgentPid(SnapshotProcessesByName(self.ProcessName), self.Id) != 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -61,6 +76,40 @@ namespace AutopilotMonitor.Agent.V2
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pid of the first name-matched process that is a real agent runtime — session 0 and not
|
||||
/// the caller itself — or <c>0</c> when there is none. Shared by the multi-instance guard
|
||||
/// and install mode's launch verification so both trust the same identity.
|
||||
/// </summary>
|
||||
internal static int FindSiblingAgentPid(IEnumerable<AgentProcessFact> nameMatches, int ownPid)
|
||||
{
|
||||
if (nameMatches == null) return 0;
|
||||
foreach (var candidate in nameMatches)
|
||||
{
|
||||
if (candidate.Pid == ownPid) continue;
|
||||
if (candidate.SessionId != 0) continue;
|
||||
return candidate.Pid;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads pid and session of every process with the given name. A process that vanished
|
||||
/// between enumeration and read is skipped: it is not a live sibling, and failing open
|
||||
/// means the worst case is two agents, never none.
|
||||
/// </summary>
|
||||
internal static List<AgentProcessFact> SnapshotProcessesByName(string processName)
|
||||
{
|
||||
var facts = new List<AgentProcessFact>();
|
||||
foreach (var process in Process.GetProcessesByName(processName))
|
||||
{
|
||||
try { facts.Add(new AgentProcessFact(process.Id, process.SessionId)); }
|
||||
catch { /* exited mid-read */ }
|
||||
finally { process.Dispose(); }
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- clean-exit marker
|
||||
|
||||
/// <summary>
|
||||
@@ -259,7 +308,7 @@ namespace AutopilotMonitor.Agent.V2
|
||||
Func<CleanupService> cleanupServiceFactory,
|
||||
AgentLogger logger,
|
||||
bool consoleMode,
|
||||
Action onBreakFired = null)
|
||||
Action<double> onBreakFired = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -298,7 +347,7 @@ namespace AutopilotMonitor.Agent.V2
|
||||
// (tasks/enrollment-status-reclassification.md). Fired BEFORE cleanup, while the
|
||||
// session state and network are still intact. Never throws — a send failure (e.g. no
|
||||
// network) must not block the cleanup/exit that is the whole point of this guard.
|
||||
try { onBreakFired?.Invoke(); }
|
||||
try { onBreakFired?.Invoke(sessionAgeHours); }
|
||||
catch (Exception cbEx) { logger.Debug($"Emergency-break notify callback failed: {cbEx.Message}"); }
|
||||
|
||||
// Write enrollment-complete.marker so the next start exits cleanly even if
|
||||
|
||||
@@ -731,7 +731,8 @@ namespace AutopilotMonitor.Agent.V2
|
||||
/// 10s / 500ms contract as the bootstrap script's Get-Process probe. The install-mode
|
||||
/// process shares the runtime's exe name, so the own pid is excluded; a pre-existing
|
||||
/// foreign runtime cannot be running here because install mode bails earlier on the
|
||||
/// Deployed marker.
|
||||
/// Deployed marker. Same identity rule as the multi-instance guard: a same-named process
|
||||
/// in a user session is not the runtime and must not satisfy the verification.
|
||||
/// </summary>
|
||||
private static int WaitForDetachedRuntimePid(string exePath, AgentLogger logger)
|
||||
{
|
||||
@@ -742,16 +743,8 @@ namespace AutopilotMonitor.Agent.V2
|
||||
{
|
||||
try
|
||||
{
|
||||
var candidates = Process.GetProcessesByName(processName);
|
||||
try
|
||||
{
|
||||
var runtime = candidates.FirstOrDefault(p => p.Id != ownPid);
|
||||
if (runtime != null) return runtime.Id;
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var p in candidates) p.Dispose();
|
||||
}
|
||||
var runtimePid = FindSiblingAgentPid(SnapshotProcessesByName(processName), ownPid);
|
||||
if (runtimePid != 0) return runtimePid;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -273,7 +273,9 @@ namespace AutopilotMonitor.Agent.V2
|
||||
var registration = Runtime.BackendSessionRegistration.Register(
|
||||
bootstrap.AgentConfig, auth, telemetry.MtlsHttpClient, GetAgentVersion(), consoleMode, logger,
|
||||
rotateSession: () => Runtime.BackendSessionRegistration.RotateSession(
|
||||
bootstrap.AgentConfig, bootstrap.SessionPersistence, auth, transportDir, logger));
|
||||
bootstrap.AgentConfig, bootstrap.SessionPersistence, auth, transportDir, logger),
|
||||
sessionPersistence: bootstrap.SessionPersistence,
|
||||
configFetchOutcome: runtimeConfig.RemoteConfigService.LastFetchOutcome.ToString());
|
||||
if (registration.ShouldExit)
|
||||
{
|
||||
return registration.ExitCode;
|
||||
|
||||
@@ -87,7 +87,11 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
cleanupServiceFactory, logger, consoleMode,
|
||||
// Best-effort: surface the otherwise-silent 48h break to the backend before cleanup
|
||||
// (tasks/enrollment-status-reclassification.md). Never blocks the exit.
|
||||
onBreakFired: () => EmergencyBreakReporter.TrySend(agentConfig, Program.GetAgentVersion(), logger)))
|
||||
// The failed-registration record is read here, before the break deletes the
|
||||
// session files.
|
||||
onBreakFired: sessionAgeHours => EmergencyBreakReporter.TrySend(
|
||||
agentConfig, Program.GetAgentVersion(), sessionAgeHours,
|
||||
sessionPersistence.LoadRegistrationFailure(), logger)))
|
||||
{
|
||||
logger.Info("Emergency break fired — agent exiting.");
|
||||
return BootstrapResult.Exit(0);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Configuration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
@@ -17,7 +18,8 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
/// <c>IncrementSessionEventCountAsync</c> / <c>UpdateSessionStatusAsync</c> silently
|
||||
/// no-op and session status / phase / admin-overrides / validator reconcile all break.
|
||||
/// On registration failure we follow V1's rule: collectors MUST NOT start and the
|
||||
/// agent exits cleanly so the next Scheduled-Task tick can retry.
|
||||
/// agent exits cleanly; the Scheduled Task has only a boot trigger, so the next attempt is
|
||||
/// the next boot. The failed run is recorded for the emergency break report.
|
||||
/// </summary>
|
||||
internal static class BackendSessionRegistration
|
||||
{
|
||||
@@ -28,12 +30,19 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
string agentVersion,
|
||||
bool consoleMode,
|
||||
AgentLogger logger,
|
||||
Func<string> rotateSession = null)
|
||||
Func<string> rotateSession = null,
|
||||
SessionIdPersistence sessionPersistence = null,
|
||||
string configFetchOutcome = null)
|
||||
{
|
||||
if (agentConfig == null) throw new ArgumentNullException(nameof(agentConfig));
|
||||
if (auth == null) throw new ArgumentNullException(nameof(auth));
|
||||
if (logger == null) throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
// Wall clock on purpose: a window far above the retry schedule is the evidence that
|
||||
// the device slept or was suspended while this run tried to register.
|
||||
var startedUtc = DateTime.UtcNow;
|
||||
var linkUpAtStart = TryIsNetworkLinkUp();
|
||||
|
||||
var registrationResult = SessionRegistrationHelper.RegisterWithRetryAsync(
|
||||
apiClient: auth.BackendApiClient,
|
||||
agentConfig: agentConfig,
|
||||
@@ -48,6 +57,10 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
rotateSession: rotateSession)
|
||||
.GetAwaiter().GetResult();
|
||||
|
||||
RecordRegistrationRun(
|
||||
sessionPersistence, registrationResult, startedUtc, DateTime.UtcNow,
|
||||
linkUpAtStart, TryIsNetworkLinkUp(), configFetchOutcome, logger);
|
||||
|
||||
if (registrationResult.Outcome != SessionRegistrationOutcome.Succeeded)
|
||||
{
|
||||
logger.Error(
|
||||
@@ -65,13 +78,71 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
return SessionRegistrationOutcomeResult.Continue(registrationResult);
|
||||
}
|
||||
|
||||
/// <summary>Longest <see cref="RegistrationFailureSummary.LastError"/> kept on disk and on the wire.</summary>
|
||||
internal const int MaxRecordedErrorLength = 256;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps <c>registration-failure.json</c> in step with this run: a failed run is folded
|
||||
/// into the record (the emergency break later reports it — for a session that never
|
||||
/// registered, the only account of why), a successful one clears it. Never throws.
|
||||
/// </summary>
|
||||
internal static void RecordRegistrationRun(
|
||||
SessionIdPersistence sessionPersistence,
|
||||
SessionRegistrationResult registrationResult,
|
||||
DateTime startedUtc,
|
||||
DateTime endedUtc,
|
||||
bool? linkUpAtStart,
|
||||
bool? linkUpAtEnd,
|
||||
string configFetchOutcome,
|
||||
AgentLogger logger)
|
||||
{
|
||||
if (sessionPersistence == null || registrationResult == null) return;
|
||||
try
|
||||
{
|
||||
if (registrationResult.Outcome == SessionRegistrationOutcome.Succeeded)
|
||||
{
|
||||
sessionPersistence.ClearRegistrationFailure(logger);
|
||||
return;
|
||||
}
|
||||
|
||||
var error = registrationResult.ErrorMessage;
|
||||
if (error != null && error.Length > MaxRecordedErrorLength)
|
||||
error = error.Substring(0, MaxRecordedErrorLength);
|
||||
|
||||
sessionPersistence.RecordRegistrationFailure(new RegistrationFailureSummary
|
||||
{
|
||||
FailedRuns = 1,
|
||||
FirstFailedAtUtc = endedUtc,
|
||||
LastFailedAtUtc = endedUtc,
|
||||
Outcome = registrationResult.Outcome.ToString(),
|
||||
LastError = error,
|
||||
NetworkLinkUpAtStart = linkUpAtStart,
|
||||
NetworkLinkUpAtEnd = linkUpAtEnd,
|
||||
AttemptWindowSeconds = Math.Round(Math.Max(0, (endedUtc - startedUtc).TotalSeconds), 1),
|
||||
ConfigFetchOutcome = configFetchOutcome,
|
||||
}, logger);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger?.Warning($"Registration run record failed (best-effort): {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool? TryIsNetworkLinkUp()
|
||||
{
|
||||
try { return NetworkInterface.GetIsNetworkAvailable(); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SESSION-OWNER-BINDING: the one place that turns "backend says this session id is not
|
||||
/// ours" into a new session. Rotates the persisted id, points the runtime config at it,
|
||||
/// drops the transport spool (its lines carry the refused session's partition key and
|
||||
/// would otherwise be uploaded against it after the rotation) and re-targets the
|
||||
/// emergency reporter, which snapshotted the id before registration. Everything else
|
||||
/// reads <c>agentConfig.SessionId</c> live after Phase 6.
|
||||
/// emergency reporter, which snapshotted the id before registration. Everything else that
|
||||
/// holds a session id (orchestrator, emitters, spool) is built in Phase 7 from the rotated
|
||||
/// <c>agentConfig.SessionId</c> — keep it that way: a component built before Phase 6 needs
|
||||
/// its own re-target here.
|
||||
/// </summary>
|
||||
internal static string RotateSession(
|
||||
AgentConfiguration agentConfig,
|
||||
|
||||
@@ -36,15 +36,20 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
// Upper bound for the blocking wait: NIC wait + 3×15s attempts + 2×5s delays + slack.
|
||||
private static readonly TimeSpan OverallBudget = TimeSpan.FromSeconds(75);
|
||||
|
||||
public static void TrySend(AgentConfiguration agentConfig, string agentVersion, AgentLogger logger)
|
||||
public static void TrySend(
|
||||
AgentConfiguration agentConfig,
|
||||
string agentVersion,
|
||||
double sessionAgeHours,
|
||||
RegistrationFailureSummary priorRegistrationFailure,
|
||||
AgentLogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
WaitForNetwork(logger);
|
||||
|
||||
var auth = BackendClientFactory.BuildAuthClients(agentConfig, agentVersion, logger);
|
||||
var message =
|
||||
$"Agent absolute session-age emergency break fired (cap {agentConfig.AbsoluteMaxSessionHours}h) — cleaning up and exiting.";
|
||||
var roundedAgeHours = Math.Round(sessionAgeHours, 1);
|
||||
var message = BuildMessage(roundedAgeHours, agentConfig.AbsoluteMaxSessionHours, priorRegistrationFailure);
|
||||
|
||||
// The process is about to exit, so block on the otherwise fire-and-forget send
|
||||
// rather than let it be abandoned mid-flight. TrySendAsync swallows its own HTTP
|
||||
@@ -56,7 +61,9 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
message,
|
||||
attempts: SendAttempts,
|
||||
perAttemptTimeout: PerAttemptTimeout,
|
||||
retryDelay: RetryDelay)
|
||||
retryDelay: RetryDelay,
|
||||
sessionAgeHours: roundedAgeHours,
|
||||
priorRegistrationFailure: priorRegistrationFailure)
|
||||
.Wait(OverallBudget);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -65,6 +72,25 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invariant culture: the text lands in the backend's ops feed and timeline, and a device
|
||||
/// locale would otherwise print "478,2h". The registration clause names what the ops feed
|
||||
/// cannot otherwise show for a session that never registered.
|
||||
/// </summary>
|
||||
internal static string BuildMessage(double roundedAgeHours, int capHours, RegistrationFailureSummary priorRegistrationFailure)
|
||||
{
|
||||
var message = FormattableString.Invariant(
|
||||
$"Agent absolute session-age emergency break fired at session age {roundedAgeHours:F1}h (cap {capHours}h) — cleaning up and exiting.");
|
||||
if (priorRegistrationFailure != null && priorRegistrationFailure.FailedRuns > 0)
|
||||
{
|
||||
message += FormattableString.Invariant(
|
||||
$" {priorRegistrationFailure.FailedRuns} earlier start(s) failed to register (last: {priorRegistrationFailure.Outcome}, network link at end: {FormatLink(priorRegistrationFailure.NetworkLinkUpAtEnd)}).");
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
private static string FormatLink(bool? up) => up == null ? "unknown" : (up.Value ? "up" : "down");
|
||||
|
||||
/// <summary>
|
||||
/// Boot-time NIC grace: the break fires during bootstrap, often seconds after boot while
|
||||
/// Wi-Fi is still associating. Polls the cheap link-level signal — it cannot prove backend
|
||||
|
||||
@@ -522,7 +522,8 @@ namespace AutopilotMonitor.DecisionCore.Tests
|
||||
.WithSkipUserEsp(value: true, sourceSignalOrdinal: 4)
|
||||
.WithEspSyncFailureTimeoutMinutes(value: 90, sourceSignalOrdinal: 5)
|
||||
.WithRegistrySelfDeployingProfile(value: false, sourceSignalOrdinal: 6)
|
||||
.WithCloudPc(value: true, sourceSignalOrdinal: 7))
|
||||
.WithCloudPc(value: true, sourceSignalOrdinal: 7)
|
||||
.WithAccountSetupProgressAtWhiteGloveSuccess(value: false, sourceSignalOrdinal: 8))
|
||||
.Build();
|
||||
|
||||
var json = StateSerializer.Serialize(state);
|
||||
@@ -538,6 +539,8 @@ namespace AutopilotMonitor.DecisionCore.Tests
|
||||
Assert.Equal(6, o.RegistrySelfDeployingProfile!.SourceSignalOrdinal);
|
||||
Assert.True(o.CloudPc!.Value);
|
||||
Assert.Equal(7, o.CloudPc!.SourceSignalOrdinal);
|
||||
Assert.False(o.AccountSetupProgressAtWhiteGloveSuccess!.Value);
|
||||
Assert.Equal(8, o.AccountSetupProgressAtWhiteGloveSuccess!.SourceSignalOrdinal);
|
||||
|
||||
// Never-observed facts must rehydrate as null (null ≠ veto — session 62e603c9).
|
||||
Assert.Null(o.WhiteGloveSealingPatternSeen);
|
||||
|
||||
@@ -31,7 +31,6 @@ namespace AutopilotMonitor.DecisionCore.Tests
|
||||
DecisionSignalKind.HelloResolved,
|
||||
DecisionSignalKind.ImeUserSessionCompleted,
|
||||
DecisionSignalKind.DeviceSetupProvisioningComplete,
|
||||
DecisionSignalKind.WhiteGloveShellCoreSuccess,
|
||||
DecisionSignalKind.WhiteGloveSealingPatternDetected,
|
||||
DecisionSignalKind.AadUserJoinedLate,
|
||||
DecisionSignalKind.DeviceInfoCollected,
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.DecisionCore.Classifiers;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Serialization;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.DecisionCore.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// The sealing classifier's AccountSetup excluder (-40) applies only when the IME reported
|
||||
/// the AccountSetup phase AND the WhiteGlove_Success signal did not report an untouched
|
||||
/// AccountSetup registry. IME logs "EspPhase: AccountSetup" from the device session once
|
||||
/// the device apps are done — on pre-provisioning with the user ESP enabled that line
|
||||
/// routinely precedes the technician's success page and used to leave Part 1 unsealed.
|
||||
/// The gate may only ever lift the excluder, never add one.
|
||||
/// </summary>
|
||||
public sealed class WhiteGloveAccountSetupProgressGateTests
|
||||
{
|
||||
private static readonly DateTime T0 = new DateTime(2026, 9, 29, 7, 25, 9, DateTimeKind.Utc);
|
||||
|
||||
[Fact]
|
||||
public void Ime_account_setup_with_untouched_registry_seals_on_the_fast_path()
|
||||
{
|
||||
var step = new DecisionEngine().Reduce(
|
||||
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "false"));
|
||||
|
||||
Assert.Equal(SessionStage.WhiteGloveSealed, step.NewState.Stage);
|
||||
Assert.Equal(SessionOutcome.WhiteGlovePart1Sealed, step.NewState.Outcome);
|
||||
Assert.Equal(HypothesisLevel.Confirmed, step.NewState.ClassifierOutcomes.WhiteGloveSealing.Level);
|
||||
Assert.Equal(WhiteGloveSealingClassifier.WeightShellCoreWhiteGloveSuccess,
|
||||
step.NewState.ClassifierOutcomes.WhiteGloveSealing.Score);
|
||||
|
||||
var fact = step.NewState.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess;
|
||||
Assert.NotNull(fact);
|
||||
Assert.False(fact!.Value);
|
||||
Assert.Equal(3, fact.SourceSignalOrdinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ime_account_setup_with_registry_progress_keeps_the_excluder()
|
||||
{
|
||||
var step = new DecisionEngine().Reduce(
|
||||
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "true"));
|
||||
|
||||
Assert.Equal(SessionStage.EspAccountSetup, step.NewState.Stage);
|
||||
Assert.Contains(step.Effects, e => e.Kind == DecisionEffectKind.RunClassifier);
|
||||
Assert.True(DecisionEngine.BuildWhiteGloveSealingSnapshot(step.NewState).HasAccountSetupActivity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_progress_payload_keeps_the_excluder_for_older_agents()
|
||||
{
|
||||
var step = new DecisionEngine().Reduce(
|
||||
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: null));
|
||||
|
||||
Assert.Equal(SessionStage.EspAccountSetup, step.NewState.Stage);
|
||||
Assert.Null(step.NewState.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess);
|
||||
Assert.True(DecisionEngine.BuildWhiteGloveSealingSnapshot(step.NewState).HasAccountSetupActivity);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("yes")]
|
||||
public void Unparseable_progress_payload_is_treated_as_missing(string raw)
|
||||
{
|
||||
var step = new DecisionEngine().Reduce(
|
||||
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: raw));
|
||||
|
||||
Assert.Null(step.NewState.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess);
|
||||
Assert.NotEqual(SessionStage.WhiteGloveSealed, step.NewState.Stage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Registry_progress_without_ime_account_setup_adds_no_excluder()
|
||||
{
|
||||
var state = DecisionState.CreateInitial("s-gate", "t-gate").ToBuilder()
|
||||
.WithStage(SessionStage.EspDeviceSetup)
|
||||
.WithStepIndex(1)
|
||||
.WithLastAppliedSignalOrdinal(0)
|
||||
.Build();
|
||||
|
||||
var step = new DecisionEngine().Reduce(state, MakeShellCoreSignal(ordinal: 1, accountSetupProgress: "true"));
|
||||
|
||||
Assert.Equal(SessionStage.WhiteGloveSealed, step.NewState.Stage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Untouched_registry_does_not_lift_a_hard_excluder()
|
||||
{
|
||||
var builder = DecisionState.CreateInitial("s-gate", "t-gate").ToBuilder()
|
||||
.WithStage(SessionStage.EspAccountSetup)
|
||||
.WithStepIndex(3)
|
||||
.WithLastAppliedSignalOrdinal(2);
|
||||
builder.AccountSetupEnteredUtc = new SignalFact<DateTime>(T0.AddMinutes(-3), 1);
|
||||
builder.DesktopArrivedUtc = new SignalFact<DateTime>(T0.AddMinutes(-1), 2);
|
||||
|
||||
var step = new DecisionEngine().Reduce(builder.Build(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "false"));
|
||||
|
||||
Assert.NotEqual(SessionStage.WhiteGloveSealed, step.NewState.Stage);
|
||||
var snapshot = DecisionEngine.BuildWhiteGloveSealingSnapshot(step.NewState);
|
||||
Assert.False(snapshot.HasAccountSetupActivity);
|
||||
Assert.True(snapshot.DesktopArrived);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Progress_fact_survives_the_state_serializer()
|
||||
{
|
||||
var step = new DecisionEngine().Reduce(
|
||||
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "false"));
|
||||
|
||||
var roundTripped = StateSerializer.Deserialize(StateSerializer.Serialize(step.NewState));
|
||||
|
||||
var fact = roundTripped.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess;
|
||||
Assert.NotNull(fact);
|
||||
Assert.False(fact!.Value);
|
||||
Assert.Equal(3, fact.SourceSignalOrdinal);
|
||||
}
|
||||
|
||||
private static DecisionState StateWithImeAccountSetup()
|
||||
{
|
||||
// The IME device-session line: AccountSetup entered before the success page.
|
||||
var builder = DecisionState.CreateInitial("s-gate", "t-gate").ToBuilder()
|
||||
.WithStage(SessionStage.EspAccountSetup)
|
||||
.WithStepIndex(3)
|
||||
.WithLastAppliedSignalOrdinal(2);
|
||||
builder.AccountSetupEnteredUtc = new SignalFact<DateTime>(T0.AddMinutes(-3), 2);
|
||||
return builder.Build();
|
||||
}
|
||||
|
||||
private static DecisionSignal MakeShellCoreSignal(long ordinal, string? accountSetupProgress)
|
||||
{
|
||||
var payload = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
if (accountSetupProgress != null)
|
||||
{
|
||||
payload[SignalPayloadKeys.AccountSetupProgress] = accountSetupProgress;
|
||||
}
|
||||
|
||||
return new DecisionSignal(
|
||||
sessionSignalOrdinal: ordinal,
|
||||
sessionTraceOrdinal: ordinal,
|
||||
kind: DecisionSignalKind.WhiteGloveShellCoreSuccess,
|
||||
kindSchemaVersion: 1,
|
||||
occurredAtUtc: T0,
|
||||
sourceOrigin: "EspAndHelloTracker",
|
||||
evidence: new Evidence(
|
||||
kind: EvidenceKind.Raw,
|
||||
identifier: "ShellCore-62407",
|
||||
summary: "WhiteGlove_Success"),
|
||||
payload: payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user