pumuki-ast-hooks 5.3.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 (567) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1105 -0
  3. package/bin/__tests__/auto-fix-violations.spec.js +132 -0
  4. package/bin/__tests__/auto-restart-guards.spec.js +11 -0
  5. package/bin/__tests__/check-doc-drift.spec.js +11 -0
  6. package/bin/__tests__/check-version.spec.js +240 -0
  7. package/bin/__tests__/cli.spec.js +11 -0
  8. package/bin/__tests__/guard-auto-manager.spec.js +11 -0
  9. package/bin/__tests__/guard-supervisor.spec.js +11 -0
  10. package/bin/__tests__/hook-status.spec.js +11 -0
  11. package/bin/__tests__/install.spec.js +11 -0
  12. package/bin/__tests__/nightly-metrics-report.spec.js +94 -0
  13. package/bin/__tests__/plan-review.spec.js +11 -0
  14. package/bin/__tests__/predictive-hooks.spec.js +11 -0
  15. package/bin/__tests__/run-ast-adapter.spec.js +11 -0
  16. package/bin/__tests__/run-orchestrator.spec.js +11 -0
  17. package/bin/__tests__/run-playbook.spec.js +11 -0
  18. package/bin/__tests__/setup-eslint.spec.js +11 -0
  19. package/bin/__tests__/violations-api.spec.js +11 -0
  20. package/bin/__tests__/watch-hooks.spec.js +11 -0
  21. package/bin/ai-commit.sh +5 -0
  22. package/bin/audit +5 -0
  23. package/bin/audit-library.js +6 -0
  24. package/bin/auto-fix-violations.js +19 -0
  25. package/bin/auto-restart-guards.js +6 -0
  26. package/bin/check-doc-drift.js +6 -0
  27. package/bin/check-version.js +19 -0
  28. package/bin/cleanup-branches.sh +5 -0
  29. package/bin/cli.js +6 -0
  30. package/bin/demo-recording.sh +5 -0
  31. package/bin/demo-violations +5 -0
  32. package/bin/fix-enforcer +5 -0
  33. package/bin/fix-gitflow-enforcement.sh +5 -0
  34. package/bin/generate-progress-report.sh +5 -0
  35. package/bin/git-analyze-pairs.sh +5 -0
  36. package/bin/git-leave-branch-check.sh +5 -0
  37. package/bin/gitflow +5 -0
  38. package/bin/gitflow-shell-integration.sh +5 -0
  39. package/bin/guard-auto-manager.js +6 -0
  40. package/bin/guard-autostart.sh +5 -0
  41. package/bin/guard-env.sh +5 -0
  42. package/bin/guard-supervisor.js +6 -0
  43. package/bin/hook-status.js +6 -0
  44. package/bin/install-git-wrapper.sh +5 -0
  45. package/bin/install.js +6 -0
  46. package/bin/kill-mcp-zombies.sh +5 -0
  47. package/bin/nightly-metrics-report.js +8 -0
  48. package/bin/plan-review.js +6 -0
  49. package/bin/predictive-hooks.js +6 -0
  50. package/bin/pumuki-audit.js +6 -0
  51. package/bin/pumuki-init.js +19 -0
  52. package/bin/pumuki-mcp-server.js +13 -0
  53. package/bin/pumuki-mcp.js +6 -0
  54. package/bin/pumuki-rules.js +6 -0
  55. package/bin/request-no-verify-approval.sh +5 -0
  56. package/bin/run-ast-adapter.js +6 -0
  57. package/bin/run-intelligent-audit.sh +5 -0
  58. package/bin/run-orchestrator.js +6 -0
  59. package/bin/run-playbook.js +6 -0
  60. package/bin/session-loader.sh +5 -0
  61. package/bin/setup-eslint.js +6 -0
  62. package/bin/start-guards.sh +5 -0
  63. package/bin/sync-autonomous-orchestrator.sh +5 -0
  64. package/bin/sync-to-library.sh +5 -0
  65. package/bin/update-evidence.sh +5 -0
  66. package/bin/update-session-context.sh +5 -0
  67. package/bin/verify-no-verify.sh +5 -0
  68. package/bin/violations +5 -0
  69. package/bin/violations-api.js +6 -0
  70. package/bin/watch-hooks.js +6 -0
  71. package/docs/API_REFERENCE.md +161 -0
  72. package/docs/ARCHITECTURE.md +236 -0
  73. package/docs/ARCHITECTURE_DETAILED.md +499 -0
  74. package/docs/BRANCH_PROTECTION_GUIDE.md +236 -0
  75. package/docs/CODE_STANDARDS.md +440 -0
  76. package/docs/CONTRIBUTING.md +246 -0
  77. package/docs/DEPENDENCIES.md +541 -0
  78. package/docs/HOW_IT_WORKS.md +716 -0
  79. package/docs/INSTALLATION.md +784 -0
  80. package/docs/MCP_SERVERS.md +786 -0
  81. package/docs/TESTING.md +423 -0
  82. package/docs/USAGE.md +856 -0
  83. package/docs/images/ast_intelligence_01.png +0 -0
  84. package/docs/images/ast_intelligence_02.png +0 -0
  85. package/docs/images/ast_intelligence_03.png +0 -0
  86. package/docs/images/ast_intelligence_04.png +0 -0
  87. package/docs/images/ast_intelligence_05.png +0 -0
  88. package/hooks/getSkillRulesPath.ts +52 -0
  89. package/hooks/git-status-monitor.ts +160 -0
  90. package/hooks/index.js +5 -0
  91. package/hooks/notify-macos.ts +42 -0
  92. package/hooks/package.json +16 -0
  93. package/hooks/post-tool-use-tracker.sh +89 -0
  94. package/hooks/pre-tool-use-evidence-validator.ts +252 -0
  95. package/hooks/pre-tool-use-guard.ts +151 -0
  96. package/hooks/skill-activation-prompt.sh +8 -0
  97. package/hooks/skill-activation-prompt.ts +307 -0
  98. package/index.js +49 -0
  99. package/package.json +117 -0
  100. package/presentation/cli/audit.sh +24 -0
  101. package/presentation/cli/autonomous-status.sh +92 -0
  102. package/presentation/cli/categorize-violations.sh +179 -0
  103. package/presentation/cli/direct-audit-option2.sh +23 -0
  104. package/presentation/cli/direct-audit.sh +33 -0
  105. package/scripts/hooks-system/.AI_TOKEN_STATUS.txt +16 -0
  106. package/scripts/hooks-system/.audit-reports/auto-recovery.log +1 -0
  107. package/scripts/hooks-system/.audit-reports/install-wizard.log +4 -0
  108. package/scripts/hooks-system/.audit-reports/notifications.log +425 -0
  109. package/scripts/hooks-system/.audit-reports/token-monitor.log +1275 -0
  110. package/scripts/hooks-system/.audit_tmp/intelligent-report.json +44953 -0
  111. package/scripts/hooks-system/.audit_tmp/intelligent-report.txt +1338 -0
  112. package/scripts/hooks-system/.audit_tmp/severity-history.jsonl +1 -0
  113. package/scripts/hooks-system/.audit_tmp/token-usage.jsonl +1 -0
  114. package/scripts/hooks-system/.hook-system/config.json +8 -0
  115. package/scripts/hooks-system/application/CompositionRoot.js +325 -0
  116. package/scripts/hooks-system/application/__tests__/CompositionRoot.spec.js +84 -0
  117. package/scripts/hooks-system/application/commands/index.js +64 -0
  118. package/scripts/hooks-system/application/queries/index.js +60 -0
  119. package/scripts/hooks-system/application/services/AutonomousOrchestrator.js +130 -0
  120. package/scripts/hooks-system/application/services/ContextDetectionEngine.js +181 -0
  121. package/scripts/hooks-system/application/services/DynamicRulesLoader.js +182 -0
  122. package/scripts/hooks-system/application/services/GitFlowService.js +156 -0
  123. package/scripts/hooks-system/application/services/GitTreeState.js +140 -0
  124. package/scripts/hooks-system/application/services/HookSystemScheduler.js +77 -0
  125. package/scripts/hooks-system/application/services/IntelligentCommitAnalyzer.js +151 -0
  126. package/scripts/hooks-system/application/services/IntelligentGitTreeMonitor.js +118 -0
  127. package/scripts/hooks-system/application/services/PlatformAnalysisService.js +173 -0
  128. package/scripts/hooks-system/application/services/PlatformDetectionService.js +168 -0
  129. package/scripts/hooks-system/application/services/PlaybookRunner.js +39 -0
  130. package/scripts/hooks-system/application/services/PredictiveHookAdvisor.js +56 -0
  131. package/scripts/hooks-system/application/services/RealtimeGuardPlugin.js +62 -0
  132. package/scripts/hooks-system/application/services/RealtimeGuardService.js +374 -0
  133. package/scripts/hooks-system/application/services/SmartDirtyTreeAnalyzer.js +63 -0
  134. package/scripts/hooks-system/application/services/__tests__/AutonomousOrchestrator.spec.js +36 -0
  135. package/scripts/hooks-system/application/services/__tests__/ContextDetectionEngine.spec.js +33 -0
  136. package/scripts/hooks-system/application/services/__tests__/DynamicRulesLoader.spec.js +43 -0
  137. package/scripts/hooks-system/application/services/__tests__/GitTreeState.spec.js +163 -0
  138. package/scripts/hooks-system/application/services/__tests__/HookSystemScheduler.spec.js +207 -0
  139. package/scripts/hooks-system/application/services/__tests__/IntelligentCommitAnalyzer.spec.js +365 -0
  140. package/scripts/hooks-system/application/services/__tests__/IntelligentGitTreeMonitor.spec.js +188 -0
  141. package/scripts/hooks-system/application/services/__tests__/PlatformDetectionService.spec.js +28 -0
  142. package/scripts/hooks-system/application/services/__tests__/PlaybookRunner.spec.js +143 -0
  143. package/scripts/hooks-system/application/services/__tests__/PredictiveHookAdvisor.spec.js +181 -0
  144. package/scripts/hooks-system/application/services/__tests__/RealtimeGuardPlugin.spec.js +45 -0
  145. package/scripts/hooks-system/application/services/__tests__/RealtimeGuardService.critical.spec.js +401 -0
  146. package/scripts/hooks-system/application/services/commit/CommitMessageGenerator.js +34 -0
  147. package/scripts/hooks-system/application/services/commit/FeatureDetector.js +101 -0
  148. package/scripts/hooks-system/application/services/evidence/EvidenceContextManager.js +163 -0
  149. package/scripts/hooks-system/application/services/evidence/__tests__/EvidenceContextManager.spec.js +98 -0
  150. package/scripts/hooks-system/application/services/guard/GuardAutoManagerService.js +169 -0
  151. package/scripts/hooks-system/application/services/guard/GuardConfig.js +15 -0
  152. package/scripts/hooks-system/application/services/guard/GuardEventLogger.js +70 -0
  153. package/scripts/hooks-system/application/services/guard/GuardHealthReminder.js +54 -0
  154. package/scripts/hooks-system/application/services/guard/GuardHeartbeatMonitor.js +94 -0
  155. package/scripts/hooks-system/application/services/guard/GuardLockManager.js +72 -0
  156. package/scripts/hooks-system/application/services/guard/GuardMonitorLoop.js +29 -0
  157. package/scripts/hooks-system/application/services/guard/GuardNotificationHandler.js +36 -0
  158. package/scripts/hooks-system/application/services/guard/GuardProcessManager.js +113 -0
  159. package/scripts/hooks-system/application/services/guard/GuardRecoveryService.js +90 -0
  160. package/scripts/hooks-system/application/services/guard/__tests__/GuardAutoManagerService.spec.js +77 -0
  161. package/scripts/hooks-system/application/services/installation/ConfigurationGeneratorService.js +123 -0
  162. package/scripts/hooks-system/application/services/installation/FileSystemInstallerService.js +112 -0
  163. package/scripts/hooks-system/application/services/installation/GitEnvironmentService.js +166 -0
  164. package/scripts/hooks-system/application/services/installation/HookInstaller.js +197 -0
  165. package/scripts/hooks-system/application/services/installation/IdeIntegrationService.js +37 -0
  166. package/scripts/hooks-system/application/services/installation/InstallService.js +130 -0
  167. package/scripts/hooks-system/application/services/installation/McpConfigurator.js +172 -0
  168. package/scripts/hooks-system/application/services/installation/PlatformDetectorService.js +36 -0
  169. package/scripts/hooks-system/application/services/installation/VSCodeTaskConfigurator.js +97 -0
  170. package/scripts/hooks-system/application/services/logging/UnifiedLogger.js +142 -0
  171. package/scripts/hooks-system/application/services/logging/__tests__/UnifiedLogger.spec.js +66 -0
  172. package/scripts/hooks-system/application/services/monitoring/ActivityMonitor.js +80 -0
  173. package/scripts/hooks-system/application/services/monitoring/AstMonitor.js +140 -0
  174. package/scripts/hooks-system/application/services/monitoring/DevDocsMonitor.js +85 -0
  175. package/scripts/hooks-system/application/services/monitoring/EvidenceMonitor.js +103 -0
  176. package/scripts/hooks-system/application/services/monitoring/EvidenceMonitorService.js +162 -0
  177. package/scripts/hooks-system/application/services/monitoring/GitTreeMonitor.js +123 -0
  178. package/scripts/hooks-system/application/services/monitoring/GitTreeMonitorService.js +114 -0
  179. package/scripts/hooks-system/application/services/monitoring/HealthCheckProviders.js +153 -0
  180. package/scripts/hooks-system/application/services/monitoring/HealthCheckService.js +118 -0
  181. package/scripts/hooks-system/application/services/monitoring/HeartbeatMonitorService.js +61 -0
  182. package/scripts/hooks-system/application/services/monitoring/TokenMonitor.js +60 -0
  183. package/scripts/hooks-system/application/services/monitoring/__tests__/EvidenceMonitorService.spec.js +107 -0
  184. package/scripts/hooks-system/application/services/monitoring/__tests__/GitTreeMonitorService.spec.js +27 -0
  185. package/scripts/hooks-system/application/services/monitoring/__tests__/HealthCheckProviders.spec.js +68 -0
  186. package/scripts/hooks-system/application/services/monitoring/__tests__/HealthCheckService.spec.js +69 -0
  187. package/scripts/hooks-system/application/services/monitoring/__tests__/HeartbeatMonitorService.spec.js +35 -0
  188. package/scripts/hooks-system/application/services/notification/MacNotificationSender.js +106 -0
  189. package/scripts/hooks-system/application/services/notification/NotificationCenterService.js +221 -0
  190. package/scripts/hooks-system/application/services/notification/NotificationDispatcher.js +42 -0
  191. package/scripts/hooks-system/application/services/notification/__tests__/NotificationCenterService.spec.js +40 -0
  192. package/scripts/hooks-system/application/services/notification/components/NotificationCooldownManager.js +62 -0
  193. package/scripts/hooks-system/application/services/notification/components/NotificationDeduplicator.js +67 -0
  194. package/scripts/hooks-system/application/services/notification/components/NotificationQueue.js +36 -0
  195. package/scripts/hooks-system/application/services/notification/components/NotificationRetryExecutor.js +58 -0
  196. package/scripts/hooks-system/application/services/platform/PlatformHeuristics.js +144 -0
  197. package/scripts/hooks-system/application/services/recovery/AutoRecoveryManager.js +137 -0
  198. package/scripts/hooks-system/application/services/recovery/__tests__/AutoRecoveryManager.spec.js +62 -0
  199. package/scripts/hooks-system/application/services/smart-commit/CommitMessageSuggester.js +97 -0
  200. package/scripts/hooks-system/application/services/smart-commit/FileContextGrouper.js +114 -0
  201. package/scripts/hooks-system/application/services/smart-commit/SmartCommitSummaryBuilder.js +53 -0
  202. package/scripts/hooks-system/application/services/token/CursorTokenService.js +44 -0
  203. package/scripts/hooks-system/application/services/token/TokenMetricsService.js +109 -0
  204. package/scripts/hooks-system/application/services/token/TokenMonitorService.js +160 -0
  205. package/scripts/hooks-system/application/services/token/TokenStatusReporter.js +56 -0
  206. package/scripts/hooks-system/application/services/token/__tests__/CursorTokenService.spec.js +69 -0
  207. package/scripts/hooks-system/application/services/token/__tests__/TokenMonitorService.spec.js +185 -0
  208. package/scripts/hooks-system/application/state/HookSystemStateMachine.js +59 -0
  209. package/scripts/hooks-system/application/state/__tests__/HookSystemStateMachine.spec.js +115 -0
  210. package/scripts/hooks-system/application/use-cases/AnalyzeCodebaseUseCase.js +54 -0
  211. package/scripts/hooks-system/application/use-cases/AnalyzeStagedFilesUseCase.js +61 -0
  212. package/scripts/hooks-system/application/use-cases/AutoExecuteAIStartUseCase.js +123 -0
  213. package/scripts/hooks-system/application/use-cases/BlockCommitUseCase.js +90 -0
  214. package/scripts/hooks-system/application/use-cases/GenerateAuditReportUseCase.js +184 -0
  215. package/scripts/hooks-system/application/use-cases/__tests__/AnalyzeCodebaseUseCase.spec.js +156 -0
  216. package/scripts/hooks-system/application/use-cases/__tests__/AnalyzeStagedFilesUseCase.spec.js +146 -0
  217. package/scripts/hooks-system/application/use-cases/__tests__/AutoExecuteAIStartUseCase.spec.js +89 -0
  218. package/scripts/hooks-system/application/use-cases/__tests__/BlockCommitUseCase.spec.js +171 -0
  219. package/scripts/hooks-system/application/use-cases/__tests__/GenerateAuditReportUseCase.spec.js +207 -0
  220. package/scripts/hooks-system/bin/__tests__/auto-fix-violations.spec.js +132 -0
  221. package/scripts/hooks-system/bin/__tests__/auto-restart-guards.spec.js +11 -0
  222. package/scripts/hooks-system/bin/__tests__/check-doc-drift.spec.js +11 -0
  223. package/scripts/hooks-system/bin/__tests__/check-version.spec.js +240 -0
  224. package/scripts/hooks-system/bin/__tests__/cli.spec.js +11 -0
  225. package/scripts/hooks-system/bin/__tests__/guard-auto-manager.spec.js +11 -0
  226. package/scripts/hooks-system/bin/__tests__/guard-supervisor.spec.js +11 -0
  227. package/scripts/hooks-system/bin/__tests__/hook-status.spec.js +11 -0
  228. package/scripts/hooks-system/bin/__tests__/install.spec.js +11 -0
  229. package/scripts/hooks-system/bin/__tests__/nightly-metrics-report.spec.js +94 -0
  230. package/scripts/hooks-system/bin/__tests__/plan-review.spec.js +11 -0
  231. package/scripts/hooks-system/bin/__tests__/predictive-hooks.spec.js +11 -0
  232. package/scripts/hooks-system/bin/__tests__/run-ast-adapter.spec.js +11 -0
  233. package/scripts/hooks-system/bin/__tests__/run-orchestrator.spec.js +11 -0
  234. package/scripts/hooks-system/bin/__tests__/run-playbook.spec.js +11 -0
  235. package/scripts/hooks-system/bin/__tests__/setup-eslint.spec.js +11 -0
  236. package/scripts/hooks-system/bin/__tests__/violations-api.spec.js +11 -0
  237. package/scripts/hooks-system/bin/__tests__/watch-hooks.spec.js +11 -0
  238. package/scripts/hooks-system/bin/ai-commit.sh +63 -0
  239. package/scripts/hooks-system/bin/audit +463 -0
  240. package/scripts/hooks-system/bin/audit-library.js +54 -0
  241. package/scripts/hooks-system/bin/auto-fix-violations.js +130 -0
  242. package/scripts/hooks-system/bin/auto-restart-guards.js +93 -0
  243. package/scripts/hooks-system/bin/check-doc-drift.js +35 -0
  244. package/scripts/hooks-system/bin/check-version.js +201 -0
  245. package/scripts/hooks-system/bin/cleanup-branches.sh +106 -0
  246. package/scripts/hooks-system/bin/cli.js +208 -0
  247. package/scripts/hooks-system/bin/demo-recording.sh +57 -0
  248. package/scripts/hooks-system/bin/demo-violations +44 -0
  249. package/scripts/hooks-system/bin/fix-enforcer +27 -0
  250. package/scripts/hooks-system/bin/fix-gitflow-enforcement.sh +68 -0
  251. package/scripts/hooks-system/bin/generate-progress-report.sh +129 -0
  252. package/scripts/hooks-system/bin/git-analyze-pairs.sh +0 -0
  253. package/scripts/hooks-system/bin/git-leave-branch-check.sh +73 -0
  254. package/scripts/hooks-system/bin/gitflow +17 -0
  255. package/scripts/hooks-system/bin/gitflow-shell-integration.sh +64 -0
  256. package/scripts/hooks-system/bin/guard-auto-manager.js +44 -0
  257. package/scripts/hooks-system/bin/guard-autostart.sh +158 -0
  258. package/scripts/hooks-system/bin/guard-env.sh +40 -0
  259. package/scripts/hooks-system/bin/guard-supervisor.js +516 -0
  260. package/scripts/hooks-system/bin/hook-status.js +41 -0
  261. package/scripts/hooks-system/bin/install-git-wrapper.sh +53 -0
  262. package/scripts/hooks-system/bin/install.js +10 -0
  263. package/scripts/hooks-system/bin/kill-mcp-zombies.sh +48 -0
  264. package/scripts/hooks-system/bin/nightly-metrics-report.js +138 -0
  265. package/scripts/hooks-system/bin/plan-review.js +31 -0
  266. package/scripts/hooks-system/bin/predictive-hooks.js +18 -0
  267. package/scripts/hooks-system/bin/pumuki-audit.js +113 -0
  268. package/scripts/hooks-system/bin/pumuki-init.js +104 -0
  269. package/scripts/hooks-system/bin/pumuki-mcp.js +74 -0
  270. package/scripts/hooks-system/bin/pumuki-rules.js +74 -0
  271. package/scripts/hooks-system/bin/request-no-verify-approval.sh +116 -0
  272. package/scripts/hooks-system/bin/run-ast-adapter.js +86 -0
  273. package/scripts/hooks-system/bin/run-intelligent-audit.sh +67 -0
  274. package/scripts/hooks-system/bin/run-orchestrator.js +27 -0
  275. package/scripts/hooks-system/bin/run-playbook.js +23 -0
  276. package/scripts/hooks-system/bin/session-loader.sh +264 -0
  277. package/scripts/hooks-system/bin/setup-eslint.js +110 -0
  278. package/scripts/hooks-system/bin/start-guards.sh +190 -0
  279. package/scripts/hooks-system/bin/sync-autonomous-orchestrator.sh +32 -0
  280. package/scripts/hooks-system/bin/sync-to-library.sh +46 -0
  281. package/scripts/hooks-system/bin/update-evidence.sh +1167 -0
  282. package/scripts/hooks-system/bin/update-session-context.sh +261 -0
  283. package/scripts/hooks-system/bin/verify-no-verify.sh +68 -0
  284. package/scripts/hooks-system/bin/violations +20 -0
  285. package/scripts/hooks-system/bin/violations-api.js +345 -0
  286. package/scripts/hooks-system/bin/watch-hooks.js +20 -0
  287. package/scripts/hooks-system/config/project.config.json +36 -0
  288. package/scripts/hooks-system/config/state-map.json +12 -0
  289. package/scripts/hooks-system/domain/entities/AuditResult.js +139 -0
  290. package/scripts/hooks-system/domain/entities/Finding.js +116 -0
  291. package/scripts/hooks-system/domain/entities/SeverityConfig.js +73 -0
  292. package/scripts/hooks-system/domain/entities/SeverityConfig.ts +90 -0
  293. package/scripts/hooks-system/domain/entities/__tests__/AuditResult.spec.js +450 -0
  294. package/scripts/hooks-system/domain/entities/__tests__/Finding.spec.js +335 -0
  295. package/scripts/hooks-system/domain/entities/__tests__/SeverityConfig.spec.js +240 -0
  296. package/scripts/hooks-system/domain/entities/__tests__/entities.spec.js +29 -0
  297. package/scripts/hooks-system/domain/errors/__tests__/DomainErrors.spec.js +59 -0
  298. package/scripts/hooks-system/domain/errors/index.js +169 -0
  299. package/scripts/hooks-system/domain/events/__tests__/DomainEvents.spec.js +60 -0
  300. package/scripts/hooks-system/domain/events/index.js +121 -0
  301. package/scripts/hooks-system/domain/ports/IAstPort.js +67 -0
  302. package/scripts/hooks-system/domain/ports/IEvidencePort.js +86 -0
  303. package/scripts/hooks-system/domain/ports/IGitCommandPort.js +110 -0
  304. package/scripts/hooks-system/domain/ports/IGitPort.js +114 -0
  305. package/scripts/hooks-system/domain/ports/IGitQueryPort.js +93 -0
  306. package/scripts/hooks-system/domain/ports/INotificationPort.js +35 -0
  307. package/scripts/hooks-system/domain/ports/__tests__/ports.spec.js +36 -0
  308. package/scripts/hooks-system/domain/ports/index.js +14 -0
  309. package/scripts/hooks-system/domain/repositories/ICursorTokenRepository.js +13 -0
  310. package/scripts/hooks-system/domain/repositories/IFindingsRepository.js +30 -0
  311. package/scripts/hooks-system/domain/repositories/__tests__/IFindingsRepository.spec.js +18 -0
  312. package/scripts/hooks-system/domain/rules/CommitBlockingRules.js +142 -0
  313. package/scripts/hooks-system/domain/rules/__tests__/CommitBlockingRules.spec.js +18 -0
  314. package/scripts/hooks-system/domain/services/AuditAnalyzer.js +103 -0
  315. package/scripts/hooks-system/domain/services/AuditFilter.js +26 -0
  316. package/scripts/hooks-system/domain/services/AuditResultSerializer.js +35 -0
  317. package/scripts/hooks-system/domain/services/AuditScorer.js +38 -0
  318. package/scripts/hooks-system/domain/values/Severity.js +93 -0
  319. package/scripts/hooks-system/index.js +49 -0
  320. package/scripts/hooks-system/infrastructure/adapters/AstAnalyzerAdapter.js +150 -0
  321. package/scripts/hooks-system/infrastructure/adapters/FileEvidenceAdapter.js +140 -0
  322. package/scripts/hooks-system/infrastructure/adapters/GitCliAdapter.js +16 -0
  323. package/scripts/hooks-system/infrastructure/adapters/GitCommandAdapter.js +68 -0
  324. package/scripts/hooks-system/infrastructure/adapters/GitHubCliAdapter.js +85 -0
  325. package/scripts/hooks-system/infrastructure/adapters/GitQueryAdapter.js +58 -0
  326. package/scripts/hooks-system/infrastructure/adapters/LegacyAnalyzerAdapter.js +61 -0
  327. package/scripts/hooks-system/infrastructure/adapters/MacOSNotificationAdapter.js +99 -0
  328. package/scripts/hooks-system/infrastructure/adapters/__tests__/AstAnalyzerAdapter.spec.js +32 -0
  329. package/scripts/hooks-system/infrastructure/adapters/__tests__/FileEvidenceAdapter.spec.js +31 -0
  330. package/scripts/hooks-system/infrastructure/adapters/__tests__/GitCliAdapter.spec.js +39 -0
  331. package/scripts/hooks-system/infrastructure/adapters/__tests__/MacOSNotificationAdapter.spec.js +33 -0
  332. package/scripts/hooks-system/infrastructure/adapters/git/GitCommandRunner.js +78 -0
  333. package/scripts/hooks-system/infrastructure/adapters/git/GitCommandService.js +67 -0
  334. package/scripts/hooks-system/infrastructure/adapters/git/GitQueryService.js +50 -0
  335. package/scripts/hooks-system/infrastructure/adapters/index.js +14 -0
  336. package/scripts/hooks-system/infrastructure/ast/README.md +198 -0
  337. package/scripts/hooks-system/infrastructure/ast/__tests__/ast-core.spec.js +160 -0
  338. package/scripts/hooks-system/infrastructure/ast/__tests__/ast-intelligence.spec.js +20 -0
  339. package/scripts/hooks-system/infrastructure/ast/android/__tests__/ast-android.spec.js +33 -0
  340. package/scripts/hooks-system/infrastructure/ast/android/__tests__/clean-architecture-analyzer.spec.js +96 -0
  341. package/scripts/hooks-system/infrastructure/ast/android/__tests__/ddd-analyzer.spec.js +113 -0
  342. package/scripts/hooks-system/infrastructure/ast/android/__tests__/detekt-runner.spec.js +36 -0
  343. package/scripts/hooks-system/infrastructure/ast/android/__tests__/feature-first-analyzer.spec.js +80 -0
  344. package/scripts/hooks-system/infrastructure/ast/android/__tests__/native-bridge.spec.js +31 -0
  345. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidASTIntelligentAnalyzer.js +15 -0
  346. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidASTParser.js +157 -0
  347. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidAnalysisOrchestrator.js +164 -0
  348. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidArchitectureDetector.js +334 -0
  349. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidClassAnalyzer.js +162 -0
  350. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidForbiddenLiteralsAnalyzer.js +261 -0
  351. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidSOLIDAnalyzer.js +287 -0
  352. package/scripts/hooks-system/infrastructure/ast/android/analyzers/__tests__/AndroidForbiddenLiteralsAnalyzer.spec.js +58 -0
  353. package/scripts/hooks-system/infrastructure/ast/android/analyzers/__tests__/AndroidSOLIDAnalyzer.spec.js +84 -0
  354. package/scripts/hooks-system/infrastructure/ast/android/ast-android.js +1785 -0
  355. package/scripts/hooks-system/infrastructure/ast/android/clean-architecture-analyzer.js +115 -0
  356. package/scripts/hooks-system/infrastructure/ast/android/ddd-analyzer.js +70 -0
  357. package/scripts/hooks-system/infrastructure/ast/android/detekt-runner.js +81 -0
  358. package/scripts/hooks-system/infrastructure/ast/android/feature-first-analyzer.js +53 -0
  359. package/scripts/hooks-system/infrastructure/ast/android/native-bridge.js +119 -0
  360. package/scripts/hooks-system/infrastructure/ast/archive/README.md +18 -0
  361. package/scripts/hooks-system/infrastructure/ast/archive/ast-intelligence.ts +276 -0
  362. package/scripts/hooks-system/infrastructure/ast/archive/ios-rules.js +329 -0
  363. package/scripts/hooks-system/infrastructure/ast/archive/kotlin-analyzer.js +332 -0
  364. package/scripts/hooks-system/infrastructure/ast/archive/kotlin-parser.js +303 -0
  365. package/scripts/hooks-system/infrastructure/ast/archive/swift-analyzer.js +390 -0
  366. package/scripts/hooks-system/infrastructure/ast/ast-core.js +594 -0
  367. package/scripts/hooks-system/infrastructure/ast/ast-intelligence.js +617 -0
  368. package/scripts/hooks-system/infrastructure/ast/backend/__tests__/ast-backend.spec.js +20 -0
  369. package/scripts/hooks-system/infrastructure/ast/backend/__tests__/clean-architecture-analyzer.spec.js +151 -0
  370. package/scripts/hooks-system/infrastructure/ast/backend/__tests__/ddd-analyzer.spec.js +124 -0
  371. package/scripts/hooks-system/infrastructure/ast/backend/__tests__/feature-first-analyzer.spec.js +128 -0
  372. package/scripts/hooks-system/infrastructure/ast/backend/__tests__/forbidden-literals-analyzer.spec.js +95 -0
  373. package/scripts/hooks-system/infrastructure/ast/backend/__tests__/nestjs-patterns-analyzer.spec.js +59 -0
  374. package/scripts/hooks-system/infrastructure/ast/backend/__tests__/solid-analyzer.spec.js +114 -0
  375. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/BackendArchitectureDetector.js +141 -0
  376. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/BackendPatternDetector.js +23 -0
  377. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/__tests__/BackendArchitectureDetector.spec.js +239 -0
  378. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/__tests__/BackendPatternDetector.spec.js +58 -0
  379. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/detectors/CQRSDetector.js +41 -0
  380. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/detectors/CleanArchitectureDetector.js +52 -0
  381. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/detectors/FeatureFirstCleanDetector.js +74 -0
  382. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/detectors/LayeredArchitectureDetector.js +25 -0
  383. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/detectors/MVCDetector.js +32 -0
  384. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/detectors/OnionArchitectureDetector.js +32 -0
  385. package/scripts/hooks-system/infrastructure/ast/backend/ast-backend-clean.js +44 -0
  386. package/scripts/hooks-system/infrastructure/ast/backend/ast-backend.js +2048 -0
  387. package/scripts/hooks-system/infrastructure/ast/backend/clean-architecture-analyzer.js +142 -0
  388. package/scripts/hooks-system/infrastructure/ast/backend/ddd-analyzer.js +256 -0
  389. package/scripts/hooks-system/infrastructure/ast/backend/feature-first-analyzer.js +70 -0
  390. package/scripts/hooks-system/infrastructure/ast/backend/forbidden-literals-analyzer.js +236 -0
  391. package/scripts/hooks-system/infrastructure/ast/backend/nestjs-patterns-analyzer.js +11 -0
  392. package/scripts/hooks-system/infrastructure/ast/backend/solid-analyzer.js +392 -0
  393. package/scripts/hooks-system/infrastructure/ast/common/BDDTDDWorkflowRules.js +52 -0
  394. package/scripts/hooks-system/infrastructure/ast/common/__tests__/BDDTDDWorkflowRules.spec.js +133 -0
  395. package/scripts/hooks-system/infrastructure/ast/common/__tests__/ast-common.spec.js +20 -0
  396. package/scripts/hooks-system/infrastructure/ast/common/__tests__/documentation-analyzer.spec.js +120 -0
  397. package/scripts/hooks-system/infrastructure/ast/common/__tests__/images-backend-analyzer.spec.js +123 -0
  398. package/scripts/hooks-system/infrastructure/ast/common/__tests__/monorepo-health-analyzer.spec.js +118 -0
  399. package/scripts/hooks-system/infrastructure/ast/common/__tests__/network-resilience-analyzer.spec.js +180 -0
  400. package/scripts/hooks-system/infrastructure/ast/common/__tests__/offline-backend-analyzer.spec.js +111 -0
  401. package/scripts/hooks-system/infrastructure/ast/common/__tests__/push-backend-analyzer.spec.js +124 -0
  402. package/scripts/hooks-system/infrastructure/ast/common/ast-common.js +345 -0
  403. package/scripts/hooks-system/infrastructure/ast/common/documentation-analyzer.js +217 -0
  404. package/scripts/hooks-system/infrastructure/ast/common/images-backend-analyzer.js +36 -0
  405. package/scripts/hooks-system/infrastructure/ast/common/monorepo-health-analyzer.js +452 -0
  406. package/scripts/hooks-system/infrastructure/ast/common/network-resilience-analyzer.js +178 -0
  407. package/scripts/hooks-system/infrastructure/ast/common/offline-backend-analyzer.js +53 -0
  408. package/scripts/hooks-system/infrastructure/ast/common/push-backend-analyzer.js +42 -0
  409. package/scripts/hooks-system/infrastructure/ast/common/rules/BDDRules.js +87 -0
  410. package/scripts/hooks-system/infrastructure/ast/common/rules/ImplementationRules.js +83 -0
  411. package/scripts/hooks-system/infrastructure/ast/common/rules/TDDRules.js +109 -0
  412. package/scripts/hooks-system/infrastructure/ast/common/rules/WorkflowRules.js +137 -0
  413. package/scripts/hooks-system/infrastructure/ast/frontend/__tests__/ast-frontend.spec.js +20 -0
  414. package/scripts/hooks-system/infrastructure/ast/frontend/analyzers/FrontendArchitectureDetector.js +289 -0
  415. package/scripts/hooks-system/infrastructure/ast/frontend/analyzers/FrontendForbiddenLiteralsAnalyzer.js +257 -0
  416. package/scripts/hooks-system/infrastructure/ast/frontend/analyzers/FrontendSOLIDAnalyzer.js +274 -0
  417. package/scripts/hooks-system/infrastructure/ast/frontend/analyzers/__tests__/FrontendArchitectureDetector.spec.js +151 -0
  418. package/scripts/hooks-system/infrastructure/ast/frontend/analyzers/__tests__/FrontendForbiddenLiteralsAnalyzer.spec.js +20 -0
  419. package/scripts/hooks-system/infrastructure/ast/frontend/analyzers/__tests__/FrontendSOLIDAnalyzer.spec.js +108 -0
  420. package/scripts/hooks-system/infrastructure/ast/frontend/ast-frontend-clean.js +42 -0
  421. package/scripts/hooks-system/infrastructure/ast/frontend/ast-frontend.js +2094 -0
  422. package/scripts/hooks-system/infrastructure/ast/frontend/clean-architecture-analyzer.js +88 -0
  423. package/scripts/hooks-system/infrastructure/ast/frontend/ddd-analyzer.js +94 -0
  424. package/scripts/hooks-system/infrastructure/ast/frontend/feature-first-analyzer.js +51 -0
  425. package/scripts/hooks-system/infrastructure/ast/ios/__tests__/ast-ios.spec.js +40 -0
  426. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSArchitectureDetector.spec.js +20 -0
  427. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSArchitectureRules.spec.js +61 -0
  428. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSCICDRules.spec.js +10 -0
  429. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSEnterpriseAnalyzer.spec.js +36 -0
  430. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSForbiddenLiteralsAnalyzer.spec.js +64 -0
  431. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSNetworkingAdvancedRules.spec.js +10 -0
  432. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSPerformanceRules.spec.js +34 -0
  433. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSSPMRules.spec.js +10 -0
  434. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSSwiftUIAdvancedRules.spec.js +10 -0
  435. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSASTIntelligentAnalyzer.js +894 -0
  436. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSArchitectureDetector.js +445 -0
  437. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSArchitectureRules.js +700 -0
  438. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSCICDRules.js +431 -0
  439. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSEnterpriseAnalyzer.js +580 -0
  440. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSForbiddenLiteralsAnalyzer.js +261 -0
  441. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSNetworkingAdvancedRules.js +177 -0
  442. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSPerformanceRules.js +11 -0
  443. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSSPMRules.js +496 -0
  444. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSSwiftUIAdvancedRules.js +333 -0
  445. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSTestingAdvancedRules.js +225 -0
  446. package/scripts/hooks-system/infrastructure/ast/ios/ast-ios.js +2176 -0
  447. package/scripts/hooks-system/infrastructure/ast/ios/native-bridge.js +92 -0
  448. package/scripts/hooks-system/infrastructure/ast/ios/parsers/SourceKittenParser.js +471 -0
  449. package/scripts/hooks-system/infrastructure/ast/ios/parsers/__tests__/SourceKittenParser.spec.js +41 -0
  450. package/scripts/hooks-system/infrastructure/ast/text/__tests__/text-scanner.spec.js +20 -0
  451. package/scripts/hooks-system/infrastructure/ast/text/text-scanner.js +1120 -0
  452. package/scripts/hooks-system/infrastructure/cache/CacheService.js +160 -0
  453. package/scripts/hooks-system/infrastructure/cli/__tests__/install-wizard.spec.js +16 -0
  454. package/scripts/hooks-system/infrastructure/cli/install-wizard.js +74 -0
  455. package/scripts/hooks-system/infrastructure/core/GitOperations.js +50 -0
  456. package/scripts/hooks-system/infrastructure/core/GitOperations.ts +112 -0
  457. package/scripts/hooks-system/infrastructure/core/__tests__/GitOperations.spec.js +146 -0
  458. package/scripts/hooks-system/infrastructure/eslint/eslint-integration.sh +75 -0
  459. package/scripts/hooks-system/infrastructure/events/EventListeners.js +143 -0
  460. package/scripts/hooks-system/infrastructure/events/__tests__/events.spec.js +14 -0
  461. package/scripts/hooks-system/infrastructure/external-tools/GitOperations.js +54 -0
  462. package/scripts/hooks-system/infrastructure/external-tools/eslint/backend.config.template.mjs +58 -0
  463. package/scripts/hooks-system/infrastructure/git-hooks/pre-push +35 -0
  464. package/scripts/hooks-system/infrastructure/git-server/pre-receive-hook +253 -0
  465. package/scripts/hooks-system/infrastructure/guards/git-wrapper.sh +32 -0
  466. package/scripts/hooks-system/infrastructure/guards/master-validator.sh +247 -0
  467. package/scripts/hooks-system/infrastructure/guards/prevent-no-verify.sh +34 -0
  468. package/scripts/hooks-system/infrastructure/hooks/__tests__/skill-activation-prompt.spec.js +11 -0
  469. package/scripts/hooks-system/infrastructure/hooks/pre-tool-use-intelligent-enforcer.sh +489 -0
  470. package/scripts/hooks-system/infrastructure/hooks/skill-activation-prompt.js +244 -0
  471. package/scripts/hooks-system/infrastructure/logging/UnifiedLoggerFactory.js +40 -0
  472. package/scripts/hooks-system/infrastructure/logging/__tests__/logging.spec.js +9 -0
  473. package/scripts/hooks-system/infrastructure/mcp/README.md +116 -0
  474. package/scripts/hooks-system/infrastructure/mcp/__tests__/ast-intelligence-automation.spec.js +38 -0
  475. package/scripts/hooks-system/infrastructure/mcp/__tests__/evidence-watcher.spec.js +38 -0
  476. package/scripts/hooks-system/infrastructure/mcp/ast-intelligence-automation.js +1097 -0
  477. package/scripts/hooks-system/infrastructure/mcp/evidence-watcher.js +128 -0
  478. package/scripts/hooks-system/infrastructure/mcp/package.json +17 -0
  479. package/scripts/hooks-system/infrastructure/mcp/services/EvidenceService.js +87 -0
  480. package/scripts/hooks-system/infrastructure/mcp/services/McpProtocolHandler.js +166 -0
  481. package/scripts/hooks-system/infrastructure/orchestration/__tests__/intelligent-audit.spec.js +11 -0
  482. package/scripts/hooks-system/infrastructure/orchestration/intelligent-audit.js +353 -0
  483. package/scripts/hooks-system/infrastructure/patterns/pattern-checks.sh +98 -0
  484. package/scripts/hooks-system/infrastructure/reporting/ReportImpactAnalyzer.js +109 -0
  485. package/scripts/hooks-system/infrastructure/reporting/ReportMetricsCalculator.js +114 -0
  486. package/scripts/hooks-system/infrastructure/reporting/ReportPresenter.js +86 -0
  487. package/scripts/hooks-system/infrastructure/reporting/__tests__/reporting.spec.js +15 -0
  488. package/scripts/hooks-system/infrastructure/reporting/report-generator.js +130 -0
  489. package/scripts/hooks-system/infrastructure/reporting/severity-tracker.js +105 -0
  490. package/scripts/hooks-system/infrastructure/repositories/CursorTokenRepository.js +76 -0
  491. package/scripts/hooks-system/infrastructure/repositories/FileFindingsRepository.js +88 -0
  492. package/scripts/hooks-system/infrastructure/repositories/__tests__/repositories.spec.js +20 -0
  493. package/scripts/hooks-system/infrastructure/repositories/datasources/CursorApiDataSource.js +73 -0
  494. package/scripts/hooks-system/infrastructure/repositories/datasources/CursorFileDataSource.js +55 -0
  495. package/scripts/hooks-system/infrastructure/severity/__tests__/severity-evaluator.spec.js +18 -0
  496. package/scripts/hooks-system/infrastructure/severity/analyzers/__tests__/maintainability-analyzer.spec.js +170 -0
  497. package/scripts/hooks-system/infrastructure/severity/analyzers/__tests__/performance-analyzer.spec.js +186 -0
  498. package/scripts/hooks-system/infrastructure/severity/analyzers/__tests__/security-analyzer.spec.js +151 -0
  499. package/scripts/hooks-system/infrastructure/severity/analyzers/__tests__/stability-analyzer.spec.js +143 -0
  500. package/scripts/hooks-system/infrastructure/severity/analyzers/maintainability-analyzer.js +100 -0
  501. package/scripts/hooks-system/infrastructure/severity/analyzers/performance-analyzer.js +109 -0
  502. package/scripts/hooks-system/infrastructure/severity/analyzers/security-analyzer.js +104 -0
  503. package/scripts/hooks-system/infrastructure/severity/analyzers/stability-analyzer.js +85 -0
  504. package/scripts/hooks-system/infrastructure/severity/context/analyzers/CodeClassificationAnalyzer.js +71 -0
  505. package/scripts/hooks-system/infrastructure/severity/context/analyzers/DataAnalyzer.js +64 -0
  506. package/scripts/hooks-system/infrastructure/severity/context/analyzers/ImpactAnalyzer.js +68 -0
  507. package/scripts/hooks-system/infrastructure/severity/context/analyzers/SafetyAnalyzer.js +82 -0
  508. package/scripts/hooks-system/infrastructure/severity/context/context-builder.js +88 -0
  509. package/scripts/hooks-system/infrastructure/severity/generators/RecommendationGenerator.js +153 -0
  510. package/scripts/hooks-system/infrastructure/severity/mappers/SeverityMapper.js +10 -0
  511. package/scripts/hooks-system/infrastructure/severity/policies/gate-policies.js +136 -0
  512. package/scripts/hooks-system/infrastructure/severity/policies/severity-policies.json +206 -0
  513. package/scripts/hooks-system/infrastructure/severity/scorers/ContextMultiplier.js +49 -0
  514. package/scripts/hooks-system/infrastructure/severity/severity-evaluator.js +117 -0
  515. package/scripts/hooks-system/infrastructure/shell/core/constants.sh +26 -0
  516. package/scripts/hooks-system/infrastructure/shell/core/utils.sh +45 -0
  517. package/scripts/hooks-system/infrastructure/shell/gitflow/git-wrapper.sh +646 -0
  518. package/scripts/hooks-system/infrastructure/shell/gitflow/gitflow-enforcer.sh +620 -0
  519. package/scripts/hooks-system/infrastructure/shell/gitflow/gitflow-state-manager.sh +235 -0
  520. package/scripts/hooks-system/infrastructure/shell/gitflow-state-manager.sh +225 -0
  521. package/scripts/hooks-system/infrastructure/shell/orchestrators/audit-orchestrator.sh +1106 -0
  522. package/scripts/hooks-system/infrastructure/shell/security/detect-secrets.sh +26 -0
  523. package/scripts/hooks-system/infrastructure/shell/security/detect_secrets.py +182 -0
  524. package/scripts/hooks-system/infrastructure/shell/validate-clean-architecture.sh +254 -0
  525. package/scripts/hooks-system/infrastructure/shell/validators/check-doc-structure.sh +62 -0
  526. package/scripts/hooks-system/infrastructure/shell/validators/ensure-critical-docs.sh +26 -0
  527. package/scripts/hooks-system/infrastructure/shell/validators/validate-ai-protocol.sh +474 -0
  528. package/scripts/hooks-system/infrastructure/shell/validators/validate-clean-architecture.sh +303 -0
  529. package/scripts/hooks-system/infrastructure/shell/validators/validate-conventional-commit.sh +42 -0
  530. package/scripts/hooks-system/infrastructure/storage/file-operations.sh +31 -0
  531. package/scripts/hooks-system/infrastructure/telemetry/TelemetryService.js +165 -0
  532. package/scripts/hooks-system/infrastructure/telemetry/__tests__/telemetry.spec.js +15 -0
  533. package/scripts/hooks-system/infrastructure/telemetry/metrics-logger.js +66 -0
  534. package/scripts/hooks-system/infrastructure/telemetry/metrics-server.js +61 -0
  535. package/scripts/hooks-system/infrastructure/utils/__tests__/utils.spec.js +8 -0
  536. package/scripts/hooks-system/infrastructure/utils/error-utils.js +28 -0
  537. package/scripts/hooks-system/infrastructure/utils/timestamp-helper.sh +106 -0
  538. package/scripts/hooks-system/infrastructure/utils/token-manager.js +121 -0
  539. package/scripts/hooks-system/infrastructure/validators/__tests__/detect-commit-language.spec.js +16 -0
  540. package/scripts/hooks-system/infrastructure/validators/__tests__/enforce-english-literals.spec.js +67 -0
  541. package/scripts/hooks-system/infrastructure/validators/detect-commit-language.js +145 -0
  542. package/scripts/hooks-system/infrastructure/validators/enforce-english-literals.js +202 -0
  543. package/scripts/hooks-system/infrastructure/watchdog/__tests__/.audit-reports/token-monitor.log +18 -0
  544. package/scripts/hooks-system/infrastructure/watchdog/__tests__/auto-recovery.spec.js +14 -0
  545. package/scripts/hooks-system/infrastructure/watchdog/__tests__/token-monitor.spec.js +67 -0
  546. package/scripts/hooks-system/infrastructure/watchdog/__tests__/watchdog.spec.js +22 -0
  547. package/scripts/hooks-system/infrastructure/watchdog/ai-watchdog.sh +278 -0
  548. package/scripts/hooks-system/infrastructure/watchdog/auto-recovery.js +32 -0
  549. package/scripts/hooks-system/infrastructure/watchdog/health-check.js +58 -0
  550. package/scripts/hooks-system/infrastructure/watchdog/token-monitor-loop.sh +20 -0
  551. package/scripts/hooks-system/infrastructure/watchdog/token-monitor.js +69 -0
  552. package/scripts/hooks-system/infrastructure/watchdog/token-tracker.sh +208 -0
  553. package/scripts/hooks-system/presentation/cli/audit.sh +32 -0
  554. package/scripts/hooks-system/presentation/cli/autonomous-status.sh +92 -0
  555. package/scripts/hooks-system/presentation/cli/categorize-violations.sh +179 -0
  556. package/scripts/hooks-system/presentation/cli/direct-audit-option2.sh +23 -0
  557. package/scripts/hooks-system/presentation/cli/direct-audit.sh +33 -0
  558. package/skills/android-guidelines/SKILL.md +475 -0
  559. package/skills/android-guidelines/resources/advanced-topics.md +44 -0
  560. package/skills/android-guidelines/resources/architecture-overview.md +44 -0
  561. package/skills/backend-guidelines/SKILL.md +335 -0
  562. package/skills/backend-guidelines/resources/architecture-overview.md +48 -0
  563. package/skills/frontend-guidelines/SKILL.md +367 -0
  564. package/skills/frontend-guidelines/resources/architecture-overview.md +44 -0
  565. package/skills/ios-guidelines/SKILL.md +406 -0
  566. package/skills/ios-guidelines/resources/architecture-overview.md +47 -0
  567. package/skills/skill-rules.json +334 -0
@@ -0,0 +1,137 @@
1
+ const path = require('path');
2
+
3
+ class AutoRecoveryManager {
4
+ constructor({
5
+ repoRoot = process.cwd(),
6
+ strategies = [],
7
+ logger = console,
8
+ notificationCenter = null,
9
+ timers = { setTimeout, clearTimeout },
10
+ maxAttempts = 5,
11
+ baseBackoffMs = 2000,
12
+ jitter = 0.25
13
+ } = {}) {
14
+ this.repoRoot = repoRoot;
15
+ this.logger = logger || console;
16
+ this.notificationCenter = notificationCenter;
17
+ this.timers = timers;
18
+ this.maxAttempts = maxAttempts;
19
+ this.baseBackoffMs = baseBackoffMs;
20
+ this.jitter = jitter;
21
+ this.strategies = Array.isArray(strategies) && strategies.length
22
+ ? strategies
23
+ : [AutoRecoveryManager.createSupervisorRestartStrategy()];
24
+ this.attempts = new Map();
25
+ this.timeouts = new Map();
26
+ }
27
+
28
+ static createSupervisorRestartStrategy() {
29
+ return {
30
+ id: 'guard-supervisor-restart',
31
+ condition: ({ reason }) => reason && reason.startsWith('heartbeat-'),
32
+ action: async ({ logger }) => {
33
+ logger.info('Attempting guard-supervisor restart via start-guards.sh');
34
+ return AutoRecoveryManager.runScript('start-guards.sh', ['restart']);
35
+ }
36
+ };
37
+ }
38
+
39
+ static runScript(scriptName, args = []) {
40
+ const { spawnSync } = require('child_process');
41
+ const scriptPath = path.join(process.cwd(), 'scripts', 'hooks-system', 'bin', scriptName);
42
+ const result = spawnSync(scriptPath, args, { stdio: 'pipe', cwd: process.cwd() });
43
+ if (result.error) {
44
+ throw result.error;
45
+ }
46
+ return {
47
+ stdout: (result.stdout || '').toString(),
48
+ stderr: (result.stderr || '').toString()
49
+ };
50
+ }
51
+
52
+ registerStrategy(strategy) {
53
+ if (!strategy || !strategy.id) {
54
+ return;
55
+ }
56
+ this.strategies.push(strategy);
57
+ }
58
+
59
+ async recover({ key, reason, context = {} }) {
60
+ const strategy = this.strategies.find(entry => entry.condition({ reason, context }));
61
+ if (!strategy) {
62
+ return { status: 'ignored' };
63
+ }
64
+
65
+ const attempts = this.attempts.get(key) || { count: 0, lastAttempt: 0 };
66
+ if (attempts.count >= this.maxAttempts) {
67
+ this.log('warn', 'AUTO_RECOVERY_MAX_ATTEMPTS', { key, reason });
68
+ this.notify(`Recovery skipped for ${key} (max attempts reached)`, 'warn', { key, reason });
69
+ return { status: 'skipped' };
70
+ }
71
+
72
+ const delay = this.calculateDelay(attempts.count);
73
+ this.log('info', 'AUTO_RECOVERY_SCHEDULED', { key, reason, delay });
74
+
75
+ if (this.timeouts.has(key)) {
76
+ this.timers.clearTimeout(this.timeouts.get(key));
77
+ }
78
+
79
+ const timeoutRef = this.timers.setTimeout(async () => {
80
+ const currentAttempts = this.attempts.get(key) || { count: 0 };
81
+ const nextCount = currentAttempts.count + 1;
82
+ this.attempts.set(key, { count: nextCount, lastAttempt: Date.now() });
83
+ try {
84
+ const result = await strategy.action({
85
+ key,
86
+ reason,
87
+ context,
88
+ logger: this.logger
89
+ });
90
+ this.log('info', 'AUTO_RECOVERY_SUCCESS', { key, reason, result });
91
+ this.notify(`Recovery succeeded for ${key}`, 'info', { key, reason });
92
+ } catch (error) {
93
+ this.log('error', 'AUTO_RECOVERY_FAILED', { key, reason, error: error.message });
94
+ this.notify(`Recovery failed for ${key}: ${error.message}`, 'error', { key, reason });
95
+ } finally {
96
+ this.timeouts.delete(key);
97
+ }
98
+ }, delay);
99
+
100
+ this.timeouts.set(key, timeoutRef);
101
+ return { status: 'scheduled', delay };
102
+ }
103
+
104
+ clear(key) {
105
+ this.attempts.delete(key);
106
+ const ref = this.timeouts.get(key);
107
+ if (ref) {
108
+ this.timers.clearTimeout(ref);
109
+ this.timeouts.delete(key);
110
+ }
111
+ }
112
+
113
+ calculateDelay(attemptCount) {
114
+ const exponential = this.baseBackoffMs * Math.pow(2, attemptCount);
115
+ const randomFactor = 1 + (Math.random() * 2 - 1) * this.jitter;
116
+ return Math.round(exponential * randomFactor);
117
+ }
118
+
119
+ log(level, event, data = {}) {
120
+ if (this.logger && typeof this.logger[level] === 'function') {
121
+ this.logger[level](event, data);
122
+ }
123
+ }
124
+
125
+ notify(message, level, metadata = {}) {
126
+ if (this.notificationCenter && typeof this.notificationCenter.enqueue === 'function') {
127
+ this.notificationCenter.enqueue({
128
+ message,
129
+ level,
130
+ type: `auto_recovery_${level}`,
131
+ metadata
132
+ });
133
+ }
134
+ }
135
+ }
136
+
137
+ module.exports = { AutoRecoveryManager };
@@ -0,0 +1,62 @@
1
+ const { AutoRecoveryManager } = require('../AutoRecoveryManager');
2
+
3
+ describe('AutoRecoveryManager', () => {
4
+ const create = (overrides = {}) => {
5
+ const enqueue = jest.fn();
6
+ const logger = { info: jest.fn(), warn: jest.fn(), error: jest.fn() };
7
+ const timers = {
8
+ setTimeout: jest.fn((fn) => {
9
+ timers.fn = fn;
10
+ return Symbol('timeout');
11
+ }),
12
+ clearTimeout: jest.fn()
13
+ };
14
+
15
+ const manager = new AutoRecoveryManager({
16
+ notificationCenter: { enqueue },
17
+ logger,
18
+ timers,
19
+ baseBackoffMs: 10,
20
+ jitter: 0,
21
+ strategies: [
22
+ {
23
+ id: 'test-restart',
24
+ condition: ({ reason }) => reason === 'test',
25
+ action: jest.fn()
26
+ }
27
+ ],
28
+ ...overrides
29
+ });
30
+ manager.__test = { enqueue, logger, timers };
31
+ return manager;
32
+ };
33
+
34
+ it('schedules recovery with backoff and notifies', async () => {
35
+ const manager = create();
36
+ const strategy = manager.strategies[0];
37
+ const result = await manager.recover({ key: 'guard', reason: 'test' });
38
+
39
+ expect(result.status).toBe('scheduled');
40
+ expect(manager.__test.timers.setTimeout).toHaveBeenCalled();
41
+
42
+ await manager.__test.timers.fn();
43
+
44
+ expect(strategy.action).toHaveBeenCalled();
45
+ expect(manager.__test.enqueue).toHaveBeenCalledWith(expect.objectContaining({
46
+ type: 'auto_recovery_info'
47
+ }));
48
+ });
49
+
50
+ it('bloquea recuperación cuando excede intentos', async () => {
51
+ const manager = create({ maxAttempts: 1 });
52
+ const strategy = manager.strategies[0];
53
+ await manager.recover({ key: 'guard', reason: 'test' });
54
+ await manager.__test.timers.fn();
55
+
56
+ const second = await manager.recover({ key: 'guard', reason: 'test' });
57
+
58
+ expect(second.status).toBe('skipped');
59
+ expect(manager.__test.logger.warn).toHaveBeenCalledWith('AUTO_RECOVERY_MAX_ATTEMPTS', expect.any(Object));
60
+ expect(strategy.action).toHaveBeenCalledTimes(1);
61
+ });
62
+ });
@@ -0,0 +1,97 @@
1
+ const path = require('path');
2
+
3
+ class CommitMessageSuggester {
4
+ constructor(featureDetector) {
5
+ this.featureDetector = featureDetector;
6
+ this.commitTypePatterns = {
7
+ feat: ['feature/', 'feat/', 'add', 'new', 'create', 'implement'],
8
+ fix: ['fix/', 'bugfix/', 'hotfix/', 'patch'],
9
+ refactor: ['refactor/', 'clean', 'restructure'],
10
+ docs: ['docs/', 'documentation', 'readme', 'changelog'],
11
+ test: ['test/', 'spec/', '__tests__'],
12
+ chore: ['chore/', 'config/', 'build/', 'ci/'],
13
+ style: ['style/', 'css/', 'scss/', 'styling']
14
+ };
15
+ }
16
+
17
+ suggest(group) {
18
+ const { context, platform, files } = group;
19
+ let commitType;
20
+
21
+ if (group.isTestGroup) {
22
+ commitType = 'test';
23
+ } else if (group.isMiscGroup) {
24
+ commitType = 'chore';
25
+ } else {
26
+ commitType = this.inferCommitType(files, context);
27
+ }
28
+
29
+ const scope = this.inferScope(context, platform);
30
+ const action = this.inferAction(files);
31
+
32
+ return {
33
+ type: commitType,
34
+ scope,
35
+ message: `${commitType}(${scope}): ${action}`,
36
+ files: files.length,
37
+ fileList: files.slice(0, 5)
38
+ };
39
+ }
40
+
41
+ inferCommitType(files, context) {
42
+ const lowerContext = (context || '').toLowerCase();
43
+
44
+ for (const [type, patterns] of Object.entries(this.commitTypePatterns)) {
45
+ if (patterns.some(p => lowerContext.includes(p))) {
46
+ return type;
47
+ }
48
+ }
49
+
50
+ if (files.some(f => this.featureDetector.isTestFile(f))) {
51
+ return 'test';
52
+ }
53
+
54
+ if (files.some(f => /\.md$/.test(f))) {
55
+ return 'docs';
56
+ }
57
+
58
+ if (files.some(f => /\.json$|\.yaml$|\.yml$/.test(f))) {
59
+ return 'chore';
60
+ }
61
+
62
+ return 'feat';
63
+ }
64
+
65
+ inferScope(context, platform) {
66
+ if (context && context !== 'misc' && context !== 'other') {
67
+ const parts = context.split(path.sep);
68
+ const lastPart = parts[parts.length - 1];
69
+ if (lastPart && lastPart.length <= 20) {
70
+ return lastPart.toLowerCase().replace(/[^a-z0-9-]/g, '-');
71
+ }
72
+ }
73
+
74
+ if (platform && platform !== 'other') {
75
+ return platform;
76
+ }
77
+
78
+ return 'general';
79
+ }
80
+
81
+ inferAction(files) {
82
+ if (files.length === 1) {
83
+ const basename = path.basename(files[0]);
84
+ return `update ${basename}`;
85
+ }
86
+
87
+ const extensions = new Set(files.map(f => path.extname(f)).filter(Boolean));
88
+ if (extensions.size === 1) {
89
+ const ext = Array.from(extensions)[0];
90
+ return `update ${files.length} ${ext} files`;
91
+ }
92
+
93
+ return `update ${files.length} files`;
94
+ }
95
+ }
96
+
97
+ module.exports = CommitMessageSuggester;
@@ -0,0 +1,114 @@
1
+ const path = require('path');
2
+
3
+ class FileContextGrouper {
4
+ constructor(featureDetector, platformDetector = null) {
5
+ this.featureDetector = featureDetector;
6
+ this.platformDetector = platformDetector;
7
+ }
8
+
9
+ group(files) {
10
+ const byDirectory = new Map();
11
+ const byPlatform = new Map();
12
+
13
+ for (const file of files) {
14
+ const dir = this.getContextDirectory(file);
15
+ const platform = this.detectPlatform(file);
16
+
17
+ if (!byDirectory.has(dir)) {
18
+ byDirectory.set(dir, []);
19
+ }
20
+ byDirectory.get(dir).push(file);
21
+
22
+ if (!byPlatform.has(platform)) {
23
+ byPlatform.set(platform, []);
24
+ }
25
+ byPlatform.get(platform).push(file);
26
+ }
27
+
28
+ const groups = [];
29
+ const assigned = new Set();
30
+
31
+ for (const [dir, dirFiles] of byDirectory.entries()) {
32
+ if (dirFiles.length >= 2) {
33
+ const unassigned = dirFiles.filter(f => !assigned.has(f));
34
+ if (unassigned.length >= 2) {
35
+ const platform = this.detectPlatform(unassigned[0]);
36
+ groups.push({
37
+ context: dir,
38
+ platform,
39
+ files: unassigned
40
+ });
41
+ unassigned.forEach(f => assigned.add(f));
42
+ }
43
+ }
44
+ }
45
+
46
+ for (const [platform, platformFiles] of byPlatform.entries()) {
47
+ const unassigned = platformFiles.filter(f => !assigned.has(f));
48
+ if (unassigned.length >= 2) {
49
+ groups.push({
50
+ context: platform,
51
+ platform,
52
+ files: unassigned
53
+ });
54
+ unassigned.forEach(f => assigned.add(f));
55
+ }
56
+ }
57
+
58
+ const remaining = files.filter(f => !assigned.has(f));
59
+ if (remaining.length > 0) {
60
+ const testFiles = remaining.filter(f => this.featureDetector.isTestFile(f));
61
+ const nonTestFiles = remaining.filter(f => !this.featureDetector.isTestFile(f));
62
+
63
+ if (testFiles.length >= 2) {
64
+ groups.push({
65
+ context: 'tests',
66
+ platform: 'test',
67
+ files: testFiles,
68
+ isTestGroup: true
69
+ });
70
+ testFiles.forEach(f => assigned.add(f));
71
+ }
72
+
73
+ if (nonTestFiles.length >= 2) {
74
+ groups.push({
75
+ context: 'misc',
76
+ platform: 'other',
77
+ files: nonTestFiles,
78
+ isMiscGroup: true
79
+ });
80
+ nonTestFiles.forEach(f => assigned.add(f));
81
+ }
82
+ }
83
+
84
+ // Return both groups and orphans
85
+ const groupedFiles = new Set(groups.flatMap(g => g.files));
86
+ const orphans = files.filter(f => !groupedFiles.has(f));
87
+
88
+ return { groups, orphans };
89
+ }
90
+
91
+ getContextDirectory(file) {
92
+ const parts = file.split(path.sep);
93
+ if (parts.length <= 2) {
94
+ return parts[0] || 'root';
95
+ }
96
+ return parts.slice(0, 2).join(path.sep);
97
+ }
98
+
99
+ detectPlatform(file) {
100
+ // Prefer injected detector if available
101
+ if (this.platformDetector && typeof this.platformDetector.detectPlatformFromFile === 'function') {
102
+ const detected = this.platformDetector.detectPlatformFromFile(file);
103
+ if (detected && detected !== 'other') {
104
+ return detected;
105
+ }
106
+ }
107
+
108
+ // Fallback to shared feature detector
109
+ const detected = this.featureDetector.detectPlatform(file);
110
+ return detected !== 'shared' ? detected : 'other';
111
+ }
112
+ }
113
+
114
+ module.exports = FileContextGrouper;
@@ -0,0 +1,53 @@
1
+ class SmartCommitSummaryBuilder {
2
+ build(suggestions, orphans) {
3
+ const lines = [];
4
+
5
+ if (suggestions.length > 0) {
6
+ lines.push('📦 Suggested commits:');
7
+ suggestions.forEach((suggestion, i) => {
8
+ lines.push(` ${i + 1}. ${suggestion.message} (${suggestion.files} files)`);
9
+ });
10
+ }
11
+
12
+ if (orphans.length > 0) {
13
+ lines.push('');
14
+ lines.push(`⚠️ Ungrouped files (${orphans.length}):`);
15
+ orphans.slice(0, 5).forEach(f => {
16
+ lines.push(` - ${f}`);
17
+ });
18
+ if (orphans.length > 5) {
19
+ lines.push(` ... and ${orphans.length - 5} more`);
20
+ }
21
+ }
22
+
23
+ return lines.join('\n');
24
+ }
25
+
26
+ formatNotification(suggestions, orphans, summary) {
27
+ if (suggestions.length === 0 && orphans.length === 0) {
28
+ return null;
29
+ }
30
+
31
+ let message = '';
32
+
33
+ if (suggestions.length > 0) {
34
+ message += `${suggestions.length} commit groups detected:\n`;
35
+ suggestions.forEach((suggestion, i) => {
36
+ message += `${i + 1}. ${suggestion.message}\n`;
37
+ });
38
+ }
39
+
40
+ if (orphans.length > 0) {
41
+ message += `\n⚠️ ${orphans.length} files need review`;
42
+ }
43
+
44
+ return {
45
+ title: 'Smart Commit Suggestions',
46
+ message: message.trim(),
47
+ level: orphans.length > 0 ? 'warn' : 'info',
48
+ summary
49
+ };
50
+ }
51
+ }
52
+
53
+ module.exports = SmartCommitSummaryBuilder;
@@ -0,0 +1,44 @@
1
+ const CursorTokenRepository = require('../../../infrastructure/repositories/CursorTokenRepository');
2
+
3
+ class CursorTokenService {
4
+ constructor({
5
+ cursorTokenRepository = null,
6
+ repoRoot = process.cwd(),
7
+ usageFile,
8
+ apiUrl,
9
+ apiToken,
10
+ fetchImpl,
11
+ logger = console
12
+ } = {}) {
13
+ this.logger = logger;
14
+ this.repository = cursorTokenRepository || new CursorTokenRepository({
15
+ repoRoot,
16
+ usageFile,
17
+ apiUrl,
18
+ apiToken,
19
+ fetchImpl,
20
+ logger
21
+ });
22
+ }
23
+
24
+ async getCurrentUsage() {
25
+ // Strategy: First try API (most accurate), then File (fallback/offline)
26
+
27
+ const apiUsage = await this.repository.getUsageFromApi();
28
+ if (apiUsage) {
29
+ this.logger.debug?.('CURSOR_SERVICE_USING_API', { usage: apiUsage });
30
+ return apiUsage;
31
+ }
32
+
33
+ const fileUsage = await this.repository.getUsageFromFile();
34
+ if (fileUsage) {
35
+ this.logger.debug?.('CURSOR_SERVICE_USING_FILE', { usage: fileUsage });
36
+ return fileUsage;
37
+ }
38
+
39
+ this.logger.warn?.('CURSOR_SERVICE_NO_DATA_AVAILABLE');
40
+ return null;
41
+ }
42
+ }
43
+
44
+ module.exports = CursorTokenService;
@@ -0,0 +1,109 @@
1
+ const { execSync } = require('child_process');
2
+
3
+ class TokenMetricsService {
4
+ constructor(cursorTokenService, thresholds, logger) {
5
+ this.cursorTokenService = cursorTokenService;
6
+ this.thresholds = thresholds;
7
+ this.logger = logger;
8
+ this.repoRoot = process.cwd();
9
+ }
10
+
11
+ async collectMetrics(fallbackEstimator) {
12
+ const usage = await this.cursorTokenService.getCurrentUsage();
13
+ const now = new Date();
14
+ const maxTokens = this.thresholds.maxTokens;
15
+
16
+ let tokensUsed = 0;
17
+ let source = 'fallback';
18
+ let untrusted = false;
19
+ let timestamp = now.toISOString();
20
+ let stale = true;
21
+
22
+ if (usage) {
23
+ tokensUsed = typeof usage.tokensUsed === 'number' ? usage.tokensUsed : tokensUsed;
24
+ const usageMaxTokens = typeof usage.maxTokens === 'number' ? usage.maxTokens : maxTokens;
25
+ if (Number.isFinite(usageMaxTokens)) {
26
+ // If usage has a maxTokens, use it, otherwise use our threshold default
27
+ // But wait, the original logic was:
28
+ // tokensUsed = Math.min(tokensUsed, usageMaxTokens);
29
+ // This seems wrong if usageMaxTokens is the limit.
30
+ // Let's stick to the original logic for safety but it looks like clamping usage to limit?
31
+ // Actually if usage.maxTokens is provided by the API, we should probably trust it or update our threshold?
32
+ // For now, let's keep original behavior:
33
+ tokensUsed = Math.min(tokensUsed, usageMaxTokens);
34
+ }
35
+ source = usage.source || 'realtime';
36
+ untrusted = Boolean(usage.untrusted);
37
+ timestamp = usage.timestamp || timestamp;
38
+ stale = now.getTime() - new Date(timestamp).getTime() > (15 * 60 * 1000); // 15 min stale threshold hardcoded in original service logic or passed in?
39
+ // The original service had staleThresholdMs passed in constructor. I should probably pass it here too.
40
+ }
41
+
42
+ if (source === 'fallback' && fallbackEstimator) {
43
+ const fallbackTokens = await this.safeFallbackEstimate(fallbackEstimator);
44
+ if (fallbackTokens != null) {
45
+ tokensUsed = fallbackTokens;
46
+ }
47
+ }
48
+
49
+ tokensUsed = Math.max(0, Math.min(tokensUsed, maxTokens));
50
+ const percentUsed = maxTokens === 0 ? 0 : (tokensUsed / maxTokens) * 100;
51
+ const remainingTokens = Math.max(0, maxTokens - tokensUsed);
52
+
53
+ let level = this.resolveLevel(percentUsed);
54
+ if (untrusted) {
55
+ level = 'ok';
56
+ }
57
+ const forceLevel = (process.env.TOKEN_MONITOR_FORCE_LEVEL || '').toLowerCase();
58
+ if (forceLevel === 'warning' || forceLevel === 'critical' || forceLevel === 'ok') {
59
+ level = forceLevel;
60
+ }
61
+
62
+ const metrics = {
63
+ timestamp,
64
+ tokensUsed,
65
+ maxTokens,
66
+ percentUsed: Number(percentUsed.toFixed(2)),
67
+ remainingTokens,
68
+ level,
69
+ source,
70
+ stale,
71
+ untrusted
72
+ };
73
+
74
+ if (this.logger && typeof this.logger.debug === 'function') {
75
+ this.logger.debug('TOKEN_MONITOR_METRICS', metrics);
76
+ }
77
+
78
+ return metrics;
79
+ }
80
+
81
+ async safeFallbackEstimate(fallbackEstimator) {
82
+ try {
83
+ const estimate = await fallbackEstimator();
84
+ if (typeof estimate === 'number' && Number.isFinite(estimate)) {
85
+ return estimate;
86
+ }
87
+ return null;
88
+ } catch (error) {
89
+ if (this.logger && this.logger.warn) {
90
+ this.logger.warn('TOKEN_MONITOR_FALLBACK_FAILED', { error: error.message });
91
+ }
92
+ return null;
93
+ }
94
+ }
95
+
96
+ resolveLevel(percentUsed) {
97
+ if (percentUsed >= this.thresholds.criticalPercent) {
98
+ return 'critical';
99
+ }
100
+
101
+ if (percentUsed >= this.thresholds.warningPercent) {
102
+ return 'warning';
103
+ }
104
+
105
+ return 'ok';
106
+ }
107
+ }
108
+
109
+ module.exports = TokenMetricsService;