pumuki-ast-hooks 5.3.20 → 5.3.22

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 (95) hide show
  1. package/docs/RELEASE_NOTES.md +35 -0
  2. package/docs/VIOLATIONS_RESOLUTION_PLAN.md +60 -59
  3. package/package.json +3 -3
  4. package/scripts/hooks-system/.AI_TOKEN_STATUS.txt +1 -1
  5. package/scripts/hooks-system/.audit-reports/notifications.log +935 -0
  6. package/scripts/hooks-system/.audit-reports/token-monitor.log +2809 -0
  7. package/scripts/hooks-system/application/CompositionRoot.js +38 -22
  8. package/scripts/hooks-system/application/services/AutonomousOrchestrator.js +0 -18
  9. package/scripts/hooks-system/application/services/ContextDetectionEngine.js +0 -58
  10. package/scripts/hooks-system/application/services/DynamicRulesLoader.js +2 -12
  11. package/scripts/hooks-system/application/services/GitFlowService.js +0 -80
  12. package/scripts/hooks-system/application/services/GitTreeState.js +2 -5
  13. package/scripts/hooks-system/application/services/HookSystemScheduler.js +0 -4
  14. package/scripts/hooks-system/application/services/IntelligentCommitAnalyzer.js +0 -25
  15. package/scripts/hooks-system/application/services/IntelligentGitTreeMonitor.js +0 -11
  16. package/scripts/hooks-system/application/services/PlatformAnalysisService.js +0 -19
  17. package/scripts/hooks-system/application/services/PlatformDetectionService.js +0 -19
  18. package/scripts/hooks-system/application/services/PlaybookRunner.js +1 -22
  19. package/scripts/hooks-system/application/services/PredictiveHookAdvisor.js +0 -19
  20. package/scripts/hooks-system/application/services/RealtimeGuardPlugin.js +0 -25
  21. package/scripts/hooks-system/application/services/RealtimeGuardService.js +71 -41
  22. package/scripts/hooks-system/application/services/SmartDirtyTreeAnalyzer.js +0 -11
  23. package/scripts/hooks-system/application/services/commit/CommitMessageGenerator.js +0 -11
  24. package/scripts/hooks-system/application/services/commit/FeatureDetector.js +0 -11
  25. package/scripts/hooks-system/application/services/evidence/EvidenceContextManager.js +0 -25
  26. package/scripts/hooks-system/application/services/guard/GuardAutoManagerService.js +31 -21
  27. package/scripts/hooks-system/application/services/guard/GuardConfig.js +15 -18
  28. package/scripts/hooks-system/application/services/guard/GuardEventLogger.js +0 -11
  29. package/scripts/hooks-system/application/services/guard/GuardHealthReminder.js +0 -26
  30. package/scripts/hooks-system/application/services/guard/GuardHeartbeatMonitor.js +6 -20
  31. package/scripts/hooks-system/application/services/guard/GuardLockManager.js +0 -11
  32. package/scripts/hooks-system/application/services/guard/GuardMonitorLoop.js +0 -25
  33. package/scripts/hooks-system/application/services/guard/GuardNotificationHandler.js +0 -11
  34. package/scripts/hooks-system/application/services/guard/GuardProcessManager.js +23 -11
  35. package/scripts/hooks-system/application/services/guard/GuardRecoveryService.js +0 -11
  36. package/scripts/hooks-system/application/services/installation/ConfigurationGeneratorService.js +0 -18
  37. package/scripts/hooks-system/application/services/installation/FileSystemInstallerService.js +0 -18
  38. package/scripts/hooks-system/application/services/installation/GitEnvironmentService.js +1 -19
  39. package/scripts/hooks-system/application/services/installation/HookInstaller.js +62 -24
  40. package/scripts/hooks-system/application/services/installation/IdeIntegrationService.js +0 -11
  41. package/scripts/hooks-system/application/services/installation/InstallService.js +1 -25
  42. package/scripts/hooks-system/application/services/installation/McpConfigurator.js +2 -19
  43. package/scripts/hooks-system/application/services/installation/PlatformDetectorService.js +0 -11
  44. package/scripts/hooks-system/application/services/installation/VSCodeTaskConfigurator.js +0 -11
  45. package/scripts/hooks-system/application/services/logging/AuditLogger.js +0 -8
  46. package/scripts/hooks-system/application/services/logging/UnifiedLogger.js +13 -15
  47. package/scripts/hooks-system/application/services/monitoring/ActivityMonitor.js +0 -33
  48. package/scripts/hooks-system/application/services/monitoring/AstMonitor.js +0 -27
  49. package/scripts/hooks-system/application/services/monitoring/DevDocsMonitor.js +0 -26
  50. package/scripts/hooks-system/application/services/monitoring/EvidenceMonitor.js +0 -18
  51. package/scripts/hooks-system/application/services/monitoring/EvidenceMonitorService.js +4 -28
  52. package/scripts/hooks-system/application/services/monitoring/GitTreeMonitor.js +0 -28
  53. package/scripts/hooks-system/application/services/monitoring/GitTreeMonitorService.js +0 -26
  54. package/scripts/hooks-system/application/services/monitoring/HealthCheckProviders.js +0 -4
  55. package/scripts/hooks-system/application/services/monitoring/HealthCheckService.js +0 -25
  56. package/scripts/hooks-system/application/services/monitoring/HeartbeatMonitorService.js +0 -26
  57. package/scripts/hooks-system/application/services/monitoring/TokenMonitor.js +0 -26
  58. package/scripts/hooks-system/application/services/notification/MacNotificationSender.js +0 -11
  59. package/scripts/hooks-system/application/services/notification/NotificationCenterService.js +0 -18
  60. package/scripts/hooks-system/application/services/notification/NotificationDispatcher.js +0 -11
  61. package/scripts/hooks-system/application/services/notification/components/NotificationCooldownManager.js +0 -18
  62. package/scripts/hooks-system/application/services/notification/components/NotificationDeduplicator.js +0 -18
  63. package/scripts/hooks-system/application/services/notification/components/NotificationQueue.js +0 -11
  64. package/scripts/hooks-system/application/services/notification/components/NotificationRetryExecutor.js +0 -20
  65. package/scripts/hooks-system/application/services/platform/PlatformHeuristics.js +0 -19
  66. package/scripts/hooks-system/application/services/recovery/AutoRecoveryManager.js +0 -19
  67. package/scripts/hooks-system/application/services/smart-commit/CommitMessageSuggester.js +0 -11
  68. package/scripts/hooks-system/application/services/smart-commit/FileContextGrouper.js +0 -19
  69. package/scripts/hooks-system/application/services/smart-commit/SmartCommitSummaryBuilder.js +0 -4
  70. package/scripts/hooks-system/application/services/token/CursorTokenService.js +0 -20
  71. package/scripts/hooks-system/application/services/token/TokenMetricsService.js +2 -12
  72. package/scripts/hooks-system/application/services/token/TokenMonitorService.js +0 -19
  73. package/scripts/hooks-system/application/services/token/TokenStatusReporter.js +0 -12
  74. package/scripts/hooks-system/bin/cli.js +15 -1
  75. package/scripts/hooks-system/bin/guard-env.sh +18 -38
  76. package/scripts/hooks-system/bin/guard-supervisor.js +5 -515
  77. package/scripts/hooks-system/bin/session-loader.sh +3 -262
  78. package/scripts/hooks-system/bin/start-guards.sh +21 -184
  79. package/scripts/hooks-system/bin/update-evidence.sh +10 -1161
  80. package/scripts/hooks-system/config/project.config.json +1 -1
  81. package/scripts/hooks-system/domain/events/index.js +31 -24
  82. package/scripts/hooks-system/infrastructure/ast/android/analyzers/AndroidAnalysisOrchestrator.js +3 -2
  83. package/scripts/hooks-system/infrastructure/ast/ast-core.js +12 -20
  84. package/scripts/hooks-system/infrastructure/ast/ast-intelligence.js +8 -18
  85. package/scripts/hooks-system/infrastructure/ast/backend/analyzers/BackendPatternDetector.js +2 -1
  86. package/scripts/hooks-system/infrastructure/ast/backend/ast-backend.js +18 -14
  87. package/scripts/hooks-system/infrastructure/ast/frontend/ast-frontend.js +196 -196
  88. package/scripts/hooks-system/infrastructure/ast/ios/analyzers/iOSASTIntelligentAnalyzer.js +3 -2
  89. package/scripts/hooks-system/infrastructure/hooks/skill-activation-prompt.js +3 -2
  90. package/scripts/hooks-system/infrastructure/logging/UnifiedLoggerFactory.js +5 -4
  91. package/scripts/hooks-system/infrastructure/mcp/ast-intelligence-automation.js +88 -0
  92. package/scripts/hooks-system/infrastructure/orchestration/intelligent-audit.js +17 -16
  93. package/scripts/hooks-system/infrastructure/shell/orchestrators/audit-orchestrator.sh +92 -54
  94. package/scripts/hooks-system/infrastructure/telemetry/metrics-server.js +3 -2
  95. package/scripts/hooks-system/infrastructure/validators/enforce-english-literals.js +6 -8
@@ -1,19 +1,9 @@
1
1
 
2
- const {
3
- createMetricScope: createMetricScope
4
- } = require('../../../infrastructure/telemetry/metric-scope');
5
-
6
2
  const fs = require('fs').promises;
7
3
  const path = require('path');
8
4
 
9
5
  class PlatformDetectionService {
10
6
  constructor() {
11
- const m_constructor = createMetricScope({
12
- hook: 'platform_detection_service',
13
- operation: 'constructor'
14
- });
15
-
16
- m_constructor.started();
17
7
  this.cache = {
18
8
  detections: new Map(),
19
9
  timestamp: 0,
@@ -53,7 +43,6 @@ class PlatformDetectionService {
53
43
  '*.java',
54
44
  ],
55
45
  };
56
- m_constructor.success();
57
46
  }
58
47
 
59
48
  async detectPlatforms(targetPath) {
@@ -153,12 +142,6 @@ class PlatformDetectionService {
153
142
  }
154
143
 
155
144
  getAmbiguityScore(filePath) {
156
- const m_get_ambiguity_score = createMetricScope({
157
- hook: 'platform_detection_service',
158
- operation: 'get_ambiguity_score'
159
- });
160
-
161
- m_get_ambiguity_score.started();
162
145
  const platform = this._detectPlatformUncached(filePath);
163
146
  const lowerPath = filePath.toLowerCase();
164
147
  const ext = path.extname(filePath);
@@ -173,8 +156,6 @@ class PlatformDetectionService {
173
156
  if (ext === '.ts' || ext === '.tsx') return 60;
174
157
  if (ext === '.js' || ext === '.jsx') return 70;
175
158
 
176
- m_get_ambiguity_score.success();
177
-
178
159
  return 100;
179
160
  }
180
161
 
@@ -2,27 +2,13 @@ const fs = require('fs');
2
2
  const path = require('path');
3
3
  const { spawnSync } = require('child_process');
4
4
  const { DomainError, NotFoundError } = require('../../domain/errors');
5
- const { NotFoundException } = require('../domain/exceptions');
6
-
7
- const { recordMetric } = require('../../../infrastructure/telemetry/metrics-logger');
8
-
9
- const {
10
- createMetricScope: createMetricScope
11
- } = require('../../../infrastructure/telemetry/metric-scope');
12
5
 
13
6
  const PLAYBOOKS_PATH = path.join(process.cwd(), 'scripts', 'hooks-system', 'config', 'playbooks.json');
14
7
 
15
8
  class PlaybookRunner {
16
9
  constructor(options = {}) {
17
- const m_constructor = createMetricScope({
18
- hook: 'playbook_runner',
19
- operation: 'constructor'
20
- });
21
-
22
- m_constructor.started();
23
10
  this.cwd = options.cwd || process.cwd();
24
11
  this.playbooks = JSON.parse(fs.readFileSync(PLAYBOOKS_PATH, 'utf8'));
25
- m_constructor.success();
26
12
  }
27
13
 
28
14
  list() {
@@ -30,15 +16,9 @@ class PlaybookRunner {
30
16
  }
31
17
 
32
18
  run(id) {
33
- const m_run = createMetricScope({
34
- hook: 'playbook_runner',
35
- operation: 'run'
36
- });
37
-
38
- m_run.started();
39
19
  const playbook = this.playbooks[id];
40
20
  if (!playbook) {
41
- throw new NotFoundException('Playbook', { id });
21
+ throw new NotFoundError(`Playbook '${id}'`);
42
22
  }
43
23
 
44
24
  for (const step of playbook.steps) {
@@ -53,7 +33,6 @@ class PlaybookRunner {
53
33
  }
54
34
  }
55
35
  }
56
- m_run.success();
57
36
  }
58
37
  }
59
38
 
@@ -1,22 +1,11 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
3
 
4
- const {
5
- createMetricScope: createMetricScope
6
- } = require('../../../infrastructure/telemetry/metric-scope');
7
-
8
4
  const METRICS_FILE = path.join(process.cwd(), '.audit_tmp', 'hook-metrics.jsonl');
9
5
 
10
6
  class PredictiveHookAdvisor {
11
7
  constructor({ windowSize = 200 } = {}) {
12
- const m_constructor = createMetricScope({
13
- hook: 'predictive_hook_advisor',
14
- operation: 'constructor'
15
- });
16
-
17
- m_constructor.started();
18
8
  this.windowSize = windowSize;
19
- m_constructor.success();
20
9
  }
21
10
 
22
11
  loadMetrics() {
@@ -35,12 +24,6 @@ class PredictiveHookAdvisor {
35
24
  }
36
25
 
37
26
  getFailureProbabilities() {
38
- const m_get_failure_probabilities = createMetricScope({
39
- hook: 'predictive_hook_advisor',
40
- operation: 'get_failure_probabilities'
41
- });
42
-
43
- m_get_failure_probabilities.started();
44
27
  const metrics = this.loadMetrics();
45
28
  const stats = {};
46
29
 
@@ -55,8 +38,6 @@ class PredictiveHookAdvisor {
55
38
  }
56
39
  }
57
40
 
58
- m_get_failure_probabilities.success();
59
-
60
41
  return Object.entries(stats)
61
42
  .map(([hook, { total, failures }]) => ({
62
43
  hook,
@@ -1,9 +1,5 @@
1
1
  const EvidenceMonitorService = require('./monitoring/EvidenceMonitorService');
2
2
 
3
- const {
4
- createMetricScope: createMetricScope
5
- } = require('../../../infrastructure/telemetry/metric-scope');
6
-
7
3
  class EvidenceRealtimeGuardPlugin {
8
4
  constructor({
9
5
  repoRoot = process.cwd(),
@@ -11,12 +7,6 @@ class EvidenceRealtimeGuardPlugin {
11
7
  logger = console,
12
8
  evidenceMonitor = null
13
9
  } = {}) {
14
- const m_constructor = createMetricScope({
15
- hook: 'realtime_guard_plugin',
16
- operation: 'constructor'
17
- });
18
-
19
- m_constructor.started();
20
10
  this.repoRoot = repoRoot;
21
11
  this.notificationCenter = notificationCenter;
22
12
  this.logger = logger || console;
@@ -26,33 +16,18 @@ class EvidenceRealtimeGuardPlugin {
26
16
  logger: this.logger,
27
17
  notifier: payload => this.forwardNotification(payload)
28
18
  });
29
- m_constructor.success();
30
19
  }
31
20
 
32
21
  start() {
33
- const m_start = createMetricScope({
34
- hook: 'realtime_guard_plugin',
35
- operation: 'start'
36
- });
37
-
38
- m_start.started();
39
22
  if (typeof this.evidenceMonitor.start === 'function') {
40
23
  this.evidenceMonitor.start();
41
24
  }
42
- m_start.success();
43
25
  }
44
26
 
45
27
  stop() {
46
- const m_stop = createMetricScope({
47
- hook: 'realtime_guard_plugin',
48
- operation: 'stop'
49
- });
50
-
51
- m_stop.started();
52
28
  if (typeof this.evidenceMonitor.stop === 'function') {
53
29
  this.evidenceMonitor.stop();
54
30
  }
55
- m_stop.success();
56
31
  }
57
32
 
58
33
  forwardNotification(payload) {
@@ -1,12 +1,9 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
3
  const { getGitTreeState, isTreeBeyondLimit } = require('./GitTreeState');
4
-
5
- const { recordMetric } = require('../../../infrastructure/telemetry/metrics-logger');
6
-
7
- const {
8
- createMetricScope: createMetricScope
9
- } = require('../../../infrastructure/telemetry/metric-scope');
4
+ const AuditLogger = require('./logging/AuditLogger');
5
+ const { recordMetric } = require('../../infrastructure/telemetry/metrics-logger');
6
+ const env = require('../../../config/env');
10
7
 
11
8
  class RealtimeGuardService {
12
9
  /**
@@ -18,13 +15,6 @@ class RealtimeGuardService {
18
15
  * @param {Object} dependencies.config
19
16
  */
20
17
  constructor(dependencies = {}) {
21
- recordMetric({
22
- hook: 'realtime_guard_service',
23
- operation: 'constructor',
24
- status: 'started',
25
- hasDependencies: !!dependencies
26
- });
27
-
28
18
  const {
29
19
  logger,
30
20
  notificationService,
@@ -43,45 +33,42 @@ class RealtimeGuardService {
43
33
  this.monitors = monitors || {};
44
34
  this.orchestration = orchestration;
45
35
  this.config = config || {};
36
+ this.auditLogger = dependencies.auditLogger || new AuditLogger({ repoRoot: process.cwd(), logger: this.logger });
46
37
 
47
38
  if (!this.config.debugLogPath) {
48
39
  this.config.debugLogPath = path.join(process.cwd(), '.audit-reports', 'guard-debug.log');
49
40
  }
50
41
 
51
42
  this.evidencePath = this.config.evidencePath || path.join(process.cwd(), '.AI_EVIDENCE.json');
52
- this.staleThresholdMs = Number(process.env.HOOK_GUARD_EVIDENCE_STALE_THRESHOLD || 60000);
53
- this.reminderIntervalMs = Number(process.env.HOOK_GUARD_EVIDENCE_REMINDER_INTERVAL || 60000);
54
- this.inactivityGraceMs = Number(process.env.HOOK_GUARD_INACTIVITY_GRACE_MS || 120000);
55
- this.pollIntervalMs = Number(process.env.HOOK_GUARD_EVIDENCE_POLL_INTERVAL || 30000);
43
+ this.staleThresholdMs = env.getNumber('HOOK_GUARD_EVIDENCE_STALE_THRESHOLD', 60000);
44
+ this.reminderIntervalMs = env.getNumber('HOOK_GUARD_EVIDENCE_REMINDER_INTERVAL', 60000);
45
+ this.inactivityGraceMs = env.getNumber('HOOK_GUARD_INACTIVITY_GRACE_MS', 120000);
46
+ this.pollIntervalMs = env.getNumber('HOOK_GUARD_EVIDENCE_POLL_INTERVAL', 30000);
56
47
  this.pollTimer = null;
57
48
  this.lastStaleNotification = 0;
58
49
  this.lastUserActivityAt = 0;
59
50
 
60
- this.gitTreeStagedThreshold = Number(process.env.HOOK_GUARD_DIRTY_TREE_STAGED_LIMIT || 10);
61
- this.gitTreeUnstagedThreshold = Number(process.env.HOOK_GUARD_DIRTY_TREE_UNSTAGED_LIMIT || 15);
62
- this.gitTreeTotalThreshold = Number(process.env.HOOK_GUARD_DIRTY_TREE_TOTAL_LIMIT || 20);
63
- this.gitTreeCheckIntervalMs = Number(process.env.HOOK_GUARD_DIRTY_TREE_INTERVAL || 60000);
64
- this.gitTreeReminderMs = Number(process.env.HOOK_GUARD_DIRTY_TREE_REMINDER || 300000);
51
+ this.gitTreeStagedThreshold = env.getNumber('HOOK_GUARD_DIRTY_TREE_STAGED_LIMIT', 10);
52
+ this.gitTreeUnstagedThreshold = env.getNumber('HOOK_GUARD_DIRTY_TREE_UNSTAGED_LIMIT', 15);
53
+ this.gitTreeTotalThreshold = env.getNumber('HOOK_GUARD_DIRTY_TREE_TOTAL_LIMIT', 20);
54
+ this.gitTreeCheckIntervalMs = env.getNumber('HOOK_GUARD_DIRTY_TREE_INTERVAL', 60000);
55
+ this.gitTreeReminderMs = env.getNumber('HOOK_GUARD_DIRTY_TREE_REMINDER', 300000);
65
56
  this.gitTreeTimer = null;
66
57
  this.lastDirtyTreeNotification = 0;
67
58
  this.dirtyTreeActive = false;
68
59
 
69
- this.autoRefreshCooldownMs = Number(process.env.HOOK_GUARD_EVIDENCE_AUTO_REFRESH_COOLDOWN || 180000);
60
+ this.autoRefreshCooldownMs = env.getNumber('HOOK_GUARD_EVIDENCE_AUTO_REFRESH_COOLDOWN', 180000);
70
61
  this.lastAutoRefresh = 0;
71
62
  this.autoRefreshInFlight = false;
72
63
 
73
64
  this.watchers = [];
74
- this.embedTokenMonitor = process.env.HOOK_GUARD_EMBEDDED_TOKEN_MONITOR === 'true';
65
+ this.embedTokenMonitor = env.getBool('HOOK_GUARD_EMBEDDED_TOKEN_MONITOR', false);
75
66
  }
76
67
 
77
68
  start() {
78
- const m_start = createMetricScope({
79
- hook: 'realtime_guard_service',
80
- operation: 'start'
81
- });
82
-
83
- m_start.started();
84
69
  this.logger.info('Starting RealtimeGuardService...');
70
+ this.auditLogger.record({ action: 'guard.realtime.start', resource: 'realtime_guard', status: 'success' });
71
+ recordMetric({ hook: 'realtime_guard', status: 'start' });
85
72
 
86
73
  // Start all monitors
87
74
  this._startEvidenceMonitoring();
@@ -97,17 +84,12 @@ class RealtimeGuardService {
97
84
  this._startGitFlowSync();
98
85
 
99
86
  this.logger.info('[RealtimeGuardService] All services started');
100
- m_start.success();
101
87
  }
102
88
 
103
89
  stop() {
104
- const m_stop = createMetricScope({
105
- hook: 'realtime_guard_service',
106
- operation: 'stop'
107
- });
108
-
109
- m_stop.started();
110
90
  this.logger.info('Stopping RealtimeGuardService...');
91
+ this.auditLogger.record({ action: 'guard.realtime.stop', resource: 'realtime_guard', status: 'success' });
92
+ recordMetric({ hook: 'realtime_guard', status: 'stop' });
111
93
 
112
94
  this.watchers.forEach(w => w.close());
113
95
  this.watchers = [];
@@ -119,7 +101,6 @@ class RealtimeGuardService {
119
101
  });
120
102
 
121
103
  this.logger.info('[RealtimeGuardService] All services stopped');
122
- m_stop.success();
123
104
  }
124
105
 
125
106
  _startEvidenceMonitoring() {
@@ -130,14 +111,27 @@ class RealtimeGuardService {
130
111
  }
131
112
 
132
113
  _startGitTreeMonitoring() {
133
- if (process.env.HOOK_GUARD_DIRTY_TREE_DISABLED === 'true') return;
114
+ if (env.getBool('HOOK_GUARD_DIRTY_TREE_DISABLED', false)) return;
134
115
 
135
116
  this.monitors.gitTree.startMonitoring((state) => {
136
117
  if (state.isBeyondLimit) {
137
118
  const message = `Git tree has too many files: ${state.total} total (${state.staged} staged, ${state.unstaged} unstaged)`;
138
119
  this.notify(message, 'error', { forceDialog: true });
120
+ this.auditLogger.record({
121
+ action: 'guard.git_tree.dirty',
122
+ resource: 'git_tree',
123
+ status: 'warning',
124
+ meta: { total: state.total, staged: state.staged, unstaged: state.unstaged }
125
+ });
126
+ recordMetric({ hook: 'git_tree', status: 'dirty', total: state.total, staged: state.staged, unstaged: state.unstaged });
139
127
  } else {
140
128
  this.notify('✅ Git tree is clean', 'success');
129
+ this.auditLogger.record({
130
+ action: 'guard.git_tree.clean',
131
+ resource: 'git_tree',
132
+ status: 'success'
133
+ });
134
+ recordMetric({ hook: 'git_tree', status: 'clean' });
141
135
  }
142
136
  });
143
137
  }
@@ -151,22 +145,44 @@ class RealtimeGuardService {
151
145
  try {
152
146
  this.monitors.token.start();
153
147
  this.notify('🔋 Token monitor started', 'info');
148
+ this.auditLogger.record({
149
+ action: 'guard.token_monitor.start',
150
+ resource: 'token_monitor',
151
+ status: 'success'
152
+ });
153
+ recordMetric({ hook: 'token_monitor', status: 'start' });
154
154
  } catch (error) {
155
155
  this.notify(`Failed to start token monitor: ${error.message}`, 'error');
156
+ this.auditLogger.record({
157
+ action: 'guard.token_monitor.start',
158
+ resource: 'token_monitor',
159
+ status: 'fail',
160
+ meta: { message: error.message }
161
+ });
162
+ recordMetric({ hook: 'token_monitor', status: 'fail' });
156
163
  }
157
164
  }
158
165
 
159
166
  _startGitFlowSync() {
160
167
  if (!this.monitors.gitFlow.autoSyncEnabled) return;
161
168
 
169
+ this.auditLogger.record({
170
+ action: 'guard.gitflow.autosync.enabled',
171
+ resource: 'gitflow',
172
+ status: 'success',
173
+ meta: { intervalMs: env.getNumber('HOOK_GUARD_GITFLOW_AUTOSYNC_INTERVAL', 300000) }
174
+ });
175
+ recordMetric({ hook: 'gitflow_autosync', status: 'enabled' });
176
+
162
177
  const syncInterval = setInterval(() => {
163
178
  if (this.monitors.gitFlow.isClean()) {
164
179
  const result = this.monitors.gitFlow.syncBranches();
165
180
  if (result.success) {
166
181
  this.notify('🔄 Branches synchronized', 'info');
182
+ recordMetric({ hook: 'gitflow_autosync', status: 'sync_success' });
167
183
  }
168
184
  }
169
- }, Number(process.env.HOOK_GUARD_GITFLOW_AUTOSYNC_INTERVAL || 300000));
185
+ }, env.getNumber('HOOK_GUARD_GITFLOW_AUTOSYNC_INTERVAL', 300000));
170
186
 
171
187
  syncInterval.unref();
172
188
  }
@@ -274,11 +290,18 @@ class RealtimeGuardService {
274
290
  this.lastStaleNotification = now;
275
291
  const ageSec = Math.floor(ageMs / 1000);
276
292
  this.notify(`Evidence has been stale for ${ageSec}s (source: ${source}).`, 'warn', { forceDialog: true });
293
+ this.auditLogger.record({
294
+ action: 'guard.evidence.stale',
295
+ resource: 'evidence',
296
+ status: 'warning',
297
+ meta: { ageSec, source }
298
+ });
299
+ recordMetric({ hook: 'evidence', status: 'stale', ageSec, source });
277
300
  void this.attemptAutoRefresh('stale');
278
301
  }
279
302
 
280
303
  async attemptAutoRefresh(reason = 'manual') {
281
- if (process.env.HOOK_GUARD_AUTO_REFRESH !== 'true') {
304
+ if (!env.getBool('HOOK_GUARD_AUTO_REFRESH', false)) {
282
305
  return;
283
306
  }
284
307
 
@@ -311,6 +334,13 @@ class RealtimeGuardService {
311
334
  try {
312
335
  await this.runDirectEvidenceRefresh(reason);
313
336
  this.lastAutoRefresh = now;
337
+ this.auditLogger.record({
338
+ action: 'guard.evidence.auto_refresh',
339
+ resource: 'evidence',
340
+ status: 'success',
341
+ meta: { reason }
342
+ });
343
+ recordMetric({ hook: 'evidence', status: 'auto_refresh_success', reason });
314
344
  } finally {
315
345
  this.autoRefreshInFlight = false;
316
346
  }
@@ -3,22 +3,12 @@ const FileContextGrouper = require('./smart-commit/FileContextGrouper');
3
3
  const CommitMessageSuggester = require('./smart-commit/CommitMessageSuggester');
4
4
  const SmartCommitSummaryBuilder = require('./smart-commit/SmartCommitSummaryBuilder');
5
5
 
6
- const {
7
- createMetricScope: createMetricScope
8
- } = require('../../../infrastructure/telemetry/metric-scope');
9
-
10
6
  class SmartDirtyTreeAnalyzer {
11
7
  constructor({
12
8
  platformDetector = null,
13
9
  repoRoot = process.cwd(),
14
10
  logger = console
15
11
  } = {}) {
16
- const m_constructor = createMetricScope({
17
- hook: 'smart_dirty_tree_analyzer',
18
- operation: 'constructor'
19
- });
20
-
21
- m_constructor.started();
22
12
  this.repoRoot = repoRoot;
23
13
  this.logger = logger;
24
14
 
@@ -26,7 +16,6 @@ class SmartDirtyTreeAnalyzer {
26
16
  this.grouper = new FileContextGrouper(this.featureDetector, platformDetector);
27
17
  this.suggester = new CommitMessageSuggester(this.featureDetector);
28
18
  this.summaryBuilder = new SmartCommitSummaryBuilder();
29
- m_constructor.success();
30
19
  }
31
20
 
32
21
  analyze(files) {
@@ -1,17 +1,6 @@
1
- const {
2
- createMetricScope: createMetricScope
3
- } = require('../../../infrastructure/telemetry/metric-scope');
4
-
5
1
  class CommitMessageGenerator {
6
2
  constructor(logger = console) {
7
- const m_constructor = createMetricScope({
8
- hook: 'commit_message_generator',
9
- operation: 'constructor'
10
- });
11
-
12
- m_constructor.started();
13
3
  this.logger = logger;
14
- m_constructor.success();
15
4
  }
16
5
 
17
6
  /**
@@ -1,17 +1,6 @@
1
- const {
2
- createMetricScope: createMetricScope
3
- } = require('../../../infrastructure/telemetry/metric-scope');
4
-
5
1
  class FeatureDetector {
6
2
  constructor(logger = console) {
7
- const m_constructor = createMetricScope({
8
- hook: 'feature_detector',
9
- operation: 'constructor'
10
- });
11
-
12
- m_constructor.started();
13
3
  this.logger = logger;
14
- m_constructor.success();
15
4
  }
16
5
 
17
6
  /**
@@ -3,10 +3,6 @@ const path = require('path');
3
3
  const { spawnSync } = require('child_process');
4
4
  const { DomainError } = require('../../../domain/errors');
5
5
 
6
- const {
7
- createMetricScope: createMetricScope
8
- } = require('../../../infrastructure/telemetry/metric-scope');
9
-
10
6
  const DEFAULT_PLATFORMS = ['1', '2', '3', '4'];
11
7
 
12
8
  function resolveUpdateEvidenceScript(repoRoot) {
@@ -37,12 +33,6 @@ class EvidenceContextManager {
37
33
  timers = { setInterval, clearInterval },
38
34
  runCommand = EvidenceContextManager.runUpdateScript
39
35
  } = {}) {
40
- const m_constructor = createMetricScope({
41
- hook: 'evidence_context_manager',
42
- operation: 'constructor'
43
- });
44
-
45
- m_constructor.started();
46
36
  this.repoRoot = repoRoot;
47
37
  this.updateScript = updateScript;
48
38
  this.thresholdSeconds = thresholdSeconds;
@@ -54,7 +44,6 @@ class EvidenceContextManager {
54
44
  this.runCommand = runCommand;
55
45
  this.timerRef = null;
56
46
  this.refreshInProgress = false;
57
- m_constructor.success();
58
47
  }
59
48
 
60
49
  static runUpdateScript(scriptPath, platforms) {
@@ -72,12 +61,6 @@ class EvidenceContextManager {
72
61
  }
73
62
 
74
63
  start(reason = 'startup') {
75
- const m_start = createMetricScope({
76
- hook: 'evidence_context_manager',
77
- operation: 'start'
78
- });
79
-
80
- m_start.started();
81
64
  this.ensureFresh(reason).catch(error => {
82
65
  this.log('error', 'EVIDENCE_STARTUP_REFRESH_FAILED', { error: error.message });
83
66
  });
@@ -91,21 +74,13 @@ class EvidenceContextManager {
91
74
  this.timerRef.unref();
92
75
  }
93
76
  }
94
- m_start.success();
95
77
  }
96
78
 
97
79
  stop() {
98
- const m_stop = createMetricScope({
99
- hook: 'evidence_context_manager',
100
- operation: 'stop'
101
- });
102
-
103
- m_stop.started();
104
80
  if (this.timerRef) {
105
81
  this.timers.clearInterval(this.timerRef);
106
82
  this.timerRef = null;
107
83
  }
108
- m_stop.success();
109
84
  }
110
85
 
111
86
  async ensureFresh(reason = 'manual') {
@@ -10,10 +10,9 @@ const GuardConfig = require('./GuardConfig');
10
10
  const GuardNotificationHandler = require('./GuardNotificationHandler');
11
11
  const GuardMonitorLoop = require('./GuardMonitorLoop');
12
12
  const GuardHealthReminder = require('./GuardHealthReminder');
13
-
14
- const {
15
- createMetricScope: createMetricScope
16
- } = require('../../../infrastructure/telemetry/metric-scope');
13
+ const AuditLogger = require('../logging/AuditLogger');
14
+ const envHelper = require('../../../config/env');
15
+ const { recordMetric } = require('../../../infrastructure/telemetry/metrics-logger');
17
16
 
18
17
  class GuardAutoManagerService {
19
18
  constructor({
@@ -23,16 +22,11 @@ class GuardAutoManagerService {
23
22
  fsModule = fs,
24
23
  childProcess = { spawnSync },
25
24
  timers = { setInterval, clearInterval },
26
- env = process.env,
25
+ env = envHelper,
27
26
  processRef = process,
28
- heartbeatMonitor = null
27
+ heartbeatMonitor = null,
28
+ auditLogger = null
29
29
  } = {}) {
30
- const m_constructor = createMetricScope({
31
- hook: 'guard_auto_manager_service',
32
- operation: 'constructor'
33
- });
34
-
35
- m_constructor.started();
36
30
  this.process = processRef;
37
31
 
38
32
  // Configuration & Infrastructure
@@ -40,6 +34,7 @@ class GuardAutoManagerService {
40
34
  this.eventLogger = new GuardEventLogger({ repoRoot, logger, fsModule });
41
35
  this.lockManager = new GuardLockManager({ repoRoot, logger, fsModule });
42
36
  this.processManager = new GuardProcessManager({ repoRoot, logger, fsModule, childProcess });
37
+ this.auditLogger = auditLogger || new AuditLogger({ repoRoot, logger });
43
38
 
44
39
  // Monitors & Handlers
45
40
  this.heartbeatMonitor = heartbeatMonitor || new GuardHeartbeatMonitor({
@@ -59,7 +54,6 @@ class GuardAutoManagerService {
59
54
  this.lastHeartbeatState = { healthy: true, reason: 'healthy' };
60
55
  this.lastHeartbeatRestart = 0;
61
56
  this.shuttingDown = false;
62
- m_constructor.success();
63
57
  }
64
58
 
65
59
  notifyUser(message, level = 'info', metadata = {}) {
@@ -68,25 +62,21 @@ class GuardAutoManagerService {
68
62
  }
69
63
 
70
64
  start() {
71
- const m_start = createMetricScope({
72
- hook: 'guard_auto_manager_service',
73
- operation: 'start'
74
- });
75
-
76
- m_start.started();
77
65
  if (!this.lockManager.acquireLock()) {
78
66
  this.eventLogger.log('Another guard auto manager instance detected. Exiting.');
79
- m_start.success();
67
+ this.auditLogger.record({ action: 'guard.lock.acquire', resource: 'guard_auto_manager', status: 'fail', meta: { reason: 'lock_exists' } });
68
+ recordMetric({ hook: 'guard_auto_manager', status: 'lock_fail' });
80
69
  return false;
81
70
  }
82
71
  this.lockManager.writePidFile();
83
72
  this.eventLogger.log('Guard auto manager started');
73
+ this.auditLogger.record({ action: 'guard.manager.start', resource: 'guard_auto_manager', status: 'success' });
74
+ recordMetric({ hook: 'guard_auto_manager', status: 'start' });
84
75
 
85
76
  this.ensureSupervisor('initial-start');
86
77
  this._startReminder();
87
78
  this.monitorLoop.start();
88
79
  this.registerProcessHooks();
89
- m_start.success();
90
80
  return true;
91
81
  }
92
82
 
@@ -113,6 +103,12 @@ class GuardAutoManagerService {
113
103
  handleMissingSupervisor() {
114
104
  this.lastHeartbeatState = { healthy: false, reason: 'missing-supervisor' };
115
105
  this.eventLogger.recordEvent('Guard supervisor no se encuentra en ejecución; reinicio automático.');
106
+ this.auditLogger.record({
107
+ action: 'guard.supervisor.missing',
108
+ resource: 'guard_supervisor',
109
+ status: 'fail',
110
+ meta: { reason: 'missing-supervisor' }
111
+ });
116
112
  this.ensureSupervisor('missing-supervisor');
117
113
  }
118
114
 
@@ -125,9 +121,21 @@ class GuardAutoManagerService {
125
121
  this.eventLogger.log(`Heartbeat degraded (${heartbeat.reason}); attempting supervisor ensure.`);
126
122
  this.lastHeartbeatRestart = now;
127
123
  this.ensureSupervisor(`heartbeat-${heartbeat.reason}`);
124
+ this.auditLogger.record({
125
+ action: 'guard.supervisor.ensure',
126
+ resource: 'guard_supervisor',
127
+ status: 'success',
128
+ meta: { reason: heartbeat.reason }
129
+ });
128
130
  } else {
129
131
  this.eventLogger.log(`Heartbeat degraded (${heartbeat.reason}); restart suppressed (cooldown).`);
130
132
  this.eventLogger.recordEvent(`Heartbeat degradado (${heartbeat.reason}); reinicio omitido por cooldown.`);
133
+ this.auditLogger.record({
134
+ action: 'guard.supervisor.ensure',
135
+ resource: 'guard_supervisor',
136
+ status: 'fail',
137
+ meta: { reason: heartbeat.reason, suppressed: true }
138
+ });
131
139
  }
132
140
  } else {
133
141
  this.eventLogger.recordEvent(`Heartbeat en estado ${heartbeat.reason}; reinicio no requerido.`);
@@ -167,6 +175,8 @@ class GuardAutoManagerService {
167
175
  this.lockManager.removePidFile();
168
176
  this.lockManager.releaseLock();
169
177
  this.healthReminder.stop();
178
+ this.auditLogger.record({ action: 'guard.manager.stop', resource: 'guard_auto_manager', status: 'success' });
179
+ recordMetric({ hook: 'guard_auto_manager', status: 'stop' });
170
180
  }
171
181
 
172
182
  ensureSupervisor(reason) {