diff --git a/src/adapter/cli/reports.ts b/src/adapter/cli/reports.ts index 863a2d4..fc27eb5 100644 --- a/src/adapter/cli/reports.ts +++ b/src/adapter/cli/reports.ts @@ -1,4 +1,5 @@ import { Buffer } from 'node:buffer'; +import { createHash } from 'node:crypto'; import { stripVTControlCharacters, styleText } from 'node:util'; import { applyEdits, format, visit } from 'jsonc-parser'; @@ -678,6 +679,14 @@ export function countViolations(reports: readonly RuleReport[]): number { return total; } +function violationSignature(rule: string, subject: Subject): string { + const context = ({ filepath, source, data, captures }: ScopeSubject) => ({ filepath, source, data, captures }); + const evaluated = subject.kind === 'scope' + ? context(subject) + : { group: subject.group, members: subject.members.map(context) }; + return `${createHash('sha256').update(JSON.stringify(evaluated)).digest('hex')}_${rule}`; +} + export async function renderViolationComments( reports: readonly RuleReport[], redact: TextRedactor, @@ -753,7 +762,7 @@ export async function renderViolationComments( seen.add(key); locations.push({ filepath: candidate.filepath, lines: candidate.lines }); } - comments.push({ body, locations }); + comments.push({ body, signature: violationSignature(report.name, subject), locations }); } } return comments; diff --git a/src/adapter/github/comments.ts b/src/adapter/github/comments.ts index 0271ab3..b32aad5 100644 --- a/src/adapter/github/comments.ts +++ b/src/adapter/github/comments.ts @@ -9,6 +9,19 @@ import { isolatedGitEnvironment } from '../git/environment.js'; import { createGithubApi, mapping } from './api.js'; import { originRepository, pullNumber, repositoryName, type PullRequest } from './pull-request.js'; +type GithubRequest = (path: string, method: 'GET' | 'POST', payload?: object) => Promise; + +const REVIEW_THREADS = `query($owner: String!, $name: String!, $number: Int!, $cursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + reviewThreads(first: 100, after: $cursor) { + nodes { isResolved path comments(first: 1) { nodes { body } } } + pageInfo { hasNextPage endCursor } + } + } + } +}`; + async function git( root: string, args: readonly string[], @@ -145,6 +158,53 @@ async function matchingFile( } } +async function unresolvedThreadBodies( + request: GithubRequest, + pull: PullRequest, +): Promise> { + const [owner, name] = pull.repository.split('/'); + const bodies = new Map(); + let cursor: string | null = null; + while (true) { + const response = await request('/graphql', 'POST', { + query: REVIEW_THREADS, + variables: { owner, name, number: pull.number, cursor }, + }); + const payload = mapping(await response.json().catch(() => undefined)); + const data = mapping(payload?.data); + const repository = mapping(data?.repository); + const pullRequest = mapping(repository?.pullRequest); + const threads = mapping(pullRequest?.reviewThreads); + const nodes = threads?.nodes; + const pageInfo = mapping(threads?.pageInfo); + if (!threads || !Array.isArray(nodes) || typeof pageInfo?.hasNextPage !== 'boolean' + || (pageInfo.hasNextPage && typeof pageInfo.endCursor !== 'string')) { + throw new Error('GitHub API returned an invalid review threads response.'); + } + for (const value of nodes) { + const thread = mapping(value); + const comments = mapping(thread?.comments); + const commentNodes = comments?.nodes; + if (!thread || typeof thread.isResolved !== 'boolean' || typeof thread.path !== 'string' || !Array.isArray(commentNodes)) { + throw new Error('GitHub API returned an invalid review threads response.'); + } + const firstComment = commentNodes[0]; + if (firstComment !== undefined) { + const comment = mapping(firstComment); + if (typeof comment?.body !== 'string') throw new Error('GitHub API returned an invalid review threads response.'); + if (!thread.isResolved) { + const pathBodies = bodies.get(thread.path); + if (pathBodies) pathBodies.push(comment.body); + else bodies.set(thread.path, [comment.body]); + } + } + } + if (!pageInfo.hasNextPage) return bodies; + cursor = pageInfo.endCursor as string; + } +} + + export function createGithubCommenter( env: Readonly>, ): (root: string, comments: readonly ViolationComment[], pullRequest?: PullRequest) => Promise { @@ -194,9 +254,10 @@ export function createGithubCommenter( const repository = comments.some(comment => comment.locations.length > 0) ? await repositoryPaths(root, gitEnv) : undefined; const matched = new Map>(); const patches = new Map(); - const inline: ReviewComment[] = []; + const planned: { readonly marker: string; readonly comment: ReviewComment }[] = []; const fallback: string[] = []; for (const finding of comments) { + const marker = ``; const anchors = new Set(); for (const location of finding.locations) { if (!repository || !Number.isSafeInteger(location.lines.start) || !Number.isSafeInteger(location.lines.end) @@ -218,12 +279,17 @@ export function createGithubCommenter( const key = JSON.stringify([file.filename, start, end]); if (anchors.has(key)) continue; anchors.add(key); - inline.push({ path: file.filename, body: finding.body, line: end, side: 'RIGHT', - ...(start < end ? { start_line: start, start_side: 'RIGHT' as const } : {}) }); + planned.push({ marker, comment: { path: file.filename, body: `${finding.body}\n\n${marker}`, line: end, side: 'RIGHT', + ...(start < end ? { start_line: start, start_side: 'RIGHT' as const } : {}) } }); } if (anchors.size === 0) fallback.push(finding.body); } + const unresolved = planned.length === 0 ? new Map() : await unresolvedThreadBodies(request, pull); + const inline = planned + .filter(({ marker, comment }) => !unresolved.get(comment.path)?.some(body => body.includes(marker))) + .map(({ comment }) => comment); + if (await readHead() !== head) throw new Error('GitHub pull request head changed during comment planning; refusing stale findings.'); if (inline.length > 0) { for (let index = 0; index < inline.length; index += 100) { diff --git a/src/app/violation-comments.ts b/src/app/violation-comments.ts index dafe0d1..767dcaf 100644 --- a/src/app/violation-comments.ts +++ b/src/app/violation-comments.ts @@ -1,5 +1,6 @@ export interface ViolationComment { readonly body: string; + readonly signature: string; readonly locations: readonly { readonly filepath: string; readonly lines: { diff --git a/tests/cli-auto-comment.test.ts b/tests/cli-auto-comment.test.ts index a467335..49268f1 100644 --- a/tests/cli-auto-comment.test.ts +++ b/tests/cli-auto-comment.test.ts @@ -96,7 +96,7 @@ interface Review { }[]; } -async function github(context: TestContext, target: Fixture, postStatus = 201) { +async function github(context: TestContext, target: Fixture, postStatus = 201, threads: unknown[] = []) { const requests: RequestRecord[] = []; const files = ['one', 'two', 'good'].map(name => { const filename = `src/${name}.txt`; @@ -117,6 +117,8 @@ async function github(context: TestContext, target: Fixture, postStatus = 201) { response.end(JSON.stringify(files)); } else if (request.method === 'GET' && url === '/repos/owner/project/pulls/42') { response.end(JSON.stringify({ head: { sha: target.head } })); + } else if (request.method === 'POST' && url === '/graphql') { + response.end(JSON.stringify({ data: { repository: { pullRequest: { reviewThreads: { nodes: threads, pageInfo: { hasNextPage: false, endCursor: null } } } } } })); } else if (request.method === 'POST' && ['/repos/owner/project/pulls/42/reviews', '/repos/owner/project/issues/42/comments'].includes(url)) { response.statusCode = postStatus; response.end(JSON.stringify(postStatus === 201 ? { id: 1 } : { message: `Rejected ${TOKEN} ${API_KEY}` })); @@ -143,12 +145,20 @@ async function github(context: TestContext, target: Fixture, postStatus = 201) { } function posts(requests: readonly RequestRecord[]) { - return requests.filter(request => request.method === 'POST'); + return requests.filter(request => request.method === 'POST' && request.url !== '/graphql'); } +const MARKER = /\n\n$/; function review(requests: readonly RequestRecord[]): Review { const matching = posts(requests).filter(request => request.url.endsWith('/reviews')); assert.equal(matching.length, 1); - return JSON.parse(matching[0]!.body) as Review; + const payload = JSON.parse(matching[0]!.body) as Review; + return { + ...payload, + comments: payload.comments.map(comment => { + assert.match(comment.body, MARKER); + return { ...comment, body: comment.body.replace(MARKER, '') }; + }), + }; } function fallback(requests: readonly RequestRecord[]): string { const matching = posts(requests).filter(request => request.url.endsWith('/issues/42/comments')); @@ -196,6 +206,33 @@ for (const diff of ['--diff', '--diff-only']) { }); } +test('repeated runs skip unresolved marked threads and repost after resolution', async context => { + const target = repository('repeated'); + const threads: { isResolved: boolean; path: string; comments: { nodes: { body: string }[] } }[] = []; + const requests = await github(context, target, 201, threads); + const args = ['--diff', '--base', target.base, '--auto-comment', '--json']; + + const first = await check(target, args); + assert.equal(first.status, 1, first.stderr); + assert.equal(first.stderr, ''); + assert.equal(posts(requests).length, 1); + const raw = JSON.parse(posts(requests)[0]!.body) as Review; + threads.push(...raw.comments.map(({ path, body }) => ({ isResolved: false, path, comments: { nodes: [{ body }] } }))); + + const second = await check(target, args); + assert.equal(second.status, 1, second.stderr); + assert.equal(second.stderr, ''); + assert.equal(posts(requests).length, 1, 'unresolved marked threads must suppress a repeat'); + + for (const thread of threads) thread.isResolved = true; + const third = await check(target, args); + assert.equal(third.status, 1, third.stderr); + assert.equal(third.stderr, ''); + assert.equal(posts(requests).length, 2); + assert.deepEqual(JSON.parse(posts(requests)[1]!.body).comments, raw.comments); + assert.equal(requests.filter(request => request.url === '/graphql').length, 3); +}); + const CUSTOM = '**Policy** — follow [the guide](https://example.invalid/guide) and keep `snake_case`.\n\n- mention @scope'; for (const kind of ['sync', 'async'] as const) { test(`subject-based comments (${kind})`, async context => { diff --git a/tests/cli-pr.test.ts b/tests/cli-pr.test.ts index bcb6069..c52f72a 100644 --- a/tests/cli-pr.test.ts +++ b/tests/cli-pr.test.ts @@ -93,7 +93,7 @@ function evaluations(reports: readonly CheckReportShape[]) { } function posts(requests: readonly RequestRecord[]) { - return requests.filter(request => request.method === 'POST'); + return requests.filter(request => request.method === 'POST' && request.url !== '/graphql'); } test('--pr uses current committed base and global policy only on PR changes', async context => { @@ -383,13 +383,21 @@ function commentPolicy(target: PrFixture): PrFixture { function assertCommentTarget(requests: readonly RequestRecord[], target: PrFixture): void { assert.equal(requests.some(request => request.url.startsWith(`/repos/${PR_REPOSITORY}/pulls?`)), false, 'explicit PR identity must not discover a branch'); - assert.ok(requests.every(request => request.url.startsWith(`/repos/${PR_REPOSITORY}/`)), 'unrelated Actions identity must never redirect requests'); + const graphql = requests.filter(request => request.url === '/graphql'); + assert.ok(graphql.length > 0, 'comment placement must check GraphQL review threads'); + for (const request of graphql) assert.deepEqual(JSON.parse(request.body).variables, { owner: 'owner', name: 'project', number: 42, cursor: null }); + assert.ok(requests.filter(request => request.url !== '/graphql').every(request => request.url.startsWith(`/repos/${PR_REPOSITORY}/`)), 'unrelated Actions identity must never redirect requests'); const review = posts(requests).filter(request => request.url.endsWith('/pulls/42/reviews')); assert.equal(review.length, 1); - const payload = JSON.parse(review[0]!.body); + const payload = JSON.parse(review[0]!.body) as { commit_id: string; event: string; comments: { body: string }[] }; assert.equal(payload.commit_id, target.head); assert.equal(payload.event, 'COMMENT'); - assert.deepEqual(payload.comments, [ + const marker = /\n\n$/; + const comments = payload.comments.map(({ body, ...comment }) => { + assert.match(body, marker); + return { ...comment, body: body.replace(marker, '') }; + }); + assert.deepEqual(comments, [ { path: 'src/changed.txt', body: CUSTOM_COMMENT, line: 1, side: 'RIGHT' }, ], 'inline placement requires the PR-head blob to match the analyzed file'); const fallback = posts(requests).filter(request => request.url.endsWith('/issues/42/comments')); diff --git a/tests/github-comments.test.ts b/tests/github-comments.test.ts index bae6021..d49d3aa 100644 --- a/tests/github-comments.test.ts +++ b/tests/github-comments.test.ts @@ -18,7 +18,9 @@ after(() => sandboxes.cleanup()); const token = 'github_pat_test-secret'; const body = '**memory**: app.yml:4-7 — limit is too high'; const head = 'a'.repeat(40); -const fallback = [{ body, locations: [] }]; +const signature = `${'d'.repeat(64)}_memory`; +const marker = ``; +const fallback = [{ body, signature, locations: [] }]; const detail = { body: { head: { sha: head } } }; const posted = { status: 201, body: {} }; const summary = (bodies: readonly string[]) => ({ body: `## CodeRuler violations\n\n${bodies.join('\n\n')}\n` }); @@ -107,7 +109,11 @@ function assertSafeError(error: unknown, expected: RegExp): boolean { function payload(request: Request) { return JSON.parse(request.body) as unknown; } function inline(path: string, line: number, start?: number, text = body) { - return { path, body: text, line, side: 'RIGHT', ...(start === undefined ? {} : { start_line: start, start_side: 'RIGHT' }) }; + return { path, body: `${text}\n\n${marker}`, line, side: 'RIGHT', ...(start === undefined ? {} : { start_line: start, start_side: 'RIGHT' }) }; +} + +function threads(nodes: readonly unknown[] = [], next?: string): Reply { + return { body: { data: { repository: { pullRequest: { reviewThreads: { nodes, pageInfo: { hasNextPage: next !== undefined, endCursor: next ?? null } } } } } } }; } test('empty findings do not require credentials, Git, or HTTP', async t => { @@ -160,23 +166,24 @@ test('explicit PR target supports detached HEAD and overrides unrelated Actions const repo = repository(); const file = source(repo); repo.git('checkout', '--quiet', '--detach'); - const requests = await github(t, [detail, { body: [file] }, detail, posted]); + const requests = await github(t, [detail, { body: [file] }, threads(), detail, posted]); await createGithubCommenter({ ...repo.env, GITHUB_TOKEN: token, GITHUB_REPOSITORY: 'unrelated/project', GITHUB_REF: 'refs/pull/99/merge', GITHUB_EVENT_PATH: join(repo.root, 'missing-event.json'), - })(repo.cwd, [{ body, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 5 } }] }], { + })(repo.cwd, [{ body, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 5 } }] }], { repository: 'requested/project', number: 42, head, }); assert.deepEqual(requests.map(request => [request.method, request.path]), [ ['GET', '/repos/requested/project/pulls/42'], ['GET', '/repos/requested/project/pulls/42/files?per_page=100&page=1'], + ['POST', '/graphql'], ['GET', '/repos/requested/project/pulls/42'], ['POST', '/repos/requested/project/pulls/42/reviews'], ]); - assert.deepEqual(payload(requests[3]!), { + assert.deepEqual(payload(requests[4]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('app.yml', 5, 4)], }); }); @@ -190,7 +197,7 @@ test('explicit target matches inline files despite inherited Git repository loca const callerIndex = caller.git('write-tree'); const callerStatus = caller.git('status', '--porcelain'); const transport = { origin: '' }; - const requests = await github(t, [detail, { body: [file] }, detail, posted], transport); + const requests = await github(t, [detail, { body: [file] }, threads(), detail, posted], transport); const script = ` import { createGithubCommenter } from ${JSON.stringify(new URL('../dist/adapter/github/comments.js', import.meta.url).href)}; const originalFetch = globalThis.fetch; @@ -200,7 +207,7 @@ test('explicit target matches inline files despite inherited Git repository loca return originalFetch(${JSON.stringify(transport.origin)} + url.pathname + url.search, init); }; await createGithubCommenter(process.env)(process.cwd(), ${JSON.stringify([ - { body, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 5 } }] }, + { body, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 5 } }] }, ])}, { repository: 'requested/project', number: 42 }); `; const { promise, resolve, reject } = Promise.withResolvers(); @@ -222,10 +229,11 @@ test('explicit target matches inline files despite inherited Git repository loca assert.deepEqual(requests.map(request => [request.method, request.path]), [ ['GET', '/repos/requested/project/pulls/42'], ['GET', '/repos/requested/project/pulls/42/files?per_page=100&page=1'], + ['POST', '/graphql'], ['GET', '/repos/requested/project/pulls/42'], ['POST', '/repos/requested/project/pulls/42/reviews'], ]); - assert.deepEqual(payload(requests[3]!), { + assert.deepEqual(payload(requests[4]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('app.yml', 5, 4)], }); assert.equal(caller.git('rev-parse', 'HEAD'), callerHead); @@ -236,42 +244,43 @@ test('explicit target matches inline files despite inherited Git repository loca test('nested invocation roots map rename targets and prefer RIGHT additions despite deletions', async t => { const repo = repository(); const file = source(repo, 'packages/app/new.yml'); - const requests = await github(t, [detail, { body: [{ ...file, status: 'renamed', previous_filename: 'old.yml' }] }, detail, posted]); - await actions(repo.env)(join(repo.cwd, 'packages/app'), [{ body, locations: [ + const requests = await github(t, [detail, { body: [{ ...file, status: 'renamed', previous_filename: 'old.yml' }] }, threads(), detail, posted]); + await actions(repo.env)(join(repo.cwd, 'packages/app'), [{ body, signature, locations: [ { filepath: 'new.yml', lines: { start: 2, end: 7 } }, { filepath: './new.yml', lines: { start: 4, end: 5 } }, ] }]); assert.deepEqual(requests.map(request => [request.method, request.path]), [ ['GET', '/repos/example/project/pulls/23'], ['GET', '/repos/example/project/pulls/23/files?per_page=100&page=1'], + ['POST', '/graphql'], ['GET', '/repos/example/project/pulls/23'], ['POST', '/repos/example/project/pulls/23/reviews'], ]); - assert.deepEqual(payload(requests[3]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('packages/app/new.yml', 5, 4)] }); + assert.deepEqual(payload(requests[4]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('packages/app/new.yml', 5, 4)] }); }); test('multiple hunks, optional header counts, no-newline markers and context anchors stay in one hunk', async t => { const repo = repository(); const file = source(repo); const patch = '@@ -1,2 +1,2 @@ heading\n one\n-two old\n+two\n\\ No newline at end of file\n@@ -5,2 +5,2 @@\n five\n six\n@@ -8 +8 @@\n-eight old\n+eight'; - const requests = await github(t, [detail, { body: [{ ...file, patch }] }, detail, posted]); - await actions(repo.env)(repo.cwd, [{ body, locations: [ + const requests = await github(t, [detail, { body: [{ ...file, patch }] }, threads(), detail, posted]); + await actions(repo.env)(repo.cwd, [{ body, signature, locations: [ { filepath: 'app.yml', lines: { start: 1, end: 8 } }, { filepath: 'app.yml', lines: { start: 5, end: 7 } }, { filepath: 'app.yml', lines: { start: 8, end: 8 } }, ] }]); - assert.deepEqual(payload(requests[3]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('app.yml', 2), inline('app.yml', 6, 5), inline('app.yml', 8)] }); + assert.deepEqual(payload(requests[4]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('app.yml', 2), inline('app.yml', 6, 5), inline('app.yml', 8)] }); }); test('mixed groups use only explicit usable candidates and fallback never duplicates anchored findings', async t => { const repo = repository(); const file = source(repo); - const requests = await github(t, [detail, { body: [file] }, detail, posted, posted]); + const requests = await github(t, [detail, { body: [file] }, threads(), detail, posted, posted]); await actions(repo.env)(repo.cwd, [ - { body: 'folder: selected member', locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }, { filepath: 'missing.yml', lines: { start: 1, end: 1 } }] }, - { body: 'project: no attribution', locations: [] }, - { body: 'scope: no usable hunk', locations: [{ filepath: 'app.yml', lines: { start: 99, end: 100 } }] }, + { body: 'folder: selected member', signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }, { filepath: 'missing.yml', lines: { start: 1, end: 1 } }] }, + { body: 'project: no attribution', signature, locations: [] }, + { body: 'scope: no usable hunk', signature, locations: [{ filepath: 'app.yml', lines: { start: 99, end: 100 } }] }, ]); - assert.deepEqual(payload(requests[3]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('app.yml', 4, undefined, 'folder: selected member')] }); - assert.deepEqual(payload(requests[4]!), summary(['project: no attribution', 'scope: no usable hunk'])); + assert.deepEqual(payload(requests[4]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('app.yml', 4, undefined, 'folder: selected member')] }); + assert.deepEqual(payload(requests[5]!), summary(['project: no attribution', 'scope: no usable hunk'])); }); test('unmatched source never gets inline coordinates: dirty, unpushed, untracked, absent, outside root', async t => { @@ -292,7 +301,7 @@ test('unmatched source never gets inline coordinates: dirty, unpushed, untracked writeFile(join(repo.cwd, filepath), 'one\n'); } const requests = await github(t, [detail, { body: [{ ...file, filename: kind === 'missing' ? filepath : file.filename }] }, detail, posted]); - await actions(repo.env)(repo.cwd, [{ body, locations: [{ filepath, lines: { start: 1, end: 1 } }] }]); + await actions(repo.env)(repo.cwd, [{ body, signature, locations: [{ filepath, lines: { start: 1, end: 1 } }] }]); assert.equal(requests.length, 4); assert.equal(requests[3]!.path, '/repos/example/project/issues/23/comments'); assert.deepEqual(payload(requests[3]!), summary([body])); @@ -309,7 +318,7 @@ test('removed, missing patch, deletion-only, malformed and nonoverlapping hunks const repo = repository(); const file = source(repo); const requests = await github(t, [detail, { body: [{ ...file, ...change }] }, detail, posted]); - await actions(repo.env)(repo.cwd, [{ body, locations: [{ filepath: 'app.yml', lines: { start: 1, end: 2 } }] }]); + await actions(repo.env)(repo.cwd, [{ body, signature, locations: [{ filepath: 'app.yml', lines: { start: 1, end: 2 } }] }]); assert.equal(requests[3]!.path, '/repos/example/project/issues/23/comments'); }); } @@ -323,9 +332,9 @@ test('blob identity hashes UTF-8 bytes and literal Git paths, not JavaScript str repo.git('add', '--', filename); repo.git('commit', '--quiet', '-m', 'unicode'); const file = { filename, status: 'added', sha: repo.git('hash-object', '--', filename), patch: '@@ -0,0 +1,2 @@\n+λ\n+第二行\n' }; - const requests = await github(t, [detail, { body: [file] }, detail, posted]); - await actions(repo.env)(repo.cwd, [{ body, locations: [{ filepath: filename, lines: { start: 1, end: 2 } }] }]); - assert.deepEqual(payload(requests[3]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline(filename, 2, 1)] }); + const requests = await github(t, [detail, { body: [file] }, threads(), detail, posted]); + await actions(repo.env)(repo.cwd, [{ body, signature, locations: [{ filepath: filename, lines: { start: 1, end: 2 } }] }]); + assert.deepEqual(payload(requests[4]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline(filename, 2, 1)] }); }); test('Actions checkout without usable Git metadata falls back even when a file exists', async t => { @@ -334,7 +343,7 @@ test('Actions checkout without usable Git metadata falls back even when a file e const bytes = Buffer.from('one\n'); const file = { filename: 'app.yml', status: 'added', sha: createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex'), patch: '@@ -0,0 +1 @@\n+one' }; const requests = await github(t, [detail, { body: [file] }, detail, posted]); - await actions(sandbox.env)(sandbox.cwd, [{ body, locations: [{ filepath: 'app.yml', lines: { start: 1, end: 1 } }] }]); + await actions(sandbox.env)(sandbox.cwd, [{ body, signature, locations: [{ filepath: 'app.yml', lines: { start: 1, end: 1 } }] }]); assert.equal(requests[3]!.path, '/repos/example/project/issues/23/comments'); assert.deepEqual(payload(requests[3]!), summary([body])); }); @@ -343,10 +352,10 @@ test('file pagination finds later files without following arbitrary Link URLs', const repo = repository(); const file = source(repo); const page = Array.from({ length: 100 }, (_, index) => ({ filename: `other-${index}`, status: 'modified', sha: file.sha })); - const requests = await github(t, [detail, { body: page, headers: { link: '; rel="next"' } }, { body: [file] }, detail, posted]); - await actions(repo.env)(repo.cwd, [{ body, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }]); + const requests = await github(t, [detail, { body: page, headers: { link: '; rel="next"' } }, { body: [file] }, threads(), detail, posted]); + await actions(repo.env)(repo.cwd, [{ body, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }]); assert.equal(requests[2]!.path, '/repos/example/project/pulls/23/files?per_page=100&page=2'); - assert.equal(requests[4]!.path, '/repos/example/project/pulls/23/reviews'); + assert.equal(requests[5]!.path, '/repos/example/project/pulls/23/reviews'); }); test('pagination stops at GitHub 3000-file cap and unmatched findings fall back', async t => { @@ -362,10 +371,10 @@ test('pagination stops at GitHub 3000-file cap and unmatched findings fall back' test('inline reviews batch at 100, and distinct findings are not collapsed', async t => { const repo = repository(); const file = source(repo); - const requests = await github(t, [detail, { body: [file] }, detail, posted, posted]); - await actions(repo.env)(repo.cwd, Array.from({ length: 101 }, (_, index) => ({ body: `finding ${index}`, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }))); - const first = payload(requests[3]!) as { comments: unknown[] }; - const second = payload(requests[4]!) as { comments: unknown[] }; + const requests = await github(t, [detail, { body: [file] }, threads(), detail, posted, posted]); + await actions(repo.env)(repo.cwd, Array.from({ length: 101 }, (_, index) => ({ body: `finding ${index}`, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }))); + const first = payload(requests[4]!) as { comments: unknown[] }; + const second = payload(requests[5]!) as { comments: unknown[] }; assert.equal(first.comments.length, 100); assert.equal(second.comments.length, 1); assert.deepEqual(second.comments, [inline('app.yml', 4, undefined, 'finding 100')]); @@ -374,9 +383,9 @@ test('inline reviews batch at 100, and distinct findings are not collapsed', asy test('head movement aborts all posting, including fallback', async t => { const repo = repository(); const file = source(repo); - const requests = await github(t, [detail, { body: [file] }, { body: { head: { sha: 'b'.repeat(40) } } }]); - await assert.rejects(actions(repo.env)(repo.cwd, [{ body, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }, ...fallback]), /head.*changed|head.*moved/i); - assert.deepEqual(requests.map(request => request.method), ['GET', 'GET', 'GET']); + const requests = await github(t, [detail, { body: [file] }, threads(), { body: { head: { sha: 'b'.repeat(40) } } }]); + await assert.rejects(actions(repo.env)(repo.cwd, [{ body, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }, ...fallback]), /head.*changed|head.*moved/i); + assert.deepEqual(requests.map(request => request.method), ['GET', 'GET', 'POST', 'GET']); }); test('analyzed PR revision rejects stale context anchors and summary findings before planning', async t => { @@ -387,6 +396,7 @@ test('analyzed PR revision rejects stale context anchors and summary findings be const requests = await github(t, [{ body: { head: { sha: 'b'.repeat(40) } } }]); await assert.rejects(createGithubCommenter({ ...repo.env, GITHUB_TOKEN: token })(repo.cwd, [{ body, + signature, locations: located ? [{ filepath: 'app.yml', lines: { start: 1, end: 1 } }] : [], }], { repository: 'example/project', number: 23, head }), error => assertSafeError(error, /head.*changed.*analysis/i)); assert.deepEqual(requests.map(request => [request.method, request.path]), [['GET', '/repos/example/project/pulls/23']]); @@ -402,6 +412,7 @@ test('summary-only planning rechecks the head with and without an analyzed revis const requests = await github(t, [detail, { body: [{ ...file, sha: 'c'.repeat(40) }] }, { body: { head: { sha: 'b'.repeat(40) } } }]); await assert.rejects(createGithubCommenter({ ...repo.env, GITHUB_TOKEN: token })(repo.cwd, [{ body, + signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }], }], { repository: 'example/project', number: 23, ...(expected ? { head } : {}) }), error => assertSafeError(error, /head.*changed.*planning/i)); assert.deepEqual(requests.map(request => request.method), ['GET', 'GET', 'GET']); @@ -445,20 +456,21 @@ test('credentials and valid Actions event identity are required for nonempty fin }); test('all HTTP failure stages are safe, do not retry and never replace a failed review with fallback', async t => { - for (const stage of ['discovery', 'head', 'files', 'recheck', 'review', 'fallback']) { + for (const stage of ['discovery', 'head', 'files', 'threads', 'recheck', 'review', 'fallback']) { await t.test(stage, async t => { const repo = repository(); const file = source(repo); const replies: Reply[] = stage === 'discovery' ? [] : [{ body: [{ number: 23 }] }]; if (!['discovery', 'head'].includes(stage)) replies.push(detail); if (!['discovery', 'head', 'files'].includes(stage)) replies.push({ body: stage === 'fallback' ? [] : [file] }); + if (['recheck', 'review'].includes(stage)) replies.push(threads()); if (['review', 'fallback'].includes(stage)) replies.push(detail); replies.push({ status: 403, body: { message: `credential ${token} denied` } }); const requests = await github(t, replies); - const findings = stage === 'fallback' ? fallback : [{ body, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }, ...fallback]; + const findings = stage === 'fallback' ? fallback : [{ body, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }, ...fallback]; await assert.rejects(createGithubCommenter({ ...repo.env, GITHUB_TOKEN: token })(repo.cwd, findings), error => assertSafeError(error, /GitHub.*403.*permission/i)); assert.equal(requests.length, replies.length); - assert.equal(requests.filter(request => request.method === 'POST').length, ['review', 'fallback'].includes(stage) ? 1 : 0); + assert.equal(requests.filter(request => request.method === 'POST' && request.path !== '/graphql').length, ['review', 'fallback'].includes(stage) ? 1 : 0); }); } }); @@ -488,3 +500,64 @@ test('network and malformed API responses fail without disclosing raw data', asy }); } }); + +test('unresolved marked threads suppress matching paths across pages; resolved and unmarked threads do not', async t => { + const repo = repository(); + const app = source(repo); + const other = source(repo, 'other.yml'); + const requests = await github(t, [ + detail, + { body: [app, other] }, + threads([{ isResolved: true, path: 'other.yml', comments: { nodes: [{ body: `resolved\n\n${marker}` }] } }], 'c1'), + threads([ + { isResolved: false, path: 'app.yml', comments: { nodes: [{ body: `old message\n\n${marker}` }] } }, + { isResolved: false, path: 'other.yml', comments: { nodes: [{ body: '' }] } }, + ]), + detail, + posted, + ]); + await actions(repo.env)(repo.cwd, [ + { body, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }, + { body, signature, locations: [{ filepath: 'other.yml', lines: { start: 4, end: 4 } }] }, + ]); + assert.deepEqual(requests.map(request => [request.method, request.path]), [ + ['GET', '/repos/example/project/pulls/23'], + ['GET', '/repos/example/project/pulls/23/files?per_page=100&page=1'], + ['POST', '/graphql'], + ['POST', '/graphql'], + ['GET', '/repos/example/project/pulls/23'], + ['POST', '/repos/example/project/pulls/23/reviews'], + ]); + assert.deepEqual(requests.slice(2, 4).map(request => { + const graphql = payload(request); + assert.ok(typeof graphql === 'object' && graphql !== null && 'variables' in graphql); + return graphql.variables; + }), [ + { owner: 'example', name: 'project', number: 23, cursor: null }, + { owner: 'example', name: 'project', number: 23, cursor: 'c1' }, + ]); + assert.deepEqual(payload(requests[5]!), { commit_id: head, event: 'COMMENT', body: 'CodeRuler violations', comments: [inline('other.yml', 4)] }); +}); + +test('fully suppressed findings post nothing; invalid thread responses fail safely', async t => { + const finding = { body, signature, locations: [{ filepath: 'app.yml', lines: { start: 4, end: 4 } }] }; + await t.test('matching unresolved thread', async t => { + const repo = repository(); + const file = source(repo); + const requests = await github(t, [detail, { body: [file] }, threads([{ isResolved: false, path: 'app.yml', comments: { nodes: [{ body: `old message\n\n${marker}` }] } }]), detail]); + await actions(repo.env)(repo.cwd, [finding]); + assert.deepEqual(requests.map(request => [request.method, request.path]), [ + ['GET', '/repos/example/project/pulls/23'], + ['GET', '/repos/example/project/pulls/23/files?per_page=100&page=1'], + ['POST', '/graphql'], + ['GET', '/repos/example/project/pulls/23'], + ]); + }); + await t.test('malformed thread response', async t => { + const repo = repository(); + const file = source(repo); + const requests = await github(t, [detail, { body: [file] }, { body: { errors: [{ message: token }] } }]); + await assert.rejects(actions(repo.env)(repo.cwd, [finding]), error => assertSafeError(error, /GitHub.*review threads response/i)); + assert.equal(requests.length, 3); + }); +}); diff --git a/tests/pr-support.ts b/tests/pr-support.ts index 800d4cc..437755e 100644 --- a/tests/pr-support.ts +++ b/tests/pr-support.ts @@ -155,6 +155,8 @@ export async function startGithubFixture(target: PrFixture, options: GithubFixtu response.end(JSON.stringify(files)); } else if (request.method === 'GET' && url.startsWith(`/repos/${PR_REPOSITORY}/pulls?`)) { response.end(JSON.stringify([{ number: PR_NUMBER }])); + } else if (request.method === 'POST' && url === '/graphql') { + response.end(JSON.stringify({ data: { repository: { pullRequest: { reviewThreads: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } } } } })); } else if (request.method === 'POST' && [ `${pull}/reviews`, `/repos/${PR_REPOSITORY}/issues/${PR_NUMBER}/comments`, ].includes(url)) { diff --git a/tests/violation-locations.test.ts b/tests/violation-locations.test.ts index 30d9cae..82adaa8 100644 --- a/tests/violation-locations.test.ts +++ b/tests/violation-locations.test.ts @@ -11,6 +11,7 @@ import type { Grouping, RunContext, RunEvent, + RuleReport, ScopeSelector, Subject, ViolationLocation, @@ -88,6 +89,51 @@ async function run( } const redact = (text: string): string => text; +test('comment signatures hash evaluated context and rule name, not lines or scope ids', async () => { + const base: Subject = { + kind: 'scope', + filepath: 'app.yml', + id: 'row:1', + source: 'name: test', + data: { name: 'test' }, + captures: { name: 'test' }, + lines: { start: 1, end: 1 }, + }; + const report = (name: string, subject: Subject): RuleReport => ({ + name, + ruleFile: '.coderuler/policy.rule.ts', + status: 'violation', + durationMs: 0, + evaluations: [{ subject, result: { status: 'violation', message: 'm' } }], + }); + const signature = async (name: string, subject: Subject): Promise => + (await renderViolationComments([report(name, subject)], redact))[0]!.signature; + const baseSignature = await signature('policy', base); + const hash = baseSignature.split('_')[0]; + assert.match(baseSignature, /^[0-9a-f]{64}_policy$/); + assert.equal(await signature('policy', { ...base, id: 'row:2', lines: { start: 4, end: 5 } }), baseSignature); + for (const changed of [ + { ...base, source: 'name: changed' }, + { ...base, data: { name: 'changed' } }, + { ...base, captures: { name: 'changed' } }, + { ...base, filepath: 'other.yml' }, + ]) { + assert.notEqual((await signature('policy', changed)).split('_')[0], hash); + } + assert.ok((await signature('other-policy', base)).endsWith('_other-policy')); + + const group: Subject = { + kind: 'group', + group: { type: 'project', path: '.' }, + members: [base], + }; + const groupChanged: Subject = { + ...group, + members: [{ ...base, lines: { start: 8, end: 9 } }], + }; + assert.equal(await signature('policy', groupChanged), await signature('policy', group)); +}); + function rawResult(locations: unknown, status: CheckResult['status'] = 'violation'): CheckResult { return { status, message: 'Invalid attribution', locations } as unknown as CheckResult; @@ -126,9 +172,9 @@ test('protobuf field comments preserve each field source location', async () => { status: 'violation', message: 'Use trusted token data' }, { status: 'violation', message: 'Use trusted token data' }, ]); - assert.deepEqual(await renderViolationComments(sync.reports, redact, [ + assert.deepEqual((await renderViolationComments(sync.reports, redact, [ { name: 'location-policy', ruleFile: '.coderuler/location-policy.rule.ts', rule: syncRule as Rule }, - ]), [ + ])).map(({ body, locations }) => ({ body, locations })), [ { body: '**organization_id**: Use trusted token data. [Organization policy](https://example.invalid/organization)', locations: [{ filepath: 'pkg/fields.proto', lines: { start: 3, end: 3 } }], @@ -155,9 +201,9 @@ test('protobuf field comments preserve each field source location', async () => { status: 'violation', message: 'Use trusted token data' }, { status: 'violation', message: 'Use trusted token data' }, ]); - assert.deepEqual(await renderViolationComments(asyncResult.reports, redact, [ + assert.deepEqual((await renderViolationComments(asyncResult.reports, redact, [ { name: 'location-policy', ruleFile: '.coderuler/location-policy.rule.ts', rule: asyncRule as Rule }, - ]), [ + ])).map(({ body, locations }) => ({ body, locations })), [ { body: '**organization_id**: Use trusted token data. [Organization policy](https://example.invalid/organization)', locations: [{ filepath: 'pkg/fields.proto', lines: { start: 3, end: 3 } }], @@ -190,9 +236,9 @@ test('group comments render once with all resolved member locations', async () = }; const result = await run(rule); - assert.deepEqual(await renderViolationComments(result.reports, redact, [ + assert.deepEqual((await renderViolationComments(result.reports, redact, [ { name: 'location-policy', ruleFile: '.coderuler/location-policy.rule.ts', rule: rule as Rule }, - ]), [{ + ])).map(({ body, locations }) => ({ body, locations })), [{ body: '**project .**: head, tail (2 locations)', locations: [ { filepath: 'pkg/a.txt', lines: { start: 1, end: 3 } },