@jjh32456/longlive 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
#requires -Version 5.1
|
|
2
|
+
<#
|
|
3
|
+
watch-loop.ps1 - resident watcher for dsh-longlive autoTruncate.
|
|
4
|
+
|
|
5
|
+
The plugin's "request" mode only publishes
|
|
6
|
+
<memoryRoot>\.longlive\logs\auto-truncate.request.json
|
|
7
|
+
and never touches the session. This loop is the resident consumer:
|
|
8
|
+
|
|
9
|
+
poll request file -> archive evidence -> run auto-truncate-run.ps1
|
|
10
|
+
(close app, cut visible log, verify, restart app) -> record result
|
|
11
|
+
|
|
12
|
+
Properties:
|
|
13
|
+
* single instance: named mutex + state\watcher.lock (pid/heartbeat)
|
|
14
|
+
* request parsing tolerates a half-written file (writer is atomic, but the
|
|
15
|
+
watcher still retries and then quarantines instead of crashing)
|
|
16
|
+
* failures keep evidence: archive\requests\<stamp>-<id>\ (request + runner
|
|
17
|
+
stdout/stderr + result json + evidence json)
|
|
18
|
+
* corrupt/stale/permanently-failed requests move to quarantine\
|
|
19
|
+
* log rotation: logs\watcher.log, 5 MB per file, 3 files total
|
|
20
|
+
* stale post-success requests are not executed twice
|
|
21
|
+
|
|
22
|
+
Exit codes: 0 stopped by stop.flag / another instance owns the mutex,
|
|
23
|
+
1 fatal error (Task Scheduler restarts the task),
|
|
24
|
+
2 bad config.
|
|
25
|
+
#>
|
|
26
|
+
param(
|
|
27
|
+
[string]$Config = '',
|
|
28
|
+
# data root for logs/state/archive; defaults to the package directory.
|
|
29
|
+
# Tests pass a sandbox here so they never mix evidence with production.
|
|
30
|
+
[string]$DataRoot = ''
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
$ErrorActionPreference = 'Stop'
|
|
34
|
+
$script:Root = if ($DataRoot) { $DataRoot } else { $PSScriptRoot }
|
|
35
|
+
$script:Version = '0.1.1'
|
|
36
|
+
# request states that must never be executed again: a replayed request with one
|
|
37
|
+
# of these states is quarantined instead of starting the runner a second time.
|
|
38
|
+
$script:TerminalStatuses = @('done', 'recovered', 'restart-failed', 'failed', 'request-stuck')
|
|
39
|
+
$script:LogPath = Join-Path $script:Root 'logs\watcher.log'
|
|
40
|
+
$script:StatePath = Join-Path $script:Root 'state\watcher-state.json'
|
|
41
|
+
$script:HeartbeatPath = Join-Path $script:Root 'state\heartbeat.json'
|
|
42
|
+
$script:LockPath = Join-Path $script:Root 'state\watcher.lock'
|
|
43
|
+
$script:StopFlag = Join-Path $script:Root 'state\stop.flag'
|
|
44
|
+
$script:OnceFlag = Join-Path $script:Root 'state\once.flag'
|
|
45
|
+
$script:StartedAt = (Get-Date)
|
|
46
|
+
|
|
47
|
+
function Write-WLog {
|
|
48
|
+
param([string]$Level, [string]$Message)
|
|
49
|
+
try {
|
|
50
|
+
if (Test-Path -LiteralPath $script:LogPath) {
|
|
51
|
+
$len = (Get-Item -LiteralPath $script:LogPath).Length
|
|
52
|
+
if ($len -ge [int64]$script:Cfg.logMaxBytes) { Rotate-Log }
|
|
53
|
+
}
|
|
54
|
+
$ts = (Get-Date).ToString('yyyy-MM-ddTHH:mm:ss.fffzzz')
|
|
55
|
+
$line = "[$ts] [$Level] [pid=$PID] $Message"
|
|
56
|
+
Add-Content -LiteralPath $script:LogPath -Value $line -Encoding UTF8
|
|
57
|
+
Write-Host $line
|
|
58
|
+
} catch {
|
|
59
|
+
# logging must never take the watcher down
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function Rotate-Log {
|
|
64
|
+
try {
|
|
65
|
+
$keep = [int]$script:Cfg.logKeep
|
|
66
|
+
if ($keep -lt 1) { $keep = 3 }
|
|
67
|
+
for ($i = $keep - 1; $i -ge 1; $i--) {
|
|
68
|
+
$src = "$($script:LogPath).$i"
|
|
69
|
+
if (-not (Test-Path -LiteralPath $src)) { continue }
|
|
70
|
+
$dst = "$($script:LogPath).$($i + 1)"
|
|
71
|
+
if ($i + 1 -ge $keep) {
|
|
72
|
+
Remove-Item -LiteralPath $src -Force -ErrorAction SilentlyContinue
|
|
73
|
+
} else {
|
|
74
|
+
Move-Item -LiteralPath $src -Destination $dst -Force -ErrorAction SilentlyContinue
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (Test-Path -LiteralPath $script:LogPath) {
|
|
78
|
+
Move-Item -LiteralPath $script:LogPath -Destination "$($script:LogPath).1" -Force
|
|
79
|
+
}
|
|
80
|
+
} catch {
|
|
81
|
+
# rotation is best effort
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function Get-CfgValue {
|
|
86
|
+
param($Object, [string]$Name, $Default)
|
|
87
|
+
if ($null -eq $Object) { return $Default }
|
|
88
|
+
$prop = $Object.PSObject.Properties[$Name]
|
|
89
|
+
if ($null -eq $prop -or $null -eq $prop.Value) { return $Default }
|
|
90
|
+
if ($prop.Value -is [string] -and $prop.Value -eq '') { return $Default }
|
|
91
|
+
return $prop.Value
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function Read-WatcherConfig {
|
|
95
|
+
param([string]$Path)
|
|
96
|
+
if (-not $Path) { $Path = Join-Path $script:Root 'config.json' }
|
|
97
|
+
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
|
|
98
|
+
Write-WLog 'ERROR' "config not found: $Path (run --install first)"
|
|
99
|
+
return $null
|
|
100
|
+
}
|
|
101
|
+
$raw = Get-Content -LiteralPath $Path -Raw -Encoding UTF8
|
|
102
|
+
$j = $raw | ConvertFrom-Json
|
|
103
|
+
$memoryRoot = [string](Get-CfgValue $j 'memoryRoot' '')
|
|
104
|
+
if (-not $memoryRoot) {
|
|
105
|
+
Write-WLog 'ERROR' "config has no memoryRoot: $Path"
|
|
106
|
+
return $null
|
|
107
|
+
}
|
|
108
|
+
$memoryRoot = $memoryRoot.TrimEnd('\', '/')
|
|
109
|
+
$requestPath = [string](Get-CfgValue $j 'requestPath' '')
|
|
110
|
+
if (-not $requestPath) {
|
|
111
|
+
$requestPath = Join-Path $memoryRoot '.longlive\logs\auto-truncate.request.json'
|
|
112
|
+
}
|
|
113
|
+
$cfg = [ordered]@{
|
|
114
|
+
version = [int](Get-CfgValue $j 'version' 1)
|
|
115
|
+
memoryRoot = $memoryRoot
|
|
116
|
+
requestPath = $requestPath
|
|
117
|
+
appExe = [string](Get-CfgValue $j 'appExe' '')
|
|
118
|
+
appArgs = [string](Get-CfgValue $j 'appArgs' '')
|
|
119
|
+
processName = [string](Get-CfgValue $j 'processName' 'DeepSeek Harness')
|
|
120
|
+
profile = [string](Get-CfgValue $j 'profile' 'desktop')
|
|
121
|
+
runnerPath = [string](Get-CfgValue $j 'runnerPath' (Join-Path $script:Root 'lib\auto-truncate-run.ps1'))
|
|
122
|
+
runnerLogDir = [string](Get-CfgValue $j 'runnerLogDir' (Join-Path $memoryRoot '.longlive\logs'))
|
|
123
|
+
pollSeconds = [int](Get-CfgValue $j 'pollSeconds' 2)
|
|
124
|
+
requestSettle = [int](Get-CfgValue $j 'requestSettleSeconds' 5)
|
|
125
|
+
cooldownSeconds = [int](Get-CfgValue $j 'cooldownSeconds' 90)
|
|
126
|
+
maxAttempts = [int](Get-CfgValue $j 'maxAttempts' 2)
|
|
127
|
+
retryDelay = [int](Get-CfgValue $j 'retryDelaySeconds' 30)
|
|
128
|
+
logMaxBytes = [int64](Get-CfgValue $j 'logMaxBytes' 5242880)
|
|
129
|
+
logKeep = [int](Get-CfgValue $j 'logKeep' 3)
|
|
130
|
+
taskName = [string](Get-CfgValue $j 'taskName' 'DshResidentWatcher')
|
|
131
|
+
}
|
|
132
|
+
if ($cfg.pollSeconds -lt 1) { $cfg.pollSeconds = 1 }
|
|
133
|
+
if ($cfg.logKeep -lt 1) { $cfg.logKeep = 3 }
|
|
134
|
+
if ($cfg.logMaxBytes -lt 65536) { $cfg.logMaxBytes = 5242880 }
|
|
135
|
+
return $cfg
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function Save-JsonFile {
|
|
139
|
+
param([string]$Path, $Value)
|
|
140
|
+
$tmp = "$Path.tmp-$PID"
|
|
141
|
+
$json = $Value | ConvertTo-Json -Depth 12
|
|
142
|
+
Set-Content -LiteralPath $tmp -Value $json -Encoding UTF8
|
|
143
|
+
Move-Item -LiteralPath $tmp -Destination $Path -Force
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function Read-State {
|
|
147
|
+
$state = [ordered]@{
|
|
148
|
+
version = 1
|
|
149
|
+
createdAt = (Get-Date).ToString('o')
|
|
150
|
+
lastRequestId = ''
|
|
151
|
+
lastSuccessAt = ''
|
|
152
|
+
lastStatus = ''
|
|
153
|
+
nextAttemptAt = ''
|
|
154
|
+
totals = @{ detected = 0; succeeded = 0; failed = 0; quarantined = 0; stale = 0; duplicateFailed = 0 }
|
|
155
|
+
requests = @{}
|
|
156
|
+
}
|
|
157
|
+
if (Test-Path -LiteralPath $script:StatePath) {
|
|
158
|
+
try {
|
|
159
|
+
$j = Get-Content -LiteralPath $script:StatePath -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
160
|
+
foreach ($name in @('lastRequestId', 'lastSuccessAt', 'lastStatus', 'nextAttemptAt')) {
|
|
161
|
+
if ($null -ne $j.PSObject.Properties[$name] -and $null -ne $j.$name) { $state[$name] = [string]$j.$name }
|
|
162
|
+
}
|
|
163
|
+
foreach ($name in @('detected', 'succeeded', 'failed', 'quarantined', 'stale', 'duplicateFailed')) {
|
|
164
|
+
if ($null -ne $j.totals -and $null -ne $j.totals.PSObject.Properties[$name]) {
|
|
165
|
+
$state.totals[$name] = [int]$j.totals.$name
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if ($null -ne $j.requests) {
|
|
169
|
+
foreach ($prop in $j.requests.PSObject.Properties) {
|
|
170
|
+
$state.requests[$prop.Name] = $prop.Value
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
Write-WLog 'WARN' "state file unreadable, starting fresh: $($_.Exception.Message)"
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return $state
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function Save-State {
|
|
181
|
+
param($State)
|
|
182
|
+
# keep the request journal bounded (oldest by .at first)
|
|
183
|
+
if ($State.requests.Count -gt 100) {
|
|
184
|
+
$ordered = $State.requests.GetEnumerator() | Sort-Object { [string]$_.Value.at }
|
|
185
|
+
$drop = $ordered | Select-Object -First ($State.requests.Count - 100)
|
|
186
|
+
foreach ($entry in $drop) { [void]$State.requests.Remove($entry.Key) }
|
|
187
|
+
}
|
|
188
|
+
Save-JsonFile $script:StatePath $State
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function Write-Heartbeat {
|
|
192
|
+
param($State, [int]$Loop, [string]$RunnerPid = '')
|
|
193
|
+
try {
|
|
194
|
+
$hb = [ordered]@{
|
|
195
|
+
at = (Get-Date).ToString('o')
|
|
196
|
+
pid = $PID
|
|
197
|
+
startedAt = $script:StartedAt.ToString('o')
|
|
198
|
+
loop = $Loop
|
|
199
|
+
version = $script:Version
|
|
200
|
+
config = (Join-Path $script:Root 'config.json')
|
|
201
|
+
requestExists = (Test-Path -LiteralPath $script:Cfg.requestPath -PathType Leaf)
|
|
202
|
+
lastStatus = [string]$State.lastStatus
|
|
203
|
+
runnerPid = $RunnerPid
|
|
204
|
+
}
|
|
205
|
+
Save-JsonFile $script:HeartbeatPath $hb
|
|
206
|
+
} catch {
|
|
207
|
+
# heartbeat is advisory only
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function Get-AppProcesses {
|
|
212
|
+
return @(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq $script:Cfg.processName })
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function Get-LedgerCount {
|
|
216
|
+
param([string]$SessionPath)
|
|
217
|
+
try {
|
|
218
|
+
$dir = Split-Path -Parent $SessionPath
|
|
219
|
+
$ledger = Join-Path $dir 'truncate-visible.json'
|
|
220
|
+
if (Test-Path -LiteralPath $ledger) {
|
|
221
|
+
$j = Get-Content -LiteralPath $ledger -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
222
|
+
if ($null -ne $j.truncations) { return @($j.truncations).Count }
|
|
223
|
+
}
|
|
224
|
+
} catch { }
|
|
225
|
+
return 0
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function Get-ArchiveCount {
|
|
229
|
+
param([string]$SessionPath)
|
|
230
|
+
try {
|
|
231
|
+
$dir = Split-Path -Parent $SessionPath
|
|
232
|
+
return @(Get-ChildItem -LiteralPath $dir -Directory -Filter '*.archive' -ErrorAction SilentlyContinue).Count
|
|
233
|
+
} catch { return 0 }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function Read-RequestFile {
|
|
237
|
+
param([string]$Path)
|
|
238
|
+
$lastError = ''
|
|
239
|
+
for ($attempt = 1; $attempt -le 6; $attempt++) {
|
|
240
|
+
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
|
|
241
|
+
return @{ ok = $false; absent = $true; error = 'file disappeared' }
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
$raw = [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8)
|
|
245
|
+
$obj = $raw | ConvertFrom-Json
|
|
246
|
+
return @{ ok = $true; request = $obj; raw = $raw }
|
|
247
|
+
} catch {
|
|
248
|
+
$lastError = $_.Exception.Message
|
|
249
|
+
Start-Sleep -Milliseconds 250
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return @{ ok = $false; absent = $false; error = $lastError }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function Move-ToQuarantine {
|
|
256
|
+
param([string]$Path, [string]$Reason, $Request)
|
|
257
|
+
try {
|
|
258
|
+
if (-not (Test-Path -LiteralPath $Path)) { return }
|
|
259
|
+
$stamp = (Get-Date).ToString('yyyyMMdd-HHmmss')
|
|
260
|
+
$id = 'unknown'
|
|
261
|
+
if ($null -ne $Request -and $null -ne $Request.PSObject.Properties['requestId']) { $id = [string]$Request.requestId }
|
|
262
|
+
$safe = ($id -replace '[^A-Za-z0-9._-]', '_')
|
|
263
|
+
$dest = Join-Path (Join-Path $script:Root 'quarantine') "$stamp-$safe.json"
|
|
264
|
+
Move-Item -LiteralPath $Path -Destination $dest -Force
|
|
265
|
+
Set-Content -LiteralPath "$dest.reason.txt" -Value $Reason -Encoding UTF8
|
|
266
|
+
Write-WLog 'WARN' "quarantine: $dest reason=$Reason"
|
|
267
|
+
} catch {
|
|
268
|
+
Write-WLog 'ERROR' "quarantine move failed: $($_.Exception.Message)"
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function Quote-Arg {
|
|
273
|
+
param([string]$Value)
|
|
274
|
+
if ($null -eq $Value) { return '""' }
|
|
275
|
+
return '"' + ($Value -replace '"', '\"') + '"'
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
# Read a key from a request journal entry. Entries are [ordered]@{} while the
|
|
279
|
+
# cycle is running and PSCustomObject after a state reload; PSObject.Properties
|
|
280
|
+
# only exists on the latter, so both shapes must be handled explicitly.
|
|
281
|
+
function Get-MapValue {
|
|
282
|
+
param($Map, [string]$Name, $Default = $null)
|
|
283
|
+
if ($null -eq $Map) { return $Default }
|
|
284
|
+
if ($Map -is [System.Collections.IDictionary]) {
|
|
285
|
+
if ($Map.Contains($Name)) {
|
|
286
|
+
$value = $Map[$Name]
|
|
287
|
+
if ($null -eq $value) { return $Default }
|
|
288
|
+
return $value
|
|
289
|
+
}
|
|
290
|
+
return $Default
|
|
291
|
+
}
|
|
292
|
+
$prop = $Map.PSObject.Properties[$Name]
|
|
293
|
+
if ($null -eq $prop -or $null -eq $prop.Value) { return $Default }
|
|
294
|
+
return $prop.Value
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function Get-FileLength {
|
|
298
|
+
param([string]$Path)
|
|
299
|
+
try {
|
|
300
|
+
if (Test-Path -LiteralPath $Path -PathType Leaf) { return [int64](Get-Item -LiteralPath $Path).Length }
|
|
301
|
+
} catch { }
|
|
302
|
+
return [int64]0
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
# Read only the bytes appended after $Offset: the runner log is shared by every
|
|
306
|
+
# request, so a whole-file scan could pick up an older result for the same id.
|
|
307
|
+
function Read-TextFromOffset {
|
|
308
|
+
param([string]$Path, [int64]$Offset = 0)
|
|
309
|
+
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return '' }
|
|
310
|
+
$fs = $null
|
|
311
|
+
$reader = $null
|
|
312
|
+
try {
|
|
313
|
+
$fs = [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
|
|
314
|
+
if ($Offset -lt 0 -or $Offset -gt $fs.Length) { $Offset = 0 }
|
|
315
|
+
[void]$fs.Seek($Offset, [System.IO.SeekOrigin]::Begin)
|
|
316
|
+
$reader = New-Object System.IO.StreamReader($fs, [System.Text.Encoding]::UTF8, $true)
|
|
317
|
+
return $reader.ReadToEnd()
|
|
318
|
+
} catch {
|
|
319
|
+
return ''
|
|
320
|
+
} finally {
|
|
321
|
+
if ($null -ne $reader) { $reader.Dispose() } elseif ($null -ne $fs) { $fs.Dispose() }
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function Write-FailedRecord {
|
|
326
|
+
param(
|
|
327
|
+
[string]$EvidenceDir,
|
|
328
|
+
[string]$RequestId,
|
|
329
|
+
[string]$Status,
|
|
330
|
+
$ExitCode,
|
|
331
|
+
[bool]$ExitCodeKnown,
|
|
332
|
+
[string]$Reason,
|
|
333
|
+
[int]$Attempts,
|
|
334
|
+
$Result,
|
|
335
|
+
[string]$ResultSource
|
|
336
|
+
)
|
|
337
|
+
try {
|
|
338
|
+
$record = [ordered]@{
|
|
339
|
+
ok = $false
|
|
340
|
+
requestId = $RequestId
|
|
341
|
+
status = $Status
|
|
342
|
+
exitCode = $ExitCode
|
|
343
|
+
exitCodeKnown = $ExitCodeKnown
|
|
344
|
+
reason = $Reason
|
|
345
|
+
attempts = $Attempts
|
|
346
|
+
resultStatus = $(if ($null -ne $Result) { [string](Get-MapValue $Result 'status' '') } else { '' })
|
|
347
|
+
resultOk = $(if ($null -ne $Result) { [bool](Get-MapValue $Result 'ok' $false) } else { $false })
|
|
348
|
+
resultSource = $ResultSource
|
|
349
|
+
failedAt = (Get-Date).ToString('o')
|
|
350
|
+
evidence = $EvidenceDir
|
|
351
|
+
}
|
|
352
|
+
Save-JsonFile (Join-Path $EvidenceDir 'failed.json') $record
|
|
353
|
+
return $true
|
|
354
|
+
} catch {
|
|
355
|
+
Write-WLog 'ERROR' "could not write failed.json: $($_.Exception.Message)"
|
|
356
|
+
return $false
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function Invoke-Runner {
|
|
361
|
+
param($Request, [string]$EvidenceDir)
|
|
362
|
+
$cfg = $script:Cfg
|
|
363
|
+
$runner = $cfg.runnerPath
|
|
364
|
+
$resultFile = Join-Path $EvidenceDir 'runner-result.json'
|
|
365
|
+
$outFile = Join-Path $EvidenceDir 'runner.out.txt'
|
|
366
|
+
$errFile = Join-Path $EvidenceDir 'runner.err.txt'
|
|
367
|
+
$empty = @{
|
|
368
|
+
started = $false; exitCode = $null; error = ''; pid = 0
|
|
369
|
+
startedAt = ''; endedAt = ''; durationMs = 0
|
|
370
|
+
outFile = $outFile; errFile = $errFile; resultFile = $resultFile
|
|
371
|
+
}
|
|
372
|
+
if (-not (Test-Path -LiteralPath $runner -PathType Leaf)) {
|
|
373
|
+
$empty.error = "runner not found: $runner"
|
|
374
|
+
return $empty
|
|
375
|
+
}
|
|
376
|
+
$pwsh = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
|
|
377
|
+
if (-not (Test-Path -LiteralPath $pwsh)) { $pwsh = 'powershell.exe' }
|
|
378
|
+
$parts = @(
|
|
379
|
+
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Quote-Arg $runner),
|
|
380
|
+
'-MemoryRoot', (Quote-Arg $cfg.memoryRoot),
|
|
381
|
+
'-RequestFile', (Quote-Arg $cfg.requestPath),
|
|
382
|
+
'-AppExe', (Quote-Arg $cfg.appExe),
|
|
383
|
+
'-Profile', (Quote-Arg $cfg.profile),
|
|
384
|
+
'-LogDir', (Quote-Arg $cfg.runnerLogDir)
|
|
385
|
+
)
|
|
386
|
+
if ($cfg.appArgs) { $parts += @('-AppArgs', (Quote-Arg $cfg.appArgs)) }
|
|
387
|
+
$argLine = ($parts -join ' ')
|
|
388
|
+
Write-WLog 'INFO' "runner start: $pwsh $argLine"
|
|
389
|
+
$startedAt = Get-Date
|
|
390
|
+
|
|
391
|
+
# P0-1: Start-Process -PassThru keeps ExitCode empty in Windows PowerShell
|
|
392
|
+
# 5.1 when stdout/stderr are redirected ("[int]$null" then reads as 0, i.e.
|
|
393
|
+
# every runner failure looked like success). Drive the process through
|
|
394
|
+
# System.Diagnostics.Process instead: ExitCode is real after WaitForExit().
|
|
395
|
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
396
|
+
$psi.FileName = $pwsh
|
|
397
|
+
$psi.Arguments = $argLine
|
|
398
|
+
$psi.UseShellExecute = $false
|
|
399
|
+
$psi.CreateNoWindow = $true
|
|
400
|
+
$psi.RedirectStandardOutput = $true
|
|
401
|
+
$psi.RedirectStandardError = $true
|
|
402
|
+
try { $psi.WorkingDirectory = $script:Root } catch { }
|
|
403
|
+
# The runner mirrors its result JSON here, so the watcher does not depend on
|
|
404
|
+
# parsing a shared log file. Runners that ignore the variable are covered by
|
|
405
|
+
# the log-offset fallback in Get-RunnerResult.
|
|
406
|
+
try { $psi.EnvironmentVariables['DSH_TRUNCATE_RESULT_FILE'] = $resultFile } catch { }
|
|
407
|
+
|
|
408
|
+
$proc = New-Object System.Diagnostics.Process
|
|
409
|
+
$proc.StartInfo = $psi
|
|
410
|
+
try {
|
|
411
|
+
if (-not $proc.Start()) { throw 'Process.Start returned false' }
|
|
412
|
+
} catch {
|
|
413
|
+
$message = $_.Exception.Message
|
|
414
|
+
try { $proc.Dispose() } catch { }
|
|
415
|
+
Write-WLog 'ERROR' "runner could not start: $message"
|
|
416
|
+
$empty.error = $message
|
|
417
|
+
$empty.startedAt = $startedAt.ToString('o')
|
|
418
|
+
$empty.endedAt = (Get-Date).ToString('o')
|
|
419
|
+
return $empty
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
$runnerPid = $proc.Id
|
|
423
|
+
$stdoutTask = $proc.StandardOutput.ReadToEndAsync()
|
|
424
|
+
$stderrTask = $proc.StandardError.ReadToEndAsync()
|
|
425
|
+
Write-WLog 'INFO' "runner pid=$runnerPid"
|
|
426
|
+
Write-Heartbeat -State $script:State -Loop $script:Loop -RunnerPid ([string]$runnerPid)
|
|
427
|
+
$proc.WaitForExit()
|
|
428
|
+
|
|
429
|
+
$stdout = ''
|
|
430
|
+
$stderr = ''
|
|
431
|
+
try { if ($stdoutTask.Wait(30000)) { $stdout = [string]$stdoutTask.Result } } catch { }
|
|
432
|
+
try { if ($stderrTask.Wait(30000)) { $stderr = [string]$stderrTask.Result } } catch { }
|
|
433
|
+
$endedAt = Get-Date
|
|
434
|
+
$utf8 = New-Object System.Text.UTF8Encoding($false)
|
|
435
|
+
try { [System.IO.File]::WriteAllText($outFile, $stdout, $utf8) } catch { }
|
|
436
|
+
try { [System.IO.File]::WriteAllText($errFile, $stderr, $utf8) } catch { }
|
|
437
|
+
|
|
438
|
+
$exitCode = $null
|
|
439
|
+
try { $exitCode = [int]$proc.ExitCode } catch { }
|
|
440
|
+
try { $proc.Dispose() } catch { }
|
|
441
|
+
return @{
|
|
442
|
+
started = $true
|
|
443
|
+
exitCode = $exitCode
|
|
444
|
+
pid = $runnerPid
|
|
445
|
+
startedAt = $startedAt.ToString('o')
|
|
446
|
+
endedAt = $endedAt.ToString('o')
|
|
447
|
+
durationMs = [int]($endedAt - $startedAt).TotalMilliseconds
|
|
448
|
+
outFile = $outFile
|
|
449
|
+
errFile = $errFile
|
|
450
|
+
resultFile = $resultFile
|
|
451
|
+
error = ''
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function Get-RunnerResult {
|
|
456
|
+
param([string]$RequestId, [string]$ResultFile = '', [int64]$LogOffset = 0)
|
|
457
|
+
# Preferred source: the per-request result file the runner was asked to
|
|
458
|
+
# write (DSH_TRUNCATE_RESULT_FILE). It cannot be confused with an older run.
|
|
459
|
+
if ($ResultFile -and (Test-Path -LiteralPath $ResultFile -PathType Leaf)) {
|
|
460
|
+
try {
|
|
461
|
+
$j = Get-Content -LiteralPath $ResultFile -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
462
|
+
if ($null -ne $j) {
|
|
463
|
+
$rid = [string](Get-MapValue $j 'requestId' '')
|
|
464
|
+
if (-not $rid -or $rid -eq $RequestId) {
|
|
465
|
+
return @{ result = $j; source = 'result-file' }
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
} catch { }
|
|
469
|
+
}
|
|
470
|
+
# Fallback: only the bytes appended to the shared result log during this
|
|
471
|
+
# run, so a stale line for the same id cannot be resurrected.
|
|
472
|
+
$log = Join-Path $script:Cfg.runnerLogDir 'auto-truncate.log'
|
|
473
|
+
$text = Read-TextFromOffset -Path $log -Offset $LogOffset
|
|
474
|
+
if (-not $text) { return $null }
|
|
475
|
+
$found = $null
|
|
476
|
+
foreach ($line in ($text -split "`r?`n")) {
|
|
477
|
+
$trim = $line.Trim()
|
|
478
|
+
$brace = $trim.IndexOf('{')
|
|
479
|
+
if ($brace -lt 0) { continue }
|
|
480
|
+
try { $j = $trim.Substring($brace) | ConvertFrom-Json } catch { continue }
|
|
481
|
+
$rid = [string](Get-MapValue $j 'requestId' '')
|
|
482
|
+
if ($rid -eq $RequestId) { $found = $j }
|
|
483
|
+
}
|
|
484
|
+
if ($null -eq $found) { return $null }
|
|
485
|
+
return @{ result = $found; source = 'runner-log' }
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function Invoke-RequestCycle {
|
|
489
|
+
param($State)
|
|
490
|
+
$cfg = $script:Cfg
|
|
491
|
+
$reqPath = $cfg.requestPath
|
|
492
|
+
|
|
493
|
+
$read = Read-RequestFile $reqPath
|
|
494
|
+
if ($read.absent) { return }
|
|
495
|
+
if (-not $read.ok) {
|
|
496
|
+
$age = 0
|
|
497
|
+
try { $age = ((Get-Date) - (Get-Item -LiteralPath $reqPath).LastWriteTime).TotalSeconds } catch { }
|
|
498
|
+
if ($age -ge $cfg.requestSettle) {
|
|
499
|
+
Write-WLog 'ERROR' "request unreadable after ${age}s: $($read.error)"
|
|
500
|
+
Move-ToQuarantine $reqPath "unreadable JSON: $($read.error)" $null
|
|
501
|
+
$State.totals.quarantined++
|
|
502
|
+
Save-State $State
|
|
503
|
+
} else {
|
|
504
|
+
Write-WLog 'WARN' "request still being written (age=${age}s), will retry"
|
|
505
|
+
}
|
|
506
|
+
return
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
$req = $read.request
|
|
510
|
+
$id = ''
|
|
511
|
+
if ($null -ne $req.PSObject.Properties['requestId']) { $id = [string]$req.requestId }
|
|
512
|
+
if (-not $id) {
|
|
513
|
+
Write-WLog 'ERROR' 'request has no requestId, quarantining'
|
|
514
|
+
Move-ToQuarantine $reqPath 'missing requestId' $req
|
|
515
|
+
$State.totals.quarantined++
|
|
516
|
+
Save-State $State
|
|
517
|
+
return
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
$known = $null
|
|
521
|
+
if ($State.requests.ContainsKey($id)) { $known = $State.requests[$id] }
|
|
522
|
+
|
|
523
|
+
if ($null -ne $known) {
|
|
524
|
+
# P0-2: $known is an [ordered]@{} in this process and a PSCustomObject
|
|
525
|
+
# after a state reload. PSObject.Properties is empty for the dictionary,
|
|
526
|
+
# so reading attempts that way returned 0 forever (infinite retry).
|
|
527
|
+
$knownStatus = [string](Get-MapValue $known 'status' '')
|
|
528
|
+
$attempts = [int](Get-MapValue $known 'attempts' 0)
|
|
529
|
+
if ($script:TerminalStatuses -contains $knownStatus) {
|
|
530
|
+
$knownEvidence = [string](Get-MapValue $known 'evidence' '')
|
|
531
|
+
if ($knownStatus -eq 'failed') {
|
|
532
|
+
$reason = "duplicate-failed: request $id already failed; runner not started again"
|
|
533
|
+
if ($knownEvidence) { $reason += " (evidence: $knownEvidence)" }
|
|
534
|
+
$State.totals.duplicateFailed++
|
|
535
|
+
$State.lastStatus = 'duplicate-failed'
|
|
536
|
+
Write-WLog 'WARN' $reason
|
|
537
|
+
} else {
|
|
538
|
+
$reason = "duplicate-finished: request $id already finished ($knownStatus)"
|
|
539
|
+
if ($knownEvidence) { $reason += " (evidence: $knownEvidence)" }
|
|
540
|
+
Write-WLog 'WARN' $reason
|
|
541
|
+
}
|
|
542
|
+
Move-ToQuarantine $reqPath $reason $req
|
|
543
|
+
$State.totals.quarantined++
|
|
544
|
+
Save-State $State
|
|
545
|
+
return
|
|
546
|
+
}
|
|
547
|
+
if ($attempts -ge $cfg.maxAttempts) {
|
|
548
|
+
Write-WLog 'ERROR' "request $id exhausted $attempts attempts, quarantining"
|
|
549
|
+
Move-ToQuarantine $reqPath "max attempts reached ($attempts)" $req
|
|
550
|
+
$State.totals.quarantined++
|
|
551
|
+
# terminal in the journal too: a replay must not reach the runner
|
|
552
|
+
# through this guard either
|
|
553
|
+
$entry = $State.requests[$id]
|
|
554
|
+
if ($entry -is [System.Collections.IDictionary]) { $entry['status'] = 'failed' } else { $entry.status = 'failed' }
|
|
555
|
+
Save-State $State
|
|
556
|
+
return
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
# a request produced before the last successful cut is obsolete: the cut
|
|
561
|
+
# already happened, re-running it would truncate a second time.
|
|
562
|
+
$reqAt = $null
|
|
563
|
+
if ($null -ne $req.PSObject.Properties['at']) {
|
|
564
|
+
try { $reqAt = [datetimeoffset]::Parse([string]$req.at, [System.Globalization.CultureInfo]::InvariantCulture) } catch { }
|
|
565
|
+
}
|
|
566
|
+
if ($reqAt -and $State.lastSuccessAt) {
|
|
567
|
+
try {
|
|
568
|
+
$lastOk = [datetimeoffset]::Parse([string]$State.lastSuccessAt, [System.Globalization.CultureInfo]::InvariantCulture)
|
|
569
|
+
if ($reqAt -le $lastOk) {
|
|
570
|
+
Write-WLog 'WARN' "request $id predates last success ($($State.lastSuccessAt)), quarantining as stale"
|
|
571
|
+
Move-ToQuarantine $reqPath "stale: request at $($req.at) <= last success $($State.lastSuccessAt)" $req
|
|
572
|
+
$State.totals.stale++
|
|
573
|
+
Save-State $State
|
|
574
|
+
return
|
|
575
|
+
}
|
|
576
|
+
} catch { }
|
|
577
|
+
}
|
|
578
|
+
if ($State.nextAttemptAt) {
|
|
579
|
+
try {
|
|
580
|
+
$next = [datetimeoffset]::Parse([string]$State.nextAttemptAt, [System.Globalization.CultureInfo]::InvariantCulture)
|
|
581
|
+
if ([datetimeoffset]::Now -lt $next) {
|
|
582
|
+
Write-WLog 'INFO' "request $id waiting for retry window ($($State.nextAttemptAt))"
|
|
583
|
+
return
|
|
584
|
+
}
|
|
585
|
+
} catch { }
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
$stamp = (Get-Date).ToString('yyyyMMdd-HHmmss')
|
|
589
|
+
$safeId = ($id -replace '[^A-Za-z0-9._-]', '_')
|
|
590
|
+
if ($safeId.Length -gt 40) { $safeId = $safeId.Substring(0, 40) }
|
|
591
|
+
$evDir = Join-Path (Join-Path $script:Root 'archive\requests') "$stamp-$safeId"
|
|
592
|
+
$n = 1
|
|
593
|
+
while (Test-Path -LiteralPath $evDir) { $n++; $evDir = Join-Path (Join-Path $script:Root 'archive\requests') "$stamp-$safeId-$n" }
|
|
594
|
+
New-Item -ItemType Directory -Path $evDir -Force | Out-Null
|
|
595
|
+
|
|
596
|
+
$sessionPath = ''
|
|
597
|
+
if ($null -ne $req.PSObject.Properties['sessionPath']) { $sessionPath = [string]$req.sessionPath }
|
|
598
|
+
$bytesBefore = 0
|
|
599
|
+
if ($sessionPath -and (Test-Path -LiteralPath $sessionPath -PathType Leaf)) {
|
|
600
|
+
$bytesBefore = (Get-Item -LiteralPath $sessionPath).Length
|
|
601
|
+
}
|
|
602
|
+
$ledgerBefore = 0
|
|
603
|
+
$archiveBefore = 0
|
|
604
|
+
if ($sessionPath) { $ledgerBefore = Get-LedgerCount $sessionPath; $archiveBefore = Get-ArchiveCount $sessionPath }
|
|
605
|
+
|
|
606
|
+
Set-Content -LiteralPath (Join-Path $evDir 'request.json') -Value $read.raw -Encoding UTF8
|
|
607
|
+
$startedAt = Get-Date
|
|
608
|
+
$State.totals.detected++
|
|
609
|
+
$attempts = 0
|
|
610
|
+
if ($null -ne $known) { $attempts = [int](Get-MapValue $known 'attempts' 0) }
|
|
611
|
+
$attempts++
|
|
612
|
+
$State.lastRequestId = $id
|
|
613
|
+
$State.lastStatus = 'running'
|
|
614
|
+
$State.requests[$id] = [ordered]@{
|
|
615
|
+
at = $(if ($reqAt) { $reqAt.ToString('o') } else { '' })
|
|
616
|
+
status = 'running'
|
|
617
|
+
attempts = $attempts
|
|
618
|
+
evidence = $evDir
|
|
619
|
+
updated = (Get-Date).ToString('o')
|
|
620
|
+
}
|
|
621
|
+
Save-State $State
|
|
622
|
+
Write-WLog 'INFO' "request $id detected: session=$sessionPath bytes=$bytesBefore ledger=$ledgerBefore archive=$archiveBefore"
|
|
623
|
+
|
|
624
|
+
$runLogPath = Join-Path $cfg.runnerLogDir 'auto-truncate.log'
|
|
625
|
+
$logOffset = Get-FileLength $runLogPath
|
|
626
|
+
$run = Invoke-Runner $req $evDir
|
|
627
|
+
$endedAt = Get-Date
|
|
628
|
+
$totalMs = [int]($endedAt - $startedAt).TotalMilliseconds
|
|
629
|
+
$found = Get-RunnerResult -RequestId $id -ResultFile ([string]$run.resultFile) -LogOffset $logOffset
|
|
630
|
+
$result = $null
|
|
631
|
+
$resultSource = ''
|
|
632
|
+
if ($null -ne $found) {
|
|
633
|
+
$result = $found.result
|
|
634
|
+
$resultSource = [string]$found.source
|
|
635
|
+
$result | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath (Join-Path $evDir 'result.json') -Encoding UTF8
|
|
636
|
+
}
|
|
637
|
+
$resultOk = ($null -ne $result) -and [bool](Get-MapValue $result 'ok' $false)
|
|
638
|
+
$resultStatus = $(if ($null -ne $result) { [string](Get-MapValue $result 'status' '') } else { '' })
|
|
639
|
+
$exitKnown = ($null -ne $run.exitCode)
|
|
640
|
+
$code = $(if ($exitKnown) { [int]$run.exitCode } else { -1 })
|
|
641
|
+
$codeLabel = $(if ($exitKnown) { "failed-$code" } else { 'failed-unknown' })
|
|
642
|
+
|
|
643
|
+
$bytesAfter = 0
|
|
644
|
+
if ($sessionPath -and (Test-Path -LiteralPath $sessionPath -PathType Leaf)) { $bytesAfter = (Get-Item -LiteralPath $sessionPath).Length }
|
|
645
|
+
$ledgerAfter = 0
|
|
646
|
+
$archiveAfter = 0
|
|
647
|
+
if ($sessionPath) { $ledgerAfter = Get-LedgerCount $sessionPath; $archiveAfter = Get-ArchiveCount $sessionPath }
|
|
648
|
+
$requestStillThere = Test-Path -LiteralPath $reqPath -PathType Leaf
|
|
649
|
+
$appCount = (Get-AppProcesses).Count
|
|
650
|
+
|
|
651
|
+
$evidence = [ordered]@{
|
|
652
|
+
requestId = $id
|
|
653
|
+
requestAt = $(if ($reqAt) { $reqAt.ToString('o') } else { '' })
|
|
654
|
+
detectedAt = $startedAt.ToString('o')
|
|
655
|
+
finishedAt = $endedAt.ToString('o')
|
|
656
|
+
totalMs = $totalMs
|
|
657
|
+
runnerStarted = $run.started
|
|
658
|
+
runnerPid = $run.pid
|
|
659
|
+
runnerExitCode = $run.exitCode
|
|
660
|
+
runnerExitCodeKnown = $exitKnown
|
|
661
|
+
runnerDurationMs = $run.durationMs
|
|
662
|
+
runnerError = $run.error
|
|
663
|
+
resultStatus = $resultStatus
|
|
664
|
+
resultOk = $resultOk
|
|
665
|
+
resultSource = $resultSource
|
|
666
|
+
sessionPath = $sessionPath
|
|
667
|
+
sessionBytesBefore = $bytesBefore
|
|
668
|
+
sessionBytesAfter = $bytesAfter
|
|
669
|
+
ledgerBefore = $ledgerBefore
|
|
670
|
+
ledgerAfter = $ledgerAfter
|
|
671
|
+
archiveBefore = $archiveBefore
|
|
672
|
+
archiveAfter = $archiveAfter
|
|
673
|
+
requestStillThere = $requestStillThere
|
|
674
|
+
appProcesses = $appCount
|
|
675
|
+
attempts = $attempts
|
|
676
|
+
}
|
|
677
|
+
$evidence | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $evDir 'evidence.json') -Encoding UTF8
|
|
678
|
+
|
|
679
|
+
# P0-1 double insurance: exit 0 alone is not success, the runner must also
|
|
680
|
+
# have written ok=true. Any disagreement between exit code and result is a
|
|
681
|
+
# failure; when the exit code is 0 we never retry (the cut may have
|
|
682
|
+
# happened), we quarantine instead.
|
|
683
|
+
$success = $run.started -and $exitKnown -and ($code -eq 0) -and $resultOk -and (-not $requestStillThere)
|
|
684
|
+
$requestStuck = $run.started -and $exitKnown -and ($code -eq 0) -and $resultOk -and $requestStillThere
|
|
685
|
+
$restartPath = $run.started -and (($code -eq 6) -or (($code -eq 0) -and ($resultStatus -eq 'restart-failed')))
|
|
686
|
+
|
|
687
|
+
$status = 'failed'
|
|
688
|
+
$outcome = ''
|
|
689
|
+
$failureReason = ''
|
|
690
|
+
|
|
691
|
+
if ($success) {
|
|
692
|
+
$status = 'done'
|
|
693
|
+
$outcome = 'success'
|
|
694
|
+
$State.totals.succeeded++
|
|
695
|
+
$State.lastSuccessAt = $endedAt.ToString('o')
|
|
696
|
+
$State.lastStatus = 'done'
|
|
697
|
+
$State.nextAttemptAt = ''
|
|
698
|
+
Write-WLog 'INFO' "request $id DONE exit=0 resultOk=True runnerMs=$($run.durationMs) totalMs=$totalMs bytes=$bytesBefore->$bytesAfter ledger=$ledgerBefore->$ledgerAfter app=$appCount requestPresent=False"
|
|
699
|
+
} elseif ($requestStuck) {
|
|
700
|
+
# P2: the cut happened but the request survived, so this is NOT a
|
|
701
|
+
# success and must not move the stale baseline (lastSuccessAt).
|
|
702
|
+
$status = 'request-stuck'
|
|
703
|
+
$outcome = 'request-stuck'
|
|
704
|
+
$failureReason = 'runner reported success (exit 0, ok=true) but the request file is still present'
|
|
705
|
+
$State.totals.failed++
|
|
706
|
+
$State.lastStatus = 'request-stuck'
|
|
707
|
+
$State.nextAttemptAt = ''
|
|
708
|
+
Write-WLog 'ERROR' "request $id STUCK: $failureReason"
|
|
709
|
+
Move-ToQuarantine $reqPath $failureReason $req
|
|
710
|
+
$State.totals.quarantined++
|
|
711
|
+
[void](Write-FailedRecord -EvidenceDir $evDir -RequestId $id -Status $status -ExitCode $run.exitCode -ExitCodeKnown $exitKnown -Reason $failureReason -Attempts $attempts -Result $result -ResultSource $resultSource)
|
|
712
|
+
} elseif ($restartPath) {
|
|
713
|
+
# cut+verify succeeded, only the restart failed. Re-running the request
|
|
714
|
+
# would cut a second time: try to start the app here and archive it.
|
|
715
|
+
$status = 'restart-failed'
|
|
716
|
+
$outcome = 'restart-failed'
|
|
717
|
+
$State.lastStatus = 'restart-failed'
|
|
718
|
+
Write-WLog 'ERROR' "request $id restart-failed (runner exit $code); attempting manual start"
|
|
719
|
+
try {
|
|
720
|
+
if ($script:Cfg.appArgs) {
|
|
721
|
+
Start-Process -FilePath $script:Cfg.appExe -ArgumentList $script:Cfg.appArgs | Out-Null
|
|
722
|
+
} else {
|
|
723
|
+
Start-Process -FilePath (Join-Path $env:WINDIR 'explorer.exe') -ArgumentList (Quote-Arg $script:Cfg.appExe) | Out-Null
|
|
724
|
+
}
|
|
725
|
+
Start-Sleep -Seconds 15
|
|
726
|
+
$after = (Get-AppProcesses).Count
|
|
727
|
+
if ($after -gt 0) {
|
|
728
|
+
$status = 'recovered'
|
|
729
|
+
$outcome = 'recovered'
|
|
730
|
+
$State.lastStatus = 'recovered'
|
|
731
|
+
$State.totals.succeeded++
|
|
732
|
+
Write-WLog 'INFO' "request $id recovered: app running after manual start ($after processes)"
|
|
733
|
+
} else {
|
|
734
|
+
Write-WLog 'ERROR' "request $id manual start did not bring the app back"
|
|
735
|
+
}
|
|
736
|
+
} catch {
|
|
737
|
+
Write-WLog 'ERROR' "request $id manual start failed: $($_.Exception.Message)"
|
|
738
|
+
}
|
|
739
|
+
if ($status -eq 'recovered') {
|
|
740
|
+
Move-ToQuarantine $reqPath "runner exit $code; cut applied, restart handled by watcher (recovered)" $req
|
|
741
|
+
$State.totals.quarantined++
|
|
742
|
+
} else {
|
|
743
|
+
$failureReason = "runner exit $code (restart-failed): cut applied but the app did not come back"
|
|
744
|
+
$State.totals.failed++
|
|
745
|
+
Move-ToQuarantine $reqPath $failureReason $req
|
|
746
|
+
$State.totals.quarantined++
|
|
747
|
+
[void](Write-FailedRecord -EvidenceDir $evDir -RequestId $id -Status $status -ExitCode $run.exitCode -ExitCodeKnown $exitKnown -Reason $failureReason -Attempts $attempts -Result $result -ResultSource $resultSource)
|
|
748
|
+
}
|
|
749
|
+
} else {
|
|
750
|
+
$State.totals.failed++
|
|
751
|
+
$permanent = $false
|
|
752
|
+
if (-not $run.started) {
|
|
753
|
+
$failureReason = "runner did not start: $($run.error)"
|
|
754
|
+
} elseif (-not $exitKnown) {
|
|
755
|
+
$permanent = $true
|
|
756
|
+
$failureReason = 'runner exited but its exit code could not be read'
|
|
757
|
+
} elseif ($code -eq 2 -or $code -eq 4 -or $code -eq 5) {
|
|
758
|
+
$permanent = $true
|
|
759
|
+
$failureReason = "runner exit $code"
|
|
760
|
+
if ($resultStatus) { $failureReason += " (result status=$resultStatus)" }
|
|
761
|
+
} elseif ($code -eq 0) {
|
|
762
|
+
$permanent = $true
|
|
763
|
+
if ($null -eq $result) {
|
|
764
|
+
$failureReason = 'runner exit 0 but no result record was found; refusing to retry an unverified success'
|
|
765
|
+
} else {
|
|
766
|
+
$failureReason = "runner exit 0 but result.ok=false (status=$resultStatus)"
|
|
767
|
+
}
|
|
768
|
+
} else {
|
|
769
|
+
$failureReason = "runner exit $code"
|
|
770
|
+
}
|
|
771
|
+
Write-WLog 'ERROR' "request $id failure: $failureReason"
|
|
772
|
+
if ($permanent) {
|
|
773
|
+
$status = 'failed'
|
|
774
|
+
$outcome = 'permanent-failure'
|
|
775
|
+
$State.lastStatus = $codeLabel
|
|
776
|
+
$State.nextAttemptAt = ''
|
|
777
|
+
Move-ToQuarantine $reqPath $failureReason $req
|
|
778
|
+
$State.totals.quarantined++
|
|
779
|
+
[void](Write-FailedRecord -EvidenceDir $evDir -RequestId $id -Status $status -ExitCode $run.exitCode -ExitCodeKnown $exitKnown -Reason $failureReason -Attempts $attempts -Result $result -ResultSource $resultSource)
|
|
780
|
+
} else {
|
|
781
|
+
$delay = [int]$script:Cfg.retryDelay
|
|
782
|
+
if ($delay -lt 0) { $delay = 0 }
|
|
783
|
+
Write-WLog 'WARN' "request $id transient failure: $failureReason; retry after $delay s (attempt $attempts/$($script:Cfg.maxAttempts))"
|
|
784
|
+
if ($attempts -ge [int]$script:Cfg.maxAttempts) {
|
|
785
|
+
$status = 'failed'
|
|
786
|
+
$outcome = 'exhausted'
|
|
787
|
+
$State.lastStatus = $codeLabel
|
|
788
|
+
$State.nextAttemptAt = ''
|
|
789
|
+
Move-ToQuarantine $reqPath "max attempts reached: $failureReason" $req
|
|
790
|
+
$State.totals.quarantined++
|
|
791
|
+
[void](Write-FailedRecord -EvidenceDir $evDir -RequestId $id -Status $status -ExitCode $run.exitCode -ExitCodeKnown $exitKnown -Reason "max attempts ($attempts) reached: $failureReason" -Attempts $attempts -Result $result -ResultSource $resultSource)
|
|
792
|
+
} else {
|
|
793
|
+
$status = 'retry'
|
|
794
|
+
$outcome = 'retry'
|
|
795
|
+
$State.nextAttemptAt = (Get-Date).AddSeconds($delay).ToString('o')
|
|
796
|
+
$State.lastStatus = "retry-$code"
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
$State.requests[$id] = [ordered]@{
|
|
802
|
+
at = $(if ($reqAt) { $reqAt.ToString('o') } else { '' })
|
|
803
|
+
status = $status
|
|
804
|
+
attempts = $attempts
|
|
805
|
+
exitCode = $(if ($exitKnown) { $code } else { $null })
|
|
806
|
+
exitCodeKnown = $exitKnown
|
|
807
|
+
outcome = $outcome
|
|
808
|
+
reason = $failureReason
|
|
809
|
+
evidence = $evDir
|
|
810
|
+
ms = $totalMs
|
|
811
|
+
updated = (Get-Date).ToString('o')
|
|
812
|
+
}
|
|
813
|
+
Save-State $State
|
|
814
|
+
Write-WLog 'INFO' "request $id finished status=$status outcome=$outcome exit=$code totalMs=$totalMs evidence=$evDir"
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
# ---------------------------------------------------------------------------
|
|
818
|
+
# startup
|
|
819
|
+
# ---------------------------------------------------------------------------
|
|
820
|
+
$script:Cfg = Read-WatcherConfig -Path $Config
|
|
821
|
+
if ($null -eq $script:Cfg) { exit 2 }
|
|
822
|
+
|
|
823
|
+
foreach ($d in @('logs', 'state', 'archive\requests', 'quarantine')) {
|
|
824
|
+
New-Item -ItemType Directory -Path (Join-Path $script:Root $d) -Force | Out-Null
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
$mutex = $null
|
|
828
|
+
foreach ($name in @('Global\DshResidentWatcher', 'Local\DshResidentWatcher')) {
|
|
829
|
+
try {
|
|
830
|
+
$mutex = New-Object System.Threading.Mutex($false, $name)
|
|
831
|
+
break
|
|
832
|
+
} catch { }
|
|
833
|
+
}
|
|
834
|
+
if ($null -eq $mutex) {
|
|
835
|
+
Write-WLog 'ERROR' 'cannot create the watcher mutex'
|
|
836
|
+
exit 1
|
|
837
|
+
}
|
|
838
|
+
$owned = $false
|
|
839
|
+
try {
|
|
840
|
+
$owned = $mutex.WaitOne(0)
|
|
841
|
+
} catch [System.Threading.AbandonedMutexException] {
|
|
842
|
+
# the previous owner died without releasing it; we are the owner now
|
|
843
|
+
$owned = $true
|
|
844
|
+
}
|
|
845
|
+
if (-not $owned) {
|
|
846
|
+
Write-WLog 'WARN' 'another watcher instance already owns the mutex; exiting'
|
|
847
|
+
exit 0
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
$script:State = Read-State
|
|
851
|
+
$script:Loop = 0
|
|
852
|
+
|
|
853
|
+
if (Test-Path -LiteralPath $script:LockPath) {
|
|
854
|
+
try {
|
|
855
|
+
$old = Get-Content -LiteralPath $script:LockPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
856
|
+
$oldPid = [int]$old.pid
|
|
857
|
+
if ($oldPid -and $oldPid -ne $PID) {
|
|
858
|
+
$proc = Get-Process -Id $oldPid -ErrorAction SilentlyContinue
|
|
859
|
+
if ($proc -and $proc.ProcessName -like 'powershell*') {
|
|
860
|
+
Write-WLog 'WARN' "stale lock points at a live powershell pid=$oldPid; exiting"
|
|
861
|
+
$mutex.ReleaseMutex()
|
|
862
|
+
exit 0
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
} catch { }
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
$lock = [ordered]@{
|
|
869
|
+
pid = $PID
|
|
870
|
+
startedAt = $script:StartedAt.ToString('o')
|
|
871
|
+
version = $script:Version
|
|
872
|
+
config = (Join-Path $script:Root 'config.json')
|
|
873
|
+
taskName = $script:Cfg.taskName
|
|
874
|
+
}
|
|
875
|
+
Save-JsonFile $script:LockPath $lock
|
|
876
|
+
Write-WLog 'INFO' "watcher start version=$($script:Version) pid=$PID request=$($script:Cfg.requestPath) memoryRoot=$($script:Cfg.memoryRoot) poll=$($script:Cfg.pollSeconds)s"
|
|
877
|
+
Write-Heartbeat -State $script:State -Loop 0
|
|
878
|
+
|
|
879
|
+
$exitCode = 0
|
|
880
|
+
try {
|
|
881
|
+
$lastAliveLog = Get-Date
|
|
882
|
+
while (-not (Test-Path -LiteralPath $script:StopFlag)) {
|
|
883
|
+
$script:Loop++
|
|
884
|
+
if ((Get-Date) - $lastAliveLog -ge [TimeSpan]::FromMinutes(5)) {
|
|
885
|
+
Write-WLog 'INFO' "alive loop=$($script:Loop) pending=$(Test-Path -LiteralPath $script:Cfg.requestPath -PathType Leaf) app=$((Get-AppProcesses).Count)"
|
|
886
|
+
$lastAliveLog = Get-Date
|
|
887
|
+
}
|
|
888
|
+
Write-Heartbeat -State $script:State -Loop $script:Loop
|
|
889
|
+
try {
|
|
890
|
+
Invoke-RequestCycle $script:State
|
|
891
|
+
} catch {
|
|
892
|
+
Write-WLog 'ERROR' "request cycle failed: $($_.Exception.Message) at $($_.InvocationInfo.PositionMessage)"
|
|
893
|
+
}
|
|
894
|
+
Start-Sleep -Seconds ([int]$script:Cfg.pollSeconds)
|
|
895
|
+
if (Test-Path -LiteralPath $script:OnceFlag) {
|
|
896
|
+
Write-WLog 'INFO' 'once flag detected, finishing after one cycle'
|
|
897
|
+
Remove-Item -LiteralPath $script:OnceFlag -Force -ErrorAction SilentlyContinue
|
|
898
|
+
break
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
Write-WLog 'INFO' 'stop flag detected, exiting'
|
|
902
|
+
} catch {
|
|
903
|
+
Write-WLog 'ERROR' "fatal: $($_.Exception.Message) $($_.ScriptStackTrace)"
|
|
904
|
+
$exitCode = 1
|
|
905
|
+
} finally {
|
|
906
|
+
try { if (Test-Path -LiteralPath $script:StopFlag) { Remove-Item -LiteralPath $script:StopFlag -Force -ErrorAction SilentlyContinue } } catch { }
|
|
907
|
+
try {
|
|
908
|
+
if (Test-Path -LiteralPath $script:LockPath) {
|
|
909
|
+
$cur = Get-Content -LiteralPath $script:LockPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
910
|
+
if ([int]$cur.pid -eq $PID) { Remove-Item -LiteralPath $script:LockPath -Force }
|
|
911
|
+
}
|
|
912
|
+
} catch { }
|
|
913
|
+
try { $mutex.ReleaseMutex() } catch { }
|
|
914
|
+
try { $mutex.Dispose() } catch { }
|
|
915
|
+
}
|
|
916
|
+
exit $exitCode
|