@shubh000/macrc 0.0.0-stage → 0.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.
@@ -0,0 +1,395 @@
1
+ /**
2
+ * Shared heuristic scan engine, used by both the pipeline (02-static-scan.mjs)
3
+ * and the CLI (macrc audit / macrc gate).
4
+ *
5
+ * Exports: parseDeps, grepSources, scanConfigs, heuristicScore,
6
+ * computeHeuristicSummary, isNA, NA_BY_CATEGORY,
7
+ * PENDING_DIM, ABSENT_DIM, NA_DIM
8
+ */
9
+
10
+ import { readFileSync, existsSync } from 'fs';
11
+ import { resolve } from 'path';
12
+ import { execSync } from 'child_process';
13
+ import { grepSourcesVerified } from './ast-verifier.mjs';
14
+
15
+ export const PENDING_DIM = { state: 'pending', severity: null, notes: '', snippets: [] };
16
+ export const ABSENT_DIM = { state: 'absent', severity: null, notes: '', snippets: [] };
17
+ export const NA_DIM = { state: 'n_a', severity: null, notes: 'not applicable for this stack category', snippets: [] };
18
+
19
+ // ── N/A table ─────────────────────────────────────────────────────────────────
20
+ export const NA_BY_CATEGORY = {
21
+ 'plugin-extension': new Set(['circuit_breaking','health_checks','metrics_emission','tracing','alerting','statelessness','load_balancing_awareness','distributed_assumptions']),
22
+ 'skills-config': new Set(['circuit_breaking','health_checks','metrics_emission','tracing','alerting','statelessness','load_balancing_awareness','distributed_assumptions']),
23
+ 'desktop-native': new Set(['circuit_breaking','health_checks','metrics_emission','tracing','alerting','statelessness','load_balancing_awareness','distributed_assumptions']),
24
+ 'cli-tool': new Set(['circuit_breaking','health_checks','metrics_emission','tracing','alerting','statelessness','load_balancing_awareness']),
25
+ };
26
+
27
+ export function isNA(stackCategory, dim) {
28
+ return NA_BY_CATEGORY[stackCategory]?.has(dim) ?? false;
29
+ }
30
+
31
+ // ── Grep patterns ─────────────────────────────────────────────────────────────
32
+ export const GREP_PATTERNS = {
33
+ try_catch: /\btry\s*\{/g,
34
+ dot_catch: /\.catch\s*\(/g,
35
+ on_error: /\.on\s*\(\s*['"`]error['"`]/g,
36
+ express_error_mw: /\(\s*err\s*,\s*req\s*,\s*res\s*,\s*next\s*\)/g,
37
+ py_except: /\bexcept\s+\w/g,
38
+ go_err_nil: /\berr\s*!=\s*nil\b/g,
39
+ rust_result: /\bResult\s*<|\bOption\s*<|\bunwrap\(\)|\.expect\(/g,
40
+
41
+ retry_pattern: /\bretryCount\b|\bmaxRetries\b|\bretries\s*:\s*\d|\bexponential.*backoff/gi,
42
+
43
+ circuit_pattern: /\bCircuitBreaker\b|\bcircuit.*open\b|\bhalfOpen\b/gi,
44
+
45
+ fallback_pattern: /\bfallback\b|\bdegraded\b|\bisAvailable\b/gi,
46
+ feature_flag: /\bfeatureFlag\b|\bfeature_flag\b|\bisEnabled\s*\(/gi,
47
+
48
+ abort_controller: /\bAbortController\b|\bAbortSignal\.timeout\b/g,
49
+ timeout_config: /\btimeout\s*:\s*\d+/g,
50
+ py_timeout: /\btimeout\s*=\s*\d+/g,
51
+ go_timeout: /\bcontext\.WithTimeout\b|\bcontext\.WithDeadline\b/g,
52
+ rust_timeout: /\.timeout\s*\(\s*Duration/g,
53
+
54
+ console_log: /\bconsole\.(log|warn|error|debug|info)\s*\(/g,
55
+ logger_structured: /\blogger\.(info|warn|error|debug|fatal)\s*\(/g,
56
+ py_logging: /\blogging\.(info|warning|error|debug|critical)\s*\(|\blog\.(info|warning|error|debug)\s*\(/g,
57
+ rust_log: /\btracing::(info|warn|error|debug)!|\blog::(info|warn|error|debug)!/g,
58
+
59
+ counter_gauge: /\bnew\s+(Counter|Histogram|Gauge|Summary)\s*\(|register\.(metrics|registerMetric)\b|collectDefaultMetrics\s*\(/g,
60
+
61
+ otel_span: /\bstartSpan\s*\(|\btracer\.start\w*\s*\(|\btrace\.getTracer\s*\(/g,
62
+
63
+ alerting_pattern: /[Pp]ager[Dd]uty|[Oo]ps[Gg]enie/g,
64
+
65
+ health_route: /['"`]\/(health|healthz|ping|status)['"`]/g,
66
+
67
+ session_middleware: /\bapp\.use\s*\(\s*session\s*\(|\bsession_start\s*\(|flask\.session\b/g,
68
+ jwt_usage: /\bjwt\.sign\s*\(|\bjwt\.verify\s*\(|\bverifyToken\s*\(/g,
69
+
70
+ // skip test files for this key (enforced in grepSources)
71
+ localhost_hardcoded: /https?:\/\/localhost:\d+|https?:\/\/127\.0\.0\.1/g,
72
+ env_service_url: /process\.env\.\w+_(URL|HOST|ENDPOINT|BASE)|os\.environ\.get\s*\(\s*['"`]\w+_(URL|HOST|ENDPOINT)/g,
73
+
74
+ rate_limit_code: /\brateLimit\s*\(|\bRateLimiter\b|\brate_limit\b|\blimiter\.(middleware|handle)\b/g,
75
+
76
+ cache_ops: /\bcache\.(get|set|del|mget|mset)\s*\(|\bclient\.(get|set|hget|hset)\s*\(/g,
77
+ lru_cache_py: /@lru_cache\b|@cache\b|\bfunctools\.(lru_cache|cache)\b/g,
78
+ cache_control: /Cache-Control|max-age=|s-maxage=/g,
79
+
80
+ bearer_auth: /\bBearer\s+\S|\bAuthorization.*Bearer/gi,
81
+ verify_token: /\bverifyToken\b|\brequireAuth\b|\bisAuthenticated\b|\b@login_required\b|\bDepends\s*\(\s*get_current_user/g,
82
+
83
+ zod_usage: /\bz\.(string|number|object|array|boolean|enum)\s*\(|\b\.parse\s*\(|\b\.safeParse\s*\(/g,
84
+ joi_usage: /\bJoi\.(object|string|number|array)\s*\(|\b\.validate\s*\({/g,
85
+ pydantic_usage: /\bBaseModel\b|\b@validator\b|\b@model_validator\b/g,
86
+ class_validator: /\b@IsString\b|\b@IsNumber\b|\b@IsEmail\b|\b@IsNotEmpty\b/g,
87
+
88
+ tls_code: /\bhttps\.createServer\b|\btls\.createServer\b|force_https|redirect_to_https/gi,
89
+ };
90
+
91
+ const SOURCE_EXTS_RE = /\.(js|ts|jsx|tsx|mjs|cjs|py|go|rs|rb|java|cs|php)$/;
92
+ const TEST_PATH_RE = /\.(test|spec)\.|__tests__|\/tests?\/|test_[\w]+\.py$|_test\.go$/;
93
+
94
+ // ── Signal extractors ─────────────────────────────────────────────────────────
95
+
96
+ export function parseDeps(cloneDir) {
97
+ const deps = new Set();
98
+
99
+ try {
100
+ const pkg = JSON.parse(readFileSync(resolve(cloneDir, 'package.json'), 'utf8'));
101
+ for (const d of Object.keys({ ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) })) {
102
+ deps.add(d.toLowerCase());
103
+ }
104
+ } catch {}
105
+
106
+ try {
107
+ readFileSync(resolve(cloneDir, 'requirements.txt'), 'utf8').split('\n').forEach(l => {
108
+ const n = l.trim().split(/[>=<\[!\s#;]/)[0].trim().toLowerCase();
109
+ if (n && !n.startsWith('#') && n.length > 0) {
110
+ deps.add(n);
111
+ deps.add(n.replace(/-/g, '_'));
112
+ }
113
+ });
114
+ } catch {}
115
+
116
+ try {
117
+ readFileSync(resolve(cloneDir, 'pyproject.toml'), 'utf8').split('\n').forEach(l => {
118
+ const m = l.match(/^\s*["']?([\w-]+)["']?\s*[>=]/);
119
+ if (m) { deps.add(m[1].toLowerCase()); deps.add(m[1].toLowerCase().replace(/-/g, '_')); }
120
+ });
121
+ } catch {}
122
+
123
+ try {
124
+ readFileSync(resolve(cloneDir, 'Cargo.toml'), 'utf8').split('\n').forEach(l => {
125
+ const m = l.match(/^([\w-]+)\s*=/);
126
+ if (m) deps.add(m[1].toLowerCase());
127
+ });
128
+ } catch {}
129
+
130
+ try {
131
+ readFileSync(resolve(cloneDir, 'go.mod'), 'utf8').split('\n').forEach(l => {
132
+ const m = l.match(/^\t([\S]+)\s+v\d/);
133
+ if (m) deps.add(m[1].toLowerCase());
134
+ });
135
+ } catch {}
136
+
137
+ return deps;
138
+ }
139
+
140
+ export function grepSources(cloneDir) {
141
+ const H = {};
142
+ let files = [];
143
+ try {
144
+ files = execSync('git ls-files', { cwd: cloneDir, timeout: 10000 })
145
+ .toString().split('\n').filter(f => f && SOURCE_EXTS_RE.test(f));
146
+ } catch { return H; }
147
+
148
+ for (const relPath of files.slice(0, 400)) {
149
+ const isTest = TEST_PATH_RE.test(relPath);
150
+ let content = '';
151
+ try { content = readFileSync(resolve(cloneDir, relPath), 'utf8').replace(/\0/g, ''); } catch { continue; }
152
+
153
+ for (const [key, pattern] of Object.entries(GREP_PATTERNS)) {
154
+ if (key === 'localhost_hardcoded' && isTest) continue;
155
+ const matches = content.match(pattern);
156
+ if (matches) H[key] = (H[key] || 0) + matches.length;
157
+ }
158
+ }
159
+ return H;
160
+ }
161
+
162
+ export function scanConfigs(cloneDir) {
163
+ function read(filename) {
164
+ const p = resolve(cloneDir, filename);
165
+ return existsSync(p) ? { exists: true, content: readFileSync(p, 'utf8') } : { exists: false, content: '' };
166
+ }
167
+ const cfg = {
168
+ dockerfile: read('Dockerfile'),
169
+ dockerCompose: read('docker-compose.yml'),
170
+ dockerComposeYaml: read('docker-compose.yaml'),
171
+ flyToml: read('fly.toml'),
172
+ nginxConf: read('nginx.conf'),
173
+ caddyfile: read('Caddyfile'),
174
+ netlifyToml: read('netlify.toml'),
175
+ vercelJson: read('vercel.json'),
176
+ k8sDeployment: read('deployment.yaml'),
177
+ alertsYml: read('alerts.yml'),
178
+ alertmanagerYml: read('alertmanager.yml'),
179
+ alertRulesYml: read('alert_rules.yml'),
180
+ };
181
+ const composeContent = cfg.dockerCompose.content + cfg.dockerComposeYaml.content;
182
+ cfg.hasHealthcheck = cfg.dockerfile.exists && /^HEALTHCHECK\s/m.test(cfg.dockerfile.content);
183
+ cfg.hasDockerHealth = /^\s+healthcheck\s*:/m.test(composeContent);
184
+ cfg.hasK8sHealthcheck = /livenessProbe|readinessProbe/.test(cfg.k8sDeployment.content);
185
+ cfg.hasReplicas = /\breplicas\s*:\s*[2-9]\d*/.test(composeContent + cfg.k8sDeployment.content);
186
+ cfg.hasNginxUpstream = /\bupstream\s+\w+\s*\{/.test(cfg.nginxConf.content);
187
+ cfg.hasNginxRateLimit = /limit_req/.test(cfg.nginxConf.content);
188
+ cfg.hasTlsConfig = cfg.flyToml.exists || cfg.vercelJson.exists || cfg.netlifyToml.exists || cfg.caddyfile.exists;
189
+ cfg.hasAlertConfig = cfg.alertsYml.exists || cfg.alertmanagerYml.exists || cfg.alertRulesYml.exists;
190
+ return cfg;
191
+ }
192
+
193
+ // ── Heuristic dimension scorer ────────────────────────────────────────────────
194
+
195
+ export function heuristicScore(deps, hits, configs, stackCategory) {
196
+ function h(state, severity, notes) {
197
+ return { state, severity: state === 'present' ? null : severity, notes, snippets: [] };
198
+ }
199
+ function naOr(dimName, fn) {
200
+ return isNA(stackCategory, dimName) ? { ...NA_DIM } : fn();
201
+ }
202
+ function hasDep(...names) { return names.some(n => deps.has(n.toLowerCase())); }
203
+
204
+ // ── Security enhancement signals ─────────────────────────────────────────
205
+ const secEnhancement = {};
206
+
207
+ const authPkgs = ['passport','jsonwebtoken','next-auth','@clerk/clerk-sdk-node','@supabase/auth-helpers-nextjs','express-jwt','flask_login','flask-jwt-extended','fastapi-users','django.contrib.auth'];
208
+ const authHits = (hits.bearer_auth || 0) + (hits.verify_token || 0);
209
+ if (hasDep(...authPkgs) && authHits > 0) {
210
+ secEnhancement.auth = h('present', null, 'Auth library in deps with token verification patterns');
211
+ } else if (hasDep(...authPkgs) || authHits > 1) {
212
+ secEnhancement.auth = h('partial', 'high', 'Auth signals found but incomplete implementation');
213
+ }
214
+
215
+ const valPkgs = ['zod','joi','yup','express-validator','class-validator','ajv','marshmallow','pydantic','cerberus','voluptuous','wtforms'];
216
+ const valHits = (hits.zod_usage || 0) + (hits.joi_usage || 0) + (hits.pydantic_usage || 0) + (hits.class_validator || 0);
217
+ if (hasDep(...valPkgs) && valHits > 0) {
218
+ secEnhancement.input_validation = h('present', null, 'Validation library in deps with active usage found');
219
+ } else if (hasDep(...valPkgs) || valHits > 0) {
220
+ secEnhancement.input_validation = h('partial', 'high', 'Validation signals found but incomplete coverage');
221
+ }
222
+
223
+ if ((hits.tls_code || 0) > 0) {
224
+ secEnhancement.transport_security = h('present', null, 'TLS server or force-HTTPS code found');
225
+ } else if (configs.hasTlsConfig) {
226
+ secEnhancement.transport_security = h('partial', null, 'Platform TLS config found (fly.toml/vercel.json/netlify.toml)');
227
+ }
228
+
229
+ // ── Reliability ───────────────────────────────────────────────────────────
230
+ const totalErrHits = (hits.try_catch || 0) + (hits.dot_catch || 0) + (hits.on_error || 0) +
231
+ (hits.py_except || 0) + (hits.go_err_nil || 0) + (hits.rust_result || 0);
232
+ const hasGlobalHandler = (hits.express_error_mw || 0) > 0;
233
+ const retryPkgs = ['axios-retry','p-retry','retry','@lifeomic/attempt','cockatiel','tenacity','backoff','stamina','retrying'];
234
+ const cbPkgs = ['opossum','brakes','pycircuitbreaker','circuitbreaker','gobreaker'];
235
+ const timeoutHits = (hits.abort_controller || 0) + (hits.timeout_config || 0) + (hits.py_timeout || 0) +
236
+ (hits.go_timeout || 0) + (hits.rust_timeout || 0);
237
+
238
+ const reliability = {
239
+ error_handling: (() => {
240
+ if (totalErrHits >= 5 && hasGlobalHandler) return h('present', null, `${totalErrHits} error handling instances with global handler`);
241
+ if (totalErrHits >= 2) return h('partial', 'high', `${totalErrHits} error handling instances but no global handler`);
242
+ return h('absent', 'critical', 'No error handling patterns found');
243
+ })(),
244
+ retry_logic: (() => {
245
+ if (hasDep(...retryPkgs)) return h('present', null, 'Retry library in dependencies');
246
+ if ((hits.retry_pattern || 0) > 0) return h('partial', 'high', 'Manual retry pattern in code, no retry library');
247
+ return h('absent', 'high', 'No retry logic found');
248
+ })(),
249
+ circuit_breaking: naOr('circuit_breaking', () => {
250
+ if (hasDep(...cbPkgs)) return h('present', null, 'Circuit breaker library in dependencies');
251
+ if ((hits.circuit_pattern || 0) > 0) return h('partial', 'high', 'Circuit breaker pattern in code, no library');
252
+ return h('absent', 'high', 'No circuit breaker found');
253
+ }),
254
+ graceful_degradation: (() => {
255
+ const signals = (hits.fallback_pattern || 0) + (hits.feature_flag || 0);
256
+ if (signals >= 2) return h('partial', 'medium', `${signals} fallback/feature-flag patterns found`);
257
+ return h('absent', 'medium', 'No graceful degradation patterns found');
258
+ })(),
259
+ timeout_handling: (() => {
260
+ if (timeoutHits >= 2) return h('present', null, `Timeout patterns on ${timeoutHits} call sites`);
261
+ if (timeoutHits === 1) return h('partial', 'high', 'Timeout found in 1 place, not systematic');
262
+ return h('absent', 'high', 'No timeout handling found');
263
+ })(),
264
+ };
265
+
266
+ // ── Observability ─────────────────────────────────────────────────────────
267
+ const logStructPkgs = ['winston','pino','bunyan','morgan','log4js','tslog','structlog','loguru','logrus','zap','slog'];
268
+ const metricsPkgs = ['prom-client','dd-trace','newrelic','hot-shots','prometheus_client','statsd','@opentelemetry/sdk-node','datadog-lambda'];
269
+ const tracingPkgs = ['@opentelemetry/api','@opentelemetry/sdk-node','dd-trace','jaeger-client','zipkin','opentelemetry_api','opentelemetry_sdk','opentelemetry-api','opentelemetry-sdk'];
270
+ const alertingPkgs = ['@pagerduty/pdjs','node-pagerduty','pdpyras','opsgenie-sdk'];
271
+ const structuredLogHits = (hits.logger_structured || 0) + (hits.py_logging || 0) + (hits.rust_log || 0);
272
+
273
+ const observability = {
274
+ logging: (() => {
275
+ if ((hasDep(...logStructPkgs) || structuredLogHits > 0) && structuredLogHits > 0) return h('present', null, 'Structured logging library/logger in use');
276
+ if (hasDep(...logStructPkgs)) return h('partial', null, 'Structured logging library in deps, usage not confirmed');
277
+ if ((hits.console_log || 0) > 0) return h('partial', 'high', `Only console.log statements (${hits.console_log} instances)`);
278
+ return h('absent', 'high', 'No logging found');
279
+ })(),
280
+ metrics_emission: naOr('metrics_emission', () => {
281
+ if (hasDep(...metricsPkgs) && (hits.counter_gauge || 0) > 0) return h('present', null, 'Metrics library with metric definitions found');
282
+ if (hasDep(...metricsPkgs)) return h('partial', 'medium', 'Metrics library in deps but no metric definitions found');
283
+ return h('absent', 'medium', 'No metrics emission found');
284
+ }),
285
+ tracing: naOr('tracing', () => {
286
+ if (hasDep(...tracingPkgs) && (hits.otel_span || 0) > 0) return h('present', null, 'Tracing library with span creation found');
287
+ if (hasDep(...tracingPkgs)) return h('partial', 'medium', 'Tracing library in deps but no spans found');
288
+ return h('absent', 'medium', 'No distributed tracing found');
289
+ }),
290
+ alerting: naOr('alerting', () => {
291
+ if (hasDep(...alertingPkgs)) return h('present', null, 'Alerting library in dependencies');
292
+ if (configs.hasAlertConfig) return h('partial', 'medium', 'Alert config file found');
293
+ if ((hits.alerting_pattern || 0) > 0) return h('partial', 'medium', 'PagerDuty/OpsGenie pattern in code');
294
+ return h('absent', 'medium', 'No alerting found');
295
+ }),
296
+ health_checks: naOr('health_checks', () => {
297
+ const hasEndpoint = (hits.health_route || 0) > 0;
298
+ const hasConfig = configs.hasHealthcheck || configs.hasDockerHealth || configs.hasK8sHealthcheck;
299
+ if (hasEndpoint || hasConfig) return h('present', null, 'Health endpoint or health check config found');
300
+ return h('absent', 'medium', 'No health check endpoint or config found');
301
+ }),
302
+ };
303
+
304
+ // ── Scale Contract ────────────────────────────────────────────────────────
305
+ const rlPkgs = ['express-rate-limit','rate-limiter-flexible','bottleneck','slow-down','limiter','slowapi','flask-limiter','limits','aiohttp-ratelimit','throttle'];
306
+ const redisPkgs = ['ioredis','redis','memcached','aiocache','diskcache','go-cache','ristretto'];
307
+ const inMemPkgs = ['lru-cache','node-cache','cache-manager','cachetools'];
308
+ const cacheHits = (hits.cache_ops || 0) + (hits.lru_cache_py || 0) + (hits.cache_control || 0);
309
+
310
+ const scale_contract = {
311
+ statelessness: naOr('statelessness', () => {
312
+ const hasSessionPkg = hasDep('express-session', 'cookie-session');
313
+ const hasSessionCode = (hits.session_middleware || 0) > 0;
314
+ const hasRedis = hasDep('connect-redis', 'ioredis', 'redis');
315
+ const hasJwt = hasDep('jsonwebtoken') || (hits.jwt_usage || 0) > 0;
316
+ if ((hasSessionPkg || hasSessionCode) && hasRedis) return h('partial', 'high', 'Session middleware with external Redis store (mitigated)');
317
+ if (hasSessionPkg || hasSessionCode) return h('absent', 'high', 'Session middleware with in-process store, stateful');
318
+ if (hasJwt) return h('present', null, 'JWT auth, no session middleware, stateless');
319
+ return h('present', null, 'No session middleware found, assumed stateless');
320
+ }),
321
+ load_balancing_awareness: naOr('load_balancing_awareness', () => {
322
+ const hasHealthEndpoint = (hits.health_route || 0) > 0 || configs.hasHealthcheck;
323
+ if ((configs.hasReplicas || configs.hasNginxUpstream) && hasHealthEndpoint) return h('present', null, 'Multi-replica config and health endpoint found');
324
+ if (hasHealthEndpoint) return h('partial', 'medium', 'Health endpoint present but no multi-replica deployment config');
325
+ return h('absent', 'medium', 'No load balancer awareness found');
326
+ }),
327
+ distributed_assumptions: naOr('distributed_assumptions', () => {
328
+ const hardcoded = (hits.localhost_hardcoded || 0);
329
+ const envUrls = (hits.env_service_url || 0);
330
+ if (hardcoded === 0 && envUrls > 0) return h('present', null, 'Service URLs via env vars, no hardcoded localhost');
331
+ if (hardcoded > 0 && envUrls > 0) return h('partial', 'high', `Mix of env vars and ${hardcoded} hardcoded localhost URL(s)`);
332
+ if (hardcoded > 0) return h('absent', 'high', `${hardcoded} hardcoded localhost service URL(s) in production code`);
333
+ return h('present', null, 'No hardcoded service URLs detected');
334
+ }),
335
+ rate_limiting: (() => {
336
+ if (hasDep(...rlPkgs) && (hits.rate_limit_code || 0) > 0) return h('present', null, 'Rate limiting library applied to routes');
337
+ if (configs.hasNginxRateLimit) return h('present', null, 'Nginx rate limiting configured');
338
+ if (hasDep(...rlPkgs)) return h('partial', 'high', 'Rate limiting library in deps but not wired to routes');
339
+ if ((hits.rate_limit_code || 0) > 0) return h('partial', 'high', 'Rate limiting pattern in code, no library');
340
+ return h('absent', 'high', 'No rate limiting found');
341
+ })(),
342
+ caching_strategy: (() => {
343
+ if (hasDep(...redisPkgs) && (hits.cache_ops || 0) > 0) return h('present', null, 'Distributed cache (Redis/Memcached) with cache operations found');
344
+ if (hasDep(...inMemPkgs) || (hits.lru_cache_py || 0) > 0) return h('partial', 'low', 'In-memory/LRU cache only (single-node)');
345
+ if (cacheHits > 0) return h('partial', 'low', 'Cache operations or HTTP cache headers found');
346
+ return h('absent', 'low', 'No caching strategy found');
347
+ })(),
348
+ };
349
+
350
+ return { secEnhancement, reliability, observability, scale_contract };
351
+ }
352
+
353
+ export function computeHeuristicSummary(layers) {
354
+ let absent = 0, partial = 0, present = 0, na_count = 0;
355
+ const absentByLayer = { security: 0, reliability: 0, observability: 0, scale_contract: 0 };
356
+ let hasCritical = false;
357
+
358
+ for (const [layer, dims] of Object.entries(layers)) {
359
+ for (const dim of Object.values(dims)) {
360
+ if (dim.state === 'n_a') { na_count++; continue; }
361
+ if (dim.state === 'absent') { absent++; absentByLayer[layer]++; }
362
+ else if (dim.state === 'partial') { partial++; }
363
+ else if (dim.state === 'present') { present++; }
364
+ if (dim.severity === 'critical') { hasCritical = true; }
365
+ }
366
+ }
367
+
368
+ const applicable = absent + partial + present;
369
+ return {
370
+ total_dimensions: 20,
371
+ applicable_dimensions: applicable,
372
+ na_count,
373
+ absent_count: absent,
374
+ partial_count: partial,
375
+ present_count: present,
376
+ absent_by_layer: absentByLayer,
377
+ has_critical_severity: hasCritical,
378
+ };
379
+ }
380
+
381
+ /**
382
+ * Run the full heuristic scan on a local directory and return structured results.
383
+ * stackCategory: one of ai-web-app, api-proxy, mcp-server, agent-framework,
384
+ * cli-tool, desktop-native, plugin-extension, skills-config, or ''
385
+ */
386
+ export function runHeuristic(cloneDir, stackCategory = '', { verified = true } = {}) {
387
+ const deps = parseDeps(cloneDir);
388
+ // verified=true uses context-window analysis for HIGH-FP patterns,
389
+ // reducing false positives on import-only checks (zod/pydantic/bearer_auth etc.)
390
+ const hits = verified
391
+ ? grepSourcesVerified(cloneDir, GREP_PATTERNS)
392
+ : grepSources(cloneDir);
393
+ const configs = scanConfigs(cloneDir);
394
+ return heuristicScore(deps, hits, configs, stackCategory);
395
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Output formatters: JSON, table, SARIF.
3
+ *
4
+ * Exports: formatJson, formatTable, formatSarif
5
+ */
6
+
7
+ const STATE_ICON = { present: '✓', partial: '~', absent: '✗', n_a: '—', pending: '?' };
8
+ const SEV_COLOR = { critical: '\x1b[31m', high: '\x1b[33m', medium: '\x1b[36m', low: '\x1b[2m', null: '' };
9
+ const RESET = '\x1b[0m';
10
+
11
+ export function formatJson(audit, { pretty = true } = {}) {
12
+ return JSON.stringify(audit, null, pretty ? 2 : 0);
13
+ }
14
+
15
+ export function formatTable(audit, { color = true } = {}) {
16
+ const lines = [];
17
+ const repo = audit.repo_id || '(unknown)';
18
+ const mode = audit.auditor || '?';
19
+ const date = audit.audited_at || '';
20
+
21
+ lines.push(`\nMARC Audit: ${repo} [${mode}] ${date}`);
22
+ lines.push('─'.repeat(70));
23
+
24
+ const LAYER_LABEL = { security: 'Security', reliability: 'Reliability', observability: 'Observability', scale_contract: 'Scale Contract' };
25
+ const DIM_ORDER = {
26
+ security: ['auth','input_validation','transport_security','dependency_hygiene','secrets_management'],
27
+ reliability: ['error_handling','retry_logic','circuit_breaking','graceful_degradation','timeout_handling'],
28
+ observability: ['logging','metrics_emission','tracing','alerting','health_checks'],
29
+ scale_contract: ['statelessness','load_balancing_awareness','distributed_assumptions','rate_limiting','caching_strategy'],
30
+ };
31
+
32
+ for (const [layer, dims] of Object.entries(DIM_ORDER)) {
33
+ lines.push(`\n${LAYER_LABEL[layer]}`);
34
+ for (const dim of dims) {
35
+ const d = audit.layers?.[layer]?.[dim];
36
+ if (!d) continue;
37
+ const icon = STATE_ICON[d.state] || '?';
38
+ const sev = d.severity ? ` [${d.severity}]` : '';
39
+ const note = d.notes ? ` ${d.notes}` : '';
40
+ const c = color ? (SEV_COLOR[d.severity] || '') : '';
41
+ const r = color ? RESET : '';
42
+ lines.push(` ${c}${icon} ${dim.padEnd(28)}${sev.padEnd(10)}${note}${r}`);
43
+ }
44
+ }
45
+
46
+ const s = audit.summary;
47
+ if (s) {
48
+ lines.push('\n' + '─'.repeat(70));
49
+ lines.push(` ${s.present_count} present ${s.partial_count} partial ${s.absent_count} absent ${s.na_count} n/a (${s.applicable_dimensions} applicable)`);
50
+ if (s.has_critical_severity) lines.push(` ⚠ Critical severity dimension(s) present`);
51
+ }
52
+
53
+ return lines.join('\n');
54
+ }
55
+
56
+ export function formatSarif(audit) {
57
+ const runs = [{
58
+ tool: {
59
+ driver: {
60
+ name: 'macrc',
61
+ version: '0.1.0',
62
+ rules: [],
63
+ },
64
+ },
65
+ results: [],
66
+ }];
67
+
68
+ const DIM_ORDER = {
69
+ security: ['auth','input_validation','transport_security','dependency_hygiene','secrets_management'],
70
+ reliability: ['error_handling','retry_logic','circuit_breaking','graceful_degradation','timeout_handling'],
71
+ observability: ['logging','metrics_emission','tracing','alerting','health_checks'],
72
+ scale_contract: ['statelessness','load_balancing_awareness','distributed_assumptions','rate_limiting','caching_strategy'],
73
+ };
74
+
75
+ const SEV_SARIF = { critical: 'error', high: 'error', medium: 'warning', low: 'note', null: 'note' };
76
+
77
+ for (const [layer, dims] of Object.entries(DIM_ORDER)) {
78
+ for (const dim of dims) {
79
+ const d = audit.layers?.[layer]?.[dim];
80
+ if (!d || d.state === 'present' || d.state === 'n_a' || d.state === 'pending') continue;
81
+
82
+ const ruleId = `macrc/${layer}/${dim}`;
83
+ runs[0].tool.driver.rules.push({
84
+ id: ruleId,
85
+ name: `${layer}.${dim}`,
86
+ shortDescription: { text: `${layer} / ${dim}` },
87
+ defaultConfiguration: { level: SEV_SARIF[d.severity] || 'warning' },
88
+ });
89
+
90
+ runs[0].results.push({
91
+ ruleId,
92
+ level: SEV_SARIF[d.severity] || 'warning',
93
+ message: { text: d.notes || `${dim} is ${d.state}` },
94
+ locations: [{
95
+ physicalLocation: {
96
+ artifactLocation: { uri: audit.repo_id || '.' },
97
+ },
98
+ }],
99
+ properties: { state: d.state, macrc_layer: layer },
100
+ });
101
+ }
102
+ }
103
+
104
+ return JSON.stringify({
105
+ version: '2.1.0',
106
+ $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/Documents/CommitteeSpecifications/2.1.0/sarif-schema-2.1.0.json',
107
+ runs,
108
+ }, null, 2);
109
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Policy engine: loads .macrc.yml and applies block/warn/pass rules per dim.
3
+ *
4
+ * Exports: loadPolicy(dir), applyPolicy(policy, auditResult) → PolicyResult
5
+ */
6
+
7
+ import { readFileSync, existsSync } from 'fs';
8
+ import { resolve } from 'path';
9
+
10
+ const DEFAULT_POLICY = {
11
+ version: 1,
12
+ dims: {},
13
+ defaults: {
14
+ absent: 'warn',
15
+ partial: 'pass',
16
+ present: 'pass',
17
+ n_a: 'pass',
18
+ },
19
+ };
20
+
21
+ function parseSimpleYaml(text) {
22
+ const result = { dims: {}, defaults: {} };
23
+ let currentSection = null;
24
+
25
+ for (const rawLine of text.split('\n')) {
26
+ const line = rawLine.replace(/#.*$/, '').trimEnd();
27
+ if (!line.trim()) continue;
28
+
29
+ if (/^version\s*:/.test(line)) {
30
+ result.version = parseInt(line.split(':')[1].trim(), 10);
31
+ continue;
32
+ }
33
+
34
+ if (/^dims\s*:/.test(line)) { currentSection = 'dims'; continue; }
35
+ if (/^defaults\s*:/.test(line)) { currentSection = 'defaults'; continue; }
36
+
37
+ const m = line.match(/^ ([\w.]+)\s*:\s*(.+)$/);
38
+ if (!m) continue;
39
+ const [, key, val] = m;
40
+ if (currentSection === 'dims') result.dims[key] = val.trim();
41
+ if (currentSection === 'defaults') result.defaults[key] = val.trim();
42
+ }
43
+ return result;
44
+ }
45
+
46
+ export function loadPolicy(dir) {
47
+ const candidates = ['.macrc.yml', '.macrc.yaml', 'macrc.yml', 'macrc.yaml'];
48
+ for (const name of candidates) {
49
+ const p = resolve(dir, name);
50
+ if (existsSync(p)) {
51
+ try {
52
+ const raw = readFileSync(p, 'utf8');
53
+ const parsed = parseSimpleYaml(raw);
54
+ return { ...DEFAULT_POLICY, ...parsed, dims: { ...DEFAULT_POLICY.dims, ...parsed.dims }, defaults: { ...DEFAULT_POLICY.defaults, ...parsed.defaults }, _hasFile: true };
55
+ } catch (err) {
56
+ console.warn(`[policy] failed to parse ${p}: ${err.message}`);
57
+ }
58
+ }
59
+ }
60
+ return { ...DEFAULT_POLICY, _hasFile: false };
61
+ }
62
+
63
+ export function applyPolicy(policy, auditLayers) {
64
+ const results = [];
65
+ let blocked = false;
66
+ let warnCount = 0;
67
+
68
+ const ALL_DIMS = {
69
+ security: ['auth','input_validation','transport_security','dependency_hygiene','secrets_management'],
70
+ reliability: ['error_handling','retry_logic','circuit_breaking','graceful_degradation','timeout_handling'],
71
+ observability: ['logging','metrics_emission','tracing','alerting','health_checks'],
72
+ scale_contract: ['statelessness','load_balancing_awareness','distributed_assumptions','rate_limiting','caching_strategy'],
73
+ };
74
+
75
+ for (const [layer, dims] of Object.entries(ALL_DIMS)) {
76
+ for (const dim of dims) {
77
+ const result = auditLayers[layer]?.[dim];
78
+ if (!result) continue;
79
+
80
+ const { state, severity, notes } = result;
81
+
82
+ const policyKey = `${layer}.${dim}`;
83
+ let action = policy.dims[policyKey] || policy.dims[dim] || policy.defaults[state] || 'pass';
84
+
85
+ if (action === 'block') { blocked = true; }
86
+ if (action === 'warn') { warnCount++; }
87
+
88
+ results.push({ layer, dim, state, severity, notes, action });
89
+ }
90
+ }
91
+
92
+ return { results, blocked, warnCount, passed: !blocked };
93
+ }
94
+
95
+ export function formatPolicyReport(policyResult) {
96
+ const lines = [];
97
+ for (const r of policyResult.results) {
98
+ if (r.action === 'pass') continue;
99
+ const icon = r.action === 'block' ? '✗' : '⚠';
100
+ lines.push(` ${icon} ${r.layer}.${r.dim} [${r.state}] ${r.notes}`);
101
+ }
102
+ if (lines.length === 0) lines.push(' ✓ all dimensions pass policy');
103
+ return lines.join('\n');
104
+ }