@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,643 @@
|
|
|
1
|
+
#requires -Version 5.1
|
|
2
|
+
param(
|
|
3
|
+
[Parameter(ValueFromRemainingArguments = $true)]
|
|
4
|
+
[string[]]$RestArgs = @()
|
|
5
|
+
)
|
|
6
|
+
# Keep the historical $args contract: this script and its thin wrappers pass
|
|
7
|
+
# tokens such as --install / --status / --once through @args / $args.
|
|
8
|
+
$args = $RestArgs
|
|
9
|
+
|
|
10
|
+
<#
|
|
11
|
+
resident-watcher.ps1 - install / uninstall / status / run / once
|
|
12
|
+
|
|
13
|
+
Keeps the dsh-longlive "autoTruncate request" consumer alive without
|
|
14
|
+
a human: a Scheduled Task (AtLogOn) starts watch-loop.ps1 in the interactive
|
|
15
|
+
user session, where it can close the GUI app, cut the session log, verify it
|
|
16
|
+
and start the app again.
|
|
17
|
+
|
|
18
|
+
Usage (Windows PowerShell 5.1):
|
|
19
|
+
powershell -NoProfile -ExecutionPolicy Bypass -File resident-watcher.ps1 --install
|
|
20
|
+
powershell ... resident-watcher.ps1 --status
|
|
21
|
+
powershell ... resident-watcher.ps1 --uninstall
|
|
22
|
+
powershell ... resident-watcher.ps1 --run (foreground loop)
|
|
23
|
+
powershell ... resident-watcher.ps1 --once (one poll cycle, for tests)
|
|
24
|
+
|
|
25
|
+
Install options:
|
|
26
|
+
--memory-root <path> memory store that holds .longlive\logs (default: auto)
|
|
27
|
+
--app-exe <path> DeepSeek Harness.exe (default: running process / default install)
|
|
28
|
+
--app-args <string> arguments used when the watcher restarts the app
|
|
29
|
+
--profile <name> dsh profile name (default desktop)
|
|
30
|
+
--task-name <name> scheduled task name (default DshResidentWatcher)
|
|
31
|
+
--no-start register the task but do not start it now
|
|
32
|
+
--json machine-readable output (status / install)
|
|
33
|
+
#>
|
|
34
|
+
|
|
35
|
+
$ErrorActionPreference = 'Stop'
|
|
36
|
+
$script:Root = $PSScriptRoot
|
|
37
|
+
$script:Version = '0.1.1'
|
|
38
|
+
$script:ConfigPath = Join-Path $script:Root 'config.json'
|
|
39
|
+
$script:LoopScript = Join-Path $script:Root 'watch-loop.ps1'
|
|
40
|
+
$script:StopFlag = Join-Path $script:Root 'state\stop.flag'
|
|
41
|
+
$script:OnceFlag = Join-Path $script:Root 'state\once.flag'
|
|
42
|
+
$script:LockPath = Join-Path $script:Root 'state\watcher.lock'
|
|
43
|
+
$script:StatePath = Join-Path $script:Root 'state\watcher-state.json'
|
|
44
|
+
$script:HeartbeatPath = Join-Path $script:Root 'state\heartbeat.json'
|
|
45
|
+
$script:TaskName = 'DshResidentWatcher'
|
|
46
|
+
|
|
47
|
+
function Write-Line {
|
|
48
|
+
param([string]$Text = '')
|
|
49
|
+
Write-Host $Text
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function Get-OptValue {
|
|
53
|
+
param($Table, [string]$Name, $Default = '')
|
|
54
|
+
if ($Table.ContainsKey($Name) -and $Table[$Name]) { return $Table[$Name] }
|
|
55
|
+
return $Default
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function Resolve-MemoryRoot {
|
|
59
|
+
param([string]$Explicit, [string]$Profile)
|
|
60
|
+
if ($Explicit) { return $Explicit.TrimEnd('\', '/') }
|
|
61
|
+
$patch = Join-Path $env:USERPROFILE ".dsh\profiles\$Profile\cordis.patch.yml"
|
|
62
|
+
if (Test-Path -LiteralPath $patch) {
|
|
63
|
+
$text = Get-Content -LiteralPath $patch -Raw -Encoding UTF8
|
|
64
|
+
$m = [regex]::Match($text, '(?m)^\s*memoryRoot:\s*["'']?([^"''\r\n]+?)["'']?\s*$')
|
|
65
|
+
if ($m.Success) {
|
|
66
|
+
$candidate = $m.Groups[1].Value.Trim()
|
|
67
|
+
if ($candidate) { return $candidate.TrimEnd('\', '/') }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
foreach ($candidate in @(
|
|
71
|
+
(Join-Path $env:USERPROFILE 'dsh-memory'),
|
|
72
|
+
(Join-Path $env:USERPROFILE '.dsh\longlive-memory'))) {
|
|
73
|
+
if (Test-Path -LiteralPath (Join-Path $candidate '.longlive') -PathType Container) {
|
|
74
|
+
return $candidate.TrimEnd('\', '/')
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return (Join-Path $env:USERPROFILE 'dsh-memory')
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function Find-AppExe {
|
|
81
|
+
param([string]$Explicit)
|
|
82
|
+
if ($Explicit -and (Test-Path -LiteralPath $Explicit -PathType Leaf)) { return $Explicit }
|
|
83
|
+
try {
|
|
84
|
+
$p = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Select-Object -First 1
|
|
85
|
+
if ($p -and $p.Path -and (Test-Path -LiteralPath $p.Path -PathType Leaf)) { return $p.Path }
|
|
86
|
+
} catch { }
|
|
87
|
+
$candidate = Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'
|
|
88
|
+
if (Test-Path -LiteralPath $candidate -PathType Leaf) { return $candidate }
|
|
89
|
+
return ''
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function Find-AppArgs {
|
|
93
|
+
try {
|
|
94
|
+
$procs = Get-CimInstance Win32_Process -Filter "Name='DeepSeek Harness.exe'" -ErrorAction SilentlyContinue
|
|
95
|
+
foreach ($p in $procs) {
|
|
96
|
+
if ($p.CommandLine -and $p.CommandLine -match '(--remote-debugging-port=\d+)') { return $Matches[1] }
|
|
97
|
+
}
|
|
98
|
+
} catch { }
|
|
99
|
+
return ''
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function Test-WatcherProcess {
|
|
103
|
+
param([int]$ProcessId)
|
|
104
|
+
if (-not $ProcessId) { return $null }
|
|
105
|
+
try { return (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue) } catch { return $null }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function Get-WatcherLock {
|
|
109
|
+
if (-not (Test-Path -LiteralPath $script:LockPath)) { return $null }
|
|
110
|
+
try { return (Get-Content -LiteralPath $script:LockPath -Raw -Encoding UTF8 | ConvertFrom-Json) } catch { return $null }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function Read-ConfigFile {
|
|
114
|
+
if (-not (Test-Path -LiteralPath $script:ConfigPath -PathType Leaf)) { return $null }
|
|
115
|
+
try { return (Get-Content -LiteralPath $script:ConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json) } catch { return $null }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function Get-ConfigValue {
|
|
119
|
+
param($Config, [string]$Name, $Default = $null)
|
|
120
|
+
if ($null -eq $Config) { return $Default }
|
|
121
|
+
$prop = $Config.PSObject.Properties[$Name]
|
|
122
|
+
if ($null -eq $prop) { return $Default }
|
|
123
|
+
if ($null -eq $prop.Value) { return $Default }
|
|
124
|
+
return $prop.Value
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
# P2 root cause: the installed task is named after config.json's taskName
|
|
128
|
+
# (DshResidentWatcherAuto), but status used to query the hardcoded default
|
|
129
|
+
# DshResidentWatcher, so an existing running task showed up as task=null.
|
|
130
|
+
function Resolve-WatcherTaskName {
|
|
131
|
+
param($Opts, $Config)
|
|
132
|
+
$name = ''
|
|
133
|
+
$source = ''
|
|
134
|
+
if ($Opts -and $Opts.ContainsKey('taskName') -and $Opts['taskName']) {
|
|
135
|
+
$name = [string]$Opts['taskName']
|
|
136
|
+
$source = 'option'
|
|
137
|
+
}
|
|
138
|
+
if (-not $name) {
|
|
139
|
+
$cfgName = [string](Get-ConfigValue $Config 'taskName' '')
|
|
140
|
+
if ($cfgName) { $name = $cfgName; $source = 'config' }
|
|
141
|
+
}
|
|
142
|
+
if (-not $name) { $name = $script:TaskName; $source = 'default' }
|
|
143
|
+
return [ordered]@{ name = $name; source = $source }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function Save-ConfigFile {
|
|
147
|
+
param($Config)
|
|
148
|
+
$Config | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $script:ConfigPath -Encoding UTF8
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function Wait-WatcherExit {
|
|
152
|
+
param([int]$TimeoutSeconds)
|
|
153
|
+
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
|
|
154
|
+
while ((Get-Date) -lt $deadline) {
|
|
155
|
+
$lock = Get-WatcherLock
|
|
156
|
+
if ($null -eq $lock) { return $true }
|
|
157
|
+
if (-not (Test-WatcherProcess ([int]$lock.pid))) { return $true }
|
|
158
|
+
Start-Sleep -Milliseconds 500
|
|
159
|
+
}
|
|
160
|
+
return $false
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function Wait-WatcherStart {
|
|
164
|
+
param([int]$TimeoutSeconds)
|
|
165
|
+
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
|
|
166
|
+
while ((Get-Date) -lt $deadline) {
|
|
167
|
+
$lock = Get-WatcherLock
|
|
168
|
+
if ($null -ne $lock -and (Test-WatcherProcess ([int]$lock.pid))) { return $lock }
|
|
169
|
+
Start-Sleep -Milliseconds 500
|
|
170
|
+
}
|
|
171
|
+
return $null
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function Stop-RunningWatcher {
|
|
175
|
+
param([int]$GraceSeconds = 90)
|
|
176
|
+
$lock = Get-WatcherLock
|
|
177
|
+
$wasRunning = $false
|
|
178
|
+
if ($null -ne $lock -and (Test-WatcherProcess ([int]$lock.pid))) {
|
|
179
|
+
$wasRunning = $true
|
|
180
|
+
New-Item -ItemType Directory -Path (Join-Path $script:Root 'state') -Force | Out-Null
|
|
181
|
+
Set-Content -LiteralPath $script:StopFlag -Value ('stop requested ' + (Get-Date).ToString('o')) -Encoding UTF8
|
|
182
|
+
Write-Line "watcher pid $($lock.pid) is running; asking it to stop (grace ${GraceSeconds}s)"
|
|
183
|
+
if (-not (Wait-WatcherExit $GraceSeconds)) {
|
|
184
|
+
Write-Line 'watcher did not stop in time; forcing'
|
|
185
|
+
try { Stop-Process -Id ([int]$lock.pid) -Force -ErrorAction SilentlyContinue } catch { }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
Remove-Item -LiteralPath $script:StopFlag -Force -ErrorAction SilentlyContinue
|
|
189
|
+
return $wasRunning
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function Get-TaskInfo {
|
|
193
|
+
param([string]$Name)
|
|
194
|
+
|
|
195
|
+
# Accept both "Task" and "Folder\Task". Task names are unique per folder,
|
|
196
|
+
# not globally, so try the exact path first and only then enumerate.
|
|
197
|
+
$leafName = $Name
|
|
198
|
+
$folder = ''
|
|
199
|
+
$m = [regex]::Match($Name, '^(?<path>.+)\\(?<leaf>[^\\]+)$')
|
|
200
|
+
if ($m.Success) {
|
|
201
|
+
$folder = $m.Groups['path'].Value.TrimEnd('\') + '\'
|
|
202
|
+
$leafName = $m.Groups['leaf'].Value
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
$task = $null
|
|
206
|
+
try {
|
|
207
|
+
if ($folder) {
|
|
208
|
+
$task = Get-ScheduledTask -TaskName $leafName -TaskPath $folder -ErrorAction Stop
|
|
209
|
+
} else {
|
|
210
|
+
$task = Get-ScheduledTask -TaskName $leafName -ErrorAction Stop
|
|
211
|
+
}
|
|
212
|
+
} catch { $task = $null }
|
|
213
|
+
if ($null -eq $task) {
|
|
214
|
+
# Fallback for legacy/case-mismatched registrations: one enumeration
|
|
215
|
+
# (195 tasks on this host) only when the direct lookup missed.
|
|
216
|
+
try {
|
|
217
|
+
$task = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -eq $leafName }) | Select-Object -First 1
|
|
218
|
+
} catch { $task = $null }
|
|
219
|
+
}
|
|
220
|
+
if ($null -eq $task) { return $null }
|
|
221
|
+
$realName = [string]$task.TaskName
|
|
222
|
+
$realPath = [string]$task.TaskPath
|
|
223
|
+
if (-not $realPath) { $realPath = '\' }
|
|
224
|
+
$info = $null
|
|
225
|
+
try { $info = Get-ScheduledTaskInfo -TaskName $realName -TaskPath $realPath -ErrorAction Stop } catch { }
|
|
226
|
+
$action = ''
|
|
227
|
+
try { $action = (@($task.Actions) | ForEach-Object { "$($_.Execute) $($_.Arguments)" }) -join ' ; ' } catch { }
|
|
228
|
+
$trigger = ''
|
|
229
|
+
try { $trigger = (@($task.Triggers) | ForEach-Object { $_.CimClass.CimClassName }) -join ',' } catch { }
|
|
230
|
+
return [ordered]@{
|
|
231
|
+
name = $realName
|
|
232
|
+
taskPath = $realPath
|
|
233
|
+
state = [string]$task.State
|
|
234
|
+
enabled = [bool]$task.Settings.Enabled
|
|
235
|
+
runLevel = [string]$task.Principal.RunLevel
|
|
236
|
+
logonType = [string]$task.Principal.LogonType
|
|
237
|
+
userId = [string]$task.Principal.UserId
|
|
238
|
+
multipleInstances = [string]$task.Settings.MultipleInstances
|
|
239
|
+
executionLimit = [string]$task.Settings.ExecutionTimeLimit
|
|
240
|
+
restartCount = [int]$task.Settings.RestartCount
|
|
241
|
+
restartInterval = [string]$task.Settings.RestartInterval
|
|
242
|
+
trigger = $trigger
|
|
243
|
+
action = $action
|
|
244
|
+
lastRunTime = $(if ($info) { $info.LastRunTime.ToString('o') } else { '' })
|
|
245
|
+
lastTaskResult = $(if ($info) { $info.LastTaskResult } else { $null })
|
|
246
|
+
nextRunTime = $(if ($info -and $info.NextRunTime) { $info.NextRunTime.ToString('o') } else { '' })
|
|
247
|
+
missedRuns = $(if ($info) { $info.NumberOfMissedRuns } else { $null })
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function Get-StatusObject {
|
|
252
|
+
param($Opts)
|
|
253
|
+
$cfg = Read-ConfigFile
|
|
254
|
+
$lock = Get-WatcherLock
|
|
255
|
+
$hb = $null
|
|
256
|
+
if (Test-Path -LiteralPath $script:HeartbeatPath) {
|
|
257
|
+
try { $hb = Get-Content -LiteralPath $script:HeartbeatPath -Raw -Encoding UTF8 | ConvertFrom-Json } catch { }
|
|
258
|
+
}
|
|
259
|
+
$state = $null
|
|
260
|
+
if (Test-Path -LiteralPath $script:StatePath) {
|
|
261
|
+
try { $state = Get-Content -LiteralPath $script:StatePath -Raw -Encoding UTF8 | ConvertFrom-Json } catch { }
|
|
262
|
+
}
|
|
263
|
+
$running = $false
|
|
264
|
+
$pidValue = 0
|
|
265
|
+
if ($null -ne $lock) {
|
|
266
|
+
$pidValue = [int]$lock.pid
|
|
267
|
+
$running = [bool](Test-WatcherProcess $pidValue)
|
|
268
|
+
}
|
|
269
|
+
$hbAge = $null
|
|
270
|
+
if ($hb -and $hb.at) {
|
|
271
|
+
try { $hbAge = [int]((Get-Date) - [datetime]::Parse([string]$hb.at)).TotalSeconds } catch { }
|
|
272
|
+
}
|
|
273
|
+
$requestExists = $false
|
|
274
|
+
$requestAge = $null
|
|
275
|
+
$requestId = ''
|
|
276
|
+
$requestSession = ''
|
|
277
|
+
$requestPath = ''
|
|
278
|
+
if ($cfg) {
|
|
279
|
+
$requestPath = [string](Get-ConfigValue $cfg 'requestPath' '')
|
|
280
|
+
if (-not $requestPath) {
|
|
281
|
+
$memoryRoot = [string](Get-ConfigValue $cfg 'memoryRoot' '')
|
|
282
|
+
if (-not $memoryRoot) {
|
|
283
|
+
$memoryRoot = Resolve-MemoryRoot -Explicit '' -Profile ([string](Get-ConfigValue $cfg 'profile' 'desktop'))
|
|
284
|
+
}
|
|
285
|
+
if ($memoryRoot) { $requestPath = Join-Path ($memoryRoot.TrimEnd('\', '/')) '.longlive\logs\auto-truncate.request.json' }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if ($requestPath) {
|
|
289
|
+
$requestExists = Test-Path -LiteralPath $requestPath -PathType Leaf
|
|
290
|
+
if ($requestExists) {
|
|
291
|
+
$fi = Get-Item -LiteralPath $requestPath
|
|
292
|
+
$requestAge = [int]((Get-Date) - $fi.LastWriteTime).TotalSeconds
|
|
293
|
+
try {
|
|
294
|
+
$req = Get-Content -LiteralPath $requestPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
295
|
+
$requestId = [string]$req.requestId
|
|
296
|
+
$requestSession = [string]$req.sessionPath
|
|
297
|
+
} catch { }
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
$lookup = Resolve-WatcherTaskName $Opts $cfg
|
|
301
|
+
$task = Get-TaskInfo $lookup.name
|
|
302
|
+
$taskLookup = [ordered]@{
|
|
303
|
+
name = $lookup.name
|
|
304
|
+
source = $lookup.source
|
|
305
|
+
found = ($null -ne $task)
|
|
306
|
+
taskPath = $(if ($task) { [string]$task.taskPath } else { '' })
|
|
307
|
+
error = $(if ($null -ne $task) { '' } else { "scheduled task '$($lookup.name)' not found" })
|
|
308
|
+
}
|
|
309
|
+
$ok = $running -and ($null -ne $task) -and ($task.state -eq 'Ready' -or $task.state -eq 'Running')
|
|
310
|
+
return [ordered]@{
|
|
311
|
+
ok = $ok
|
|
312
|
+
version = $script:Version
|
|
313
|
+
generatedAt = (Get-Date).ToString('o')
|
|
314
|
+
task = $task
|
|
315
|
+
taskLookup = $taskLookup
|
|
316
|
+
watcher = [ordered]@{
|
|
317
|
+
running = $running
|
|
318
|
+
pid = $pidValue
|
|
319
|
+
heartbeatAgeSeconds = $hbAge
|
|
320
|
+
startedAt = $(if ($lock) { [string]$lock.startedAt } else { '' })
|
|
321
|
+
loop = $(if ($hb) { $hb.loop } else { $null })
|
|
322
|
+
lastStatus = $(if ($hb) { [string]$hb.lastStatus } else { '' })
|
|
323
|
+
}
|
|
324
|
+
request = [ordered]@{
|
|
325
|
+
path = $requestPath
|
|
326
|
+
present = $requestExists
|
|
327
|
+
ageSeconds = $requestAge
|
|
328
|
+
requestId = $requestId
|
|
329
|
+
sessionPath = $requestSession
|
|
330
|
+
runnerPid = $(if ($hb) { [string]$hb.runnerPid } else { '' })
|
|
331
|
+
}
|
|
332
|
+
state = [ordered]@{
|
|
333
|
+
lastRequestId = $(if ($state) { [string]$state.lastRequestId } else { '' })
|
|
334
|
+
lastSuccessAt = $(if ($state) { [string]$state.lastSuccessAt } else { '' })
|
|
335
|
+
lastStatus = $(if ($state) { [string]$state.lastStatus } else { '' })
|
|
336
|
+
totals = $(if ($state) { $state.totals } else { $null })
|
|
337
|
+
}
|
|
338
|
+
config = [ordered]@{
|
|
339
|
+
path = $script:ConfigPath
|
|
340
|
+
exists = [bool]$cfg
|
|
341
|
+
memoryRoot = $(if ($cfg) { [string]$cfg.memoryRoot } else { '' })
|
|
342
|
+
appExe = $(if ($cfg) { [string]$cfg.appExe } else { '' })
|
|
343
|
+
appArgs = $(if ($cfg) { [string]$cfg.appArgs } else { '' })
|
|
344
|
+
profile = $(if ($cfg) { [string]$cfg.profile } else { '' })
|
|
345
|
+
taskName = $(if ($cfg) { [string](Get-ConfigValue $cfg 'taskName' '') } else { '' })
|
|
346
|
+
}
|
|
347
|
+
paths = [ordered]@{
|
|
348
|
+
root = $script:Root
|
|
349
|
+
log = (Join-Path $script:Root 'logs\watcher.log')
|
|
350
|
+
state = $script:StatePath
|
|
351
|
+
archive = (Join-Path $script:Root 'archive\requests')
|
|
352
|
+
quarantine = (Join-Path $script:Root 'quarantine')
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function Show-StatusText {
|
|
358
|
+
param($S)
|
|
359
|
+
Write-Line "resident-watcher $($S.version) ok=$($S.ok)"
|
|
360
|
+
if ($S.task) {
|
|
361
|
+
Write-Line "task: $($S.task.name) state=$($S.task.state) lastResult=$($S.task.lastTaskResult) lastRun=$($S.task.lastRunTime) missed=$($S.task.missedRuns)"
|
|
362
|
+
Write-Line "task: logonType=$($S.task.logonType) runLevel=$($S.task.runLevel) multipleInstances=$($S.task.multipleInstances) executionLimit=$($S.task.executionLimit) restart=$($S.task.restartCount)/$($S.task.restartInterval)"
|
|
363
|
+
Write-Line "task action: $($S.task.action)"
|
|
364
|
+
} else {
|
|
365
|
+
Write-Line "task: $($S.taskLookup.name) NOT INSTALLED (looked up by $($S.taskLookup.source); path=$($S.taskLookup.taskPath))"
|
|
366
|
+
}
|
|
367
|
+
Write-Line "watcher: running=$($S.watcher.running) pid=$($S.watcher.pid) heartbeatAge=$($S.watcher.heartbeatAgeSeconds)s loop=$($S.watcher.loop) lastStatus=$($S.watcher.lastStatus)"
|
|
368
|
+
Write-Line "request: present=$($S.request.present) age=$($S.request.ageSeconds)s id=$($S.request.requestId) runnerPid=$($S.request.runnerPid)"
|
|
369
|
+
if ($S.request.path) { Write-Line "request path: $($S.request.path)" }
|
|
370
|
+
if ($S.state.totals) {
|
|
371
|
+
Write-Line "totals: detected=$($S.state.totals.detected) succeeded=$($S.state.totals.succeeded) failed=$($S.state.totals.failed) quarantined=$($S.state.totals.quarantined) stale=$($S.state.totals.stale) duplicateFailed=$($S.state.totals.duplicateFailed)"
|
|
372
|
+
}
|
|
373
|
+
Write-Line "lastSuccess: $($S.state.lastSuccessAt) lastRequest: $($S.state.lastRequestId)"
|
|
374
|
+
if ($S.config.exists) { Write-Line "config: $($S.config.path) memoryRoot=$($S.config.memoryRoot) app=$($S.config.appExe) args=[$($S.config.appArgs)]" }
|
|
375
|
+
else { Write-Line "config: MISSING ($($S.config.path))" }
|
|
376
|
+
if (Test-Path -LiteralPath $S.paths.log) {
|
|
377
|
+
Write-Line 'recent log:'
|
|
378
|
+
Get-Content -LiteralPath $S.paths.log -Tail 5 -Encoding UTF8 | ForEach-Object { Write-Line " $_" }
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function Invoke-Install {
|
|
383
|
+
param($Opts, $RawArgs)
|
|
384
|
+
Write-Line "resident-watcher $($script:Version) install"
|
|
385
|
+
|
|
386
|
+
$existing = Read-ConfigFile
|
|
387
|
+
$profile = [string](Get-OptValue $Opts 'profile' $(if ($existing) { [string]$existing.profile } else { 'desktop' }))
|
|
388
|
+
if (-not $profile) { $profile = 'desktop' }
|
|
389
|
+
$memoryRoot = [string](Get-OptValue $Opts 'memoryRoot' $(if ($existing) { [string]$existing.memoryRoot } else { '' }))
|
|
390
|
+
$memoryRoot = Resolve-MemoryRoot -Explicit $memoryRoot -Profile $profile
|
|
391
|
+
$memoryRoot = $memoryRoot.TrimEnd('\', '/')
|
|
392
|
+
|
|
393
|
+
if ($memoryRoot -match '^[Hh]:\\') {
|
|
394
|
+
Write-Line 'REFUSING: memoryRoot resolves to a protected real-machine memory store.'
|
|
395
|
+
Write-Line 'Pass an explicit disposable --memory-root for experiments.'
|
|
396
|
+
return 2
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
$appExe = [string](Get-OptValue $Opts 'appExe' $(if ($existing) { [string]$existing.appExe } else { '' }))
|
|
400
|
+
if (-not $appExe -or -not (Test-Path -LiteralPath $appExe -PathType Leaf)) { $appExe = Find-AppExe $appExe }
|
|
401
|
+
if (-not $appExe) {
|
|
402
|
+
Write-Line 'ERROR: cannot find "DeepSeek Harness.exe"; pass --app-exe <path>'
|
|
403
|
+
return 2
|
|
404
|
+
}
|
|
405
|
+
$appArgs = [string](Get-OptValue $Opts 'appArgs' '')
|
|
406
|
+
if (-not $appArgs -and -not $Opts.ContainsKey('appArgs')) {
|
|
407
|
+
if ($existing -and $existing.appArgs) { $appArgs = [string]$existing.appArgs } else { $appArgs = Find-AppArgs }
|
|
408
|
+
}
|
|
409
|
+
$taskName = [string](Get-OptValue $Opts 'taskName' $(if ($existing -and $existing.taskName) { [string]$existing.taskName } else { $script:TaskName }))
|
|
410
|
+
$script:TaskName = $taskName
|
|
411
|
+
|
|
412
|
+
$runnerPath = Join-Path $script:Root 'lib\auto-truncate-run.ps1'
|
|
413
|
+
if (-not (Test-Path -LiteralPath $runnerPath -PathType Leaf)) {
|
|
414
|
+
Write-Line "ERROR: runner missing: $runnerPath"
|
|
415
|
+
return 2
|
|
416
|
+
}
|
|
417
|
+
if (-not (Test-Path -LiteralPath (Join-Path $memoryRoot '.longlive') -PathType Container)) {
|
|
418
|
+
Write-Line "WARN: $memoryRoot\.longlive does not exist yet; the plugin creates it on first request"
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
New-Item -ItemType Directory -Path (Join-Path $script:Root 'logs') -Force | Out-Null
|
|
422
|
+
New-Item -ItemType Directory -Path (Join-Path $script:Root 'state') -Force | Out-Null
|
|
423
|
+
New-Item -ItemType Directory -Path (Join-Path $script:Root 'archive\requests') -Force | Out-Null
|
|
424
|
+
New-Item -ItemType Directory -Path (Join-Path $script:Root 'quarantine') -Force | Out-Null
|
|
425
|
+
|
|
426
|
+
$cfg = [ordered]@{
|
|
427
|
+
version = 1
|
|
428
|
+
memoryRoot = $memoryRoot
|
|
429
|
+
requestPath = (Join-Path $memoryRoot '.longlive\logs\auto-truncate.request.json')
|
|
430
|
+
appExe = $appExe
|
|
431
|
+
appArgs = $appArgs
|
|
432
|
+
processName = 'DeepSeek Harness'
|
|
433
|
+
profile = $profile
|
|
434
|
+
runnerPath = $runnerPath
|
|
435
|
+
runnerLogDir = (Join-Path $memoryRoot '.longlive\logs')
|
|
436
|
+
pollSeconds = [int](Get-OptValue $Opts 'pollSeconds' 2)
|
|
437
|
+
requestSettleSeconds = [int](Get-OptValue $Opts 'settleSeconds' 5)
|
|
438
|
+
cooldownSeconds = 90
|
|
439
|
+
maxAttempts = 2
|
|
440
|
+
retryDelaySeconds = 30
|
|
441
|
+
logMaxBytes = 5242880
|
|
442
|
+
logKeep = 3
|
|
443
|
+
taskName = $taskName
|
|
444
|
+
}
|
|
445
|
+
Save-ConfigFile $cfg
|
|
446
|
+
Write-Line "config: $script:ConfigPath"
|
|
447
|
+
Write-Line "memoryRoot: $memoryRoot"
|
|
448
|
+
Write-Line "appExe: $appExe"
|
|
449
|
+
Write-Line "appArgs: [$appArgs]"
|
|
450
|
+
|
|
451
|
+
# replace a running watcher cleanly
|
|
452
|
+
$old = Get-TaskInfo $taskName
|
|
453
|
+
if ($old -and $old.state -eq 'Running') {
|
|
454
|
+
Write-Line 'stopping the previous task instance'
|
|
455
|
+
try { Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue } catch { }
|
|
456
|
+
}
|
|
457
|
+
Stop-RunningWatcher -GraceSeconds 90 | Out-Null
|
|
458
|
+
|
|
459
|
+
$ps = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
|
|
460
|
+
if (-not (Test-Path -LiteralPath $ps)) { $ps = 'powershell.exe' }
|
|
461
|
+
$actionArg = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$script:LoopScript`" -Config `"$script:ConfigPath`""
|
|
462
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
|
463
|
+
$registered = $false
|
|
464
|
+
$regMode = ''
|
|
465
|
+
try {
|
|
466
|
+
$action = New-ScheduledTaskAction -Execute $ps -Argument $actionArg -WorkingDirectory $script:Root
|
|
467
|
+
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
|
|
468
|
+
$settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 3 `
|
|
469
|
+
-RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) `
|
|
470
|
+
-AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable
|
|
471
|
+
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
|
|
472
|
+
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings `
|
|
473
|
+
-Principal $principal -Description 'Resident watcher: consumes dsh-longlive autoTruncate requests (close/cut/verify/restart).' `
|
|
474
|
+
-Force | Out-Null
|
|
475
|
+
$registered = $true
|
|
476
|
+
$regMode = 'Register-ScheduledTask'
|
|
477
|
+
} catch {
|
|
478
|
+
Write-Line "Register-ScheduledTask failed: $($_.Exception.Message)"
|
|
479
|
+
Write-Line 'falling back to schtasks /SC ONLOGON'
|
|
480
|
+
$tr = "$ps $actionArg"
|
|
481
|
+
$out = & schtasks.exe /Create /TN $taskName /TR $tr /SC ONLOGON /RL LIMITED /F 2>&1
|
|
482
|
+
$code = $LASTEXITCODE
|
|
483
|
+
Write-Line "schtasks exit=$code $($out | Out-String)".Trim()
|
|
484
|
+
if ($code -eq 0) { $registered = $true; $regMode = 'schtasks ONLOGON' }
|
|
485
|
+
}
|
|
486
|
+
if (-not $registered) {
|
|
487
|
+
Write-Line 'ERROR: task registration failed (need an interactive logon task; run as the desktop user)'
|
|
488
|
+
return 1
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
Remove-Item -LiteralPath $script:StopFlag -Force -ErrorAction SilentlyContinue
|
|
492
|
+
$started = $false
|
|
493
|
+
if (-not $RawArgs.Contains('--no-start')) {
|
|
494
|
+
try {
|
|
495
|
+
Start-ScheduledTask -TaskName $taskName
|
|
496
|
+
$lock = Wait-WatcherStart -TimeoutSeconds 20
|
|
497
|
+
$started = ($null -ne $lock)
|
|
498
|
+
} catch {
|
|
499
|
+
Write-Line "start failed: $($_.Exception.Message)"
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
$status = Get-StatusObject
|
|
504
|
+
Write-Line "task registered via $regMode"
|
|
505
|
+
Write-Line "watcher started: $started pid=$($status.watcher.pid)"
|
|
506
|
+
Write-Line "status: $($status.ok) log: $($status.paths.log)"
|
|
507
|
+
if ($RawArgs.Contains('--json')) { $status | ConvertTo-Json -Depth 12 }
|
|
508
|
+
if (-not $started) {
|
|
509
|
+
Write-Line 'WARN: watcher did not report a heartbeat within 20s; run --status and check logs\watcher.log'
|
|
510
|
+
return 1
|
|
511
|
+
}
|
|
512
|
+
return 0
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function Invoke-Uninstall {
|
|
516
|
+
param($Opts, $RawArgs)
|
|
517
|
+
Write-Line "resident-watcher $($script:Version) uninstall"
|
|
518
|
+
$cfg = Read-ConfigFile
|
|
519
|
+
$taskName = [string](Get-OptValue $Opts 'taskName' $(if ($cfg -and $cfg.taskName) { [string]$cfg.taskName } else { $script:TaskName }))
|
|
520
|
+
$script:TaskName = $taskName
|
|
521
|
+
|
|
522
|
+
$task = Get-TaskInfo $taskName
|
|
523
|
+
if ($task -and $task.state -eq 'Running') {
|
|
524
|
+
Write-Line "task $taskName is running; stopping via stop.flag first"
|
|
525
|
+
}
|
|
526
|
+
$stopped = Stop-RunningWatcher -GraceSeconds 120
|
|
527
|
+
if ($task) {
|
|
528
|
+
try { Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue } catch { }
|
|
529
|
+
try {
|
|
530
|
+
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop
|
|
531
|
+
Write-Line "task removed: $taskName"
|
|
532
|
+
} catch {
|
|
533
|
+
Write-Line "ERROR: could not remove task ${taskName}: $($_.Exception.Message)"
|
|
534
|
+
}
|
|
535
|
+
} else {
|
|
536
|
+
Write-Line "task not present: $taskName"
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
# anything still alive?
|
|
540
|
+
$lock = Get-WatcherLock
|
|
541
|
+
if ($null -ne $lock -and (Test-WatcherProcess ([int]$lock.pid))) {
|
|
542
|
+
Write-Line "watcher pid $($lock.pid) still alive, killing"
|
|
543
|
+
try { Stop-Process -Id ([int]$lock.pid) -Force -ErrorAction SilentlyContinue } catch { }
|
|
544
|
+
}
|
|
545
|
+
Remove-Item -LiteralPath $script:LockPath -Force -ErrorAction SilentlyContinue
|
|
546
|
+
Remove-Item -LiteralPath $script:StopFlag -Force -ErrorAction SilentlyContinue
|
|
547
|
+
Write-Line "watcher was running: $stopped"
|
|
548
|
+
|
|
549
|
+
if ($Opts.ContainsKey('purge') -and $Opts['purge']) {
|
|
550
|
+
foreach ($d in @('logs', 'state', 'archive', 'quarantine')) {
|
|
551
|
+
$p = Join-Path $script:Root $d
|
|
552
|
+
if (Test-Path -LiteralPath $p) { Remove-Item -LiteralPath $p -Recurse -Force -ErrorAction SilentlyContinue }
|
|
553
|
+
}
|
|
554
|
+
Remove-Item -LiteralPath $script:ConfigPath -Force -ErrorAction SilentlyContinue
|
|
555
|
+
Write-Line 'purged logs/state/archive/quarantine/config.json (code kept)'
|
|
556
|
+
} else {
|
|
557
|
+
Write-Line "kept evidence: $script:Root\logs, archive, quarantine (use --purge to remove)"
|
|
558
|
+
}
|
|
559
|
+
return 0
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function Invoke-Run {
|
|
563
|
+
param([switch]$Once)
|
|
564
|
+
if ($Once) {
|
|
565
|
+
New-Item -ItemType Directory -Path (Join-Path $script:Root 'state') -Force | Out-Null
|
|
566
|
+
Set-Content -LiteralPath $script:OnceFlag -Value 'once' -Encoding UTF8
|
|
567
|
+
$p = Start-Process -FilePath (Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe') `
|
|
568
|
+
-ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$script:LoopScript`" -Config `"$script:ConfigPath`"" `
|
|
569
|
+
-PassThru -Wait -NoNewWindow
|
|
570
|
+
Remove-Item -LiteralPath $script:OnceFlag -Force -ErrorAction SilentlyContinue
|
|
571
|
+
return [int]$p.ExitCode
|
|
572
|
+
}
|
|
573
|
+
& (Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe') -NoProfile -ExecutionPolicy Bypass -File $script:LoopScript -Config $script:ConfigPath
|
|
574
|
+
return [int]$LASTEXITCODE
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
# ---------------------------------------------------------------------------
|
|
578
|
+
# argument parsing (Windows PowerShell would bind --install as a parameter,
|
|
579
|
+
# so the CLI parses $args by hand)
|
|
580
|
+
# ---------------------------------------------------------------------------
|
|
581
|
+
$action = ''
|
|
582
|
+
$opts = @{}
|
|
583
|
+
$raw = @()
|
|
584
|
+
$i = 0
|
|
585
|
+
while ($i -lt $args.Count) {
|
|
586
|
+
$tok = [string]$args[$i]
|
|
587
|
+
$raw += $tok
|
|
588
|
+
$key = ([string]$args[$i]).ToLowerInvariant().TrimStart('-', '/')
|
|
589
|
+
switch ($key) {
|
|
590
|
+
'install' { $action = 'install' }
|
|
591
|
+
'uninstall' { $action = 'uninstall' }
|
|
592
|
+
'status' { $action = 'status' }
|
|
593
|
+
'run' { $action = 'run' }
|
|
594
|
+
'once' { $action = 'once' }
|
|
595
|
+
'help' { $action = 'help' }
|
|
596
|
+
'h' { $action = 'help' }
|
|
597
|
+
'no-start' { $opts['noStart'] = $true }
|
|
598
|
+
'nostart' { $opts['noStart'] = $true }
|
|
599
|
+
'purge' { $opts['purge'] = $true }
|
|
600
|
+
'json' { $opts['json'] = $true }
|
|
601
|
+
'memory-root' { $i++; $opts['memoryRoot'] = [string]$args[$i] }
|
|
602
|
+
'memoryroot' { $i++; $opts['memoryRoot'] = [string]$args[$i] }
|
|
603
|
+
'app-exe' { $i++; $opts['appExe'] = [string]$args[$i] }
|
|
604
|
+
'appexe' { $i++; $opts['appExe'] = [string]$args[$i] }
|
|
605
|
+
'app-args' { $i++; $opts['appArgs'] = [string]$args[$i] }
|
|
606
|
+
'appargs' { $i++; $opts['appArgs'] = [string]$args[$i] }
|
|
607
|
+
'profile' { $i++; $opts['profile'] = [string]$args[$i] }
|
|
608
|
+
'task-name' { $i++; $opts['taskName'] = [string]$args[$i] }
|
|
609
|
+
'taskname' { $i++; $opts['taskName'] = [string]$args[$i] }
|
|
610
|
+
'poll-seconds' { $i++; $opts['pollSeconds'] = [string]$args[$i] }
|
|
611
|
+
'pollseconds' { $i++; $opts['pollSeconds'] = [string]$args[$i] }
|
|
612
|
+
default {
|
|
613
|
+
if ($tok.StartsWith('-') -or $tok.StartsWith('/')) {
|
|
614
|
+
Write-Line "unknown argument: $tok (try --help)"
|
|
615
|
+
exit 2
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
$i++
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
$rawText = $raw -join ' '
|
|
623
|
+
switch ($action) {
|
|
624
|
+
'install' { exit (Invoke-Install -Opts $opts -RawArgs $rawText) }
|
|
625
|
+
'uninstall' { exit (Invoke-Uninstall -Opts $opts -RawArgs $rawText) }
|
|
626
|
+
'status' {
|
|
627
|
+
$s = Get-StatusObject -Opts $opts
|
|
628
|
+
if ($opts.ContainsKey('json') -and $opts['json']) { $s | ConvertTo-Json -Depth 12 }
|
|
629
|
+
else { Show-StatusText $s }
|
|
630
|
+
if ($s.ok) { exit 0 } else { exit 1 }
|
|
631
|
+
}
|
|
632
|
+
'run' { exit (Invoke-Run) }
|
|
633
|
+
'once' { exit (Invoke-Run -Once) }
|
|
634
|
+
default {
|
|
635
|
+
Write-Line 'resident-watcher.ps1 - resident watcher for dsh-longlive autoTruncate'
|
|
636
|
+
Write-Line ''
|
|
637
|
+
Write-Line ' --install [--memory-root P] [--app-exe P] [--app-args S] [--profile N] [--task-name N] [--no-start]'
|
|
638
|
+
Write-Line ' --uninstall [--purge]'
|
|
639
|
+
Write-Line ' --status [--json] [--task-name N]'
|
|
640
|
+
Write-Line ' --run | --once'
|
|
641
|
+
exit 0
|
|
642
|
+
}
|
|
643
|
+
}
|