@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,130 @@
1
+ import { Hono } from 'hono';
2
+ import { z } from 'zod';
3
+ import { authMiddleware, getUser } from '../middleware/auth.js';
4
+ import { logAuditEvent } from '../services/audit-service.js';
5
+ import { listNotifications, getUnreadCount, markRead, markAllRead, } from '../services/notification-service.js';
6
+ import { parseBody } from '../utils/validate.js';
7
+ import { notificationReadSchema } from '../schemas/logs.js';
8
+ import { getDb } from '../db/client.js';
9
+ export const notificationsRouter = new Hono();
10
+ // All routes require authentication
11
+ notificationsRouter.use('*', authMiddleware);
12
+ /**
13
+ * GET /notifications
14
+ * List notifications (paginated, filterable).
15
+ */
16
+ notificationsRouter.get('/', async (c) => {
17
+ const params = {
18
+ page: Number(c.req.query('page') ?? 1),
19
+ pageSize: Number(c.req.query('pageSize') ?? 50),
20
+ isRead: c.req.query('isRead') !== undefined ? c.req.query('isRead') === 'true' : undefined,
21
+ severity: c.req.query('severity') ?? undefined,
22
+ type: c.req.query('type') ?? undefined,
23
+ nodeId: c.req.query('nodeId') ?? undefined,
24
+ };
25
+ const result = await listNotifications(params);
26
+ return c.json({ success: true, data: result });
27
+ });
28
+ /**
29
+ * GET /notifications/unread-count
30
+ * Return number of unread notifications.
31
+ */
32
+ notificationsRouter.get('/unread-count', async (c) => {
33
+ const count = await getUnreadCount();
34
+ return c.json({ success: true, data: { count } });
35
+ });
36
+ /**
37
+ * POST /notifications/read
38
+ * Mark specific notifications as read.
39
+ * Body: { ids: string[] }
40
+ */
41
+ notificationsRouter.post('/read', async (c) => {
42
+ const user = getUser(c);
43
+ const body = await parseBody(c, notificationReadSchema);
44
+ const count = await markRead(body.ids);
45
+ await logAuditEvent({
46
+ action: 'notification.read',
47
+ actorId: user.userId,
48
+ targetType: 'notification',
49
+ targetId: body.ids.join(','),
50
+ details: { count },
51
+ });
52
+ return c.json({ success: true, data: { marked: count } });
53
+ });
54
+ /**
55
+ * POST /notifications/read-all
56
+ * Mark all notifications as read.
57
+ */
58
+ notificationsRouter.post('/read-all', async (c) => {
59
+ const user = getUser(c);
60
+ const count = await markAllRead();
61
+ await logAuditEvent({
62
+ action: 'notification.read_all',
63
+ actorId: user.userId,
64
+ targetType: 'notification',
65
+ targetId: '*',
66
+ details: { count },
67
+ });
68
+ return c.json({ success: true, data: { marked: count } });
69
+ });
70
+ // ── Notification Preferences ──
71
+ const prefSchema = z.object({
72
+ channel: z.enum(['in_app', 'email', 'webhook']).default('in_app'),
73
+ category: z.string().min(1),
74
+ enabled: z.boolean(),
75
+ minSeverity: z.enum(['info', 'warning', 'critical']).default('info'),
76
+ });
77
+ const bulkPrefSchema = z.object({
78
+ preferences: z.array(prefSchema).min(1).max(100),
79
+ });
80
+ /**
81
+ * GET /notifications/preferences
82
+ * Get the current user's notification preferences.
83
+ */
84
+ notificationsRouter.get('/preferences', async (c) => {
85
+ const user = getUser(c);
86
+ const db = getDb();
87
+ const prefs = await db.notificationPreference.findMany({
88
+ where: { userId: user.userId },
89
+ orderBy: { category: 'asc' },
90
+ });
91
+ return c.json({ success: true, data: prefs });
92
+ });
93
+ /**
94
+ * PUT /notifications/preferences
95
+ * Bulk upsert notification preferences.
96
+ */
97
+ notificationsRouter.put('/preferences', async (c) => {
98
+ const user = getUser(c);
99
+ const body = await parseBody(c, bulkPrefSchema);
100
+ const db = getDb();
101
+ const results = await db.$transaction(body.preferences.map((pref) => db.notificationPreference.upsert({
102
+ where: {
103
+ userId_channel_category: {
104
+ userId: user.userId,
105
+ channel: pref.channel,
106
+ category: pref.category,
107
+ },
108
+ },
109
+ update: {
110
+ enabled: pref.enabled,
111
+ minSeverity: pref.minSeverity,
112
+ },
113
+ create: {
114
+ userId: user.userId,
115
+ channel: pref.channel,
116
+ category: pref.category,
117
+ enabled: pref.enabled,
118
+ minSeverity: pref.minSeverity,
119
+ },
120
+ })));
121
+ await logAuditEvent({
122
+ action: 'notification.preferences_update',
123
+ actorId: user.userId,
124
+ targetType: 'notification_preference',
125
+ targetId: user.userId,
126
+ details: { count: results.length },
127
+ });
128
+ return c.json({ success: true, data: results });
129
+ });
130
+ //# sourceMappingURL=notifications.js.map
@@ -0,0 +1,258 @@
1
+ import { applicationProbeContractDigest, getApplicationProbeCollectorStatus } from '../services/application-probes.js';
2
+ import { lessonSchema, publishLesson, lessonSuggestions, supersedeLesson } from '../services/incident-lessons.js';
3
+ import { exportIncidentEvidence } from '../services/incident-evidence.js';
4
+ import { getNodeManagerSecret } from '../utils/env.js';
5
+ import { Hono } from 'hono';
6
+ import { authMiddleware, getUser, requireRole } from '../middleware/auth.js';
7
+ import { HttpError } from '../middleware/error-handler.js';
8
+ import { getDependencyHealth, getFleetReadiness, getFleetTimeline, getPredictiveMaintenance, getIncidentSummary, classifyRemediationPlan, getHermesEffectiveState, getPackageSecurityPosture, getRetentionSummary, getTraceDependencyMap, } from '../services/ops-service.js';
9
+ import { getOperationalObservations, getCapacityAdvice } from '../services/operational-observations.js';
10
+ import { getDb } from '../db/index.js';
11
+ import { getApplicationConfigs } from '../services/operations-config.js';
12
+ import { maintenanceSchema } from '../services/maintenance-service.js';
13
+ import { parseBody } from '../utils/validate.js';
14
+ import { logAuditEvent } from '../services/audit-service.js';
15
+ import { getCodexFleetPosture } from '../services/codex-service.js';
16
+ import { describeRemediationPlan } from '../services/team-approvals.js';
17
+ import { assessDelivery, assessDependencyFailure, assessForecast, assessRestore, assessRunbook, deliveryAssessmentSchema, dependencyFailureSchema, forecastAssessmentSchema, loadInventoryBoundOperationsCatalog, restoreAssessmentSchema, runbookAssessmentSchema, } from '../services/engineering-assurance.js';
18
+ import { loadEngineeringEvidenceLedger } from '../services/engineering-evidence-ledger.js';
19
+ import { loadRecoveryExerciseAssessmentEvidence } from '../services/recovery-exercises.js';
20
+ export const opsRouter = new Hono();
21
+ opsRouter.use('*', authMiddleware);
22
+ opsRouter.get('/dependency-health', async (c) => c.json({ success: true, data: await getDependencyHealth() }));
23
+ opsRouter.get('/readiness', async (c) => c.json({ success: true, data: await getFleetReadiness() }));
24
+ opsRouter.get('/timeline', async (c) => {
25
+ const limit = Math.min(Number(c.req.query('limit') ?? '80'), 200);
26
+ return c.json({ success: true, data: await getFleetTimeline(limit) });
27
+ });
28
+ opsRouter.get('/retention', async (c) => c.json({ success: true, data: await getRetentionSummary() }));
29
+ opsRouter.get('/trace-map', async (c) => c.json({ success: true, data: await getTraceDependencyMap() }));
30
+ opsRouter.get('/predictive-maintenance', async (c) => c.json({ success: true, data: await getPredictiveMaintenance() }));
31
+ opsRouter.get('/incident-summary', async (c) => {
32
+ const nodeId = c.req.query('nodeId') ?? undefined;
33
+ const hours = Math.min(Number(c.req.query('hours') ?? '24'), 168);
34
+ return c.json({ success: true, data: await getIncidentSummary(nodeId, hours) });
35
+ });
36
+ opsRouter.post('/remediation-plan/classify', async (c) => {
37
+ const body = await c.req.json();
38
+ return c.json({ success: true, data: classifyRemediationPlan(body.description ?? '') });
39
+ });
40
+ opsRouter.get('/hermes-effective-state', async (c) => c.json({ success: true, data: await getHermesEffectiveState() }));
41
+ opsRouter.get('/package-security-posture', async (c) => c.json({ success: true, data: await getPackageSecurityPosture() }));
42
+ opsRouter.get('/codex-fleet-status', (c) => c.json({ success: true, data: getCodexFleetPosture() }));
43
+ opsRouter.get('/observations', async (c) => c.json({ success: true, data: await getOperationalObservations() }));
44
+ opsRouter.get('/capacity-advice', async (c) => c.json({ success: true, data: await getCapacityAdvice() }));
45
+ opsRouter.get('/engineering/catalog', requireRole('ADMIN', 'OPERATOR'), async (c) => {
46
+ const catalog = await loadInventoryBoundOperationsCatalog();
47
+ return c.json({ success: true, data: catalog });
48
+ });
49
+ opsRouter.post('/engineering/dependency-impact', requireRole('ADMIN', 'OPERATOR'), async (c) => {
50
+ const body = await parseBody(c, dependencyFailureSchema);
51
+ const catalog = await loadInventoryBoundOperationsCatalog();
52
+ if (!catalog.applications.some(application => application.id === body.failedApplicationId))
53
+ throw new HttpError(409, 'OPERATIONS_CATALOG_TARGET_MISSING', 'Failed application is absent from the authoritative catalog');
54
+ const observations = await getDb().applicationObservation.findMany({
55
+ where: { id: { in: catalog.applications.map(application => application.id) } },
56
+ select: { id: true, projectId: true, serviceId: true, nodeId: true, status: true, resultJson: true, observedAt: true },
57
+ take: 200,
58
+ orderBy: { id: 'asc' },
59
+ });
60
+ const probeContracts = getApplicationConfigs().map(config => ({ id: config.id, projectId: config.projectId,
61
+ serviceId: config.serviceId, nodeId: config.nodeId, healthPath: config.healthPath,
62
+ probeContractSha256: applicationProbeContractDigest(config) }));
63
+ return c.json({ success: true, data: assessDependencyFailure(catalog, body, observations, probeContracts) });
64
+ });
65
+ opsRouter.post('/engineering/runbook-assessment', requireRole('ADMIN', 'OPERATOR'), async (c) => {
66
+ const body = await parseBody(c, runbookAssessmentSchema);
67
+ const catalog = await loadInventoryBoundOperationsCatalog();
68
+ const target = catalog.applications.find(application => application.id === body.applicationId);
69
+ if (!target)
70
+ throw new HttpError(409, 'OPERATIONS_CATALOG_TARGET_MISSING', 'Runbook target is absent from the authoritative catalog');
71
+ const approval = body.approvalExecutionId ? await getDb().teamApprovalDecision.findUnique({
72
+ where: { executionId: body.approvalExecutionId },
73
+ select: { decisionId: true, executionId: true, planSha256: true, decision: true, decidedAt: true, expiresAt: true },
74
+ }) : null;
75
+ const lease = await getDb().commandResourceLease.findUnique({
76
+ where: { id: body.leaseId },
77
+ select: { id: true, nodeId: true, commandId: true, state: true, deadline: true, acquiredAt: true,
78
+ dispatchedAt: true, settledAt: true, evidenceSha256: true },
79
+ });
80
+ const command = lease ? await getDb().remoteCommand.findUnique({ where: { id: lease.commandId },
81
+ select: { id: true, nodeId: true, correlationId: true, command: true, args: true, timeoutSeconds: true } }) : null;
82
+ let executionBinding = null;
83
+ if (command?.correlationId?.startsWith('remediation_')) {
84
+ const remediation = await getDb().remediationExecution.findUnique({ where: { id: command.correlationId.slice('remediation_'.length) } });
85
+ if (remediation) {
86
+ try {
87
+ const plan = JSON.parse(remediation.input);
88
+ const output = JSON.parse(remediation.output ?? '{}');
89
+ const view = describeRemediationPlan(remediation);
90
+ const args = JSON.parse(command.args);
91
+ if (typeof plan.runbookVersion === 'string' && typeof plan.command === 'string'
92
+ && Array.isArray(plan.args) && plan.args.every((arg) => typeof arg === 'string')
93
+ && Number.isInteger(plan.timeoutSeconds) && Array.isArray(args) && args.every((arg) => typeof arg === 'string')
94
+ && remediation.nodeId === command.nodeId && (plan.nodeId === undefined || plan.nodeId === command.nodeId)
95
+ && plan.command === command.command && JSON.stringify(plan.args) === JSON.stringify(args)
96
+ && plan.timeoutSeconds === command.timeoutSeconds)
97
+ executionBinding = {
98
+ commandId: command.id, nodeId: command.nodeId,
99
+ applicationId: typeof plan.applicationId === 'string' ? plan.applicationId : null,
100
+ runbookVersion: plan.runbookVersion,
101
+ command: command.command, args, timeoutSeconds: command.timeoutSeconds,
102
+ telegramExecutionId: typeof output.telegramExecutionId === 'string' ? output.telegramExecutionId : null,
103
+ decisionId: typeof output.telegramDecisionId === 'string' ? output.telegramDecisionId : null,
104
+ approvalPlanSha256: view.plan_sha256,
105
+ catalogPlanSha256: typeof plan.catalogPlanSha256 === 'string' ? plan.catalogPlanSha256 : null,
106
+ };
107
+ }
108
+ catch { /* malformed stored rows fail the assessment closed */ }
109
+ }
110
+ }
111
+ const observation = await getDb().applicationObservation.findUnique({ where: { id: target.id },
112
+ select: { id: true, projectId: true, serviceId: true, nodeId: true, status: true, resultJson: true, observedAt: true } });
113
+ const probe = getApplicationConfigs().find(config => config.id === target.id);
114
+ const probeContract = probe ? { id: probe.id, projectId: probe.projectId, serviceId: probe.serviceId,
115
+ nodeId: probe.nodeId, healthPath: probe.healthPath, probeContractSha256: applicationProbeContractDigest(probe) } : undefined;
116
+ return c.json({ success: true, data: assessRunbook(catalog, body, approval, lease, executionBinding, observation ?? undefined, probeContract) });
117
+ });
118
+ opsRouter.post('/engineering/delivery-assessment', requireRole('ADMIN', 'OPERATOR'), async (c) => {
119
+ const body = await parseBody(c, deliveryAssessmentSchema);
120
+ const catalog = await loadInventoryBoundOperationsCatalog();
121
+ const ledger = loadEngineeringEvidenceLedger();
122
+ const record = ledger.records.filter(candidate => candidate.kind === 'delivery').find(candidate => candidate.requestId === body.requestId);
123
+ if (!record)
124
+ return c.json({ success: true, data: assessDelivery(catalog, body, undefined, null, undefined, undefined, ledger.ledgerSha256) });
125
+ const canary = await getDb().magnusReleaseCanary.findFirst({ where: { acceptedCommit: record.source.workingRevision,
126
+ sourceTreeSha256: record.source.sourceTreeSha256 }, select: { acceptedCommit: true, sourceTreeSha256: true, createdAt: true },
127
+ orderBy: { createdAt: 'desc' } });
128
+ const observation = await getDb().applicationObservation.findUnique({ where: { id: record.applicationId },
129
+ select: { id: true, projectId: true, serviceId: true, nodeId: true, status: true, resultJson: true, observedAt: true } });
130
+ const probe = getApplicationConfigs().find(config => config.id === record.applicationId);
131
+ const contract = probe ? { id: probe.id, projectId: probe.projectId, serviceId: probe.serviceId,
132
+ nodeId: probe.nodeId, healthPath: probe.healthPath, probeContractSha256: applicationProbeContractDigest(probe) } : undefined;
133
+ return c.json({ success: true, data: assessDelivery(catalog, body, record, canary, observation ?? undefined, contract, ledger.ledgerSha256) });
134
+ });
135
+ opsRouter.post('/engineering/forecast-assessment', requireRole('ADMIN', 'OPERATOR'), async (c) => {
136
+ const body = await parseBody(c, forecastAssessmentSchema);
137
+ const catalog = await loadInventoryBoundOperationsCatalog();
138
+ const application = catalog.applications.find(candidate => candidate.id === body.applicationId);
139
+ if (!application)
140
+ throw new HttpError(409, 'OPERATIONS_CATALOG_TARGET_MISSING', 'Forecast target is absent from the authoritative catalog');
141
+ const now = Date.now();
142
+ const source = application.metricSources.find(candidate => candidate.metric === body.metric);
143
+ const needsHealthSnapshots = body.metric === 'disk' || body.metric === 'memory'
144
+ || source?.collector === 'health_service_expiry' || source?.collector === 'cron_success';
145
+ const snapshots = needsHealthSnapshots ? await getDb().healthSnapshot.findMany({
146
+ where: { nodeId: application.nodeId, timestamp: { gte: new Date(now - body.maxWindowMs) } },
147
+ select: { id: true, nodeId: true, timestamp: true, memoryPercent: true, disks: true, services: true, source: true },
148
+ take: 10_001,
149
+ orderBy: [{ timestamp: 'desc' }, { id: 'desc' }],
150
+ }) : [];
151
+ const metricSamples = source?.collector === 'application_probe' ? await getDb().engineeringMetricSample.findMany({
152
+ where: { applicationId: application.id, nodeId: application.nodeId, metric: body.metric, sourceKey: source.sourceKey,
153
+ observedAt: { gte: new Date(now - body.maxWindowMs) } },
154
+ select: { id: true, applicationId: true, nodeId: true, metric: true, sourceKey: true, unit: true,
155
+ value: true, observedAt: true, probeContractSha256: true, method: true, path: true,
156
+ httpStatus: true, evidenceSha256: true }, take: 10_001, orderBy: [{ observedAt: 'desc' }, { id: 'desc' }],
157
+ }) : [];
158
+ const windowStart = new Date(now - body.maxWindowMs);
159
+ const cronExecutionsInWindow = source?.collector === 'cron_success' ? await getDb().cronJobExecution.findMany({
160
+ where: { cronJobId: source.sourceKey, nodeId: application.nodeId,
161
+ completedAt: { gte: windowStart, lte: new Date(now) }, exitCode: 0 },
162
+ select: { id: true, cronJobId: true, nodeId: true, startedAt: true, completedAt: true, exitCode: true },
163
+ take: 10_001, orderBy: [{ completedAt: 'desc' }, { id: 'desc' }],
164
+ }) : [];
165
+ const cronPredecessor = source?.collector === 'cron_success' ? await getDb().cronJobExecution.findFirst({
166
+ where: { cronJobId: source.sourceKey, nodeId: application.nodeId, completedAt: { lt: windowStart }, exitCode: 0 },
167
+ select: { id: true, cronJobId: true, nodeId: true, startedAt: true, completedAt: true, exitCode: true },
168
+ orderBy: [{ completedAt: 'desc' }, { id: 'desc' }],
169
+ }) : null;
170
+ const cronExecutions = [...cronExecutionsInWindow.slice(0, 10_000), ...(cronPredecessor ? [cronPredecessor] : [])];
171
+ const probe = source?.collector === 'application_probe' ? getApplicationConfigs().find(config => config.id === application.id) : undefined;
172
+ const probeContract = probe ? { id: probe.id, projectId: probe.projectId, serviceId: probe.serviceId,
173
+ nodeId: probe.nodeId, healthPath: probe.healthPath, probeContractSha256: applicationProbeContractDigest(probe),
174
+ checks: [
175
+ { sourceKey: 'reachability', method: 'GET', path: probe.healthPath },
176
+ ...(probe.readinessPath ? [{ sourceKey: 'readiness', method: 'GET', path: probe.readinessPath }] : []),
177
+ ...(probe.queuePath ? [{ sourceKey: 'worker-queue', method: 'GET', path: probe.queuePath }] : []),
178
+ ] } : undefined;
179
+ const evidenceWindowComplete = snapshots.length <= 10_000 && metricSamples.length <= 10_000 && cronExecutionsInWindow.length <= 10_000;
180
+ return c.json({ success: true, data: assessForecast(catalog, body, { healthSnapshots: snapshots.slice(0, 10_000),
181
+ metricSamples: metricSamples.slice(0, 10_000), cronExecutions, probeContract }, evidenceWindowComplete, now) });
182
+ });
183
+ opsRouter.post('/engineering/restore-assessment', requireRole('ADMIN', 'OPERATOR'), async (c) => {
184
+ const body = await parseBody(c, restoreAssessmentSchema);
185
+ const evidence = await loadRecoveryExerciseAssessmentEvidence(body.exerciseId);
186
+ return c.json({ success: true, data: assessRestore(body, evidence.record, evidence.productionIdentityFound, Date.now(), evidence.inventorySnapshotSha256) });
187
+ });
188
+ opsRouter.get('/applications', async (c) => {
189
+ const configs = getApplicationConfigs();
190
+ const rows = await getDb().applicationObservation.findMany({ where: { id: { in: configs.map(config => config.id) } }, take: 100, orderBy: { id: 'asc' } });
191
+ return c.json({ success: true, meta: { collector: getApplicationProbeCollectorStatus() }, data: configs.map(config => {
192
+ const row = rows.find(r => r.id === config.id);
193
+ return { id: config.id, projectId: config.projectId, serviceId: config.serviceId, nodeId: config.nodeId, kind: config.kind,
194
+ status: row?.observedAt && Date.now() - row.observedAt.getTime() < 180000 ? row.status : 'unknown',
195
+ observedAt: row?.observedAt?.toISOString() ?? null, result: JSON.parse(row?.resultJson ?? '{}') };
196
+ }) });
197
+ });
198
+ opsRouter.get('/maintenance', async (c) => c.json({ success: true, data: await getDb().maintenanceWindow.findMany({ take: 100, orderBy: { createdAt: 'desc' } }) }));
199
+ opsRouter.post('/maintenance', requireRole('ADMIN', 'OPERATOR'), async (c) => {
200
+ const body = await parseBody(c, maintenanceSchema);
201
+ const actorId = getUser(c).userId;
202
+ const window = await getDb().maintenanceWindow.create({ data: { ...body, nodeIds: JSON.stringify(body.nodeIds), serviceIds: JSON.stringify(body.serviceIds),
203
+ startsAt: new Date(body.startsAt), endsAt: new Date(body.endsAt), actorId } });
204
+ await logAuditEvent({ action: 'maintenance.create', actorId, targetType: 'maintenance', targetId: window.id,
205
+ details: { nodeIds: body.nodeIds, serviceIds: body.serviceIds, startsAt: body.startsAt, endsAt: body.endsAt } });
206
+ return c.json({ success: true, data: window }, 201);
207
+ });
208
+ opsRouter.post('/maintenance/:id/cancel', requireRole('ADMIN', 'OPERATOR'), async (c) => {
209
+ const window = await getDb().maintenanceWindow.update({ where: { id: c.req.param('id') }, data: { cancelledAt: new Date() } });
210
+ await logAuditEvent({ action: 'maintenance.cancel', actorId: getUser(c).userId, targetType: 'maintenance', targetId: window.id, details: {} });
211
+ return c.json({ success: true, data: window });
212
+ });
213
+ opsRouter.get('/incidents/:id/evidence', requireRole('ADMIN', 'OPERATOR'), async (c) => c.json({ success: true, data: await exportIncidentEvidence(c.req.param('id')) }));
214
+ opsRouter.get('/storage-evidence/:nodeId', requireRole('ADMIN', 'OPERATOR'), async (c) => {
215
+ const node = await getDb().node.findUnique({ where: { id: c.req.param('nodeId') }, select: { ipAddress: true, port: true } });
216
+ const mount = c.req.query('mount');
217
+ if (!node || !mount || mount.length > 4096)
218
+ return c.json({ success: false, error: { message: 'Valid node and mount required' } }, 400);
219
+ const host = node.ipAddress.includes(':') ? `[${node.ipAddress}]` : node.ipAddress;
220
+ const response = await fetch(`https://${host}:${node.port}/api/v1/storage-evidence?${new URLSearchParams({ mount })}`, { headers: { 'x-node-token': getNodeManagerSecret() }, signal: AbortSignal.timeout(15000), redirect: 'error' });
221
+ const { boundedJson } = await import('../services/application-probes.js');
222
+ const body = await boundedJson(response);
223
+ await logAuditEvent({ action: 'storage.investigate', actorId: getUser(c).userId, targetType: 'node', targetId: c.req.param('nodeId'), details: { operation: 'storage-evidence', readOnly: true, success: response.ok } });
224
+ return c.json(body, response.ok ? 200 : 502);
225
+ });
226
+ opsRouter.get('/lessons', requireRole('ADMIN', 'OPERATOR'), async (c) => c.json({ success: true, data: await lessonSuggestions((c.req.query('query') ?? '').slice(0, 500)) }));
227
+ opsRouter.post('/lessons', requireRole('ADMIN', 'OPERATOR'), async (c) => {
228
+ const body = await parseBody(c, lessonSchema);
229
+ const actorId = getUser(c).userId;
230
+ const data = await publishLesson(body, actorId);
231
+ await logAuditEvent({ action: 'incident.lesson.publish', actorId, targetType: 'incident', targetId: body.incidentId, details: { lessonId: data.id, publication: data.publication } });
232
+ return c.json({ success: true, data }, 201);
233
+ });
234
+ opsRouter.post('/lessons/:id/supersede', requireRole('ADMIN', 'OPERATOR'), async (c) => {
235
+ const data = await supersedeLesson(c.req.param('id'));
236
+ await logAuditEvent({ action: 'incident.lesson.supersede', actorId: getUser(c).userId, targetType: 'lesson', targetId: data.id, details: { publication: data.publication } });
237
+ return c.json({ success: true, data });
238
+ });
239
+ opsRouter.post('/applications/:id/canary', requireRole('ADMIN', 'OPERATOR'), async (c) => {
240
+ const config = getApplicationConfigs().find(a => a.id === c.req.param('id') && a.kind === 'hive-router');
241
+ const token = config?.tokenEnv ? process.env[config.tokenEnv] : undefined;
242
+ if (!config?.canaryModel || !token)
243
+ return c.json({ success: false, error: { message: 'A scoped Hive Router credential and canary model must be configured' } }, 409);
244
+ const { boundedJson } = await import('../services/application-probes.js');
245
+ const started = Date.now();
246
+ let data;
247
+ try {
248
+ const response = await fetch(new URL('/v1/chat/completions', config.baseUrl), { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: config.canaryModel, messages: [{ role: 'user', content: 'Reply OK.' }], max_tokens: 1, stream: false }), signal: AbortSignal.timeout(8000), redirect: 'error' });
249
+ const body = await boundedJson(response);
250
+ data = { status: response.ok && Array.isArray(body.choices) && body.choices.length ? 'pass' : 'fail', durationMs: Date.now() - started, totalTokens: typeof body.usage?.total_tokens === 'number' ? body.usage.total_tokens : null };
251
+ }
252
+ catch {
253
+ data = { status: 'fail', durationMs: Date.now() - started, totalTokens: null };
254
+ }
255
+ await logAuditEvent({ action: 'application.canary', actorId: getUser(c).userId, targetType: 'application', targetId: config.id, details: data });
256
+ return c.json({ success: true, data });
257
+ });
258
+ //# sourceMappingURL=ops.js.map