@interlace/eslint-devkit 1.3.3 β†’ 1.4.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,107 @@
1
+ ## [1.4.0] - 2026-05-03
2
+
3
+ ### Changed
4
+
5
+ - Module resolver swapped from `enhanced-resolve` + `get-tsconfig` to [`oxc-resolver`](https://www.npmjs.com/package/oxc-resolver) (Rust NAPI, ~18-30Γ— faster). Per-tsconfig caching for monorepo path-alias correctness across package boundaries.
6
+ - `peerDependenciesMeta` no longer lists `enhanced-resolve` and `get-tsconfig` (consumers don't need to peer-provide them; this is **technically breaking** but no consumer impact is expected).
7
+
8
+ ### Added
9
+
10
+ - `oxc-resolver` is now a hard `dependencies` entry. Note for adopters: NAPI prebuilds cover common targets (Linux x64/arm64 glibc + musl, macOS x64/arm64, Windows x64); rare targets may need to fall back to a build step.
11
+
12
+ ## [1.3.3] - 2026-02-08
13
+
14
+ This was a version bump only for eslint-devkit to align it with other projects, there were no code changes.
15
+
16
+ ## [1.3.2] - 2026-02-06
17
+
18
+ This was a version bump only for eslint-devkit to align it with other projects, there were no code changes.
19
+
20
+ # Changelog
21
+
22
+ All notable changes to `@interlace/eslint-devkit` are documented here.
23
+
24
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and [SemVer](https://semver.org/spec/v2.0.0.html).
25
+
26
+ ## [1.0.0] - 2025-11-30
27
+
28
+ ### πŸš€ Features
29
+
30
+ - Enhanced LLM message formatting utilities.
31
+ - Improved TypeScript typings for IDE support.
32
+
33
+ ### 🩹 Fixes
34
+
35
+ - Compatibility fixes for TS strict mode.
36
+ - More accurate type guards for AST checking.
37
+
38
+ ### πŸ“Œ Notes
39
+
40
+ - Package name aligned to `@interlace/eslint-devkit` (formerly eslint-plugin-utils).
41
+
42
+ ### ❀️ Thank You
43
+
44
+ - Ofri Peretz
45
+
46
+ ---
47
+
48
+ ## [0.3.0] - 2025-11-15
49
+
50
+ ### πŸš€ Features
51
+
52
+ - Enhanced type utilities.
53
+ - Improved AST helpers.
54
+ - Better LLM-oriented error messaging.
55
+
56
+ ### 🩹 Fixes
57
+
58
+ - Type checking edge cases.
59
+ - Documentation improvements.
60
+
61
+ ### ❀️ Thank You
62
+
63
+ - Ofri Peretz
64
+
65
+ ---
66
+
67
+ ## [0.2.2] - 2025-11-07
68
+
69
+ ### 🩹 Fixes
70
+
71
+ - Config fixes; removed codecov vite plugin.
72
+ - Adjusted ignore patterns in dependency checks.
73
+ - Added vitest to peerDependencies.
74
+
75
+ ### ❀️ Thank You
76
+
77
+ - Ofri Peretz
78
+
79
+ ---
80
+
81
+ ## [0.2.1] - 2025-11-07
82
+
83
+ ### 🩹 Fixes
84
+
85
+ - Config and dependency-check adjustments.
86
+
87
+ ### ❀️ Thank You
88
+
89
+ - Ofri Peretz
90
+
91
+ ---
92
+
93
+ ## [0.2.0] - 2025-11-02
94
+
95
+ Version bump to align packages; no code changes.
96
+
97
+ ---
98
+
99
+ ## [0.1.1] - 2025-11-02
100
+
101
+ Version bump to align packages; no code changes.
102
+
103
+ ---
104
+
105
+ ## [0.1.0] - 2025-11-02
106
+
107
+ Initial prerelease for the devkit utilities.
package/README.md CHANGED
@@ -494,19 +494,21 @@ const rule = createRule<[], 'messageId'>({
494
494
 
495
495
  ## Compatibility
496
496
 
497
- | Package | Version |
498
- | ------------------------- | ------------------ |
499
- | ESLint | ^8.0.0 \|\| ^9.0.0 |
500
- | TypeScript | >=4.0.0 |
501
- | @typescript-eslint/parser | >=6.0.0 |
502
- | @typescript-eslint/utils | ^8.0.0 |
503
- | Node.js | >=18.0.0 |
497
+ | Package | Version |
498
+ | ------------------------- | ----------------------------- |
499
+ | ESLint | ^8.0.0 \|\| ^9.0.0 \|\| ^10.0.0 |
500
+ | TypeScript | >=4.0.0 |
501
+ | @typescript-eslint/parser | >=6.0.0 |
502
+ | @typescript-eslint/utils | ^8.0.0 |
503
+ | Node.js | >=18.0.0 |
504
+
505
+ See the [ESLint Version Support Policy](../../docs/ESLINT_VERSION_SUPPORT.md) for current ecosystem share data and the rules that determine which majors are supported.
504
506
 
505
507
  ---
506
508
 
507
509
  ## Related Packages
508
510
 
509
- - **[eslint-plugin-llm-optimized](https://www.npmjs.com/package/eslint-plugin-llm-optimized)** - Ready-to-use LLM-optimized rules built with this package
511
+ - **The `@interlace/eslint-plugin-*` family** β€” Ready-to-use LLM-optimized rules built with this package. See the [root README](https://github.com/ofri-peretz/eslint#-available-packages) for the full list.
510
512
  - **[@typescript-eslint/utils](https://www.npmjs.com/package/@typescript-eslint/utils)** - Official TypeScript ESLint utilities
511
513
  - **[eslint-plugin-import](https://www.npmjs.com/package/eslint-plugin-import)** - Import/export validation
512
514
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interlace/eslint-devkit",
3
- "version": "1.3.3",
3
+ "version": "1.4.0",
4
4
  "description": "TypeScript utilities for building LLM-optimized ESLint plugins - AST helpers, type utilities, security benchmarks, and SARIF output",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -60,25 +60,27 @@
60
60
  "engines": {
61
61
  "node": ">=18.0.0"
62
62
  },
63
+ "scripts": {
64
+ "build": "tsx ../../scripts/build-package.ts",
65
+ "test": "vitest run",
66
+ "test:coverage": "vitest run --coverage",
67
+ "typecheck": "tsc -p tsconfig.lib.json --noEmit"
68
+ },
63
69
  "peerDependencies": {
70
+ "eslint": "^8.0.0 || ^9.0.0 || ^10.0.0",
64
71
  "tslib": "^2.3.0"
65
72
  },
66
73
  "peerDependenciesMeta": {
67
74
  "typescript": {
68
75
  "optional": true
69
- },
70
- "get-tsconfig": {
71
- "optional": true
72
- },
73
- "enhanced-resolve": {
74
- "optional": true
75
76
  }
76
77
  },
77
- "optionalDependencies": {},
78
78
  "dependencies": {
79
- "@typescript-eslint/utils": "^7.0.0 || ^8.0.0"
79
+ "@typescript-eslint/utils": "^7.0.0 || ^8.0.0",
80
+ "oxc-resolver": "^11.19.1"
80
81
  },
81
82
  "devDependencies": {
82
- "@typescript-eslint/parser": "^8.46.2"
83
+ "@typescript-eslint/parser": "^8.46.2",
84
+ "gpt-tokenizer": "^3.4.0"
83
85
  }
84
- }
86
+ }
package/src/index.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  * - SARIF output for security tool integration
19
19
  * - Custom message templates for organizations
20
20
  */
21
+ import './types/meta-augmentation';
21
22
  export * from './rule-creation';
22
23
  export * from './ast/ast-utils';
23
24
  export * from './types/type-utils';
package/src/index.js CHANGED
@@ -23,6 +23,10 @@ const tslib_1 = require("tslib");
23
23
  * - Custom message templates for organizations
24
24
  */
25
25
  // Rule creation utilities
26
+ // Side-effect import: extends `@typescript-eslint/utils` `RuleMetaDataDocs`
27
+ // with Interlace fields (cwe + cvss) so plugin authors can populate them
28
+ // without per-rule `@ts-expect-error`. See ./types/meta-augmentation.ts.
29
+ require("./types/meta-augmentation");
26
30
  tslib_1.__exportStar(require("./rule-creation"), exports);
27
31
  // AST utilities
28
32
  tslib_1.__exportStar(require("./ast/ast-utils"), exports);
@@ -6,9 +6,28 @@
6
6
  /**
7
7
  * AI-Native Runtime functions for LLM message formatting (Next-Gen)
8
8
  *
9
- * Contains the "Dual-Hertz" formatting engine for Agentic workflows
10
- * This module provides context-aware message formatting that automatically
11
- * routes between Human (CLI), Agent (JSON), and Hybrid (Cursor) modes.
9
+ * Contains the "Dual-Hertz" formatting engine for Agentic workflows.
10
+ * Provides context-aware message formatting that automatically routes
11
+ * between Human (CLI), Agent (JSON), and Hybrid (Cursor) modes.
12
+ *
13
+ * ⚠️ For NEW rule code, prefer the V2 formatters in `./formatters-v2`:
14
+ * - `formatSecurityMessage` β€” CWE-mapped security rules
15
+ * - `formatCodeQualityMessage` β€” structural / import / cycle rules
16
+ * - `formatPerformanceMessage` β€” performance / complexity rules
17
+ *
18
+ * The V2 formatters are category-specific (no force-fit security metadata
19
+ * on quality rules), expose `why` + before/after examples for higher
20
+ * first-fix accuracy, and support `'human' | 'compact' | 'agent'` modes.
21
+ *
22
+ * This file is retained for two reasons:
23
+ * 1. `buildASTSelector` β€” AST-targeting precision selector that V2 does
24
+ * not yet replicate. Still useful for agent-mode messages that want
25
+ * to hand the model an esquery target instead of a file/line.
26
+ * 2. `formatMessageNextGen` β€” the IDE_CURSOR mode that injects hidden
27
+ * `<!-- AI_HINT: ... -->` comments. Not yet ported to V2.
28
+ *
29
+ * Do not deprecate β€” downstream plugins still consume this API. New work
30
+ * should land in `formatters-v2.ts` instead.
12
31
  */
13
32
  import type { LLMMessageOptions, EnterpriseMessageOptions, AgentMessageOptions } from './types';
14
33
  import { type RuleContextLike } from './config';
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+ import type { SecurityMessageOptions, CodeQualityMessageOptions, PerformanceMessageOptions } from './types-v2';
7
+ /**
8
+ * Output mode for v2 formatters.
9
+ * - `'human'`: Rich multi-line output for CLI/IDE (default)
10
+ * - `'compact'`: Condensed single/two-line for token-sensitive contexts
11
+ * - `'agent'`: Minified JSON for programmatic agent consumption
12
+ */
13
+ export type V2OutputMode = 'human' | 'compact' | 'agent';
14
+ /**
15
+ * Formats a security-focused rule message.
16
+ *
17
+ * Supports three output modes:
18
+ * - `'human'` (default): Rich multi-line with OWASP, compliance, examples
19
+ * - `'compact'`: Token-optimized two-line (CWE+CVSS, inline examples)
20
+ * - `'agent'`: Minified JSON with self-describing keys
21
+ *
22
+ * Tokens measured with `tiktoken` o200k_base on the example below:
23
+ * human=120, compact=65, agent=72. (V1 baseline for the same content
24
+ * minus `why`/`vulnerable`/`safe`: 69 tokens.)
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * // Human mode (~120 tokens)
29
+ * formatSecurityMessage({
30
+ * cwe: 'CWE-89', severity: 'CRITICAL',
31
+ * description: 'SQL injection via string concatenation',
32
+ * why: 'Attackers can modify the query structure',
33
+ * vulnerable: "db.query('SELECT...' + userId)",
34
+ * safe: "db.query('SELECT...$1', [userId])",
35
+ * fix: 'Use parameterized queries ($1, $2)',
36
+ * docs: 'https://node-postgres.com/...',
37
+ * });
38
+ *
39
+ * // Compact mode (~65 tokens β€” actually cheaper than V1)
40
+ * formatSecurityMessage({ ...same... }, 'compact');
41
+ *
42
+ * // Agent mode (~72 tokens)
43
+ * formatSecurityMessage({ ...same... }, 'agent');
44
+ * ```
45
+ */
46
+ export declare function formatSecurityMessage(options: SecurityMessageOptions, mode?: V2OutputMode): string;
47
+ /**
48
+ * Formats a code quality / structural rule message.
49
+ *
50
+ * No CWE/OWASP/CVSS β€” these are architecture concerns, not vulnerabilities.
51
+ * Supports cycle path rendering for circular dependency rules.
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * formatCodeQualityMessage({
56
+ * category: 'circular-dependency',
57
+ * severity: 'WARNING',
58
+ * description: 'Circular import detected: A β†’ B β†’ C β†’ A',
59
+ * why: 'Circular imports cause undefined values at import time',
60
+ * cycle: ['src/A.ts', 'src/B.ts', 'src/C.ts', 'src/A.ts'],
61
+ * fix: 'Extract shared types to a separate module',
62
+ * });
63
+ * ```
64
+ */
65
+ export declare function formatCodeQualityMessage(options: CodeQualityMessageOptions, mode?: V2OutputMode): string;
66
+ /**
67
+ * Formats a performance-focused rule message.
68
+ *
69
+ * Uses complexity metrics instead of security metadata.
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * formatPerformanceMessage({
74
+ * severity: 'MEDIUM',
75
+ * description: 'Loop-based INSERT detected β€” O(n) database calls',
76
+ * why: 'Each iteration opens a new round-trip, causing NΓ—latency',
77
+ * vulnerable: 'for (const row of rows) { await db.query("INSERT...", row); }',
78
+ * safe: 'await db.query("INSERT INTO t VALUES " + values.join(","), flat)',
79
+ * impact: { current: 'O(n) queries', optimized: 'O(1) query' },
80
+ * fix: 'Use bulk INSERT with a single VALUES clause',
81
+ * });
82
+ * ```
83
+ */
84
+ export declare function formatPerformanceMessage(options: PerformanceMessageOptions, mode?: V2OutputMode): string;
@@ -0,0 +1,363 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Ofri Peretz
4
+ * Licensed under the MIT License. Use of this source code is governed by the
5
+ * MIT license that can be found in the LICENSE file.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.formatSecurityMessage = formatSecurityMessage;
9
+ exports.formatCodeQualityMessage = formatCodeQualityMessage;
10
+ exports.formatPerformanceMessage = formatPerformanceMessage;
11
+ const constants_1 = require("./constants");
12
+ // ============================================================================
13
+ // SHARED UTILITIES
14
+ // ============================================================================
15
+ /** Icons for each category */
16
+ const CATEGORY_ICONS = {
17
+ security: 'πŸ”’',
18
+ 'circular-dependency': 'πŸ”„',
19
+ 'unused-import': '🧹',
20
+ 'barrel-file': 'πŸ“¦',
21
+ 'dependency-boundary': '🚧',
22
+ 'import-order': 'πŸ“‹',
23
+ 'naming-convention': '✏️',
24
+ 'dead-code': 'πŸ’€',
25
+ performance: '⚑',
26
+ };
27
+ /**
28
+ * Compact-mode severity strings. Measured against `tiktoken` o200k_base:
29
+ * CRITICAL β†’ CRIT saves 0 tokens (both 2)
30
+ * MEDIUM β†’ MED saves 1 token (2 β†’ 1)
31
+ * HIGH/LOW/INFO already 1 token
32
+ * The abbreviations are kept primarily for visual width consistency in
33
+ * compact mode, not for measurable token savings.
34
+ */
35
+ const SEVERITY_SHORT = {
36
+ CRITICAL: 'CRIT',
37
+ HIGH: 'HIGH',
38
+ MEDIUM: 'MED',
39
+ LOW: 'LOW',
40
+ INFO: 'INFO',
41
+ };
42
+ /**
43
+ * Renders the optional `why` line.
44
+ */
45
+ function renderWhy(why) {
46
+ return why ? `\n Why: ${why}` : '';
47
+ }
48
+ /**
49
+ * Renders the optional vulnerable/safe code examples.
50
+ */
51
+ function renderExamples(vulnerable, safe) {
52
+ const parts = [];
53
+ if (vulnerable)
54
+ parts.push(` βœ— ${vulnerable}`);
55
+ if (safe)
56
+ parts.push(` βœ“ ${safe}`);
57
+ return parts.length > 0 ? '\n' + parts.join('\n') : '';
58
+ }
59
+ /**
60
+ * Renders inline examples for compact mode (same line as fix).
61
+ */
62
+ function renderInlineExamples(vulnerable, safe) {
63
+ const parts = [];
64
+ if (vulnerable)
65
+ parts.push(`βœ— ${vulnerable}`);
66
+ if (safe)
67
+ parts.push(`βœ“ ${safe}`);
68
+ return parts.length > 0 ? ' | ' + parts.join(' ') : '';
69
+ }
70
+ /**
71
+ * Renders the optional docs link suffix.
72
+ */
73
+ function renderDocs(docs) {
74
+ return docs ? ` | ${docs}` : '';
75
+ }
76
+ // ============================================================================
77
+ // SECURITY FORMATTER
78
+ // ============================================================================
79
+ /**
80
+ * Auto-enriches security options with CWE benchmark data.
81
+ */
82
+ function enrichSecurity(options) {
83
+ if (!options.cwe)
84
+ return options;
85
+ const cweData = constants_1.CWE_MAPPING[options.cwe];
86
+ if (!cweData)
87
+ return options;
88
+ return {
89
+ ...options,
90
+ owasp: options.owasp ?? cweData.owasp,
91
+ cvss: options.cvss ?? cweData.cvss,
92
+ compliance: options.compliance ?? constants_1.CWE_COMPLIANCE_MAPPING[options.cwe],
93
+ };
94
+ }
95
+ /**
96
+ * Builds the standards reference string (CWE, OWASP, CVSS).
97
+ */
98
+ function buildStandards(cwe, owasp, cvss) {
99
+ const parts = [];
100
+ if (cwe)
101
+ parts.push(cwe);
102
+ if (owasp) {
103
+ const owaspCode = owasp.split(':')[0];
104
+ const owaspDetails = constants_1.OWASP_DETAILS[owasp];
105
+ const owaspName = owaspDetails?.name?.split(' ')[0] || '';
106
+ parts.push(`OWASP:${owaspCode}-${owaspName}`);
107
+ }
108
+ if (cvss !== undefined)
109
+ parts.push(`CVSS:${cvss}`);
110
+ return parts.length > 0 ? `${parts.join(' ')} | ` : '';
111
+ }
112
+ /**
113
+ * Builds compact standards (CWE + CVSS only). Drops OWASP and compliance,
114
+ * which together cost ~27 tokens in a typical SQLi rule (measured with
115
+ * `tiktoken` o200k_base). LLMs already know what `CWE-89` means; the
116
+ * spelled-out `OWASP:A05-Injection [SOC2,PCI-DSS,HIPAA,ISO27001]` block
117
+ * is GRC-dashboard ergonomics, not agent fuel.
118
+ */
119
+ function buildCompactStandards(cwe, cvss) {
120
+ const parts = [];
121
+ if (cwe)
122
+ parts.push(cwe);
123
+ if (cvss !== undefined)
124
+ parts.push(`${cvss}`);
125
+ return parts.length > 0 ? `${parts.join(' ')} ` : '';
126
+ }
127
+ /**
128
+ * Builds the compliance tag string.
129
+ */
130
+ function buildCompliance(compliance) {
131
+ return compliance && compliance.length > 0
132
+ ? ` [${compliance.slice(0, 4).join(',')}]`
133
+ : '';
134
+ }
135
+ /**
136
+ * Formats a security-focused rule message.
137
+ *
138
+ * Supports three output modes:
139
+ * - `'human'` (default): Rich multi-line with OWASP, compliance, examples
140
+ * - `'compact'`: Token-optimized two-line (CWE+CVSS, inline examples)
141
+ * - `'agent'`: Minified JSON with self-describing keys
142
+ *
143
+ * Tokens measured with `tiktoken` o200k_base on the example below:
144
+ * human=120, compact=65, agent=72. (V1 baseline for the same content
145
+ * minus `why`/`vulnerable`/`safe`: 69 tokens.)
146
+ *
147
+ * @example
148
+ * ```typescript
149
+ * // Human mode (~120 tokens)
150
+ * formatSecurityMessage({
151
+ * cwe: 'CWE-89', severity: 'CRITICAL',
152
+ * description: 'SQL injection via string concatenation',
153
+ * why: 'Attackers can modify the query structure',
154
+ * vulnerable: "db.query('SELECT...' + userId)",
155
+ * safe: "db.query('SELECT...$1', [userId])",
156
+ * fix: 'Use parameterized queries ($1, $2)',
157
+ * docs: 'https://node-postgres.com/...',
158
+ * });
159
+ *
160
+ * // Compact mode (~65 tokens β€” actually cheaper than V1)
161
+ * formatSecurityMessage({ ...same... }, 'compact');
162
+ *
163
+ * // Agent mode (~72 tokens)
164
+ * formatSecurityMessage({ ...same... }, 'agent');
165
+ * ```
166
+ */
167
+ function formatSecurityMessage(options, mode = 'human') {
168
+ const enriched = enrichSecurity(options);
169
+ if (mode === 'agent') {
170
+ return securityToAgentJSON(enriched);
171
+ }
172
+ if (mode === 'compact') {
173
+ return securityToCompact(enriched);
174
+ }
175
+ return securityToHuman(enriched);
176
+ }
177
+ /** Human mode: rich, multi-line */
178
+ function securityToHuman(enriched) {
179
+ const { cwe, owasp, cvss, compliance, description, severity, fix, docs, why, vulnerable, safe } = enriched;
180
+ const icon = CATEGORY_ICONS['security'];
181
+ const standardsPart = buildStandards(cwe, owasp, cvss);
182
+ const compliancePart = buildCompliance(compliance);
183
+ const line1 = `${icon} ${standardsPart}${description} | ${severity}${compliancePart}`;
184
+ const whyLine = renderWhy(why);
185
+ const fixLine = `\n Fix: ${fix}${renderDocs(docs)}`;
186
+ const examples = renderExamples(vulnerable, safe);
187
+ return `${line1}${whyLine}${fixLine}${examples}`;
188
+ }
189
+ /**
190
+ * Compact mode: token-optimized two-line.
191
+ * Drops OWASP display, drops compliance tags, inlines examples.
192
+ * Target: ~45 tokens (vs 72 for v1, 124 for full v2).
193
+ */
194
+ function securityToCompact(enriched) {
195
+ const { cwe, cvss, description, severity, fix, vulnerable, safe } = enriched;
196
+ const sev = SEVERITY_SHORT[severity] || severity;
197
+ const std = buildCompactStandards(cwe, cvss);
198
+ const examples = renderInlineExamples(vulnerable, safe);
199
+ return `${std}${description} | ${sev}\n Fix: ${fix}${examples}`;
200
+ }
201
+ /**
202
+ * Agent mode: minified JSON with self-describing keys.
203
+ * Schema: { id, cvss, description, fix, bad?, good? }
204
+ *
205
+ * Measured with `tiktoken` o200k_base on a realistic SQLi payload, full
206
+ * keys cost only +1 token vs single-letter abbreviations (72 β†’ 73). The
207
+ * interpretability win for cold-start agents (no system-prompt key
208
+ * dictionary) is worth that token.
209
+ */
210
+ function securityToAgentJSON(enriched) {
211
+ const obj = {
212
+ id: enriched.cwe,
213
+ cvss: enriched.cvss ?? (0, constants_1.severityToCVSS)(enriched.severity),
214
+ description: enriched.description,
215
+ fix: enriched.fix,
216
+ };
217
+ if (enriched.vulnerable)
218
+ obj['bad'] = enriched.vulnerable;
219
+ if (enriched.safe)
220
+ obj['good'] = enriched.safe;
221
+ return JSON.stringify(obj);
222
+ }
223
+ // ============================================================================
224
+ // CODE QUALITY FORMATTER
225
+ // ============================================================================
226
+ /**
227
+ * Formats a code quality / structural rule message.
228
+ *
229
+ * No CWE/OWASP/CVSS β€” these are architecture concerns, not vulnerabilities.
230
+ * Supports cycle path rendering for circular dependency rules.
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * formatCodeQualityMessage({
235
+ * category: 'circular-dependency',
236
+ * severity: 'WARNING',
237
+ * description: 'Circular import detected: A β†’ B β†’ C β†’ A',
238
+ * why: 'Circular imports cause undefined values at import time',
239
+ * cycle: ['src/A.ts', 'src/B.ts', 'src/C.ts', 'src/A.ts'],
240
+ * fix: 'Extract shared types to a separate module',
241
+ * });
242
+ * ```
243
+ */
244
+ function formatCodeQualityMessage(options, mode = 'human') {
245
+ if (mode === 'agent') {
246
+ return codeQualityToAgentJSON(options);
247
+ }
248
+ if (mode === 'compact') {
249
+ return codeQualityToCompact(options);
250
+ }
251
+ return codeQualityToHuman(options);
252
+ }
253
+ /** Human mode: rich output with cycle path */
254
+ function codeQualityToHuman(options) {
255
+ const { category, description, severity, fix, docs, why, cycle, vulnerable, safe } = options;
256
+ const icon = CATEGORY_ICONS[category] || 'πŸ“';
257
+ const line1 = `${icon} ${description} | ${severity}`;
258
+ const whyLine = renderWhy(why);
259
+ const fixLine = `\n Fix: ${fix}${renderDocs(docs)}`;
260
+ const examples = renderExamples(vulnerable, safe);
261
+ const cycleLine = cycle && cycle.length > 0
262
+ ? `\n Cycle: ${cycle.join(' β†’ ')}`
263
+ : '';
264
+ return `${line1}${whyLine}${fixLine}${examples}${cycleLine}`;
265
+ }
266
+ /** Compact mode: inlined examples, abbreviated severity */
267
+ function codeQualityToCompact(options) {
268
+ const { description, severity, fix, vulnerable, safe, cycle } = options;
269
+ const sev = SEVERITY_SHORT[severity] || severity;
270
+ const examples = renderInlineExamples(vulnerable, safe);
271
+ const cycleSuffix = cycle && cycle.length > 0
272
+ ? ` [${cycle.map(f => f.split('/').pop()).join('β†’')}]`
273
+ : '';
274
+ return `${description} | ${sev}\n Fix: ${fix}${examples}${cycleSuffix}`;
275
+ }
276
+ /**
277
+ * Agent mode: compact JSON with self-describing keys.
278
+ * Schema: { category, description, fix, cycle?, bad?, good? }
279
+ * Measured: full keys cost 0 extra tokens vs `cat/d/f/cy/b/g` (both 70).
280
+ */
281
+ function codeQualityToAgentJSON(options) {
282
+ const obj = {
283
+ category: options.category,
284
+ description: options.description,
285
+ fix: options.fix,
286
+ };
287
+ if (options.cycle)
288
+ obj['cycle'] = options.cycle;
289
+ if (options.vulnerable)
290
+ obj['bad'] = options.vulnerable;
291
+ if (options.safe)
292
+ obj['good'] = options.safe;
293
+ return JSON.stringify(obj);
294
+ }
295
+ // ============================================================================
296
+ // PERFORMANCE FORMATTER
297
+ // ============================================================================
298
+ /**
299
+ * Formats a performance-focused rule message.
300
+ *
301
+ * Uses complexity metrics instead of security metadata.
302
+ *
303
+ * @example
304
+ * ```typescript
305
+ * formatPerformanceMessage({
306
+ * severity: 'MEDIUM',
307
+ * description: 'Loop-based INSERT detected β€” O(n) database calls',
308
+ * why: 'Each iteration opens a new round-trip, causing NΓ—latency',
309
+ * vulnerable: 'for (const row of rows) { await db.query("INSERT...", row); }',
310
+ * safe: 'await db.query("INSERT INTO t VALUES " + values.join(","), flat)',
311
+ * impact: { current: 'O(n) queries', optimized: 'O(1) query' },
312
+ * fix: 'Use bulk INSERT with a single VALUES clause',
313
+ * });
314
+ * ```
315
+ */
316
+ function formatPerformanceMessage(options, mode = 'human') {
317
+ if (mode === 'agent') {
318
+ return performanceToAgentJSON(options);
319
+ }
320
+ if (mode === 'compact') {
321
+ return performanceToCompact(options);
322
+ }
323
+ return performanceToHuman(options);
324
+ }
325
+ /** Human mode: rich with impact metrics */
326
+ function performanceToHuman(options) {
327
+ const { description, severity, fix, docs, why, vulnerable, safe, impact } = options;
328
+ const icon = CATEGORY_ICONS['performance'];
329
+ const line1 = `${icon} ${description} | ${severity}`;
330
+ const whyLine = renderWhy(why);
331
+ const fixLine = `\n Fix: ${fix}${renderDocs(docs)}`;
332
+ const impactLine = impact
333
+ ? `\n Impact: ${impact.current} β†’ ${impact.optimized}`
334
+ : '';
335
+ const examples = renderExamples(vulnerable, safe);
336
+ return `${line1}${whyLine}${fixLine}${impactLine}${examples}`;
337
+ }
338
+ /** Compact mode: inline impact and examples */
339
+ function performanceToCompact(options) {
340
+ const { description, severity, fix, vulnerable, safe, impact } = options;
341
+ const sev = SEVERITY_SHORT[severity] || severity;
342
+ const impactSuffix = impact ? ` (${impact.current}β†’${impact.optimized})` : '';
343
+ const examples = renderInlineExamples(vulnerable, safe);
344
+ return `${description} | ${sev}${impactSuffix}\n Fix: ${fix}${examples}`;
345
+ }
346
+ /**
347
+ * Agent mode: compact JSON with self-describing keys.
348
+ * Schema: { description, fix, impact?: { current, optimized }, bad?, good? }
349
+ * Measured: full keys cost 0 extra tokens vs `d/f/imp{c,o}/b/g` (both 75).
350
+ */
351
+ function performanceToAgentJSON(options) {
352
+ const obj = {
353
+ description: options.description,
354
+ fix: options.fix,
355
+ };
356
+ if (options.impact)
357
+ obj['impact'] = { current: options.impact.current, optimized: options.impact.optimized };
358
+ if (options.vulnerable)
359
+ obj['bad'] = options.vulnerable;
360
+ if (options.safe)
361
+ obj['good'] = options.safe;
362
+ return JSON.stringify(obj);
363
+ }