@ryuenn3123/agentic-senior-core 4.4.0 → 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 (196) hide show
  1. package/.agents/plugins/marketplace.json +21 -0
  2. package/.agents/rules/agentic-senior-core.md +126 -0
  3. package/.claude-plugin/marketplace.json +17 -0
  4. package/.claude-plugin/plugin.json +17 -0
  5. package/.clinerules/agentic-senior-core.md +94 -0
  6. package/.codex-plugin/plugin.json +24 -0
  7. package/.cursor/rules/agentic-senior-core.mdc +99 -0
  8. package/.devin-plugin/plugin.json +13 -0
  9. package/.github/copilot-instructions.md +94 -0
  10. package/.github/plugin/marketplace.json +20 -0
  11. package/.github/plugin/plugin.json +16 -0
  12. package/.kiro/steering/agentic-senior-core.md +94 -0
  13. package/.openclaw/skills/asc/SKILL.md +23 -0
  14. package/.openclaw/skills/asc-audit/SKILL.md +28 -0
  15. package/.openclaw/skills/asc-review/SKILL.md +54 -0
  16. package/.opencode/plugins/agentic-senior-core.mjs +31 -0
  17. package/.windsurf/rules/agentic-senior-core.md +94 -0
  18. package/AGENTS.md +126 -127
  19. package/CONTRIBUTING.md +93 -63
  20. package/README.md +160 -111
  21. package/__init__.py +61 -0
  22. package/bin/agentic-senior-core.js +42 -41
  23. package/commands/asc-audit.md +1 -0
  24. package/commands/asc-audit.toml +2 -0
  25. package/commands/asc-help.md +9 -0
  26. package/commands/asc-help.toml +2 -0
  27. package/commands/asc-refactor.md +1 -0
  28. package/commands/asc-refactor.toml +2 -0
  29. package/commands/asc-review.md +1 -0
  30. package/commands/asc-review.toml +2 -0
  31. package/gemini-extension.json +10 -0
  32. package/hooks/copilot-hooks.json +21 -0
  33. package/hooks/hooks.json +31 -0
  34. package/hooks/session-start.js +36 -0
  35. package/hooks/subagent-start.js +38 -0
  36. package/lib/cli/commands/adapter.mjs +109 -0
  37. package/lib/cli/commands/clean.mjs +63 -0
  38. package/lib/cli/commands/status.mjs +94 -0
  39. package/package.json +43 -60
  40. package/plugin.yaml +16 -0
  41. package/scripts/uninstall.js +38 -0
  42. package/skills/asc/SKILL.md +16 -0
  43. package/skills/asc-audit/SKILL.md +28 -0
  44. package/skills/asc-refactor/SKILL.md +35 -0
  45. package/skills/asc-review/SKILL.md +54 -0
  46. package/.agent-context/policies/llm-judge-threshold.json +0 -29
  47. package/.agent-context/prompts/bootstrap-design.md +0 -63
  48. package/.agent-context/prompts/compact-natural-mode.md +0 -100
  49. package/.agent-context/prompts/init-project.md +0 -60
  50. package/.agent-context/prompts/refactor.md +0 -38
  51. package/.agent-context/prompts/review-code.md +0 -31
  52. package/.agent-context/review-checklists/architecture-review.md +0 -57
  53. package/.agent-context/review-checklists/pr-checklist.md +0 -134
  54. package/.agent-context/rules/api-docs.md +0 -24
  55. package/.agent-context/rules/api-versioning.md +0 -16
  56. package/.agent-context/rules/architecture.md +0 -38
  57. package/.agent-context/rules/background-jobs.md +0 -17
  58. package/.agent-context/rules/config-and-flags.md +0 -16
  59. package/.agent-context/rules/database-design.md +0 -18
  60. package/.agent-context/rules/docker-runtime.md +0 -17
  61. package/.agent-context/rules/error-handling.md +0 -16
  62. package/.agent-context/rules/event-driven.md +0 -16
  63. package/.agent-context/rules/frontend-architecture.md +0 -54
  64. package/.agent-context/rules/microservices.md +0 -16
  65. package/.agent-context/rules/migrations.md +0 -16
  66. package/.agent-context/rules/observability.md +0 -16
  67. package/.agent-context/rules/performance.md +0 -16
  68. package/.agent-context/rules/realtime.md +0 -16
  69. package/.agent-context/rules/resilience.md +0 -18
  70. package/.agent-context/rules/security.md +0 -18
  71. package/.agent-context/rules/testing.md +0 -16
  72. package/.agent-context/state/README.md +0 -25
  73. package/.agent-context/state/architecture-map.md +0 -40
  74. package/.agent-context/state/benchmark-comparison-schema.json +0 -181
  75. package/.agent-context/state/benchmark-reproducibility.json +0 -87
  76. package/.agent-context/state/benchmark-thresholds.json +0 -10
  77. package/.agent-context/state/benchmark-writer-judge-config.json +0 -58
  78. package/.agent-context/state/dependency-map.md +0 -41
  79. package/.agent-context/state/memory-adapter-contract.json +0 -52
  80. package/.agent-context/state/memory-schema-v1.json +0 -88
  81. package/GEMINI.md +0 -1
  82. package/benchmarks/README.md +0 -60
  83. package/benchmarks/compact-natural-mode/fixtures.mjs +0 -359
  84. package/benchmarks/compact-natural-mode/scorer.mjs +0 -331
  85. package/benchmarks/runtime-token-saver/fixtures.mjs +0 -836
  86. package/lib/cli/adaptive-context/catalog.mjs +0 -394
  87. package/lib/cli/adaptive-context/file-signals.mjs +0 -100
  88. package/lib/cli/adaptive-context/implications.mjs +0 -44
  89. package/lib/cli/adaptive-context.mjs +0 -151
  90. package/lib/cli/audits/typography-palette-anti-repeat/color-utils.mjs +0 -156
  91. package/lib/cli/audits/typography-palette-anti-repeat/file-scanner.mjs +0 -103
  92. package/lib/cli/audits/typography-palette-anti-repeat/typography-utils.mjs +0 -70
  93. package/lib/cli/backup.mjs +0 -210
  94. package/lib/cli/commands/context.mjs +0 -140
  95. package/lib/cli/commands/init/project-context.mjs +0 -60
  96. package/lib/cli/commands/init/runtime-environment.mjs +0 -59
  97. package/lib/cli/commands/init/setup-decisions.mjs +0 -83
  98. package/lib/cli/commands/init.mjs +0 -654
  99. package/lib/cli/commands/launch.mjs +0 -76
  100. package/lib/cli/commands/optimize.mjs +0 -284
  101. package/lib/cli/commands/rollback.mjs +0 -64
  102. package/lib/cli/commands/upgrade/token-optimization-state.mjs +0 -51
  103. package/lib/cli/commands/upgrade.mjs +0 -451
  104. package/lib/cli/compiler.mjs +0 -187
  105. package/lib/cli/constants.mjs +0 -136
  106. package/lib/cli/detector/constants.mjs +0 -135
  107. package/lib/cli/detector/design-evidence/collector.mjs +0 -256
  108. package/lib/cli/detector/design-evidence/constants.mjs +0 -39
  109. package/lib/cli/detector/design-evidence/file-traversal.mjs +0 -83
  110. package/lib/cli/detector/design-evidence/structured-attribute-evidence.mjs +0 -117
  111. package/lib/cli/detector/design-evidence/summary.mjs +0 -109
  112. package/lib/cli/detector/design-evidence/utility-helpers.mjs +0 -122
  113. package/lib/cli/detector/design-evidence.mjs +0 -25
  114. package/lib/cli/detector/stack-detection.mjs +0 -243
  115. package/lib/cli/detector/ui-signals.mjs +0 -150
  116. package/lib/cli/detector/workspace-scan.mjs +0 -177
  117. package/lib/cli/detector.mjs +0 -23
  118. package/lib/cli/init-detection-flow.mjs +0 -48
  119. package/lib/cli/init-options.mjs +0 -237
  120. package/lib/cli/init-selection.mjs +0 -29
  121. package/lib/cli/memory-continuity.mjs +0 -537
  122. package/lib/cli/preflight.mjs +0 -76
  123. package/lib/cli/project-scaffolder/constants.mjs +0 -69
  124. package/lib/cli/project-scaffolder/discovery.mjs +0 -272
  125. package/lib/cli/project-scaffolder/prompt-builders.mjs +0 -171
  126. package/lib/cli/project-scaffolder/storage.mjs +0 -144
  127. package/lib/cli/project-scaffolder/ui-scope-detection.mjs +0 -36
  128. package/lib/cli/project-scaffolder.mjs +0 -29
  129. package/lib/cli/rollback.mjs +0 -66
  130. package/lib/cli/token-optimization.mjs +0 -401
  131. package/lib/cli/utils/filesystem.mjs +0 -81
  132. package/lib/cli/utils/managed-surface.mjs +0 -280
  133. package/lib/cli/utils/prompting.mjs +0 -44
  134. package/lib/cli/utils.mjs +0 -479
  135. package/mcp.json +0 -134
  136. package/scripts/adaptive-context/fixtures.mjs +0 -183
  137. package/scripts/adaptive-context-benchmark.mjs +0 -9
  138. package/scripts/ascx-runtime-token-saver-benchmark.mjs +0 -9
  139. package/scripts/benchmark-evidence-bundle.mjs +0 -645
  140. package/scripts/benchmark-gate.mjs +0 -121
  141. package/scripts/benchmark-intelligence.mjs +0 -33
  142. package/scripts/benchmark-writer-judge-matrix.mjs +0 -379
  143. package/scripts/build-release-benchmark-bundle.mjs +0 -202
  144. package/scripts/bump-version.mjs +0 -103
  145. package/scripts/clean-local-artifacts.mjs +0 -78
  146. package/scripts/compact-natural-mode-benchmark.mjs +0 -9
  147. package/scripts/context-triggered-audit.mjs +0 -391
  148. package/scripts/detection-benchmark.mjs +0 -127
  149. package/scripts/docs-quality-drift-report.mjs +0 -358
  150. package/scripts/documentation-boundary-audit.mjs +0 -305
  151. package/scripts/explain-on-demand-audit.mjs +0 -427
  152. package/scripts/forbidden-content-check.mjs +0 -123
  153. package/scripts/frontend-usability-audit.mjs +0 -243
  154. package/scripts/generate-sbom.mjs +0 -61
  155. package/scripts/governance-weekly-report.mjs +0 -466
  156. package/scripts/llm-judge/checklist-loader.mjs +0 -45
  157. package/scripts/llm-judge/constants.mjs +0 -66
  158. package/scripts/llm-judge/diff-collection.mjs +0 -74
  159. package/scripts/llm-judge/prompting.mjs +0 -78
  160. package/scripts/llm-judge/providers.mjs +0 -111
  161. package/scripts/llm-judge/verdict.mjs +0 -134
  162. package/scripts/llm-judge.mjs +0 -200
  163. package/scripts/memory-continuity-benchmark.mjs +0 -322
  164. package/scripts/quality-trend-report.mjs +0 -289
  165. package/scripts/release-gate/audit-checks.mjs +0 -441
  166. package/scripts/release-gate/constants.mjs +0 -53
  167. package/scripts/release-gate/runtime.mjs +0 -63
  168. package/scripts/release-gate/static-checks.mjs +0 -182
  169. package/scripts/release-gate.mjs +0 -42
  170. package/scripts/rules-guardian-audit.mjs +0 -580
  171. package/scripts/single-source-lazy-loading-audit.mjs +0 -449
  172. package/scripts/sync-thin-adapters.mjs +0 -72
  173. package/scripts/token-optimization-benchmark.mjs +0 -252
  174. package/scripts/ui-design-judge/constants.mjs +0 -13
  175. package/scripts/ui-design-judge/design-execution-summary.mjs +0 -81
  176. package/scripts/ui-design-judge/git-input.mjs +0 -134
  177. package/scripts/ui-design-judge/prompting.mjs +0 -52
  178. package/scripts/ui-design-judge/providers.mjs +0 -102
  179. package/scripts/ui-design-judge/reporting.mjs +0 -183
  180. package/scripts/ui-design-judge/rubric-calibration.mjs +0 -214
  181. package/scripts/ui-design-judge/rubric-goldset.json +0 -188
  182. package/scripts/ui-design-judge.mjs +0 -319
  183. package/scripts/ui-rubric-calibration.mjs +0 -35
  184. package/scripts/validate/audits/cache-layer-contract.mjs +0 -230
  185. package/scripts/validate/audits/caching-scope-hygiene.mjs +0 -235
  186. package/scripts/validate/audits/file-size.mjs +0 -158
  187. package/scripts/validate/audits/reflection-citations.mjs +0 -130
  188. package/scripts/validate/audits/release-bundle.mjs +0 -135
  189. package/scripts/validate/audits/rule-id-uniqueness.mjs +0 -278
  190. package/scripts/validate/config.mjs +0 -501
  191. package/scripts/validate/coverage-checks.mjs +0 -446
  192. package/scripts/validate/file-structure.mjs +0 -158
  193. package/scripts/validate/markdown-content.mjs +0 -109
  194. package/scripts/validate/project-metadata.mjs +0 -166
  195. package/scripts/validate/utils.mjs +0 -52
  196. package/scripts/validate.mjs +0 -267
@@ -1,78 +0,0 @@
1
- // @ts-check
2
-
3
- /**
4
- * Prompt construction for the LLM judge. Keeps the system role and the
5
- * user-message diff packaging in one place so the contract surface (severity
6
- * scheme + JSON_VERDICT format) stays inspectable.
7
- */
8
-
9
- import { MAX_DIFF_CHARS } from './constants.mjs';
10
-
11
- /**
12
- * Returns the system-level instruction for the LLM judge role.
13
- *
14
- * @returns {string}
15
- */
16
- export function buildSystemPrompt() {
17
- return `You are a Senior Software Architect performing an automated code review for a CI/CD pipeline.
18
-
19
- Your job: evaluate a git diff against the provided PR checklist and identify violations.
20
- You must categorize each violation with a severity level: critical, high, medium, or low.
21
-
22
- ## Severity classification:
23
- - critical: Security vulnerabilities (hardcoded secrets, SQL/command injection, missing auth checks, CORS), unvalidated external inputs.
24
- - high: N+1 database queries, swallowed errors (empty catch blocks without re-throw/recovery), layer boundary violations.
25
- - medium: TypeScript \`any\` type used without justification, missing test coverage, bad architectural patterns.
26
- - low: Style preferences, minor naming nitpicks, documentation nitpicks, performance micro-optimizations.
27
-
28
- ## Mandatory output format:
29
- You MUST output your findings in EXACTLY this structure:
30
-
31
- \`\`\`
32
- ## PR REVIEW RESULTS
33
- ━━━━━━━━━━━━━━━━━━━
34
-
35
- ✅ [Section Name] — Passes
36
- ❌ [Section Name] — FAILS
37
- 📌 Rule: [rule file and section]
38
- ❌ Problem: [exact description of the issue found in the diff]
39
- ⚠️ Severity: [critical | high | medium | low]
40
- ✅ Fix: [specific actionable fix]
41
-
42
- \`\`\`
43
-
44
- Rules:
45
- - Then at the absolute LAST line of your response, output a JSON array of the failed checks. Each object should have 'rule', 'problem', 'severity'. If there are no failures, output an empty array [].
46
- - Make sure the JSON array is perfectly valid JSON on a single line starting with \`JSON_VERDICT: \`. For example:
47
- JSON_VERDICT: [{"rule": "Security", "problem": "Hardcoded secret", "severity": "critical"}]
48
- - If the diff is empty, contains only documentation changes, or has no source code changes, output JSON_VERDICT: [] immediately.`;
49
- }
50
-
51
- /**
52
- * Builds the user message combining the checklist and the (possibly truncated)
53
- * diff. Truncation is annotated so the model knows the diff is partial.
54
- *
55
- * @param {string} prChecklistContent
56
- * @param {string} diffContent
57
- * @returns {string}
58
- */
59
- export function buildUserMessage(prChecklistContent, diffContent) {
60
- const truncatedDiff =
61
- diffContent.length > MAX_DIFF_CHARS
62
- ? `${diffContent.slice(0, MAX_DIFF_CHARS)}\n\n[DIFF TRUNCATED — ${(diffContent.length - MAX_DIFF_CHARS).toLocaleString()} additional characters omitted to stay within token limits]`
63
- : diffContent;
64
-
65
- return `## PR Checklist Reference
66
-
67
- ${prChecklistContent}
68
-
69
- ---
70
-
71
- ## Git Diff to Review
72
-
73
- \`\`\`diff
74
- ${truncatedDiff.trim() || '(empty diff — no source code changes detected)'}
75
- \`\`\`
76
-
77
- Review the diff against the checklist. Report your findings in the required format, ending with VERDICT: PASS ✅ or VERDICT: FAIL ❌.`;
78
- }
@@ -1,111 +0,0 @@
1
- // @ts-check
2
-
3
- /**
4
- * LLM provider invocations and selection logic. Each provider sticks to its
5
- * native API contract; the selection helper picks the first one whose env key
6
- * is set so callers do not need provider-specific glue code.
7
- */
8
-
9
- /**
10
- * @typedef {{ providerName: string, invokeProvider: (sys: string, usr: string) => Promise<string> }} SelectedProvider
11
- */
12
-
13
- async function callOpenAiProvider(systemPrompt, userMessage) {
14
- const selectedModel = process.env.LLM_JUDGE_MODEL ?? 'gpt-4o-mini';
15
- const apiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
16
- method: 'POST',
17
- headers: {
18
- 'Content-Type': 'application/json',
19
- Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
20
- },
21
- body: JSON.stringify({
22
- model: selectedModel,
23
- max_tokens: 2048,
24
- temperature: 0,
25
- messages: [
26
- { role: 'system', content: systemPrompt },
27
- { role: 'user', content: userMessage },
28
- ],
29
- }),
30
- });
31
-
32
- if (!apiResponse.ok) {
33
- const errorBody = await apiResponse.text();
34
- throw new Error(`OpenAI API returned ${apiResponse.status}: ${errorBody}`);
35
- }
36
-
37
- /** @type {{ choices: Array<{ message: { content: string } }> }} */
38
- const responsePayload = await apiResponse.json();
39
- return responsePayload.choices[0].message.content;
40
- }
41
-
42
- async function callAnthropicProvider(systemPrompt, userMessage) {
43
- const selectedModel = process.env.LLM_JUDGE_MODEL ?? 'claude-3-5-haiku-latest';
44
- const apiResponse = await fetch('https://api.anthropic.com/v1/messages', {
45
- method: 'POST',
46
- headers: {
47
- 'Content-Type': 'application/json',
48
- 'x-api-key': process.env.ANTHROPIC_API_KEY ?? '',
49
- 'anthropic-version': '2023-06-01',
50
- },
51
- body: JSON.stringify({
52
- model: selectedModel,
53
- max_tokens: 2048,
54
- system: systemPrompt,
55
- messages: [{ role: 'user', content: userMessage }],
56
- }),
57
- });
58
-
59
- if (!apiResponse.ok) {
60
- const errorBody = await apiResponse.text();
61
- throw new Error(`Anthropic API returned ${apiResponse.status}: ${errorBody}`);
62
- }
63
-
64
- /** @type {{ content: Array<{ text: string }> }} */
65
- const responsePayload = await apiResponse.json();
66
- return responsePayload.content[0].text;
67
- }
68
-
69
- async function callGeminiProvider(systemPrompt, userMessage) {
70
- const selectedModel = process.env.LLM_JUDGE_MODEL ?? 'gemini-2.0-flash';
71
- const apiKey = process.env.GEMINI_API_KEY ?? '';
72
- const endpointUrl = `https://generativelanguage.googleapis.com/v1beta/models/${selectedModel}:generateContent?key=${apiKey}`;
73
-
74
- const apiResponse = await fetch(endpointUrl, {
75
- method: 'POST',
76
- headers: { 'Content-Type': 'application/json' },
77
- body: JSON.stringify({
78
- system_instruction: { parts: [{ text: systemPrompt }] },
79
- contents: [{ role: 'user', parts: [{ text: userMessage }] }],
80
- generationConfig: { temperature: 0, maxOutputTokens: 2048 },
81
- }),
82
- });
83
-
84
- if (!apiResponse.ok) {
85
- const errorBody = await apiResponse.text();
86
- throw new Error(`Gemini API returned ${apiResponse.status}: ${errorBody}`);
87
- }
88
-
89
- /** @type {{ candidates: Array<{ content: { parts: Array<{ text: string }> } }> }} */
90
- const responsePayload = await apiResponse.json();
91
- return responsePayload.candidates[0].content.parts[0].text;
92
- }
93
-
94
- /**
95
- * Returns the first available LLM provider based on environment keys.
96
- * Priority: OpenAI, then Anthropic, then Gemini.
97
- *
98
- * @returns {SelectedProvider | null}
99
- */
100
- export function selectAvailableProvider() {
101
- if (process.env.OPENAI_API_KEY) {
102
- return { providerName: 'OpenAI (gpt-4o-mini)', invokeProvider: callOpenAiProvider };
103
- }
104
- if (process.env.ANTHROPIC_API_KEY) {
105
- return { providerName: 'Anthropic (claude-3-5-haiku-latest)', invokeProvider: callAnthropicProvider };
106
- }
107
- if (process.env.GEMINI_API_KEY) {
108
- return { providerName: 'Google Gemini (gemini-2.0-flash)', invokeProvider: callGeminiProvider };
109
- }
110
- return null;
111
- }
@@ -1,134 +0,0 @@
1
- // @ts-check
2
-
3
- /**
4
- * Verdict parsing and machine-readable report assembly for the LLM judge. Keeps
5
- * the pipeline output deterministic so downstream gates and CI dashboards can
6
- * consume a stable schema.
7
- */
8
-
9
- import { writeFileSync } from 'node:fs';
10
-
11
- import {
12
- MACHINE_REPORT_PATH,
13
- SEVERITY_NORMALIZATION_TABLE,
14
- SHOULD_EMIT_MACHINE_REPORT,
15
- } from './constants.mjs';
16
- import { detectCiProvider } from './diff-collection.mjs';
17
-
18
- /**
19
- * @typedef {import('./constants.mjs').MachineReportPayload} MachineReportPayload
20
- * @typedef {import('./constants.mjs').Violation} Violation
21
- */
22
-
23
- /**
24
- * @param {string | undefined} rawSeverityValue
25
- * @returns {string}
26
- */
27
- export function normalizeSeverity(rawSeverityValue) {
28
- const normalizedSeverityKey = String(rawSeverityValue || '').trim().toLowerCase();
29
- return SEVERITY_NORMALIZATION_TABLE[normalizedSeverityKey] || 'low';
30
- }
31
-
32
- /**
33
- * @param {MachineReportPayload} machineReportPayload
34
- * @returns {string}
35
- */
36
- export function formatMachineReadableLine(machineReportPayload) {
37
- return `JSON_REPORT: ${JSON.stringify(machineReportPayload)}`;
38
- }
39
-
40
- /**
41
- * @param {MachineReportPayload} machineReportPayload
42
- */
43
- export function emitMachineReadableReport(machineReportPayload) {
44
- if (!SHOULD_EMIT_MACHINE_REPORT) {
45
- return;
46
- }
47
-
48
- writeFileSync(MACHINE_REPORT_PATH, `${JSON.stringify(machineReportPayload, null, 2)}\n`, 'utf-8');
49
- console.log(formatMachineReadableLine(machineReportPayload));
50
- console.log(`📎 Machine report saved: ${MACHINE_REPORT_PATH}`);
51
- }
52
-
53
- /**
54
- * Extracts and parses the JSON verdict from the LLM response.
55
- *
56
- * @param {string} llmResponseText
57
- * @param {boolean} failOnMalformedResponse
58
- * @returns {Array<{ rule: string, problem: string, severity: string }>}
59
- */
60
- export function extractVerdict(llmResponseText, failOnMalformedResponse) {
61
- const match = llmResponseText.match(/JSON_VERDICT:\s*(\[.*\])/i);
62
- if (!match) {
63
- console.warn('⚠️ LLM response did not include a valid JSON_VERDICT line.');
64
- if (failOnMalformedResponse) {
65
- console.error('❌ Failing pipeline because malformed responses are not allowed by the profile.');
66
- process.exit(1);
67
- }
68
- return [];
69
- }
70
- try {
71
- return JSON.parse(match[1]);
72
- } catch (err) {
73
- const parseError = /** @type {Error} */ (err);
74
- console.error('⚠️ Failed to parse JSON_VERDICT:', parseError.message);
75
- if (failOnMalformedResponse) {
76
- process.exit(1);
77
- }
78
- return [];
79
- }
80
- }
81
-
82
- /**
83
- * @param {Array<{ rule?: string, problem?: string, severity?: string }>} violations
84
- * @returns {Violation[]}
85
- */
86
- export function normalizeViolations(violations) {
87
- return violations.map((violationItem) => ({
88
- rule: String(violationItem.rule || 'Unknown Rule'),
89
- problem: String(violationItem.problem || 'No problem description provided.'),
90
- severity: normalizeSeverity(violationItem.severity),
91
- }));
92
- }
93
-
94
- /**
95
- * @param {{
96
- * provider: string,
97
- * selectedProfile: string,
98
- * blockingSeverities: string[],
99
- * finalViolations: Violation[],
100
- * blockingFound: Violation[],
101
- * isDryRun: boolean,
102
- * malformedVerdict: boolean,
103
- * providerError: boolean,
104
- * }} payloadInput
105
- * @returns {MachineReportPayload}
106
- */
107
- export function buildMachineReportPayload({
108
- provider,
109
- selectedProfile,
110
- blockingSeverities,
111
- finalViolations,
112
- blockingFound,
113
- isDryRun,
114
- malformedVerdict,
115
- providerError,
116
- }) {
117
- return {
118
- generatedAt: new Date().toISOString(),
119
- schemaVersion: '1.0',
120
- profile: selectedProfile,
121
- provider,
122
- ciProvider: detectCiProvider(),
123
- blockingSeverities,
124
- failDecision: blockingFound.length > 0 || malformedVerdict || providerError,
125
- malformedVerdict,
126
- providerError,
127
- dryRun: isDryRun,
128
- summary: {
129
- totalViolations: finalViolations.length,
130
- blockingViolations: blockingFound.length,
131
- },
132
- violations: finalViolations,
133
- };
134
- }
@@ -1,200 +0,0 @@
1
- #!/usr/bin/env node
2
- // @ts-check
3
-
4
- /**
5
- * scripts/llm-judge.mjs
6
- *
7
- * LLM-as-a-Judge CI gate. Enforces pr-checklist.md on every pull request.
8
- *
9
- * Reads the git diff of the current PR, loads the PR checklist, sends both
10
- * to the first available LLM provider, and exits 1 when CRITICAL findings
11
- * exist (security gaps, N+1 queries, swallowed errors, hardcoded secrets,
12
- * layer boundary violations, SQL injection risks).
13
- *
14
- * Implementation is split per concern under scripts/llm-judge/. This entry
15
- * file owns the CLI orchestration only.
16
- *
17
- * Supported providers (auto-selected by first available env key):
18
- * OPENAI_API_KEY -> gpt-4o-mini (override with LLM_JUDGE_MODEL)
19
- * ANTHROPIC_API_KEY -> claude-3-5-haiku-latest
20
- * GEMINI_API_KEY -> gemini-2.0-flash
21
- *
22
- * Usage:
23
- * node scripts/llm-judge.mjs (auto-detect diff, call LLM)
24
- * node scripts/llm-judge.mjs --dry-run (print prompt, skip LLM call)
25
- *
26
- * Environment variables:
27
- * OPENAI_API_KEY OpenAI secret key
28
- * ANTHROPIC_API_KEY Anthropic secret key
29
- * GEMINI_API_KEY Google Gemini API key
30
- * LLM_JUDGE_MODEL Override model name for the selected provider
31
- * LLM_MAX_DIFF_CHARS Max characters of diff to send (default: 12000)
32
- * PR_DIFF Inject diff directly (bypasses git commands)
33
- * GITHUB_BASE_SHA Base commit SHA for GitHub Actions PR diffs
34
- * GITHUB_HEAD_SHA Head commit SHA for GitHub Actions PR diffs
35
- * CI_MERGE_REQUEST_DIFF_BASE_SHA Base SHA for GitLab MR diffs
36
- * CI_COMMIT_SHA Head SHA for GitLab MR diffs
37
- *
38
- * Zero external dependencies — uses Node.js built-ins only (Node 18+).
39
- */
40
-
41
- import { IS_DRY_RUN, MAX_DIFF_CHARS } from './llm-judge/constants.mjs';
42
- import { collectPullRequestDiff } from './llm-judge/diff-collection.mjs';
43
- import { loadPrChecklist, loadThresholds } from './llm-judge/checklist-loader.mjs';
44
- import { buildSystemPrompt, buildUserMessage } from './llm-judge/prompting.mjs';
45
- import { selectAvailableProvider } from './llm-judge/providers.mjs';
46
- import {
47
- buildMachineReportPayload,
48
- emitMachineReadableReport,
49
- extractVerdict,
50
- normalizeViolations,
51
- } from './llm-judge/verdict.mjs';
52
-
53
- async function main() {
54
- console.log('');
55
- console.log('🔍 LLM Judge — Automated Code Review Gate');
56
- console.log('════════════════════════════════════════════');
57
- console.log('');
58
-
59
- // ── Step 1: Load checklist and thresholds ──────────────
60
- const prChecklistContent = loadPrChecklist();
61
- const thresholdsObj = loadThresholds();
62
- const selectedProfile = thresholdsObj.selectedProfile || 'balanced';
63
- const profileConfig = thresholdsObj.profileThresholds[selectedProfile] || {};
64
- const blockingSeverities = profileConfig.blockingSeverities || ['critical', 'high'];
65
- const failOnMalformedResponse = profileConfig.failOnMalformedResponse !== false;
66
- const failOnProviderError = profileConfig.failOnProviderError || false;
67
-
68
- console.log(`✅ PR checklist loaded (${prChecklistContent.length} chars)`);
69
- console.log(`✅ Threshold profile loaded: ${selectedProfile} (blocking: ${blockingSeverities.join(', ')})`);
70
-
71
- // ── Step 2: Collect diff ────────────────────────────────
72
- const rawDiff = collectPullRequestDiff();
73
- console.log(`✅ Git diff collected (${rawDiff.length} chars${rawDiff.length > MAX_DIFF_CHARS ? ` — will truncate to ${MAX_DIFF_CHARS}` : ''})`);
74
-
75
- // ── Step 3: Build prompt ────────────────────────────────
76
- const systemPrompt = buildSystemPrompt();
77
- const userMessage = buildUserMessage(prChecklistContent, rawDiff);
78
-
79
- // ── Step 4: Dry run mode ────────────────────────────────
80
- if (IS_DRY_RUN) {
81
- console.log('');
82
- console.log('── DRY RUN MODE ──────────────────────────────────────────');
83
- console.log('[SYSTEM PROMPT PREVIEW]');
84
- console.log(systemPrompt.slice(0, 400) + '...');
85
- console.log('');
86
- console.log('[USER MESSAGE PREVIEW]');
87
- console.log(userMessage.slice(0, 400) + '...');
88
- console.log('─────────────────────────────────────────────────────────');
89
- console.log('');
90
- const dryRunReportPayload = buildMachineReportPayload({
91
- provider: 'dry-run',
92
- selectedProfile,
93
- blockingSeverities,
94
- finalViolations: [],
95
- blockingFound: [],
96
- isDryRun: true,
97
- malformedVerdict: false,
98
- providerError: false,
99
- });
100
- emitMachineReadableReport(dryRunReportPayload);
101
- console.log('VERDICT: JSON_VERDICT: [] (dry run — no LLM call made)');
102
- process.exit(0);
103
- }
104
-
105
- // ── Step 5: Select provider ─────────────────────────────
106
- const selectedProvider = selectAvailableProvider();
107
- if (!selectedProvider) {
108
- console.warn('');
109
- console.warn('⚠️ No LLM API key detected.');
110
- console.warn(' Set OPENAI_API_KEY, ANTHROPIC_API_KEY, or GEMINI_API_KEY');
111
- console.warn(' to enable automated code review.');
112
- console.warn('');
113
- console.warn('⏭️ Skipping LLM review — pipeline continues (PASS).');
114
- const skippedReportPayload = buildMachineReportPayload({
115
- provider: 'none',
116
- selectedProfile,
117
- blockingSeverities,
118
- finalViolations: [],
119
- blockingFound: [],
120
- isDryRun: false,
121
- malformedVerdict: false,
122
- providerError: false,
123
- });
124
- emitMachineReadableReport(skippedReportPayload);
125
- process.exit(0);
126
- }
127
-
128
- console.log(`✅ Provider selected: ${selectedProvider.providerName}`);
129
- if (process.env.LLM_JUDGE_MODEL) {
130
- console.log(` Model override: ${process.env.LLM_JUDGE_MODEL}`);
131
- }
132
- console.log('');
133
- console.log('⏳ Sending diff to LLM for review...');
134
- console.log('');
135
-
136
- // ── Step 6: Call LLM ────────────────────────────────────
137
- let llmReviewText;
138
- try {
139
- llmReviewText = await selectedProvider.invokeProvider(systemPrompt, userMessage);
140
- } catch (providerCallError) {
141
- console.warn(`⚠️ LLM call failed: ${/** @type {Error} */ (providerCallError).message}`);
142
- const providerErrorReportPayload = buildMachineReportPayload({
143
- provider: selectedProvider.providerName,
144
- selectedProfile,
145
- blockingSeverities,
146
- finalViolations: [],
147
- blockingFound: [],
148
- isDryRun: false,
149
- malformedVerdict: false,
150
- providerError: Boolean(failOnProviderError),
151
- });
152
- emitMachineReadableReport(providerErrorReportPayload);
153
- if (failOnProviderError) {
154
- console.error('❌ Failing pipeline because provider errors are not allowed by the profile.');
155
- process.exit(1);
156
- }
157
- console.warn(' Skipping LLM review — pipeline continues (PASS).');
158
- process.exit(0);
159
- }
160
-
161
- // ── Step 7: Print report ────────────────────────────────
162
- console.log('── LLM Review Report ─────────────────────────────────────');
163
- console.log('');
164
- console.log(llmReviewText);
165
- console.log('');
166
- console.log('──────────────────────────────────────────────────────────');
167
- console.log('');
168
-
169
- // ── Step 8: Enforce verdict ─────────────────────────────
170
- const rawVerdictViolations = extractVerdict(llmReviewText, failOnMalformedResponse);
171
- const finalViolations = normalizeViolations(rawVerdictViolations);
172
- const hasMalformedVerdict = !/JSON_VERDICT:\s*\[/i.test(llmReviewText);
173
-
174
- const blockingFound = finalViolations.filter((v) => blockingSeverities.includes(v.severity.toLowerCase()));
175
- const machineReportPayload = buildMachineReportPayload({
176
- provider: selectedProvider.providerName,
177
- selectedProfile,
178
- blockingSeverities,
179
- finalViolations,
180
- blockingFound,
181
- isDryRun: false,
182
- malformedVerdict: hasMalformedVerdict,
183
- providerError: false,
184
- });
185
- emitMachineReadableReport(machineReportPayload);
186
-
187
- if (blockingFound.length > 0) {
188
- console.error(`❌ LLM Judge: ${blockingFound.length} blocking violations found (severities: ${blockingSeverities.join(', ')}). Pipeline FAILED.`);
189
- console.error(' Fix the issues listed above before merging.');
190
- process.exit(1);
191
- }
192
-
193
- console.log('✅ LLM Judge: No blocking violations. Pipeline PASSED.');
194
- process.exit(0);
195
- }
196
-
197
- main().catch((unexpectedError) => {
198
- console.error('❌ Unexpected error in llm-judge:', unexpectedError);
199
- process.exit(1);
200
- });