@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,39 @@
1
+ #!/usr/bin/env node
2
+ // scripts/index-maintain.mjs — explicitly refresh INDEX.md + freshness ledger.
3
+ //
4
+ // node scripts/index-maintain.mjs --memory-root <dir> [--apply] [--json]
5
+ //
6
+ // Default is dry-run. This is the same maintenance path captureTurn invokes
7
+ // after a successful event/card capture; it is idempotent (`ifChanged`).
8
+
9
+ import { memoryIndex } from '../src/memory/index.js';
10
+ import { getIndexFreshness, refreshIndexAfterCapture } from '../src/memory/index-freshness.js';
11
+
12
+ function arg(argv, name) {
13
+ const i = argv.indexOf(name);
14
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : '';
15
+ }
16
+ const argv = process.argv.slice(2);
17
+ const root = arg(argv, '--memory-root');
18
+ if (root === '') {
19
+ console.error('[index-maintain] --memory-root is required');
20
+ process.exit(2);
21
+ }
22
+ const apply = argv.includes('--apply');
23
+ let result;
24
+ if (apply) {
25
+ result = refreshIndexAfterCapture({ memoryRoot: root, indexer: memoryIndex });
26
+ result.status = result.ok ? 'applied' : 'error';
27
+ } else {
28
+ result = memoryIndex({}, { memoryRoot: root });
29
+ result.freshness = getIndexFreshness({ memoryRoot: root });
30
+ result.status = 'dry-run';
31
+ }
32
+ if (argv.includes('--json')) console.log(JSON.stringify(result, null, 2));
33
+ else {
34
+ console.log(`[index-maintain] status=${result.status} ok=${result.ok}`);
35
+ console.log(`[index-maintain] cards=${result.cards ?? '-'} changed=${result.changed ?? '-'}`);
36
+ if (result.freshness) console.log(`[index-maintain] freshness=${result.freshness.status} lagMs=${result.freshness.indexLagMs}`);
37
+ if (result.failure) console.log(`[index-maintain] failure=${result.failure.code}`);
38
+ }
39
+ process.exitCode = result.ok === false ? 1 : 0;
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ // scripts/index-reconcile.mjs — event/card/audit/anchor set reconciliation.
3
+ //
4
+ // node scripts/index-reconcile.mjs --memory-root <dir> [--write] [--json]
5
+ // node scripts/index-reconcile.mjs --memory-root <dir> --accept <cardId> [--apply] [--json]
6
+ //
7
+ // Default: summarize only. `--write` emits .longlive/reports/reconcile-<date>.json.
8
+ // Promotion is dry-run unless `--apply` AND `--accept` are both supplied.
9
+
10
+ import { promoteAutoCard, reconcileIndex } from '../src/memory/reconcile.js';
11
+
12
+ function arg(argv, name) {
13
+ const i = argv.indexOf(name);
14
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : '';
15
+ }
16
+ const argv = process.argv.slice(2);
17
+ const root = arg(argv, '--memory-root');
18
+ if (root === '') {
19
+ console.error('[index-reconcile] --memory-root is required');
20
+ process.exit(2);
21
+ }
22
+ const json = argv.includes('--json');
23
+ const accept = arg(argv, '--accept');
24
+ if (accept !== '') {
25
+ const result = promoteAutoCard({
26
+ memoryRoot: root,
27
+ cardId: accept,
28
+ dryRun: !argv.includes('--apply'),
29
+ });
30
+ if (json) console.log(JSON.stringify(result, null, 2));
31
+ else {
32
+ console.log(`[index-reconcile] promote card=${result.cardId} dryRun=${result.dryRun}`);
33
+ console.log(`[index-reconcile] target=${result.rel}`);
34
+ if (result.index) console.log(`[index-reconcile] INDEX applied=${result.index.applied} changed=${result.index.changed}`);
35
+ }
36
+ process.exitCode = result.ok === false ? 1 : 0;
37
+ } else {
38
+ const result = reconcileIndex({ memoryRoot: root, write: argv.includes('--write') });
39
+ if (json) console.log(JSON.stringify(result, null, 2));
40
+ else {
41
+ console.log(`[index-reconcile] candidates=${result.autoCandidates.count}`);
42
+ console.log(`[index-reconcile] eventNotAudit=${result.sets.eventNotAudit.count} eventNoCard=${result.sets.eventNoCard.count} dropStillCarded=${result.sets.dropButStillCarded.count}`);
43
+ console.log(`[index-reconcile] anchorLegacy/empty=${result.sets.cardAnchors.legacyOrEmptyAnchors} invalidSourceIds=${result.sets.cardAnchors.invalidSourceEventIds.length}`);
44
+ if (result.reportPath) console.log(`[index-reconcile] report=${result.reportPath}`);
45
+ const first = result.autoCandidates.sample[0];
46
+ if (first) console.log(`[index-reconcile] example=${first.cardId} turn=${first.turn} title=${first.title.slice(0, 50)}`);
47
+ }
48
+ process.exitCode = result.events.ok === false ? 1 : 0;
49
+ }
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ // scripts/index-status.mjs — read-only "indexed through / lag" status.
3
+ //
4
+ // node scripts/index-status.mjs --memory-root <dir> [--json]
5
+ //
6
+ // Never writes. The status is the same object memory-state / the memory_index
7
+ // tool result exposes; a generated timestamp alone is not treated as health.
8
+
9
+ import { getIndexFreshness } from '../src/memory/index-freshness.js';
10
+
11
+ function arg(argv, name) {
12
+ const i = argv.indexOf(name);
13
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : '';
14
+ }
15
+ const root = arg(process.argv.slice(2), '--memory-root');
16
+ if (root === '') {
17
+ console.error('[index-status] --memory-root is required (real memory roots are not written by this script)');
18
+ process.exit(2);
19
+ }
20
+ const status = getIndexFreshness({ memoryRoot: root });
21
+ if (process.argv.includes('--json')) {
22
+ console.log(JSON.stringify(status, null, 2));
23
+ } else {
24
+ console.log(`[index-status] status=${status.status} healthy=${status.healthy}`);
25
+ console.log(`[index-status] generatedAt=${status.generatedAt ?? '-'} dataThroughAt=${status.dataThroughAt ?? '-'}`);
26
+ console.log(`[index-status] indexLagMs=${status.indexLagMs ?? '-'} dataAgeMs=${status.dataAgeMs ?? '-'}`);
27
+ if (status.lastError) console.log(`[index-status] lastError=${status.lastError}`);
28
+ }
@@ -0,0 +1,15 @@
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
+ # install.ps1 - thin wrapper: same flags as resident-watcher.ps1 --install
11
+ $ErrorActionPreference = 'Stop'
12
+ $cli = Join-Path $PSScriptRoot 'resident-watcher.ps1'
13
+ $ps = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
14
+ & $ps -NoProfile -ExecutionPolicy Bypass -File $cli --install @args
15
+ exit $LASTEXITCODE
@@ -0,0 +1,332 @@
1
+ #Requires -Version 5.1
2
+ <#
3
+ .SYNOPSIS
4
+ Install the resident session watchdog as a per-user scheduled task.
5
+
6
+ .DESCRIPTION
7
+ Copies the watchdog, the truncate CLI and src/ into an install directory,
8
+ writes session-watch.config.json, validates it with `session-watch.mjs
9
+ --check`, and registers a Task Scheduler task that runs
10
+
11
+ <node> <install>\scripts\session-watch.mjs --config <config> --loop
12
+
13
+ at logon. The watchdog is a separate process tree: it never loads the DSH
14
+ host, never closes/starts the GUI, and a failed tick is only a log line.
15
+
16
+ This script changes Task Scheduler, which is a high-impact action on a real
17
+ machine. It is safe to dry-run first:
18
+ powershell -NoProfile -File install-session-watch.ps1 -DryRun
19
+
20
+ All paths that end up in the scheduled-task command line must be ASCII
21
+ (7-bit). That is deliberate: schtasks quoting is fragile around non-ASCII
22
+ paths, and a task that silently fails to start is worse than a rejected
23
+ install.
24
+
25
+ .PARAMETER InstallDir
26
+ Default: %LOCALAPPDATA%\dsh-session-watch. Must be ASCII.
27
+
28
+ .PARAMETER Mode
29
+ dryrun (default) or request. The mode can be overridden later by the profile's
30
+ autoTruncate block when -ProfileConfig is used.
31
+
32
+ .PARAMETER Enabled
33
+ Initial kill switch. Default true; set false to stage the task inert.
34
+
35
+ .PARAMETER ProfileConfig
36
+ Optional path to cordis.patch.yml. When set, the watcher re-reads its
37
+ autoTruncate block on every wake-up; that block owns enabled/mode/thresholds.
38
+
39
+ .PARAMETER DryRun
40
+ Validate and print the exact plan; write nothing, register nothing.
41
+
42
+ .PARAMETER NoRegister
43
+ Copy files and write config, but do not create the scheduled task.
44
+
45
+ .PARAMETER NoStart
46
+ Register but do not start the task now.
47
+
48
+ .PARAMETER Force
49
+ Overwrite an existing install directory and task.
50
+ #>
51
+ [CmdletBinding()]
52
+ param(
53
+ [string]$InstallDir = (Join-Path $env:LOCALAPPDATA 'dsh-session-watch'),
54
+ [ValidateSet('dryrun', 'request')]
55
+ [string]$Mode = 'dryrun',
56
+ [bool]$Enabled = $true,
57
+ [string]$TaskName = 'DshSessionWatch',
58
+ [string]$DshHome = $(if ($env:DSH_HOME) { $env:DSH_HOME } else { Join-Path $env:USERPROFILE '.dsh' }),
59
+ [string]$SessionsRoot = '',
60
+ [string]$MemoryRoot = '',
61
+ [string]$ProfileConfig = '',
62
+ [string]$NodeExe = '',
63
+ [int]$IntervalSeconds = 300,
64
+ [switch]$DryRun,
65
+ [switch]$NoRegister,
66
+ [switch]$NoStart,
67
+ [switch]$Force
68
+ )
69
+
70
+ $ErrorActionPreference = 'Stop'
71
+ $script:StartedAt = Get-Date
72
+
73
+ function Fail([string]$Message) {
74
+ throw "install-session-watch: $Message"
75
+ }
76
+
77
+ function Test-AsciiPath([string]$Value, [string]$Label) {
78
+ if ([string]::IsNullOrWhiteSpace($Value)) { Fail "$Label is empty" }
79
+ if ($Value -notmatch '^[\x20-\x7E]+$') {
80
+ Fail "$Label must be pure ASCII for schtasks, got: $Value"
81
+ }
82
+ return $Value
83
+ }
84
+
85
+ function Resolve-FullPath([string]$Value, [string]$Base) {
86
+ if ([string]::IsNullOrWhiteSpace($Value)) { return '' }
87
+ if ([System.IO.Path]::IsPathRooted($Value)) { return [System.IO.Path]::GetFullPath($Value) }
88
+ return [System.IO.Path]::GetFullPath((Join-Path $Base $Value))
89
+ }
90
+
91
+ function Write-JsonFile([string]$Path, $Value) {
92
+ $dir = Split-Path -Parent $Path
93
+ if ($dir -and -not (Test-Path -LiteralPath $dir)) {
94
+ New-Item -ItemType Directory -Path $dir -Force | Out-Null
95
+ }
96
+ $json = $Value | ConvertTo-Json -Depth 10
97
+ [System.IO.File]::WriteAllText($Path, $json + [Environment]::NewLine, (New-Object System.Text.UTF8Encoding($false)))
98
+ }
99
+
100
+ function Test-Node([string]$Node, [string]$ScriptPath) {
101
+ $output = & $Node --check $ScriptPath 2>&1
102
+ if ($LASTEXITCODE -ne 0) {
103
+ Fail "node --check failed for $ScriptPath`n$output"
104
+ }
105
+ }
106
+
107
+ # --- resolve and validate paths -------------------------------------------------
108
+ $repo = Split-Path -Parent $PSScriptRoot
109
+ $sourceWatch = Join-Path $PSScriptRoot 'session-watch.mjs'
110
+ $sourceCli = Join-Path $PSScriptRoot 'truncate-cli.mjs'
111
+ $sourceSrc = Join-Path $repo 'src'
112
+ $sourcePkg = Join-Path $repo 'package.json'
113
+ foreach ($required in @($sourceWatch, $sourceCli, $sourcePkg)) {
114
+ if (-not (Test-Path -LiteralPath $required -PathType Leaf)) { Fail "source file missing: $required" }
115
+ }
116
+ if (-not (Test-Path -LiteralPath $sourceSrc -PathType Container)) { Fail "source directory missing: $sourceSrc" }
117
+
118
+ $install = Resolve-FullPath $InstallDir (Get-Location).Path
119
+ $dsh = Resolve-FullPath $DshHome (Get-Location).Path
120
+ if (-not $SessionsRoot) { $SessionsRoot = Join-Path $dsh 'sessions' }
121
+ $sessions = Resolve-FullPath $SessionsRoot (Get-Location).Path
122
+ # An explicit sessions root is the strongest signal of the DSH home; without
123
+ # this, `-SessionsRoot <fixture>` would pair a fake sessions tree with the real
124
+ # ~/.dsh and the installed watcher would hand the CLI a contradictory DSH_HOME.
125
+ if ($PSBoundParameters.ContainsKey('SessionsRoot') -and -not $PSBoundParameters.ContainsKey('DshHome')) {
126
+ $parent = Split-Path -Parent $sessions
127
+ if ($parent) { $dsh = $parent }
128
+ }
129
+ if (-not $MemoryRoot) {
130
+ if ($env:DSH_MEM) { $MemoryRoot = $env:DSH_MEM }
131
+ else { $MemoryRoot = Join-Path $dsh 'longlive-memory' }
132
+ }
133
+ $memory = Resolve-FullPath $MemoryRoot (Get-Location).Path
134
+ if ($ProfileConfig) { $ProfileConfig = Resolve-FullPath $ProfileConfig (Get-Location).Path }
135
+
136
+ if (-not $NodeExe) {
137
+ $candidate = Join-Path $dsh 'dsh-runtimes\dsh-primary-runtime\dependencies\node\bin\node.exe'
138
+ if (Test-Path -LiteralPath $candidate -PathType Leaf) { $NodeExe = $candidate }
139
+ else {
140
+ $command = Get-Command node.exe -ErrorAction SilentlyContinue
141
+ if (-not $command) { Fail 'node.exe not found; pass -NodeExe' }
142
+ $NodeExe = $command.Source
143
+ }
144
+ }
145
+ $node = Resolve-FullPath $NodeExe (Get-Location).Path
146
+ if (-not (Test-Path -LiteralPath $node -PathType Leaf)) { Fail "node executable missing: $node" }
147
+
148
+ $configPath = Join-Path $install 'session-watch.config.json'
149
+ $watchPath = Join-Path $install 'scripts\session-watch.mjs'
150
+ $cliPath = Join-Path $install 'scripts\truncate-cli.mjs'
151
+
152
+ $asciiChecks = @(
153
+ @{ Value = $install; Label = 'InstallDir' },
154
+ @{ Value = $node; Label = 'NodeExe' },
155
+ @{ Value = $configPath; Label = 'config path' },
156
+ @{ Value = $watchPath; Label = 'watcher path' },
157
+ @{ Value = $TaskName; Label = 'TaskName' }
158
+ )
159
+ foreach ($entry in $asciiChecks) { [void](Test-AsciiPath $entry.Value $entry.Label) }
160
+ if ($ProfileConfig -and $ProfileConfig -notmatch '^[\x20-\x7E]+$') {
161
+ Fail "ProfileConfig must be ASCII because it is stored in config.json and read by the task process: $ProfileConfig"
162
+ }
163
+ if (-not (Test-Path -LiteralPath $sessions -PathType Container)) {
164
+ Fail "SessionsRoot does not exist: $sessions (this script does not guess a real DSH home)"
165
+ }
166
+ if (-not (Test-Path -LiteralPath $memory -PathType Container)) {
167
+ Fail "MemoryRoot does not exist: $memory (create it, or pass -MemoryRoot)"
168
+ }
169
+ if ($ProfileConfig -and -not (Test-Path -LiteralPath $ProfileConfig -PathType Leaf)) {
170
+ Fail "ProfileConfig does not exist: $ProfileConfig"
171
+ }
172
+ if ($IntervalSeconds -lt 1) { Fail 'IntervalSeconds must be >= 1' }
173
+
174
+ $taskCommand = "`"$node`" `"$watchPath`" --config `"$configPath`" --loop"
175
+ $plan = [ordered]@{
176
+ ok = $true
177
+ dryRun = [bool]$DryRun
178
+ installDir = $install
179
+ configPath = $configPath
180
+ watcher = $watchPath
181
+ cli = $cliPath
182
+ nodeExe = $node
183
+ memoryRoot = $memory
184
+ sessionsRoot = $sessions
185
+ dshHome = $dsh
186
+ profileConfig = $ProfileConfig
187
+ mode = $Mode
188
+ enabled = $Enabled
189
+ intervalSeconds = $IntervalSeconds
190
+ taskName = $TaskName
191
+ taskCommand = $taskCommand
192
+ copyFrom = $repo
193
+ startedAt = $script:StartedAt.ToString('o')
194
+ }
195
+
196
+ if ($DryRun) {
197
+ $plan['registered'] = $false
198
+ $plan['started'] = $false
199
+ $plan['note'] = 'dry run: no file was written and no task was registered'
200
+ $plan | ConvertTo-Json -Depth 6
201
+ exit 0
202
+ }
203
+
204
+ # --- guard existing install -----------------------------------------------------
205
+ if ((Test-Path -LiteralPath $install -PathType Container) -and -not $Force) {
206
+ $existing = @(Get-ChildItem -LiteralPath $install -Force -ErrorAction SilentlyContinue)
207
+ if ($existing.Count -gt 0) {
208
+ Fail "install directory is not empty: $install (pass -Force to update in place)"
209
+ }
210
+ }
211
+ New-Item -ItemType Directory -Path $install -Force | Out-Null
212
+ New-Item -ItemType Directory -Path (Join-Path $install 'scripts') -Force | Out-Null
213
+
214
+ # --- copy runtime --------------------------------------------------------------
215
+ Copy-Item -LiteralPath $sourceWatch -Destination (Join-Path $install 'scripts\session-watch.mjs') -Force
216
+ Copy-Item -LiteralPath $sourceCli -Destination (Join-Path $install 'scripts\truncate-cli.mjs') -Force
217
+ Copy-Item -LiteralPath $sourcePkg -Destination (Join-Path $install 'package.json') -Force
218
+
219
+ $libSource = Join-Path $PSScriptRoot 'lib'
220
+ if (Test-Path -LiteralPath $libSource -PathType Container) {
221
+ $libDest = Join-Path $install 'scripts\lib'
222
+ New-Item -ItemType Directory -Path $libDest -Force | Out-Null
223
+ Get-ChildItem -LiteralPath $libSource -File | Copy-Item -Destination $libDest -Force
224
+ }
225
+ $srcDest = Join-Path $install 'src'
226
+ if (Test-Path -LiteralPath $srcDest) { Remove-Item -LiteralPath $srcDest -Recurse -Force }
227
+ Copy-Item -LiteralPath $sourceSrc -Destination $srcDest -Recurse -Force
228
+ $docsSource = Join-Path $repo 'docs\SESSION-WATCH.md'
229
+ if (Test-Path -LiteralPath $docsSource -PathType Leaf) {
230
+ New-Item -ItemType Directory -Path (Join-Path $install 'docs') -Force | Out-Null
231
+ Copy-Item -LiteralPath $docsSource -Destination (Join-Path $install 'docs\SESSION-WATCH.md') -Force
232
+ }
233
+ # Keep the operator entry points beside the runtime so the install can be
234
+ # inspected/removed without remembering the original package directory.
235
+ foreach ($name in @('session-watch-status.ps1', 'uninstall-session-watch.ps1')) {
236
+ Copy-Item -LiteralPath (Join-Path $PSScriptRoot $name) -Destination (Join-Path $install ('scripts\' + $name)) -Force
237
+ }
238
+
239
+ # --- config --------------------------------------------------------------------
240
+ $config = [ordered]@{
241
+ version = 1
242
+ enabled = $Enabled
243
+ mode = $Mode
244
+ intervalSeconds = $IntervalSeconds
245
+ settleSeconds = 10
246
+ tokensThreshold = 300000
247
+ minTurns = 12
248
+ bytesThreshold = 0
249
+ eventsThreshold = 0
250
+ keepTurns = 12
251
+ keepTokens = 80000
252
+ firstUserCapChars = 4000
253
+ boundaryRetries = 3
254
+ cooldownMinutes = 60
255
+ profileConfig = $ProfileConfig
256
+ memoryRoot = $memory
257
+ sessionsRoot = $sessions
258
+ dshHome = $dsh
259
+ nodeExe = $node
260
+ cliPath = $cliPath
261
+ scanMaxFiles = 500
262
+ cliTimeoutSeconds = 600
263
+ taskName = $TaskName
264
+ installDir = $install
265
+ }
266
+ Write-JsonFile $configPath $config
267
+ Write-JsonFile (Join-Path $install 'install-manifest.json') ([ordered]@{
268
+ version = 1
269
+ installedAt = (Get-Date).ToString('o')
270
+ source = $repo
271
+ taskName = $TaskName
272
+ taskCommand = $taskCommand
273
+ files = @(
274
+ 'scripts\session-watch.mjs',
275
+ 'scripts\truncate-cli.mjs',
276
+ 'scripts\session-watch-status.ps1',
277
+ 'scripts\uninstall-session-watch.ps1',
278
+ 'src\',
279
+ 'package.json',
280
+ 'session-watch.config.json'
281
+ )
282
+ })
283
+
284
+ # --- validate the copied install ------------------------------------------------
285
+ Test-Node $node $watchPath
286
+ Test-Node $node $cliPath
287
+ $checkOutput = & $node $watchPath --config $configPath --check 2>&1
288
+ if ($LASTEXITCODE -ne 0) { Fail "watcher --check failed:`n$($checkOutput -join "`n")" }
289
+ try { $check = ($checkOutput -join "`n") | ConvertFrom-Json } catch { Fail "watcher --check did not return JSON:`n$($checkOutput -join "`n")" }
290
+ if (-not $check.ok) { Fail "watcher --check reported not-ok:`n$($checkOutput -join "`n")" }
291
+
292
+ # --- scheduled task -------------------------------------------------------------
293
+ $registered = $false
294
+ $registerMethod = $null
295
+ if (-not $NoRegister) {
296
+ $argument = "--config `"$configPath`" --loop"
297
+ $action = New-ScheduledTaskAction -Execute $node -Argument $argument -WorkingDirectory $install
298
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME"
299
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable `
300
+ -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero)
301
+ try {
302
+ Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings `
303
+ -Description 'DSH session watchdog: threshold-driven visible truncation, separate process tree.' -Force | Out-Null
304
+ $registered = $true
305
+ $registerMethod = 'Register-ScheduledTask'
306
+ } catch {
307
+ $fallback = "`"$node`" `"$watchPath`" --config `"$configPath`" --loop"
308
+ & schtasks.exe /Create /TN $TaskName /SC ONLOGON /RL LIMITED /TR $fallback /F 2>&1 | ForEach-Object { Write-Verbose $_ }
309
+ if ($LASTEXITCODE -ne 0) { Fail 'both Register-ScheduledTask and schtasks /Create failed' }
310
+ $registered = $true
311
+ $registerMethod = 'schtasks.exe'
312
+ }
313
+ }
314
+
315
+ $started = $false
316
+ if ($registered -and -not $NoStart) {
317
+ try {
318
+ Start-ScheduledTask -TaskName $TaskName
319
+ $started = $true
320
+ } catch {
321
+ & schtasks.exe /Run /TN $TaskName 2>&1 | ForEach-Object { Write-Verbose $_ }
322
+ if ($LASTEXITCODE -eq 0) { $started = $true }
323
+ }
324
+ }
325
+
326
+ $plan['registered'] = $registered
327
+ $plan['registerMethod'] = $registerMethod
328
+ $plan['started'] = $started
329
+ $plan['validated'] = $true
330
+ $plan['finishedAt'] = (Get-Date).ToString('o')
331
+ $plan | ConvertTo-Json -Depth 6
332
+ exit 0
@@ -0,0 +1,174 @@
1
+ #requires -Version 5.1
2
+ <#
3
+ .SYNOPSIS
4
+ Register and start the hidden longlive surgery task (no visible console).
5
+
6
+ .DESCRIPTION
7
+ Creates a one-shot Task Scheduler task that runs
8
+ scripts/unattended-surgery.ps1 through powershell.exe with
9
+ -NoProfile -NonInteractive -WindowStyle Hidden. The task has no window the
10
+ user can close: closing this registrar window before TASK_STARTED only
11
+ cancels registration; after TASK_STARTED the surgery is owned by the
12
+ Task Scheduler service.
13
+
14
+ The task is registered with -Hidden, ignores duplicate instances, and is
15
+ limited to 2 hours. It runs as the current interactive user.
16
+
17
+ .PARAMETER TaskName
18
+ Scheduled task name (default dsh-longlive-surgery). Re-registering replaces it.
19
+
20
+ .PARAMETER NoStart
21
+ Register only; do not start the task now.
22
+
23
+ .EXAMPLE
24
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\install-surgery-task.ps1 `
25
+ -SessionPath "%USERPROFILE%\.dsh\sessions\scope\abc\session.v4.jsonl.zstd" `
26
+ -AppPath "<path-to-DSH-host.exe>" -Confirm TRUNCATE-VISIBLE
27
+ #>
28
+ [CmdletBinding()]
29
+ param(
30
+ [Parameter(Mandatory = $true)]
31
+ [string]$SessionPath,
32
+
33
+ [int]$KeepTurns = 12,
34
+ [int]$KeepTokens = 80000,
35
+ [int]$StartDelaySeconds = 30,
36
+ [int]$RestartDelaySeconds = 0,
37
+
38
+ [string]$AppPath = '',
39
+ [string]$ResultPath = '',
40
+ [string]$MemoryRoot = '',
41
+ [string]$NodeExe = '',
42
+ [string]$Confirm = '',
43
+
44
+ [string]$TaskName = 'dsh-longlive-surgery',
45
+ [switch]$DryRun,
46
+ [switch]$AllowOutsideSessions,
47
+ [switch]$NoStart
48
+ )
49
+
50
+ $ErrorActionPreference = 'Stop'
51
+
52
+ function Write-Fail {
53
+ param([string]$Message, [int]$Code = 2)
54
+ [Console]::Error.WriteLine($Message)
55
+ exit $Code
56
+ }
57
+
58
+ if (-not (Test-Path -LiteralPath $SessionPath -PathType Leaf)) {
59
+ Write-Fail "SessionPath not found: $SessionPath" 2
60
+ }
61
+ $SessionPath = (Resolve-Path -LiteralPath $SessionPath).Path
62
+
63
+ if (-not $DryRun) {
64
+ if ($Confirm -ne 'TRUNCATE-VISIBLE') {
65
+ Write-Fail "Refusing to register a real cut: pass -Confirm TRUNCATE-VISIBLE (or -DryRun)." 2
66
+ }
67
+ if (-not $AppPath -and $env:DSH_APP_PATH) {
68
+ $AppPath = $env:DSH_APP_PATH
69
+ }
70
+ if (-not $AppPath) {
71
+ Write-Fail "Refusing to register a real cut: pass -AppPath <dsh host exe> or set DSH_APP_PATH." 2
72
+ }
73
+ }
74
+ if ($AppPath) {
75
+ if (-not (Test-Path -LiteralPath $AppPath -PathType Leaf)) {
76
+ Write-Fail "AppPath not found: $AppPath" 2
77
+ }
78
+ $AppPath = (Resolve-Path -LiteralPath $AppPath).Path
79
+ }
80
+ if ($TaskName -notmatch '^[A-Za-z0-9._-]{1,120}$') {
81
+ Write-Fail "TaskName may only contain letters, digits, dot, underscore, dash (max 120)." 2
82
+ }
83
+
84
+ $launcher = Join-Path $PSScriptRoot 'unattended-surgery.ps1'
85
+ if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
86
+ Write-Fail "Launcher not found: $launcher" 2
87
+ }
88
+
89
+ function Quote-Arg {
90
+ param([string]$Value)
91
+ if ($Value -match '[\s"]') {
92
+ return '"' + ($Value -replace '"', '\"') + '"'
93
+ }
94
+ return $Value
95
+ }
96
+
97
+ $tokens = @(
98
+ '-NoProfile',
99
+ '-NonInteractive',
100
+ '-WindowStyle', 'Hidden',
101
+ '-ExecutionPolicy', 'Bypass',
102
+ '-File', (Quote-Arg $launcher),
103
+ '-SessionPath', (Quote-Arg $SessionPath),
104
+ '-KeepTurns', "$KeepTurns",
105
+ '-KeepTokens', "$KeepTokens",
106
+ '-StartDelaySeconds', "$StartDelaySeconds",
107
+ '-RestartDelaySeconds', "$RestartDelaySeconds"
108
+ )
109
+ if ($AppPath) { $tokens += @('-AppPath', (Quote-Arg $AppPath)) }
110
+ if ($ResultPath) { $tokens += @('-ResultPath', (Quote-Arg $ResultPath)) }
111
+ if ($MemoryRoot) { $tokens += @('-MemoryRoot', (Quote-Arg $MemoryRoot)) }
112
+ if ($NodeExe) { $tokens += @('-NodeExe', (Quote-Arg $NodeExe)) }
113
+ if ($DryRun) { $tokens += '-DryRun' } else { $tokens += @('-Confirm', 'TRUNCATE-VISIBLE') }
114
+ if ($AllowOutsideSessions) { $tokens += '-AllowOutsideSessions' }
115
+
116
+ $argumentLine = $tokens -join ' '
117
+
118
+ $registered = $false
119
+ try {
120
+ if (Get-Command Register-ScheduledTask -ErrorAction SilentlyContinue) {
121
+ $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $argumentLine
122
+ $settings = New-ScheduledTaskSettingsSet `
123
+ -Hidden `
124
+ -AllowStartIfOnBatteries `
125
+ -DontStopIfGoingOnBatteries `
126
+ -MultipleInstances IgnoreNew `
127
+ -ExecutionTimeLimit (New-TimeSpan -Hours 2)
128
+ $userId = $env:USERNAME
129
+ if ($env:USERDOMAIN) { $userId = "$env:USERDOMAIN\$env:USERNAME" }
130
+ $principal = New-ScheduledTaskPrincipal -UserId $userId -LogonType Interactive -RunLevel Limited
131
+ Register-ScheduledTask -TaskName $TaskName -Action $action -Settings $settings -Principal $principal -Force | Out-Null
132
+ $registered = $true
133
+ }
134
+ } catch {
135
+ [Console]::Error.WriteLine("Register-ScheduledTask failed: $($_.Exception.Message)")
136
+ }
137
+
138
+ if (-not $registered) {
139
+ # Windows PowerShell 5.1 always has schtasks.exe; /IT keeps it in the
140
+ # interactive session so the restarted host is visible on the desktop.
141
+ $taskCommand = 'powershell.exe ' + $argumentLine
142
+ & schtasks.exe /Create /TN $TaskName /SC ONCE /ST 23:59 /F /IT /TR $taskCommand | Out-Null
143
+ if ($LASTEXITCODE -ne 0) {
144
+ Write-Fail "schtasks /Create failed with exit code $LASTEXITCODE" 1
145
+ }
146
+ $registered = $true
147
+ }
148
+
149
+ if (-not $registered) {
150
+ Write-Fail "Could not register scheduled task $TaskName" 1
151
+ }
152
+
153
+ if ($NoStart) {
154
+ Write-Output "TASK_REGISTERED $TaskName"
155
+ exit 0
156
+ }
157
+
158
+ if (Get-Command Start-ScheduledTask -ErrorAction SilentlyContinue) {
159
+ Start-ScheduledTask -TaskName $TaskName
160
+ } else {
161
+ & schtasks.exe /Run /TN $TaskName | Out-Null
162
+ if ($LASTEXITCODE -ne 0) {
163
+ Write-Fail "schtasks /Run failed with exit code $LASTEXITCODE" 1
164
+ }
165
+ }
166
+
167
+ Write-Output "TASK_STARTED $TaskName"
168
+ Write-Output "The surgery now runs detached and windowless. This console can be closed."
169
+ if ($DryRun) {
170
+ Write-Output "Dry run: no host will be closed and no bytes will be cut."
171
+ } else {
172
+ Write-Output ("Closing the host in {0} seconds (reading window), then cut, verify, receipt, restart (+{1}s)." -f $StartDelaySeconds, $RestartDelaySeconds)
173
+ }
174
+ exit 0