@jagilber-org/index-server 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1354 -0
- package/CODE_OF_CONDUCT.md +49 -0
- package/CONTRIBUTING.md +99 -0
- package/LICENSE +21 -0
- package/README.md +228 -0
- package/SECURITY.md +50 -0
- package/dist/config/configUtils.d.ts +11 -0
- package/dist/config/configUtils.js +87 -0
- package/dist/config/dashboardConfig.d.ts +46 -0
- package/dist/config/dashboardConfig.js +67 -0
- package/dist/config/defaultValues.d.ts +63 -0
- package/dist/config/defaultValues.js +72 -0
- package/dist/config/dirConstants.d.ts +18 -0
- package/dist/config/dirConstants.js +29 -0
- package/dist/config/featureConfig.d.ts +61 -0
- package/dist/config/featureConfig.js +121 -0
- package/dist/config/runtimeConfig.d.ts +151 -0
- package/dist/config/runtimeConfig.js +380 -0
- package/dist/config/serverConfig.d.ts +90 -0
- package/dist/config/serverConfig.js +167 -0
- package/dist/dashboard/analytics/AnalyticsEngine.d.ts +142 -0
- package/dist/dashboard/analytics/AnalyticsEngine.js +373 -0
- package/dist/dashboard/analytics/BusinessIntelligence.d.ts +187 -0
- package/dist/dashboard/analytics/BusinessIntelligence.js +594 -0
- package/dist/dashboard/client/admin.html +2175 -0
- package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/chunk-SP2CHFBE.mjs +1 -0
- package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/render-T6MDALS3.mjs +27 -0
- package/dist/dashboard/client/css/admin.css +1587 -0
- package/dist/dashboard/client/js/admin.auth.js +179 -0
- package/dist/dashboard/client/js/admin.boot.js +359 -0
- package/dist/dashboard/client/js/admin.config.js +196 -0
- package/dist/dashboard/client/js/admin.embeddings.js +426 -0
- package/dist/dashboard/client/js/admin.graph.js +615 -0
- package/dist/dashboard/client/js/admin.instances.js +120 -0
- package/dist/dashboard/client/js/admin.instructions.js +579 -0
- package/dist/dashboard/client/js/admin.logs.js +113 -0
- package/dist/dashboard/client/js/admin.maintenance.js +393 -0
- package/dist/dashboard/client/js/admin.messaging.js +636 -0
- package/dist/dashboard/client/js/admin.monitor.js +184 -0
- package/dist/dashboard/client/js/admin.overview.js +221 -0
- package/dist/dashboard/client/js/admin.performance.js +61 -0
- package/dist/dashboard/client/js/admin.sessions.js +292 -0
- package/dist/dashboard/client/js/admin.sqlite.js +373 -0
- package/dist/dashboard/client/js/admin.utils.js +49 -0
- package/dist/dashboard/client/js/chart.umd.js +14 -0
- package/dist/dashboard/client/js/elk.bundled.js +6696 -0
- package/dist/dashboard/client/js/marked.umd.js +74 -0
- package/dist/dashboard/client/js/mermaid.min.js +3022 -0
- package/dist/dashboard/client/mermaid-layout-elk.esm.min.mjs +1 -0
- package/dist/dashboard/export/DataExporter.d.ts +169 -0
- package/dist/dashboard/export/DataExporter.js +737 -0
- package/dist/dashboard/export/exporters/csvExporter.d.ts +11 -0
- package/dist/dashboard/export/exporters/csvExporter.js +47 -0
- package/dist/dashboard/export/exporters/exportTypes.d.ts +89 -0
- package/dist/dashboard/export/exporters/exportTypes.js +5 -0
- package/dist/dashboard/export/exporters/jsonExporter.d.ts +7 -0
- package/dist/dashboard/export/exporters/jsonExporter.js +23 -0
- package/dist/dashboard/export/exporters/xmlExporter.d.ts +17 -0
- package/dist/dashboard/export/exporters/xmlExporter.js +176 -0
- package/dist/dashboard/integration/APIIntegration.d.ts +41 -0
- package/dist/dashboard/integration/APIIntegration.js +95 -0
- package/dist/dashboard/security/SecurityMonitor.d.ts +167 -0
- package/dist/dashboard/security/SecurityMonitor.js +560 -0
- package/dist/dashboard/server/AdminPanel.d.ts +195 -0
- package/dist/dashboard/server/AdminPanel.js +861 -0
- package/dist/dashboard/server/AdminPanelConfig.d.ts +42 -0
- package/dist/dashboard/server/AdminPanelConfig.js +80 -0
- package/dist/dashboard/server/AdminPanelState.d.ts +47 -0
- package/dist/dashboard/server/AdminPanelState.js +215 -0
- package/dist/dashboard/server/ApiRoutes.d.ts +17 -0
- package/dist/dashboard/server/ApiRoutes.js +184 -0
- package/dist/dashboard/server/DashboardServer.d.ts +49 -0
- package/dist/dashboard/server/DashboardServer.js +160 -0
- package/dist/dashboard/server/FileMetricsStorage.d.ts +49 -0
- package/dist/dashboard/server/FileMetricsStorage.js +196 -0
- package/dist/dashboard/server/HttpTransport.d.ts +23 -0
- package/dist/dashboard/server/HttpTransport.js +116 -0
- package/dist/dashboard/server/InstanceManager.d.ts +53 -0
- package/dist/dashboard/server/InstanceManager.js +295 -0
- package/dist/dashboard/server/KnowledgeStore.d.ts +35 -0
- package/dist/dashboard/server/KnowledgeStore.js +105 -0
- package/dist/dashboard/server/LeaderElection.d.ts +81 -0
- package/dist/dashboard/server/LeaderElection.js +268 -0
- package/dist/dashboard/server/MetricsCollector.d.ts +200 -0
- package/dist/dashboard/server/MetricsCollector.js +810 -0
- package/dist/dashboard/server/SessionPersistenceManager.d.ts +88 -0
- package/dist/dashboard/server/SessionPersistenceManager.js +458 -0
- package/dist/dashboard/server/ThinClient.d.ts +64 -0
- package/dist/dashboard/server/ThinClient.js +237 -0
- package/dist/dashboard/server/WebSocketManager.d.ts +161 -0
- package/dist/dashboard/server/WebSocketManager.js +448 -0
- package/dist/dashboard/server/httpLifecycle.d.ts +17 -0
- package/dist/dashboard/server/httpLifecycle.js +35 -0
- package/dist/dashboard/server/legacyDashboardHtml.d.ts +9 -0
- package/dist/dashboard/server/legacyDashboardHtml.js +618 -0
- package/dist/dashboard/server/legacyDashboardStyles.d.ts +5 -0
- package/dist/dashboard/server/legacyDashboardStyles.js +490 -0
- package/dist/dashboard/server/metricsAggregation.d.ts +252 -0
- package/dist/dashboard/server/metricsAggregation.js +210 -0
- package/dist/dashboard/server/metricsSerializer.d.ts +25 -0
- package/dist/dashboard/server/metricsSerializer.js +195 -0
- package/dist/dashboard/server/middleware/ensureLoadedMiddleware.d.ts +25 -0
- package/dist/dashboard/server/middleware/ensureLoadedMiddleware.js +24 -0
- package/dist/dashboard/server/routes/admin.routes.d.ts +16 -0
- package/dist/dashboard/server/routes/admin.routes.js +574 -0
- package/dist/dashboard/server/routes/adminAuth.d.ts +4 -0
- package/dist/dashboard/server/routes/adminAuth.js +46 -0
- package/dist/dashboard/server/routes/alerts.routes.d.ts +7 -0
- package/dist/dashboard/server/routes/alerts.routes.js +91 -0
- package/dist/dashboard/server/routes/api.feedback.routes.d.ts +73 -0
- package/dist/dashboard/server/routes/api.feedback.routes.js +171 -0
- package/dist/dashboard/server/routes/api.instructions.routes.d.ts +101 -0
- package/dist/dashboard/server/routes/api.instructions.routes.js +213 -0
- package/dist/dashboard/server/routes/api.usage.routes.d.ts +57 -0
- package/dist/dashboard/server/routes/api.usage.routes.js +374 -0
- package/dist/dashboard/server/routes/embeddings.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/embeddings.routes.js +246 -0
- package/dist/dashboard/server/routes/graph.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/graph.routes.js +279 -0
- package/dist/dashboard/server/routes/index.d.ts +39 -0
- package/dist/dashboard/server/routes/index.js +229 -0
- package/dist/dashboard/server/routes/instances.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/instances.routes.js +35 -0
- package/dist/dashboard/server/routes/instructions.routes.d.ts +8 -0
- package/dist/dashboard/server/routes/instructions.routes.js +268 -0
- package/dist/dashboard/server/routes/knowledge.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/knowledge.routes.js +80 -0
- package/dist/dashboard/server/routes/logs.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/logs.routes.js +166 -0
- package/dist/dashboard/server/routes/messaging.routes.d.ts +16 -0
- package/dist/dashboard/server/routes/messaging.routes.js +307 -0
- package/dist/dashboard/server/routes/metrics.routes.d.ts +10 -0
- package/dist/dashboard/server/routes/metrics.routes.js +335 -0
- package/dist/dashboard/server/routes/scripts.routes.d.ts +9 -0
- package/dist/dashboard/server/routes/scripts.routes.js +84 -0
- package/dist/dashboard/server/routes/sqlite.routes.d.ts +9 -0
- package/dist/dashboard/server/routes/sqlite.routes.js +570 -0
- package/dist/dashboard/server/routes/status.routes.d.ts +7 -0
- package/dist/dashboard/server/routes/status.routes.js +179 -0
- package/dist/dashboard/server/routes/synthetic.routes.d.ts +7 -0
- package/dist/dashboard/server/routes/synthetic.routes.js +197 -0
- package/dist/dashboard/server/routes/tools.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/tools.routes.js +47 -0
- package/dist/dashboard/server/routes/usage.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/usage.routes.js +26 -0
- package/dist/dashboard/server/wsInit.d.ts +16 -0
- package/dist/dashboard/server/wsInit.js +35 -0
- package/dist/externalClientLib.d.ts +1 -0
- package/dist/externalClientLib.js +2 -0
- package/dist/minimal/index.d.ts +1 -0
- package/dist/minimal/index.js +140 -0
- package/dist/models/SessionPersistence.d.ts +115 -0
- package/dist/models/SessionPersistence.js +66 -0
- package/dist/models/instruction.d.ts +46 -0
- package/dist/models/instruction.js +2 -0
- package/dist/perf/benchmark.d.ts +1 -0
- package/dist/perf/benchmark.js +50 -0
- package/dist/portableClientWrapper.d.ts +1 -0
- package/dist/portableClientWrapper.js +2 -0
- package/dist/schemas/index.d.ts +132 -0
- package/dist/schemas/index.js +372 -0
- package/dist/scripts/runPerformanceBaseline.d.ts +1 -0
- package/dist/scripts/runPerformanceBaseline.js +17 -0
- package/dist/server/backgroundServicesStartup.d.ts +3 -0
- package/dist/server/backgroundServicesStartup.js +51 -0
- package/dist/server/handshakeManager.d.ts +25 -0
- package/dist/server/handshakeManager.js +470 -0
- package/dist/server/index-server.d.ts +38 -0
- package/dist/server/index-server.js +620 -0
- package/dist/server/multiInstanceStartup.d.ts +6 -0
- package/dist/server/multiInstanceStartup.js +132 -0
- package/dist/server/registry.d.ts +44 -0
- package/dist/server/registry.js +236 -0
- package/dist/server/sdkServer.d.ts +8 -0
- package/dist/server/sdkServer.js +299 -0
- package/dist/server/shutdownGuard.d.ts +41 -0
- package/dist/server/shutdownGuard.js +52 -0
- package/dist/server/startupDiagnostics.d.ts +2 -0
- package/dist/server/startupDiagnostics.js +33 -0
- package/dist/server/thin-client.d.ts +22 -0
- package/dist/server/thin-client.js +111 -0
- package/dist/server/transport.d.ts +41 -0
- package/dist/server/transport.js +312 -0
- package/dist/server/transportFactory.d.ts +21 -0
- package/dist/server/transportFactory.js +429 -0
- package/dist/services/atomicFs.d.ts +22 -0
- package/dist/services/atomicFs.js +103 -0
- package/dist/services/auditLog.d.ts +38 -0
- package/dist/services/auditLog.js +142 -0
- package/dist/services/autoBackup.d.ts +14 -0
- package/dist/services/autoBackup.js +171 -0
- package/dist/services/autoSplit.d.ts +32 -0
- package/dist/services/autoSplit.js +113 -0
- package/dist/services/backupZip.d.ts +25 -0
- package/dist/services/backupZip.js +112 -0
- package/dist/services/bootstrapGating.d.ts +123 -0
- package/dist/services/bootstrapGating.js +221 -0
- package/dist/services/canonical.d.ts +23 -0
- package/dist/services/canonical.js +65 -0
- package/dist/services/categoryRules.d.ts +7 -0
- package/dist/services/categoryRules.js +37 -0
- package/dist/services/classificationService.d.ts +42 -0
- package/dist/services/classificationService.js +168 -0
- package/dist/services/embeddingService.d.ts +62 -0
- package/dist/services/embeddingService.js +264 -0
- package/dist/services/errors.d.ts +22 -0
- package/dist/services/errors.js +31 -0
- package/dist/services/featureFlags.d.ts +25 -0
- package/dist/services/featureFlags.js +89 -0
- package/dist/services/features.d.ts +13 -0
- package/dist/services/features.js +35 -0
- package/dist/services/handlers/instructions.add.d.ts +1 -0
- package/dist/services/handlers/instructions.add.js +510 -0
- package/dist/services/handlers/instructions.groom.d.ts +1 -0
- package/dist/services/handlers/instructions.groom.js +575 -0
- package/dist/services/handlers/instructions.import.d.ts +1 -0
- package/dist/services/handlers/instructions.import.js +205 -0
- package/dist/services/handlers/instructions.patch.d.ts +1 -0
- package/dist/services/handlers/instructions.patch.js +121 -0
- package/dist/services/handlers/instructions.query.d.ts +159 -0
- package/dist/services/handlers/instructions.query.js +469 -0
- package/dist/services/handlers/instructions.reload.d.ts +1 -0
- package/dist/services/handlers/instructions.reload.js +13 -0
- package/dist/services/handlers/instructions.remove.d.ts +1 -0
- package/dist/services/handlers/instructions.remove.js +122 -0
- package/dist/services/handlers/instructions.shared.d.ts +32 -0
- package/dist/services/handlers/instructions.shared.js +91 -0
- package/dist/services/handlers.activation.d.ts +1 -0
- package/dist/services/handlers.activation.js +203 -0
- package/dist/services/handlers.bootstrap.d.ts +1 -0
- package/dist/services/handlers.bootstrap.js +38 -0
- package/dist/services/handlers.dashboardConfig.d.ts +34 -0
- package/dist/services/handlers.dashboardConfig.js +110 -0
- package/dist/services/handlers.diagnostics.d.ts +1 -0
- package/dist/services/handlers.diagnostics.js +64 -0
- package/dist/services/handlers.feedback.d.ts +15 -0
- package/dist/services/handlers.feedback.js +389 -0
- package/dist/services/handlers.gates.d.ts +1 -0
- package/dist/services/handlers.gates.js +47 -0
- package/dist/services/handlers.graph.d.ts +53 -0
- package/dist/services/handlers.graph.js +231 -0
- package/dist/services/handlers.help.d.ts +1 -0
- package/dist/services/handlers.help.js +119 -0
- package/dist/services/handlers.instructionSchema.d.ts +1 -0
- package/dist/services/handlers.instructionSchema.js +227 -0
- package/dist/services/handlers.instructions.d.ts +8 -0
- package/dist/services/handlers.instructions.js +14 -0
- package/dist/services/handlers.instructionsDiagnostics.d.ts +1 -0
- package/dist/services/handlers.instructionsDiagnostics.js +14 -0
- package/dist/services/handlers.integrity.d.ts +1 -0
- package/dist/services/handlers.integrity.js +35 -0
- package/dist/services/handlers.manifest.d.ts +1 -0
- package/dist/services/handlers.manifest.js +24 -0
- package/dist/services/handlers.messaging.d.ts +12 -0
- package/dist/services/handlers.messaging.js +203 -0
- package/dist/services/handlers.metrics.d.ts +1 -0
- package/dist/services/handlers.metrics.js +43 -0
- package/dist/services/handlers.promote.d.ts +1 -0
- package/dist/services/handlers.promote.js +326 -0
- package/dist/services/handlers.prompt.d.ts +1 -0
- package/dist/services/handlers.prompt.js +7 -0
- package/dist/services/handlers.search.d.ts +69 -0
- package/dist/services/handlers.search.js +669 -0
- package/dist/services/handlers.testPrimitive.d.ts +1 -0
- package/dist/services/handlers.testPrimitive.js +5 -0
- package/dist/services/handlers.trace.d.ts +1 -0
- package/dist/services/handlers.trace.js +35 -0
- package/dist/services/handlers.usage.d.ts +1 -0
- package/dist/services/handlers.usage.js +11 -0
- package/dist/services/hotScore.d.ts +137 -0
- package/dist/services/hotScore.js +244 -0
- package/dist/services/indexContext.d.ts +117 -0
- package/dist/services/indexContext.js +989 -0
- package/dist/services/indexLoader.d.ts +44 -0
- package/dist/services/indexLoader.js +920 -0
- package/dist/services/indexRepository.d.ts +32 -0
- package/dist/services/indexRepository.js +71 -0
- package/dist/services/indexingService.d.ts +1 -0
- package/dist/services/indexingService.js +2 -0
- package/dist/services/instructions.dispatcher.d.ts +1 -0
- package/dist/services/instructions.dispatcher.js +231 -0
- package/dist/services/logPrefix.d.ts +1 -0
- package/dist/services/logPrefix.js +30 -0
- package/dist/services/logger.d.ts +52 -0
- package/dist/services/logger.js +268 -0
- package/dist/services/manifestManager.d.ts +82 -0
- package/dist/services/manifestManager.js +200 -0
- package/dist/services/messaging/agentMailbox.d.ts +60 -0
- package/dist/services/messaging/agentMailbox.js +353 -0
- package/dist/services/messaging/messagingPersistence.d.ts +20 -0
- package/dist/services/messaging/messagingPersistence.js +111 -0
- package/dist/services/messaging/messagingTypes.d.ts +150 -0
- package/dist/services/messaging/messagingTypes.js +66 -0
- package/dist/services/ownershipService.d.ts +1 -0
- package/dist/services/ownershipService.js +36 -0
- package/dist/services/performanceBaseline.d.ts +19 -0
- package/dist/services/performanceBaseline.js +210 -0
- package/dist/services/preflight.d.ts +12 -0
- package/dist/services/preflight.js +79 -0
- package/dist/services/promptReviewService.d.ts +44 -0
- package/dist/services/promptReviewService.js +101 -0
- package/dist/services/responseEnvelope.d.ts +6 -0
- package/dist/services/responseEnvelope.js +25 -0
- package/dist/services/seedBootstrap.d.ts +34 -0
- package/dist/services/seedBootstrap.js +259 -0
- package/dist/services/storage/factory.d.ts +17 -0
- package/dist/services/storage/factory.js +35 -0
- package/dist/services/storage/hashUtils.d.ts +11 -0
- package/dist/services/storage/hashUtils.js +35 -0
- package/dist/services/storage/index.d.ts +12 -0
- package/dist/services/storage/index.js +18 -0
- package/dist/services/storage/jsonFileStore.d.ts +32 -0
- package/dist/services/storage/jsonFileStore.js +241 -0
- package/dist/services/storage/migrationEngine.d.ts +35 -0
- package/dist/services/storage/migrationEngine.js +93 -0
- package/dist/services/storage/sqliteMessageStore.d.ts +53 -0
- package/dist/services/storage/sqliteMessageStore.js +146 -0
- package/dist/services/storage/sqliteSchema.d.ts +12 -0
- package/dist/services/storage/sqliteSchema.js +123 -0
- package/dist/services/storage/sqliteStore.d.ts +42 -0
- package/dist/services/storage/sqliteStore.js +361 -0
- package/dist/services/storage/sqliteUsageStore.d.ts +35 -0
- package/dist/services/storage/sqliteUsageStore.js +94 -0
- package/dist/services/storage/types.d.ts +171 -0
- package/dist/services/storage/types.js +12 -0
- package/dist/services/toolHandlers.d.ts +23 -0
- package/dist/services/toolHandlers.js +50 -0
- package/dist/services/toolRegistry.d.ts +20 -0
- package/dist/services/toolRegistry.js +490 -0
- package/dist/services/toolRegistry.zod.d.ts +10 -0
- package/dist/services/toolRegistry.zod.js +325 -0
- package/dist/services/tracing.d.ts +26 -0
- package/dist/services/tracing.js +260 -0
- package/dist/services/usageBuckets.d.ts +161 -0
- package/dist/services/usageBuckets.js +364 -0
- package/dist/services/validationService.d.ts +38 -0
- package/dist/services/validationService.js +125 -0
- package/dist/utils/BufferRing.d.ts +203 -0
- package/dist/utils/BufferRing.js +551 -0
- package/dist/utils/BufferRingExamples.d.ts +55 -0
- package/dist/utils/BufferRingExamples.js +188 -0
- package/dist/utils/envUtils.d.ts +42 -0
- package/dist/utils/envUtils.js +80 -0
- package/dist/utils/memoryMonitor.d.ts +83 -0
- package/dist/utils/memoryMonitor.js +275 -0
- package/dist/versioning/schemaVersion.d.ts +6 -0
- package/dist/versioning/schemaVersion.js +94 -0
- package/package.json +139 -0
- package/schemas/README.md +13 -0
- package/schemas/feedback-entry.schema.json +27 -0
- package/schemas/graph-export-v2.schema.json +60 -0
- package/schemas/index-server.code-schema.json +40670 -0
- package/schemas/instruction.schema.json +262 -0
- package/schemas/json-schema/SessionPersistence-persisted-admin-session.schema.json +54 -0
- package/schemas/json-schema/SessionPersistence-persisted-session-history-entry.schema.json +51 -0
- package/schemas/json-schema/SessionPersistence-persisted-web-socket-connection.schema.json +54 -0
- package/schemas/json-schema/SessionPersistence-session-persistence-config.schema.json +110 -0
- package/schemas/json-schema/SessionPersistence-session-persistence-data.schema.json +229 -0
- package/schemas/json-schema/SessionPersistence-session-persistence-manifest.schema.json +109 -0
- package/schemas/json-schema/SessionPersistence-session-persistence-metadata.schema.json +55 -0
- package/schemas/json-schema/instruction-audience-scope.schema.json +14 -0
- package/schemas/json-schema/instruction-content-type.schema.json +17 -0
- package/schemas/json-schema/instruction-instruction-entry.schema.json +210 -0
- package/schemas/json-schema/instruction-requirement-level.schema.json +16 -0
- package/schemas/manifest.json +78 -0
- package/schemas/manifest.schema.json +33 -0
- package/schemas/usage-batch.schema.json +16 -0
- package/schemas/usage-buckets.schema.json +30 -0
- package/schemas/usage-event.schema.json +17 -0
- package/scripts/copy-dashboard-assets.mjs +170 -0
- package/scripts/dist/README.md +15 -0
- package/scripts/setup-hooks.cjs +28 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Embeddings Routes
|
|
4
|
+
* Route: GET /embeddings/projection — PCA-project embeddings to 2D for visualization.
|
|
5
|
+
*/
|
|
6
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
7
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
8
|
+
};
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.createEmbeddingsRoutes = createEmbeddingsRoutes;
|
|
11
|
+
const express_1 = require("express");
|
|
12
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
13
|
+
const runtimeConfig_js_1 = require("../../../config/runtimeConfig.js");
|
|
14
|
+
const embeddingService_js_1 = require("../../../services/embeddingService.js");
|
|
15
|
+
const adminAuth_js_1 = require("./adminAuth.js");
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Category derivation from instruction ID (shared rules)
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
const categoryRules_js_1 = require("../../../services/categoryRules.js");
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// PCA via power iteration (no dependencies)
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
function mean(vectors) {
|
|
24
|
+
const n = vectors.length;
|
|
25
|
+
const d = vectors[0].length;
|
|
26
|
+
const m = new Array(d).fill(0);
|
|
27
|
+
for (const v of vectors)
|
|
28
|
+
for (let i = 0; i < d; i++)
|
|
29
|
+
m[i] += v[i];
|
|
30
|
+
for (let i = 0; i < d; i++)
|
|
31
|
+
m[i] /= n;
|
|
32
|
+
return m;
|
|
33
|
+
}
|
|
34
|
+
function subtract(a, b) {
|
|
35
|
+
return a.map((v, i) => v - b[i]);
|
|
36
|
+
}
|
|
37
|
+
function dot(a, b) {
|
|
38
|
+
let s = 0;
|
|
39
|
+
for (let i = 0; i < a.length; i++)
|
|
40
|
+
s += a[i] * b[i];
|
|
41
|
+
return s;
|
|
42
|
+
}
|
|
43
|
+
function norm(v) {
|
|
44
|
+
return Math.sqrt(dot(v, v));
|
|
45
|
+
}
|
|
46
|
+
function scale(v, s) {
|
|
47
|
+
return v.map(x => x * s);
|
|
48
|
+
}
|
|
49
|
+
/** Compute the top principal component via power iteration. */
|
|
50
|
+
function powerIteration(centered, dims, iterations = 100) {
|
|
51
|
+
// random init
|
|
52
|
+
let pc = Array.from({ length: dims }, () => Math.random() - 0.5);
|
|
53
|
+
const n = norm(pc);
|
|
54
|
+
if (n > 0)
|
|
55
|
+
pc = scale(pc, 1 / n);
|
|
56
|
+
for (let iter = 0; iter < iterations; iter++) {
|
|
57
|
+
const newPc = new Array(dims).fill(0);
|
|
58
|
+
for (const row of centered) {
|
|
59
|
+
const d = dot(row, pc);
|
|
60
|
+
for (let j = 0; j < dims; j++)
|
|
61
|
+
newPc[j] += d * row[j];
|
|
62
|
+
}
|
|
63
|
+
const len = norm(newPc);
|
|
64
|
+
if (len === 0)
|
|
65
|
+
break;
|
|
66
|
+
pc = scale(newPc, 1 / len);
|
|
67
|
+
}
|
|
68
|
+
return pc;
|
|
69
|
+
}
|
|
70
|
+
/** Deflate: remove component along given direction */
|
|
71
|
+
function deflate(centered, pc) {
|
|
72
|
+
return centered.map(row => {
|
|
73
|
+
const proj = dot(row, pc);
|
|
74
|
+
return row.map((v, i) => v - proj * pc[i]);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** PCA project to 2D */
|
|
78
|
+
function pcaProject(vectors) {
|
|
79
|
+
if (vectors.length === 0)
|
|
80
|
+
return [];
|
|
81
|
+
const dims = vectors[0].length;
|
|
82
|
+
if (vectors.length === 1) {
|
|
83
|
+
return [{ x: 0, y: 0 }];
|
|
84
|
+
}
|
|
85
|
+
const mu = mean(vectors);
|
|
86
|
+
let centered = vectors.map(v => subtract(v, mu));
|
|
87
|
+
const pc1 = powerIteration(centered, dims);
|
|
88
|
+
centered = deflate(centered, pc1);
|
|
89
|
+
const pc2 = powerIteration(centered, dims);
|
|
90
|
+
return vectors.map(v => {
|
|
91
|
+
const c = subtract(v, mu);
|
|
92
|
+
return { x: dot(c, pc1), y: dot(c, pc2) };
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
// Cosine similarity stats
|
|
97
|
+
// ---------------------------------------------------------------------------
|
|
98
|
+
function cosineSimilarity(a, b) {
|
|
99
|
+
const na = norm(a);
|
|
100
|
+
const nb = norm(b);
|
|
101
|
+
if (na === 0 || nb === 0)
|
|
102
|
+
return 0;
|
|
103
|
+
return dot(a, b) / (na * nb);
|
|
104
|
+
}
|
|
105
|
+
function computeStats(ids, vectors, topK = 10) {
|
|
106
|
+
let sumSim = 0;
|
|
107
|
+
let minSim = 1;
|
|
108
|
+
let maxSim = -1;
|
|
109
|
+
let pairCount = 0;
|
|
110
|
+
let sumNorm = 0;
|
|
111
|
+
const topPairs = [];
|
|
112
|
+
for (let i = 0; i < vectors.length; i++) {
|
|
113
|
+
sumNorm += norm(vectors[i]);
|
|
114
|
+
}
|
|
115
|
+
// Sample up to 5000 pairs for large collections
|
|
116
|
+
const maxPairs = 5000;
|
|
117
|
+
const allPairs = (vectors.length * (vectors.length - 1)) / 2;
|
|
118
|
+
const sampleRate = allPairs > maxPairs ? maxPairs / allPairs : 1;
|
|
119
|
+
for (let i = 0; i < vectors.length; i++) {
|
|
120
|
+
for (let j = i + 1; j < vectors.length; j++) {
|
|
121
|
+
if (sampleRate < 1 && Math.random() > sampleRate)
|
|
122
|
+
continue;
|
|
123
|
+
const sim = cosineSimilarity(vectors[i], vectors[j]);
|
|
124
|
+
sumSim += sim;
|
|
125
|
+
if (sim < minSim)
|
|
126
|
+
minSim = sim;
|
|
127
|
+
if (sim > maxSim)
|
|
128
|
+
maxSim = sim;
|
|
129
|
+
pairCount++;
|
|
130
|
+
if (topPairs.length < topK || sim > topPairs[topPairs.length - 1].similarity) {
|
|
131
|
+
topPairs.push({ a: ids[i], b: ids[j], similarity: Math.round(sim * 1000) / 1000 });
|
|
132
|
+
topPairs.sort((a, b) => b.similarity - a.similarity);
|
|
133
|
+
if (topPairs.length > topK)
|
|
134
|
+
topPairs.pop();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
stats: {
|
|
140
|
+
avgCosineSim: pairCount > 0 ? Math.round((sumSim / pairCount) * 1000) / 1000 : 0,
|
|
141
|
+
minCosineSim: pairCount > 0 ? Math.round(minSim * 1000) / 1000 : 0,
|
|
142
|
+
maxCosineSim: pairCount > 0 ? Math.round(maxSim * 1000) / 1000 : 0,
|
|
143
|
+
avgNorm: vectors.length > 0 ? Math.round((sumNorm / vectors.length) * 1000) / 1000 : 0,
|
|
144
|
+
},
|
|
145
|
+
similarPairs: topPairs,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
// Route factory
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
function createEmbeddingsRoutes(embeddingPathOverride) {
|
|
152
|
+
const router = (0, express_1.Router)();
|
|
153
|
+
router.get('/embeddings/projection', (_req, res) => {
|
|
154
|
+
try {
|
|
155
|
+
const embeddingPath = embeddingPathOverride ?? (0, runtimeConfig_js_1.getRuntimeConfig)().semantic.embeddingPath ?? '';
|
|
156
|
+
if (!embeddingPath || !node_fs_1.default.existsSync(embeddingPath)) {
|
|
157
|
+
return res.status(404).json({
|
|
158
|
+
success: false,
|
|
159
|
+
error: 'Embeddings file not found',
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
const raw = node_fs_1.default.readFileSync(embeddingPath, 'utf-8');
|
|
163
|
+
const data = JSON.parse(raw);
|
|
164
|
+
const ids = Object.keys(data.embeddings);
|
|
165
|
+
const vectors = ids.map(id => data.embeddings[id]);
|
|
166
|
+
if (ids.length === 0) {
|
|
167
|
+
return res.json({
|
|
168
|
+
success: true,
|
|
169
|
+
count: 0,
|
|
170
|
+
dimensions: 0,
|
|
171
|
+
model: data.modelName,
|
|
172
|
+
points: [],
|
|
173
|
+
stats: { avgCosineSim: 0, minCosineSim: 0, maxCosineSim: 0, avgNorm: 0 },
|
|
174
|
+
similarPairs: [],
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
const dims = vectors[0].length;
|
|
178
|
+
const projected = pcaProject(vectors);
|
|
179
|
+
const points = ids.map((id, i) => ({
|
|
180
|
+
id,
|
|
181
|
+
x: Math.round(projected[i].x * 10000) / 10000,
|
|
182
|
+
y: Math.round(projected[i].y * 10000) / 10000,
|
|
183
|
+
category: (0, categoryRules_js_1.deriveCategory)(id),
|
|
184
|
+
norm: Math.round(norm(vectors[i]) * 10000) / 10000,
|
|
185
|
+
}));
|
|
186
|
+
const { stats, similarPairs } = computeStats(ids, vectors);
|
|
187
|
+
return res.json({
|
|
188
|
+
success: true,
|
|
189
|
+
count: ids.length,
|
|
190
|
+
dimensions: dims,
|
|
191
|
+
model: data.modelName,
|
|
192
|
+
points,
|
|
193
|
+
stats,
|
|
194
|
+
similarPairs,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
return res.status(500).json({
|
|
199
|
+
success: false,
|
|
200
|
+
error: 'Failed to compute projection',
|
|
201
|
+
message: err.message,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
// POST /embeddings/compute — trigger embedding computation for all instructions
|
|
206
|
+
router.post('/embeddings/compute', adminAuth_js_1.dashboardAdminAuth, async (_req, res) => {
|
|
207
|
+
try {
|
|
208
|
+
const config = (0, runtimeConfig_js_1.getRuntimeConfig)();
|
|
209
|
+
const sem = config.semantic;
|
|
210
|
+
if (!sem.enabled) {
|
|
211
|
+
return res.status(400).json({
|
|
212
|
+
success: false,
|
|
213
|
+
error: 'Semantic embeddings are disabled',
|
|
214
|
+
hint: 'Set INDEX_SERVER_SEMANTIC_ENABLED=1 and restart the server',
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
const state = res.locals.indexState;
|
|
218
|
+
if (!state || !state.list || state.list.length === 0) {
|
|
219
|
+
return res.status(400).json({
|
|
220
|
+
success: false,
|
|
221
|
+
error: 'No instructions loaded in index',
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
const start = performance.now();
|
|
225
|
+
const embeddings = await (0, embeddingService_js_1.getInstructionEmbeddings)(state.list, state.hash, sem.embeddingPath, sem.model, sem.cacheDir, sem.device, sem.localOnly);
|
|
226
|
+
const elapsed = (performance.now() - start).toFixed(0);
|
|
227
|
+
const count = Object.keys(embeddings).length;
|
|
228
|
+
return res.json({
|
|
229
|
+
success: true,
|
|
230
|
+
count,
|
|
231
|
+
model: sem.model,
|
|
232
|
+
device: sem.device,
|
|
233
|
+
elapsedMs: Number(elapsed),
|
|
234
|
+
embeddingPath: sem.embeddingPath,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
return res.status(500).json({
|
|
239
|
+
success: false,
|
|
240
|
+
error: 'Failed to compute embeddings',
|
|
241
|
+
message: err.message,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
return router;
|
|
246
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Graph Routes
|
|
4
|
+
* Routes: GET /graph/mermaid, GET /graph/categories, GET /graph/instructions, GET /graph/relations
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.createGraphRoutes = createGraphRoutes;
|
|
8
|
+
const express_1 = require("express");
|
|
9
|
+
const handlers_graph_js_1 = require("../../../services/handlers.graph.js");
|
|
10
|
+
const runtimeConfig_js_1 = require("../../../config/runtimeConfig.js");
|
|
11
|
+
function createGraphRoutes() {
|
|
12
|
+
const router = (0, express_1.Router)();
|
|
13
|
+
/**
|
|
14
|
+
* GET /api/graph/mermaid - Returns mermaid representation of the instruction graph.
|
|
15
|
+
* Query params:
|
|
16
|
+
* enrich=1 -> include enriched schema (v2) data generation path
|
|
17
|
+
* categories=1 -> include explicit category nodes
|
|
18
|
+
* usage=1 -> include usageCount when available
|
|
19
|
+
* edgeTypes=a,b -> restrict edge types (comma separated)
|
|
20
|
+
*/
|
|
21
|
+
router.get('/graph/mermaid', (req, res) => {
|
|
22
|
+
try {
|
|
23
|
+
const { enrich, categories, usage, edgeTypes, selectedCategories, selectedIds } = req.query;
|
|
24
|
+
const includeEdgeTypes = edgeTypes ? edgeTypes.split(',').filter(Boolean) : undefined;
|
|
25
|
+
const t0 = Date.now();
|
|
26
|
+
try {
|
|
27
|
+
// eslint-disable-next-line no-console
|
|
28
|
+
console.debug('[graph/mermaid][start]', `enrich=${enrich}`, `categories=${categories}`, `usage=${usage}`, `edgeTypes=${edgeTypes || ''}`, `selCats=${selectedCategories || ''}`, `selIds=${selectedIds || ''}`); // lgtm[js/log-injection] — query params for debugging
|
|
29
|
+
}
|
|
30
|
+
catch { /* ignore diag logging errors */ }
|
|
31
|
+
const graph = (0, handlers_graph_js_1.buildGraph)({
|
|
32
|
+
enrich: enrich === '1' || enrich === 'true',
|
|
33
|
+
includeCategoryNodes: categories === '1' || categories === 'true',
|
|
34
|
+
includeUsage: usage === '1' || usage === 'true',
|
|
35
|
+
includeEdgeTypes,
|
|
36
|
+
format: 'mermaid'
|
|
37
|
+
});
|
|
38
|
+
if (!graph.mermaid) {
|
|
39
|
+
return res.status(500).json({ success: false, error: 'failed_to_generate_mermaid' });
|
|
40
|
+
}
|
|
41
|
+
let mermaidSource = graph.mermaid;
|
|
42
|
+
const catFilter = selectedCategories?.split(',').filter(Boolean) || [];
|
|
43
|
+
const idFilter = selectedIds?.split(',').filter(Boolean) || [];
|
|
44
|
+
let filteredNodeCount;
|
|
45
|
+
let filteredEdgeCount;
|
|
46
|
+
let scoped = false;
|
|
47
|
+
let keptIdsSize = 0;
|
|
48
|
+
if ((catFilter.length || idFilter.length) && mermaidSource) {
|
|
49
|
+
try {
|
|
50
|
+
const keepIds = new Set();
|
|
51
|
+
for (const id of idFilter)
|
|
52
|
+
keepIds.add(id);
|
|
53
|
+
const wantCategoryNodes = (categories === '1' || categories === 'true');
|
|
54
|
+
if (catFilter.length) {
|
|
55
|
+
const catSet = new Set(catFilter.map(c => c.toLowerCase()));
|
|
56
|
+
if (wantCategoryNodes) {
|
|
57
|
+
for (const c of catFilter) {
|
|
58
|
+
keepIds.add(`category:${c}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (graph.meta.graphSchemaVersion === 2) {
|
|
62
|
+
for (const nodeRaw of graph.nodes) {
|
|
63
|
+
const nodeCats = nodeRaw.categories;
|
|
64
|
+
if (Array.isArray(nodeCats) && nodeCats.some(c => catSet.has(c.toLowerCase()))) {
|
|
65
|
+
keepIds.add(nodeRaw.id);
|
|
66
|
+
if (wantCategoryNodes) {
|
|
67
|
+
for (const c of nodeCats) {
|
|
68
|
+
if (catSet.has(c.toLowerCase()))
|
|
69
|
+
keepIds.add(`category:${c}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (keepIds.size) {
|
|
77
|
+
let frontmatterBlock = '';
|
|
78
|
+
let remainder = mermaidSource;
|
|
79
|
+
if (remainder.startsWith('---\n')) {
|
|
80
|
+
const fmMatch = /^---\n[\s\S]*?\n---\n/.exec(remainder);
|
|
81
|
+
if (fmMatch) {
|
|
82
|
+
frontmatterBlock = fmMatch[0];
|
|
83
|
+
remainder = remainder.slice(fmMatch[0].length);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const lines = remainder.split(/\r?\n/);
|
|
87
|
+
const directiveIdx = lines.findIndex(l => /^\s*(flowchart|graph)\b/i.test(l));
|
|
88
|
+
let directiveLine = '';
|
|
89
|
+
if (directiveIdx >= 0) {
|
|
90
|
+
directiveLine = lines[directiveIdx];
|
|
91
|
+
}
|
|
92
|
+
const nodeIdPattern = Array.from(keepIds).map(id => id.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|');
|
|
93
|
+
const nodeRegex = new RegExp(`^(\\s*)(${nodeIdPattern})\\[`);
|
|
94
|
+
const edgeRegex = new RegExp(`^(.*)(${nodeIdPattern})(.*)(${nodeIdPattern})(.*)$`);
|
|
95
|
+
const filtered = [];
|
|
96
|
+
const styleRegexes = [
|
|
97
|
+
/^\s*classDef\s+/i,
|
|
98
|
+
/^\s*style\s+[A-Za-z0-9:_-]+\s+/i,
|
|
99
|
+
/^\s*class\s+[A-Za-z0-9:_-]+\s+/i,
|
|
100
|
+
/^\s*linkStyle\s+\d+/i
|
|
101
|
+
];
|
|
102
|
+
for (const ln of lines) {
|
|
103
|
+
if (!ln)
|
|
104
|
+
continue;
|
|
105
|
+
if (directiveLine && ln === directiveLine) {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const trimmed = ln.trim();
|
|
109
|
+
if (trimmed.startsWith('%%')) {
|
|
110
|
+
filtered.push(ln);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (styleRegexes.some(r => r.test(trimmed))) {
|
|
114
|
+
filtered.push(ln);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (nodeRegex.test(ln) || edgeRegex.test(ln))
|
|
118
|
+
filtered.push(ln);
|
|
119
|
+
}
|
|
120
|
+
const parts = [];
|
|
121
|
+
if (frontmatterBlock)
|
|
122
|
+
parts.push(frontmatterBlock.trimEnd());
|
|
123
|
+
if (directiveLine)
|
|
124
|
+
parts.push(directiveLine);
|
|
125
|
+
parts.push(...filtered);
|
|
126
|
+
mermaidSource = parts.join('\n');
|
|
127
|
+
if ((0, runtimeConfig_js_1.getRuntimeConfig)().logging.verbose) {
|
|
128
|
+
// eslint-disable-next-line no-console
|
|
129
|
+
console.debug('[graph/mermaid][filter:new]', { selectedIds: idFilter.length, selectedCategories: catFilter.length, kept: keepIds.size, totalLines: lines.length, emittedLines: parts.length });
|
|
130
|
+
}
|
|
131
|
+
keptIdsSize = keepIds.size;
|
|
132
|
+
scoped = true;
|
|
133
|
+
try {
|
|
134
|
+
const nodeLineRegex = /^(\s*)([A-Za-z0-9:_-]+)\[[^\]]*\]/; // lgtm[js/bad-tag-filter] — IDs escaped with regex special char replacement
|
|
135
|
+
const edgeLineRegex = /-->|===|~~>|\|-/;
|
|
136
|
+
let n = 0, eCnt = 0;
|
|
137
|
+
for (const ln of filtered) {
|
|
138
|
+
if (nodeLineRegex.test(ln))
|
|
139
|
+
n++;
|
|
140
|
+
else if (edgeLineRegex.test(ln))
|
|
141
|
+
eCnt++;
|
|
142
|
+
}
|
|
143
|
+
filteredNodeCount = n;
|
|
144
|
+
filteredEdgeCount = eCnt;
|
|
145
|
+
}
|
|
146
|
+
catch { /* ignore count derivation errors */ }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
catch (filterErr) {
|
|
150
|
+
console.warn('[graph/mermaid][filter-failed]', filterErr);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
// eslint-disable-next-line no-console
|
|
155
|
+
console.debug('[graph/mermaid][ok]', { ms: Date.now() - t0, nodes: graph.meta?.nodeCount, edges: graph.meta?.edgeCount, bytes: mermaidSource.length });
|
|
156
|
+
}
|
|
157
|
+
catch { /* ignore diag logging errors */ }
|
|
158
|
+
let metaOut = graph.meta;
|
|
159
|
+
if (scoped && graph.meta) {
|
|
160
|
+
try {
|
|
161
|
+
const base = { ...graph.meta };
|
|
162
|
+
const augmented = base;
|
|
163
|
+
if (typeof filteredNodeCount === 'number')
|
|
164
|
+
augmented.nodeCount = filteredNodeCount;
|
|
165
|
+
if (typeof filteredEdgeCount === 'number')
|
|
166
|
+
augmented.edgeCount = filteredEdgeCount;
|
|
167
|
+
augmented.scoped = true;
|
|
168
|
+
augmented.keptIds = keptIdsSize;
|
|
169
|
+
metaOut = augmented;
|
|
170
|
+
}
|
|
171
|
+
catch { /* ignore meta cloning issues */ }
|
|
172
|
+
}
|
|
173
|
+
res.json({ success: true, meta: metaOut, mermaid: mermaidSource });
|
|
174
|
+
}
|
|
175
|
+
catch (err) {
|
|
176
|
+
const e = err;
|
|
177
|
+
try {
|
|
178
|
+
// eslint-disable-next-line no-console
|
|
179
|
+
console.warn('[graph/mermaid][error]', e.message);
|
|
180
|
+
}
|
|
181
|
+
catch { /* ignore diag logging errors */ }
|
|
182
|
+
res.status(500).json({ success: false, error: 'Failed to generate mermaid graph' });
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
/**
|
|
186
|
+
* GET /api/graph/categories
|
|
187
|
+
* Returns list of unique categories with instruction counts.
|
|
188
|
+
*/
|
|
189
|
+
router.get('/graph/categories', (_req, res) => {
|
|
190
|
+
try {
|
|
191
|
+
const st = res.locals.indexState;
|
|
192
|
+
const map = new Map();
|
|
193
|
+
for (const inst of st.list) {
|
|
194
|
+
const cats = Array.isArray(inst.categories) ? inst.categories : [];
|
|
195
|
+
for (const c of cats) {
|
|
196
|
+
map.set(c, (map.get(c) || 0) + 1);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const categories = [...map.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([id, count]) => ({ id, count }));
|
|
200
|
+
res.json({ success: true, categories, total: categories.length, timestamp: Date.now() });
|
|
201
|
+
}
|
|
202
|
+
catch (err) {
|
|
203
|
+
console.error('[graph/categories] Error:', err);
|
|
204
|
+
res.status(500).json({ success: false, error: 'Failed to get categories' });
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
/**
|
|
208
|
+
* GET /api/graph/instructions?categories=a,b&limit=100
|
|
209
|
+
* Returns lightweight instruction list filtered by categories (OR semantics).
|
|
210
|
+
*/
|
|
211
|
+
router.get('/graph/instructions', (req, res) => {
|
|
212
|
+
try {
|
|
213
|
+
const st = res.locals.indexState;
|
|
214
|
+
const catsParam = req.query.categories || '';
|
|
215
|
+
const filterCats = catsParam ? catsParam.split(',').filter(Boolean) : [];
|
|
216
|
+
const limitRaw = parseInt(req.query.limit || '0', 10);
|
|
217
|
+
const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? limitRaw : 500;
|
|
218
|
+
let instructions = st.list.slice().sort((a, b) => a.id.localeCompare(b.id));
|
|
219
|
+
if (filterCats.length) {
|
|
220
|
+
const set = new Set(filterCats.map(c => c.toLowerCase()));
|
|
221
|
+
instructions = instructions.filter(i => (i.categories || []).some(c => set.has(c.toLowerCase())));
|
|
222
|
+
}
|
|
223
|
+
instructions = instructions.slice(0, limit);
|
|
224
|
+
const flat = instructions.map(i => ({ id: i.id, primaryCategory: i.primaryCategory || i.categories?.[0], categories: i.categories || [] }));
|
|
225
|
+
res.json({ success: true, instructions: flat, count: flat.length, filtered: !!filterCats.length, timestamp: Date.now() });
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
console.error('[graph/instructions] Error:', err);
|
|
229
|
+
res.status(500).json({ success: false, error: 'Failed to get instructions' });
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
/**
|
|
233
|
+
* GET /api/graph/relations?instructions=id1,id2
|
|
234
|
+
* Returns minimal edges among the provided instruction ids plus category linkage.
|
|
235
|
+
*/
|
|
236
|
+
router.get('/graph/relations', (req, res) => {
|
|
237
|
+
try {
|
|
238
|
+
const idsParam = req.query.instructions || '';
|
|
239
|
+
const ids = idsParam.split(',').filter(Boolean);
|
|
240
|
+
if (!ids.length) {
|
|
241
|
+
return res.json({ success: true, nodes: [], edges: [], categories: [], timestamp: Date.now() });
|
|
242
|
+
}
|
|
243
|
+
const graph = (0, handlers_graph_js_1.buildGraph)({ enrich: true, includeCategoryNodes: true, includeUsage: false });
|
|
244
|
+
const expand = (req.query.expand === '1' || req.query.expand === 'true');
|
|
245
|
+
const selectedSet = new Set(ids);
|
|
246
|
+
const workingSet = new Set(ids);
|
|
247
|
+
const firstEdges = graph.edges.filter(e => selectedSet.has(e.from) || selectedSet.has(e.to));
|
|
248
|
+
if (expand) {
|
|
249
|
+
const instructionNodeIds = new Set(graph.nodes.filter(n => n.nodeType === 'instruction').map(n => n.id));
|
|
250
|
+
for (const e of firstEdges) {
|
|
251
|
+
if (instructionNodeIds.has(e.from) && !workingSet.has(e.from))
|
|
252
|
+
workingSet.add(e.from);
|
|
253
|
+
if (instructionNodeIds.has(e.to) && !workingSet.has(e.to))
|
|
254
|
+
workingSet.add(e.to);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const nodesAll = graph.nodes.filter(n => workingSet.has(n.id) || n.nodeType === 'category');
|
|
258
|
+
const edges = graph.edges.filter(e => workingSet.has(e.from) && workingSet.has(e.to) && (selectedSet.has(e.from) || selectedSet.has(e.to)));
|
|
259
|
+
const categoryRefs = new Set();
|
|
260
|
+
for (const e of edges) {
|
|
261
|
+
if (e.type === 'belongs' || e.type === 'primary') {
|
|
262
|
+
if (e.to.startsWith('category:'))
|
|
263
|
+
categoryRefs.add(e.to);
|
|
264
|
+
if (e.from.startsWith('category:'))
|
|
265
|
+
categoryRefs.add(e.from);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const finalNodes = nodesAll.filter(n => !('nodeType' in n && n.nodeType === 'category') || categoryRefs.has(n.id));
|
|
269
|
+
const categories = [...categoryRefs].map(id => ({ id: id.replace(/^category:/, '') }));
|
|
270
|
+
const expandedCount = workingSet.size - selectedSet.size;
|
|
271
|
+
res.json({ success: true, nodes: finalNodes, edges, categories, expanded: expand ? expandedCount : 0, timestamp: Date.now() });
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
console.error('[graph/relations] Error:', err);
|
|
275
|
+
res.status(500).json({ success: false, error: 'Failed to get relations' });
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
return router;
|
|
279
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route module index — re-exports all route factories and mounts dashboard routes.
|
|
3
|
+
*/
|
|
4
|
+
import { Express } from 'express';
|
|
5
|
+
import { MetricsCollector } from '../MetricsCollector.js';
|
|
6
|
+
export { createStatusRoutes } from './status.routes.js';
|
|
7
|
+
export { createMetricsRoutes } from './metrics.routes.js';
|
|
8
|
+
export { createAdminRoutes } from './admin.routes.js';
|
|
9
|
+
export { createGraphRoutes } from './graph.routes.js';
|
|
10
|
+
export { createInstructionsRoutes } from './instructions.routes.js';
|
|
11
|
+
export { createKnowledgeRoutes } from './knowledge.routes.js';
|
|
12
|
+
export { createAlertsRoutes } from './alerts.routes.js';
|
|
13
|
+
export { createLogsRoutes } from './logs.routes.js';
|
|
14
|
+
export { createSyntheticRoutes } from './synthetic.routes.js';
|
|
15
|
+
export { createInstancesRoutes } from './instances.routes.js';
|
|
16
|
+
export { createToolsRoutes } from './tools.routes.js';
|
|
17
|
+
export { createEmbeddingsRoutes } from './embeddings.routes.js';
|
|
18
|
+
export { createUsageRoutes } from './usage.routes.js';
|
|
19
|
+
export { createScriptsRoutes } from './scripts.routes.js';
|
|
20
|
+
export { createMessagingRoutes } from './messaging.routes.js';
|
|
21
|
+
export { createSqliteRoutes } from './sqlite.routes.js';
|
|
22
|
+
export interface DashboardRoutesContext {
|
|
23
|
+
metricsCollector: MetricsCollector;
|
|
24
|
+
enableWebSockets: boolean;
|
|
25
|
+
enableCors: boolean;
|
|
26
|
+
graphEnabled: boolean;
|
|
27
|
+
wsProtocol: 'wss' | 'ws';
|
|
28
|
+
getServerInfo: () => {
|
|
29
|
+
port: number;
|
|
30
|
+
host: string;
|
|
31
|
+
url: string;
|
|
32
|
+
} | null;
|
|
33
|
+
}
|
|
34
|
+
export declare function renderPanelMarkdownHtml(name: string, markdown: string): string;
|
|
35
|
+
/**
|
|
36
|
+
* Registers all top-level dashboard routes on the given Express app.
|
|
37
|
+
* Called once during DashboardServer construction after middleware is set up.
|
|
38
|
+
*/
|
|
39
|
+
export declare function mountDashboardRoutes(app: Express, ctx: DashboardRoutesContext): void;
|