@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.
Files changed (360) hide show
  1. package/CHANGELOG.md +1218 -0
  2. package/CODE_OF_CONDUCT.md +49 -0
  3. package/CONTRIBUTING.md +75 -0
  4. package/LICENSE +21 -0
  5. package/README.md +523 -0
  6. package/SECURITY.md +50 -0
  7. package/dist/config/configUtils.d.ts +11 -0
  8. package/dist/config/configUtils.js +87 -0
  9. package/dist/config/dashboardConfig.d.ts +45 -0
  10. package/dist/config/dashboardConfig.js +63 -0
  11. package/dist/config/defaultValues.d.ts +61 -0
  12. package/dist/config/defaultValues.js +70 -0
  13. package/dist/config/dirConstants.d.ts +17 -0
  14. package/dist/config/dirConstants.js +28 -0
  15. package/dist/config/featureConfig.d.ts +61 -0
  16. package/dist/config/featureConfig.js +121 -0
  17. package/dist/config/runtimeConfig.d.ts +145 -0
  18. package/dist/config/runtimeConfig.js +334 -0
  19. package/dist/config/serverConfig.d.ts +90 -0
  20. package/dist/config/serverConfig.js +164 -0
  21. package/dist/dashboard/analytics/AnalyticsEngine.d.ts +142 -0
  22. package/dist/dashboard/analytics/AnalyticsEngine.js +373 -0
  23. package/dist/dashboard/analytics/BusinessIntelligence.d.ts +187 -0
  24. package/dist/dashboard/analytics/BusinessIntelligence.js +594 -0
  25. package/dist/dashboard/client/admin.html +2150 -0
  26. package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/chunk-SP2CHFBE.mjs +1 -0
  27. package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/render-T6MDALS3.mjs +27 -0
  28. package/dist/dashboard/client/css/admin.css +1466 -0
  29. package/dist/dashboard/client/js/admin.boot.js +359 -0
  30. package/dist/dashboard/client/js/admin.config.js +196 -0
  31. package/dist/dashboard/client/js/admin.embeddings.js +425 -0
  32. package/dist/dashboard/client/js/admin.graph.js +583 -0
  33. package/dist/dashboard/client/js/admin.instances.js +120 -0
  34. package/dist/dashboard/client/js/admin.instructions.js +552 -0
  35. package/dist/dashboard/client/js/admin.logs.js +113 -0
  36. package/dist/dashboard/client/js/admin.maintenance.js +354 -0
  37. package/dist/dashboard/client/js/admin.messaging.js +635 -0
  38. package/dist/dashboard/client/js/admin.monitor.js +181 -0
  39. package/dist/dashboard/client/js/admin.overview.js +221 -0
  40. package/dist/dashboard/client/js/admin.performance.js +61 -0
  41. package/dist/dashboard/client/js/admin.sessions.js +293 -0
  42. package/dist/dashboard/client/js/admin.sqlite.js +366 -0
  43. package/dist/dashboard/client/js/admin.utils.js +49 -0
  44. package/dist/dashboard/client/js/chart.umd.js +14 -0
  45. package/dist/dashboard/client/js/elk.bundled.js +6696 -0
  46. package/dist/dashboard/client/js/marked.umd.js +74 -0
  47. package/dist/dashboard/client/js/mermaid.min.js +3022 -0
  48. package/dist/dashboard/client/mermaid-layout-elk.esm.min.mjs +1 -0
  49. package/dist/dashboard/export/DataExporter.d.ts +169 -0
  50. package/dist/dashboard/export/DataExporter.js +737 -0
  51. package/dist/dashboard/export/exporters/csvExporter.d.ts +11 -0
  52. package/dist/dashboard/export/exporters/csvExporter.js +46 -0
  53. package/dist/dashboard/export/exporters/exportTypes.d.ts +89 -0
  54. package/dist/dashboard/export/exporters/exportTypes.js +5 -0
  55. package/dist/dashboard/export/exporters/jsonExporter.d.ts +7 -0
  56. package/dist/dashboard/export/exporters/jsonExporter.js +22 -0
  57. package/dist/dashboard/export/exporters/xmlExporter.d.ts +17 -0
  58. package/dist/dashboard/export/exporters/xmlExporter.js +175 -0
  59. package/dist/dashboard/integration/APIIntegration.d.ts +41 -0
  60. package/dist/dashboard/integration/APIIntegration.js +95 -0
  61. package/dist/dashboard/security/SecurityMonitor.d.ts +167 -0
  62. package/dist/dashboard/security/SecurityMonitor.js +559 -0
  63. package/dist/dashboard/server/AdminPanel.d.ts +183 -0
  64. package/dist/dashboard/server/AdminPanel.js +792 -0
  65. package/dist/dashboard/server/AdminPanelConfig.d.ts +42 -0
  66. package/dist/dashboard/server/AdminPanelConfig.js +80 -0
  67. package/dist/dashboard/server/AdminPanelState.d.ts +47 -0
  68. package/dist/dashboard/server/AdminPanelState.js +214 -0
  69. package/dist/dashboard/server/ApiRoutes.d.ts +17 -0
  70. package/dist/dashboard/server/ApiRoutes.js +149 -0
  71. package/dist/dashboard/server/DashboardServer.d.ts +49 -0
  72. package/dist/dashboard/server/DashboardServer.js +159 -0
  73. package/dist/dashboard/server/FileMetricsStorage.d.ts +49 -0
  74. package/dist/dashboard/server/FileMetricsStorage.js +195 -0
  75. package/dist/dashboard/server/HttpTransport.d.ts +23 -0
  76. package/dist/dashboard/server/HttpTransport.js +116 -0
  77. package/dist/dashboard/server/InstanceManager.d.ts +53 -0
  78. package/dist/dashboard/server/InstanceManager.js +284 -0
  79. package/dist/dashboard/server/KnowledgeStore.d.ts +35 -0
  80. package/dist/dashboard/server/KnowledgeStore.js +105 -0
  81. package/dist/dashboard/server/LeaderElection.d.ts +81 -0
  82. package/dist/dashboard/server/LeaderElection.js +268 -0
  83. package/dist/dashboard/server/MetricsCollector.d.ts +200 -0
  84. package/dist/dashboard/server/MetricsCollector.js +803 -0
  85. package/dist/dashboard/server/SessionPersistenceManager.d.ts +88 -0
  86. package/dist/dashboard/server/SessionPersistenceManager.js +457 -0
  87. package/dist/dashboard/server/ThinClient.d.ts +64 -0
  88. package/dist/dashboard/server/ThinClient.js +237 -0
  89. package/dist/dashboard/server/WebSocketManager.d.ts +161 -0
  90. package/dist/dashboard/server/WebSocketManager.js +463 -0
  91. package/dist/dashboard/server/httpLifecycle.d.ts +17 -0
  92. package/dist/dashboard/server/httpLifecycle.js +35 -0
  93. package/dist/dashboard/server/legacyDashboardHtml.d.ts +9 -0
  94. package/dist/dashboard/server/legacyDashboardHtml.js +618 -0
  95. package/dist/dashboard/server/legacyDashboardStyles.d.ts +5 -0
  96. package/dist/dashboard/server/legacyDashboardStyles.js +490 -0
  97. package/dist/dashboard/server/metricsAggregation.d.ts +252 -0
  98. package/dist/dashboard/server/metricsAggregation.js +206 -0
  99. package/dist/dashboard/server/metricsSerializer.d.ts +25 -0
  100. package/dist/dashboard/server/metricsSerializer.js +195 -0
  101. package/dist/dashboard/server/routes/admin.routes.d.ts +16 -0
  102. package/dist/dashboard/server/routes/admin.routes.js +596 -0
  103. package/dist/dashboard/server/routes/alerts.routes.d.ts +7 -0
  104. package/dist/dashboard/server/routes/alerts.routes.js +93 -0
  105. package/dist/dashboard/server/routes/api.feedback.routes.d.ts +73 -0
  106. package/dist/dashboard/server/routes/api.feedback.routes.js +171 -0
  107. package/dist/dashboard/server/routes/api.instructions.routes.d.ts +101 -0
  108. package/dist/dashboard/server/routes/api.instructions.routes.js +213 -0
  109. package/dist/dashboard/server/routes/api.usage.routes.d.ts +57 -0
  110. package/dist/dashboard/server/routes/api.usage.routes.js +374 -0
  111. package/dist/dashboard/server/routes/embeddings.routes.d.ts +6 -0
  112. package/dist/dashboard/server/routes/embeddings.routes.js +246 -0
  113. package/dist/dashboard/server/routes/graph.routes.d.ts +6 -0
  114. package/dist/dashboard/server/routes/graph.routes.js +280 -0
  115. package/dist/dashboard/server/routes/index.d.ts +38 -0
  116. package/dist/dashboard/server/routes/index.js +194 -0
  117. package/dist/dashboard/server/routes/instances.routes.d.ts +6 -0
  118. package/dist/dashboard/server/routes/instances.routes.js +35 -0
  119. package/dist/dashboard/server/routes/instructions.routes.d.ts +8 -0
  120. package/dist/dashboard/server/routes/instructions.routes.js +336 -0
  121. package/dist/dashboard/server/routes/knowledge.routes.d.ts +6 -0
  122. package/dist/dashboard/server/routes/knowledge.routes.js +82 -0
  123. package/dist/dashboard/server/routes/logs.routes.d.ts +6 -0
  124. package/dist/dashboard/server/routes/logs.routes.js +164 -0
  125. package/dist/dashboard/server/routes/messaging.routes.d.ts +16 -0
  126. package/dist/dashboard/server/routes/messaging.routes.js +293 -0
  127. package/dist/dashboard/server/routes/metrics.routes.d.ts +10 -0
  128. package/dist/dashboard/server/routes/metrics.routes.js +346 -0
  129. package/dist/dashboard/server/routes/scripts.routes.d.ts +9 -0
  130. package/dist/dashboard/server/routes/scripts.routes.js +84 -0
  131. package/dist/dashboard/server/routes/sqlite.routes.d.ts +9 -0
  132. package/dist/dashboard/server/routes/sqlite.routes.js +569 -0
  133. package/dist/dashboard/server/routes/status.routes.d.ts +7 -0
  134. package/dist/dashboard/server/routes/status.routes.js +183 -0
  135. package/dist/dashboard/server/routes/synthetic.routes.d.ts +7 -0
  136. package/dist/dashboard/server/routes/synthetic.routes.js +195 -0
  137. package/dist/dashboard/server/routes/tools.routes.d.ts +6 -0
  138. package/dist/dashboard/server/routes/tools.routes.js +46 -0
  139. package/dist/dashboard/server/routes/usage.routes.d.ts +6 -0
  140. package/dist/dashboard/server/routes/usage.routes.js +25 -0
  141. package/dist/dashboard/server/wsInit.d.ts +16 -0
  142. package/dist/dashboard/server/wsInit.js +35 -0
  143. package/dist/externalClientLib.d.ts +1 -0
  144. package/dist/externalClientLib.js +2 -0
  145. package/dist/minimal/index.d.ts +1 -0
  146. package/dist/minimal/index.js +140 -0
  147. package/dist/models/SessionPersistence.d.ts +115 -0
  148. package/dist/models/SessionPersistence.js +66 -0
  149. package/dist/models/instruction.d.ts +45 -0
  150. package/dist/models/instruction.js +2 -0
  151. package/dist/perf/benchmark.d.ts +1 -0
  152. package/dist/perf/benchmark.js +50 -0
  153. package/dist/portableClientWrapper.d.ts +1 -0
  154. package/dist/portableClientWrapper.js +2 -0
  155. package/dist/schemas/index.d.ts +128 -0
  156. package/dist/schemas/index.js +371 -0
  157. package/dist/scripts/runPerformanceBaseline.d.ts +1 -0
  158. package/dist/scripts/runPerformanceBaseline.js +17 -0
  159. package/dist/server/handshakeManager.d.ts +25 -0
  160. package/dist/server/handshakeManager.js +472 -0
  161. package/dist/server/index-server.d.ts +56 -0
  162. package/dist/server/index-server.js +822 -0
  163. package/dist/server/registry.d.ts +44 -0
  164. package/dist/server/registry.js +236 -0
  165. package/dist/server/sdkServer.d.ts +8 -0
  166. package/dist/server/sdkServer.js +299 -0
  167. package/dist/server/shutdownGuard.d.ts +41 -0
  168. package/dist/server/shutdownGuard.js +52 -0
  169. package/dist/server/thin-client.d.ts +22 -0
  170. package/dist/server/thin-client.js +111 -0
  171. package/dist/server/transport.d.ts +41 -0
  172. package/dist/server/transport.js +312 -0
  173. package/dist/server/transportFactory.d.ts +21 -0
  174. package/dist/server/transportFactory.js +429 -0
  175. package/dist/services/atomicFs.d.ts +22 -0
  176. package/dist/services/atomicFs.js +103 -0
  177. package/dist/services/auditLog.d.ts +38 -0
  178. package/dist/services/auditLog.js +142 -0
  179. package/dist/services/autoBackup.d.ts +14 -0
  180. package/dist/services/autoBackup.js +171 -0
  181. package/dist/services/autoSplit.d.ts +32 -0
  182. package/dist/services/autoSplit.js +113 -0
  183. package/dist/services/backupZip.d.ts +25 -0
  184. package/dist/services/backupZip.js +110 -0
  185. package/dist/services/bootstrapGating.d.ts +123 -0
  186. package/dist/services/bootstrapGating.js +221 -0
  187. package/dist/services/canonical.d.ts +23 -0
  188. package/dist/services/canonical.js +65 -0
  189. package/dist/services/categoryRules.d.ts +7 -0
  190. package/dist/services/categoryRules.js +37 -0
  191. package/dist/services/classificationService.d.ts +42 -0
  192. package/dist/services/classificationService.js +168 -0
  193. package/dist/services/embeddingService.d.ts +62 -0
  194. package/dist/services/embeddingService.js +259 -0
  195. package/dist/services/errors.d.ts +22 -0
  196. package/dist/services/errors.js +31 -0
  197. package/dist/services/featureFlags.d.ts +25 -0
  198. package/dist/services/featureFlags.js +89 -0
  199. package/dist/services/features.d.ts +13 -0
  200. package/dist/services/features.js +35 -0
  201. package/dist/services/handlers/instructions.add.d.ts +1 -0
  202. package/dist/services/handlers/instructions.add.js +496 -0
  203. package/dist/services/handlers/instructions.groom.d.ts +1 -0
  204. package/dist/services/handlers/instructions.groom.js +523 -0
  205. package/dist/services/handlers/instructions.import.d.ts +1 -0
  206. package/dist/services/handlers/instructions.import.js +173 -0
  207. package/dist/services/handlers/instructions.patch.d.ts +1 -0
  208. package/dist/services/handlers/instructions.patch.js +167 -0
  209. package/dist/services/handlers/instructions.query.d.ts +163 -0
  210. package/dist/services/handlers/instructions.query.js +522 -0
  211. package/dist/services/handlers/instructions.reload.d.ts +1 -0
  212. package/dist/services/handlers/instructions.reload.js +13 -0
  213. package/dist/services/handlers/instructions.remove.d.ts +1 -0
  214. package/dist/services/handlers/instructions.remove.js +118 -0
  215. package/dist/services/handlers/instructions.shared.d.ts +31 -0
  216. package/dist/services/handlers/instructions.shared.js +124 -0
  217. package/dist/services/handlers.activation.d.ts +1 -0
  218. package/dist/services/handlers.activation.js +203 -0
  219. package/dist/services/handlers.bootstrap.d.ts +1 -0
  220. package/dist/services/handlers.bootstrap.js +38 -0
  221. package/dist/services/handlers.dashboardConfig.d.ts +34 -0
  222. package/dist/services/handlers.dashboardConfig.js +108 -0
  223. package/dist/services/handlers.diagnostics.d.ts +1 -0
  224. package/dist/services/handlers.diagnostics.js +64 -0
  225. package/dist/services/handlers.feedback.d.ts +15 -0
  226. package/dist/services/handlers.feedback.js +378 -0
  227. package/dist/services/handlers.gates.d.ts +1 -0
  228. package/dist/services/handlers.gates.js +46 -0
  229. package/dist/services/handlers.graph.d.ts +53 -0
  230. package/dist/services/handlers.graph.js +231 -0
  231. package/dist/services/handlers.help.d.ts +1 -0
  232. package/dist/services/handlers.help.js +119 -0
  233. package/dist/services/handlers.instructionSchema.d.ts +1 -0
  234. package/dist/services/handlers.instructionSchema.js +227 -0
  235. package/dist/services/handlers.instructions.d.ts +8 -0
  236. package/dist/services/handlers.instructions.js +14 -0
  237. package/dist/services/handlers.instructionsDiagnostics.d.ts +1 -0
  238. package/dist/services/handlers.instructionsDiagnostics.js +14 -0
  239. package/dist/services/handlers.integrity.d.ts +1 -0
  240. package/dist/services/handlers.integrity.js +35 -0
  241. package/dist/services/handlers.manifest.d.ts +1 -0
  242. package/dist/services/handlers.manifest.js +24 -0
  243. package/dist/services/handlers.messaging.d.ts +12 -0
  244. package/dist/services/handlers.messaging.js +203 -0
  245. package/dist/services/handlers.metrics.d.ts +1 -0
  246. package/dist/services/handlers.metrics.js +43 -0
  247. package/dist/services/handlers.promote.d.ts +1 -0
  248. package/dist/services/handlers.promote.js +306 -0
  249. package/dist/services/handlers.prompt.d.ts +1 -0
  250. package/dist/services/handlers.prompt.js +7 -0
  251. package/dist/services/handlers.search.d.ts +69 -0
  252. package/dist/services/handlers.search.js +645 -0
  253. package/dist/services/handlers.testPrimitive.d.ts +1 -0
  254. package/dist/services/handlers.testPrimitive.js +5 -0
  255. package/dist/services/handlers.trace.d.ts +1 -0
  256. package/dist/services/handlers.trace.js +31 -0
  257. package/dist/services/handlers.usage.d.ts +1 -0
  258. package/dist/services/handlers.usage.js +11 -0
  259. package/dist/services/hotScore.d.ts +137 -0
  260. package/dist/services/hotScore.js +244 -0
  261. package/dist/services/indexContext.d.ts +117 -0
  262. package/dist/services/indexContext.js +968 -0
  263. package/dist/services/indexLoader.d.ts +44 -0
  264. package/dist/services/indexLoader.js +921 -0
  265. package/dist/services/indexRepository.d.ts +32 -0
  266. package/dist/services/indexRepository.js +71 -0
  267. package/dist/services/indexingService.d.ts +1 -0
  268. package/dist/services/indexingService.js +2 -0
  269. package/dist/services/instructions.dispatcher.d.ts +1 -0
  270. package/dist/services/instructions.dispatcher.js +231 -0
  271. package/dist/services/logPrefix.d.ts +1 -0
  272. package/dist/services/logPrefix.js +30 -0
  273. package/dist/services/logger.d.ts +52 -0
  274. package/dist/services/logger.js +268 -0
  275. package/dist/services/manifestManager.d.ts +82 -0
  276. package/dist/services/manifestManager.js +200 -0
  277. package/dist/services/messaging/agentMailbox.d.ts +60 -0
  278. package/dist/services/messaging/agentMailbox.js +353 -0
  279. package/dist/services/messaging/messagingPersistence.d.ts +20 -0
  280. package/dist/services/messaging/messagingPersistence.js +111 -0
  281. package/dist/services/messaging/messagingTypes.d.ts +150 -0
  282. package/dist/services/messaging/messagingTypes.js +66 -0
  283. package/dist/services/ownershipService.d.ts +1 -0
  284. package/dist/services/ownershipService.js +38 -0
  285. package/dist/services/performanceBaseline.d.ts +19 -0
  286. package/dist/services/performanceBaseline.js +210 -0
  287. package/dist/services/preflight.d.ts +12 -0
  288. package/dist/services/preflight.js +79 -0
  289. package/dist/services/promptReviewService.d.ts +44 -0
  290. package/dist/services/promptReviewService.js +101 -0
  291. package/dist/services/responseEnvelope.d.ts +6 -0
  292. package/dist/services/responseEnvelope.js +25 -0
  293. package/dist/services/seedBootstrap.d.ts +34 -0
  294. package/dist/services/seedBootstrap.js +427 -0
  295. package/dist/services/storage/factory.d.ts +17 -0
  296. package/dist/services/storage/factory.js +35 -0
  297. package/dist/services/storage/hashUtils.d.ts +11 -0
  298. package/dist/services/storage/hashUtils.js +35 -0
  299. package/dist/services/storage/index.d.ts +12 -0
  300. package/dist/services/storage/index.js +18 -0
  301. package/dist/services/storage/jsonFileStore.d.ts +32 -0
  302. package/dist/services/storage/jsonFileStore.js +241 -0
  303. package/dist/services/storage/migrationEngine.d.ts +35 -0
  304. package/dist/services/storage/migrationEngine.js +93 -0
  305. package/dist/services/storage/sqliteMessageStore.d.ts +53 -0
  306. package/dist/services/storage/sqliteMessageStore.js +146 -0
  307. package/dist/services/storage/sqliteSchema.d.ts +12 -0
  308. package/dist/services/storage/sqliteSchema.js +122 -0
  309. package/dist/services/storage/sqliteStore.d.ts +41 -0
  310. package/dist/services/storage/sqliteStore.js +339 -0
  311. package/dist/services/storage/sqliteUsageStore.d.ts +35 -0
  312. package/dist/services/storage/sqliteUsageStore.js +94 -0
  313. package/dist/services/storage/types.d.ts +171 -0
  314. package/dist/services/storage/types.js +12 -0
  315. package/dist/services/toolHandlers.d.ts +23 -0
  316. package/dist/services/toolHandlers.js +50 -0
  317. package/dist/services/toolRegistry.d.ts +20 -0
  318. package/dist/services/toolRegistry.js +490 -0
  319. package/dist/services/toolRegistry.zod.d.ts +10 -0
  320. package/dist/services/toolRegistry.zod.js +323 -0
  321. package/dist/services/tracing.d.ts +26 -0
  322. package/dist/services/tracing.js +260 -0
  323. package/dist/services/usageBuckets.d.ts +161 -0
  324. package/dist/services/usageBuckets.js +364 -0
  325. package/dist/services/validationService.d.ts +38 -0
  326. package/dist/services/validationService.js +125 -0
  327. package/dist/utils/BufferRing.d.ts +203 -0
  328. package/dist/utils/BufferRing.js +551 -0
  329. package/dist/utils/BufferRingExamples.d.ts +55 -0
  330. package/dist/utils/BufferRingExamples.js +188 -0
  331. package/dist/utils/envUtils.d.ts +42 -0
  332. package/dist/utils/envUtils.js +80 -0
  333. package/dist/utils/memoryMonitor.d.ts +83 -0
  334. package/dist/utils/memoryMonitor.js +275 -0
  335. package/dist/versioning/schemaVersion.d.ts +6 -0
  336. package/dist/versioning/schemaVersion.js +93 -0
  337. package/package.json +134 -0
  338. package/schemas/README.md +13 -0
  339. package/schemas/feedback-entry.schema.json +27 -0
  340. package/schemas/graph-export-v2.schema.json +60 -0
  341. package/schemas/index-server.code-schema.json +38477 -0
  342. package/schemas/instruction.schema.json +262 -0
  343. package/schemas/json-schema/SessionPersistence-persisted-admin-session.schema.json +54 -0
  344. package/schemas/json-schema/SessionPersistence-persisted-session-history-entry.schema.json +51 -0
  345. package/schemas/json-schema/SessionPersistence-persisted-web-socket-connection.schema.json +54 -0
  346. package/schemas/json-schema/SessionPersistence-session-persistence-config.schema.json +110 -0
  347. package/schemas/json-schema/SessionPersistence-session-persistence-data.schema.json +229 -0
  348. package/schemas/json-schema/SessionPersistence-session-persistence-manifest.schema.json +109 -0
  349. package/schemas/json-schema/SessionPersistence-session-persistence-metadata.schema.json +55 -0
  350. package/schemas/json-schema/instruction-audience-scope.schema.json +14 -0
  351. package/schemas/json-schema/instruction-content-type.schema.json +17 -0
  352. package/schemas/json-schema/instruction-instruction-entry.schema.json +206 -0
  353. package/schemas/json-schema/instruction-requirement-level.schema.json +16 -0
  354. package/schemas/manifest.json +78 -0
  355. package/schemas/manifest.schema.json +33 -0
  356. package/schemas/usage-batch.schema.json +16 -0
  357. package/schemas/usage-buckets.schema.json +30 -0
  358. package/schemas/usage-event.schema.json +17 -0
  359. package/scripts/copy-dashboard-assets.mjs +170 -0
  360. package/scripts/setup-hooks.cjs +28 -0
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ // Instruction Graph Export Handler
3
+ // Phase 1 minimal deterministic implementation to satisfy graphExport.spec.ts.
4
+ // Provides a structural graph representation of the current instruction index with:
5
+ // - Deterministic node ordering (alphabetical by id)
6
+ // - Two edge types: 'primary' (instruction -> primaryCategory) and 'category' (pairwise co-category)
7
+ // - Optional exclusion of primary edges via env GRAPH_INCLUDE_PRIMARY_EDGES=0
8
+ // - Large category pairwise edge skip with note when size exceeds GRAPH_LARGE_CATEGORY_CAP (default: no cap)
9
+ // - includeEdgeTypes filter (applied before truncation)
10
+ // - maxEdges truncation (stable ordering then slice)
11
+ // - format:'dot' emits Graphviz DOT output (undirected graph)
12
+ // - Shallow caching for default parameter calls (returns identical object reference until index hash changes)
13
+ // - meta: { graphSchemaVersion:1, nodeCount, edgeCount, truncated?, notes?[] }
14
+ // NOTE: This is intentionally dependency-light; future phases can enrich node/edge metadata.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.buildGraph = buildGraph;
17
+ exports.__resetGraphCache = __resetGraphCache;
18
+ const registry_1 = require("../server/registry");
19
+ const indexContext_1 = require("./indexContext");
20
+ const runtimeConfig_1 = require("../config/runtimeConfig");
21
+ // NOTE: For enriched responses we bump schema version to 2 (only when enrich=true)
22
+ const GRAPH_SCHEMA_VERSION_V1 = 1;
23
+ const GRAPH_SCHEMA_VERSION_V2 = 2;
24
+ // Cache now also considers environment-dependent knobs so toggling env vars between tests
25
+ // (e.g. disabling primary edges or applying a large category cap) does not incorrectly
26
+ // reuse a prior result built under different environmental semantics.
27
+ // We keep a small cache map for default param invocations (no format/includeEdgeTypes/maxEdges) keyed by envSig.
28
+ // Each entry invalidated when governance hash changes. Explicit env overrides still bypass caching (determinism focus).
29
+ const cachedDefaults = new Map(); // v1 only cache
30
+ // Exported for dashboard API usage
31
+ function buildGraph(params, graphCfg = (0, runtimeConfig_1.getRuntimeConfig)().graph) {
32
+ const { includeEdgeTypes, maxEdges, format, enrich, includeCategoryNodes, includeUsage } = params;
33
+ const st = (0, indexContext_1.ensureLoaded)();
34
+ const instructions = [...st.list].sort((a, b) => a.id.localeCompare(b.id));
35
+ const enriched = !!enrich;
36
+ // Build base instruction nodes (schema-dependent)
37
+ const nodes = instructions.map(i => {
38
+ if (!enriched) {
39
+ return { id: i.id };
40
+ }
41
+ const inst = i;
42
+ const n = {
43
+ id: i.id,
44
+ nodeType: 'instruction',
45
+ categories: Array.isArray(i.categories) ? [...i.categories] : [],
46
+ primaryCategory: i.primaryCategory || i.categories?.[0],
47
+ priority: typeof i.priority === 'number' ? i.priority : undefined,
48
+ priorityTier: inst.priorityTier,
49
+ requirement: inst.requirement,
50
+ owner: inst.owner,
51
+ status: inst.status,
52
+ createdAt: inst.createdAt,
53
+ updatedAt: inst.updatedAt,
54
+ };
55
+ if (includeUsage) {
56
+ const usageVal = i.usageCount;
57
+ n.usageCount = usageVal != null ? usageVal : 0; // real value or 0 fallback
58
+ }
59
+ return n;
60
+ });
61
+ const includePrimary = graphCfg.includePrimaryEdges;
62
+ const largeCap = graphCfg.largeCategoryCap;
63
+ const edges = [];
64
+ const notes = [];
65
+ // Primary edges (instruction -> pseudo-node named primaryCategory).
66
+ // We do not currently add category nodes; tests only assert edge.type membership.
67
+ if (includePrimary) {
68
+ for (const inst of instructions) {
69
+ const primary = inst.primaryCategory || inst.categories?.[0];
70
+ if (primary) {
71
+ // In enriched+categoryNodes mode, primary edge points to category node id to unify references
72
+ const toId = (enriched && includeCategoryNodes) ? `category:${primary}` : `${primary}`;
73
+ const edge = { from: inst.id, to: toId, type: 'primary' };
74
+ if (enriched)
75
+ edge.weight = 1;
76
+ edges.push(edge);
77
+ }
78
+ }
79
+ }
80
+ // Category pairwise edges (instruction id pairs that share a category)
81
+ // Build index of category -> instruction ids
82
+ const catMap = new Map();
83
+ for (const inst of instructions) {
84
+ const cats = Array.isArray(inst.categories) ? inst.categories : [];
85
+ for (const c of cats) {
86
+ const lc = c.toLowerCase();
87
+ let arr = catMap.get(lc);
88
+ if (!arr) {
89
+ arr = [];
90
+ catMap.set(lc, arr);
91
+ }
92
+ arr.push(inst.id);
93
+ }
94
+ }
95
+ const sortedCategories = [...catMap.keys()].sort((a, b) => a.localeCompare(b));
96
+ for (const cat of sortedCategories) {
97
+ const ids = catMap.get(cat);
98
+ ids.sort((a, b) => a.localeCompare(b));
99
+ if (ids.length > largeCap) {
100
+ if (Number.isFinite(largeCap)) {
101
+ notes.push(`skipped pairwise for category '${cat}' size=${ids.length} cap=${largeCap}`);
102
+ }
103
+ continue;
104
+ }
105
+ // Pairwise category edges remain for backward compatibility even when category nodes materialized
106
+ for (let i = 0; i < ids.length; i++) {
107
+ for (let j = i + 1; j < ids.length; j++) {
108
+ const edge = { from: ids[i], to: ids[j], type: 'category' };
109
+ if (enriched)
110
+ edge.weight = 1;
111
+ edges.push(edge);
112
+ }
113
+ }
114
+ }
115
+ // Optional category nodes & belongs edges (enriched mode only)
116
+ if (enriched && includeCategoryNodes) {
117
+ const allCats = sortedCategories; // already sorted
118
+ for (const cat of allCats) {
119
+ nodes.push({ id: `category:${cat}`, nodeType: 'category' });
120
+ }
121
+ // belongs edges: instruction -> category node
122
+ for (const inst of instructions) {
123
+ const cats = Array.isArray(inst.categories) ? inst.categories : [];
124
+ for (const c of cats) {
125
+ const edge = { from: inst.id, to: `category:${c}`, type: 'belongs' };
126
+ edge.weight = 1;
127
+ edges.push(edge);
128
+ }
129
+ }
130
+ }
131
+ // Filter edge types before truncation
132
+ let finalEdges = edges;
133
+ if (includeEdgeTypes && includeEdgeTypes.length) {
134
+ const allowed = new Set(includeEdgeTypes);
135
+ finalEdges = edges.filter(e => allowed.has(e.type));
136
+ }
137
+ let truncated = false;
138
+ if (typeof maxEdges === 'number' && maxEdges >= 0 && finalEdges.length > maxEdges) {
139
+ finalEdges = finalEdges.slice(0, maxEdges);
140
+ truncated = true;
141
+ }
142
+ const meta = { graphSchemaVersion: (enriched ? GRAPH_SCHEMA_VERSION_V2 : GRAPH_SCHEMA_VERSION_V1), nodeCount: nodes.length, edgeCount: finalEdges.length };
143
+ if (truncated)
144
+ meta.truncated = true;
145
+ if (notes.length)
146
+ meta.notes = notes;
147
+ const result = { meta, nodes, edges: finalEdges };
148
+ if (format === 'dot') {
149
+ // Simple undirected DOT format representation. Include all nodes (instructions + optional category nodes)
150
+ const lines = ['graph Instructions {'];
151
+ for (const n of nodes) {
152
+ lines.push(` "${n.id}";`);
153
+ }
154
+ for (const e of finalEdges) {
155
+ lines.push(` "${e.from}" -- "${e.to}" [label="${e.type}"];`);
156
+ }
157
+ lines.push('}');
158
+ result.dot = lines.join('\n');
159
+ }
160
+ else if (format === 'mermaid') {
161
+ // Mermaid undirected graph (flowchart) representation.
162
+ // We use a simple flowchart with -- links and edge type labels.
163
+ // Mermaid v10+ requires a direction (TB/LR/RL/BT); previous placeholder 'undirected' caused syntax errors.
164
+ // Using 'flowchart TB' (top-bottom) while edges use '---' (no arrow) to visually appear undirected.
165
+ const lines = ['flowchart TB'];
166
+ for (const n of nodes) {
167
+ // Escape minimal invalid chars (leave colon and hyphen intact)
168
+ const safeId = n.id.replace(/[^A-Za-z0-9_:.-]/g, '_');
169
+ lines.push(`${safeId}["${n.id}"]`);
170
+ }
171
+ for (const e of finalEdges) {
172
+ const fromSafe = e.from.replace(/[^A-Za-z0-9_:.-]/g, '_');
173
+ const toSafe = e.to.replace(/[^A-Za-z0-9_:.-]/g, '_');
174
+ lines.push(`${fromSafe} ---|${e.type}| ${toSafe}`);
175
+ }
176
+ const mermaidBody = lines.join('\n');
177
+ // Provide standard YAML frontmatter with theme + layout + themeVariables so tests can assert presence
178
+ // independent of client dashboard augmentation. Keep single themeVariables block.
179
+ const fm = [
180
+ '---',
181
+ 'config:',
182
+ ' theme: base',
183
+ ' layout: elk',
184
+ ' themeVariables:',
185
+ " primaryColor: '#58a6ff'",
186
+ " primaryTextColor: '#f0f6fc'",
187
+ " primaryBorderColor: '#30363d'",
188
+ " lineColor: '#484f58'",
189
+ " secondaryColor: '#21262d'",
190
+ " tertiaryColor: '#161b22'",
191
+ " background: '#0d1117'",
192
+ " mainBkg: '#161b22'",
193
+ " secondBkg: '#21262d'",
194
+ '---'
195
+ ].join('\n');
196
+ result.mermaid = fm + '\n' + mermaidBody;
197
+ }
198
+ return result;
199
+ }
200
+ (0, registry_1.registerHandler)('graph_export', (params) => {
201
+ const p = params || {};
202
+ const cacheEligible = !p.enrich && !p.format && !p.includeEdgeTypes && (p.maxEdges === undefined);
203
+ // If either env knob is explicitly set we skip caching to avoid cross-test flakiness where
204
+ // suites toggle values. Determinism > micro perf for explicit env usage.
205
+ const graphCfg = (0, runtimeConfig_1.getRuntimeConfig)().graph;
206
+ const envExplicit = graphCfg.explicitIncludePrimaryEnv || graphCfg.explicitLargeCategoryEnv;
207
+ const st = (0, indexContext_1.ensureLoaded)();
208
+ const hash = st.hash || (0, indexContext_1.computeGovernanceHash)(st.list);
209
+ const envSig = graphCfg.signature;
210
+ if (cacheEligible && !envExplicit) {
211
+ const entry = cachedDefaults.get(envSig);
212
+ if (entry && entry.hash === hash) {
213
+ return entry.result;
214
+ }
215
+ }
216
+ const graph = buildGraph(p, graphCfg);
217
+ // Defensive: unexpected undefined safeguard (should never happen). Emit diagnostic once.
218
+ if (!graph) {
219
+ // eslint-disable-next-line no-console
220
+ console.error('[graph_export] buildGraph returned undefined - returning empty graph (diagnostic)');
221
+ return { meta: { graphSchemaVersion: 1, nodeCount: 0, edgeCount: 0 }, nodes: [], edges: [] };
222
+ }
223
+ if (cacheEligible && !envExplicit) {
224
+ cachedDefaults.set(envSig, { hash, result: graph });
225
+ }
226
+ return graph;
227
+ });
228
+ // Test-only helper (not registered as a tool) to clear cached default between suites.
229
+ // Exported with a leading double underscore to discourage production usage.
230
+ function __resetGraphCache() { cachedDefaults.clear(); }
231
+ // Future phases: enrich node metadata (categories, priority, usage metrics), provenance, and export adapters.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Onboarding / Help Handlers
5
+ *
6
+ * Provides a stable read-only tool 'help_overview' that returns structured
7
+ * onboarding guidance so a naive / first-time agent can self-bootstrap:
8
+ * - Discover tools & their purpose
9
+ * - Understand local (P0) vs indexed (P1+) lifecycle & promotion workflow
10
+ * - Learn safe mutation enabling pattern (INDEX_SERVER_MUTATION)
11
+ * - Follow a deterministic promotion checklist
12
+ * - Avoid governance/spec recursion (documents intentionally NOT ingested)
13
+ */
14
+ const registry_1 = require("../server/registry");
15
+ const toolRegistry_1 = require("./toolRegistry");
16
+ const indexContext_1 = require("./indexContext");
17
+ const HELP_VERSION = '2025-09-14';
18
+ function buildSections() {
19
+ return [
20
+ {
21
+ id: 'intro',
22
+ title: 'Welcome',
23
+ content: 'This server exposes a governance-aware instruction index and supporting MCP tools. Use this overview to learn discovery, lifecycle tiers, and safe promotion patterns.'
24
+ },
25
+ {
26
+ id: 'discovery',
27
+ title: 'Tool Discovery Flow',
28
+ content: 'Initialize (initialize), then enumerate capabilities via meta_tools or tools/list. Call help_overview for structured guidance before attempting mutations.',
29
+ bullets: [
30
+ 'initialize → tools/call meta_tools → tools/call help_overview',
31
+ 'index_dispatch (action=list) to enumerate index entries',
32
+ 'index_schema for instruction JSON schema + examples + validation rules',
33
+ 'index_governanceHash for deterministic governance projection',
34
+ 'index_health to assess drift & recursionRisk'
35
+ ],
36
+ nextActions: ['Call meta_tools', 'Call help_overview', 'Call index_schema', 'List index via index_dispatch {action:list}']
37
+ },
38
+ {
39
+ id: 'lifecycle',
40
+ title: 'Lifecycle Tiers',
41
+ content: 'Instructions progress from local experimental (P0) to indexed stable (P1+) via explicit promotion. Governance documents (constitution, specs) are excluded from ingestion to prevent recursion.',
42
+ bullets: [
43
+ 'P0 Local: workspace-specific, rapid iteration, not shareable',
44
+ 'P1 Indexed: canonical, versioned, governance-compliant',
45
+ 'Higher tiers (P2+): optional refinement / broader distribution',
46
+ 'Denylist prevents governance/spec ingestion (see recursionRisk metric)'
47
+ ]
48
+ },
49
+ {
50
+ id: 'promotion',
51
+ title: 'Promotion Checklist',
52
+ content: 'Before promoting a P0 instruction to index ensure quality, clarity, and uniqueness benchmarks are satisfied.',
53
+ bullets: [
54
+ 'Clarity: concise title + semantic summary',
55
+ 'Accuracy: verified against current repo state',
56
+ 'Value: non-duplicative & materially helpful',
57
+ 'Maintainability: minimal volatile references',
58
+ 'Classification & priorityTier assigned',
59
+ 'Owner + review cadence set (lastReviewedAt/nextReviewDue)',
60
+ 'ChangeLog initialized if version > 1'
61
+ ],
62
+ nextActions: ['Run prompt_review for large bodies', 'Run integrity_verify', 'Submit via index_add']
63
+ },
64
+ {
65
+ id: 'mutation-safety',
66
+ title: 'Safe Mutation',
67
+ content: 'All write operations require INDEX_SERVER_MUTATION=1. Without it, mutation tools return disabled errors ensuring read-only safety by default.'
68
+ },
69
+ {
70
+ id: 'recursion-safeguards',
71
+ title: 'Recursion Safeguards',
72
+ content: 'Loader denylist excludes governance/spec seeds. index_health exposes recursionRisk and leakage metrics; expected value is recursionRisk=none.'
73
+ },
74
+ {
75
+ id: 'next-steps',
76
+ title: 'Suggested Next Steps',
77
+ content: 'Follow these steps to integrate effectively.',
78
+ bullets: [
79
+ '1. Fetch meta_tools and record stable tools',
80
+ '2. Call index_schema for instruction format guidance',
81
+ '3. List index entries (index_dispatch list)',
82
+ '4. Track usage for relevant instructions (usage_track)',
83
+ '5. Draft local P0 improvements in a separate directory',
84
+ '6. Evaluate with prompt_review & integrity_verify',
85
+ '7. Promote via index_add (with mutation enabled)',
86
+ '8. Monitor drift via index_health and governanceHash'
87
+ ]
88
+ }
89
+ ];
90
+ }
91
+ (0, registry_1.registerHandler)('help_overview', () => {
92
+ const registry = (0, toolRegistry_1.getToolRegistry)({ tier: 'admin' }).map(t => t.name);
93
+ const idx = (0, indexContext_1.getIndexState)();
94
+ return {
95
+ generatedAt: new Date().toISOString(),
96
+ version: HELP_VERSION,
97
+ summary: 'Structured onboarding guidance for new agents: discovery → lifecycle → promotion → safety.',
98
+ sections: buildSections(),
99
+ toolDiscovery: {
100
+ primary: registry.filter(n => !n.startsWith('diagnostics/')),
101
+ diagnostics: registry.filter(n => n.startsWith('diagnostics/'))
102
+ },
103
+ lifecycleModel: {
104
+ tiers: [
105
+ { tier: 'P0', purpose: 'Local experimental / workspace-scoped, not indexed' },
106
+ { tier: 'P1', purpose: 'Indexed baseline, governance compliant' },
107
+ { tier: 'P2', purpose: 'Refined / broader consumption (optional)' }
108
+ ],
109
+ promotionChecklist: [
110
+ 'Ensure uniqueness (no near-duplicate id/body)',
111
+ 'Provide semantic summary & owner',
112
+ 'Assign priorityTier & classification',
113
+ 'Set review dates',
114
+ 'Pass integrity_verify and governanceHash stable'
115
+ ]
116
+ },
117
+ index: { count: idx.list.length, hash: idx.hash }
118
+ };
119
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ /**
37
+ * Instruction Schema Handler
38
+ *
39
+ * Provides self-documentation tool 'index_schema' that returns:
40
+ * - Full JSON schema for instruction entries
41
+ * - Minimal example template
42
+ * - Validation rules and constraints
43
+ * - Field descriptions and requirements
44
+ *
45
+ * Addresses Priority 2.1: Self-documentation of instruction schema format
46
+ * Source: Production feedback entry 1967100008b4b465 (2026-01-25)
47
+ */
48
+ const registry_1 = require("../server/registry");
49
+ const fs = __importStar(require("fs"));
50
+ const path = __importStar(require("path"));
51
+ const SCHEMA_VERSION = '1.0.0';
52
+ /**
53
+ * Load the canonical instruction.schema.json from disk
54
+ */
55
+ function loadInstructionSchema() {
56
+ const schemaPath = path.join(__dirname, '../../schemas/instruction.schema.json');
57
+ return JSON.parse(fs.readFileSync(schemaPath, 'utf-8'));
58
+ }
59
+ /**
60
+ * Build a minimal valid instruction entry template
61
+ */
62
+ function buildMinimalExample() {
63
+ return {
64
+ id: "example-instruction-id",
65
+ title: "Example Instruction Title",
66
+ body: "Detailed instruction content goes here. This is the primary guidance text that agents will follow.\n\nYou can use markdown formatting for clarity.",
67
+ priority: 50,
68
+ audience: "all",
69
+ requirement: "recommended",
70
+ categories: ["example", "documentation"],
71
+ primaryCategory: "example",
72
+ contentType: "instruction",
73
+ schemaVersion: "4"
74
+ };
75
+ }
76
+ /**
77
+ * Build a comprehensive example with governance metadata
78
+ */
79
+ function _buildComprehensiveExample() {
80
+ return {
81
+ id: "comprehensive-example-id",
82
+ title: "Comprehensive Example with Governance",
83
+ body: "This example shows all recommended fields for a complete instruction.\n\n## Purpose\nDescribe the purpose and context.\n\n## Usage\nProvide specific usage guidance.\n\n## Examples\nInclude concrete examples.",
84
+ rationale: "Optional rationale explaining why this instruction exists and what problem it solves.",
85
+ priority: 30,
86
+ audience: "all",
87
+ requirement: "recommended",
88
+ categories: ["example", "documentation", "governance"],
89
+ primaryCategory: "governance",
90
+ contentType: "instruction",
91
+ schemaVersion: "4",
92
+ version: "1.0.0",
93
+ status: "approved",
94
+ owner: "platform-team",
95
+ priorityTier: "P2",
96
+ classification: "internal",
97
+ reviewIntervalDays: 90,
98
+ semanticSummary: "Example instruction demonstrating comprehensive governance metadata and best practices.",
99
+ createdAt: new Date().toISOString(),
100
+ updatedAt: new Date().toISOString(),
101
+ lastReviewedAt: new Date().toISOString(),
102
+ nextReviewDue: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString()
103
+ };
104
+ }
105
+ /**
106
+ * Define promotion workflow stages
107
+ */
108
+ function definePromotionWorkflow() {
109
+ return [
110
+ {
111
+ stage: 'P0: Local Development',
112
+ description: 'Workspace-specific experimental instruction, not indexed',
113
+ checklistItems: [
114
+ 'Create instruction file in local workspace directory',
115
+ 'Include required fields: id, title, body, priority, audience, requirement, categories',
116
+ 'Test locally with index_dispatch {action: "query", id: "your-id"}',
117
+ 'Iterate rapidly without governance overhead'
118
+ ]
119
+ },
120
+ {
121
+ stage: 'P1: Pre-Promotion Review',
122
+ description: 'Quality checks before indexing',
123
+ checklistItems: [
124
+ 'Ensure uniqueness: no duplicate id or near-duplicate body',
125
+ 'Add semantic summary (semanticSummary field)',
126
+ 'Assign owner and classification',
127
+ 'Set priorityTier (P1/P2/P3/P4)',
128
+ 'Run prompt_review for large bodies to check quality',
129
+ 'Run integrity_verify to confirm no drift',
130
+ 'Establish review cadence (lastReviewedAt, nextReviewDue, reviewIntervalDays)'
131
+ ]
132
+ },
133
+ {
134
+ stage: 'P1: Indexed Baseline',
135
+ description: 'Canonical, versioned, governance-compliant instruction',
136
+ checklistItems: [
137
+ 'Submit via index_dispatch {action: "add", ...}',
138
+ 'Verify instruction appears in index_dispatch {action: "list"}',
139
+ 'Monitor index_health for recursionRisk=none',
140
+ 'Track usage with usage_track',
141
+ 'Maintain via index_dispatch {action: "update"} as needed'
142
+ ]
143
+ },
144
+ {
145
+ stage: 'P2+: Optional Refinement',
146
+ description: 'Broader distribution and enhanced governance',
147
+ checklistItems: [
148
+ 'Accumulate usage metrics over multiple sessions',
149
+ 'Demonstrate cross-category or cross-team relevance',
150
+ 'Bump priorityTier if warranted',
151
+ 'Initialize changeLog for version tracking',
152
+ 'Consider promotion to higher tier (P2, P3, etc.)'
153
+ ]
154
+ }
155
+ ];
156
+ }
157
+ /**
158
+ * Define key validation rules
159
+ */
160
+ function defineValidationRules() {
161
+ return [
162
+ { field: 'id', rule: 'Pattern', constraint: '^[a-z0-9](?:[a-z0-9-_]{0,118}[a-z0-9])?$ (120 chars max, lowercase, no leading/trailing hyphen/underscore)' },
163
+ { field: 'id', rule: 'Uniqueness', constraint: 'Must be unique across the index' },
164
+ { field: 'title', rule: 'Length', constraint: '1-200 characters, non-empty' },
165
+ { field: 'body', rule: 'Length', constraint: '1-20,000 characters, markdown supported' },
166
+ { field: 'priority', rule: 'Range', constraint: '1-100 (lower number = higher priority)' },
167
+ { field: 'audience', rule: 'Enum', constraint: 'One of: individual, group, all' },
168
+ { field: 'requirement', rule: 'Enum', constraint: 'One of: mandatory, critical, recommended, optional, deprecated' },
169
+ { field: 'categories', rule: 'Array', constraint: '0-25 items, each 1-49 chars, lowercase, pattern: ^[a-z0-9][a-z0-9-_]{0,48}$' },
170
+ { field: 'primaryCategory', rule: 'Reference', constraint: 'Must be a member of categories array if present' },
171
+ { field: 'contentType', rule: 'Enum', constraint: 'One of: instruction (default), template, chat-session, reference, example, agent' },
172
+ { field: 'schemaVersion', rule: 'Enum', constraint: 'Currently "4"' },
173
+ { field: 'sourceHash', rule: 'Pattern', constraint: 'SHA256 hex string (64 chars) when present' },
174
+ { field: 'version', rule: 'Pattern', constraint: 'Semantic version: ^\\d+\\.\\d+\\.\\d+$ (e.g., "1.0.0")' },
175
+ { field: 'status', rule: 'Enum', constraint: 'One of: draft, review, approved, deprecated' },
176
+ { field: 'priorityTier', rule: 'Enum', constraint: 'One of: P1, P2, P3, P4' },
177
+ { field: 'classification', rule: 'Enum', constraint: 'One of: public, internal, restricted' },
178
+ { field: 'reviewIntervalDays', rule: 'Range', constraint: '1-365 days' }
179
+ ];
180
+ }
181
+ (0, registry_1.registerHandler)('index_schema', () => {
182
+ const schema = loadInstructionSchema();
183
+ const response = {
184
+ generatedAt: new Date().toISOString(),
185
+ version: SCHEMA_VERSION,
186
+ summary: 'Instruction schema template with validation rules, examples, and promotion workflow guidance.',
187
+ schema,
188
+ minimalExample: buildMinimalExample(),
189
+ requiredFields: [
190
+ 'id',
191
+ 'title',
192
+ 'body',
193
+ 'priority',
194
+ 'audience',
195
+ 'requirement',
196
+ 'categories'
197
+ ],
198
+ optionalFieldsCommon: [
199
+ 'rationale',
200
+ 'primaryCategory',
201
+ 'contentType',
202
+ 'schemaVersion',
203
+ 'version',
204
+ 'status',
205
+ 'owner',
206
+ 'priorityTier',
207
+ 'classification',
208
+ 'semanticSummary',
209
+ 'reviewIntervalDays',
210
+ 'lastReviewedAt',
211
+ 'nextReviewDue'
212
+ ],
213
+ promotionWorkflow: definePromotionWorkflow(),
214
+ validationRules: defineValidationRules(),
215
+ nextSteps: [
216
+ '1. Review the minimalExample for required fields',
217
+ '2. Study promotionWorkflow stages (P0 → P1 → P2+)',
218
+ '3. Validate against validationRules before submission',
219
+ '4. Use index_dispatch {action: "add"} to create (requires INDEX_SERVER_MUTATION=1)',
220
+ '5. Monitor index_health for recursionRisk and drift',
221
+ '6. Track usage with usage_track',
222
+ '7. Iterate via index_dispatch {action: "update"} as needed',
223
+ '8. Consult help_overview for broader lifecycle guidance'
224
+ ]
225
+ };
226
+ return response;
227
+ });
@@ -0,0 +1,8 @@
1
+ import './handlers/instructions.add';
2
+ import './handlers/instructions.import';
3
+ import './handlers/instructions.remove';
4
+ import './handlers/instructions.patch';
5
+ import './handlers/instructions.reload';
6
+ import './handlers/instructions.groom';
7
+ import './handlers/instructions.query';
8
+ export { instructionActions } from './handlers/instructions.query';
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.instructionActions = void 0;
4
+ // handlers.instructions.ts — barrel re-export (thin coordinator)
5
+ require("./handlers/instructions.add");
6
+ require("./handlers/instructions.import");
7
+ require("./handlers/instructions.remove");
8
+ require("./handlers/instructions.patch");
9
+ require("./handlers/instructions.reload");
10
+ require("./handlers/instructions.groom");
11
+ require("./handlers/instructions.query");
12
+ // Re-export instructionActions for instructions.dispatcher.ts back-compat
13
+ var instructions_query_1 = require("./handlers/instructions.query");
14
+ Object.defineProperty(exports, "instructionActions", { enumerable: true, get: function () { return instructions_query_1.instructionActions; } });
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const registry_1 = require("../server/registry");
4
+ const indexContext_1 = require("./indexContext");
5
+ // Read-only diagnostics tool exposing loader acceptance vs rejection reasoning.
6
+ // Stable, side-effect free. Optional includeTrace param surfaces a capped trace sample.
7
+ (0, registry_1.registerHandler)('index_diagnostics', (p = {}) => {
8
+ try {
9
+ return (0, indexContext_1.getIndexDiagnostics)({ includeTrace: !!p.includeTrace });
10
+ }
11
+ catch (e) {
12
+ return { error: e?.message || 'diagnostics-failed' };
13
+ }
14
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,35 @@
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 crypto_1 = __importDefault(require("crypto"));
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 features_1 = require("./features");
12
+ (0, registry_1.registerHandler)('integrity_verify', () => { const st = (0, indexContext_1.ensureLoaded)(); const issues = []; for (const e of st.list) {
13
+ const actual = crypto_1.default.createHash('sha256').update(e.body, 'utf8').digest('hex');
14
+ if (actual !== e.sourceHash)
15
+ issues.push({ id: e.id, expected: e.sourceHash, actual });
16
+ } return { hash: st.hash, count: st.list.length, issues, issueCount: issues.length }; });
17
+ (0, registry_1.registerHandler)('integrity_manifest', () => { const manifestPath = path_1.default.join(process.cwd(), 'snapshots', 'index-manifest.json'); if (!fs_1.default.existsSync(manifestPath))
18
+ return { manifest: 'missing' }; let manifest; try {
19
+ manifest = JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf8'));
20
+ }
21
+ catch (e) {
22
+ return { manifest: 'invalid', error: e instanceof Error ? e.message : String(e) };
23
+ } const entries = Array.isArray(manifest.entries) ? manifest.entries : []; const map = new Map(entries.map(e => [e.id, e])); const st = (0, indexContext_1.ensureLoaded)(); const drift = []; for (const e of st.list) {
24
+ const entry = map.get(e.id);
25
+ const bodyHash = crypto_1.default.createHash('sha256').update(e.body, 'utf8').digest('hex');
26
+ if (!entry)
27
+ drift.push({ id: e.id, change: 'added' });
28
+ else if (entry.sourceHash !== e.sourceHash || entry.bodyHash !== bodyHash)
29
+ drift.push({ id: e.id, change: 'hash-mismatch' });
30
+ } for (const id of map.keys()) {
31
+ if (!st.byId.has(id))
32
+ drift.push({ id, change: 'removed' });
33
+ } return { manifest: 'present', drift: drift.length, details: drift }; });
34
+ // Phase 0: feature flags status
35
+ (0, registry_1.registerHandler)('feature_status', () => (0, features_1.featureStatus)());