[CmdletBinding()] param( [string]$OutputPath = (Join-Path $PSScriptRoot '../output/status.json'), [string]$OverridesPath, [string]$AliasesPath, [string]$CodexAutomationsPath, [switch]$IncludeScheduledTasks, [string]$WorkflowRepository, [string]$WorkflowId, [string]$SchedulerLogRoot ) $ErrorActionPreference = 'Stop' . (Join-Path $PSScriptRoot 'workflow-run-status.ps1') $records = [System.Collections.Generic.List[object]]::new() $aliasesByTarget = @{} if ($AliasesPath -and (Test-Path -LiteralPath $AliasesPath)) { $aliasPayload = Get-Content -LiteralPath $AliasesPath -Raw | ConvertFrom-Json foreach ($mapping in @($aliasPayload.mappings)) { $target = [string]$mapping.target if (-not [string]::IsNullOrWhiteSpace($target)) { $aliasesByTarget[$target.ToLowerInvariant()] = @($mapping.aliases) } } } function Get-CalendarRefreshResult { param([string]$Text) # Only the latest run and statements about this refresh are evidence. # Counts of failed managed jobs describe other automations, not this job. $headers = [regex]::Matches($Text, '(?m)^- Run time:\s*([^\r\n]+)') if (-not $headers.Count) { return [pscustomobject]@{ outcome = 'unknown'; lastRun = $null } } $header = $headers[$headers.Count - 1] $section = $Text.Substring($header.Index + $header.Length) $outcome = 'unknown' foreach ($line in ($section -split '\r?\n')) { if ($line -notmatch 'refresh_automations_calendar\.ps1|requested refresh|refresh (?:failed|succeeded|completed)|script exited') { continue } if ($line -match '(?i)\b(failed|blocked|rejected|denied|fatal)\b|exited with code [1-9]') { $outcome = 'failure' } elseif ($line -match '(?i)\b(successfully|succeeded)\b|completed successfully') { $outcome = 'success' } } $timestamp = $null $parsed = [DateTimeOffset]::MinValue if ([DateTimeOffset]::TryParse($header.Groups[1].Value.Trim(), [ref]$parsed)) { $timestamp = $parsed.ToString('o') } return [pscustomobject]@{ outcome = $outcome; lastRun = $timestamp } } function Get-ConfiguredAliases { param([string[]]$Targets) $found = [System.Collections.Generic.List[string]]::new() foreach ($target in $Targets) { if ([string]::IsNullOrWhiteSpace($target)) { continue } $key = $target.ToLowerInvariant() if ($aliasesByTarget.ContainsKey($key)) { foreach ($alias in @($aliasesByTarget[$key])) { if (-not [string]::IsNullOrWhiteSpace([string]$alias) -and -not $found.Contains([string]$alias)) { $found.Add([string]$alias) } } } } return @($found) } if ($IncludeScheduledTasks) { try { foreach ($task in Get-ScheduledTask -ErrorAction Stop) { try { $info = Get-ScheduledTaskInfo -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop $hasRun = $info.LastRunTime -and $info.LastRunTime.Year -gt 2000 $outcome = if (-not $hasRun) { 'unknown' } elseif ($info.LastTaskResult -eq 267009) { 'unknown' } elseif ($info.LastTaskResult -eq 0) { 'success' } else { 'failure' } $records.Add([pscustomobject]@{ name = $task.TaskName aliases = @(Get-ConfiguredAliases -Targets @($task.TaskName, "$($task.TaskPath)$($task.TaskName)")) outcome = $outcome lastRun = if ($hasRun) { $info.LastRunTime.ToString('o') } else { $null } detail = if ($hasRun) { "Windows Task Scheduler result: $($info.LastTaskResult). State: $($task.State)." } else { 'Windows Task Scheduler reports no completed run.' } source = 'windows-task-scheduler' }) } catch { $records.Add([pscustomobject]@{ name = $task.TaskName; aliases = @(); outcome = 'unknown'; lastRun = $null; detail = $_.Exception.Message; source = 'windows-task-scheduler' }) } } } catch { Write-Warning "Could not query Windows Task Scheduler: $($_.Exception.Message)" } } if ($CodexAutomationsPath -and (Test-Path -LiteralPath $CodexAutomationsPath)) { foreach ($folder in Get-ChildItem -LiteralPath $CodexAutomationsPath -Directory) { $definition = Join-Path $folder.FullName 'automation.toml' if (-not (Test-Path -LiteralPath $definition)) { continue } $definitionText = Get-Content -LiteralPath $definition -Raw $nameMatch = [regex]::Match($definitionText, '(?m)^name\s*=\s*"([^"]+)"') $name = if ($nameMatch.Success) { $nameMatch.Groups[1].Value } else { $folder.Name } $memory = Join-Path $folder.FullName 'memory.md' $outcome = 'unknown' $lastRun = $null $detail = 'Codex automation exists, but no verifiable run result was found.' if (Test-Path -LiteralPath $memory) { $memoryItem = Get-Item -LiteralPath $memory $lastRun = $memoryItem.LastWriteTime.ToString('o') $tail = (Get-Content -LiteralPath $memory -Tail 120) -join "`n" $failureMatches = [regex]::Matches($tail, '(?i)\b(failed|failure|blocked|fatal|error)\b') $successMatches = [regex]::Matches($tail, '(?i)\b(success|successful|completed|passed|refreshed|created|updated|wrote)\b') $lastFailure = if ($failureMatches.Count) { $failureMatches[$failureMatches.Count - 1].Index } else { -1 } $lastSuccess = if ($successMatches.Count) { $successMatches[$successMatches.Count - 1].Index } else { -1 } if ($lastSuccess -gt $lastFailure) { $outcome = 'success' } elseif ($lastFailure -gt $lastSuccess) { $outcome = 'failure' } $detail = "Best-effort result from the latest Codex automation memory for $($folder.Name); inspect memory.md when investigating." if ($folder.Name -eq 'automations-calendar-refresh') { $refreshResult = Get-CalendarRefreshResult -Text (Get-Content -LiteralPath $memory -Raw) $outcome = $refreshResult.outcome $lastRun = $refreshResult.lastRun $detail = "Latest recorded calendar refresh: $outcome. Based on the refresh's own execution statement, excluding outcome counts for other jobs. Evidence: $($folder.Name)/memory.md" } } $statusSource = 'codex-automation-memory' $configuredAliases = @(Get-ConfiguredAliases -Targets @($name, $folder.Name)) $records.Add([pscustomobject]@{ name = $name aliases = @(@($folder.Name) + $configuredAliases | Select-Object -Unique) outcome = $outcome lastRun = $lastRun detail = $detail source = $statusSource }) } } if ($WorkflowRepository -or $WorkflowId -or $SchedulerLogRoot) { if (-not $WorkflowRepository -or -not $WorkflowId) { throw 'WorkflowRepository and WorkflowId must be specified together.' } $workflow = Get-WorkflowRunStatus -Repository $WorkflowRepository -WorkflowId $WorkflowId -LogRoot $SchedulerLogRoot $records.Add([pscustomobject]@{ name = $WorkflowId aliases = @(Get-ConfiguredAliases -Targets @($WorkflowId)) outcome = if ($workflow) { $workflow.outcome } else { 'unknown' } lastRun = if ($workflow) { $workflow.time.ToString('o') } else { $null } detail = if ($workflow) { $workflow.detail } else { 'No verified receipt or scheduler failure was found.' } source = if ($workflow) { $workflow.source } else { 'none' } }) } if ($OverridesPath -and (Test-Path -LiteralPath $OverridesPath)) { $overridePayload = Get-Content -LiteralPath $OverridesPath -Raw | ConvertFrom-Json $overrideRecords = if ($overridePayload.records) { $overridePayload.records } else { $overridePayload } foreach ($override in @($overrideRecords)) { $records.Add($override) } } $now = Get-Date $today = $now.ToString('yyyy-MM-dd') $target = [System.IO.Path]::GetFullPath($OutputPath) $priorHistory = @() if (Test-Path -LiteralPath $target) { try { $existingPayload = Get-Content -LiteralPath $target -Raw | ConvertFrom-Json $priorHistory = @($existingPayload.history) } catch { $priorHistory = @() } } $snapshot = [ordered]@{ date = $today generatedAt = $now.ToUniversalTime().ToString('o') records = @($records) } $history = @($priorHistory | Where-Object { $_.date -ne $today }) + @([pscustomobject]$snapshot) $history = @($history | Sort-Object date -Descending | Select-Object -First 3) $payload = [ordered]@{ generatedAt = $now.ToUniversalTime().ToString('o') note = 'Success and failure are shown only when a local scheduler, Codex memory, or explicit override supplies evidence. Unknown is preserved instead of guessing.' records = $records history = $history } [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($target)) | Out-Null $temp = "$target.tmp" $payload | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $temp -Encoding utf8 Move-Item -LiteralPath $temp -Destination $target -Force Write-Output "Wrote $target with $($records.Count) status records."