-
Notifications
You must be signed in to change notification settings - Fork 4
CLI-247 Post tool use #159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
kirill-knize-sonarsource
merged 1 commit into
task/kk/CLI-244-245-callback-infrastructure
from
task/kk/CLI-247-post-tool-use
Apr 15, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| /* | ||
| * SonarQube CLI | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the GNU Lesser General Public | ||
| * License as published by the Free Software Foundation; either | ||
| * version 3 of the License, or (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
| * Lesser General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Lesser General Public License | ||
| * along with this program; if not, write to the Free Software Foundation, | ||
| * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
| */ | ||
|
|
||
| // PostToolUse callback handler — runs SQAA analysis after the agent edits or writes a file. | ||
| // Replaces the bash/PowerShell logic that was previously embedded in the hook script. | ||
|
|
||
| import { existsSync, readFileSync } from 'node:fs'; | ||
| import { relative } from 'node:path'; | ||
| import { resolveAuth } from '../../../lib/auth-resolver'; | ||
| import logger from '../../../lib/logger'; | ||
| import { SonarQubeClient } from '../../../sonarqube/client'; | ||
| import type { SqaaIssue } from '../../../sonarqube/client'; | ||
| import { readStdinJson } from './stdin'; | ||
|
|
||
| interface PostToolUsePayload { | ||
| tool_name?: string; | ||
| tool_input?: { file_path?: string }; | ||
| } | ||
|
|
||
| export interface AgentPostToolUseOptions { | ||
| project?: string; | ||
| } | ||
|
|
||
| export async function agentPostToolUse(options: AgentPostToolUseOptions): Promise<void> { | ||
| let payload: PostToolUsePayload; | ||
| try { | ||
| payload = await readStdinJson<PostToolUsePayload>(); | ||
| } catch { | ||
| return; // unparseable stdin — non-blocking | ||
| } | ||
|
|
||
| const toolName = payload.tool_name; | ||
| if (toolName !== 'Edit' && toolName !== 'Write') return; | ||
|
|
||
| const filePath = payload.tool_input?.file_path; | ||
| if (!filePath || !existsSync(filePath)) return; | ||
|
|
||
| const auth = await resolveAuth().catch(() => null); | ||
| if (auth?.connectionType !== 'cloud' || !auth.orgKey) return; | ||
|
|
||
| const projectKey = options.project; | ||
| if (!projectKey) return; | ||
|
|
||
| try { | ||
| const fileContent = readFileSync(filePath, 'utf-8'); | ||
| const filePath_ = relative(process.cwd(), filePath); | ||
| const client = new SonarQubeClient(auth.serverUrl, auth.token); | ||
|
|
||
| const response = await client.analyzeFile({ | ||
| organizationKey: auth.orgKey, | ||
| projectKey, | ||
| filePath: filePath_, | ||
| fileContent, | ||
| }); | ||
|
|
||
| const text = formatSqaaResult(response.issues, response.errors); | ||
| process.stdout.write( | ||
| JSON.stringify({ | ||
| hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: text }, | ||
| }) + '\n', | ||
| ); | ||
| } catch (err) { | ||
| logger.debug(`PostToolUse SQAA analysis failed: ${(err as Error).message}`); | ||
| } | ||
| } | ||
|
|
||
| function formatSqaaResult( | ||
| issues: SqaaIssue[], | ||
| errors?: Array<{ code: string; message: string }> | null, | ||
| ): string { | ||
| const lines: string[] = []; | ||
|
|
||
| if (issues.length === 0) { | ||
| lines.push('SQAA analysis completed — no issues found.'); | ||
| } else { | ||
| lines.push(`SQAA analysis found ${issues.length} issue${issues.length === 1 ? '' : 's'}:`); | ||
| issues.forEach((issue, idx) => { | ||
| const location = issue.textRange ? ` (line ${issue.textRange.startLine})` : ''; | ||
| lines.push(` [${idx + 1}] ${issue.message}${location} [${issue.rule}]`); | ||
| }); | ||
| } | ||
|
|
||
| if (errors && errors.length > 0) { | ||
| lines.push('SQAA errors:'); | ||
| errors.forEach((e) => lines.push(` [${e.code}] ${e.message}`)); | ||
| } | ||
|
|
||
| return lines.join('\n'); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
tests/integration/specs/hook/hook-agent-post-tool-use.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| /* | ||
| * SonarQube CLI | ||
| * Copyright (C) 2026 SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * This program is free software; you can redistribute it and/or | ||
| * modify it under the terms of the GNU Lesser General Public | ||
| * License as published by the Free Software Foundation; either | ||
| * version 3 of the License, or (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
| * Lesser General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Lesser General Public License | ||
| * along with this program; if not, write to the Free Software Foundation, | ||
| * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
| */ | ||
|
|
||
| // Integration tests for `sonar hook claude-post-tool-use`. | ||
|
|
||
| import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; | ||
| import { join } from 'node:path'; | ||
| import { TestHarness } from '../../harness'; | ||
|
|
||
| const VALID_TOKEN = 'integration-test-token'; | ||
| const TEST_ORG = 'my-org'; | ||
| const TEST_PROJECT = 'my-project'; | ||
|
|
||
| function postToolUseStdin(filePath: string, toolName = 'Edit'): string { | ||
| return JSON.stringify({ tool_name: toolName, tool_input: { file_path: filePath } }); | ||
| } | ||
|
|
||
| describe('sonar hook claude-post-tool-use', () => { | ||
| let harness: TestHarness; | ||
|
|
||
| beforeEach(async () => { | ||
| harness = await TestHarness.create(); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await harness.dispose(); | ||
| }); | ||
|
|
||
| it( | ||
| 'exits 0 and outputs SQAA JSON when analysis returns no issues', | ||
| async () => { | ||
| const server = await harness | ||
| .newFakeServer() | ||
| .withAuthToken(VALID_TOKEN) | ||
| .withSqaaResponse({ issues: [] }) | ||
| .start(); | ||
| harness.withAuth(server.baseUrl(), VALID_TOKEN, TEST_ORG); | ||
| harness.cwd.writeFile('src/main.ts', 'const x = 1;'); | ||
| const filePath = join(harness.cwd.path, 'src/main.ts'); | ||
|
|
||
| const result = await harness.run(`hook claude-post-tool-use --project ${TEST_PROJECT}`, { | ||
| stdin: postToolUseStdin(filePath), | ||
| }); | ||
|
|
||
| expect(result.exitCode).toBe(0); | ||
| const output = JSON.parse(result.stdout.trim()); | ||
| expect(output.hookSpecificOutput.hookEventName).toBe('PostToolUse'); | ||
| expect(output.hookSpecificOutput.additionalContext).toContain('no issues'); | ||
| }, | ||
| { timeout: 15000 }, | ||
| ); | ||
|
|
||
| it( | ||
| 'exits 0 and outputs no hook response when not authenticated', | ||
| async () => { | ||
| harness.cwd.writeFile('src/main.ts', 'const x = 1;'); | ||
| const filePath = join(harness.cwd.path, 'src/main.ts'); | ||
|
|
||
| const result = await harness.run(`hook claude-post-tool-use --project ${TEST_PROJECT}`, { | ||
| stdin: postToolUseStdin(filePath), | ||
| }); | ||
|
|
||
| expect(result.exitCode).toBe(0); | ||
| expect(result.stdout.trim()).toBe(''); | ||
| }, | ||
| { timeout: 15000 }, | ||
| ); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Logic duplication:
formatSqaaResultreimplements the same logic asdisplaySqaaResultsinsrc/cli/commands/analyze/sqaa.ts(line 162). Both iterate over issues with the same[idx+1] message (line startLine)structure and handle theerrorsarray the same way. They've already diverged:displaySqaaResultsputs the rule on a separateRule: Xline, while this version inlines it as[rule].If the output format needs to change (e.g. adding severity, effort, or a new field), both functions must be updated. Extract shared formatting logic — for example a
buildSqaaIssueLines(issues, errors): string[]helper in a shared module — and have each caller apply its own output target on top.