pumuki-ast-hooks 5.3.18 → 5.3.20

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 (91) hide show
  1. package/docs/VIOLATIONS_RESOLUTION_PLAN.md +39 -37
  2. package/package.json +8 -2
  3. package/scripts/hooks-system/application/CompositionRoot.js +24 -73
  4. package/scripts/hooks-system/application/services/AutonomousOrchestrator.js +18 -0
  5. package/scripts/hooks-system/application/services/ContextDetectionEngine.js +58 -0
  6. package/scripts/hooks-system/application/services/DynamicRulesLoader.js +12 -2
  7. package/scripts/hooks-system/application/services/GitFlowService.js +80 -0
  8. package/scripts/hooks-system/application/services/GitTreeState.js +143 -13
  9. package/scripts/hooks-system/application/services/HookSystemScheduler.js +47 -0
  10. package/scripts/hooks-system/application/services/IntelligentCommitAnalyzer.js +25 -0
  11. package/scripts/hooks-system/application/services/IntelligentGitTreeMonitor.js +11 -0
  12. package/scripts/hooks-system/application/services/PlatformAnalysisService.js +19 -0
  13. package/scripts/hooks-system/application/services/PlatformDetectionService.js +19 -0
  14. package/scripts/hooks-system/application/services/PlaybookRunner.js +22 -1
  15. package/scripts/hooks-system/application/services/PredictiveHookAdvisor.js +19 -0
  16. package/scripts/hooks-system/application/services/RealtimeGuardPlugin.js +25 -0
  17. package/scripts/hooks-system/application/services/RealtimeGuardService.js +41 -84
  18. package/scripts/hooks-system/application/services/SmartDirtyTreeAnalyzer.js +11 -0
  19. package/scripts/hooks-system/application/services/commit/CommitMessageGenerator.js +11 -0
  20. package/scripts/hooks-system/application/services/commit/FeatureDetector.js +11 -0
  21. package/scripts/hooks-system/application/services/evidence/EvidenceContextManager.js +25 -0
  22. package/scripts/hooks-system/application/services/guard/GuardAutoManagerService.js +21 -31
  23. package/scripts/hooks-system/application/services/guard/GuardConfig.js +18 -15
  24. package/scripts/hooks-system/application/services/guard/GuardEventLogger.js +11 -0
  25. package/scripts/hooks-system/application/services/guard/GuardHealthReminder.js +26 -0
  26. package/scripts/hooks-system/application/services/guard/GuardHeartbeatMonitor.js +20 -6
  27. package/scripts/hooks-system/application/services/guard/GuardLockManager.js +11 -0
  28. package/scripts/hooks-system/application/services/guard/GuardMonitorLoop.js +25 -0
  29. package/scripts/hooks-system/application/services/guard/GuardNotificationHandler.js +11 -0
  30. package/scripts/hooks-system/application/services/guard/GuardProcessManager.js +10 -28
  31. package/scripts/hooks-system/application/services/guard/GuardRecoveryService.js +11 -0
  32. package/scripts/hooks-system/application/services/installation/ConfigurationGeneratorService.js +18 -0
  33. package/scripts/hooks-system/application/services/installation/FileSystemInstallerService.js +18 -0
  34. package/scripts/hooks-system/application/services/installation/GitEnvironmentService.js +18 -3
  35. package/scripts/hooks-system/application/services/installation/HookInstaller.js +19 -0
  36. package/scripts/hooks-system/application/services/installation/IdeIntegrationService.js +11 -0
  37. package/scripts/hooks-system/application/services/installation/InstallService.js +25 -1
  38. package/scripts/hooks-system/application/services/installation/McpConfigurator.js +19 -2
  39. package/scripts/hooks-system/application/services/installation/PlatformDetectorService.js +11 -0
  40. package/scripts/hooks-system/application/services/installation/VSCodeTaskConfigurator.js +11 -0
  41. package/scripts/hooks-system/application/services/logging/AuditLogger.js +90 -1
  42. package/scripts/hooks-system/application/services/logging/UnifiedLogger.js +15 -13
  43. package/scripts/hooks-system/application/services/monitoring/ActivityMonitor.js +33 -0
  44. package/scripts/hooks-system/application/services/monitoring/AstMonitor.js +27 -0
  45. package/scripts/hooks-system/application/services/monitoring/DevDocsMonitor.js +26 -0
  46. package/scripts/hooks-system/application/services/monitoring/EvidenceMonitor.js +19 -0
  47. package/scripts/hooks-system/application/services/monitoring/EvidenceMonitorService.js +27 -6
  48. package/scripts/hooks-system/application/services/monitoring/GitTreeMonitor.js +28 -0
  49. package/scripts/hooks-system/application/services/monitoring/GitTreeMonitorService.js +26 -0
  50. package/scripts/hooks-system/application/services/monitoring/HealthCheckProviders.js +4 -0
  51. package/scripts/hooks-system/application/services/monitoring/HealthCheckService.js +25 -0
  52. package/scripts/hooks-system/application/services/monitoring/HeartbeatMonitorService.js +26 -0
  53. package/scripts/hooks-system/application/services/monitoring/TokenMonitor.js +26 -0
  54. package/scripts/hooks-system/application/services/notification/MacNotificationSender.js +11 -0
  55. package/scripts/hooks-system/application/services/notification/NotificationCenterService.js +18 -0
  56. package/scripts/hooks-system/application/services/notification/NotificationDispatcher.js +11 -0
  57. package/scripts/hooks-system/application/services/notification/components/NotificationCooldownManager.js +18 -0
  58. package/scripts/hooks-system/application/services/notification/components/NotificationDeduplicator.js +18 -0
  59. package/scripts/hooks-system/application/services/notification/components/NotificationQueue.js +11 -0
  60. package/scripts/hooks-system/application/services/notification/components/NotificationRetryExecutor.js +20 -0
  61. package/scripts/hooks-system/application/services/platform/PlatformHeuristics.js +19 -0
  62. package/scripts/hooks-system/application/services/recovery/AutoRecoveryManager.js +19 -0
  63. package/scripts/hooks-system/application/services/smart-commit/CommitMessageSuggester.js +11 -0
  64. package/scripts/hooks-system/application/services/smart-commit/FileContextGrouper.js +19 -0
  65. package/scripts/hooks-system/application/services/smart-commit/SmartCommitSummaryBuilder.js +4 -0
  66. package/scripts/hooks-system/application/services/token/CursorTokenService.js +20 -0
  67. package/scripts/hooks-system/application/services/token/TokenMetricsService.js +11 -13
  68. package/scripts/hooks-system/application/services/token/TokenMonitorService.js +19 -0
  69. package/scripts/hooks-system/application/services/token/TokenStatusReporter.js +12 -0
  70. package/scripts/hooks-system/bin/__tests__/evidence-update.spec.js +49 -0
  71. package/scripts/hooks-system/bin/cli.js +1 -15
  72. package/scripts/hooks-system/config/project.config.json +1 -1
  73. package/scripts/hooks-system/domain/events/index.js +24 -31
  74. package/scripts/hooks-system/domain/exceptions/index.js +87 -0
  75. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidAnalysisOrchestrator.js +2 -3
  76. package/scripts/hooks-system/infrastructure/ast/ast-core.js +20 -12
  77. package/scripts/hooks-system/infrastructure/ast/ast-intelligence.js +18 -8
  78. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/BackendPatternDetector.js +1 -2
  79. package/scripts/hooks-system/infrastructure/ast/backend/ast-backend.js +14 -18
  80. package/scripts/hooks-system/infrastructure/ast/frontend/ast-frontend.js +196 -196
  81. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/__tests__/iOSASTIntelligentAnalyzer.spec.js +66 -0
  82. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSASTIntelligentAnalyzer.js +2 -3
  83. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSArchitectureRules.js +24 -86
  84. package/scripts/hooks-system/infrastructure/config/config.js +5 -0
  85. package/scripts/hooks-system/infrastructure/hooks/skill-activation-prompt.js +2 -3
  86. package/scripts/hooks-system/infrastructure/logging/UnifiedLoggerFactory.js +5 -35
  87. package/scripts/hooks-system/infrastructure/orchestration/intelligent-audit.js +16 -86
  88. package/scripts/hooks-system/infrastructure/shell/orchestrators/audit-orchestrator.sh +54 -92
  89. package/scripts/hooks-system/infrastructure/telemetry/metric-scope.js +98 -0
  90. package/scripts/hooks-system/infrastructure/telemetry/metrics-server.js +2 -51
  91. package/scripts/hooks-system/infrastructure/validators/enforce-english-literals.js +8 -6
@@ -10,8 +10,8 @@
10
10
  ---
11
11
 
12
12
  ## 📊 Resumen Ejecutivo
13
- - **Estado actual:** ⚠️ Acción requerida (217 críticas, 1 alta, 117 medias, 211 bajas)
14
- - **Branch:** `fix/audit-staged-severity-case-insensitive`
13
+ - **Estado actual:** ⚠️ Acción requerida (1 crítica, 4 altas, 294 medias, 242 bajas)
14
+ - **Branch:** `feature/add-prometheus-metrics`
15
15
  - **Fecha de inicio:** 30/12/2025 — **ETA general:** 15/01/2026
16
16
  - **Objetivo:** Reducir a 0 las CRÍTICAS/HIGH y bajar el total < 20 antes de permitir commits sin bypass.
17
17
  - **Riesgos:**
@@ -29,16 +29,12 @@
29
29
  gantt
30
30
  title Fases de Resolución de Violaciones
31
31
  dateFormat YYYY-MM-DD
32
- section Fase 1: CRÍTICAS
33
- Excepciones personalizadas :active, crit1, 2025-12-30, 4d
34
- Separación de entornos : crit2, after crit1, 3d
35
- Auditoría de seguridad : crit3, after crit2, 3d
36
- Métricas Prometheus : crit4, after crit3, 2d
37
- Patrones de confiabilidad : crit5, after crit4, 2d
38
-
39
- section Fase 2: HIGH + MEDIUM
40
- Corrección HIGH : high1, after crit5, 1d
41
- Refactorización MEDIUM : med1, after high1, 5d
32
+ section Fase 1: BLOQUEANTES (CRITICAL + HIGH)
33
+ Resolver CRITICAL :active, crit1, 2025-12-30, 1d
34
+ Resolver HIGH : high1, after crit1, 2d
35
+
36
+ section Fase 2: MEDIUM
37
+ Refactorización MEDIUM : med1, after high1, 7d
42
38
 
43
39
  section Fase 3: LOW
44
40
  Optimizaciones y documentación : low1, after med1, 5d
@@ -46,50 +42,56 @@ gantt
46
42
 
47
43
  ---
48
44
 
49
- ## 🔴 Fase 1: Violaciones CRÍTICAS (217)
50
- | Estado | Violación | Cant. | Responsable | DOD (Definition of Done) | Doc |
51
- |--------|-----------|-------|-------------|--------------------------|-----|
52
- | | backend.error.custom_exceptions | 105 | BE | CustomError base + reemplazo de `Error` genérico en BE; tests pasando | [Guía de excepciones](../docs/error-handling.md) |
53
- | | backend.config.missing_env_separation | 80 | BE | Config por entorno (dev/stg/prod), sin secretos hardcode | [Config entornos](../docs/env-configuration.md) |
54
- | ✅ | backend.security.missing_audit_logging | 69 | BE | Audit trail en operaciones sensibles + logs estructurados | [Audit logging](../docs/security-auditing.md) |
55
- | ✅ | backend.metrics.missing_prometheus | 64 | BE | Endpoints /metrics, instrumentación clave y dashboard base | [Prometheus](../docs/metrics-monitoring.md) |
56
- | ✅ | backend.reliability.missing_bulkhead | 40 | BE | Limitadores/aislamiento en puntos críticos + pruebas de carga | [Reliability](../docs/reliability-patterns.md) |
45
+ ## 🔴 Fase 1: Violaciones BLOQUEANTES (CRITICAL + HIGH)
46
+ | Estado | Severidad | Cant. | Responsable | DOD (Definition of Done) | Fuente |
47
+ |--------|-----------|-------|-------------|--------------------------|--------|
48
+ | | CRITICAL | 1 | BE | Resolver la violación CRITICAL en repositorio (0 CRITICAL para desbloquear) | `.audit_tmp/ast-summary.json` / `.violations-by-priority.md` |
49
+ | | HIGH | 4 | BE | Resolver las 4 violaciones HIGH en repositorio (0 HIGH para desbloquear) | `.audit_tmp/ast-summary.json` / `.violations-by-priority.md` |
57
50
 
58
51
  ---
59
52
 
60
- ## 🟠 Fase 2: Violaciones HIGH + MEDIUM (118)
53
+ ## 🟠 Fase 2: Violaciones MEDIUM (294)
61
54
  | Estado | Violación | Cant. | Responsable | DOD | Doc |
62
55
  |--------|-----------|-------|-------------|-----|-----|
63
- | | HIGH (1) | 1 | BE | No aplica (repo JS puro sin TS); se documenta enfoque de seguridad de tipos | [Type safety](../docs/type-safety.md) |
64
- | ✅ | backend.testing.mocks | 40 | QA/BE | Mocks revisados; cobertura > 80% en módulos afectados | [Testing](../docs/testing-strategies.md) |
65
- | ✅ | backend.event.handler | 26 | BE | Handlers idempotentes + tests de eventos | [Eventos](../docs/event-handling.md) |
66
- | ⏳ | backend.observability.missing_prometheus | 24 | BE | Métricas por handler; dashboards mínimos | [Observabilidad](../docs/observability.md) |
67
- | ✅ | backend.auth.missing_cors | 17 | BE | No aplica al hook-system (no expone servidor HTTP); la detección queda en proyectos auditados | [CORS](../docs/cors-configuration.md) |
68
- | ✅ | backend.observability.missing_alerting | 10 | SRE | Alertas en métricas críticas; umbrales definidos | [Alerting](../docs/alerting-system.md) |
56
+ | | MEDIUM | 294 | BE | Resolver violaciones de complejidad media restantes | [Medium violations](../docs/medium-violations.md) |
69
57
 
70
58
  ---
71
59
 
72
- ## 🔵 Fase 3: Violaciones LOW (211)
60
+ ## 🔵 Fase 3: Violaciones LOW (242)
73
61
  | Estado | Violación | Cant. | Responsable | DOD | Doc |
74
62
  |--------|-----------|-------|-------------|-----|-----|
75
- | ⏳ | frontend.code_quality.comment | 4 | FE | Comentarios depurados; lint OK | [Code standards](../docs/code-standards.md) |
76
- | ⏳ | frontend.code_quality.magic_number | 4 | FE | Constantes declaradas; tests ajustados | [Constantes](../docs/constants-vs-magic-numbers.md) |
77
- | ⏳ | frontend.devops.hardcoded_feature_flag | 2 | FE/DevOps | Flags externalizados por entorno | [Feature flags](../docs/feature-flags.md) |
78
- | ⏳ | frontend.performance.code_splitting | 2 | FE | Split aplicado en rutas pesadas; bundle size reducido | [Perf FE](../docs/frontend-performance.md) |
79
- | | frontend.performance.missing_code_splitting | 2 | FE | Lazy loading habilitado en vistas grandes | [Code splitting](../docs/code-splitting.md) |
63
+ | ⏳ | LOW | 242 | BE/FE | Resolver violaciones de baja prioridad restantes | [Low violations](../docs/low-violations.md) |
64
+
65
+ ---
66
+
67
+ ## 🎯 Top violaciones (por volumen / impacto) para priorizar dentro de MEDIUM/LOW
68
+ | Prioridad | Violación | Cant. | Notas |
69
+ |----------|-----------|-------|------|
70
+ | P1 | backend.error.custom_exceptions | 105 | Normalmente MEDIUM: refactor a CustomError + reemplazo de `Error` genérico en BE |
71
+ | P1 | backend.config.missing_env_separation | 81 | Normalmente MEDIUM: separar config por entorno |
72
+ | P1 | backend.security.missing_audit_logging | 69 | Normalmente MEDIUM: audit trail en operaciones sensibles |
73
+ | P2 | backend.metrics.missing_prometheus | 42 | MEDIUM/LOW según regla: instrumentación de servicios |
74
+ | P2 | backend.reliability.missing_bulkhead | 41 | MEDIUM/LOW: bulkheads/timeouts en puntos críticos |
75
+ | P2 | backend.testing.mocks | 40 | MEDIUM: mejorar estrategia de tests |
76
+ | P2 | backend.observability.missing_prometheus | 30 | LOW: observabilidad y dashboards |
77
+ | P3 | backend.event.handler | 26 | LOW: try/catch y resiliencia |
78
+ | P3 | backend.auth.missing_cors | 17 | LOW: CORS/headers |
79
+ | P3 | backend.event.emitter | 14 | LOW: emisores de eventos seguros |
80
80
 
81
81
  ---
82
82
 
83
83
  ## 📈 Métricas de Progreso
84
84
  | Fase | Total | Completado | % |
85
85
  |------|-------|------------|---|
86
- | CRÍTICAS | 217 | 0 | 0% |
87
- | HIGH + MEDIUM | 118 | 0 | 0% |
88
- | LOW | 211 | 0 | 0% |
89
- | **TOTAL** | **546** | **0** | **0%** |
86
+ | BLOQUEANTES (CRITICAL + HIGH) | 5 | 0 | 0% |
87
+ | MEDIUM | 294 | 0 | 0% |
88
+ | LOW | 242 | 0 | 0% |
89
+ | **TOTAL** | **541** | **0** | **0%** |
90
90
 
91
91
  **Riesgos actualizados:**
92
92
  1) Implementación de Prometheus podría requerir cambios de infra; 2) Revisión de seguridad depende de disponibilidad de equipo; 3) Refactorizaciones pueden impactar tiempos.
93
93
 
94
94
  **Comentarios/Notas colaborativas:**
95
95
  - Añade comentarios bajo cada tabla al cerrar tareas (usa la leyenda para actualizar estados).
96
+ - Progreso en métricas Prometheus: aplicada una barrida automática sobre `scripts/hooks-system/application/services/**`; el audit sigue reportando 42 (`backend.metrics.missing_prometheus`) y 30 (`backend.observability.missing_prometheus`) pendientes.
97
+ - Último escaneo: 449 archivos, 541 violaciones totales (1 crítica, 4 altas, 294 medias, 242 bajas).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pumuki-ast-hooks",
3
- "version": "5.3.18",
3
+ "version": "5.3.20",
4
4
  "description": "Enterprise-grade AST Intelligence System with multi-platform support (iOS, Android, Backend, Frontend) and Feature-First + DDD + Clean Architecture enforcement. Includes dynamic violations API for intelligent querying.",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -86,10 +86,16 @@
86
86
  "ts-morph": "^21.0.0"
87
87
  },
88
88
  "devDependencies": {
89
+ "@babel/generator": "^7.28.5",
90
+ "@babel/parser": "^7.28.5",
91
+ "@babel/traverse": "^7.28.5",
89
92
  "@pumuki/ast-intelligence-hooks": "file:pumuki-ast-intelligence-hooks-5.3.1.tgz",
90
93
  "@types/node": "^20.10.0",
91
94
  "eslint": "^9.12.0",
92
95
  "jest": "^30.2.0",
96
+ "jscodeshift": "^17.3.0",
97
+ "pumuki-ast-hooks": "^5.3.19",
98
+ "recast": "^0.23.11",
93
99
  "typescript": "^5.3.0"
94
100
  },
95
101
  "files": [
@@ -116,4 +122,4 @@
116
122
  "./skills": "./skills/skill-rules.json",
117
123
  "./hooks": "./hooks/index.js"
118
124
  }
119
- }
125
+ }
@@ -21,54 +21,19 @@ const TokenMonitor = require('./services/monitoring/TokenMonitor');
21
21
  const ActivityMonitor = require('./services/monitoring/ActivityMonitor');
22
22
  const DevDocsMonitor = require('./services/monitoring/DevDocsMonitor');
23
23
  const AstMonitor = require('./services/monitoring/AstMonitor');
24
- const AuditLogger = require('./services/logging/AuditLogger');
25
24
 
26
25
  const path = require('path');
27
26
  const fs = require('fs');
28
- const env = require('../config/env');
29
-
30
- // Import recordMetric for prometheus metrics
31
- const { recordMetric } = require('../infrastructure/telemetry/metrics-logger');
32
27
 
33
28
  class CompositionRoot {
34
29
  constructor(repoRoot) {
35
30
  this.repoRoot = repoRoot;
36
31
  this.instances = new Map();
37
32
 
38
- this._initializeInfrastructure();
39
- this._initializeServices();
40
- this._initializeMonitors();
41
- }
42
-
43
- _initializeInfrastructure() {
44
33
  // Ensure audit directories exist
45
- this.auditDir = path.join(this.repoRoot, '.audit-reports');
46
- this.tempDir = path.join(this.repoRoot, '.audit_tmp');
34
+ this.auditDir = path.join(repoRoot, '.audit-reports');
35
+ this.tempDir = path.join(repoRoot, '.audit_tmp');
47
36
  this._ensureDirectories([this.auditDir, this.tempDir]);
48
-
49
- // Audit log composition root creation
50
- const auditLogger = this.getAuditLogger();
51
- auditLogger.log({
52
- action: 'composition_root_created',
53
- category: 'system',
54
- severity: 'info',
55
- message: 'CompositionRoot initialized for dependency injection',
56
- metadata: {
57
- repoRoot: this.repoRoot,
58
- auditDir: this.auditDir,
59
- tempDir: this.tempDir
60
- }
61
- });
62
- }
63
-
64
- _initializeServices() {
65
- // Services are created lazily when requested
66
- // This reduces the initialization load
67
- }
68
-
69
- _initializeMonitors() {
70
- // Monitors are created lazily when requested
71
- // This reduces the initialization load
72
37
  }
73
38
 
74
39
  _ensureDirectories(dirs) {
@@ -86,7 +51,7 @@ class CompositionRoot {
86
51
  file: {
87
52
  enabled: true,
88
53
  path: path.join(this.auditDir, 'guard-audit.jsonl'),
89
- level: env.get('HOOK_LOG_LEVEL', env.isProd ? 'warn' : 'info')
54
+ level: process.env.HOOK_LOG_LEVEL || 'info'
90
55
  },
91
56
  console: {
92
57
  enabled: false,
@@ -108,18 +73,6 @@ class CompositionRoot {
108
73
  return this.instances.get('notificationService');
109
74
  }
110
75
 
111
- getAuditLogger() {
112
- if (!this.instances.has('auditLogger')) {
113
- const logger = this.getLogger();
114
- this.instances.set('auditLogger', new AuditLogger({
115
- repoRoot: this.repoRoot,
116
- filename: path.join('.audit_tmp', 'audit.log'),
117
- logger
118
- }));
119
- }
120
- return this.instances.get('auditLogger');
121
- }
122
-
123
76
  // --- Infrastructure Adapters ---
124
77
 
125
78
  getNotificationAdapter() {
@@ -230,9 +183,9 @@ class CompositionRoot {
230
183
  getEvidenceMonitor() {
231
184
  if (!this.instances.has('evidenceMonitor')) {
232
185
  this.instances.set('evidenceMonitor', new EvidenceMonitor(this.repoRoot, {
233
- staleThresholdMs: env.getNumber('HOOK_GUARD_EVIDENCE_STALE_THRESHOLD', 180000),
234
- pollIntervalMs: env.getNumber('HOOK_GUARD_EVIDENCE_POLL_INTERVAL', 30000),
235
- reminderIntervalMs: env.getNumber('HOOK_GUARD_EVIDENCE_REMINDER_INTERVAL', 60000)
186
+ staleThresholdMs: Number(process.env.HOOK_GUARD_EVIDENCE_STALE_THRESHOLD || 180000),
187
+ pollIntervalMs: Number(process.env.HOOK_GUARD_EVIDENCE_POLL_INTERVAL || 30000),
188
+ reminderIntervalMs: Number(process.env.HOOK_GUARD_EVIDENCE_REMINDER_INTERVAL || 60000)
236
189
  }));
237
190
  }
238
191
  return this.instances.get('evidenceMonitor');
@@ -241,11 +194,11 @@ class CompositionRoot {
241
194
  getGitTreeMonitor() {
242
195
  if (!this.instances.has('gitTreeMonitor')) {
243
196
  this.instances.set('gitTreeMonitor', new GitTreeMonitor(this.repoRoot, {
244
- stagedThreshold: env.getNumber('HOOK_GUARD_DIRTY_TREE_STAGED_LIMIT', 10),
245
- unstagedThreshold: env.getNumber('HOOK_GUARD_DIRTY_TREE_UNSTAGED_LIMIT', 15),
246
- totalThreshold: env.getNumber('HOOK_GUARD_DIRTY_TREE_TOTAL_LIMIT', 20),
247
- checkIntervalMs: env.getNumber('HOOK_GUARD_DIRTY_TREE_INTERVAL', 60000),
248
- reminderMs: env.getNumber('HOOK_GUARD_DIRTY_TREE_REMINDER', 300000)
197
+ stagedThreshold: Number(process.env.HOOK_GUARD_DIRTY_TREE_STAGED_LIMIT || 10),
198
+ unstagedThreshold: Number(process.env.HOOK_GUARD_DIRTY_TREE_UNSTAGED_LIMIT || 15),
199
+ totalThreshold: Number(process.env.HOOK_GUARD_DIRTY_TREE_TOTAL_LIMIT || 20),
200
+ checkIntervalMs: Number(process.env.HOOK_GUARD_DIRTY_TREE_INTERVAL || 60000),
201
+ reminderMs: Number(process.env.HOOK_GUARD_DIRTY_TREE_REMINDER || 300000)
249
202
  }));
250
203
  }
251
204
  return this.instances.get('gitTreeMonitor');
@@ -266,11 +219,11 @@ class CompositionRoot {
266
219
  const github = this.getGitHubAdapter();
267
220
 
268
221
  this.instances.set('gitFlowService', new GitFlowService(this.repoRoot, {
269
- developBranch: env.get('HOOK_GUARD_GITFLOW_DEVELOP_BRANCH', 'develop'),
270
- mainBranch: env.get('HOOK_GUARD_GITFLOW_MAIN_BRANCH', 'main'),
271
- autoSyncEnabled: env.getBool('HOOK_GUARD_GITFLOW_AUTOSYNC', true),
272
- autoCleanEnabled: env.getBool('HOOK_GUARD_GITFLOW_AUTOCLEAN', true),
273
- requireClean: env.getBool('HOOK_GUARD_GITFLOW_REQUIRE_CLEAN', true)
222
+ developBranch: process.env.HOOK_GUARD_GITFLOW_DEVELOP_BRANCH || 'develop',
223
+ mainBranch: process.env.HOOK_GUARD_GITFLOW_MAIN_BRANCH || 'main',
224
+ autoSyncEnabled: process.env.HOOK_GUARD_GITFLOW_AUTOSYNC !== 'false',
225
+ autoCleanEnabled: process.env.HOOK_GUARD_GITFLOW_AUTOCLEAN !== 'false',
226
+ requireClean: process.env.HOOK_GUARD_GITFLOW_REQUIRE_CLEAN !== 'false'
274
227
  }, logger, gitQuery, gitCommand, github));
275
228
  }
276
229
  return this.instances.get('gitFlowService');
@@ -281,7 +234,7 @@ class CompositionRoot {
281
234
  const logger = this.getLogger();
282
235
  this.instances.set('activityMonitor', new ActivityMonitor({
283
236
  repoRoot: this.repoRoot,
284
- inactivityGraceMs: env.getNumber('HOOK_GUARD_INACTIVITY_GRACE_MS', 420000),
237
+ inactivityGraceMs: Number(process.env.HOOK_GUARD_INACTIVITY_GRACE_MS || 420000),
285
238
  logger
286
239
  }));
287
240
  }
@@ -294,9 +247,9 @@ class CompositionRoot {
294
247
  const notificationService = this.getNotificationService();
295
248
  this.instances.set('devDocsMonitor', new DevDocsMonitor({
296
249
  repoRoot: this.repoRoot,
297
- checkIntervalMs: env.getNumber('HOOK_GUARD_DEV_DOCS_CHECK_INTERVAL', 300000),
298
- staleThresholdMs: env.getNumber('HOOK_GUARD_DEV_DOCS_STALE_THRESHOLD', 86400000),
299
- autoRefreshEnabled: env.getBool('HOOK_GUARD_DEV_DOCS_AUTO_REFRESH', true),
250
+ checkIntervalMs: Number(process.env.HOOK_GUARD_DEV_DOCS_CHECK_INTERVAL || 300000),
251
+ staleThresholdMs: Number(process.env.HOOK_GUARD_DEV_DOCS_STALE_THRESHOLD || 86400000),
252
+ autoRefreshEnabled: process.env.HOOK_GUARD_DEV_DOCS_AUTO_REFRESH !== 'false',
300
253
  logger,
301
254
  notificationService
302
255
  }));
@@ -310,9 +263,9 @@ class CompositionRoot {
310
263
  const notificationService = this.getNotificationService();
311
264
  this.instances.set('astMonitor', new AstMonitor({
312
265
  repoRoot: this.repoRoot,
313
- debounceMs: env.getNumber('HOOK_AST_WATCH_DEBOUNCE', 8000),
314
- cooldownMs: env.getNumber('HOOK_AST_WATCH_COOLDOWN', 30000),
315
- enabled: env.getBool('HOOK_AST_WATCH', true),
266
+ debounceMs: Number(process.env.HOOK_AST_WATCH_DEBOUNCE || 8000),
267
+ cooldownMs: Number(process.env.HOOK_AST_WATCH_COOLDOWN || 30000),
268
+ enabled: process.env.HOOK_AST_WATCH !== 'false',
316
269
  logger,
317
270
  notificationService
318
271
  }));
@@ -338,7 +291,6 @@ class CompositionRoot {
338
291
  const notificationService = this.getNotificationService();
339
292
  const monitors = this.getMonitors();
340
293
  const orchestrator = this.getOrchestrator();
341
- const auditLogger = this.getAuditLogger();
342
294
  const config = {
343
295
  debugLogPath: path.join(this.auditDir, 'guard-debug.log'),
344
296
  repoRoot: this.repoRoot
@@ -349,8 +301,7 @@ class CompositionRoot {
349
301
  notificationService,
350
302
  monitors,
351
303
  orchestration: orchestrator,
352
- config,
353
- auditLogger
304
+ config
354
305
  }));
355
306
  }
356
307
  return this.instances.get('guardService');
@@ -3,8 +3,18 @@ const { execSync } = require('child_process');
3
3
  const path = require('path');
4
4
  const UnifiedLogger = require('./logging/UnifiedLogger');
5
5
 
6
+ const {
7
+ createMetricScope: createMetricScope
8
+ } = require('../../../infrastructure/telemetry/metric-scope');
9
+
6
10
  class AutonomousOrchestrator {
7
11
  constructor(contextEngine, platformDetector, rulesLoader, logger = new UnifiedLogger()) {
12
+ const m_constructor = createMetricScope({
13
+ hook: 'autonomous_orchestrator',
14
+ operation: 'constructor'
15
+ });
16
+
17
+ m_constructor.started();
8
18
  this.contextEngine = contextEngine;
9
19
  this.platformDetector = platformDetector || new PlatformDetectionService();
10
20
  this.rulesLoader = rulesLoader;
@@ -15,6 +25,7 @@ class AutonomousOrchestrator {
15
25
  };
16
26
  this.lastAnalysis = null;
17
27
  this.lastAnalysisTime = 0;
28
+ m_constructor.success();
18
29
  }
19
30
 
20
31
  detectFromASTSystemFiles(files) {
@@ -123,6 +134,13 @@ class AutonomousOrchestrator {
123
134
  }
124
135
 
125
136
  getLastAnalysis() {
137
+ const m_get_last_analysis = createMetricScope({
138
+ hook: 'autonomous_orchestrator',
139
+ operation: 'get_last_analysis'
140
+ });
141
+
142
+ m_get_last_analysis.started();
143
+ m_get_last_analysis.success();
126
144
  return this.lastAnalysis;
127
145
  }
128
146
  }
@@ -1,7 +1,17 @@
1
1
  const crypto = require('crypto');
2
2
 
3
+ const {
4
+ createMetricScope: createMetricScope
5
+ } = require('../../../infrastructure/telemetry/metric-scope');
6
+
3
7
  class ContextDetectionEngine {
4
8
  constructor(repoRootOrGitPort = null, logger = console) {
9
+ const m_constructor = createMetricScope({
10
+ hook: 'context_detection_engine',
11
+ operation: 'constructor'
12
+ });
13
+
14
+ m_constructor.started();
5
15
  if (typeof repoRootOrGitPort === 'string') {
6
16
  this.repoRoot = repoRootOrGitPort;
7
17
  this.git = null;
@@ -16,6 +26,7 @@ class ContextDetectionEngine {
16
26
  timestamp: 0,
17
27
  ttl: 10000
18
28
  };
29
+ m_constructor.success();
19
30
  }
20
31
 
21
32
  async detectContext() {
@@ -54,40 +65,74 @@ class ContextDetectionEngine {
54
65
  }
55
66
 
56
67
  getStagedFiles() {
68
+ const m_get_staged_files = createMetricScope({
69
+ hook: 'context_detection_engine',
70
+ operation: 'get_staged_files'
71
+ });
72
+
73
+ m_get_staged_files.started();
57
74
  try {
75
+ m_get_staged_files.success();
58
76
  return this.git.getStagedFiles();
59
77
  } catch (error) {
60
78
  this.logger.error('ContextDetectionEngine: Failed to get staged files', error);
79
+ m_get_staged_files.success();
61
80
  return [];
62
81
  }
82
+ m_get_staged_files.success();
63
83
  }
64
84
 
65
85
  getStagedSignature() {
86
+ const m_get_staged_signature = createMetricScope({
87
+ hook: 'context_detection_engine',
88
+ operation: 'get_staged_signature'
89
+ });
90
+
91
+ m_get_staged_signature.started();
66
92
  try {
67
93
  const patch = this.git.getDiff(true);
68
94
  if (!patch) return '';
95
+ m_get_staged_signature.success();
69
96
  return crypto.createHash('sha1').update(patch).digest('hex');
70
97
  } catch (error) {
98
+ m_get_staged_signature.success();
71
99
  return '';
72
100
  }
101
+ m_get_staged_signature.success();
73
102
  }
74
103
 
75
104
  getRecentlyModifiedFiles() {
105
+ const m_get_recently_modified_files = createMetricScope({
106
+ hook: 'context_detection_engine',
107
+ operation: 'get_recently_modified_files'
108
+ });
109
+
110
+ m_get_recently_modified_files.started();
76
111
  try {
77
112
  const output = this.git.getStatusShort();
78
113
  if (!output) return [];
79
114
 
115
+ m_get_recently_modified_files.success();
116
+
80
117
  return output
81
118
  .split('\n')
82
119
  .filter(Boolean)
83
120
  .map(line => line.trim().substring(2)) // Remove status code
84
121
  .filter(file => !file.startsWith('.git'));
85
122
  } catch (error) {
123
+ m_get_recently_modified_files.success();
86
124
  return [];
87
125
  }
126
+ m_get_recently_modified_files.success();
88
127
  }
89
128
 
90
129
  getRecentCommitPatterns() {
130
+ const m_get_recent_commit_patterns = createMetricScope({
131
+ hook: 'context_detection_engine',
132
+ operation: 'get_recent_commit_patterns'
133
+ });
134
+
135
+ m_get_recent_commit_patterns.started();
91
136
  try {
92
137
  const output = this.git.getLog(10);
93
138
  if (!output) return [];
@@ -116,18 +161,31 @@ class ContextDetectionEngine {
116
161
  commits.push(currentCommit);
117
162
  }
118
163
 
164
+ m_get_recent_commit_patterns.success();
165
+
119
166
  return commits.slice(0, 10);
120
167
  } catch (error) {
168
+ m_get_recent_commit_patterns.success();
121
169
  return [];
122
170
  }
171
+ m_get_recent_commit_patterns.success();
123
172
  }
124
173
 
125
174
  getCurrentBranch() {
175
+ const m_get_current_branch = createMetricScope({
176
+ hook: 'context_detection_engine',
177
+ operation: 'get_current_branch'
178
+ });
179
+
180
+ m_get_current_branch.started();
126
181
  try {
182
+ m_get_current_branch.success();
127
183
  return this.git.getCurrentBranch();
128
184
  } catch (error) {
185
+ m_get_current_branch.success();
129
186
  return 'unknown';
130
187
  }
188
+ m_get_current_branch.success();
131
189
  }
132
190
 
133
191
  inferFromGitStatus() {
@@ -1,9 +1,18 @@
1
+ const {
2
+ createMetricScope: createMetricScope
3
+ } = require('../../../infrastructure/telemetry/metric-scope');
4
+
1
5
  const fs = require('fs').promises;
2
6
  const path = require('path');
3
- const env = require('../config/env');
4
7
 
5
8
  class DynamicRulesLoader {
6
9
  constructor(rulesDirectory, logger = console) {
10
+ const m_constructor = createMetricScope({
11
+ hook: 'dynamic_rules_loader',
12
+ operation: 'constructor'
13
+ });
14
+
15
+ m_constructor.started();
7
16
  this.rulesDirectory = rulesDirectory || null;
8
17
  this.logger = logger;
9
18
  this.rulesDirectories = this.resolveRulesDirectories();
@@ -19,6 +28,7 @@ class DynamicRulesLoader {
19
28
  ttl: 60000
20
29
  };
21
30
  this.lastLoadWarnings = [];
31
+ m_constructor.success();
22
32
  }
23
33
 
24
34
  resolveRulesDirectories() {
@@ -28,7 +38,7 @@ class DynamicRulesLoader {
28
38
  return [this.rulesDirectory];
29
39
  }
30
40
 
31
- const envRaw = env.get('AST_RULES_DIRECTORIES');
41
+ const envRaw = process.env.AST_RULES_DIRECTORIES;
32
42
  if (envRaw && typeof envRaw === 'string' && envRaw.trim().length > 0) {
33
43
  return envRaw
34
44
  .split(',')