claude-flow-novice 2.0.3 → 2.0.4

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 (272) hide show
  1. package/dist/src/cli/commands/guidance.js +487 -668
  2. package/dist/src/cli/commands/index-validate.js +18 -29
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +230 -282
  4. package/dist/src/cli/commands/neural-goal-init.js +92 -125
  5. package/dist/src/cli/commands/swarm-exec.js +317 -393
  6. package/dist/src/cli/commands/swarm.js +1 -1
  7. package/dist/src/cli/commands/validate-framework.js +983 -1100
  8. package/dist/src/cli/commands/validate.js +144 -223
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +265 -277
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +6 -7
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +373 -356
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +6 -7
  13. package/dist/src/cli/simple-commands/agent.js +157 -193
  14. package/dist/src/cli/simple-commands/analysis.js +336 -446
  15. package/dist/src/cli/simple-commands/automation-executor.js +1095 -1339
  16. package/dist/src/cli/simple-commands/automation.js +481 -469
  17. package/dist/src/cli/simple-commands/batch-manager.js +261 -313
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +241 -267
  19. package/dist/src/cli/simple-commands/claude-track.js +68 -90
  20. package/dist/src/cli/simple-commands/concurrent-display.js +266 -320
  21. package/dist/src/cli/simple-commands/config.js +245 -290
  22. package/dist/src/cli/simple-commands/coordination.js +182 -234
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +812 -615
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +922 -981
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +274 -294
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +378 -457
  27. package/dist/src/cli/simple-commands/github/github-api.js +535 -574
  28. package/dist/src/cli/simple-commands/github/init.js +276 -303
  29. package/dist/src/cli/simple-commands/github.js +222 -247
  30. package/dist/src/cli/simple-commands/goal.js +51 -63
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +208 -278
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +601 -696
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +907 -979
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +406 -655
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1125 -1245
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +854 -1090
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +459 -574
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +263 -347
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +727 -768
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +745 -1049
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +227 -283
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +174 -217
  43. package/dist/src/cli/simple-commands/hive-mind.js +1842 -2283
  44. package/dist/src/cli/simple-commands/hive.js +90 -79
  45. package/dist/src/cli/simple-commands/hook-safety.js +431 -521
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +203 -254
  47. package/dist/src/cli/simple-commands/hooks.js +1064 -1204
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +294 -319
  49. package/dist/src/cli/simple-commands/init/batch-init.js +496 -562
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +13 -19
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +13 -19
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +61 -88
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +125 -150
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +42 -49
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +43 -61
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +141 -147
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +31 -44
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +64 -90
  59. package/dist/src/cli/simple-commands/init/help.js +104 -107
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +509 -528
  61. package/dist/src/cli/simple-commands/init/index.js +1510 -1759
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +234 -317
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +441 -504
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +289 -364
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +652 -728
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +416 -481
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +369 -448
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +1 -2
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +122 -99
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +32 -37
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +55 -62
  72. package/dist/src/cli/simple-commands/init/template-copier.js +421 -533
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +3 -6
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +344 -318
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +173 -218
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +65 -75
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +3 -6
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +2 -4
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +187 -230
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +53 -80
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +101 -85
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +283 -330
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +495 -561
  84. package/dist/src/cli/simple-commands/init/validation/index.js +302 -358
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +308 -359
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +389 -366
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +270 -268
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +427 -447
  89. package/dist/src/cli/simple-commands/init.js +1 -2
  90. package/dist/src/cli/simple-commands/mcp-health.js +131 -158
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +533 -634
  92. package/dist/src/cli/simple-commands/mcp.js +345 -400
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +426 -537
  94. package/dist/src/cli/simple-commands/memory.js +247 -311
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +39 -46
  96. package/dist/src/cli/simple-commands/monitor.js +294 -363
  97. package/dist/src/cli/simple-commands/neural.js +51 -65
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +538 -662
  99. package/dist/src/cli/simple-commands/pair-basic.js +528 -656
  100. package/dist/src/cli/simple-commands/pair-old.js +430 -543
  101. package/dist/src/cli/simple-commands/pair-working.js +615 -751
  102. package/dist/src/cli/simple-commands/pair.js +615 -751
  103. package/dist/src/cli/simple-commands/performance-hooks.js +83 -111
  104. package/dist/src/cli/simple-commands/performance-metrics.js +348 -433
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +708 -787
  106. package/dist/src/cli/simple-commands/process-ui.js +230 -254
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +525 -611
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1704 -1530
  109. package/dist/src/cli/simple-commands/sparc/commands.js +438 -516
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1224 -1481
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +913 -978
  112. package/dist/src/cli/simple-commands/sparc/index.js +241 -298
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +314 -390
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +965 -869
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +980 -1273
  116. package/dist/src/cli/simple-commands/sparc/specification.js +559 -645
  117. package/dist/src/cli/simple-commands/sparc-modes/architect.js +1 -1
  118. package/dist/src/cli/simple-commands/sparc-modes/ask.js +1 -1
  119. package/dist/src/cli/simple-commands/sparc-modes/code.js +1 -1
  120. package/dist/src/cli/simple-commands/sparc-modes/debug.js +1 -1
  121. package/dist/src/cli/simple-commands/sparc-modes/devops.js +1 -1
  122. package/dist/src/cli/simple-commands/sparc-modes/docs-writer.js +1 -1
  123. package/dist/src/cli/simple-commands/sparc-modes/generic.js +1 -1
  124. package/dist/src/cli/simple-commands/sparc-modes/index.js +47 -55
  125. package/dist/src/cli/simple-commands/sparc-modes/integration.js +1 -1
  126. package/dist/src/cli/simple-commands/sparc-modes/mcp.js +1 -1
  127. package/dist/src/cli/simple-commands/sparc-modes/monitoring.js +1 -1
  128. package/dist/src/cli/simple-commands/sparc-modes/optimization.js +1 -1
  129. package/dist/src/cli/simple-commands/sparc-modes/security-review.js +1 -1
  130. package/dist/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +1 -1
  131. package/dist/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +1 -1
  132. package/dist/src/cli/simple-commands/sparc-modes/supabase-admin.js +1 -1
  133. package/dist/src/cli/simple-commands/sparc-modes/swarm.js +101 -87
  134. package/dist/src/cli/simple-commands/sparc-modes/tdd.js +1 -1
  135. package/dist/src/cli/simple-commands/sparc-modes/tutorial.js +1 -1
  136. package/dist/src/cli/simple-commands/sparc.js +465 -493
  137. package/dist/src/cli/simple-commands/start-ui.js +108 -132
  138. package/dist/src/cli/simple-commands/start-wrapper.js +240 -268
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +254 -275
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +128 -171
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +61 -82
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +267 -331
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +211 -263
  145. package/dist/src/cli/simple-commands/stream-chain.js +260 -318
  146. package/dist/src/cli/simple-commands/stream-processor.js +290 -315
  147. package/dist/src/cli/simple-commands/swarm-executor.js +189 -222
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +208 -300
  149. package/dist/src/cli/simple-commands/swarm-ui.js +623 -703
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +258 -286
  151. package/dist/src/cli/simple-commands/swarm.js +887 -1082
  152. package/dist/src/cli/simple-commands/task.js +161 -206
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +59 -89
  154. package/dist/src/cli/simple-commands/token-tracker.js +258 -316
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +433 -519
  156. package/dist/src/cli/simple-commands/train-and-stream.js +275 -331
  157. package/dist/src/cli/simple-commands/training-pipeline.js +619 -725
  158. package/dist/src/cli/simple-commands/training.js +170 -227
  159. package/dist/src/cli/simple-commands/verification-hooks.js +261 -284
  160. package/dist/src/cli/simple-commands/verification-integration.js +389 -417
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +486 -606
  162. package/dist/src/cli/simple-commands/verification.js +493 -513
  163. package/dist/src/cli/simple-commands/web-server.js +766 -836
  164. package/dist/src/cli/simple-commands/webui-validator.js +106 -124
  165. package/dist/src/coordination/event-bus/demo-wasm-integration.js +212 -251
  166. package/dist/src/coordination/event-bus/qe-event-bus.js +608 -748
  167. package/dist/src/coordination/event-bus/qe-event-bus.test.js +379 -454
  168. package/dist/src/coordination/iteration-tracker.js +363 -454
  169. package/dist/src/enterprise/analytics-manager.js +1135 -0
  170. package/dist/src/enterprise/audit-manager.js +1115 -0
  171. package/dist/src/enterprise/cloud-manager.js +891 -0
  172. package/dist/src/enterprise/deployment-manager.js +966 -0
  173. package/dist/src/enterprise/index.js +6 -0
  174. package/dist/src/enterprise/project-manager.js +584 -0
  175. package/dist/src/enterprise/security-manager.js +991 -0
  176. package/dist/src/index.js +1 -1
  177. package/dist/src/mcp/DEPRECATED.js +46 -60
  178. package/dist/src/mcp/fixes/mcp-error-fixes.js +115 -134
  179. package/dist/src/mcp/implementations/agent-tracker.js +114 -128
  180. package/dist/src/mcp/implementations/daa-tools.js +292 -350
  181. package/dist/src/mcp/implementations/workflow-tools.js +329 -361
  182. package/dist/src/mcp/mcp-config-manager.js +1183 -1331
  183. package/dist/src/mcp/mcp-server-novice-simplified.js +11 -17
  184. package/dist/src/mcp/mcp-server-novice.js +11 -17
  185. package/dist/src/mcp/mcp-server-sdk.js +11 -17
  186. package/dist/src/mcp/mcp-server.js +1620 -1484
  187. package/dist/src/mcp/ruv-swarm-wrapper.js +209 -239
  188. package/dist/src/memory/advanced-serializer.js +609 -589
  189. package/dist/src/memory/enhanced-examples.js +220 -305
  190. package/dist/src/memory/enhanced-memory.js +295 -336
  191. package/dist/src/memory/enhanced-session-serializer.js +408 -492
  192. package/dist/src/memory/fallback-memory-system.js +900 -1021
  193. package/dist/src/memory/fallback-store.js +93 -131
  194. package/dist/src/memory/high-performance-serialization.js +592 -730
  195. package/dist/src/memory/in-memory-store.js +161 -213
  196. package/dist/src/memory/index.js +123 -157
  197. package/dist/src/memory/lock-free-structures.js +578 -764
  198. package/dist/src/memory/memory-mapped-persistence.js +585 -766
  199. package/dist/src/memory/memory-pressure-manager.js +569 -707
  200. package/dist/src/memory/migration.js +358 -445
  201. package/dist/src/memory/shared-memory.js +641 -768
  202. package/dist/src/memory/sqlite-store.js +245 -325
  203. package/dist/src/memory/sqlite-wrapper.js +122 -151
  204. package/dist/src/memory/swarm-memory.js +470 -603
  205. package/dist/src/memory/test-example.js +126 -134
  206. package/dist/src/memory/ultra-fast-memory-store.js +622 -821
  207. package/dist/src/memory/unified-memory-manager.js +356 -437
  208. package/dist/src/migration/index.js +92 -0
  209. package/dist/src/migration/logger.js +121 -0
  210. package/dist/src/migration/migration-analyzer.js +268 -0
  211. package/dist/src/migration/migration-runner.js +522 -0
  212. package/dist/src/migration/migration-validator.js +285 -0
  213. package/dist/src/migration/progress-reporter.js +150 -0
  214. package/dist/src/migration/rollback-manager.js +321 -0
  215. package/dist/src/migration/tests/migration-system.test.js +7 -0
  216. package/dist/src/migration/types.js +3 -0
  217. package/dist/src/swarm/CodeRefactoringSwarm.js +777 -952
  218. package/dist/src/swarm/__tests__/integration.test.js +227 -0
  219. package/dist/src/swarm/__tests__/prompt-copier.test.js +344 -0
  220. package/dist/src/swarm/advanced-orchestrator.js +1095 -0
  221. package/dist/src/swarm/claude-code-interface.js +961 -0
  222. package/dist/src/swarm/claude-flow-executor.js +229 -0
  223. package/dist/src/swarm/consensus-coordinator.js +475 -0
  224. package/dist/src/swarm/coordinator.js +2993 -0
  225. package/dist/src/swarm/direct-executor.js +1180 -0
  226. package/dist/src/swarm/error-recovery/advanced-error-detection.js +691 -0
  227. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +998 -0
  228. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +1197 -0
  229. package/dist/src/swarm/error-recovery/recovery-monitoring.js +772 -0
  230. package/dist/src/swarm/error-recovery/resilience-architecture.js +714 -0
  231. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +1319 -0
  232. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +808 -0
  233. package/dist/src/swarm/executor-v2.js +322 -0
  234. package/dist/src/swarm/executor.js +815 -0
  235. package/dist/src/swarm/hive-mind-integration.js +703 -0
  236. package/dist/src/swarm/index.js +41 -0
  237. package/dist/src/swarm/json-output-aggregator.js +267 -0
  238. package/dist/src/swarm/large-scale-coordinator.js +542 -0
  239. package/dist/src/swarm/mcp-integration-wrapper.js +628 -0
  240. package/dist/src/swarm/memory.js +1117 -0
  241. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +348 -0
  242. package/dist/src/swarm/optimizations/async-file-manager.js +285 -0
  243. package/dist/src/swarm/optimizations/circular-buffer.js +162 -0
  244. package/dist/src/swarm/optimizations/connection-pool.js +244 -0
  245. package/dist/src/swarm/optimizations/index.js +28 -0
  246. package/dist/src/swarm/optimizations/optimized-executor.js +320 -0
  247. package/dist/src/swarm/optimizations/ttl-map.js +234 -0
  248. package/dist/src/swarm/prompt-cli.js +200 -0
  249. package/dist/src/swarm/prompt-copier-enhanced.js +202 -0
  250. package/dist/src/swarm/prompt-copier.js +381 -0
  251. package/dist/src/swarm/prompt-manager.js +295 -0
  252. package/dist/src/swarm/prompt-utils.js +310 -0
  253. package/dist/src/swarm/result-aggregator.js +718 -0
  254. package/dist/src/swarm/sparc-executor.js +1568 -0
  255. package/dist/src/swarm/strategies/auto.js +758 -0
  256. package/dist/src/swarm/strategies/base.js +128 -0
  257. package/dist/src/swarm/strategies/research.js +914 -0
  258. package/dist/src/swarm/strategies/strategy-metrics-patch.js +2 -0
  259. package/dist/src/swarm/types.js +52 -0
  260. package/dist/src/swarm/workers/copy-worker.js +56 -0
  261. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +332 -400
  262. package/dist/src/utils/github-cli-safe.js +56 -64
  263. package/dist/src/utils/github-cli-safety-wrapper.js +451 -546
  264. package/dist/src/utils/npx-isolated-cache.js +104 -119
  265. package/dist/src/utils/preference-manager.js +622 -652
  266. package/dist/src/utils/timezone-utils.js +86 -105
  267. package/dist/src/validators/epic-config-schema.js +214 -0
  268. package/dist/src/validators/index.js +10 -0
  269. package/dist/src/validators/swarm-init-validator.js +259 -0
  270. package/dist/src/validators/todowrite-batching-validator.js +215 -0
  271. package/dist/src/validators/todowrite-integration.js +187 -0
  272. package/package.json +2 -2
@@ -5,737 +5,599 @@
5
5
  * eviction policies optimized for ultra-high-performance scenarios. The system
6
6
  * uses lock-free algorithms to maintain sub-microsecond performance even during
7
7
  * memory cleanup operations.
8
- */
9
-
10
- import { AtomicOperations } from './lock-free-structures.js';
11
-
8
+ */ import { AtomicOperations } from "./lock-free-structures.js";
12
9
  /**
13
10
  * Memory pressure thresholds and configuration
14
- */
15
- const MEMORY_PRESSURE_CONFIG = {
16
- // Pressure thresholds (utilization percentages)
17
- LOW_PRESSURE: 0.60, // 60% - Start background cleanup
18
- MEDIUM_PRESSURE: 0.75, // 75% - Aggressive cleanup
19
- HIGH_PRESSURE: 0.85, // 85% - Block new allocations
20
- CRITICAL_PRESSURE: 0.95, // 95% - Emergency cleanup
21
-
22
- // Eviction batch sizes
23
- BACKGROUND_BATCH: 64, // Background cleanup batch
24
- AGGRESSIVE_BATCH: 256, // Aggressive cleanup batch
25
- EMERGENCY_BATCH: 1024, // Emergency cleanup batch
26
-
27
- // Timing thresholds (nanoseconds)
28
- RECENCY_THRESHOLD: 1000000000, // 1 second
29
- FREQUENCY_THRESHOLD: 10, // Access count threshold
30
- AGE_THRESHOLD: 5000000000, // 5 seconds
31
-
32
- // Clock algorithm parameters
33
- CLOCK_SEGMENTS: 8, // Number of clock segments
34
- REFERENCE_BITS: 2, // Reference bit count (2^n levels)
35
- };
36
-
11
+ */ const MEMORY_PRESSURE_CONFIG = {
12
+ // Pressure thresholds (utilization percentages)
13
+ LOW_PRESSURE: 0.60,
14
+ MEDIUM_PRESSURE: 0.75,
15
+ HIGH_PRESSURE: 0.85,
16
+ CRITICAL_PRESSURE: 0.95,
17
+ // Eviction batch sizes
18
+ BACKGROUND_BATCH: 64,
19
+ AGGRESSIVE_BATCH: 256,
20
+ EMERGENCY_BATCH: 1024,
21
+ // Timing thresholds (nanoseconds)
22
+ RECENCY_THRESHOLD: 1000000000,
23
+ FREQUENCY_THRESHOLD: 10,
24
+ AGE_THRESHOLD: 5000000000,
25
+ // Clock algorithm parameters
26
+ CLOCK_SEGMENTS: 8,
27
+ REFERENCE_BITS: 2
28
+ };
37
29
  /**
38
30
  * Entry metadata for eviction algorithms
39
- */
40
- const ENTRY_METADATA_LAYOUT = {
41
- accessCount: 0, // uint32 - Access frequency counter
42
- lastAccess: 4, // uint64 - Last access timestamp (ns)
43
- creationTime: 12, // uint64 - Creation timestamp (ns)
44
- referenceLevel: 20, // uint8 - Reference level (0-3)
45
- evictionScore: 21, // uint8 - Calculated eviction score
46
- flags: 22, // uint16 - Entry flags
47
- // Total: 24 bytes per entry
48
- };
49
-
31
+ */ const ENTRY_METADATA_LAYOUT = {
32
+ accessCount: 0,
33
+ lastAccess: 4,
34
+ creationTime: 12,
35
+ referenceLevel: 20,
36
+ evictionScore: 21,
37
+ flags: 22
38
+ };
50
39
  /**
51
40
  * Advanced memory pressure manager with multiple eviction strategies
52
- */
53
- export class AdvancedMemoryPressureManager {
54
- constructor(memoryStore, config = MEMORY_PRESSURE_CONFIG) {
55
- this.store = memoryStore;
56
- this.config = config;
57
-
58
- // Current pressure state
59
- this.currentPressure = 0.0;
60
- this.pressureLevel = 'LOW';
61
- this.lastCleanup = 0;
62
-
63
- // Clock algorithm state
64
- this.clockHands = new Array(this.config.CLOCK_SEGMENTS).fill(0);
65
- this.currentClockSegment = 0;
66
-
67
- // Eviction statistics
68
- this.stats = {
69
- totalEvictions: 0,
70
- evictionsByReason: new Map(),
71
- avgEvictionTime: 0,
72
- lastPressureCheck: 0,
73
- backgroundCleanups: 0
74
- };
75
-
76
- // Access pattern analyzer
77
- this.accessAnalyzer = new AccessPatternAnalyzer();
78
-
79
- this.initializeMetadataRegion();
80
- this.startBackgroundCleanup();
81
- }
82
-
83
- /**
41
+ */ export class AdvancedMemoryPressureManager {
42
+ /**
84
43
  * Initialize metadata region for entry tracking
85
- */
86
- initializeMetadataRegion() {
87
- const entryCount = this.store.maxEntries;
88
- const metadataSize = entryCount * 24; // 24 bytes per entry metadata
89
-
90
- this.metadataOffset = this.store.poolOffset - metadataSize;
91
- this.metadataBuffer = new ArrayBuffer(metadataSize);
92
- this.metadataView = new DataView(this.metadataBuffer);
93
-
94
- // Clear metadata region
95
- for (let i = 0; i < metadataSize; i += 4) {
96
- this.metadataView.setUint32(i, 0);
97
- }
98
- }
99
-
100
- /**
44
+ */ initializeMetadataRegion() {
45
+ const entryCount = this.store.maxEntries;
46
+ const metadataSize = entryCount * 24; // 24 bytes per entry metadata
47
+ this.metadataOffset = this.store.poolOffset - metadataSize;
48
+ this.metadataBuffer = new ArrayBuffer(metadataSize);
49
+ this.metadataView = new DataView(this.metadataBuffer);
50
+ // Clear metadata region
51
+ for(let i = 0; i < metadataSize; i += 4){
52
+ this.metadataView.setUint32(i, 0);
53
+ }
54
+ }
55
+ /**
101
56
  * Check memory pressure and trigger appropriate response
102
- */
103
- checkMemoryPressure() {
104
- const startTime = performance.now() * 1000000;
105
-
106
- const totalMemory = this.store.totalSize;
107
- const usedMemory = this.calculateUsedMemory();
108
- const pressure = usedMemory / totalMemory;
109
-
110
- this.currentPressure = pressure;
111
- this.stats.lastPressureCheck = startTime;
112
-
113
- // Determine pressure level
114
- const previousLevel = this.pressureLevel;
115
- if (pressure >= this.config.CRITICAL_PRESSURE) {
116
- this.pressureLevel = 'CRITICAL';
117
- } else if (pressure >= this.config.HIGH_PRESSURE) {
118
- this.pressureLevel = 'HIGH';
119
- } else if (pressure >= this.config.MEDIUM_PRESSURE) {
120
- this.pressureLevel = 'MEDIUM';
121
- } else if (pressure >= this.config.LOW_PRESSURE) {
122
- this.pressureLevel = 'LOW';
123
- } else {
124
- this.pressureLevel = 'NORMAL';
125
- }
126
-
127
- // React to pressure level changes
128
- if (this.pressureLevel !== previousLevel) {
129
- this.onPressureLevelChange(previousLevel, this.pressureLevel);
130
- }
131
-
132
- // Trigger appropriate cleanup strategy
133
- switch (this.pressureLevel) {
134
- case 'CRITICAL':
135
- return this.emergencyCleanup();
136
- case 'HIGH':
137
- return this.aggressiveCleanup();
138
- case 'MEDIUM':
139
- return this.adaptiveCleanup();
140
- case 'LOW':
141
- return this.backgroundCleanup();
142
- default:
143
- return false;
144
- }
145
- }
146
-
147
- /**
57
+ */ checkMemoryPressure() {
58
+ const startTime = performance.now() * 1000000;
59
+ const totalMemory = this.store.totalSize;
60
+ const usedMemory = this.calculateUsedMemory();
61
+ const pressure = usedMemory / totalMemory;
62
+ this.currentPressure = pressure;
63
+ this.stats.lastPressureCheck = startTime;
64
+ // Determine pressure level
65
+ const previousLevel = this.pressureLevel;
66
+ if (pressure >= this.config.CRITICAL_PRESSURE) {
67
+ this.pressureLevel = 'CRITICAL';
68
+ } else if (pressure >= this.config.HIGH_PRESSURE) {
69
+ this.pressureLevel = 'HIGH';
70
+ } else if (pressure >= this.config.MEDIUM_PRESSURE) {
71
+ this.pressureLevel = 'MEDIUM';
72
+ } else if (pressure >= this.config.LOW_PRESSURE) {
73
+ this.pressureLevel = 'LOW';
74
+ } else {
75
+ this.pressureLevel = 'NORMAL';
76
+ }
77
+ // React to pressure level changes
78
+ if (this.pressureLevel !== previousLevel) {
79
+ this.onPressureLevelChange(previousLevel, this.pressureLevel);
80
+ }
81
+ // Trigger appropriate cleanup strategy
82
+ switch(this.pressureLevel){
83
+ case 'CRITICAL':
84
+ return this.emergencyCleanup();
85
+ case 'HIGH':
86
+ return this.aggressiveCleanup();
87
+ case 'MEDIUM':
88
+ return this.adaptiveCleanup();
89
+ case 'LOW':
90
+ return this.backgroundCleanup();
91
+ default:
92
+ return false;
93
+ }
94
+ }
95
+ /**
148
96
  * Emergency cleanup - most aggressive eviction
149
- */
150
- emergencyCleanup() {
151
- const startTime = performance.now() * 1000000;
152
- let evicted = 0;
153
- const targetEvictions = this.config.EMERGENCY_BATCH;
154
-
155
- // Use simple age-based eviction for speed
156
- const entries = this.getAllEntries();
157
- entries.sort((a, b) => a.lastAccess - b.lastAccess);
158
-
159
- for (let i = 0; i < Math.min(targetEvictions, entries.length); i++) {
160
- if (this.tryEvictEntry(entries[i], 'EMERGENCY_AGE')) {
161
- evicted++;
162
- }
163
- }
164
-
165
- this.recordEvictionStats('EMERGENCY', evicted, startTime);
166
- return evicted > 0;
167
- }
168
-
169
- /**
97
+ */ emergencyCleanup() {
98
+ const startTime = performance.now() * 1000000;
99
+ let evicted = 0;
100
+ const targetEvictions = this.config.EMERGENCY_BATCH;
101
+ // Use simple age-based eviction for speed
102
+ const entries = this.getAllEntries();
103
+ entries.sort((a, b)=>a.lastAccess - b.lastAccess);
104
+ for(let i = 0; i < Math.min(targetEvictions, entries.length); i++){
105
+ if (this.tryEvictEntry(entries[i], 'EMERGENCY_AGE')) {
106
+ evicted++;
107
+ }
108
+ }
109
+ this.recordEvictionStats('EMERGENCY', evicted, startTime);
110
+ return evicted > 0;
111
+ }
112
+ /**
170
113
  * Aggressive cleanup using combined scoring
171
- */
172
- aggressiveCleanup() {
173
- const startTime = performance.now() * 1000000;
174
- let evicted = 0;
175
- const targetEvictions = this.config.AGGRESSIVE_BATCH;
176
-
177
- // Calculate eviction scores for all entries
178
- const scoredEntries = this.calculateEvictionScores();
179
- scoredEntries.sort((a, b) => b.score - a.score); // Highest score = most evictable
180
-
181
- for (let i = 0; i < Math.min(targetEvictions, scoredEntries.length); i++) {
182
- if (this.tryEvictEntry(scoredEntries[i].entry, 'AGGRESSIVE_SCORE')) {
183
- evicted++;
184
- }
185
- }
186
-
187
- this.recordEvictionStats('AGGRESSIVE', evicted, startTime);
188
- return evicted > 0;
189
- }
190
-
191
- /**
114
+ */ aggressiveCleanup() {
115
+ const startTime = performance.now() * 1000000;
116
+ let evicted = 0;
117
+ const targetEvictions = this.config.AGGRESSIVE_BATCH;
118
+ // Calculate eviction scores for all entries
119
+ const scoredEntries = this.calculateEvictionScores();
120
+ scoredEntries.sort((a, b)=>b.score - a.score); // Highest score = most evictable
121
+ for(let i = 0; i < Math.min(targetEvictions, scoredEntries.length); i++){
122
+ if (this.tryEvictEntry(scoredEntries[i].entry, 'AGGRESSIVE_SCORE')) {
123
+ evicted++;
124
+ }
125
+ }
126
+ this.recordEvictionStats('AGGRESSIVE', evicted, startTime);
127
+ return evicted > 0;
128
+ }
129
+ /**
192
130
  * Adaptive cleanup based on access patterns
193
- */
194
- adaptiveCleanup() {
195
- const startTime = performance.now() * 1000000;
196
- const accessPattern = this.accessAnalyzer.getCurrentPattern();
197
-
198
- let evicted = 0;
199
- switch (accessPattern.type) {
200
- case 'SEQUENTIAL':
201
- evicted = this.sequentialEviction();
202
- break;
203
- case 'RANDOM':
204
- evicted = this.clockEviction();
205
- break;
206
- case 'HOTSPOT':
207
- evicted = this.lruEviction();
208
- break;
209
- case 'TEMPORAL':
210
- evicted = this.temporalEviction();
211
- break;
212
- default:
213
- evicted = this.clockEviction();
214
- }
215
-
216
- this.recordEvictionStats('ADAPTIVE', evicted, startTime);
217
- return evicted > 0;
218
- }
219
-
220
- /**
131
+ */ adaptiveCleanup() {
132
+ const startTime = performance.now() * 1000000;
133
+ const accessPattern = this.accessAnalyzer.getCurrentPattern();
134
+ let evicted = 0;
135
+ switch(accessPattern.type){
136
+ case 'SEQUENTIAL':
137
+ evicted = this.sequentialEviction();
138
+ break;
139
+ case 'RANDOM':
140
+ evicted = this.clockEviction();
141
+ break;
142
+ case 'HOTSPOT':
143
+ evicted = this.lruEviction();
144
+ break;
145
+ case 'TEMPORAL':
146
+ evicted = this.temporalEviction();
147
+ break;
148
+ default:
149
+ evicted = this.clockEviction();
150
+ }
151
+ this.recordEvictionStats('ADAPTIVE', evicted, startTime);
152
+ return evicted > 0;
153
+ }
154
+ /**
221
155
  * Background cleanup - least intrusive
222
- */
223
- backgroundCleanup() {
224
- if (this.isBackgroundCleanupDue()) {
225
- const startTime = performance.now() * 1000000;
226
- const evicted = this.incrementalClockEviction();
227
-
228
- this.stats.backgroundCleanups++;
229
- this.recordEvictionStats('BACKGROUND', evicted, startTime);
230
- this.lastCleanup = startTime;
231
-
232
- return evicted > 0;
233
- }
234
- return false;
235
- }
236
-
237
- /**
156
+ */ backgroundCleanup() {
157
+ if (this.isBackgroundCleanupDue()) {
158
+ const startTime = performance.now() * 1000000;
159
+ const evicted = this.incrementalClockEviction();
160
+ this.stats.backgroundCleanups++;
161
+ this.recordEvictionStats('BACKGROUND', evicted, startTime);
162
+ this.lastCleanup = startTime;
163
+ return evicted > 0;
164
+ }
165
+ return false;
166
+ }
167
+ /**
238
168
  * Enhanced Clock algorithm with reference levels
239
- */
240
- clockEviction() {
241
- const targetEvictions = this.config.AGGRESSIVE_BATCH;
242
- const clockSegment = this.currentClockSegment;
243
- let evicted = 0;
244
- let scanned = 0;
245
- const maxScan = this.store.maxEntries;
246
-
247
- while (evicted < targetEvictions && scanned < maxScan) {
248
- const entryIndex = this.clockHands[clockSegment];
249
- const entry = this.getEntryByIndex(entryIndex);
250
-
251
- if (entry) {
252
- const referenceLevel = this.getEntryReferenceLevel(entry);
253
-
254
- if (referenceLevel === 0) {
255
- // Reference level is 0, evict this entry
256
- if (this.tryEvictEntry(entry, 'CLOCK_EVICTION')) {
257
- evicted++;
258
- }
259
- } else {
260
- // Decrement reference level
261
- this.decrementReferenceLevel(entry);
262
- }
263
- }
264
-
265
- // Advance clock hand
266
- this.clockHands[clockSegment] = (entryIndex + 1) % this.store.maxEntries;
267
- scanned++;
268
- }
269
-
270
- this.currentClockSegment = (clockSegment + 1) % this.config.CLOCK_SEGMENTS;
271
- return evicted;
272
- }
273
-
274
- /**
169
+ */ clockEviction() {
170
+ const targetEvictions = this.config.AGGRESSIVE_BATCH;
171
+ const clockSegment = this.currentClockSegment;
172
+ let evicted = 0;
173
+ let scanned = 0;
174
+ const maxScan = this.store.maxEntries;
175
+ while(evicted < targetEvictions && scanned < maxScan){
176
+ const entryIndex = this.clockHands[clockSegment];
177
+ const entry = this.getEntryByIndex(entryIndex);
178
+ if (entry) {
179
+ const referenceLevel = this.getEntryReferenceLevel(entry);
180
+ if (referenceLevel === 0) {
181
+ // Reference level is 0, evict this entry
182
+ if (this.tryEvictEntry(entry, 'CLOCK_EVICTION')) {
183
+ evicted++;
184
+ }
185
+ } else {
186
+ // Decrement reference level
187
+ this.decrementReferenceLevel(entry);
188
+ }
189
+ }
190
+ // Advance clock hand
191
+ this.clockHands[clockSegment] = (entryIndex + 1) % this.store.maxEntries;
192
+ scanned++;
193
+ }
194
+ this.currentClockSegment = (clockSegment + 1) % this.config.CLOCK_SEGMENTS;
195
+ return evicted;
196
+ }
197
+ /**
275
198
  * Incremental clock eviction for background cleanup
276
- */
277
- incrementalClockEviction() {
278
- const targetEvictions = this.config.BACKGROUND_BATCH;
279
- const segmentSize = Math.ceil(this.store.maxEntries / this.config.CLOCK_SEGMENTS);
280
- const clockSegment = this.currentClockSegment;
281
-
282
- let evicted = 0;
283
- const startIndex = this.clockHands[clockSegment];
284
- const endIndex = Math.min(startIndex + segmentSize, this.store.maxEntries);
285
-
286
- for (let i = startIndex; i < endIndex && evicted < targetEvictions; i++) {
287
- const entry = this.getEntryByIndex(i);
288
- if (entry) {
289
- const age = this.getEntryAge(entry);
290
- const accessCount = this.getEntryAccessCount(entry);
291
-
292
- // Simple heuristic: evict if old and infrequently accessed
293
- if (age > this.config.AGE_THRESHOLD && accessCount < this.config.FREQUENCY_THRESHOLD) {
294
- if (this.tryEvictEntry(entry, 'BACKGROUND_AGE')) {
295
- evicted++;
296
- }
297
- }
298
- }
299
- }
300
-
301
- this.clockHands[clockSegment] = endIndex % this.store.maxEntries;
302
- return evicted;
303
- }
304
-
305
- /**
199
+ */ incrementalClockEviction() {
200
+ const targetEvictions = this.config.BACKGROUND_BATCH;
201
+ const segmentSize = Math.ceil(this.store.maxEntries / this.config.CLOCK_SEGMENTS);
202
+ const clockSegment = this.currentClockSegment;
203
+ let evicted = 0;
204
+ const startIndex = this.clockHands[clockSegment];
205
+ const endIndex = Math.min(startIndex + segmentSize, this.store.maxEntries);
206
+ for(let i = startIndex; i < endIndex && evicted < targetEvictions; i++){
207
+ const entry = this.getEntryByIndex(i);
208
+ if (entry) {
209
+ const age = this.getEntryAge(entry);
210
+ const accessCount = this.getEntryAccessCount(entry);
211
+ // Simple heuristic: evict if old and infrequently accessed
212
+ if (age > this.config.AGE_THRESHOLD && accessCount < this.config.FREQUENCY_THRESHOLD) {
213
+ if (this.tryEvictEntry(entry, 'BACKGROUND_AGE')) {
214
+ evicted++;
215
+ }
216
+ }
217
+ }
218
+ }
219
+ this.clockHands[clockSegment] = endIndex % this.store.maxEntries;
220
+ return evicted;
221
+ }
222
+ /**
306
223
  * LRU eviction using access timestamps
307
- */
308
- lruEviction() {
309
- const targetEvictions = this.config.AGGRESSIVE_BATCH;
310
- const entries = this.getAllEntries();
311
-
312
- // Sort by last access time (oldest first)
313
- entries.sort((a, b) => this.getEntryLastAccess(a) - this.getEntryLastAccess(b));
314
-
315
- let evicted = 0;
316
- for (let i = 0; i < Math.min(targetEvictions, entries.length); i++) {
317
- if (this.tryEvictEntry(entries[i], 'LRU_EVICTION')) {
318
- evicted++;
319
- }
320
- }
321
-
322
- return evicted;
323
- }
324
-
325
- /**
224
+ */ lruEviction() {
225
+ const targetEvictions = this.config.AGGRESSIVE_BATCH;
226
+ const entries = this.getAllEntries();
227
+ // Sort by last access time (oldest first)
228
+ entries.sort((a, b)=>this.getEntryLastAccess(a) - this.getEntryLastAccess(b));
229
+ let evicted = 0;
230
+ for(let i = 0; i < Math.min(targetEvictions, entries.length); i++){
231
+ if (this.tryEvictEntry(entries[i], 'LRU_EVICTION')) {
232
+ evicted++;
233
+ }
234
+ }
235
+ return evicted;
236
+ }
237
+ /**
326
238
  * Sequential access pattern eviction (FIFO-like)
327
- */
328
- sequentialEviction() {
329
- const targetEvictions = this.config.AGGRESSIVE_BATCH;
330
- const entries = this.getAllEntries();
331
-
332
- // Sort by creation time (oldest first)
333
- entries.sort((a, b) => this.getEntryCreationTime(a) - this.getEntryCreationTime(b));
334
-
335
- let evicted = 0;
336
- for (let i = 0; i < Math.min(targetEvictions, entries.length); i++) {
337
- if (this.tryEvictEntry(entries[i], 'SEQUENTIAL_FIFO')) {
338
- evicted++;
339
- }
340
- }
341
-
342
- return evicted;
343
- }
344
-
345
- /**
239
+ */ sequentialEviction() {
240
+ const targetEvictions = this.config.AGGRESSIVE_BATCH;
241
+ const entries = this.getAllEntries();
242
+ // Sort by creation time (oldest first)
243
+ entries.sort((a, b)=>this.getEntryCreationTime(a) - this.getEntryCreationTime(b));
244
+ let evicted = 0;
245
+ for(let i = 0; i < Math.min(targetEvictions, entries.length); i++){
246
+ if (this.tryEvictEntry(entries[i], 'SEQUENTIAL_FIFO')) {
247
+ evicted++;
248
+ }
249
+ }
250
+ return evicted;
251
+ }
252
+ /**
346
253
  * Temporal locality eviction - evict entries with poor temporal locality
347
- */
348
- temporalEviction() {
349
- const targetEvictions = this.config.AGGRESSIVE_BATCH;
350
- const entries = this.getAllEntries();
351
- const now = performance.now() * 1000000;
352
-
353
- // Calculate temporal locality score
354
- const temporalScores = entries.map(entry => ({
355
- entry,
356
- score: this.calculateTemporalLocalityScore(entry, now)
357
- }));
358
-
359
- // Sort by temporal locality score (worst first)
360
- temporalScores.sort((a, b) => b.score - a.score);
361
-
362
- let evicted = 0;
363
- for (let i = 0; i < Math.min(targetEvictions, temporalScores.length); i++) {
364
- if (this.tryEvictEntry(temporalScores[i].entry, 'TEMPORAL_LOCALITY')) {
365
- evicted++;
366
- }
367
- }
368
-
369
- return evicted;
370
- }
371
-
372
- /**
254
+ */ temporalEviction() {
255
+ const targetEvictions = this.config.AGGRESSIVE_BATCH;
256
+ const entries = this.getAllEntries();
257
+ const now = performance.now() * 1000000;
258
+ // Calculate temporal locality score
259
+ const temporalScores = entries.map((entry)=>({
260
+ entry,
261
+ score: this.calculateTemporalLocalityScore(entry, now)
262
+ }));
263
+ // Sort by temporal locality score (worst first)
264
+ temporalScores.sort((a, b)=>b.score - a.score);
265
+ let evicted = 0;
266
+ for(let i = 0; i < Math.min(targetEvictions, temporalScores.length); i++){
267
+ if (this.tryEvictEntry(temporalScores[i].entry, 'TEMPORAL_LOCALITY')) {
268
+ evicted++;
269
+ }
270
+ }
271
+ return evicted;
272
+ }
273
+ /**
373
274
  * Calculate comprehensive eviction scores
374
- */
375
- calculateEvictionScores() {
376
- const entries = this.getAllEntries();
377
- const now = performance.now() * 1000000;
378
-
379
- return entries.map(entry => {
380
- const age = now - this.getEntryCreationTime(entry);
381
- const recency = now - this.getEntryLastAccess(entry);
382
- const frequency = this.getEntryAccessCount(entry);
383
- const size = this.getEntrySize(entry);
384
-
385
- // Multi-factor scoring algorithm
386
- let score = 0;
387
-
388
- // Age factor (older = higher score)
389
- score += Math.min(age / this.config.AGE_THRESHOLD, 1.0) * 30;
390
-
391
- // Recency factor (less recent = higher score)
392
- score += Math.min(recency / this.config.RECENCY_THRESHOLD, 1.0) * 25;
393
-
394
- // Frequency factor (less frequent = higher score)
395
- score += Math.max(0, 1.0 - frequency / this.config.FREQUENCY_THRESHOLD) * 25;
396
-
397
- // Size factor (larger = higher score)
398
- score += Math.min(size / 1024, 1.0) * 20; // Normalize by 1KB
399
-
400
- return { entry, score };
401
- });
402
- }
403
-
404
- /**
275
+ */ calculateEvictionScores() {
276
+ const entries = this.getAllEntries();
277
+ const now = performance.now() * 1000000;
278
+ return entries.map((entry)=>{
279
+ const age = now - this.getEntryCreationTime(entry);
280
+ const recency = now - this.getEntryLastAccess(entry);
281
+ const frequency = this.getEntryAccessCount(entry);
282
+ const size = this.getEntrySize(entry);
283
+ // Multi-factor scoring algorithm
284
+ let score = 0;
285
+ // Age factor (older = higher score)
286
+ score += Math.min(age / this.config.AGE_THRESHOLD, 1.0) * 30;
287
+ // Recency factor (less recent = higher score)
288
+ score += Math.min(recency / this.config.RECENCY_THRESHOLD, 1.0) * 25;
289
+ // Frequency factor (less frequent = higher score)
290
+ score += Math.max(0, 1.0 - frequency / this.config.FREQUENCY_THRESHOLD) * 25;
291
+ // Size factor (larger = higher score)
292
+ score += Math.min(size / 1024, 1.0) * 20; // Normalize by 1KB
293
+ return {
294
+ entry,
295
+ score
296
+ };
297
+ });
298
+ }
299
+ /**
405
300
  * Calculate temporal locality score
406
- */
407
- calculateTemporalLocalityScore(entry, currentTime) {
408
- const lastAccess = this.getEntryLastAccess(entry);
409
- const accessCount = this.getEntryAccessCount(entry);
410
- const age = currentTime - this.getEntryCreationTime(entry);
411
-
412
- // Poor temporal locality = high score (more evictable)
413
- const recencyScore = (currentTime - lastAccess) / this.config.RECENCY_THRESHOLD;
414
- const frequencyScore = Math.max(0, 1.0 - accessCount / this.config.FREQUENCY_THRESHOLD);
415
- const ageScore = age / this.config.AGE_THRESHOLD;
416
-
417
- return (recencyScore * 0.4 + frequencyScore * 0.4 + ageScore * 0.2);
418
- }
419
-
420
- /**
301
+ */ calculateTemporalLocalityScore(entry, currentTime) {
302
+ const lastAccess = this.getEntryLastAccess(entry);
303
+ const accessCount = this.getEntryAccessCount(entry);
304
+ const age = currentTime - this.getEntryCreationTime(entry);
305
+ // Poor temporal locality = high score (more evictable)
306
+ const recencyScore = (currentTime - lastAccess) / this.config.RECENCY_THRESHOLD;
307
+ const frequencyScore = Math.max(0, 1.0 - accessCount / this.config.FREQUENCY_THRESHOLD);
308
+ const ageScore = age / this.config.AGE_THRESHOLD;
309
+ return recencyScore * 0.4 + frequencyScore * 0.4 + ageScore * 0.2;
310
+ }
311
+ /**
421
312
  * Try to evict a specific entry
422
- */
423
- tryEvictEntry(entry, reason) {
424
- if (!entry || this.isEntryPinned(entry)) {
425
- return false;
426
- }
427
-
428
- // Attempt to mark entry as deleted
429
- const flags = this.getEntryFlags(entry);
430
- const deletedFlag = flags | 0x80000000;
431
-
432
- const success = AtomicOperations.compareAndSwap32(
433
- this.store.buffer, entry.offset + 24, flags, deletedFlag
434
- );
435
-
436
- if (success === flags) {
437
- // Update statistics
438
- this.stats.totalEvictions++;
439
- if (!this.stats.evictionsByReason.has(reason)) {
440
- this.stats.evictionsByReason.set(reason, 0);
441
- }
442
- this.stats.evictionsByReason.set(reason,
443
- this.stats.evictionsByReason.get(reason) + 1);
444
-
445
- // Clear metadata
446
- this.clearEntryMetadata(entry);
447
-
448
- // Add to free list
449
- this.store.memoryPool.deallocate(entry.offset);
450
-
451
- return true;
452
- }
453
-
454
- return false;
455
- }
456
-
457
- /**
313
+ */ tryEvictEntry(entry, reason) {
314
+ if (!entry || this.isEntryPinned(entry)) {
315
+ return false;
316
+ }
317
+ // Attempt to mark entry as deleted
318
+ const flags = this.getEntryFlags(entry);
319
+ const deletedFlag = flags | 0x80000000;
320
+ const success = AtomicOperations.compareAndSwap32(this.store.buffer, entry.offset + 24, flags, deletedFlag);
321
+ if (success === flags) {
322
+ // Update statistics
323
+ this.stats.totalEvictions++;
324
+ if (!this.stats.evictionsByReason.has(reason)) {
325
+ this.stats.evictionsByReason.set(reason, 0);
326
+ }
327
+ this.stats.evictionsByReason.set(reason, this.stats.evictionsByReason.get(reason) + 1);
328
+ // Clear metadata
329
+ this.clearEntryMetadata(entry);
330
+ // Add to free list
331
+ this.store.memoryPool.deallocate(entry.offset);
332
+ return true;
333
+ }
334
+ return false;
335
+ }
336
+ /**
458
337
  * Update entry access metadata
459
- */
460
- updateEntryAccess(entry) {
461
- const now = performance.now() * 1000000;
462
- const metadataOffset = this.getEntryMetadataOffset(entry);
463
-
464
- // Update access count atomically
465
- AtomicOperations.atomicIncrement(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.accessCount);
466
-
467
- // Update last access timestamp
468
- AtomicOperations.storeRelease(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.lastAccess, now);
469
-
470
- // Update reference level (for clock algorithm)
471
- const currentLevel = this.metadataView.getUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel);
472
- const newLevel = Math.min(currentLevel + 1, (1 << this.config.REFERENCE_BITS) - 1);
473
- this.metadataView.setUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel, newLevel);
474
-
475
- // Record access pattern
476
- this.accessAnalyzer.recordAccess(entry, now);
477
- }
478
-
479
- /**
338
+ */ updateEntryAccess(entry) {
339
+ const now = performance.now() * 1000000;
340
+ const metadataOffset = this.getEntryMetadataOffset(entry);
341
+ // Update access count atomically
342
+ AtomicOperations.atomicIncrement(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.accessCount);
343
+ // Update last access timestamp
344
+ AtomicOperations.storeRelease(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.lastAccess, now);
345
+ // Update reference level (for clock algorithm)
346
+ const currentLevel = this.metadataView.getUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel);
347
+ const newLevel = Math.min(currentLevel + 1, (1 << this.config.REFERENCE_BITS) - 1);
348
+ this.metadataView.setUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel, newLevel);
349
+ // Record access pattern
350
+ this.accessAnalyzer.recordAccess(entry, now);
351
+ }
352
+ /**
480
353
  * Memory pressure management utilities
481
- */
482
- calculateUsedMemory() {
483
- const entryCount = AtomicOperations.loadAcquire(this.store.buffer, this.store.headerLayout.entryCount);
484
- const avgEntrySize = this.calculateAverageEntrySize();
485
- return entryCount * avgEntrySize;
486
- }
487
-
488
- calculateAverageEntrySize() {
489
- const samples = Math.min(100, this.store.maxEntries);
490
- let totalSize = 0;
491
- let sampleCount = 0;
492
-
493
- for (let i = 0; i < samples; i++) {
494
- const entry = this.getEntryByIndex(i);
495
- if (entry) {
496
- totalSize += this.getEntrySize(entry);
497
- sampleCount++;
498
- }
499
- }
500
-
501
- return sampleCount > 0 ? Math.ceil(totalSize / sampleCount) : 64;
502
- }
503
-
504
- isBackgroundCleanupDue() {
505
- const now = performance.now() * 1000000;
506
- const timeSinceLastCleanup = now - this.lastCleanup;
507
- return timeSinceLastCleanup > 1000000000; // 1 second
508
- }
509
-
510
- onPressureLevelChange(oldLevel, newLevel) {
511
- console.log(`Memory pressure changed: ${oldLevel} -> ${newLevel} (${(this.currentPressure * 100).toFixed(1)}%)`);
512
-
513
- // Adjust background cleanup frequency
514
- if (newLevel === 'HIGH' || newLevel === 'CRITICAL') {
515
- this.increaseCleanupFrequency();
516
- } else if (newLevel === 'NORMAL' || newLevel === 'LOW') {
517
- this.normalizeCleanupFrequency();
518
- }
519
- }
520
-
521
- /**
354
+ */ calculateUsedMemory() {
355
+ const entryCount = AtomicOperations.loadAcquire(this.store.buffer, this.store.headerLayout.entryCount);
356
+ const avgEntrySize = this.calculateAverageEntrySize();
357
+ return entryCount * avgEntrySize;
358
+ }
359
+ calculateAverageEntrySize() {
360
+ const samples = Math.min(100, this.store.maxEntries);
361
+ let totalSize = 0;
362
+ let sampleCount = 0;
363
+ for(let i = 0; i < samples; i++){
364
+ const entry = this.getEntryByIndex(i);
365
+ if (entry) {
366
+ totalSize += this.getEntrySize(entry);
367
+ sampleCount++;
368
+ }
369
+ }
370
+ return sampleCount > 0 ? Math.ceil(totalSize / sampleCount) : 64;
371
+ }
372
+ isBackgroundCleanupDue() {
373
+ const now = performance.now() * 1000000;
374
+ const timeSinceLastCleanup = now - this.lastCleanup;
375
+ return timeSinceLastCleanup > 1000000000; // 1 second
376
+ }
377
+ onPressureLevelChange(oldLevel, newLevel) {
378
+ console.log(`Memory pressure changed: ${oldLevel} -> ${newLevel} (${(this.currentPressure * 100).toFixed(1)}%)`);
379
+ // Adjust background cleanup frequency
380
+ if (newLevel === 'HIGH' || newLevel === 'CRITICAL') {
381
+ this.increaseCleanupFrequency();
382
+ } else if (newLevel === 'NORMAL' || newLevel === 'LOW') {
383
+ this.normalizeCleanupFrequency();
384
+ }
385
+ }
386
+ /**
522
387
  * Entry metadata access methods
523
- */
524
- getEntryMetadataOffset(entry) {
525
- return entry.index * 24; // 24 bytes per entry metadata
526
- }
527
-
528
- getEntryAccessCount(entry) {
529
- const metadataOffset = this.getEntryMetadataOffset(entry);
530
- return AtomicOperations.loadAcquire(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.accessCount);
531
- }
532
-
533
- getEntryLastAccess(entry) {
534
- const metadataOffset = this.getEntryMetadataOffset(entry);
535
- return AtomicOperations.loadAcquire(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.lastAccess);
536
- }
537
-
538
- getEntryCreationTime(entry) {
539
- const metadataOffset = this.getEntryMetadataOffset(entry);
540
- return AtomicOperations.loadAcquire(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.creationTime);
541
- }
542
-
543
- getEntryReferenceLevel(entry) {
544
- const metadataOffset = this.getEntryMetadataOffset(entry);
545
- return this.metadataView.getUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel);
546
- }
547
-
548
- decrementReferenceLevel(entry) {
549
- const metadataOffset = this.getEntryMetadataOffset(entry);
550
- const currentLevel = this.metadataView.getUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel);
551
- const newLevel = Math.max(0, currentLevel - 1);
552
- this.metadataView.setUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel, newLevel);
553
- }
554
-
555
- clearEntryMetadata(entry) {
556
- const metadataOffset = this.getEntryMetadataOffset(entry);
557
- for (let i = 0; i < 24; i += 4) {
558
- AtomicOperations.storeRelease(this.metadataBuffer, metadataOffset + i, 0);
559
- }
560
- }
561
-
562
- /**
388
+ */ getEntryMetadataOffset(entry) {
389
+ return entry.index * 24; // 24 bytes per entry metadata
390
+ }
391
+ getEntryAccessCount(entry) {
392
+ const metadataOffset = this.getEntryMetadataOffset(entry);
393
+ return AtomicOperations.loadAcquire(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.accessCount);
394
+ }
395
+ getEntryLastAccess(entry) {
396
+ const metadataOffset = this.getEntryMetadataOffset(entry);
397
+ return AtomicOperations.loadAcquire(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.lastAccess);
398
+ }
399
+ getEntryCreationTime(entry) {
400
+ const metadataOffset = this.getEntryMetadataOffset(entry);
401
+ return AtomicOperations.loadAcquire(this.metadataBuffer, metadataOffset + ENTRY_METADATA_LAYOUT.creationTime);
402
+ }
403
+ getEntryReferenceLevel(entry) {
404
+ const metadataOffset = this.getEntryMetadataOffset(entry);
405
+ return this.metadataView.getUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel);
406
+ }
407
+ decrementReferenceLevel(entry) {
408
+ const metadataOffset = this.getEntryMetadataOffset(entry);
409
+ const currentLevel = this.metadataView.getUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel);
410
+ const newLevel = Math.max(0, currentLevel - 1);
411
+ this.metadataView.setUint8(metadataOffset + ENTRY_METADATA_LAYOUT.referenceLevel, newLevel);
412
+ }
413
+ clearEntryMetadata(entry) {
414
+ const metadataOffset = this.getEntryMetadataOffset(entry);
415
+ for(let i = 0; i < 24; i += 4){
416
+ AtomicOperations.storeRelease(this.metadataBuffer, metadataOffset + i, 0);
417
+ }
418
+ }
419
+ /**
563
420
  * Statistics and monitoring
564
- */
565
- recordEvictionStats(type, evictedCount, startTime) {
566
- const endTime = performance.now() * 1000000;
567
- const duration = endTime - startTime;
568
-
569
- this.stats.avgEvictionTime = (this.stats.avgEvictionTime + duration) / 2;
570
- console.log(`${type} eviction: ${evictedCount} entries in ${(duration / 1000).toFixed(2)}μs`);
571
- }
572
-
573
- getMemoryPressureStats() {
574
- return {
575
- currentPressure: this.currentPressure,
576
- pressureLevel: this.pressureLevel,
577
- totalEvictions: this.stats.totalEvictions,
578
- evictionsByReason: Object.fromEntries(this.stats.evictionsByReason),
579
- avgEvictionTime: this.stats.avgEvictionTime,
580
- backgroundCleanups: this.stats.backgroundCleanups,
581
- accessPattern: this.accessAnalyzer.getCurrentPattern()
582
- };
583
- }
584
-
585
- /**
421
+ */ recordEvictionStats(type, evictedCount, startTime) {
422
+ const endTime = performance.now() * 1000000;
423
+ const duration = endTime - startTime;
424
+ this.stats.avgEvictionTime = (this.stats.avgEvictionTime + duration) / 2;
425
+ console.log(`${type} eviction: ${evictedCount} entries in ${(duration / 1000).toFixed(2)}μs`);
426
+ }
427
+ getMemoryPressureStats() {
428
+ return {
429
+ currentPressure: this.currentPressure,
430
+ pressureLevel: this.pressureLevel,
431
+ totalEvictions: this.stats.totalEvictions,
432
+ evictionsByReason: Object.fromEntries(this.stats.evictionsByReason),
433
+ avgEvictionTime: this.stats.avgEvictionTime,
434
+ backgroundCleanups: this.stats.backgroundCleanups,
435
+ accessPattern: this.accessAnalyzer.getCurrentPattern()
436
+ };
437
+ }
438
+ /**
586
439
  * Start background cleanup process
587
- */
588
- startBackgroundCleanup() {
589
- setInterval(() => {
590
- if (this.currentPressure > this.config.LOW_PRESSURE) {
591
- this.checkMemoryPressure();
592
- }
593
- }, 100); // Check every 100ms
594
- }
595
-
596
- // Placeholder methods for entry access (to be implemented by memory store)
597
- getAllEntries() { return []; }
598
- getEntryByIndex(index) { return null; }
599
- getEntryAge(entry) { return 0; }
600
- getEntrySize(entry) { return 64; }
601
- getEntryFlags(entry) { return 0; }
602
- isEntryPinned(entry) { return false; }
603
- increaseCleanupFrequency() { /* Implementation needed */ }
604
- normalizeCleanupFrequency() { /* Implementation needed */ }
605
- }
606
-
440
+ */ startBackgroundCleanup() {
441
+ setInterval(()=>{
442
+ if (this.currentPressure > this.config.LOW_PRESSURE) {
443
+ this.checkMemoryPressure();
444
+ }
445
+ }, 100); // Check every 100ms
446
+ }
447
+ // Placeholder methods for entry access (to be implemented by memory store)
448
+ getAllEntries() {
449
+ return [];
450
+ }
451
+ getEntryByIndex(index) {
452
+ return null;
453
+ }
454
+ getEntryAge(entry) {
455
+ return 0;
456
+ }
457
+ getEntrySize(entry) {
458
+ return 64;
459
+ }
460
+ getEntryFlags(entry) {
461
+ return 0;
462
+ }
463
+ isEntryPinned(entry) {
464
+ return false;
465
+ }
466
+ increaseCleanupFrequency() {}
467
+ normalizeCleanupFrequency() {}
468
+ constructor(memoryStore, config = MEMORY_PRESSURE_CONFIG){
469
+ this.store = memoryStore;
470
+ this.config = config;
471
+ // Current pressure state
472
+ this.currentPressure = 0.0;
473
+ this.pressureLevel = 'LOW';
474
+ this.lastCleanup = 0;
475
+ // Clock algorithm state
476
+ this.clockHands = new Array(this.config.CLOCK_SEGMENTS).fill(0);
477
+ this.currentClockSegment = 0;
478
+ // Eviction statistics
479
+ this.stats = {
480
+ totalEvictions: 0,
481
+ evictionsByReason: new Map(),
482
+ avgEvictionTime: 0,
483
+ lastPressureCheck: 0,
484
+ backgroundCleanups: 0
485
+ };
486
+ // Access pattern analyzer
487
+ this.accessAnalyzer = new AccessPatternAnalyzer();
488
+ this.initializeMetadataRegion();
489
+ this.startBackgroundCleanup();
490
+ }
491
+ }
607
492
  /**
608
493
  * Access pattern analyzer for adaptive eviction
609
- */
610
- class AccessPatternAnalyzer {
611
- constructor() {
612
- this.accessHistory = [];
613
- this.maxHistorySize = 1000;
614
- this.patternWindow = 100;
615
-
616
- this.patterns = {
617
- SEQUENTIAL: 0,
618
- RANDOM: 0,
619
- HOTSPOT: 0,
620
- TEMPORAL: 0
621
- };
622
-
623
- this.currentPattern = { type: 'RANDOM', confidence: 0.5 };
624
- }
625
-
626
- recordAccess(entry, timestamp) {
627
- this.accessHistory.push({
628
- entryId: entry.id || entry.offset,
629
- timestamp,
630
- namespace: entry.namespace
631
- });
632
-
633
- if (this.accessHistory.length > this.maxHistorySize) {
634
- this.accessHistory.shift();
635
- }
636
-
637
- // Analyze pattern periodically
638
- if (this.accessHistory.length % this.patternWindow === 0) {
639
- this.analyzePattern();
640
- }
641
- }
642
-
643
- analyzePattern() {
644
- if (this.accessHistory.length < this.patternWindow) {
645
- return;
646
- }
647
-
648
- const recent = this.accessHistory.slice(-this.patternWindow);
649
-
650
- // Reset pattern scores
651
- for (const pattern in this.patterns) {
652
- this.patterns[pattern] = 0;
653
- }
654
-
655
- // Analyze sequential access pattern
656
- let sequentialScore = this.calculateSequentialScore(recent);
657
- this.patterns.SEQUENTIAL = sequentialScore;
658
-
659
- // Analyze random access pattern
660
- let randomScore = this.calculateRandomScore(recent);
661
- this.patterns.RANDOM = randomScore;
662
-
663
- // Analyze hotspot pattern
664
- let hotspotScore = this.calculateHotspotScore(recent);
665
- this.patterns.HOTSPOT = hotspotScore;
666
-
667
- // Analyze temporal locality pattern
668
- let temporalScore = this.calculateTemporalScore(recent);
669
- this.patterns.TEMPORAL = temporalScore;
670
-
671
- // Determine dominant pattern
672
- let maxScore = 0;
673
- let dominantPattern = 'RANDOM';
674
-
675
- for (const [pattern, score] of Object.entries(this.patterns)) {
676
- if (score > maxScore) {
677
- maxScore = score;
678
- dominantPattern = pattern;
679
- }
680
- }
681
-
682
- this.currentPattern = {
683
- type: dominantPattern,
684
- confidence: maxScore,
685
- scores: { ...this.patterns }
686
- };
687
- }
688
-
689
- calculateSequentialScore(accesses) {
690
- let sequentialCount = 0;
691
- const entryIds = accesses.map(a => a.entryId).sort((a, b) => a - b);
692
-
693
- for (let i = 1; i < entryIds.length; i++) {
694
- if (entryIds[i] - entryIds[i-1] === 1) {
695
- sequentialCount++;
696
- }
697
- }
698
-
699
- return sequentialCount / (entryIds.length - 1);
700
- }
701
-
702
- calculateRandomScore(accesses) {
703
- const uniqueEntries = new Set(accesses.map(a => a.entryId));
704
- const uniqueRatio = uniqueEntries.size / accesses.length;
705
- return uniqueRatio; // Higher ratio = more random
706
- }
707
-
708
- calculateHotspotScore(accesses) {
709
- const entryFreq = new Map();
710
- for (const access of accesses) {
711
- entryFreq.set(access.entryId, (entryFreq.get(access.entryId) || 0) + 1);
712
- }
713
-
714
- const frequencies = Array.from(entryFreq.values()).sort((a, b) => b - a);
715
- const top20Percent = Math.ceil(frequencies.length * 0.2);
716
- const hotspotAccesses = frequencies.slice(0, top20Percent).reduce((a, b) => a + b, 0);
717
-
718
- return hotspotAccesses / accesses.length;
719
- }
720
-
721
- calculateTemporalScore(accesses) {
722
- const entryLastAccess = new Map();
723
- let temporalHits = 0;
724
-
725
- for (const access of accesses) {
726
- const lastAccess = entryLastAccess.get(access.entryId);
727
- if (lastAccess && access.timestamp - lastAccess < 1000000000) { // 1 second
728
- temporalHits++;
729
- }
730
- entryLastAccess.set(access.entryId, access.timestamp);
731
- }
732
-
733
- return temporalHits / accesses.length;
734
- }
735
-
736
- getCurrentPattern() {
737
- return this.currentPattern;
738
- }
739
- }
740
-
741
- export { AccessPatternAnalyzer, MEMORY_PRESSURE_CONFIG };
494
+ */ let AccessPatternAnalyzer = class AccessPatternAnalyzer {
495
+ recordAccess(entry, timestamp) {
496
+ this.accessHistory.push({
497
+ entryId: entry.id || entry.offset,
498
+ timestamp,
499
+ namespace: entry.namespace
500
+ });
501
+ if (this.accessHistory.length > this.maxHistorySize) {
502
+ this.accessHistory.shift();
503
+ }
504
+ // Analyze pattern periodically
505
+ if (this.accessHistory.length % this.patternWindow === 0) {
506
+ this.analyzePattern();
507
+ }
508
+ }
509
+ analyzePattern() {
510
+ if (this.accessHistory.length < this.patternWindow) {
511
+ return;
512
+ }
513
+ const recent = this.accessHistory.slice(-this.patternWindow);
514
+ // Reset pattern scores
515
+ for(const pattern in this.patterns){
516
+ this.patterns[pattern] = 0;
517
+ }
518
+ // Analyze sequential access pattern
519
+ let sequentialScore = this.calculateSequentialScore(recent);
520
+ this.patterns.SEQUENTIAL = sequentialScore;
521
+ // Analyze random access pattern
522
+ let randomScore = this.calculateRandomScore(recent);
523
+ this.patterns.RANDOM = randomScore;
524
+ // Analyze hotspot pattern
525
+ let hotspotScore = this.calculateHotspotScore(recent);
526
+ this.patterns.HOTSPOT = hotspotScore;
527
+ // Analyze temporal locality pattern
528
+ let temporalScore = this.calculateTemporalScore(recent);
529
+ this.patterns.TEMPORAL = temporalScore;
530
+ // Determine dominant pattern
531
+ let maxScore = 0;
532
+ let dominantPattern = 'RANDOM';
533
+ for (const [pattern, score] of Object.entries(this.patterns)){
534
+ if (score > maxScore) {
535
+ maxScore = score;
536
+ dominantPattern = pattern;
537
+ }
538
+ }
539
+ this.currentPattern = {
540
+ type: dominantPattern,
541
+ confidence: maxScore,
542
+ scores: {
543
+ ...this.patterns
544
+ }
545
+ };
546
+ }
547
+ calculateSequentialScore(accesses) {
548
+ let sequentialCount = 0;
549
+ const entryIds = accesses.map((a)=>a.entryId).sort((a, b)=>a - b);
550
+ for(let i = 1; i < entryIds.length; i++){
551
+ if (entryIds[i] - entryIds[i - 1] === 1) {
552
+ sequentialCount++;
553
+ }
554
+ }
555
+ return sequentialCount / (entryIds.length - 1);
556
+ }
557
+ calculateRandomScore(accesses) {
558
+ const uniqueEntries = new Set(accesses.map((a)=>a.entryId));
559
+ const uniqueRatio = uniqueEntries.size / accesses.length;
560
+ return uniqueRatio; // Higher ratio = more random
561
+ }
562
+ calculateHotspotScore(accesses) {
563
+ const entryFreq = new Map();
564
+ for (const access of accesses){
565
+ entryFreq.set(access.entryId, (entryFreq.get(access.entryId) || 0) + 1);
566
+ }
567
+ const frequencies = Array.from(entryFreq.values()).sort((a, b)=>b - a);
568
+ const top20Percent = Math.ceil(frequencies.length * 0.2);
569
+ const hotspotAccesses = frequencies.slice(0, top20Percent).reduce((a, b)=>a + b, 0);
570
+ return hotspotAccesses / accesses.length;
571
+ }
572
+ calculateTemporalScore(accesses) {
573
+ const entryLastAccess = new Map();
574
+ let temporalHits = 0;
575
+ for (const access of accesses){
576
+ const lastAccess = entryLastAccess.get(access.entryId);
577
+ if (lastAccess && access.timestamp - lastAccess < 1000000000) {
578
+ temporalHits++;
579
+ }
580
+ entryLastAccess.set(access.entryId, access.timestamp);
581
+ }
582
+ return temporalHits / accesses.length;
583
+ }
584
+ getCurrentPattern() {
585
+ return this.currentPattern;
586
+ }
587
+ constructor(){
588
+ this.accessHistory = [];
589
+ this.maxHistorySize = 1000;
590
+ this.patternWindow = 100;
591
+ this.patterns = {
592
+ SEQUENTIAL: 0,
593
+ RANDOM: 0,
594
+ HOTSPOT: 0,
595
+ TEMPORAL: 0
596
+ };
597
+ this.currentPattern = {
598
+ type: 'RANDOM',
599
+ confidence: 0.5
600
+ };
601
+ }
602
+ };
603
+ export { AccessPatternAnalyzer, MEMORY_PRESSURE_CONFIG };