@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.
Files changed (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. 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
+ }