@jagilber-org/index-server 1.19.1
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 +1218 -0
- package/CODE_OF_CONDUCT.md +49 -0
- package/CONTRIBUTING.md +75 -0
- package/LICENSE +21 -0
- package/README.md +523 -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 +45 -0
- package/dist/config/dashboardConfig.js +63 -0
- package/dist/config/defaultValues.d.ts +61 -0
- package/dist/config/defaultValues.js +70 -0
- package/dist/config/dirConstants.d.ts +17 -0
- package/dist/config/dirConstants.js +28 -0
- package/dist/config/featureConfig.d.ts +61 -0
- package/dist/config/featureConfig.js +121 -0
- package/dist/config/runtimeConfig.d.ts +145 -0
- package/dist/config/runtimeConfig.js +334 -0
- package/dist/config/serverConfig.d.ts +90 -0
- package/dist/config/serverConfig.js +164 -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 +2150 -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 +1466 -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 +425 -0
- package/dist/dashboard/client/js/admin.graph.js +583 -0
- package/dist/dashboard/client/js/admin.instances.js +120 -0
- package/dist/dashboard/client/js/admin.instructions.js +552 -0
- package/dist/dashboard/client/js/admin.logs.js +113 -0
- package/dist/dashboard/client/js/admin.maintenance.js +354 -0
- package/dist/dashboard/client/js/admin.messaging.js +635 -0
- package/dist/dashboard/client/js/admin.monitor.js +181 -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 +293 -0
- package/dist/dashboard/client/js/admin.sqlite.js +366 -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 +46 -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 +22 -0
- package/dist/dashboard/export/exporters/xmlExporter.d.ts +17 -0
- package/dist/dashboard/export/exporters/xmlExporter.js +175 -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 +559 -0
- package/dist/dashboard/server/AdminPanel.d.ts +183 -0
- package/dist/dashboard/server/AdminPanel.js +792 -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 +214 -0
- package/dist/dashboard/server/ApiRoutes.d.ts +17 -0
- package/dist/dashboard/server/ApiRoutes.js +149 -0
- package/dist/dashboard/server/DashboardServer.d.ts +49 -0
- package/dist/dashboard/server/DashboardServer.js +159 -0
- package/dist/dashboard/server/FileMetricsStorage.d.ts +49 -0
- package/dist/dashboard/server/FileMetricsStorage.js +195 -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 +284 -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 +803 -0
- package/dist/dashboard/server/SessionPersistenceManager.d.ts +88 -0
- package/dist/dashboard/server/SessionPersistenceManager.js +457 -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 +463 -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 +206 -0
- package/dist/dashboard/server/metricsSerializer.d.ts +25 -0
- package/dist/dashboard/server/metricsSerializer.js +195 -0
- package/dist/dashboard/server/routes/admin.routes.d.ts +16 -0
- package/dist/dashboard/server/routes/admin.routes.js +596 -0
- package/dist/dashboard/server/routes/alerts.routes.d.ts +7 -0
- package/dist/dashboard/server/routes/alerts.routes.js +93 -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 +280 -0
- package/dist/dashboard/server/routes/index.d.ts +38 -0
- package/dist/dashboard/server/routes/index.js +194 -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 +336 -0
- package/dist/dashboard/server/routes/knowledge.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/knowledge.routes.js +82 -0
- package/dist/dashboard/server/routes/logs.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/logs.routes.js +164 -0
- package/dist/dashboard/server/routes/messaging.routes.d.ts +16 -0
- package/dist/dashboard/server/routes/messaging.routes.js +293 -0
- package/dist/dashboard/server/routes/metrics.routes.d.ts +10 -0
- package/dist/dashboard/server/routes/metrics.routes.js +346 -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 +569 -0
- package/dist/dashboard/server/routes/status.routes.d.ts +7 -0
- package/dist/dashboard/server/routes/status.routes.js +183 -0
- package/dist/dashboard/server/routes/synthetic.routes.d.ts +7 -0
- package/dist/dashboard/server/routes/synthetic.routes.js +195 -0
- package/dist/dashboard/server/routes/tools.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/tools.routes.js +46 -0
- package/dist/dashboard/server/routes/usage.routes.d.ts +6 -0
- package/dist/dashboard/server/routes/usage.routes.js +25 -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 +45 -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 +128 -0
- package/dist/schemas/index.js +371 -0
- package/dist/scripts/runPerformanceBaseline.d.ts +1 -0
- package/dist/scripts/runPerformanceBaseline.js +17 -0
- package/dist/server/handshakeManager.d.ts +25 -0
- package/dist/server/handshakeManager.js +472 -0
- package/dist/server/index-server.d.ts +56 -0
- package/dist/server/index-server.js +822 -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/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 +110 -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 +259 -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 +496 -0
- package/dist/services/handlers/instructions.groom.d.ts +1 -0
- package/dist/services/handlers/instructions.groom.js +523 -0
- package/dist/services/handlers/instructions.import.d.ts +1 -0
- package/dist/services/handlers/instructions.import.js +173 -0
- package/dist/services/handlers/instructions.patch.d.ts +1 -0
- package/dist/services/handlers/instructions.patch.js +167 -0
- package/dist/services/handlers/instructions.query.d.ts +163 -0
- package/dist/services/handlers/instructions.query.js +522 -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 +118 -0
- package/dist/services/handlers/instructions.shared.d.ts +31 -0
- package/dist/services/handlers/instructions.shared.js +124 -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 +108 -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 +378 -0
- package/dist/services/handlers.gates.d.ts +1 -0
- package/dist/services/handlers.gates.js +46 -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 +306 -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 +645 -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 +31 -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 +968 -0
- package/dist/services/indexLoader.d.ts +44 -0
- package/dist/services/indexLoader.js +921 -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 +38 -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 +427 -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 +122 -0
- package/dist/services/storage/sqliteStore.d.ts +41 -0
- package/dist/services/storage/sqliteStore.js +339 -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 +323 -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 +93 -0
- package/package.json +134 -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 +38477 -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 +206 -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/setup-hooks.cjs +28 -0
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.instructionActions = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const registry_1 = require("../../server/registry");
|
|
10
|
+
const indexContext_1 = require("../indexContext");
|
|
11
|
+
const bootstrapGating_1 = require("../bootstrapGating");
|
|
12
|
+
const classificationService_1 = require("../classificationService");
|
|
13
|
+
const features_1 = require("../features");
|
|
14
|
+
const runtimeConfig_1 = require("../../config/runtimeConfig");
|
|
15
|
+
const tracing_1 = require("../tracing");
|
|
16
|
+
const handlers_search_1 = require("../handlers.search");
|
|
17
|
+
const instructions_shared_1 = require("./instructions.shared");
|
|
18
|
+
// Legacy individual instruction handlers removed in favor of unified dispatcher (index_dispatch).
|
|
19
|
+
// Internal implementation functions retained below for dispatcher direct invocation.
|
|
20
|
+
exports.instructionActions = {
|
|
21
|
+
list: (p) => {
|
|
22
|
+
let st = (0, indexContext_1.ensureLoaded)();
|
|
23
|
+
const originalHash = st.hash;
|
|
24
|
+
let items = st.list;
|
|
25
|
+
if (p?.category) {
|
|
26
|
+
const c = p.category.toLowerCase();
|
|
27
|
+
items = items.filter(i => i.categories.includes(c));
|
|
28
|
+
}
|
|
29
|
+
if (p?.contentType) {
|
|
30
|
+
const ct = p.contentType;
|
|
31
|
+
items = items.filter(i => (i.contentType || 'instruction') === ct);
|
|
32
|
+
}
|
|
33
|
+
let attemptedReload = false;
|
|
34
|
+
const attemptedLate = false;
|
|
35
|
+
if (p?.expectId) {
|
|
36
|
+
const idx = items.findIndex(i => i.id === p.expectId);
|
|
37
|
+
if (idx > 0) {
|
|
38
|
+
const target = items[idx];
|
|
39
|
+
items = [target, ...items.slice(0, idx), ...items.slice(idx + 1)];
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (p?.expectId) {
|
|
43
|
+
try {
|
|
44
|
+
const dir = (0, indexContext_1.getInstructionsDir)();
|
|
45
|
+
const file = path_1.default.join(dir, `${p.expectId}.json`);
|
|
46
|
+
const hasFile = fs_1.default.existsSync(file);
|
|
47
|
+
const inIndex = st.byId.has(p.expectId);
|
|
48
|
+
if (hasFile && !inIndex) {
|
|
49
|
+
attemptedReload = true;
|
|
50
|
+
(0, indexContext_1.invalidate)();
|
|
51
|
+
st = (0, indexContext_1.ensureLoaded)();
|
|
52
|
+
items = st.list;
|
|
53
|
+
if (p.category) {
|
|
54
|
+
const c2 = p.category.toLowerCase();
|
|
55
|
+
items = items.filter(i => i.categories.includes(c2));
|
|
56
|
+
}
|
|
57
|
+
if (st.byId.has(p.expectId)) {
|
|
58
|
+
const idx2 = items.findIndex(i => i.id === p.expectId);
|
|
59
|
+
if (idx2 > 0) {
|
|
60
|
+
const target2 = items[idx2];
|
|
61
|
+
items = [target2, ...items.slice(0, idx2), ...items.slice(idx2 + 1)];
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
catch { /* ignore repair errors */ }
|
|
67
|
+
}
|
|
68
|
+
if ((0, instructions_shared_1.traceVisibility)()) {
|
|
69
|
+
try {
|
|
70
|
+
const dir = (0, indexContext_1.getInstructionsDir)();
|
|
71
|
+
const disk = fs_1.default.readdirSync(dir).filter(f => f.endsWith('.json'));
|
|
72
|
+
const diskIds = new Set(disk.map(f => f.slice(0, -5)));
|
|
73
|
+
const idsSample = items.slice(0, 5).map(i => i.id);
|
|
74
|
+
const missingOnIndex = [...diskIds].filter(id => !st.byId.has(id));
|
|
75
|
+
const expectId = p?.expectId;
|
|
76
|
+
const expectOnDisk = expectId ? diskIds.has(expectId) : undefined;
|
|
77
|
+
const expectinIndex = expectId ? st.byId.has(expectId) : undefined;
|
|
78
|
+
(0, tracing_1.emitTrace)('[trace:list]', { dir, total: st.list.length, filtered: items.length, sample: idsSample, diskCount: disk.length, missingOnIndexCount: missingOnIndex.length, missingOnIndex: missingOnIndex.slice(0, 5), expectId, expectOnDisk, expectinIndex, attemptedReload, attemptedLate, originalHash, finalHash: st.hash });
|
|
79
|
+
}
|
|
80
|
+
catch { /* ignore */ }
|
|
81
|
+
}
|
|
82
|
+
const totalCount = items.length;
|
|
83
|
+
// Apply offset/limit pagination when provided via REST bridge callers
|
|
84
|
+
const offset = typeof p?.offset === 'number' && p.offset > 0 ? p.offset : 0;
|
|
85
|
+
if (offset > 0) {
|
|
86
|
+
items = items.slice(offset);
|
|
87
|
+
}
|
|
88
|
+
if (typeof p?.limit === 'number' && p.limit > 0) {
|
|
89
|
+
items = items.slice(0, p.limit);
|
|
90
|
+
}
|
|
91
|
+
const resp = (0, instructions_shared_1.limitResponseSize)({ hash: st.hash, count: totalCount, items });
|
|
92
|
+
return resp;
|
|
93
|
+
},
|
|
94
|
+
listScoped: (p) => {
|
|
95
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
96
|
+
const userId = p.userId?.toLowerCase();
|
|
97
|
+
const workspaceId = p.workspaceId?.toLowerCase();
|
|
98
|
+
const teamIds = (p.teamIds || []).map(t => t.toLowerCase());
|
|
99
|
+
const all = st.list;
|
|
100
|
+
const matchUser = userId ? all.filter(e => (e.userId || '').toLowerCase() === userId) : [];
|
|
101
|
+
if (matchUser.length)
|
|
102
|
+
return { hash: st.hash, count: matchUser.length, scope: 'user', items: matchUser };
|
|
103
|
+
const matchWorkspace = workspaceId ? all.filter(e => (e.workspaceId || '').toLowerCase() === workspaceId) : [];
|
|
104
|
+
if (matchWorkspace.length)
|
|
105
|
+
return { hash: st.hash, count: matchWorkspace.length, scope: 'workspace', items: matchWorkspace };
|
|
106
|
+
const teamSet = new Set(teamIds);
|
|
107
|
+
const matchTeams = teamIds.length ? all.filter(e => Array.isArray(e.teamIds) && e.teamIds.some(t => teamSet.has(t.toLowerCase()))) : [];
|
|
108
|
+
if (matchTeams.length)
|
|
109
|
+
return { hash: st.hash, count: matchTeams.length, scope: 'team', items: matchTeams };
|
|
110
|
+
const audienceAll = all.filter(e => e.audience === 'all');
|
|
111
|
+
return { hash: st.hash, count: audienceAll.length, scope: 'all', items: audienceAll };
|
|
112
|
+
},
|
|
113
|
+
get: (p) => {
|
|
114
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
115
|
+
const item = st.byId.get(p.id);
|
|
116
|
+
if (!item && (0, runtimeConfig_1.getRuntimeConfig)().instructions.strictVisibility) {
|
|
117
|
+
const enhanced = exports.instructionActions.getEnhanced({ id: p.id });
|
|
118
|
+
if (enhanced.item)
|
|
119
|
+
return { hash: enhanced.hash || st.hash, item: enhanced.item };
|
|
120
|
+
}
|
|
121
|
+
if ((0, instructions_shared_1.traceVisibility)()) {
|
|
122
|
+
const dir = (0, indexContext_1.getInstructionsDir)();
|
|
123
|
+
(0, tracing_1.emitTrace)('[trace:get]', { dir, id: p.id, found: !!item, total: st.list.length, strict: (0, runtimeConfig_1.getRuntimeConfig)().instructions.strictVisibility });
|
|
124
|
+
(0, instructions_shared_1.traceInstructionVisibility)(p.id, item ? 'get-found' : 'get-not-found');
|
|
125
|
+
if (!item)
|
|
126
|
+
(0, instructions_shared_1.traceEnvSnapshot)('get-not-found');
|
|
127
|
+
}
|
|
128
|
+
return item ? { hash: st.hash, item } : { notFound: true, id: p.id, hint: `No instruction found with id "${p.id}". Use action="search" with q="<keyword>" to find valid ids, or action="list" to see all.`, example: { action: 'get', id: 'valid-instruction-id' } };
|
|
129
|
+
},
|
|
130
|
+
getEnhanced: (p) => {
|
|
131
|
+
const base = (0, indexContext_1.getInstructionsDir)();
|
|
132
|
+
const file = path_1.default.join(base, `${p.id}.json`);
|
|
133
|
+
let st = (0, indexContext_1.ensureLoaded)();
|
|
134
|
+
let item = st.byId.get(p.id);
|
|
135
|
+
if (item)
|
|
136
|
+
return { hash: st.hash, item };
|
|
137
|
+
if (!fs_1.default.existsSync(file))
|
|
138
|
+
return { notFound: true };
|
|
139
|
+
let repaired = false;
|
|
140
|
+
try {
|
|
141
|
+
(0, instructions_shared_1.traceInstructionVisibility)(p.id, 'getEnhanced-start');
|
|
142
|
+
(0, indexContext_1.invalidate)();
|
|
143
|
+
st = (0, indexContext_1.ensureLoaded)();
|
|
144
|
+
item = st.byId.get(p.id);
|
|
145
|
+
if (item) {
|
|
146
|
+
repaired = true;
|
|
147
|
+
}
|
|
148
|
+
if (!repaired) {
|
|
149
|
+
const txt = fs_1.default.readFileSync(file, 'utf8');
|
|
150
|
+
if (txt.trim()) {
|
|
151
|
+
try {
|
|
152
|
+
const raw = JSON.parse(txt);
|
|
153
|
+
const classifier = new classificationService_1.ClassificationService();
|
|
154
|
+
const issues = classifier.validate(raw);
|
|
155
|
+
if (!issues.length) {
|
|
156
|
+
const norm = classifier.normalize(raw);
|
|
157
|
+
st.list.push(norm);
|
|
158
|
+
st.byId.set(norm.id, norm);
|
|
159
|
+
item = norm;
|
|
160
|
+
repaired = true;
|
|
161
|
+
(0, features_1.incrementCounter)('instructions:getLateMaterialize');
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
(0, features_1.incrementCounter)('instructions:getLateMaterializeRejected');
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
(0, features_1.incrementCounter)('instructions:getLateMaterializeParseError');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
(0, features_1.incrementCounter)('instructions:getLateMaterializeEmptyFile');
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
catch { /* swallow */ }
|
|
177
|
+
if ((0, instructions_shared_1.traceVisibility)()) {
|
|
178
|
+
(0, tracing_1.emitTrace)('[trace:get:late-materialize]', { id: p.id, repaired, fileExists: true });
|
|
179
|
+
}
|
|
180
|
+
(0, instructions_shared_1.traceInstructionVisibility)(p.id, 'getEnhanced-end', { repaired, finalFound: !!item });
|
|
181
|
+
return item ? { hash: st.hash, item } : { notFound: true };
|
|
182
|
+
},
|
|
183
|
+
search: async (p) => {
|
|
184
|
+
const providedKeywords = Array.isArray(p.keywords)
|
|
185
|
+
? p.keywords.filter((keyword) => typeof keyword === 'string' && keyword.trim().length > 0)
|
|
186
|
+
: [];
|
|
187
|
+
const keywords = providedKeywords.length > 0
|
|
188
|
+
? providedKeywords
|
|
189
|
+
: (typeof p.q === 'string' && p.q.trim().length > 0 ? [p.q] : []);
|
|
190
|
+
const searchResult = await (0, handlers_search_1.handleInstructionsSearch)({
|
|
191
|
+
keywords,
|
|
192
|
+
mode: p.mode,
|
|
193
|
+
limit: p.limit,
|
|
194
|
+
includeCategories: p.includeCategories ?? true,
|
|
195
|
+
caseSensitive: p.caseSensitive,
|
|
196
|
+
contentType: p.contentType,
|
|
197
|
+
});
|
|
198
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
199
|
+
const items = searchResult.results
|
|
200
|
+
.map(result => st.byId.get(result.instructionId))
|
|
201
|
+
.filter((item) => !!item);
|
|
202
|
+
if ((0, instructions_shared_1.traceVisibility)()) {
|
|
203
|
+
const dir = (0, indexContext_1.getInstructionsDir)();
|
|
204
|
+
const sample = items.slice(0, 5).map(i => i.id);
|
|
205
|
+
(0, tracing_1.emitTrace)('[trace:search]', { dir, q: keywords.join(' '), matches: items.length, sample });
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
hash: st.hash,
|
|
209
|
+
count: items.length,
|
|
210
|
+
totalMatches: searchResult.totalMatches,
|
|
211
|
+
items,
|
|
212
|
+
results: searchResult.results,
|
|
213
|
+
query: searchResult.query,
|
|
214
|
+
autoTokenized: searchResult.autoTokenized,
|
|
215
|
+
hints: searchResult.hints,
|
|
216
|
+
};
|
|
217
|
+
},
|
|
218
|
+
diff: (p) => {
|
|
219
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
220
|
+
const clientHash = p.clientHash;
|
|
221
|
+
const known = p.known;
|
|
222
|
+
if (!known && clientHash && clientHash === st.hash)
|
|
223
|
+
return { upToDate: true, hash: st.hash };
|
|
224
|
+
if (known) {
|
|
225
|
+
const map = new Map();
|
|
226
|
+
for (const k of known) {
|
|
227
|
+
if (k && k.id && !map.has(k.id))
|
|
228
|
+
map.set(k.id, k.sourceHash);
|
|
229
|
+
}
|
|
230
|
+
const added = [];
|
|
231
|
+
const updated = [];
|
|
232
|
+
const removed = [];
|
|
233
|
+
for (const e of st.list) {
|
|
234
|
+
const prev = map.get(e.id);
|
|
235
|
+
if (prev === undefined)
|
|
236
|
+
added.push(e);
|
|
237
|
+
else if (prev !== e.sourceHash)
|
|
238
|
+
updated.push(e);
|
|
239
|
+
}
|
|
240
|
+
for (const id of map.keys()) {
|
|
241
|
+
if (!st.byId.has(id))
|
|
242
|
+
removed.push(id);
|
|
243
|
+
}
|
|
244
|
+
if (!added.length && !updated.length && !removed.length && clientHash === st.hash)
|
|
245
|
+
return { upToDate: true, hash: st.hash };
|
|
246
|
+
return { hash: st.hash, added, updated, removed };
|
|
247
|
+
}
|
|
248
|
+
if (!clientHash || clientHash !== st.hash)
|
|
249
|
+
return { hash: st.hash, changed: st.list };
|
|
250
|
+
return { upToDate: true, hash: st.hash };
|
|
251
|
+
},
|
|
252
|
+
export: (p) => {
|
|
253
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
254
|
+
let items = st.list;
|
|
255
|
+
if (p?.ids?.length) {
|
|
256
|
+
const want = new Set(p.ids);
|
|
257
|
+
items = items.filter(i => want.has(i.id));
|
|
258
|
+
}
|
|
259
|
+
if (p?.metaOnly) {
|
|
260
|
+
items = items.map(i => ({ ...i, body: '' }));
|
|
261
|
+
}
|
|
262
|
+
return (0, instructions_shared_1.limitResponseSize)({ hash: st.hash, count: items.length, items });
|
|
263
|
+
},
|
|
264
|
+
query: (p) => {
|
|
265
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
266
|
+
if ((0, instructions_shared_1.traceVisibility)()) {
|
|
267
|
+
try {
|
|
268
|
+
(0, tracing_1.emitTrace)('[trace:query:start]', { pid: process.pid, dir: (0, indexContext_1.getInstructionsDir)(), keys: Object.keys(p || {}), categoriesAny: p.categoriesAny, categoriesAll: p.categoriesAll, excludeCategories: p.excludeCategories });
|
|
269
|
+
}
|
|
270
|
+
catch { /* ignore */ }
|
|
271
|
+
}
|
|
272
|
+
const norm = (arr) => Array.from(new Set((arr || []).filter(x => typeof x === 'string' && x.trim()).map(x => x.toLowerCase())));
|
|
273
|
+
const catsAll = norm(p.categoriesAll);
|
|
274
|
+
const catsAny = norm(p.categoriesAny);
|
|
275
|
+
const catsEx = norm(p.excludeCategories);
|
|
276
|
+
const tierSet = new Set((p.priorityTiers || []).filter(t => ['P1', 'P2', 'P3', 'P4'].includes(String(t))));
|
|
277
|
+
const reqSet = new Set((p.requirements || []).filter(r => ['mandatory', 'critical', 'recommended', 'optional', 'deprecated'].includes(String(r))));
|
|
278
|
+
const prMin = typeof p.priorityMin === 'number' ? p.priorityMin : undefined;
|
|
279
|
+
const prMax = typeof p.priorityMax === 'number' ? p.priorityMax : undefined;
|
|
280
|
+
const text = (p.text || '').toLowerCase().trim();
|
|
281
|
+
let items = st.list;
|
|
282
|
+
const instructionsCfg = (0, runtimeConfig_1.getRuntimeConfig)().instructions;
|
|
283
|
+
const diagActive = instructionsCfg.traceQueryDiag && (catsAll.length || catsAny.length || catsEx.length || text.length);
|
|
284
|
+
const stages = [];
|
|
285
|
+
const pushStage = (stage, note) => { if (diagActive)
|
|
286
|
+
stages.push({ stage, count: items.length, note }); };
|
|
287
|
+
if (diagActive)
|
|
288
|
+
pushStage('loaded');
|
|
289
|
+
let preFilterSample;
|
|
290
|
+
if (diagActive) {
|
|
291
|
+
preFilterSample = items.slice(0, 25).map(i => i.id);
|
|
292
|
+
}
|
|
293
|
+
const preCount = items.length;
|
|
294
|
+
if (catsAll.length) {
|
|
295
|
+
items = items.filter(e => catsAll.every(c => e.categories.includes(c)));
|
|
296
|
+
pushStage('catsAll');
|
|
297
|
+
}
|
|
298
|
+
if (catsAny.length) {
|
|
299
|
+
const before = items.length;
|
|
300
|
+
items = items.filter(e => e.categories.some(c => catsAny.includes(c)));
|
|
301
|
+
pushStage('catsAny', before !== items.length ? undefined : 'no-change');
|
|
302
|
+
}
|
|
303
|
+
if (catsEx.length) {
|
|
304
|
+
items = items.filter(e => !e.categories.some(c => catsEx.includes(c)));
|
|
305
|
+
pushStage('catsEx');
|
|
306
|
+
}
|
|
307
|
+
if (p?.contentType) {
|
|
308
|
+
const ct = p.contentType;
|
|
309
|
+
items = items.filter(i => (i.contentType || 'instruction') === ct);
|
|
310
|
+
pushStage('contentType');
|
|
311
|
+
}
|
|
312
|
+
if (prMin !== undefined) {
|
|
313
|
+
items = items.filter(e => e.priority >= prMin);
|
|
314
|
+
pushStage('prMin');
|
|
315
|
+
}
|
|
316
|
+
if (prMax !== undefined) {
|
|
317
|
+
items = items.filter(e => e.priority <= prMax);
|
|
318
|
+
pushStage('prMax');
|
|
319
|
+
}
|
|
320
|
+
if (tierSet.size) {
|
|
321
|
+
items = items.filter(e => e.priorityTier && tierSet.has(e.priorityTier));
|
|
322
|
+
pushStage('tiers');
|
|
323
|
+
}
|
|
324
|
+
if (reqSet.size) {
|
|
325
|
+
items = items.filter(e => reqSet.has(e.requirement));
|
|
326
|
+
pushStage('requirements');
|
|
327
|
+
}
|
|
328
|
+
if (text) {
|
|
329
|
+
items = items.filter(e => e.title.toLowerCase().includes(text) || e.body.toLowerCase().includes(text) || (e.semanticSummary || '').toLowerCase().includes(text));
|
|
330
|
+
pushStage('text');
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
const recent = st._recentAdds;
|
|
334
|
+
if (recent) {
|
|
335
|
+
const now = Date.now();
|
|
336
|
+
const GRACE = 300;
|
|
337
|
+
for (const [id, meta] of Object.entries(recent)) {
|
|
338
|
+
if (now - meta.ts > GRACE)
|
|
339
|
+
continue;
|
|
340
|
+
if (items.some(e => e.id === id))
|
|
341
|
+
continue;
|
|
342
|
+
const catMatchAll = !catsAll.length || catsAll.every(c => meta.categories.includes(c));
|
|
343
|
+
const catMatchAny = !catsAny.length || meta.categories.some(c => catsAny.includes(c));
|
|
344
|
+
const catExcluded = catsEx.length && meta.categories.some(c => catsEx.includes(c));
|
|
345
|
+
if (catMatchAll && catMatchAny && !catExcluded) {
|
|
346
|
+
const injected = st.byId.get(id);
|
|
347
|
+
if (injected) {
|
|
348
|
+
items = items.concat([injected]);
|
|
349
|
+
if ((0, instructions_shared_1.traceVisibility)())
|
|
350
|
+
(0, tracing_1.emitTrace)('[trace:query:recent-add-injected]', { id, graceMs: now - meta.ts });
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
catch { /* ignore fallback */ }
|
|
357
|
+
const total = items.length;
|
|
358
|
+
const limit = Math.min(Math.max((p.limit ?? 100), 1), 1000);
|
|
359
|
+
const offset = Math.max((p.offset ?? 0), 0);
|
|
360
|
+
const paged = items.slice(offset, offset + limit);
|
|
361
|
+
if ((0, instructions_shared_1.traceVisibility)()) {
|
|
362
|
+
const sample = paged.slice(0, 5).map(i => i.id);
|
|
363
|
+
(0, tracing_1.emitTrace)('[trace:query]', { applied: { catsAll, catsAny, catsEx, prMin, prMax, tiers: [...tierSet], requirements: [...reqSet], text: text || undefined }, preCount, total, returned: paged.length, sample });
|
|
364
|
+
if (diagActive) {
|
|
365
|
+
const suspicious = paged.length === 0 || paged.length < Math.min(3, preCount);
|
|
366
|
+
if (suspicious) {
|
|
367
|
+
const categoryDiagnostics = {};
|
|
368
|
+
for (const c of catsAny) {
|
|
369
|
+
let present = 0;
|
|
370
|
+
let passed = 0;
|
|
371
|
+
const sampleIds = [];
|
|
372
|
+
for (const e of st.list) {
|
|
373
|
+
if (e.categories.includes(c)) {
|
|
374
|
+
present++;
|
|
375
|
+
if (items.includes(e)) {
|
|
376
|
+
passed++;
|
|
377
|
+
if (sampleIds.length < 5)
|
|
378
|
+
sampleIds.push(e.id);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
categoryDiagnostics[c] = { present, passedAllFilters: passed, sampleIds };
|
|
383
|
+
}
|
|
384
|
+
(0, tracing_1.emitTrace)('[trace:query:diag]', { preFilterSample, stages, categoryDiagnostics, finalReturned: paged.length, totalAfterFilters: total, preCount });
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return { hash: st.hash, total, count: paged.length, offset, limit, items: paged, applied: { catsAll, catsAny, catsEx, prMin, prMax, tiers: [...tierSet], requirements: [...reqSet], text: text || undefined } };
|
|
389
|
+
},
|
|
390
|
+
categories: (_p) => {
|
|
391
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
392
|
+
const counts = new Map();
|
|
393
|
+
for (const e of st.list) {
|
|
394
|
+
for (const c of e.categories) {
|
|
395
|
+
counts.set(c, (counts.get(c) || 0) + 1);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const categories = [...counts.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([name, count]) => ({ name, count }));
|
|
399
|
+
return { count: categories.length, categories };
|
|
400
|
+
},
|
|
401
|
+
dir: () => {
|
|
402
|
+
const dir = (0, indexContext_1.getInstructionsDir)();
|
|
403
|
+
let files = [];
|
|
404
|
+
try {
|
|
405
|
+
files = fs_1.default.readdirSync(dir).filter(f => f.endsWith('.json')).sort();
|
|
406
|
+
}
|
|
407
|
+
catch { /* ignore */ }
|
|
408
|
+
return { dir, filesCount: files.length, files };
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
// Deep file-level inspection (diagnostics)
|
|
412
|
+
(0, registry_1.registerHandler)('index_inspect', (p) => {
|
|
413
|
+
const id = p.id;
|
|
414
|
+
if (!id)
|
|
415
|
+
return { error: 'missing id' };
|
|
416
|
+
const dir = (0, indexContext_1.getInstructionsDir)();
|
|
417
|
+
const file = path_1.default.join(dir, `${id}.json`);
|
|
418
|
+
let rawText = '';
|
|
419
|
+
let raw = null;
|
|
420
|
+
let parseError;
|
|
421
|
+
try {
|
|
422
|
+
rawText = fs_1.default.readFileSync(file, 'utf8');
|
|
423
|
+
raw = JSON.parse(rawText);
|
|
424
|
+
}
|
|
425
|
+
catch (e) {
|
|
426
|
+
if (e.code === 'ENOENT')
|
|
427
|
+
return { id, exists: false, fileMissing: true };
|
|
428
|
+
parseError = e instanceof Error ? e.message : String(e);
|
|
429
|
+
}
|
|
430
|
+
let schemaErrors;
|
|
431
|
+
let classificationIssues;
|
|
432
|
+
let normalized;
|
|
433
|
+
try {
|
|
434
|
+
if (!parseError) {
|
|
435
|
+
try {
|
|
436
|
+
const rec = raw;
|
|
437
|
+
const missing = [];
|
|
438
|
+
if (!rec.id)
|
|
439
|
+
missing.push('missing id');
|
|
440
|
+
if (!rec.title)
|
|
441
|
+
missing.push('missing title');
|
|
442
|
+
if (!rec.body)
|
|
443
|
+
missing.push('missing body');
|
|
444
|
+
if (missing.length)
|
|
445
|
+
schemaErrors = missing.join(', ');
|
|
446
|
+
const classifier = new classificationService_1.ClassificationService();
|
|
447
|
+
if (!schemaErrors) {
|
|
448
|
+
classificationIssues = classifier.validate(rec);
|
|
449
|
+
if (!classificationIssues.length) {
|
|
450
|
+
normalized = classifier.normalize(rec);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
catch (err) {
|
|
455
|
+
schemaErrors = err.message;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
catch { /* ignore */ }
|
|
460
|
+
return { id, exists: true, file, parseError, schemaErrors, classificationIssues, normalized, raw };
|
|
461
|
+
});
|
|
462
|
+
(0, registry_1.registerHandler)('index_health', () => {
|
|
463
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
464
|
+
const governanceHash = (0, indexContext_1.computeGovernanceHash)(st.list);
|
|
465
|
+
const summary = st.loadSummary || { scanned: st.loadDebug?.scanned ?? st.list.length, accepted: st.list.length, skipped: (st.loadDebug ? (st.loadDebug.scanned - st.loadDebug.accepted) : 0), reasons: {} };
|
|
466
|
+
const total = st.list.length || 1;
|
|
467
|
+
const governanceKeywords = ['constitution', 'quality gate', 'p1 ', 'p0 ', 'lifecycle', 'governance', 'bootstrapper'];
|
|
468
|
+
let governanceLike = 0;
|
|
469
|
+
let keywordHit = 0;
|
|
470
|
+
for (const e of st.list) {
|
|
471
|
+
const body = (e.body || '').toLowerCase();
|
|
472
|
+
const title = (e.title || '').toLowerCase();
|
|
473
|
+
const composite = title + '\n' + body.slice(0, 2000);
|
|
474
|
+
if (/__governance_seed__/.test(composite) || /^000-bootstrapper/.test(e.id) || /^001-knowledge-index-lifecycle/.test(e.id)) {
|
|
475
|
+
governanceLike++;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (governanceKeywords.some(k => composite.includes(k))) {
|
|
479
|
+
keywordHit++;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const leakageRatio = governanceLike / total;
|
|
483
|
+
const effectiveGovernanceLike = ((0, indexContext_1.ensureLoaded)().list.filter(e => e && e.id && !bootstrapGating_1.BOOTSTRAP_ALLOWLIST.has(e.id)).length === 0) ? 0 : governanceLike;
|
|
484
|
+
let recursionRisk;
|
|
485
|
+
try {
|
|
486
|
+
const st3 = (0, indexContext_1.ensureLoaded)();
|
|
487
|
+
const allowlistedCount = st3.list.filter(e => bootstrapGating_1.BOOTSTRAP_ALLOWLIST.has(e.id)).length;
|
|
488
|
+
const adjusted = Math.max(0, governanceLike - allowlistedCount);
|
|
489
|
+
recursionRisk = adjusted === 0 ? 'none' : (leakageRatio < 0.01 ? 'warning' : 'critical');
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
recursionRisk = effectiveGovernanceLike === 0 ? 'none' : (leakageRatio < 0.01 ? 'warning' : 'critical');
|
|
493
|
+
}
|
|
494
|
+
const snapshot = path_1.default.join(process.cwd(), 'snapshots', 'canonical-instructions.json');
|
|
495
|
+
if (!fs_1.default.existsSync(snapshot))
|
|
496
|
+
return { snapshot: 'missing', hash: st.hash, count: st.list.length, governanceHash, recursionRisk, leakage: { governanceLike, keywordHit, leakageRatio }, summary };
|
|
497
|
+
try {
|
|
498
|
+
const raw = JSON.parse(fs_1.default.readFileSync(snapshot, 'utf8'));
|
|
499
|
+
const snapItems = raw.items || [];
|
|
500
|
+
const snapMap = new Map(snapItems.map(i => [i.id, i.sourceHash]));
|
|
501
|
+
const missing = [];
|
|
502
|
+
const changed = [];
|
|
503
|
+
for (const e of st.list) {
|
|
504
|
+
const h = snapMap.get(e.id);
|
|
505
|
+
if (h === undefined)
|
|
506
|
+
missing.push(e.id);
|
|
507
|
+
else if (h !== e.sourceHash)
|
|
508
|
+
changed.push(e.id);
|
|
509
|
+
}
|
|
510
|
+
const extra = snapItems.filter(i => !st.byId.has(i.id)).map(i => i.id);
|
|
511
|
+
return { snapshot: 'present', hash: st.hash, count: st.list.length, missing, changed, extra, drift: missing.length + changed.length + extra.length, governanceHash, recursionRisk, leakage: { governanceLike, keywordHit, leakageRatio }, summary };
|
|
512
|
+
}
|
|
513
|
+
catch (e) {
|
|
514
|
+
return { snapshot: 'error', error: e instanceof Error ? e.message : String(e), hash: st.hash, governanceHash, recursionRisk, leakage: { governanceLike, keywordHit, leakageRatio }, summary };
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
(0, registry_1.registerHandler)('index_debug', () => {
|
|
518
|
+
const before = (0, indexContext_1.getDebugIndexSnapshot)();
|
|
519
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
520
|
+
const after = { hash: st.hash, count: st.list.length };
|
|
521
|
+
return { before, after };
|
|
522
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const registry_1 = require("../../server/registry");
|
|
4
|
+
const indexContext_1 = require("../indexContext");
|
|
5
|
+
const auditLog_1 = require("../auditLog");
|
|
6
|
+
const instructions_shared_1 = require("./instructions.shared");
|
|
7
|
+
(0, registry_1.registerHandler)('index_reload', (0, instructions_shared_1.guard)('index_reload', () => {
|
|
8
|
+
(0, indexContext_1.invalidate)();
|
|
9
|
+
const st = (0, indexContext_1.ensureLoaded)();
|
|
10
|
+
const resp = { reloaded: true, hash: st.hash, count: st.list.length };
|
|
11
|
+
(0, auditLog_1.logAudit)('reload', undefined, { count: st.list.length });
|
|
12
|
+
return resp;
|
|
13
|
+
}));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const fs_1 = __importDefault(require("fs"));
|
|
7
|
+
const path_1 = __importDefault(require("path"));
|
|
8
|
+
const registry_1 = require("../../server/registry");
|
|
9
|
+
const indexContext_1 = require("../indexContext");
|
|
10
|
+
const auditLog_1 = require("../auditLog");
|
|
11
|
+
const runtimeConfig_1 = require("../../config/runtimeConfig");
|
|
12
|
+
const manifestManager_1 = require("../manifestManager");
|
|
13
|
+
const tracing_1 = require("../tracing");
|
|
14
|
+
const instructions_shared_1 = require("./instructions.shared");
|
|
15
|
+
const backupZip_1 = require("../backupZip");
|
|
16
|
+
function backupInstructionsDir() {
|
|
17
|
+
const cfg = (0, runtimeConfig_1.getRuntimeConfig)();
|
|
18
|
+
const base = (0, indexContext_1.getInstructionsDir)();
|
|
19
|
+
const backupsRoot = cfg.dashboard.admin.backupsDir;
|
|
20
|
+
fs_1.default.mkdirSync(backupsRoot, { recursive: true });
|
|
21
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '').replace('T', '-').slice(0, 15);
|
|
22
|
+
let zipPath = path_1.default.join(backupsRoot, `instructions-${stamp}.zip`);
|
|
23
|
+
let i = 1;
|
|
24
|
+
while (fs_1.default.existsSync(zipPath)) {
|
|
25
|
+
zipPath = path_1.default.join(backupsRoot, `instructions-${stamp}-${i++}.zip`);
|
|
26
|
+
}
|
|
27
|
+
(0, backupZip_1.createZipBackup)(base, zipPath);
|
|
28
|
+
return zipPath;
|
|
29
|
+
}
|
|
30
|
+
(0, registry_1.registerHandler)('index_remove', (0, instructions_shared_1.guard)('index_remove', (p) => {
|
|
31
|
+
const ids = Array.isArray(p.ids) ? Array.from(new Set(p.ids.filter(x => typeof x === 'string' && x.trim()))) : [];
|
|
32
|
+
if (!ids.length)
|
|
33
|
+
return { removed: 0, removedIds: [], missing: [], errorCount: 0, errors: ['no ids supplied'] };
|
|
34
|
+
const base = (0, indexContext_1.getInstructionsDir)();
|
|
35
|
+
const cfg = (0, runtimeConfig_1.getRuntimeConfig)();
|
|
36
|
+
const instructionsCfg = cfg.instructions;
|
|
37
|
+
const mutationCfg = cfg.mutation;
|
|
38
|
+
const maxBulk = mutationCfg.maxBulkDelete;
|
|
39
|
+
if (p.dryRun) {
|
|
40
|
+
const wouldRemove = [];
|
|
41
|
+
const wouldMiss = [];
|
|
42
|
+
for (const id of ids) {
|
|
43
|
+
const file = path_1.default.join(base, `${id}.json`);
|
|
44
|
+
if (fs_1.default.existsSync(file))
|
|
45
|
+
wouldRemove.push(id);
|
|
46
|
+
else
|
|
47
|
+
wouldMiss.push(id);
|
|
48
|
+
}
|
|
49
|
+
return { dryRun: true, wouldRemove: wouldRemove.length, wouldRemoveIds: wouldRemove, wouldMiss, removed: 0 };
|
|
50
|
+
}
|
|
51
|
+
if (ids.length > maxBulk && !p.force) {
|
|
52
|
+
(0, auditLog_1.logAudit)('remove_blocked', ids, { count: ids.length, maxBulkDelete: maxBulk, reason: 'bulk_limit_exceeded' });
|
|
53
|
+
return { removed: 0, removedIds: [], missing: [], errorCount: 1, errors: [`Bulk delete blocked: ${ids.length} IDs exceeds INDEX_SERVER_MAX_BULK_DELETE=${maxBulk}. Pass force=true to proceed (a backup will be created first).`], bulkBlocked: true, maxBulkDelete: maxBulk, requestedCount: ids.length };
|
|
54
|
+
}
|
|
55
|
+
let backupDir;
|
|
56
|
+
if (ids.length > maxBulk && mutationCfg.backupBeforeBulkDelete) {
|
|
57
|
+
try {
|
|
58
|
+
backupDir = backupInstructionsDir();
|
|
59
|
+
(0, auditLog_1.logAudit)('remove_backup', ids, { backupDir, count: ids.length });
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
const msg = e instanceof Error ? e.message : 'backup-failed';
|
|
63
|
+
(0, auditLog_1.logAudit)('remove_backup_failed', ids, { error: msg, count: ids.length });
|
|
64
|
+
return { removed: 0, removedIds: [], missing: [], errorCount: 1, errors: [`Bulk delete aborted: pre-mutation backup failed: ${msg}`], backupFailed: true };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const missing = [];
|
|
68
|
+
const removed = [];
|
|
69
|
+
const errors = [];
|
|
70
|
+
for (const id of ids) {
|
|
71
|
+
const file = path_1.default.join(base, `${id}.json`);
|
|
72
|
+
try {
|
|
73
|
+
if (!fs_1.default.existsSync(file)) {
|
|
74
|
+
missing.push(id);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
fs_1.default.unlinkSync(file);
|
|
78
|
+
removed.push(id);
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
errors.push({ id, error: e instanceof Error ? e.message : 'delete-failed' });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (removed.length) {
|
|
85
|
+
(0, indexContext_1.touchIndexVersion)();
|
|
86
|
+
(0, indexContext_1.invalidate)();
|
|
87
|
+
}
|
|
88
|
+
let st = (0, indexContext_1.ensureLoaded)();
|
|
89
|
+
const strictRemove = instructionsCfg.strictRemove;
|
|
90
|
+
let strictFailed = [];
|
|
91
|
+
if (strictRemove) {
|
|
92
|
+
const stillVisible = removed.filter(id => st.byId.has(id));
|
|
93
|
+
if (stillVisible.length) {
|
|
94
|
+
try {
|
|
95
|
+
(0, indexContext_1.invalidate)();
|
|
96
|
+
st = (0, indexContext_1.ensureLoaded)();
|
|
97
|
+
}
|
|
98
|
+
catch { /* ignore */ }
|
|
99
|
+
}
|
|
100
|
+
strictFailed = removed.filter(id => st.byId.has(id));
|
|
101
|
+
if (strictFailed.length && (0, instructions_shared_1.traceVisibility)())
|
|
102
|
+
(0, tracing_1.emitTrace)('[trace:remove:strict-failed]', { ids: strictFailed });
|
|
103
|
+
}
|
|
104
|
+
const resp = { removed: removed.length, removedIds: removed, missing, errorCount: errors.length + (strictFailed.length ? 1 : 0), errors, strictVerified: strictRemove ? (strictFailed.length === 0) : undefined, strictFailed, backupDir };
|
|
105
|
+
if (strictRemove && strictFailed.length) {
|
|
106
|
+
(0, auditLog_1.logAudit)('remove', ids, { removed: removed.length, missing: missing.length, errors: errors.length, strict_failed: strictFailed.length, backupDir });
|
|
107
|
+
return resp;
|
|
108
|
+
}
|
|
109
|
+
(0, auditLog_1.logAudit)('remove', ids, { removed: removed.length, missing: missing.length, errors: errors.length, backupDir });
|
|
110
|
+
try {
|
|
111
|
+
setImmediate(() => { try {
|
|
112
|
+
(0, manifestManager_1.attemptManifestUpdate)();
|
|
113
|
+
}
|
|
114
|
+
catch { /* ignore */ } });
|
|
115
|
+
}
|
|
116
|
+
catch { /* ignore */ }
|
|
117
|
+
return resp;
|
|
118
|
+
}));
|