@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.
- package/.env.example +171 -0
- package/LICENSE +202 -0
- package/README.md +169 -2
- package/agent-version.json +1 -0
- package/dist/ai/HEARTBEAT.md +56 -0
- package/dist/ai/IDENTITY.md +54 -0
- package/dist/ai/MEMORY.md +40 -0
- package/dist/ai/TOOLS.md +538 -0
- package/dist/ai/USER.md +32 -0
- package/dist/cli/args.js +62 -0
- package/dist/cli/env-catalog.js +131 -0
- package/dist/cli/preflight.js +89 -0
- package/dist/cli.js +175 -0
- package/dist/config/cors.js +16 -0
- package/dist/config/env.js +392 -0
- package/dist/config/features.js +16 -0
- package/dist/config/index.js +3 -0
- package/dist/config/listener-security.js +38 -0
- package/dist/config/version.js +31 -0
- package/dist/db/client.js +44 -0
- package/dist/db/generated/prisma/browser.js +18 -0
- package/dist/db/generated/prisma/client.js +35 -0
- package/dist/db/generated/prisma/commonInputTypes.js +11 -0
- package/dist/db/generated/prisma/enums.js +42 -0
- package/dist/db/generated/prisma/internal/class.js +50 -0
- package/dist/db/generated/prisma/internal/prismaNamespace.js +1598 -0
- package/dist/db/generated/prisma/internal/prismaNamespaceBrowser.js +1569 -0
- package/dist/db/generated/prisma/models/A2ATask.js +2 -0
- package/dist/db/generated/prisma/models/AdmissionFence.js +2 -0
- package/dist/db/generated/prisma/models/Agent.js +2 -0
- package/dist/db/generated/prisma/models/AiConversation.js +2 -0
- package/dist/db/generated/prisma/models/AiDashboard.js +2 -0
- package/dist/db/generated/prisma/models/AiMemory.js +2 -0
- package/dist/db/generated/prisma/models/AiMessage.js +2 -0
- package/dist/db/generated/prisma/models/AiScheduledOp.js +2 -0
- package/dist/db/generated/prisma/models/AlertConditionState.js +2 -0
- package/dist/db/generated/prisma/models/AlertRule.js +2 -0
- package/dist/db/generated/prisma/models/AlertViolation.js +2 -0
- package/dist/db/generated/prisma/models/AnomalyEvent.js +2 -0
- package/dist/db/generated/prisma/models/ApplicationObservation.js +2 -0
- package/dist/db/generated/prisma/models/ArdentInstallation.js +2 -0
- package/dist/db/generated/prisma/models/ArdentProfile.js +2 -0
- package/dist/db/generated/prisma/models/ArdentScopeEnrollment.js +2 -0
- package/dist/db/generated/prisma/models/CommandResourceFence.js +2 -0
- package/dist/db/generated/prisma/models/CommandResourceLease.js +2 -0
- package/dist/db/generated/prisma/models/CommandResult.js +2 -0
- package/dist/db/generated/prisma/models/CronJob.js +2 -0
- package/dist/db/generated/prisma/models/CronJobExecution.js +2 -0
- package/dist/db/generated/prisma/models/DeployJob.js +2 -0
- package/dist/db/generated/prisma/models/DriftScan.js +2 -0
- package/dist/db/generated/prisma/models/EngineeringMetricSample.js +2 -0
- package/dist/db/generated/prisma/models/EngineeringRecoveryExercise.js +2 -0
- package/dist/db/generated/prisma/models/ExecutionRun.js +2 -0
- package/dist/db/generated/prisma/models/FilePatchTask.js +2 -0
- package/dist/db/generated/prisma/models/GpuSnapshot.js +2 -0
- package/dist/db/generated/prisma/models/HealthSnapshot.js +2 -0
- package/dist/db/generated/prisma/models/HermesCoreRollout.js +2 -0
- package/dist/db/generated/prisma/models/HermesCoreRolloutHost.js +2 -0
- package/dist/db/generated/prisma/models/HermesCredentialPool.js +2 -0
- package/dist/db/generated/prisma/models/HermesCredentialPoolAttachment.js +2 -0
- package/dist/db/generated/prisma/models/HermesCronJob.js +2 -0
- package/dist/db/generated/prisma/models/HermesHook.js +2 -0
- package/dist/db/generated/prisma/models/HermesInstallation.js +2 -0
- package/dist/db/generated/prisma/models/HermesMcpServer.js +2 -0
- package/dist/db/generated/prisma/models/HermesMcpServerAttachment.js +2 -0
- package/dist/db/generated/prisma/models/HermesMessagingBinding.js +2 -0
- package/dist/db/generated/prisma/models/HermesOperationJob.js +2 -0
- package/dist/db/generated/prisma/models/HermesPluginInstall.js +2 -0
- package/dist/db/generated/prisma/models/HermesProfile.js +2 -0
- package/dist/db/generated/prisma/models/HermesProviderConfig.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryClient.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryInventory.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryReceipt.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryRevision.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryTarget.js +2 -0
- package/dist/db/generated/prisma/models/HermesRole.js +2 -0
- package/dist/db/generated/prisma/models/HermesRoleApplication.js +2 -0
- package/dist/db/generated/prisma/models/HermesSkillAssignment.js +2 -0
- package/dist/db/generated/prisma/models/HermesToolsetPolicy.js +2 -0
- package/dist/db/generated/prisma/models/IncidentLesson.js +2 -0
- package/dist/db/generated/prisma/models/LibraryCategory.js +2 -0
- package/dist/db/generated/prisma/models/LibraryFile.js +2 -0
- package/dist/db/generated/prisma/models/LogEntry.js +2 -0
- package/dist/db/generated/prisma/models/MagnusReleaseCanary.js +2 -0
- package/dist/db/generated/prisma/models/MaintenanceWindow.js +2 -0
- package/dist/db/generated/prisma/models/ManagedCronDefinition.js +2 -0
- package/dist/db/generated/prisma/models/ManagedCronOccurrence.js +2 -0
- package/dist/db/generated/prisma/models/Node.js +2 -0
- package/dist/db/generated/prisma/models/Notification.js +2 -0
- package/dist/db/generated/prisma/models/NotificationPreference.js +2 -0
- package/dist/db/generated/prisma/models/RemediationExecution.js +2 -0
- package/dist/db/generated/prisma/models/RemediationRule.js +2 -0
- package/dist/db/generated/prisma/models/RemoteCommand.js +2 -0
- package/dist/db/generated/prisma/models/ResourceDrainParticipant.js +2 -0
- package/dist/db/generated/prisma/models/ResourceEnrollment.js +2 -0
- package/dist/db/generated/prisma/models/ResourceParticipantWork.js +2 -0
- package/dist/db/generated/prisma/models/Role.js +2 -0
- package/dist/db/generated/prisma/models/RoleApplication.js +2 -0
- package/dist/db/generated/prisma/models/RolloutTarget.js +2 -0
- package/dist/db/generated/prisma/models/SecurityExportOutbox.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionAction.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionActionApproval.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCase.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseActivity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseEntity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseEvent.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseRelationship.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCollector.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCommandOutbox.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionDeletionReceipt.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionDelivery.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEntity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEntityAlias.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEvent.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEventEntity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEvidence.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionInvestigation.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionNonce.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionReceiptChainHead.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionRuleVersion.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionSourceState.js +2 -0
- package/dist/db/generated/prisma/models/SecurityServiceState.js +2 -0
- package/dist/db/generated/prisma/models/SharedResourceFence.js +2 -0
- package/dist/db/generated/prisma/models/SharedResourceLease.js +2 -0
- package/dist/db/generated/prisma/models/SharedResourceLeaseResource.js +2 -0
- package/dist/db/generated/prisma/models/SkillInstallation.js +2 -0
- package/dist/db/generated/prisma/models/SkillRegistryEntry.js +2 -0
- package/dist/db/generated/prisma/models/SkillTag.js +2 -0
- package/dist/db/generated/prisma/models/SkillVersion.js +2 -0
- package/dist/db/generated/prisma/models/TeamApprovalDecision.js +2 -0
- package/dist/db/generated/prisma/models/User.js +2 -0
- package/dist/db/generated/prisma/models/WebhookDelivery.js +2 -0
- package/dist/db/generated/prisma/models/WebhookEndpoint.js +2 -0
- package/dist/db/generated/prisma/models.js +2 -0
- package/dist/db/index.js +3 -0
- package/dist/db/read-retry.js +35 -0
- package/dist/db/seed.js +348 -0
- package/dist/index.js +162 -0
- package/dist/middleware/auth.js +361 -0
- package/dist/middleware/body-limit.js +14 -0
- package/dist/middleware/correlation-id.js +13 -0
- package/dist/middleware/error-handler.js +28 -0
- package/dist/middleware/iam-token.js +21 -0
- package/dist/middleware/rate-limit.js +78 -0
- package/dist/middleware/request-logger.js +85 -0
- package/dist/middleware/security-headers.js +23 -0
- package/dist/middleware/tracing.js +120 -0
- package/dist/middleware/user-status.js +33 -0
- package/dist/openapi/spec.js +2656 -0
- package/dist/queue/redis.js +20 -0
- package/dist/queue/requeue.js +27 -0
- package/dist/queue/workers.js +342 -0
- package/dist/routes/ai-schedule.js +73 -0
- package/dist/routes/alerts.js +79 -0
- package/dist/routes/anomalies.js +101 -0
- package/dist/routes/ardent.js +82 -0
- package/dist/routes/assistant.js +417 -0
- package/dist/routes/audit.js +138 -0
- package/dist/routes/codex.js +65 -0
- package/dist/routes/commands.js +226 -0
- package/dist/routes/credentials.js +58 -0
- package/dist/routes/cron.js +292 -0
- package/dist/routes/dependencies.js +49 -0
- package/dist/routes/deploy.js +18 -0
- package/dist/routes/discovery.js +168 -0
- package/dist/routes/docs.js +24 -0
- package/dist/routes/drift.js +126 -0
- package/dist/routes/events-stream.js +87 -0
- package/dist/routes/files.js +214 -0
- package/dist/routes/fleet-checks.js +21 -0
- package/dist/routes/health.js +133 -0
- package/dist/routes/heartbeat.js +545 -0
- package/dist/routes/hermes-registry.js +278 -0
- package/dist/routes/hermes.js +61 -0
- package/dist/routes/library.js +402 -0
- package/dist/routes/logs.js +172 -0
- package/dist/routes/managed-cron.js +23 -0
- package/dist/routes/mcp.js +39 -0
- package/dist/routes/metrics.js +187 -0
- package/dist/routes/nodes.js +951 -0
- package/dist/routes/notifications.js +130 -0
- package/dist/routes/ops.js +258 -0
- package/dist/routes/orchestra.js +430 -0
- package/dist/routes/predictions.js +23 -0
- package/dist/routes/profiling.js +68 -0
- package/dist/routes/quick-command.js +72 -0
- package/dist/routes/remediation.js +111 -0
- package/dist/routes/resource-leases.js +297 -0
- package/dist/routes/roles.js +370 -0
- package/dist/routes/rollout.js +124 -0
- package/dist/routes/scan.js +116 -0
- package/dist/routes/security-backup.js +58 -0
- package/dist/routes/security-fusion.js +605 -0
- package/dist/routes/security-integration.js +71 -0
- package/dist/routes/self-update.js +129 -0
- package/dist/routes/shared-resource-leases.js +78 -0
- package/dist/routes/skills.js +485 -0
- package/dist/routes/stats.js +96 -0
- package/dist/routes/team-approvals.js +23 -0
- package/dist/routes/terminal-ticket.js +15 -0
- package/dist/routes/terminal.js +17 -0
- package/dist/routes/topology.js +37 -0
- package/dist/routes/users.js +219 -0
- package/dist/routes/webhooks.js +137 -0
- package/dist/schemas/command-reconciliation.js +14 -0
- package/dist/schemas/commands.js +51 -0
- package/dist/schemas/cron.js +33 -0
- package/dist/schemas/deploy.js +20 -0
- package/dist/schemas/files.js +14 -0
- package/dist/schemas/hermes.js +69 -0
- package/dist/schemas/index.js +11 -0
- package/dist/schemas/library.js +48 -0
- package/dist/schemas/logs.js +35 -0
- package/dist/schemas/managed-cron.js +127 -0
- package/dist/schemas/node-responses.js +87 -0
- package/dist/schemas/node-session-receipt.js +84 -0
- package/dist/schemas/nodes.js +36 -0
- package/dist/schemas/orchestra.js +118 -0
- package/dist/schemas/resource-participant-reconciliation.js +99 -0
- package/dist/schemas/roles.js +54 -0
- package/dist/schemas/shared-resource-lease.js +132 -0
- package/dist/schemas/skills.js +44 -0
- package/dist/schemas/users.js +28 -0
- package/dist/scripts/run-disposable-recovery-exercise.js +39 -0
- package/dist/sdk/index.js +2 -0
- package/dist/sdk/node-api-client.js +474 -0
- package/dist/security/approval-assertion.js +66 -0
- package/dist/security/command-completion-registry.js +35 -0
- package/dist/security/command-request.js +12 -0
- package/dist/security/command-result-signature.js +34 -0
- package/dist/security/managed-http.js +45 -0
- package/dist/security/native-completion-registry.js +44 -0
- package/dist/server.js +178 -0
- package/dist/services/admission-fence.js +71 -0
- package/dist/services/ai-assistant-service.js +2523 -0
- package/dist/services/ai-correlation-service.js +225 -0
- package/dist/services/ai-export-service.js +141 -0
- package/dist/services/ai-insights-service.js +219 -0
- package/dist/services/ai-schedule-service.js +145 -0
- package/dist/services/ai-scratchpad-service.js +222 -0
- package/dist/services/ai-tools.js +1343 -0
- package/dist/services/alert-service.js +313 -0
- package/dist/services/anomaly-detector.js +419 -0
- package/dist/services/api-local-work.js +79 -0
- package/dist/services/application-probes.js +309 -0
- package/dist/services/ardent-scope-enrollment.js +123 -0
- package/dist/services/ardent-service.js +86 -0
- package/dist/services/audit-service.js +308 -0
- package/dist/services/codex-service.js +209 -0
- package/dist/services/command-lifecycle.js +60 -0
- package/dist/services/command-resource-leases.js +305 -0
- package/dist/services/control-host-node.js +242 -0
- package/dist/services/credential-rotation-service.js +294 -0
- package/dist/services/dependency-service.js +145 -0
- package/dist/services/disposable-recovery-runner.js +595 -0
- package/dist/services/docker-group-health.js +121 -0
- package/dist/services/engineering-assurance.js +492 -0
- package/dist/services/engineering-evidence-ledger.js +94 -0
- package/dist/services/engineering-metric-evidence.js +26 -0
- package/dist/services/event-bus.js +227 -0
- package/dist/services/fleet-check-log.js +102 -0
- package/dist/services/forecast-service.js +154 -0
- package/dist/services/health-retention.js +175 -0
- package/dist/services/heartbeat-stream.js +63 -0
- package/dist/services/hermes-catalog-import.js +62 -0
- package/dist/services/hermes-cli-parser.js +671 -0
- package/dist/services/hermes-core-rollout.js +90 -0
- package/dist/services/hermes-dashboard-endpoint.js +13 -0
- package/dist/services/hermes-plugin-source.js +149 -0
- package/dist/services/hermes-registry-service.js +258 -0
- package/dist/services/hermes-service.js +566 -0
- package/dist/services/hivemem-client.js +85 -0
- package/dist/services/host-local-writer.js +82 -0
- package/dist/services/incident-evidence.js +110 -0
- package/dist/services/incident-lessons.js +186 -0
- package/dist/services/llm-providers/anthropic.js +143 -0
- package/dist/services/llm-providers/index.js +7 -0
- package/dist/services/llm-providers/llama-cpp.js +237 -0
- package/dist/services/llm-providers/ollama.js +292 -0
- package/dist/services/llm-providers/openai-compatible.js +200 -0
- package/dist/services/llm-providers/provider-error.js +36 -0
- package/dist/services/llm-providers/registry.js +45 -0
- package/dist/services/llm-providers/types.js +2 -0
- package/dist/services/log-emitter.js +19 -0
- package/dist/services/log-retention.js +66 -0
- package/dist/services/maintenance-service.js +29 -0
- package/dist/services/managed-cron.js +493 -0
- package/dist/services/managed-ssh-admission.js +68 -0
- package/dist/services/monitor-pulse.js +10 -0
- package/dist/services/node-issue-monitor.js +71 -0
- package/dist/services/node-service.js +35 -0
- package/dist/services/notification-retention.js +51 -0
- package/dist/services/notification-service.js +94 -0
- package/dist/services/operational-observations.js +112 -0
- package/dist/services/operations-config.js +67 -0
- package/dist/services/ops-service.js +491 -0
- package/dist/services/orchestra-extras-service.js +370 -0
- package/dist/services/orchestra-resources-service.js +530 -0
- package/dist/services/os-scheduler-writer.js +73 -0
- package/dist/services/password-service.js +22 -0
- package/dist/services/prediction-service.js +284 -0
- package/dist/services/recovery-exercises.js +682 -0
- package/dist/services/remediation-service.js +325 -0
- package/dist/services/resource-enrollment.js +433 -0
- package/dist/services/resource-node-lock.js +18 -0
- package/dist/services/resource-participant-work.js +302 -0
- package/dist/services/role-service.js +388 -0
- package/dist/services/rollout-service.js +440 -0
- package/dist/services/security-export.js +185 -0
- package/dist/services/security-fusion-actions.js +22 -0
- package/dist/services/security-fusion-approvals.js +83 -0
- package/dist/services/security-fusion-evidence-integrity.js +144 -0
- package/dist/services/security-fusion-ingest.js +101 -0
- package/dist/services/security-fusion-outbox.js +185 -0
- package/dist/services/security-fusion-receipt-chain.js +134 -0
- package/dist/services/security-fusion-service.js +751 -0
- package/dist/services/security-fusion-verification.js +50 -0
- package/dist/services/self-update-service.js +200 -0
- package/dist/services/shared-resource-leases.js +413 -0
- package/dist/services/skill-publication-bundle.js +90 -0
- package/dist/services/skill-publication-settlement.js +36 -0
- package/dist/services/skill-publication-state.js +40 -0
- package/dist/services/skill-registry-service.js +327 -0
- package/dist/services/skill-service.js +148 -0
- package/dist/services/ssh-exec-service.js +139 -0
- package/dist/services/ssh-host-verification.js +27 -0
- package/dist/services/tailscale-node-key-service.js +75 -0
- package/dist/services/team-approvals.js +118 -0
- package/dist/services/topology-service.js +138 -0
- package/dist/services/transfer-authority-snapshot.js +151 -0
- package/dist/services/webhook-credential-migration.js +97 -0
- package/dist/services/webhook-security.js +242 -0
- package/dist/services/webhook-service.js +494 -0
- package/dist/types/auth.js +3 -0
- package/dist/types/index.js +3 -0
- package/dist/types/library.js +3 -0
- package/dist/types/notifications.js +3 -0
- package/dist/types/roles.js +3 -0
- package/dist/types/shared-contracts.js +3 -0
- package/dist/utils/env.js +141 -0
- package/dist/utils/heartbeat-peer.js +19 -0
- package/dist/utils/idempotency.js +45 -0
- package/dist/utils/ip.js +25 -0
- package/dist/utils/json-fields.js +94 -0
- package/dist/utils/local-tls.js +39 -0
- package/dist/utils/magnus-home.js +15 -0
- package/dist/utils/node-url.js +59 -0
- package/dist/utils/redact.js +26 -0
- package/dist/utils/safe-equal.js +13 -0
- package/dist/utils/sentinel-nodes.js +16 -0
- package/dist/utils/validate.js +41 -0
- package/package.json +119 -4
- package/prisma/migrations/20261031000000_baseline/migration.sql +2935 -0
- package/prisma/migrations/migration_lock.toml +3 -0
- package/prisma/schema.prisma +2185 -0
- package/prisma.config.ts +14 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ai-correlation-service.ts — Cross-fleet anomaly correlation engine.
|
|
3
|
+
*
|
|
4
|
+
* Groups anomalies by time proximity, identifies fleet-wide patterns,
|
|
5
|
+
* and correlates anomalies with recent commands/events.
|
|
6
|
+
*/
|
|
7
|
+
import { getDb } from '../db/index.js';
|
|
8
|
+
/**
|
|
9
|
+
* Correlate active anomalies by grouping them within time windows (±5 minutes).
|
|
10
|
+
* Also fetches related commands executed around the same time.
|
|
11
|
+
*/
|
|
12
|
+
export async function correlateAnomalies(options) {
|
|
13
|
+
const db = getDb();
|
|
14
|
+
const windowMs = (options?.windowMinutes ?? 5) * 60 * 1000;
|
|
15
|
+
const anomalies = await db.anomalyEvent.findMany({
|
|
16
|
+
where: options?.includeResolved ? {} : { resolved: false },
|
|
17
|
+
orderBy: { createdAt: 'asc' },
|
|
18
|
+
take: 200,
|
|
19
|
+
});
|
|
20
|
+
if (anomalies.length === 0)
|
|
21
|
+
return [];
|
|
22
|
+
// Group anomalies into time-based clusters
|
|
23
|
+
const groups = [];
|
|
24
|
+
let currentGroup = [anomalies[0]];
|
|
25
|
+
for (let i = 1; i < anomalies.length; i++) {
|
|
26
|
+
const prev = currentGroup[currentGroup.length - 1];
|
|
27
|
+
const curr = anomalies[i];
|
|
28
|
+
if (curr.createdAt.getTime() - prev.createdAt.getTime() <= windowMs) {
|
|
29
|
+
currentGroup.push(curr);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
if (currentGroup.length > 0) {
|
|
33
|
+
groups.push(await buildGroup(db, currentGroup, groups.length));
|
|
34
|
+
}
|
|
35
|
+
currentGroup = [curr];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Don't forget the last group
|
|
39
|
+
if (currentGroup.length > 0) {
|
|
40
|
+
groups.push(await buildGroup(db, currentGroup, groups.length));
|
|
41
|
+
}
|
|
42
|
+
return groups;
|
|
43
|
+
}
|
|
44
|
+
export async function getAnomalyTimeline(options) {
|
|
45
|
+
const db = getDb();
|
|
46
|
+
const hours = Math.min(Math.max(options?.hours ?? 24, 1), 24 * 30);
|
|
47
|
+
const since = new Date(Date.now() - hours * 60 * 60 * 1000);
|
|
48
|
+
const anomalyWhere = { createdAt: { gte: since } };
|
|
49
|
+
const healthWhere = { timestamp: { gte: since } };
|
|
50
|
+
if (options?.nodeId) {
|
|
51
|
+
anomalyWhere['nodeId'] = options.nodeId;
|
|
52
|
+
healthWhere['nodeId'] = options.nodeId;
|
|
53
|
+
}
|
|
54
|
+
const [anomalies, healthSnapshots] = await Promise.all([
|
|
55
|
+
db.anomalyEvent.findMany({
|
|
56
|
+
where: anomalyWhere,
|
|
57
|
+
orderBy: { createdAt: 'asc' },
|
|
58
|
+
take: 200,
|
|
59
|
+
select: {
|
|
60
|
+
id: true,
|
|
61
|
+
nodeId: true,
|
|
62
|
+
metric: true,
|
|
63
|
+
value: true,
|
|
64
|
+
severity: true,
|
|
65
|
+
zScore: true,
|
|
66
|
+
resolved: true,
|
|
67
|
+
createdAt: true,
|
|
68
|
+
},
|
|
69
|
+
}),
|
|
70
|
+
db.healthSnapshot.findMany({
|
|
71
|
+
where: healthWhere,
|
|
72
|
+
orderBy: { timestamp: 'asc' },
|
|
73
|
+
take: 200,
|
|
74
|
+
select: {
|
|
75
|
+
nodeId: true,
|
|
76
|
+
timestamp: true,
|
|
77
|
+
cpuUsagePercent: true,
|
|
78
|
+
memoryPercent: true,
|
|
79
|
+
},
|
|
80
|
+
}),
|
|
81
|
+
]);
|
|
82
|
+
return {
|
|
83
|
+
timeRange: { start: since.toISOString(), end: new Date().toISOString() },
|
|
84
|
+
anomalyCount: anomalies.length,
|
|
85
|
+
anomalies: anomalies.map((item) => ({ ...item, createdAt: item.createdAt.toISOString() })),
|
|
86
|
+
healthContext: healthSnapshots.map((item) => ({
|
|
87
|
+
nodeId: item.nodeId,
|
|
88
|
+
timestamp: item.timestamp.toISOString(),
|
|
89
|
+
cpu: item.cpuUsagePercent,
|
|
90
|
+
memory: item.memoryPercent,
|
|
91
|
+
})),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
async function buildGroup(db, anomalies, index) {
|
|
95
|
+
const start = anomalies[0].createdAt;
|
|
96
|
+
const end = anomalies[anomalies.length - 1].createdAt;
|
|
97
|
+
const affectedNodes = [...new Set(anomalies.map(a => a.nodeId))];
|
|
98
|
+
const metrics = [...new Set(anomalies.map(a => a.metric))];
|
|
99
|
+
// Find commands executed within ±30 minutes of the anomaly window
|
|
100
|
+
const windowStart = new Date(start.getTime() - 30 * 60 * 1000);
|
|
101
|
+
const windowEnd = new Date(end.getTime() + 30 * 60 * 1000);
|
|
102
|
+
const relatedCommands = await db.remoteCommand.findMany({
|
|
103
|
+
where: {
|
|
104
|
+
nodeId: { in: affectedNodes },
|
|
105
|
+
createdAt: { gte: windowStart, lte: windowEnd },
|
|
106
|
+
},
|
|
107
|
+
select: { id: true, nodeId: true, command: true, status: true, createdAt: true },
|
|
108
|
+
take: 20,
|
|
109
|
+
orderBy: { createdAt: 'desc' },
|
|
110
|
+
});
|
|
111
|
+
// Generate pattern description
|
|
112
|
+
let pattern;
|
|
113
|
+
if (affectedNodes.length > 1 && metrics.length === 1) {
|
|
114
|
+
pattern = `Fleet-wide ${metrics[0]} anomaly across ${affectedNodes.length} nodes`;
|
|
115
|
+
}
|
|
116
|
+
else if (affectedNodes.length === 1 && metrics.length > 1) {
|
|
117
|
+
pattern = `Multi-metric anomaly on single node (${metrics.join(', ')})`;
|
|
118
|
+
}
|
|
119
|
+
else if (affectedNodes.length > 1 && metrics.length > 1) {
|
|
120
|
+
pattern = `Correlated multi-metric anomaly across ${affectedNodes.length} nodes`;
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
pattern = `Isolated ${metrics[0] ?? 'unknown'} anomaly`;
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
id: `corr-${index}`,
|
|
127
|
+
timeWindow: { start: start.toISOString(), end: end.toISOString() },
|
|
128
|
+
anomalies: anomalies.map(a => ({
|
|
129
|
+
id: a.id,
|
|
130
|
+
nodeId: a.nodeId,
|
|
131
|
+
metric: a.metric,
|
|
132
|
+
value: a.value,
|
|
133
|
+
severity: a.severity,
|
|
134
|
+
zScore: a.zScore,
|
|
135
|
+
createdAt: a.createdAt.toISOString(),
|
|
136
|
+
})),
|
|
137
|
+
affectedNodes,
|
|
138
|
+
metrics,
|
|
139
|
+
pattern,
|
|
140
|
+
relatedCommands: relatedCommands.map(c => ({
|
|
141
|
+
id: c.id,
|
|
142
|
+
nodeId: c.nodeId,
|
|
143
|
+
command: c.command,
|
|
144
|
+
status: c.status,
|
|
145
|
+
createdAt: c.createdAt.toISOString(),
|
|
146
|
+
})),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Get a concise summary of current anomaly correlations.
|
|
151
|
+
*/
|
|
152
|
+
export async function getCorrelationSummary() {
|
|
153
|
+
const groups = await correlateAnomalies();
|
|
154
|
+
const fleetWide = groups.filter(g => g.affectedNodes.length > 1);
|
|
155
|
+
const allAffected = new Set(groups.flatMap(g => g.affectedNodes));
|
|
156
|
+
const critical = groups.filter(g => g.anomalies.some(a => a.severity === 'critical'));
|
|
157
|
+
const parts = [];
|
|
158
|
+
if (groups.length === 0) {
|
|
159
|
+
parts.push('No active anomaly correlations detected.');
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
parts.push(`${groups.length} anomaly group(s) detected.`);
|
|
163
|
+
if (fleetWide.length > 0) {
|
|
164
|
+
parts.push(`${fleetWide.length} fleet-wide pattern(s) affecting multiple nodes.`);
|
|
165
|
+
}
|
|
166
|
+
if (critical.length > 0) {
|
|
167
|
+
parts.push(`${critical.length} group(s) contain critical-severity anomalies.`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
totalGroups: groups.length,
|
|
172
|
+
fleetWidePatterns: fleetWide.length,
|
|
173
|
+
affectedNodes: allAffected.size,
|
|
174
|
+
criticalGroups: critical.length,
|
|
175
|
+
summary: parts.join(' '),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
export async function getAnomalyCorrelationDetails(anomalyId) {
|
|
179
|
+
const db = getDb();
|
|
180
|
+
const anomaly = await db.anomalyEvent.findUnique({ where: { id: anomalyId } });
|
|
181
|
+
if (!anomaly)
|
|
182
|
+
return null;
|
|
183
|
+
const groups = await correlateAnomalies({ windowMinutes: 10, includeResolved: true });
|
|
184
|
+
let group = groups.find((candidate) => candidate.anomalies.some((entry) => entry.id === anomalyId)) ?? null;
|
|
185
|
+
if (!group) {
|
|
186
|
+
group = await buildGroup(db, [anomaly], 0);
|
|
187
|
+
}
|
|
188
|
+
const suspectedTriggers = group.relatedCommands.length > 0
|
|
189
|
+
? group.relatedCommands.slice(0, 3).map((command) => command.command)
|
|
190
|
+
: ['No nearby command activity detected'];
|
|
191
|
+
const recommendedActions = [
|
|
192
|
+
group.metrics.some((metric) => metric.includes('disk')) ? 'Inspect disk usage growth and recent package/file operations.' : null,
|
|
193
|
+
group.metrics.some((metric) => metric.includes('cpu')) ? 'Check recent process spikes, deploys, or runaway services.' : null,
|
|
194
|
+
group.metrics.some((metric) => metric.includes('memory')) ? 'Review top memory consumers and restart leaky services if needed.' : null,
|
|
195
|
+
group.metrics.some((metric) => metric.includes('network')) ? 'Validate upstream dependencies, routing, and packet loss on affected nodes.' : null,
|
|
196
|
+
group.relatedCommands.length === 0 ? 'Correlate with external incidents or scheduled jobs outside Magnus command history.' : null,
|
|
197
|
+
].filter((item) => Boolean(item));
|
|
198
|
+
if (recommendedActions.length === 0) {
|
|
199
|
+
recommendedActions.push('Review node health history and recent configuration changes for the affected systems.');
|
|
200
|
+
}
|
|
201
|
+
const blastRadius = group.affectedNodes.length > 1 ? 'multi-node' : 'single-node';
|
|
202
|
+
const summary = blastRadius === 'multi-node'
|
|
203
|
+
? `${group.pattern}. ${group.anomalies.length} anomalies were detected across ${group.affectedNodes.length} nodes in the same time window.`
|
|
204
|
+
: `${group.pattern}. The issue currently appears isolated to a single node, but it still correlates with ${group.relatedCommands.length} nearby command event(s).`;
|
|
205
|
+
return {
|
|
206
|
+
anomaly: {
|
|
207
|
+
id: anomaly.id,
|
|
208
|
+
nodeId: anomaly.nodeId,
|
|
209
|
+
metric: anomaly.metric,
|
|
210
|
+
value: anomaly.value,
|
|
211
|
+
severity: anomaly.severity,
|
|
212
|
+
zScore: anomaly.zScore,
|
|
213
|
+
createdAt: anomaly.createdAt.toISOString(),
|
|
214
|
+
resolved: anomaly.resolved,
|
|
215
|
+
},
|
|
216
|
+
group,
|
|
217
|
+
analysis: {
|
|
218
|
+
blastRadius,
|
|
219
|
+
suspectedTriggers,
|
|
220
|
+
recommendedActions,
|
|
221
|
+
summary,
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
//# sourceMappingURL=ai-correlation-service.js.map
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ai-export-service.ts — Conversation export in multiple formats.
|
|
3
|
+
*
|
|
4
|
+
* Supports exporting AI conversations as Markdown, JSON, or CSV.
|
|
5
|
+
*/
|
|
6
|
+
import { getDb } from '../db/index.js';
|
|
7
|
+
/**
|
|
8
|
+
* Export a conversation in the specified format.
|
|
9
|
+
*/
|
|
10
|
+
export async function exportConversation(conversationId, format = 'markdown') {
|
|
11
|
+
const db = getDb();
|
|
12
|
+
const conversation = await db.aiConversation.findUnique({
|
|
13
|
+
where: { id: conversationId },
|
|
14
|
+
include: {
|
|
15
|
+
messages: {
|
|
16
|
+
orderBy: { createdAt: 'asc' },
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
if (!conversation)
|
|
21
|
+
return null;
|
|
22
|
+
const dateStr = conversation.createdAt.toISOString().slice(0, 10);
|
|
23
|
+
const slug = conversation.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40);
|
|
24
|
+
switch (format) {
|
|
25
|
+
case 'markdown':
|
|
26
|
+
return {
|
|
27
|
+
content: toMarkdown(conversation),
|
|
28
|
+
contentType: 'text/markdown; charset=utf-8',
|
|
29
|
+
filename: `${slug}-${dateStr}.md`,
|
|
30
|
+
};
|
|
31
|
+
case 'json':
|
|
32
|
+
return {
|
|
33
|
+
content: toJson(conversation),
|
|
34
|
+
contentType: 'application/json; charset=utf-8',
|
|
35
|
+
filename: `${slug}-${dateStr}.json`,
|
|
36
|
+
};
|
|
37
|
+
case 'csv':
|
|
38
|
+
return {
|
|
39
|
+
content: toCsv(conversation),
|
|
40
|
+
contentType: 'text/csv; charset=utf-8',
|
|
41
|
+
filename: `${slug}-${dateStr}.csv`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function toMarkdown(conv) {
|
|
46
|
+
const lines = [];
|
|
47
|
+
lines.push(`# ${conv.title}`);
|
|
48
|
+
lines.push('');
|
|
49
|
+
lines.push(`**Type:** ${conv.type} | **Status:** ${conv.status} | **Created:** ${conv.createdAt.toISOString()}`);
|
|
50
|
+
if (conv.nodeId)
|
|
51
|
+
lines.push(`**Node:** ${conv.nodeId}`);
|
|
52
|
+
if (conv.summary) {
|
|
53
|
+
lines.push('');
|
|
54
|
+
lines.push(`> **Summary:** ${conv.summary}`);
|
|
55
|
+
}
|
|
56
|
+
lines.push('');
|
|
57
|
+
lines.push('---');
|
|
58
|
+
lines.push('');
|
|
59
|
+
for (const msg of conv.messages) {
|
|
60
|
+
if (msg.role === 'system')
|
|
61
|
+
continue; // Skip system messages
|
|
62
|
+
const roleLabel = msg.role === 'user' ? '🧑 **User**' :
|
|
63
|
+
msg.role === 'assistant' ? '🤖 **Magnus AI**' :
|
|
64
|
+
msg.role === 'tool' ? '🔧 **Tool**' : `**${msg.role}**`;
|
|
65
|
+
const time = msg.createdAt.toLocaleString();
|
|
66
|
+
lines.push(`### ${roleLabel} — ${time}`);
|
|
67
|
+
lines.push('');
|
|
68
|
+
// Content
|
|
69
|
+
lines.push(msg.content);
|
|
70
|
+
lines.push('');
|
|
71
|
+
// Tool calls
|
|
72
|
+
const toolCalls = parseToolCalls(msg.toolCalls);
|
|
73
|
+
if (toolCalls.length > 0) {
|
|
74
|
+
lines.push('**Tool Calls:**');
|
|
75
|
+
for (const tc of toolCalls) {
|
|
76
|
+
lines.push(`- \`${tc.name}\`: ${tc.success ? '✅' : '❌'} ${truncate(JSON.stringify(tc.result), 200)}`);
|
|
77
|
+
}
|
|
78
|
+
lines.push('');
|
|
79
|
+
}
|
|
80
|
+
lines.push('---');
|
|
81
|
+
lines.push('');
|
|
82
|
+
}
|
|
83
|
+
lines.push(`*Exported from Magnus AI on ${new Date().toISOString()}*`);
|
|
84
|
+
return lines.join('\n');
|
|
85
|
+
}
|
|
86
|
+
function toJson(conv) {
|
|
87
|
+
return JSON.stringify({
|
|
88
|
+
conversation: {
|
|
89
|
+
id: conv.id,
|
|
90
|
+
title: conv.title,
|
|
91
|
+
type: conv.type,
|
|
92
|
+
nodeId: conv.nodeId,
|
|
93
|
+
status: conv.status,
|
|
94
|
+
summary: conv.summary,
|
|
95
|
+
createdBy: conv.createdBy,
|
|
96
|
+
createdAt: conv.createdAt.toISOString(),
|
|
97
|
+
updatedAt: conv.updatedAt.toISOString(),
|
|
98
|
+
},
|
|
99
|
+
messages: conv.messages.map(m => ({
|
|
100
|
+
id: m.id,
|
|
101
|
+
role: m.role,
|
|
102
|
+
content: m.content,
|
|
103
|
+
toolCalls: parseToolCalls(m.toolCalls),
|
|
104
|
+
tokenCount: m.tokenCount,
|
|
105
|
+
createdAt: m.createdAt.toISOString(),
|
|
106
|
+
})),
|
|
107
|
+
exportedAt: new Date().toISOString(),
|
|
108
|
+
}, null, 2);
|
|
109
|
+
}
|
|
110
|
+
function toCsv(conv) {
|
|
111
|
+
const rows = [];
|
|
112
|
+
rows.push('timestamp,role,content,tool_calls,token_count');
|
|
113
|
+
for (const msg of conv.messages) {
|
|
114
|
+
if (msg.role === 'system')
|
|
115
|
+
continue;
|
|
116
|
+
const content = csvEscape(msg.content);
|
|
117
|
+
const tools = csvEscape(msg.toolCalls !== '[]' ? msg.toolCalls : '');
|
|
118
|
+
rows.push(`${msg.createdAt.toISOString()},${msg.role},${content},${tools},${msg.tokenCount}`);
|
|
119
|
+
}
|
|
120
|
+
return rows.join('\n');
|
|
121
|
+
}
|
|
122
|
+
// ── Helpers ──
|
|
123
|
+
function parseToolCalls(raw) {
|
|
124
|
+
try {
|
|
125
|
+
const parsed = JSON.parse(raw);
|
|
126
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function truncate(str, max) {
|
|
133
|
+
return str.length > max ? str.slice(0, max) + '...' : str;
|
|
134
|
+
}
|
|
135
|
+
function csvEscape(str) {
|
|
136
|
+
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
|
|
137
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
138
|
+
}
|
|
139
|
+
return str;
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=ai-export-service.js.map
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ai-insights-service.ts — AI-powered fleet insights generation.
|
|
3
|
+
*
|
|
4
|
+
* Generates structured insights from fleet data using the AI model.
|
|
5
|
+
* Results are cached for 10 minutes to avoid excessive LLM calls.
|
|
6
|
+
*/
|
|
7
|
+
import { getDb } from '../db/index.js';
|
|
8
|
+
import { chat } from './ai-assistant-service.js';
|
|
9
|
+
import { nanoid } from 'nanoid';
|
|
10
|
+
// ── Cache ──
|
|
11
|
+
let cachedInsights = null;
|
|
12
|
+
let cacheTime = 0;
|
|
13
|
+
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes
|
|
14
|
+
/**
|
|
15
|
+
* Generate AI-powered fleet insights.
|
|
16
|
+
* Uses a dedicated heartbeat-style analysis conversation.
|
|
17
|
+
* Results are cached for 10 minutes.
|
|
18
|
+
*/
|
|
19
|
+
export async function generateInsights(force = false) {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
// Return cached result if still fresh
|
|
22
|
+
if (!force && cachedInsights && (now - cacheTime) < CACHE_TTL_MS) {
|
|
23
|
+
return cachedInsights;
|
|
24
|
+
}
|
|
25
|
+
const db = getDb();
|
|
26
|
+
const latestStructuredHeartbeat = await db.aiMessage.findFirst({
|
|
27
|
+
where: {
|
|
28
|
+
conversation: { type: 'heartbeat' },
|
|
29
|
+
structuredAnalysis: { not: null },
|
|
30
|
+
},
|
|
31
|
+
orderBy: { createdAt: 'desc' },
|
|
32
|
+
select: { structuredAnalysis: true, createdAt: true, conversationId: true },
|
|
33
|
+
});
|
|
34
|
+
if (!force && latestStructuredHeartbeat?.structuredAnalysis) {
|
|
35
|
+
try {
|
|
36
|
+
const structured = JSON.parse(latestStructuredHeartbeat.structuredAnalysis);
|
|
37
|
+
if (Array.isArray(structured.insights) && structured.insights.length > 0) {
|
|
38
|
+
const response = {
|
|
39
|
+
insights: structured.insights.slice(0, 5).map((insight) => ({
|
|
40
|
+
title: String(insight.title ?? 'Insight').slice(0, 80),
|
|
41
|
+
body: String(insight.body ?? '').slice(0, 500),
|
|
42
|
+
severity: (['critical', 'warning', 'info', 'success'].includes(insight.severity) ? insight.severity : 'info'),
|
|
43
|
+
category: String(insight.category ?? 'health'),
|
|
44
|
+
nodeId: insight.nodeId ? String(insight.nodeId) : undefined,
|
|
45
|
+
})),
|
|
46
|
+
generatedAt: structured.generatedAt ?? latestStructuredHeartbeat.createdAt.toISOString(),
|
|
47
|
+
conversationId: latestStructuredHeartbeat.conversationId,
|
|
48
|
+
};
|
|
49
|
+
cachedInsights = response;
|
|
50
|
+
cacheTime = now;
|
|
51
|
+
return response;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// fall back to active generation below
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
// Gather fleet context
|
|
59
|
+
const [nodeCount, onlineCount, anomalyCount, recentCommands] = await Promise.all([
|
|
60
|
+
db.node.count({ where: { metadata: { not: '{"sentinel":true}' } } }),
|
|
61
|
+
db.node.count({ where: { status: 'ONLINE', metadata: { not: '{"sentinel":true}' } } }),
|
|
62
|
+
db.anomalyEvent.count({ where: { resolved: false } }),
|
|
63
|
+
db.remoteCommand.findMany({
|
|
64
|
+
orderBy: { createdAt: 'desc' },
|
|
65
|
+
take: 10,
|
|
66
|
+
select: { command: true, status: true, nodeId: true, createdAt: true },
|
|
67
|
+
}),
|
|
68
|
+
]);
|
|
69
|
+
// Get recent anomalies for context
|
|
70
|
+
const recentAnomalies = await db.anomalyEvent.findMany({
|
|
71
|
+
where: { resolved: false },
|
|
72
|
+
orderBy: { createdAt: 'desc' },
|
|
73
|
+
take: 15,
|
|
74
|
+
select: { nodeId: true, metric: true, value: true, severity: true, zScore: true, createdAt: true },
|
|
75
|
+
});
|
|
76
|
+
// Get latest health snapshots
|
|
77
|
+
const nodes = await db.node.findMany({
|
|
78
|
+
where: { metadata: { not: '{"sentinel":true}' } },
|
|
79
|
+
select: { id: true, name: true, status: true },
|
|
80
|
+
});
|
|
81
|
+
const healthSnapshots = await Promise.all(nodes.slice(0, 10).map(async (node) => {
|
|
82
|
+
const snapshot = await db.healthSnapshot.findFirst({
|
|
83
|
+
where: { nodeId: node.id },
|
|
84
|
+
orderBy: { timestamp: 'desc' },
|
|
85
|
+
select: { cpuUsagePercent: true, memoryPercent: true, disks: true, timestamp: true },
|
|
86
|
+
});
|
|
87
|
+
return { nodeName: node.name, status: node.status, health: snapshot };
|
|
88
|
+
}));
|
|
89
|
+
const insightPrompt = `You are analyzing fleet health data. Generate a JSON array of insights.
|
|
90
|
+
|
|
91
|
+
FLEET STATUS:
|
|
92
|
+
- Total nodes: ${nodeCount}, Online: ${onlineCount}, Offline: ${nodeCount - onlineCount}
|
|
93
|
+
- Unresolved anomalies: ${anomalyCount}
|
|
94
|
+
|
|
95
|
+
RECENT ANOMALIES:
|
|
96
|
+
${recentAnomalies.map(a => `- [${a.severity}] ${a.metric}=${a.value.toFixed(1)} (z=${a.zScore.toFixed(1)}) on ${a.nodeId}`).join('\n') || 'None'}
|
|
97
|
+
|
|
98
|
+
NODE HEALTH:
|
|
99
|
+
${healthSnapshots.map(h => {
|
|
100
|
+
if (!h.health)
|
|
101
|
+
return `- ${h.nodeName}: ${h.status} (no health data)`;
|
|
102
|
+
return `- ${h.nodeName}: ${h.status} | CPU=${h.health.cpuUsagePercent.toFixed(0)}% MEM=${h.health.memoryPercent.toFixed(0)}%`;
|
|
103
|
+
}).join('\n')}
|
|
104
|
+
|
|
105
|
+
RECENT COMMANDS:
|
|
106
|
+
${recentCommands.map(c => `- ${c.command.slice(0, 60)} → ${c.status}`).join('\n') || 'None'}
|
|
107
|
+
|
|
108
|
+
Respond ONLY with a valid JSON array of insight objects. Each object must have:
|
|
109
|
+
- "title": short headline (max 80 chars)
|
|
110
|
+
- "body": explanation (1-2 sentences)
|
|
111
|
+
- "severity": "critical" | "warning" | "info" | "success"
|
|
112
|
+
- "category": "health" | "security" | "performance" | "availability" | "trend"
|
|
113
|
+
- "nodeId": optional node ID if specific to one node
|
|
114
|
+
|
|
115
|
+
Generate 3-5 most important insights. No markdown, no explanation, ONLY the JSON array.`;
|
|
116
|
+
try {
|
|
117
|
+
const result = await chat({
|
|
118
|
+
message: insightPrompt,
|
|
119
|
+
type: 'analysis',
|
|
120
|
+
createdBy: 'system',
|
|
121
|
+
});
|
|
122
|
+
// Parse the JSON response
|
|
123
|
+
let insights = [];
|
|
124
|
+
try {
|
|
125
|
+
// Try to extract JSON array from the response
|
|
126
|
+
const jsonMatch = result.content.match(/\[[\s\S]*\]/);
|
|
127
|
+
if (jsonMatch) {
|
|
128
|
+
insights = JSON.parse(jsonMatch[0]);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// If parsing fails, create a single insight from the raw response
|
|
133
|
+
insights = [{
|
|
134
|
+
title: 'Fleet Analysis',
|
|
135
|
+
body: result.content.slice(0, 200),
|
|
136
|
+
severity: 'info',
|
|
137
|
+
category: 'health',
|
|
138
|
+
}];
|
|
139
|
+
}
|
|
140
|
+
// Validate and sanitize insights
|
|
141
|
+
insights = insights.slice(0, 5).map(i => ({
|
|
142
|
+
title: String(i.title ?? 'Insight').slice(0, 80),
|
|
143
|
+
body: String(i.body ?? '').slice(0, 500),
|
|
144
|
+
severity: (['critical', 'warning', 'info', 'success'].includes(i.severity) ? i.severity : 'info'),
|
|
145
|
+
category: String(i.category ?? 'health'),
|
|
146
|
+
nodeId: i.nodeId ? String(i.nodeId) : undefined,
|
|
147
|
+
}));
|
|
148
|
+
const response = {
|
|
149
|
+
insights,
|
|
150
|
+
generatedAt: new Date().toISOString(),
|
|
151
|
+
conversationId: result.conversationId,
|
|
152
|
+
};
|
|
153
|
+
// Cache the result
|
|
154
|
+
cachedInsights = response;
|
|
155
|
+
cacheTime = now;
|
|
156
|
+
return response;
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
console.error('[AI Insights] Generation failed:', err instanceof Error ? err.message : err);
|
|
160
|
+
// Return a fallback insight
|
|
161
|
+
const fallback = {
|
|
162
|
+
insights: [{
|
|
163
|
+
title: 'Insights Unavailable',
|
|
164
|
+
body: 'Unable to generate AI insights at this time. The AI service may be offline.',
|
|
165
|
+
severity: 'warning',
|
|
166
|
+
category: 'availability',
|
|
167
|
+
}],
|
|
168
|
+
generatedAt: new Date().toISOString(),
|
|
169
|
+
};
|
|
170
|
+
return fallback;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Clear the insights cache (e.g., after significant fleet changes).
|
|
175
|
+
*/
|
|
176
|
+
export function clearInsightsCache() {
|
|
177
|
+
cachedInsights = null;
|
|
178
|
+
cacheTime = 0;
|
|
179
|
+
}
|
|
180
|
+
export async function listPinnedInsights() {
|
|
181
|
+
const db = getDb();
|
|
182
|
+
const records = await db.aiMemory.findMany({
|
|
183
|
+
where: { category: 'pinned_insight' },
|
|
184
|
+
orderBy: { updatedAt: 'desc' },
|
|
185
|
+
});
|
|
186
|
+
return records.flatMap((record) => {
|
|
187
|
+
try {
|
|
188
|
+
return [JSON.parse(record.content)];
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
export async function pinInsight(insight) {
|
|
196
|
+
const db = getDb();
|
|
197
|
+
const pinned = {
|
|
198
|
+
id: nanoid(),
|
|
199
|
+
pinnedAt: new Date().toISOString(),
|
|
200
|
+
generatedAt: insight.generatedAt,
|
|
201
|
+
...insight,
|
|
202
|
+
};
|
|
203
|
+
await db.aiMemory.create({
|
|
204
|
+
data: {
|
|
205
|
+
id: nanoid(),
|
|
206
|
+
key: `pinned_insight:${pinned.id}`,
|
|
207
|
+
category: 'pinned_insight',
|
|
208
|
+
content: JSON.stringify(pinned),
|
|
209
|
+
source: 'user',
|
|
210
|
+
relevance: 0.0,
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
return pinned;
|
|
214
|
+
}
|
|
215
|
+
export async function unpinInsight(id) {
|
|
216
|
+
const db = getDb();
|
|
217
|
+
await db.aiMemory.deleteMany({ where: { key: `pinned_insight:${id}` } });
|
|
218
|
+
}
|
|
219
|
+
//# sourceMappingURL=ai-insights-service.js.map
|