@hivemagnus/magnus-server 0.0.0-stage → 1.0.2

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 (356) hide show
  1. package/.env.example +171 -0
  2. package/LICENSE +202 -0
  3. package/README.md +169 -2
  4. package/agent-version.json +1 -0
  5. package/dist/ai/HEARTBEAT.md +56 -0
  6. package/dist/ai/IDENTITY.md +54 -0
  7. package/dist/ai/MEMORY.md +40 -0
  8. package/dist/ai/TOOLS.md +538 -0
  9. package/dist/ai/USER.md +32 -0
  10. package/dist/cli/args.js +62 -0
  11. package/dist/cli/env-catalog.js +131 -0
  12. package/dist/cli/preflight.js +89 -0
  13. package/dist/cli.js +175 -0
  14. package/dist/config/cors.js +16 -0
  15. package/dist/config/env.js +392 -0
  16. package/dist/config/features.js +16 -0
  17. package/dist/config/index.js +3 -0
  18. package/dist/config/listener-security.js +38 -0
  19. package/dist/config/version.js +31 -0
  20. package/dist/db/client.js +44 -0
  21. package/dist/db/generated/prisma/browser.js +18 -0
  22. package/dist/db/generated/prisma/client.js +35 -0
  23. package/dist/db/generated/prisma/commonInputTypes.js +11 -0
  24. package/dist/db/generated/prisma/enums.js +42 -0
  25. package/dist/db/generated/prisma/internal/class.js +50 -0
  26. package/dist/db/generated/prisma/internal/prismaNamespace.js +1598 -0
  27. package/dist/db/generated/prisma/internal/prismaNamespaceBrowser.js +1569 -0
  28. package/dist/db/generated/prisma/models/A2ATask.js +2 -0
  29. package/dist/db/generated/prisma/models/AdmissionFence.js +2 -0
  30. package/dist/db/generated/prisma/models/Agent.js +2 -0
  31. package/dist/db/generated/prisma/models/AiConversation.js +2 -0
  32. package/dist/db/generated/prisma/models/AiDashboard.js +2 -0
  33. package/dist/db/generated/prisma/models/AiMemory.js +2 -0
  34. package/dist/db/generated/prisma/models/AiMessage.js +2 -0
  35. package/dist/db/generated/prisma/models/AiScheduledOp.js +2 -0
  36. package/dist/db/generated/prisma/models/AlertConditionState.js +2 -0
  37. package/dist/db/generated/prisma/models/AlertRule.js +2 -0
  38. package/dist/db/generated/prisma/models/AlertViolation.js +2 -0
  39. package/dist/db/generated/prisma/models/AnomalyEvent.js +2 -0
  40. package/dist/db/generated/prisma/models/ApplicationObservation.js +2 -0
  41. package/dist/db/generated/prisma/models/ArdentInstallation.js +2 -0
  42. package/dist/db/generated/prisma/models/ArdentProfile.js +2 -0
  43. package/dist/db/generated/prisma/models/ArdentScopeEnrollment.js +2 -0
  44. package/dist/db/generated/prisma/models/CommandResourceFence.js +2 -0
  45. package/dist/db/generated/prisma/models/CommandResourceLease.js +2 -0
  46. package/dist/db/generated/prisma/models/CommandResult.js +2 -0
  47. package/dist/db/generated/prisma/models/CronJob.js +2 -0
  48. package/dist/db/generated/prisma/models/CronJobExecution.js +2 -0
  49. package/dist/db/generated/prisma/models/DeployJob.js +2 -0
  50. package/dist/db/generated/prisma/models/DriftScan.js +2 -0
  51. package/dist/db/generated/prisma/models/EngineeringMetricSample.js +2 -0
  52. package/dist/db/generated/prisma/models/EngineeringRecoveryExercise.js +2 -0
  53. package/dist/db/generated/prisma/models/ExecutionRun.js +2 -0
  54. package/dist/db/generated/prisma/models/FilePatchTask.js +2 -0
  55. package/dist/db/generated/prisma/models/GpuSnapshot.js +2 -0
  56. package/dist/db/generated/prisma/models/HealthSnapshot.js +2 -0
  57. package/dist/db/generated/prisma/models/HermesCoreRollout.js +2 -0
  58. package/dist/db/generated/prisma/models/HermesCoreRolloutHost.js +2 -0
  59. package/dist/db/generated/prisma/models/HermesCredentialPool.js +2 -0
  60. package/dist/db/generated/prisma/models/HermesCredentialPoolAttachment.js +2 -0
  61. package/dist/db/generated/prisma/models/HermesCronJob.js +2 -0
  62. package/dist/db/generated/prisma/models/HermesHook.js +2 -0
  63. package/dist/db/generated/prisma/models/HermesInstallation.js +2 -0
  64. package/dist/db/generated/prisma/models/HermesMcpServer.js +2 -0
  65. package/dist/db/generated/prisma/models/HermesMcpServerAttachment.js +2 -0
  66. package/dist/db/generated/prisma/models/HermesMessagingBinding.js +2 -0
  67. package/dist/db/generated/prisma/models/HermesOperationJob.js +2 -0
  68. package/dist/db/generated/prisma/models/HermesPluginInstall.js +2 -0
  69. package/dist/db/generated/prisma/models/HermesProfile.js +2 -0
  70. package/dist/db/generated/prisma/models/HermesProviderConfig.js +2 -0
  71. package/dist/db/generated/prisma/models/HermesRegistryClient.js +2 -0
  72. package/dist/db/generated/prisma/models/HermesRegistryInventory.js +2 -0
  73. package/dist/db/generated/prisma/models/HermesRegistryReceipt.js +2 -0
  74. package/dist/db/generated/prisma/models/HermesRegistryRevision.js +2 -0
  75. package/dist/db/generated/prisma/models/HermesRegistryTarget.js +2 -0
  76. package/dist/db/generated/prisma/models/HermesRole.js +2 -0
  77. package/dist/db/generated/prisma/models/HermesRoleApplication.js +2 -0
  78. package/dist/db/generated/prisma/models/HermesSkillAssignment.js +2 -0
  79. package/dist/db/generated/prisma/models/HermesToolsetPolicy.js +2 -0
  80. package/dist/db/generated/prisma/models/IncidentLesson.js +2 -0
  81. package/dist/db/generated/prisma/models/LibraryCategory.js +2 -0
  82. package/dist/db/generated/prisma/models/LibraryFile.js +2 -0
  83. package/dist/db/generated/prisma/models/LogEntry.js +2 -0
  84. package/dist/db/generated/prisma/models/MagnusReleaseCanary.js +2 -0
  85. package/dist/db/generated/prisma/models/MaintenanceWindow.js +2 -0
  86. package/dist/db/generated/prisma/models/ManagedCronDefinition.js +2 -0
  87. package/dist/db/generated/prisma/models/ManagedCronOccurrence.js +2 -0
  88. package/dist/db/generated/prisma/models/Node.js +2 -0
  89. package/dist/db/generated/prisma/models/Notification.js +2 -0
  90. package/dist/db/generated/prisma/models/NotificationPreference.js +2 -0
  91. package/dist/db/generated/prisma/models/RemediationExecution.js +2 -0
  92. package/dist/db/generated/prisma/models/RemediationRule.js +2 -0
  93. package/dist/db/generated/prisma/models/RemoteCommand.js +2 -0
  94. package/dist/db/generated/prisma/models/ResourceDrainParticipant.js +2 -0
  95. package/dist/db/generated/prisma/models/ResourceEnrollment.js +2 -0
  96. package/dist/db/generated/prisma/models/ResourceParticipantWork.js +2 -0
  97. package/dist/db/generated/prisma/models/Role.js +2 -0
  98. package/dist/db/generated/prisma/models/RoleApplication.js +2 -0
  99. package/dist/db/generated/prisma/models/RolloutTarget.js +2 -0
  100. package/dist/db/generated/prisma/models/SecurityExportOutbox.js +2 -0
  101. package/dist/db/generated/prisma/models/SecurityFusionAction.js +2 -0
  102. package/dist/db/generated/prisma/models/SecurityFusionActionApproval.js +2 -0
  103. package/dist/db/generated/prisma/models/SecurityFusionCase.js +2 -0
  104. package/dist/db/generated/prisma/models/SecurityFusionCaseActivity.js +2 -0
  105. package/dist/db/generated/prisma/models/SecurityFusionCaseEntity.js +2 -0
  106. package/dist/db/generated/prisma/models/SecurityFusionCaseEvent.js +2 -0
  107. package/dist/db/generated/prisma/models/SecurityFusionCaseRelationship.js +2 -0
  108. package/dist/db/generated/prisma/models/SecurityFusionCollector.js +2 -0
  109. package/dist/db/generated/prisma/models/SecurityFusionCommandOutbox.js +2 -0
  110. package/dist/db/generated/prisma/models/SecurityFusionDeletionReceipt.js +2 -0
  111. package/dist/db/generated/prisma/models/SecurityFusionDelivery.js +2 -0
  112. package/dist/db/generated/prisma/models/SecurityFusionEntity.js +2 -0
  113. package/dist/db/generated/prisma/models/SecurityFusionEntityAlias.js +2 -0
  114. package/dist/db/generated/prisma/models/SecurityFusionEvent.js +2 -0
  115. package/dist/db/generated/prisma/models/SecurityFusionEventEntity.js +2 -0
  116. package/dist/db/generated/prisma/models/SecurityFusionEvidence.js +2 -0
  117. package/dist/db/generated/prisma/models/SecurityFusionInvestigation.js +2 -0
  118. package/dist/db/generated/prisma/models/SecurityFusionNonce.js +2 -0
  119. package/dist/db/generated/prisma/models/SecurityFusionReceiptChainHead.js +2 -0
  120. package/dist/db/generated/prisma/models/SecurityFusionRuleVersion.js +2 -0
  121. package/dist/db/generated/prisma/models/SecurityFusionSourceState.js +2 -0
  122. package/dist/db/generated/prisma/models/SecurityServiceState.js +2 -0
  123. package/dist/db/generated/prisma/models/SharedResourceFence.js +2 -0
  124. package/dist/db/generated/prisma/models/SharedResourceLease.js +2 -0
  125. package/dist/db/generated/prisma/models/SharedResourceLeaseResource.js +2 -0
  126. package/dist/db/generated/prisma/models/SkillInstallation.js +2 -0
  127. package/dist/db/generated/prisma/models/SkillRegistryEntry.js +2 -0
  128. package/dist/db/generated/prisma/models/SkillTag.js +2 -0
  129. package/dist/db/generated/prisma/models/SkillVersion.js +2 -0
  130. package/dist/db/generated/prisma/models/TeamApprovalDecision.js +2 -0
  131. package/dist/db/generated/prisma/models/User.js +2 -0
  132. package/dist/db/generated/prisma/models/WebhookDelivery.js +2 -0
  133. package/dist/db/generated/prisma/models/WebhookEndpoint.js +2 -0
  134. package/dist/db/generated/prisma/models.js +2 -0
  135. package/dist/db/index.js +3 -0
  136. package/dist/db/read-retry.js +35 -0
  137. package/dist/db/seed.js +348 -0
  138. package/dist/index.js +162 -0
  139. package/dist/middleware/auth.js +361 -0
  140. package/dist/middleware/body-limit.js +14 -0
  141. package/dist/middleware/correlation-id.js +13 -0
  142. package/dist/middleware/error-handler.js +28 -0
  143. package/dist/middleware/iam-token.js +21 -0
  144. package/dist/middleware/rate-limit.js +78 -0
  145. package/dist/middleware/request-logger.js +85 -0
  146. package/dist/middleware/security-headers.js +23 -0
  147. package/dist/middleware/tracing.js +120 -0
  148. package/dist/middleware/user-status.js +33 -0
  149. package/dist/openapi/spec.js +2656 -0
  150. package/dist/queue/redis.js +20 -0
  151. package/dist/queue/requeue.js +27 -0
  152. package/dist/queue/workers.js +342 -0
  153. package/dist/routes/ai-schedule.js +73 -0
  154. package/dist/routes/alerts.js +79 -0
  155. package/dist/routes/anomalies.js +101 -0
  156. package/dist/routes/ardent.js +82 -0
  157. package/dist/routes/assistant.js +417 -0
  158. package/dist/routes/audit.js +138 -0
  159. package/dist/routes/codex.js +65 -0
  160. package/dist/routes/commands.js +226 -0
  161. package/dist/routes/credentials.js +58 -0
  162. package/dist/routes/cron.js +292 -0
  163. package/dist/routes/dependencies.js +49 -0
  164. package/dist/routes/deploy.js +18 -0
  165. package/dist/routes/discovery.js +168 -0
  166. package/dist/routes/docs.js +24 -0
  167. package/dist/routes/drift.js +126 -0
  168. package/dist/routes/events-stream.js +87 -0
  169. package/dist/routes/files.js +214 -0
  170. package/dist/routes/fleet-checks.js +21 -0
  171. package/dist/routes/health.js +133 -0
  172. package/dist/routes/heartbeat.js +545 -0
  173. package/dist/routes/hermes-registry.js +278 -0
  174. package/dist/routes/hermes.js +61 -0
  175. package/dist/routes/library.js +402 -0
  176. package/dist/routes/logs.js +172 -0
  177. package/dist/routes/managed-cron.js +23 -0
  178. package/dist/routes/mcp.js +39 -0
  179. package/dist/routes/metrics.js +187 -0
  180. package/dist/routes/nodes.js +951 -0
  181. package/dist/routes/notifications.js +130 -0
  182. package/dist/routes/ops.js +258 -0
  183. package/dist/routes/orchestra.js +430 -0
  184. package/dist/routes/predictions.js +23 -0
  185. package/dist/routes/profiling.js +68 -0
  186. package/dist/routes/quick-command.js +72 -0
  187. package/dist/routes/remediation.js +111 -0
  188. package/dist/routes/resource-leases.js +297 -0
  189. package/dist/routes/roles.js +370 -0
  190. package/dist/routes/rollout.js +124 -0
  191. package/dist/routes/scan.js +116 -0
  192. package/dist/routes/security-backup.js +58 -0
  193. package/dist/routes/security-fusion.js +605 -0
  194. package/dist/routes/security-integration.js +71 -0
  195. package/dist/routes/self-update.js +129 -0
  196. package/dist/routes/shared-resource-leases.js +78 -0
  197. package/dist/routes/skills.js +485 -0
  198. package/dist/routes/stats.js +96 -0
  199. package/dist/routes/team-approvals.js +23 -0
  200. package/dist/routes/terminal-ticket.js +15 -0
  201. package/dist/routes/terminal.js +17 -0
  202. package/dist/routes/topology.js +37 -0
  203. package/dist/routes/users.js +219 -0
  204. package/dist/routes/webhooks.js +137 -0
  205. package/dist/schemas/command-reconciliation.js +14 -0
  206. package/dist/schemas/commands.js +51 -0
  207. package/dist/schemas/cron.js +33 -0
  208. package/dist/schemas/deploy.js +20 -0
  209. package/dist/schemas/files.js +14 -0
  210. package/dist/schemas/hermes.js +69 -0
  211. package/dist/schemas/index.js +11 -0
  212. package/dist/schemas/library.js +48 -0
  213. package/dist/schemas/logs.js +35 -0
  214. package/dist/schemas/managed-cron.js +127 -0
  215. package/dist/schemas/node-responses.js +87 -0
  216. package/dist/schemas/node-session-receipt.js +84 -0
  217. package/dist/schemas/nodes.js +36 -0
  218. package/dist/schemas/orchestra.js +118 -0
  219. package/dist/schemas/resource-participant-reconciliation.js +99 -0
  220. package/dist/schemas/roles.js +54 -0
  221. package/dist/schemas/shared-resource-lease.js +132 -0
  222. package/dist/schemas/skills.js +44 -0
  223. package/dist/schemas/users.js +28 -0
  224. package/dist/scripts/run-disposable-recovery-exercise.js +39 -0
  225. package/dist/sdk/index.js +2 -0
  226. package/dist/sdk/node-api-client.js +474 -0
  227. package/dist/security/approval-assertion.js +66 -0
  228. package/dist/security/command-completion-registry.js +35 -0
  229. package/dist/security/command-request.js +12 -0
  230. package/dist/security/command-result-signature.js +34 -0
  231. package/dist/security/managed-http.js +45 -0
  232. package/dist/security/native-completion-registry.js +44 -0
  233. package/dist/server.js +178 -0
  234. package/dist/services/admission-fence.js +71 -0
  235. package/dist/services/ai-assistant-service.js +2523 -0
  236. package/dist/services/ai-correlation-service.js +225 -0
  237. package/dist/services/ai-export-service.js +141 -0
  238. package/dist/services/ai-insights-service.js +219 -0
  239. package/dist/services/ai-schedule-service.js +145 -0
  240. package/dist/services/ai-scratchpad-service.js +222 -0
  241. package/dist/services/ai-tools.js +1343 -0
  242. package/dist/services/alert-service.js +313 -0
  243. package/dist/services/anomaly-detector.js +419 -0
  244. package/dist/services/api-local-work.js +79 -0
  245. package/dist/services/application-probes.js +309 -0
  246. package/dist/services/ardent-scope-enrollment.js +123 -0
  247. package/dist/services/ardent-service.js +86 -0
  248. package/dist/services/audit-service.js +308 -0
  249. package/dist/services/codex-service.js +209 -0
  250. package/dist/services/command-lifecycle.js +60 -0
  251. package/dist/services/command-resource-leases.js +305 -0
  252. package/dist/services/control-host-node.js +242 -0
  253. package/dist/services/credential-rotation-service.js +294 -0
  254. package/dist/services/dependency-service.js +145 -0
  255. package/dist/services/disposable-recovery-runner.js +595 -0
  256. package/dist/services/docker-group-health.js +121 -0
  257. package/dist/services/engineering-assurance.js +492 -0
  258. package/dist/services/engineering-evidence-ledger.js +94 -0
  259. package/dist/services/engineering-metric-evidence.js +26 -0
  260. package/dist/services/event-bus.js +227 -0
  261. package/dist/services/fleet-check-log.js +102 -0
  262. package/dist/services/forecast-service.js +154 -0
  263. package/dist/services/health-retention.js +175 -0
  264. package/dist/services/heartbeat-stream.js +63 -0
  265. package/dist/services/hermes-catalog-import.js +62 -0
  266. package/dist/services/hermes-cli-parser.js +671 -0
  267. package/dist/services/hermes-core-rollout.js +90 -0
  268. package/dist/services/hermes-dashboard-endpoint.js +13 -0
  269. package/dist/services/hermes-plugin-source.js +149 -0
  270. package/dist/services/hermes-registry-service.js +258 -0
  271. package/dist/services/hermes-service.js +566 -0
  272. package/dist/services/hivemem-client.js +85 -0
  273. package/dist/services/host-local-writer.js +82 -0
  274. package/dist/services/incident-evidence.js +110 -0
  275. package/dist/services/incident-lessons.js +186 -0
  276. package/dist/services/llm-providers/anthropic.js +143 -0
  277. package/dist/services/llm-providers/index.js +7 -0
  278. package/dist/services/llm-providers/llama-cpp.js +237 -0
  279. package/dist/services/llm-providers/ollama.js +292 -0
  280. package/dist/services/llm-providers/openai-compatible.js +200 -0
  281. package/dist/services/llm-providers/provider-error.js +36 -0
  282. package/dist/services/llm-providers/registry.js +45 -0
  283. package/dist/services/llm-providers/types.js +2 -0
  284. package/dist/services/log-emitter.js +19 -0
  285. package/dist/services/log-retention.js +66 -0
  286. package/dist/services/maintenance-service.js +29 -0
  287. package/dist/services/managed-cron.js +493 -0
  288. package/dist/services/managed-ssh-admission.js +68 -0
  289. package/dist/services/monitor-pulse.js +10 -0
  290. package/dist/services/node-issue-monitor.js +71 -0
  291. package/dist/services/node-service.js +35 -0
  292. package/dist/services/notification-retention.js +51 -0
  293. package/dist/services/notification-service.js +94 -0
  294. package/dist/services/operational-observations.js +112 -0
  295. package/dist/services/operations-config.js +67 -0
  296. package/dist/services/ops-service.js +491 -0
  297. package/dist/services/orchestra-extras-service.js +370 -0
  298. package/dist/services/orchestra-resources-service.js +530 -0
  299. package/dist/services/os-scheduler-writer.js +73 -0
  300. package/dist/services/password-service.js +22 -0
  301. package/dist/services/prediction-service.js +284 -0
  302. package/dist/services/recovery-exercises.js +682 -0
  303. package/dist/services/remediation-service.js +325 -0
  304. package/dist/services/resource-enrollment.js +433 -0
  305. package/dist/services/resource-node-lock.js +18 -0
  306. package/dist/services/resource-participant-work.js +302 -0
  307. package/dist/services/role-service.js +388 -0
  308. package/dist/services/rollout-service.js +440 -0
  309. package/dist/services/security-export.js +185 -0
  310. package/dist/services/security-fusion-actions.js +22 -0
  311. package/dist/services/security-fusion-approvals.js +83 -0
  312. package/dist/services/security-fusion-evidence-integrity.js +144 -0
  313. package/dist/services/security-fusion-ingest.js +101 -0
  314. package/dist/services/security-fusion-outbox.js +185 -0
  315. package/dist/services/security-fusion-receipt-chain.js +134 -0
  316. package/dist/services/security-fusion-service.js +751 -0
  317. package/dist/services/security-fusion-verification.js +50 -0
  318. package/dist/services/self-update-service.js +200 -0
  319. package/dist/services/shared-resource-leases.js +413 -0
  320. package/dist/services/skill-publication-bundle.js +90 -0
  321. package/dist/services/skill-publication-settlement.js +36 -0
  322. package/dist/services/skill-publication-state.js +40 -0
  323. package/dist/services/skill-registry-service.js +327 -0
  324. package/dist/services/skill-service.js +148 -0
  325. package/dist/services/ssh-exec-service.js +139 -0
  326. package/dist/services/ssh-host-verification.js +27 -0
  327. package/dist/services/tailscale-node-key-service.js +75 -0
  328. package/dist/services/team-approvals.js +118 -0
  329. package/dist/services/topology-service.js +138 -0
  330. package/dist/services/transfer-authority-snapshot.js +151 -0
  331. package/dist/services/webhook-credential-migration.js +97 -0
  332. package/dist/services/webhook-security.js +242 -0
  333. package/dist/services/webhook-service.js +494 -0
  334. package/dist/types/auth.js +3 -0
  335. package/dist/types/index.js +3 -0
  336. package/dist/types/library.js +3 -0
  337. package/dist/types/notifications.js +3 -0
  338. package/dist/types/roles.js +3 -0
  339. package/dist/types/shared-contracts.js +3 -0
  340. package/dist/utils/env.js +141 -0
  341. package/dist/utils/heartbeat-peer.js +19 -0
  342. package/dist/utils/idempotency.js +45 -0
  343. package/dist/utils/ip.js +25 -0
  344. package/dist/utils/json-fields.js +94 -0
  345. package/dist/utils/local-tls.js +39 -0
  346. package/dist/utils/magnus-home.js +15 -0
  347. package/dist/utils/node-url.js +59 -0
  348. package/dist/utils/redact.js +26 -0
  349. package/dist/utils/safe-equal.js +13 -0
  350. package/dist/utils/sentinel-nodes.js +16 -0
  351. package/dist/utils/validate.js +41 -0
  352. package/package.json +119 -4
  353. package/prisma/migrations/20261031000000_baseline/migration.sql +2935 -0
  354. package/prisma/migrations/migration_lock.toml +3 -0
  355. package/prisma/schema.prisma +2185 -0
  356. package/prisma.config.ts +14 -0
@@ -0,0 +1,94 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstatSync, readFileSync } from 'node:fs';
3
+ import { z } from 'zod';
4
+ const id = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9:._/-]{0,159}$/);
5
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
6
+ const revision = z.string().regex(/^[a-f0-9]{40}$/);
7
+ const isoDate = z.string().datetime({ offset: true });
8
+ const evidence = z.object({ evidenceSha256: digest, observedAt: isoDate, source: id }).strict();
9
+ const common = {
10
+ sequence: z.number().int().positive(),
11
+ previousReceiptSha256: digest.nullable(),
12
+ receiptSha256: digest,
13
+ recordedAt: isoDate,
14
+ };
15
+ export const deliveryEvidenceRecordSchema = z.object({
16
+ ...common,
17
+ kind: z.literal('delivery'),
18
+ requestId: id,
19
+ applicationId: id,
20
+ deploySource: z.string().min(1).max(500),
21
+ documentationOnly: z.boolean(),
22
+ establishedProductionWorkflow: z.boolean(),
23
+ source: z.object({ workingRevision: revision, mainRevision: revision, remoteRevision: revision,
24
+ sourceTreeSha256: digest }).strict(),
25
+ tests: z.array(z.object({ name: id, revision, status: z.literal('passed') }).merge(evidence)).min(1).max(100),
26
+ review: evidence.extend({ revision }),
27
+ ci: z.object({ revision, status: z.literal('passed') }).merge(evidence),
28
+ deployment: z.object({ applicationId: id, deploySource: z.string().min(1).max(500), revision,
29
+ sourceTreeSha256: digest, deployedAt: isoDate, evidenceSha256: digest, source: id }).strict().optional(),
30
+ limitations: z.array(z.string().min(1).max(500)).max(50),
31
+ }).strict();
32
+ export const exerciseEvidenceRecordSchema = z.object({
33
+ ...common,
34
+ kind: z.literal('exercise'),
35
+ exerciseId: id,
36
+ environment: z.object({ isolated: z.literal(true), production: z.literal(false), targetId: id }).strict(),
37
+ scenario: z.enum(['backup_restore', 'rollback', 'specialist_loss', 'coordinator_loss']),
38
+ startedAt: isoDate,
39
+ recoveredAt: isoDate,
40
+ recoveryPointAt: isoDate,
41
+ objectives: z.object({ rtoSeconds: z.number().int().positive(), rpoSeconds: z.number().int().nonnegative() }).strict(),
42
+ before: z.object({ stateSha256: digest, taskReceiptsSha256: digest, artifactManifestSha256: digest }).strict(),
43
+ after: z.object({ stateSha256: digest, taskReceiptsSha256: digest, artifactManifestSha256: digest }).strict(),
44
+ directRecoveryEvidence: evidence,
45
+ }).strict();
46
+ export const engineeringEvidenceLedgerSchema = z.object({
47
+ schemaVersion: z.literal(1),
48
+ records: z.array(z.discriminatedUnion('kind', [deliveryEvidenceRecordSchema, exerciseEvidenceRecordSchema])).max(10_000),
49
+ }).strict().superRefine((value, ctx) => {
50
+ value.records.forEach((record, index) => {
51
+ if (record.kind === 'delivery' && record.establishedProductionWorkflow && !record.documentationOnly && !record.deployment)
52
+ ctx.addIssue({ code: 'custom', message: 'Established production workflow requires an application-bound deployment receipt',
53
+ path: ['records', index, 'deployment'] });
54
+ });
55
+ });
56
+ function canonical(value) {
57
+ if (Array.isArray(value))
58
+ return `[${value.map(canonical).join(',')}]`;
59
+ if (value && typeof value === 'object')
60
+ return `{${Object.entries(value)
61
+ .sort(([a], [b]) => a.localeCompare(b)).map(([key, field]) => `${JSON.stringify(key)}:${canonical(field)}`).join(',')}}`;
62
+ return JSON.stringify(value);
63
+ }
64
+ function hash(value) { return createHash('sha256').update(canonical(value)).digest('hex'); }
65
+ export function engineeringEvidenceReceiptSha256(record) {
66
+ const { receiptSha256: _receiptSha256, ...payload } = record;
67
+ return hash(payload);
68
+ }
69
+ export function loadEngineeringEvidenceLedger(path = process.env['MAGNUS_ENGINEERING_EVIDENCE_FILE'], expectedHeadSha256 = process.env['MAGNUS_ENGINEERING_EVIDENCE_HEAD_SHA256']) {
70
+ if (!path)
71
+ throw new Error('MAGNUS_ENGINEERING_EVIDENCE_FILE is not configured');
72
+ if (!expectedHeadSha256 || !digest.safeParse(expectedHeadSha256).success)
73
+ throw new Error('MAGNUS_ENGINEERING_EVIDENCE_HEAD_SHA256 must pin the current ledger head');
74
+ const stat = lstatSync(path);
75
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 2_000_000 || (stat.mode & 0o022))
76
+ throw new Error('Unsafe engineering evidence ledger');
77
+ const parsed = engineeringEvidenceLedgerSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
78
+ let previous = null;
79
+ const unique = new Set();
80
+ parsed.records.forEach((record, index) => {
81
+ if (record.sequence !== index + 1 || record.previousReceiptSha256 !== previous
82
+ || engineeringEvidenceReceiptSha256(record) !== record.receiptSha256)
83
+ throw new Error(`Invalid engineering evidence chain at sequence ${index + 1}`);
84
+ const key = record.kind === 'delivery' ? `delivery:${record.requestId}` : `exercise:${record.exerciseId}`;
85
+ if (unique.has(key))
86
+ throw new Error(`Duplicate engineering evidence record ${key}`);
87
+ unique.add(key);
88
+ previous = record.receiptSha256;
89
+ });
90
+ if (previous !== expectedHeadSha256)
91
+ throw new Error('Engineering evidence ledger head does not match configured pin');
92
+ return { ...parsed, ledgerSha256: hash(parsed), headSha256: previous };
93
+ }
94
+ //# sourceMappingURL=engineering-evidence-ledger.js.map
@@ -0,0 +1,26 @@
1
+ import { createHash } from 'node:crypto';
2
+ function canonical(value) {
3
+ if (Array.isArray(value))
4
+ return `[${value.map(canonical).join(',')}]`;
5
+ if (value && typeof value === 'object')
6
+ return `{${Object.entries(value)
7
+ .sort(([a], [b]) => a.localeCompare(b)).map(([key, field]) => `${JSON.stringify(key)}:${canonical(field)}`).join(',')}}`;
8
+ return JSON.stringify(value);
9
+ }
10
+ export function engineeringMetricEvidenceSha256(input) {
11
+ return createHash('sha256').update(canonical({
12
+ version: 1,
13
+ applicationId: input.applicationId,
14
+ nodeId: input.nodeId,
15
+ metric: input.metric,
16
+ sourceKey: input.sourceKey,
17
+ unit: input.unit,
18
+ value: input.value,
19
+ observedAt: typeof input.observedAt === 'string' ? input.observedAt : input.observedAt.toISOString(),
20
+ probeContractSha256: input.probeContractSha256,
21
+ method: input.method,
22
+ path: input.path,
23
+ httpStatus: input.httpStatus,
24
+ })).digest('hex');
25
+ }
26
+ //# sourceMappingURL=engineering-metric-evidence.js.map
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Redis-backed event bus for real-time inter-service communication.
3
+ *
4
+ * Uses Redis Pub/Sub to broadcast events (node status changes, commands,
5
+ * audit events, alerts) to all connected subscribers. Enables front-end
6
+ * SSE endpoints to receive live updates without polling.
7
+ *
8
+ * Usage:
9
+ * import { eventBus } from './event-bus.js';
10
+ * eventBus.publish('node:status', { nodeId, status });
11
+ * eventBus.subscribe('node:*', (channel, data) => { ... });
12
+ */
13
+ import { Redis } from 'ioredis';
14
+ import { randomUUID } from 'node:crypto';
15
+ import { EventEmitter } from 'node:events';
16
+ const REDIS_URL = process.env['REDIS_URL'] ?? 'redis://127.0.0.1:6379';
17
+ const CHANNEL_PREFIX = 'magnus:events:';
18
+ const FAILURE_THRESHOLD = 3;
19
+ const RESET_TIMEOUT_MS = 30_000; // 30s before trying half-open
20
+ const MAX_BUFFER_SIZE = 500;
21
+ function isEnvelope(value) {
22
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
23
+ && typeof value.origin === 'string'
24
+ && 'data' in value;
25
+ }
26
+ class EventBus {
27
+ publisher = null;
28
+ subscriber = null;
29
+ localEmitter = new EventEmitter();
30
+ connected = false;
31
+ connecting = null;
32
+ patterns = new Set();
33
+ originId = randomUUID();
34
+ // Circuit breaker state
35
+ circuitState = 'closed';
36
+ consecutiveFailures = 0;
37
+ lastFailureAt = 0;
38
+ buffer = [];
39
+ constructor() {
40
+ this.localEmitter.setMaxListeners(100);
41
+ }
42
+ /** Connect to Redis (lazy — called automatically on first publish/subscribe).
43
+ * Concurrent callers share one in-flight attempt. */
44
+ ensureConnected() {
45
+ if (this.connected)
46
+ return Promise.resolve();
47
+ this.connecting ??= this.connect().finally(() => { this.connecting = null; });
48
+ return this.connecting;
49
+ }
50
+ disconnectClients() {
51
+ const publisher = this.publisher;
52
+ const subscriber = this.subscriber;
53
+ this.publisher = null;
54
+ this.subscriber = null;
55
+ subscriber?.removeAllListeners('pmessage');
56
+ subscriber?.disconnect();
57
+ publisher?.disconnect();
58
+ }
59
+ async connect() {
60
+ // Never leak a previous pair (circuit-breaker reopen or failed attempt).
61
+ this.disconnectClients();
62
+ try {
63
+ const publisher = new Redis(REDIS_URL, { maxRetriesPerRequest: 3, lazyConnect: true });
64
+ const subscriber = new Redis(REDIS_URL, { maxRetriesPerRequest: 3, lazyConnect: true });
65
+ this.publisher = publisher;
66
+ this.subscriber = subscriber;
67
+ await Promise.all([
68
+ publisher.connect(),
69
+ subscriber.connect(),
70
+ ]);
71
+ subscriber.on('pmessage', (_pattern, channel, message) => {
72
+ const shortChannel = channel.replace(CHANNEL_PREFIX, '');
73
+ let parsed;
74
+ try {
75
+ parsed = JSON.parse(message);
76
+ }
77
+ catch {
78
+ this.localEmitter.emit(shortChannel, shortChannel, message);
79
+ return;
80
+ }
81
+ let data = parsed;
82
+ if (isEnvelope(parsed)) {
83
+ // Already delivered locally by publish().
84
+ if (parsed.origin === this.originId)
85
+ return;
86
+ data = parsed.data;
87
+ }
88
+ this.localEmitter.emit(shortChannel, shortChannel, data);
89
+ this.localEmitter.emit('*', shortChannel, data);
90
+ });
91
+ // Re-subscribe to patterns
92
+ for (const pattern of this.patterns) {
93
+ await subscriber.psubscribe(`${CHANNEL_PREFIX}${pattern}`);
94
+ }
95
+ this.connected = true;
96
+ }
97
+ catch (err) {
98
+ // Callers fall back to local-only mode; publish() counts the failure.
99
+ this.disconnectClients();
100
+ this.connected = false;
101
+ throw err;
102
+ }
103
+ }
104
+ /** Publish an event to the bus. Uses circuit breaker to avoid slow failures. */
105
+ async publish(channel, data) {
106
+ const fullChannel = `${CHANNEL_PREFIX}${channel}`;
107
+ const payload = JSON.stringify({ origin: this.originId, data });
108
+ // Always emit locally (never lost)
109
+ this.localEmitter.emit(channel, channel, data);
110
+ this.localEmitter.emit('*', channel, data);
111
+ // Circuit breaker check
112
+ if (this.circuitState === 'open') {
113
+ if (Date.now() - this.lastFailureAt > RESET_TIMEOUT_MS) {
114
+ this.circuitState = 'half-open';
115
+ }
116
+ else {
117
+ // Buffer the event for replay when circuit closes
118
+ if (this.buffer.length < MAX_BUFFER_SIZE) {
119
+ this.buffer.push({ channel: fullChannel, payload });
120
+ }
121
+ return;
122
+ }
123
+ }
124
+ try {
125
+ await this.ensureConnected();
126
+ if (this.publisher) {
127
+ await this.publisher.publish(fullChannel, payload);
128
+ }
129
+ this.onSuccess();
130
+ }
131
+ catch {
132
+ this.onFailure(fullChannel, payload);
133
+ }
134
+ }
135
+ /** Record a successful Redis operation — close the circuit. */
136
+ onSuccess() {
137
+ if (this.circuitState !== 'closed') {
138
+ this.circuitState = 'closed';
139
+ this.consecutiveFailures = 0;
140
+ // Replay buffered events (fire-and-forget)
141
+ void this.replayBuffer();
142
+ }
143
+ this.consecutiveFailures = 0;
144
+ }
145
+ /** Record a failed Redis operation — maybe open the circuit. */
146
+ onFailure(channel, payload) {
147
+ this.consecutiveFailures++;
148
+ this.lastFailureAt = Date.now();
149
+ if (this.consecutiveFailures >= FAILURE_THRESHOLD) {
150
+ this.circuitState = 'open';
151
+ this.connected = false;
152
+ console.warn(`[EventBus] Circuit breaker OPEN after ${this.consecutiveFailures} failures`);
153
+ }
154
+ if (this.buffer.length < MAX_BUFFER_SIZE) {
155
+ this.buffer.push({ channel, payload });
156
+ }
157
+ }
158
+ /** Replay buffered events after circuit recovery. */
159
+ async replayBuffer() {
160
+ if (this.buffer.length === 0 || !this.publisher)
161
+ return;
162
+ console.log(`[EventBus] Replaying ${this.buffer.length} buffered events`);
163
+ const events = this.buffer.splice(0);
164
+ for (const evt of events) {
165
+ try {
166
+ await this.publisher.publish(evt.channel, evt.payload);
167
+ }
168
+ catch {
169
+ // If replay fails, re-open circuit
170
+ this.onFailure(evt.channel, evt.payload);
171
+ break;
172
+ }
173
+ }
174
+ }
175
+ /** Subscribe to events matching a pattern (supports * glob). */
176
+ async subscribe(pattern, handler) {
177
+ this.patterns.add(pattern);
178
+ try {
179
+ await this.ensureConnected();
180
+ if (this.subscriber) {
181
+ await this.subscriber.psubscribe(`${CHANNEL_PREFIX}${pattern}`);
182
+ }
183
+ }
184
+ catch {
185
+ // Local-only mode
186
+ }
187
+ // Wrap to match the pattern ourselves for local events
188
+ const wrappedHandler = (ch, data) => {
189
+ handler(ch, data);
190
+ };
191
+ if (pattern === '*') {
192
+ this.localEmitter.on('*', wrappedHandler);
193
+ }
194
+ else {
195
+ this.localEmitter.on(pattern, wrappedHandler);
196
+ }
197
+ return () => {
198
+ this.localEmitter.off(pattern === '*' ? '*' : pattern, wrappedHandler);
199
+ };
200
+ }
201
+ /** Graceful shutdown. */
202
+ async close() {
203
+ await this.connecting?.catch(() => undefined);
204
+ if (this.subscriber && this.connected) {
205
+ await this.subscriber.punsubscribe().catch(() => undefined);
206
+ }
207
+ this.disconnectClients();
208
+ this.localEmitter.removeAllListeners();
209
+ this.connected = false;
210
+ }
211
+ }
212
+ /** Singleton event bus instance for the application. */
213
+ export const eventBus = new EventBus();
214
+ // ── Typed event channels ──
215
+ export const EventChannels = {
216
+ NODE_STATUS: 'node:status',
217
+ NODE_HEARTBEAT: 'node:heartbeat',
218
+ COMMAND_STATUS: 'command:status',
219
+ COMMAND_OUTPUT: 'command:output',
220
+ DEPLOY_STATUS: 'deploy:status',
221
+ ALERT_FIRED: 'alert:fired',
222
+ AUDIT_EVENT: 'audit:event',
223
+ ROLLOUT_PROGRESS: 'rollout:progress',
224
+ DRIFT_RESULT: 'drift:result',
225
+ HERMES_STATUS: 'hermes:status',
226
+ };
227
+ //# sourceMappingURL=event-bus.js.map
@@ -0,0 +1,102 @@
1
+ import { readdir, readFile, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ const DEFAULT_LOG_DIR = '/var/log/magnus/fleet-checks';
4
+ const MAX_LINE_BYTES = 1024 * 1024;
5
+ export function getFleetCheckLogDir() {
6
+ return process.env['MAGNUS_FLEET_CHECK_LOG_DIR']?.trim() || DEFAULT_LOG_DIR;
7
+ }
8
+ function safeParseRun(line) {
9
+ if (!line.trim() || Buffer.byteLength(line) > MAX_LINE_BYTES)
10
+ return null;
11
+ try {
12
+ const value = JSON.parse(line);
13
+ if (!value.runId || !value.kind || !value.startedAt || !value.completedAt)
14
+ return null;
15
+ return {
16
+ runId: String(value.runId),
17
+ kind: String(value.kind),
18
+ status: ['ok', 'warning', 'critical', 'error'].includes(String(value.status))
19
+ ? value.status
20
+ : 'error',
21
+ startedAt: String(value.startedAt),
22
+ completedAt: String(value.completedAt),
23
+ durationMs: Number(value.durationMs ?? 0),
24
+ summary: String(value.summary ?? ''),
25
+ counts: typeof value.counts === 'object' && value.counts ? value.counts : undefined,
26
+ data: typeof value.data === 'object' && value.data ? value.data : undefined,
27
+ errors: Array.isArray(value.errors) ? value.errors.map(String) : undefined,
28
+ };
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ async function listLogFiles() {
35
+ const dir = getFleetCheckLogDir();
36
+ let entries;
37
+ try {
38
+ entries = await readdir(dir);
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ const files = await Promise.all(entries
44
+ .filter((entry) => entry.endsWith('.jsonl'))
45
+ .map(async (entry) => {
46
+ const fullPath = path.join(dir, entry);
47
+ try {
48
+ const info = await stat(fullPath);
49
+ if (!info.isFile())
50
+ return null;
51
+ return {
52
+ file: entry,
53
+ sizeBytes: info.size,
54
+ modifiedAt: info.mtime.toISOString(),
55
+ };
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ }));
61
+ return files
62
+ .filter((file) => Boolean(file))
63
+ .sort((a, b) => b.file.localeCompare(a.file));
64
+ }
65
+ export async function listFleetCheckLogFiles() {
66
+ return {
67
+ directory: getFleetCheckLogDir(),
68
+ files: await listLogFiles(),
69
+ };
70
+ }
71
+ export async function listFleetCheckRuns(options = {}) {
72
+ const limit = Math.min(Math.max(options.limit ?? 20, 1), 200);
73
+ const files = await listLogFiles();
74
+ const runs = [];
75
+ const dir = getFleetCheckLogDir();
76
+ for (const file of files) {
77
+ if (runs.length >= limit)
78
+ break;
79
+ const fullPath = path.join(dir, file.file);
80
+ let content = '';
81
+ try {
82
+ content = await readFile(fullPath, 'utf8');
83
+ }
84
+ catch {
85
+ continue;
86
+ }
87
+ const parsed = content
88
+ .split('\n')
89
+ .reverse()
90
+ .map(safeParseRun)
91
+ .filter((run) => Boolean(run))
92
+ .filter((run) => !options.kind || run.kind === options.kind);
93
+ runs.push(...parsed.slice(0, limit - runs.length));
94
+ }
95
+ runs.sort((a, b) => b.completedAt.localeCompare(a.completedAt));
96
+ return { directory: dir, runs: runs.slice(0, limit) };
97
+ }
98
+ export async function getLatestFleetCheckRun(kind) {
99
+ const { directory, runs } = await listFleetCheckRuns({ limit: 1, kind });
100
+ return { directory, run: runs[0] ?? null };
101
+ }
102
+ //# sourceMappingURL=fleet-check-log.js.map
@@ -0,0 +1,154 @@
1
+ import { getDb } from '../db/index.js';
2
+ function linearRegression(points) {
3
+ const n = points.length;
4
+ if (n < 2)
5
+ return { slope: 0, intercept: 0, r2: 0 };
6
+ const sumX = points.reduce((a, p) => a + p.x, 0);
7
+ const sumY = points.reduce((a, p) => a + p.y, 0);
8
+ const sumXY = points.reduce((a, p) => a + p.x * p.y, 0);
9
+ const sumX2 = points.reduce((a, p) => a + p.x ** 2, 0);
10
+ const denom = n * sumX2 - sumX ** 2;
11
+ if (denom === 0)
12
+ return { slope: 0, intercept: sumY / n, r2: 0 };
13
+ const slope = (n * sumXY - sumX * sumY) / denom;
14
+ const intercept = (sumY - slope * sumX) / n;
15
+ // R² for confidence
16
+ const yMean = sumY / n;
17
+ const ssTot = points.reduce((a, p) => a + (p.y - yMean) ** 2, 0);
18
+ if (ssTot === 0)
19
+ return { slope, intercept, r2: 1 };
20
+ const ssRes = points.reduce((a, p) => a + (p.y - (slope * p.x + intercept)) ** 2, 0);
21
+ const r2 = 1 - ssRes / ssTot;
22
+ return { slope, intercept, r2 };
23
+ }
24
+ // ─── Forecast for a single node ───
25
+ const MS_PER_DAY = 86_400_000;
26
+ const MIN_DATA_POINTS = 3;
27
+ const MIN_FORECAST_CONFIDENCE = 0.25;
28
+ const DEFAULT_LOOKBACK_DAYS = 30;
29
+ const SYSTEM_MOUNT_PREFIXES = ['/boot', '/snap', '/var/lib/docker/', '/var/lib/containers/'];
30
+ const READ_ONLY_FILESYSTEMS = new Set(['iso9660', 'squashfs']);
31
+ function isForecastableVolume(disk) {
32
+ const workloadPath = disk.mountPoint === '/'
33
+ || disk.mountPoint === '/home'
34
+ || disk.mountPoint.startsWith('/home/')
35
+ || disk.mountPoint.startsWith('/mnt/')
36
+ || disk.mountPoint.startsWith('/srv/');
37
+ return workloadPath
38
+ && !SYSTEM_MOUNT_PREFIXES.some((prefix) => disk.mountPoint === prefix || disk.mountPoint.startsWith(prefix))
39
+ && !READ_ONLY_FILESYSTEMS.has((disk.filesystemType ?? '').toLowerCase());
40
+ }
41
+ export function capacityRecommendation(mountPoint) {
42
+ if (/\b(models?|checkpoints?|weights?|ollama|huggingface)\b/i.test(mountPoint)) {
43
+ return {
44
+ workloadClass: 'models',
45
+ recommendation: 'Move inactive model checkpoints to colder storage, remove superseded weights, or expand this model volume before the forecast horizon.',
46
+ };
47
+ }
48
+ if (/\b(cache|download|tmp|artifact)\b/i.test(mountPoint)) {
49
+ return {
50
+ workloadClass: 'downloads-cache',
51
+ recommendation: 'Expire completed downloads and cache entries, cap cache size, or redirect new artifacts to a larger persistent volume.',
52
+ };
53
+ }
54
+ return {
55
+ workloadClass: 'general',
56
+ recommendation: 'Review the largest growing directories, enforce retention, and plan volume expansion before the forecast horizon.',
57
+ };
58
+ }
59
+ export async function forecastDisk(nodeId, lookbackDays = DEFAULT_LOOKBACK_DAYS) {
60
+ const db = getDb();
61
+ const since = new Date(Date.now() - lookbackDays * MS_PER_DAY);
62
+ const snapshots = await db.healthSnapshot.findMany({
63
+ where: { nodeId, timestamp: { gte: since } },
64
+ orderBy: { timestamp: 'asc' },
65
+ select: { timestamp: true, disks: true },
66
+ });
67
+ if (snapshots.length < MIN_DATA_POINTS)
68
+ return [];
69
+ // Collect per-mount time series: mountPoint → { timestamp, usedBytes, totalBytes }[]
70
+ const mountSeries = new Map();
71
+ for (const snap of snapshots) {
72
+ let disks;
73
+ try {
74
+ disks = JSON.parse(snap.disks);
75
+ }
76
+ catch {
77
+ continue;
78
+ }
79
+ const ts = snap.timestamp.getTime();
80
+ for (const d of disks) {
81
+ if (!d || typeof d.mountPoint !== 'string' || !Number.isFinite(d.usedBytes) || !Number.isFinite(d.totalBytes) || !isForecastableVolume(d))
82
+ continue;
83
+ if (!mountSeries.has(d.mountPoint)) {
84
+ mountSeries.set(d.mountPoint, []);
85
+ }
86
+ mountSeries.get(d.mountPoint).push({
87
+ timestamp: ts,
88
+ usedBytes: d.usedBytes,
89
+ totalBytes: d.totalBytes,
90
+ });
91
+ }
92
+ }
93
+ const forecasts = [];
94
+ for (const [mountPoint, series] of mountSeries) {
95
+ if (series.length < MIN_DATA_POINTS)
96
+ continue;
97
+ const latest = series[series.length - 1];
98
+ const totalBytes = latest.totalBytes;
99
+ const currentUsagePercent = totalBytes > 0 ? (latest.usedBytes / totalBytes) * 100 : 0;
100
+ // Build regression points: x = days since first sample, y = usedBytes
101
+ const t0 = series[0].timestamp;
102
+ const points = series.map((s) => ({
103
+ x: (s.timestamp - t0) / MS_PER_DAY,
104
+ y: s.usedBytes,
105
+ }));
106
+ const reg = linearRegression(points);
107
+ const growthRatePerDay = reg.slope; // bytes per day
108
+ let estimatedFullDate = null;
109
+ let daysUntilFull = null;
110
+ if (growthRatePerDay > 0 && reg.r2 >= MIN_FORECAST_CONFIDENCE) {
111
+ const availableBytes = totalBytes - latest.usedBytes;
112
+ daysUntilFull = Math.ceil(availableBytes / growthRatePerDay);
113
+ const fullDate = new Date(Date.now() + daysUntilFull * MS_PER_DAY);
114
+ estimatedFullDate = fullDate.toISOString().split('T')[0] ?? null;
115
+ }
116
+ forecasts.push({
117
+ mountPoint,
118
+ currentUsagePercent: Math.round(currentUsagePercent * 100) / 100,
119
+ growthRatePerDay: Math.round(growthRatePerDay),
120
+ estimatedFullDate,
121
+ daysUntilFull,
122
+ confidence: Math.round(Math.max(0, reg.r2) * 100) / 100,
123
+ ...capacityRecommendation(mountPoint),
124
+ });
125
+ }
126
+ return forecasts;
127
+ }
128
+ // ─── Fleet-wide at-risk nodes ───
129
+ export async function forecastAtRisk(daysThreshold = 30) {
130
+ const db = getDb();
131
+ const nodes = await db.node.findMany({
132
+ select: { id: true, hostname: true },
133
+ });
134
+ const results = [];
135
+ for (const node of nodes) {
136
+ const forecasts = await forecastDisk(node.id);
137
+ const atRisk = forecasts.filter((f) => f.daysUntilFull !== null && f.daysUntilFull <= daysThreshold);
138
+ if (atRisk.length > 0) {
139
+ results.push({
140
+ nodeId: node.id,
141
+ hostname: node.hostname,
142
+ forecasts: atRisk,
143
+ });
144
+ }
145
+ }
146
+ // Sort by most urgent first
147
+ results.sort((a, b) => {
148
+ const aMin = Math.min(...a.forecasts.map((f) => f.daysUntilFull ?? Infinity));
149
+ const bMin = Math.min(...b.forecasts.map((f) => f.daysUntilFull ?? Infinity));
150
+ return aMin - bMin;
151
+ });
152
+ return results;
153
+ }
154
+ //# sourceMappingURL=forecast-service.js.map