From d975b9d598938db709124b1f539f0c8f31d610dc Mon Sep 17 00:00:00 2001 From: Juan Carlos Joya Carvajal Date: Fri, 6 Nov 2026 09:01:32 -0500 Subject: [PATCH] fix(review): local branch reviews judge the true base; release 1.7.2 A path review read the base from the user's refs, so a stale origin/develop or a default of main reviewed the wrong diff. The base is now fetched from GitHub into the review's own copy, and defaults to the open PR's base. Another base starts clean, and a branch with an open PR gets its description, discussion and CI. review_get also returns reviewBody and ci. --- CHANGELOG.md | 15 ++- .../main/review/local-review.ts | 109 ++++++++++++---- .../main/review/review-bridge.ts | 4 +- .../main/review/review-service.ts | 2 +- apps/roku-dev-studio/package.json | 2 +- .../scripts/verify-review-mcp.ts | 9 +- apps/roku-dev-studio/shared/review-mcp.ts | 12 ++ docs/features.html | 2 +- docs/index.html | 2 +- docs/mcp.html | 2 +- package-lock.json | 2 +- packages/roku-dev-studio-mcp/README.md | 4 +- packages/roku-dev-studio-mcp/src/tools.ts | 12 +- packages/roku-review/git.ts | 123 ++++++++++++++---- packages/roku-review/verify-review.ts | 98 +++++++++++++- 15 files changed, 329 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7076a1d8..ff4d9621 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,17 @@ entries up to 1.3.0 are upstream's, and their links point there. ## [Unreleased] +## [1.7.2] + +### Fixed +- **Local branch reviews now judge the same diff as the PR.** A review started over MCP with `path` read the base from your own refs, so a stale `origin/develop`, or a default of `main` on a repo that integrates into `develop`, reviewed the wrong diff and reported problems in code the branch never touched. The base is now fetched fresh from GitHub into the review's own copy, and your repo is still not changed. If it can't be fetched, the local ref is used and `review_get` says so in `baseNotes`. +- **`base` defaults to the open PR's base**, then to `origin/HEAD`. A base that differs from the PR's gets a `baseNotes` line. `origin-https/develop` now means `develop` on that remote when it is this repo, and `origin/develop` no longer picks up a local branch with that name. A ref on a remote of another repo is used as it is, with a `baseNotes` line. +- **Changing the base starts clean.** Findings from a review of another base are no longer re-checked into the new one. The same goes for a review that had to use a stale copy of its base. Local reviews saved before this version start clean once, since they may have read a stale base. + +### Changed +- **A local review of a branch with an open PR reads what a PR review reads:** the description, the discussion, and CI when the commit is pushed. Settled threads stay settled, and the ticket can come from the PR. The device step stays PR-only. +- **`review_get` returns the overall comment (`reviewBody`) and the `ci` checks**, and for a local review `baseNotes` and `pullRequest`. + ## [1.7.1] ### Fixed @@ -278,7 +289,9 @@ First release of this fork. **Moving from an upstream build is a one-time manual ### Added - Initial public release: Remote Control, Device Discovery, Sideload, RALE / App Connector, Network Inspector, Action Scripts, MCP server for AI agents, and the `rds` CLI. -[Unreleased]: https://github.com/jack1590/roku-dev-studio/compare/v1.7.0...HEAD +[Unreleased]: https://github.com/jack1590/roku-dev-studio/compare/v1.7.2...HEAD +[1.7.2]: https://github.com/jack1590/roku-dev-studio/compare/v1.7.1...v1.7.2 +[1.7.1]: https://github.com/jack1590/roku-dev-studio/compare/v1.7.0...v1.7.1 [1.7.0]: https://github.com/jack1590/roku-dev-studio/compare/v1.6.3...v1.7.0 [1.6.3]: https://github.com/jack1590/roku-dev-studio/compare/v1.6.2...v1.6.3 [1.6.2]: https://github.com/jack1590/roku-dev-studio/compare/v1.6.1...v1.6.2 diff --git a/apps/roku-dev-studio/main/review/local-review.ts b/apps/roku-dev-studio/main/review/local-review.ts index 4c427ff9..e4f44837 100644 --- a/apps/roku-dev-studio/main/review/local-review.ts +++ b/apps/roku-dev-studio/main/review/local-review.ts @@ -3,19 +3,21 @@ * * - Committed work only: the review reads a copy at HEAD (see `prepareLocalCheckout`), never the * user's folder, so uncommitted edits stay out. - * - Same pipeline as a PR review, minus what needs a PR: no CI, no PR discussion, no device step. - * JIRA comes from the branch name only. + * - Same pipeline as a PR review, minus the device step. When the branch has an open PR, the review + * reads what a PR review reads: its base, description, discussion and CI. Without one, JIRA comes + * from the branch name only. * - Kept per branch, apart from PR reviews (not in the PR list, never posted). A second review of - * the same branch re-checks the open findings and reviews only the new commits, like a PR re-review. + * the same branch and base re-checks the open findings and reviews only the new commits, like a PR + * re-review. Another base starts clean. */ import { agentBackendFor } from './claude-code'; -import { budgetDiff, dismissalPromptBlock, fileInventory, lookupTicket, prepareLocalCheckout, readChangedFiles, readStandards, removeLocalCheckout, runReview, ticketPromptBlock, type ReviewResult } from 'roku-dev-studio-review'; -import { encodeJobId, parseGitHubRemote, resolveProject } from '../../shared/review-mcp'; +import { budgetDiff, ciPromptBlock, countFindings, discussionPromptBlock, dismissalPromptBlock, fetchCi, fetchDiscussion, fileInventory, lookupTicket, prepareLocalCheckout, readChangedFiles, readStandards, removeLocalCheckout, runReview, ticketPromptBlock, type ReviewResult } from 'roku-dev-studio-review'; +import { encodeJobId, LOCAL_REVIEW_VERSION, parseGitHubRemote, resolveProject, reusableLocalReview } from '../../shared/review-mcp'; import { getProjectRecord, listProjectRecords } from '../ipc/project-handlers'; import * as tokenStore from '../project-token-store'; import { loadDismissals } from './review-dismissals'; -import { reviewDataDir, wikiContext, type JobStatus } from './review-service'; +import { githubJson, reviewDataDir, wikiContext, type JobStatus } from './review-service'; const fs = require('fs'); const path = require('path'); @@ -39,14 +41,29 @@ export interface LocalSummary { } interface StoredLocal { - version: 1; + version: number; projectId: string; repo: string; branch: string; base: string; + /** What the reader should know about the base, e.g. that it could not be refreshed. */ + baseNotes?: string[]; + /** The diff used a local base that could not be refreshed: not a starting point for the next review. */ + baseStale?: boolean; + /** The open PR whose description, discussion and CI the review read. */ + pullRequest?: number; result: ReviewResult; } +interface OpenPr { + number: number; + title: string; + body: string | null; + user: { login: string } | null; + base: { ref: string }; + head: { sha: string }; +} + const jobs = new Map(); const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '_'); @@ -94,14 +111,23 @@ export async function startLocalReview(input: { path: string; base?: string; pro } /** The local review's live state, and its result once saved. */ -export function getLocalReview(projectId: string, repo: string, branch: string): { summary: LocalSummary; result?: ReviewResult; base?: string } | null { +export function getLocalReview(projectId: string, repo: string, branch: string): { summary: LocalSummary; result?: ReviewResult; base?: string; baseNotes?: string[]; pullRequest?: number } | null { const jobId = encodeJobId({ kind: 'local', projectId, repo, branch }); const job = jobs.get(jobId); if (job && job.status !== 'done') return { summary: { ...job } }; const stored = readStoredLocal(projectId, repo, branch); if (!stored) return null; const r = stored.result; - return { summary: { jobId, projectId, repo, branch, base: stored.base, status: 'done', headSha: r.headSha, counts: r.counts, finishedAt: r.finishedAt, lostLenses: r.lostLenses }, result: r, base: stored.base }; + return { summary: { jobId, projectId, repo, branch, base: stored.base, status: 'done', headSha: r.headSha, counts: r.counts, finishedAt: r.finishedAt, lostLenses: r.lostLenses }, result: r, base: stored.base, baseNotes: stored.baseNotes, pullRequest: stored.pullRequest }; +} + +/** The branch's open PRs on this repo: a failed lookup only costs the PR's context. */ +async function openPrsFor(token: string, repo: string, branch: string): Promise { + const owner = repo.split('/')[0]; + return githubJson(token, `/repos/${repo}/pulls?state=open&per_page=5&head=${encodeURIComponent(`${owner}:${branch}`)}`).catch((err: unknown) => { + mainWarn(`[reviews] could not look up the PR of ${repo}@${branch}: ${err instanceof Error ? err.message : String(err)}`); + return []; + }); } async function executeLocal(job: LocalSummary, checkoutPath: string, base?: string): Promise { @@ -109,13 +135,31 @@ async function executeLocal(job: LocalSummary, checkoutPath: string, base?: stri const project = getProjectRecord(job.projectId); if (!project) throw new Error('Project not found.'); const { apiKey: cursorKey, backend } = await agentBackendFor(project); + const token = tokenStore.getToken(project.id, 'github') ?? undefined; + + update({ detail: 'looking for an open pull request' }); + const prs = token ? await openPrsFor(token, job.repo, job.branch) : []; + const pr = prs[0]; update({ detail: 'checking out the committed work' }); - const previous = readStoredLocal(job.projectId, job.repo, job.branch); - const sinceSha = project.incrementalReview !== false && previous && !previous.result.lostLenses?.length ? previous.result.headSha : undefined; - const checkout = await prepareLocalCheckout({ path: checkoutPath, base, dataDir: reviewDataDir(), sinceSha }); + const stored = readStoredLocal(job.projectId, job.repo, job.branch); + const sinceSha = project.incrementalReview !== false && stored && !stored.result.lostLenses?.length ? stored.result.headSha : undefined; + const checkout = await prepareLocalCheckout({ + path: checkoutPath, + base, + prBase: pr?.base.ref, + dataDir: reviewDataDir(), + sinceSha, + remote: { url: `https://github.com/${job.repo}.git`, token, owns: (remoteUrl) => parseGitHubRemote(remoteUrl)?.toLowerCase() === job.repo.toLowerCase() }, + }); try { update({ base: checkout.baseRef, headSha: checkout.headSha }); + const previous = reusableLocalReview(stored, checkout.baseRef); + const baseNotes = [ + ...checkout.baseNotes, + ...(pr && pr.base.ref !== checkout.baseRef ? [`Open PR #${pr.number} targets ${pr.base.ref}, but this review diffed against ${checkout.baseRef}.`] : []), + ]; + const about = { baseNotes, baseStale: checkout.baseStale }; const full = budgetDiff(checkout.diff); const branchFiles = full.files.map((f) => f.path); const incremental = sinceSha !== undefined && checkout.sinceDiff !== undefined && previous ? { sinceSha, diff: budgetDiff(checkout.sinceDiff) } : undefined; @@ -126,8 +170,13 @@ async function executeLocal(job: LocalSummary, checkoutPath: string, base?: stri if (incremental && !changedFiles.length && previous) { // New commits touch none of the branch's own files: the earlier findings carry over. const now = Date.now(); - save(job, checkout.baseRef, { + // The findings carry over, but not what was read about the old head: its CI is not this commit's. + const findings = previous.result.findings.filter((f) => !f.ci); + save(job, checkout.baseRef, { ...about, pullRequest: previous.pullRequest }, { ...previous.result, + ci: undefined, + findings, + counts: countFindings(findings), headSha: checkout.headSha, startedAt: now, finishedAt: now, @@ -142,11 +191,16 @@ async function executeLocal(job: LocalSummary, checkoutPath: string, base?: stri const standards = await readStandards(checkout.worktree); const files = await readChangedFiles(checkout.worktree, changedFiles); - update({ detail: 'reading the JIRA ticket' }); - const ticket = await lookupTicket({ site: project.jiraSite, email: project.jiraEmail, token: tokenStore.getToken(project.id, 'jira'), pr: { title: '', body: '', branch: job.branch } }).catch((err: unknown) => ({ - ticket: null, - note: `Could not read JIRA (${err instanceof Error ? err.message : String(err)}).`, - })); + update({ detail: pr ? 'reading CI checks, the JIRA ticket and the PR discussion' : 'reading the JIRA ticket' }); + const [ticket, ci, discussion] = await Promise.all([ + lookupTicket({ site: project.jiraSite, email: project.jiraEmail, token: tokenStore.getToken(project.id, 'jira'), pr: { title: pr?.title ?? '', body: pr?.body ?? '', branch: job.branch } }).catch((err: unknown) => ({ + ticket: null, + note: `Could not read JIRA (${err instanceof Error ? err.message : String(err)}).`, + })), + // CI ran on what was pushed: the checks of another commit say nothing about this one. + pr && token && pr.head.sha === checkout.headSha ? fetchCi({ token, repo: job.repo, headSha: checkout.headSha }) : undefined, + pr && token ? fetchDiscussion({ token, repo: job.repo, number: pr.number }) : undefined, + ]); const dismissals = loadDismissals(job.repo); const { wikiBlock, wikiPages } = await wikiContext(project, job.repo, changedFiles); @@ -156,10 +210,10 @@ async function executeLocal(job: LocalSummary, checkoutPath: string, base?: stri models: { reviewer1: project.models?.reviewer1, reviewer2: project.models?.reviewer2, reviewer3: project.models?.reviewer3, judge: project.models?.judge }, ctx: { repo: job.repo, - prNumber: 0, - title: '', - body: '', - author: checkout.author, + prNumber: pr?.number ?? 0, + title: pr?.title ?? '', + body: pr?.body ?? '', + author: pr?.user?.login ?? checkout.author, baseRef: checkout.baseRef, headRef: job.branch, inventory: fileInventory(budgeted), @@ -170,8 +224,10 @@ async function executeLocal(job: LocalSummary, checkoutPath: string, base?: stri instructions: project.reviewInstructions ?? '', ...(incremental ? { sinceSha: incremental.sinceSha } : {}), ...(files.length ? { files } : {}), + ...(ci ? { ciBlock: ciPromptBlock(ci) } : {}), ticketBlock: ticketPromptBlock(ticket), dismissedBlock: dismissalPromptBlock(dismissals), + ...(discussion ? { discussionBlock: discussionPromptBlock(discussion) } : {}), prTests: [], }, worktree: checkout.worktree, @@ -179,22 +235,25 @@ async function executeLocal(job: LocalSummary, checkoutPath: string, base?: stri changedFiles, wikiPages, onPhase: (phase, detail) => update({ phase, detail }), + ...(ci ? { ci } : {}), ticket, dismissals, + ...(discussion ? { discussion } : {}), ...(incremental ? { previous: { sinceSha: incremental.sinceSha, recheck: openBefore, carry: [], prFiles: branchFiles } } : openBefore.length ? { recheck: openBefore } : {}), }); - save(job, checkout.baseRef, result); + const severalPrs = prs.length > 1 ? [`This branch has ${prs.length} open PRs; the review read #${pr.number} only.`] : []; + save(job, checkout.baseRef, { ...about, baseNotes: [...baseNotes, ...severalPrs], ...(pr ? { pullRequest: pr.number } : {}) }, result); } finally { await removeLocalCheckout(checkout.worktree); } } -function save(job: LocalSummary, base: string, result: ReviewResult): void { - const stored: StoredLocal = { version: 1, projectId: job.projectId, repo: job.repo, branch: job.branch, base, result }; +function save(job: LocalSummary, base: string, about: Pick, result: ReviewResult): void { + const stored: StoredLocal = { version: LOCAL_REVIEW_VERSION, projectId: job.projectId, repo: job.repo, branch: job.branch, base, ...about, result }; const file = storedPath(job.projectId, job.repo, job.branch); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(stored, null, 2), 'utf-8'); diff --git a/apps/roku-dev-studio/main/review/review-bridge.ts b/apps/roku-dev-studio/main/review/review-bridge.ts index 3ed2103a..37a2a7f3 100644 --- a/apps/roku-dev-studio/main/review/review-bridge.ts +++ b/apps/roku-dev-studio/main/review/review-bridge.ts @@ -38,10 +38,12 @@ function resultBody(result: ReviewResult) { headSha: result.headSha, finishedAt: result.finishedAt, summary: result.summary, + ...(result.reviewBody ? { reviewBody: result.reviewBody } : {}), counts: result.counts, ...(result.lostLenses?.length ? { lostLenses: result.lostLenses } : {}), ...(result.context.diffNotes.length ? { skippedFiles: result.context.diffNotes } : {}), ticket: result.context.ticket ? `${result.context.ticket.key}: ${result.context.ticket.summary}` : (result.context.ticketNote ?? 'none'), + ...(result.ci ? { ci: result.ci } : {}), ...(result.incremental ? { incremental: result.incremental } : {}), }; } @@ -87,7 +89,7 @@ export async function reviewRoute(pathname: string, body: Record): void { broadcast(publicSummary(job)); } -async function githubJson(token: string, url: string): Promise { +export async function githubJson(token: string, url: string): Promise { // The token is only used in this header. It is not logged and not returned. const res = await fetch(`https://api.github.com${url}`, { headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }, diff --git a/apps/roku-dev-studio/package.json b/apps/roku-dev-studio/package.json index e7218de5..e300b379 100644 --- a/apps/roku-dev-studio/package.json +++ b/apps/roku-dev-studio/package.json @@ -1,6 +1,6 @@ { "name": "roku-dev-studio", - "version": "1.7.1", + "version": "1.7.2", "description": "Roku Dev Studio - Control your Roku device over the local network", "homepage": "https://github.com/jack1590/roku-dev-studio", "main": "main.bundled.cjs", diff --git a/apps/roku-dev-studio/scripts/verify-review-mcp.ts b/apps/roku-dev-studio/scripts/verify-review-mcp.ts index 0945e0f6..63fc9e6a 100644 --- a/apps/roku-dev-studio/scripts/verify-review-mcp.ts +++ b/apps/roku-dev-studio/scripts/verify-review-mcp.ts @@ -1,6 +1,6 @@ /** Pins the review MCP helpers: job ids, project lookup, remotes, the draft view. Run with `npm run verify:review-mcp`. */ import assert from 'node:assert/strict'; -import { checkPostRequest, draftView, encodeJobId, parseGitHubRemote, parseJobId, resolveProject } from '../shared/review-mcp.js'; +import { checkPostRequest, draftView, encodeJobId, LOCAL_REVIEW_VERSION, parseGitHubRemote, parseJobId, resolveProject, reusableLocalReview } from '../shared/review-mcp.js'; assert.equal(encodeJobId({ kind: 'pr', projectId: 'acme', repo: 'o/r', number: 12 }), 'pr:acme:o/r#12'); assert.equal(encodeJobId({ kind: 'local', projectId: 'acme', repo: 'o/r', branch: 'feat/x' }), 'local:acme:o/r:feat/x'); @@ -70,4 +70,11 @@ assert.match(unknown.error, /f3/); // dismissed: not postable assert.equal((checkPostRequest({ ...base, ids: [] }) as { status: number }).status, 400); assert.deepEqual(checkPostRequest({ ...base, ids: ['f2-reply-1'] }), { ok: true, ids: ['f2-reply-1'] }); // already posted is fine: posting skips it +const stored = { version: LOCAL_REVIEW_VERSION, base: 'develop' }; +assert.equal(reusableLocalReview(stored, 'develop'), stored); +assert.equal(reusableLocalReview(stored, 'main'), null); // another base judged another diff +assert.equal(reusableLocalReview({ version: 1, base: 'develop' }, 'develop'), null); // may have read a stale base +assert.equal(reusableLocalReview(null, 'develop'), null); +assert.equal(reusableLocalReview({ ...stored, baseStale: true }, 'develop'), null); // judged a diff that may be wrong + console.log('verify-review-mcp: ok'); diff --git a/apps/roku-dev-studio/shared/review-mcp.ts b/apps/roku-dev-studio/shared/review-mcp.ts index 159bc216..45f4fb82 100644 --- a/apps/roku-dev-studio/shared/review-mcp.ts +++ b/apps/roku-dev-studio/shared/review-mcp.ts @@ -48,6 +48,18 @@ export function resolveProject(repo: string, projects: { id: string; name: strin return { ok: false, error: `${repo} is in more than one project (${matches.map((p) => `${p.name} [${p.id}]`).join(', ')}). Pass projectId.` }; } +/** Bump when stored local reviews can no longer be trusted as a starting point. */ +export const LOCAL_REVIEW_VERSION = 2; + +/** + * The stored local review a new run may build on. A review of another base judged another diff, so + * its findings must not be re-checked into this one. The same goes for a review that had to use a + * base it could not refresh, and for version 1, which could do that without saying so. + */ +export function reusableLocalReview(stored: T | null, baseRef: string): T | null { + return stored && stored.version === LOCAL_REVIEW_VERSION && stored.base === baseRef && !stored.baseStale ? stored : null; +} + export interface DraftSource { id: string; postId?: string; diff --git a/docs/features.html b/docs/features.html index da074db3..dcc04474 100644 --- a/docs/features.html +++ b/docs/features.html @@ -33,7 +33,7 @@ "description": "The full feature tour for Roku Dev Studio, the unified, single desktop app for Roku development: Remote Control, Device Discovery, Sideload Relay, Network Inspector, BrightScript Debugger, Action Scripts, AI Agents (MCP), Static Channel Analysis, and more.", "url": "https://jack1590.github.io/roku-dev-studio/features.html", "image": "https://jack1590.github.io/roku-dev-studio/images/og-image.png", - "softwareVersion": "1.7.1", + "softwareVersion": "1.7.2", "license": "https://github.com/jack1590/roku-dev-studio/blob/main/LICENSE", "downloadUrl": "https://github.com/jack1590/roku-dev-studio/releases", "author": { diff --git a/docs/index.html b/docs/index.html index 95c119ac..65e33378 100644 --- a/docs/index.html +++ b/docs/index.html @@ -33,7 +33,7 @@ "description": "The unified, single desktop application for developing and testing on Roku devices: remote control, sideloading, network inspection, an in-app BrightScript debugger, scripted automation, and an MCP server so AI agents like Cursor and Claude Desktop can drive a real device too.", "url": "https://jack1590.github.io/roku-dev-studio/", "image": "https://jack1590.github.io/roku-dev-studio/images/og-image.png", - "softwareVersion": "1.7.1", + "softwareVersion": "1.7.2", "license": "https://github.com/jack1590/roku-dev-studio/blob/main/LICENSE", "downloadUrl": "https://github.com/jack1590/roku-dev-studio/releases", "author": { diff --git a/docs/mcp.html b/docs/mcp.html index 2ced3743..9c602904 100644 --- a/docs/mcp.html +++ b/docs/mcp.html @@ -33,7 +33,7 @@ "description": "Model Context Protocol server bundled with Roku Dev Studio — lets Cursor, Claude Desktop, VS Code, and other MCP clients drive a real Roku device: remote control, sideload, App Connector, Network Inspector, and BrightScript debugging.", "url": "https://jack1590.github.io/roku-dev-studio/mcp.html", "image": "https://jack1590.github.io/roku-dev-studio/images/og-image.png", - "softwareVersion": "1.7.1", + "softwareVersion": "1.7.2", "license": "https://github.com/jack1590/roku-dev-studio/blob/main/LICENSE", "downloadUrl": "https://github.com/jack1590/roku-dev-studio/releases", "author": { diff --git a/package-lock.json b/package-lock.json index 7cd825b2..9e64de98 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,7 @@ ] }, "apps/roku-dev-studio": { - "version": "1.7.1", + "version": "1.7.2", "license": "MIT", "dependencies": { "@cursor/sdk": "1.0.37", diff --git a/packages/roku-dev-studio-mcp/README.md b/packages/roku-dev-studio-mcp/README.md index b07ffbdd..955a9582 100644 --- a/packages/roku-dev-studio-mcp/README.md +++ b/packages/roku-dev-studio-mcp/README.md @@ -137,9 +137,9 @@ The same multi-model review as Dev Studio's PR Reviews tab, for a GitHub PR or f | Tool | Live? | Notes | | --- | --- | --- | -| `review_start` | live | Start a review of `repo` + `number`, or of the branch checked out at `path` (diffed against `base`, default origin/HEAD). Returns a `jobId`. | +| `review_start` | live | Start a review of `repo` + `number`, or of the branch checked out at `path` (diffed against a fresh copy of `base`, default the open PR's base, else origin/HEAD). Returns a `jobId`. | | `review_status` | live | Progress of a review; poll about every 30 s until `done` or `failed`. | -| `review_get` | live | Findings with severity, confidence, location and the draft GitHub comment exactly as it would post, plus the review's `headSha` and `finishedAt`. | +| `review_get` | live | Findings with severity, confidence, location and the draft GitHub comment exactly as it would post, plus the overall comment, CI checks, and the review's `headSha` and `finishedAt`. | | `review_post` | live | Post the finding ids the user approved to the PR. Needs `headSha` and `finishedAt` from `review_get` and a posting key (see below). Never posts free text, local reviews, or your own PRs. | | `review_list` | live | Saved and in-progress PR reviews with their `jobId`s. | diff --git a/packages/roku-dev-studio-mcp/src/tools.ts b/packages/roku-dev-studio-mcp/src/tools.ts index c2a9c123..f1d1609a 100644 --- a/packages/roku-dev-studio-mcp/src/tools.ts +++ b/packages/roku-dev-studio-mcp/src/tools.ts @@ -1912,9 +1912,9 @@ const REVIEW_TOOLS: Tool[] = [ title: 'Start a code review', description: [ 'Start Dev Studio\'s multi-model code review of a GitHub PR (`repo` + `number`) or of the committed work on a local branch (`path`, optional `base`). Returns a `jobId` right away.', - 'Local reviews read only committed work on the branch checked out at `path` (an absolute path; pass your working directory). The diff is from the merge-base with `base` (default: the repo\'s origin/HEAD, e.g. main; pass `base` for repos that integrate into develop or similar). No device step; never posted.', + 'Local reviews read only committed work on the branch checked out at `path` (an absolute path; pass your working directory). The diff is from the merge-base with `base`, fetched fresh from GitHub into the review\'s own copy (your repo is not changed). `base` defaults to the base of the branch\'s open PR, else the repo\'s origin/HEAD, e.g. main; pass `base` for a repo that integrates into develop or similar and has no PR yet. A branch with an open PR also gets its description, discussion and CI. No device step; never posted. Check `baseNotes` in `review_get`: it says when the base could not be refreshed or differs from the PR\'s.', 'Reviews take several minutes. Call `review_status` with the `jobId` about every 30 s until `status` is `done` or `failed`; do not wait inside one call. Starting again while one runs returns the running job.', - 'Reviewing the same PR or branch again re-checks the earlier findings (fixed or still open) and reviews only the new commits.', + 'Reviewing the same PR, or the same branch against the same base, again re-checks the earlier findings (fixed or still open) and reviews only the new commits. Another base, or a base that could not be refreshed, starts clean.', 'The project (tokens, models) is found from the repo; pass `projectId` when Dev Studio says the repo is in more than one project. Needs Roku Dev Studio running.' ], inputSchema: { @@ -1923,7 +1923,7 @@ const REVIEW_TOOLS: Tool[] = [ repo: { type: 'string', description: 'GitHub repo "owner/name" (PR review).' }, number: { type: 'number', description: 'PR number (PR review).' }, path: { type: 'string', description: 'Absolute path of a local git checkout (local branch review).' }, - base: { type: 'string', description: 'Local review only: branch to diff against. Default: origin/HEAD.' }, + base: { type: 'string', description: 'Local review only: branch to diff against, fetched fresh from GitHub. Default: the base of the branch\'s open PR, else origin/HEAD.' }, projectId: { type: 'string', description: 'Dev Studio project id, when the repo is in more than one project.' } }, oneOf: [{ required: ['repo', 'number'] }, { required: ['path'] }], @@ -1959,7 +1959,7 @@ const REVIEW_TOOLS: Tool[] = [ name: 'review_get', title: 'Review findings', description: [ - 'The finished review: `summary`, `counts`, `headSha`, the JIRA ticket it was checked against, files skipped as too large or generated, lenses lost (an incomplete review), and `findings[]`.', + 'The finished review: `summary`, the overall comment `reviewBody`, `counts`, `headSha`, the JIRA ticket it was checked against, the `ci` checks it read, files skipped as too large or generated, lenses lost (an incomplete review), and `findings[]`. A local review also has `base`, `baseNotes`, and `pullRequest` when the branch has an open PR.', 'Each finding has an `id`, `status` (issue = verified problem; needs-device = needs a device to confirm; noted = minor/hedged, below the counting floors; dismissed = judged not real), `severity`, `confidence` (0-1), `file`/`line`, `detail`, and `comment`: the draft GitHub comment exactly as it would post (including edits made in Dev Studio).', '`postable` findings can be posted with `review_post` (PR reviews only). Show the user the findings and drafts and post only what they approve, passing this `headSha` and `finishedAt`.' ], @@ -1980,9 +1980,13 @@ const REVIEW_TOOLS: Tool[] = [ url: { type: 'string' }, branch: { type: 'string' }, base: { type: 'string' }, + baseNotes: { type: 'array', items: { type: 'string' } }, + pullRequest: { type: 'number' }, headSha: { type: 'string' }, finishedAt: { type: 'number' }, summary: { type: 'string' }, + reviewBody: { type: 'string' }, + ci: { type: 'object', additionalProperties: true }, counts: { type: 'object', additionalProperties: true }, lostLenses: { type: 'array', items: { type: 'string' } }, skippedFiles: { type: 'array', items: { type: 'string' } }, diff --git a/packages/roku-review/git.ts b/packages/roku-review/git.ts index 47b97f3d..d9053648 100644 --- a/packages/roku-review/git.ts +++ b/packages/roku-review/git.ts @@ -127,17 +127,33 @@ export interface LocalCheckout extends Checkout { originUrl: string; /** `git config user.name`, or "local". */ author: string; + /** What the reader should know about the base, e.g. that it could not be refreshed. */ + baseNotes: string[]; + /** This repo's remote-tracking ref had to stand in for its branch on GitHub, so the diff may be wrong. */ + baseStale: boolean; } const validRef = (ref: string) => REF_PATTERN.test(ref) && !ref.startsWith('-') && !ref.includes('..'); +/** A base fetch that hangs must not hold a review forever: it falls back to the local ref. */ +const BASE_FETCH_MS = 120_000; + /** * Checks out the committed work of a local branch for review. Only reads the user's repo (never * fetches, never adds refs or worktrees there): the review copy is a `--shared` clone at HEAD under * `dataDir`, so uncommitted edits stay out and the user can keep working. The diff is * `merge-base(base, HEAD)..HEAD`; base defaults to `origin/HEAD`. + * + * The base is fetched from `remote` into the copy, because the user's own refs can be stale or + * can come from a remote that no longer fetches. When that fails the local ref is used and `baseNotes` + * says so; `baseStale` is set when that ref is a remote-tracking copy of this repo's branch. + * + * `base` is what someone typed: `origin-https/develop` names `develop` on that remote when that ref + * exists. If the remote is another repo (`remote.owns` says no), its ref is used as is, since this + * repo's `develop` is a different branch. `prBase` is a PR's base, always a plain branch name, and + * is used when `base` is not given. */ -export async function prepareLocalCheckout(input: { path: string; base?: string; dataDir: string; signal?: AbortSignal; sinceSha?: string }): Promise { +export async function prepareLocalCheckout(input: { path: string; base?: string; prBase?: string; dataDir: string; signal?: AbortSignal; sinceSha?: string; remote?: { url: string; token?: string; owns: (remoteUrl: string) => boolean } }): Promise { const { dataDir, signal, sinceSha } = input; const run = (args: string[], cwd: string) => git(args, { cwd, signal }).then((out) => out.trim()); const top = await run(['rev-parse', '--show-toplevel'], input.path).catch(() => { @@ -151,42 +167,44 @@ export async function prepareLocalCheckout(input: { path: string; base?: string; }); const author = (await run(['config', 'user.name'], top).catch(() => '')) || 'local'; + const exists = (ref: string) => run(['rev-parse', '--verify', '--quiet', ref], top).then(() => true, () => false); + const plainBranch = (b: string) => [`refs/remotes/origin/${b}`, `refs/heads/${b}`]; + const prBase = input.prBase && validRef(input.prBase) ? input.prBase : undefined; + let baseRef: string; - let baseFull: string; + let localRefs: string[]; + let canFetch = !!input.remote; + let foreign = false; if (input.base) { if (!validRef(input.base)) throw new Error('Invalid base branch name.'); - baseRef = input.base; - const candidates = [`refs/remotes/origin/${baseRef}`, `refs/heads/${baseRef}`]; - let found: string | undefined; - for (const ref of candidates) { - if (await run(['rev-parse', '--verify', '--quiet', ref], top).then(() => true, () => false)) { - found = ref; - break; + const named = input.base; + const remoteName = (await run(['remote'], top)).split('\n').find((r) => r && named.startsWith(`${r}/`)); + if (remoteName && (await exists(`refs/remotes/${named}`))) { + localRefs = [`refs/remotes/${named}`]; + const remoteUrl = await run(['remote', 'get-url', remoteName], top).catch(() => ''); + if (input.remote?.owns(remoteUrl)) { + baseRef = named.slice(remoteName.length + 1); + } else { + baseRef = named; + canFetch = false; + foreign = !!input.remote; } + } else { + baseRef = named; + localRefs = plainBranch(named); } - if (!found) throw new Error(`Base branch "${baseRef}" not found locally or on origin.`); - baseFull = found; + } else if (prBase) { + baseRef = prBase; + localRefs = plainBranch(prBase); } else { const head = await run(['symbolic-ref', 'refs/remotes/origin/HEAD'], top).catch(() => { throw new Error('Could not tell the base branch (origin/HEAD is not set). Pass base, e.g. "develop".'); }); - baseFull = head; baseRef = head.replace(/^refs\/remotes\/origin\//, ''); + localRefs = [head]; } const headSha = await run(['rev-parse', 'HEAD'], top); - const mergeBase = await run(['merge-base', baseFull, headSha], top); - if (mergeBase === headSha) throw new Error(`Nothing to review: no commits on ${branch} since ${baseRef}.`); - const diff = await git(['diff', '--no-color', '--find-renames', mergeBase, headSha], { cwd: top, signal }); - - let sinceDiff: string | undefined; - if (sinceSha && /^[0-9a-f]{40}$/.test(sinceSha) && sinceSha !== headSha) { - const ancestor = await run(['merge-base', '--is-ancestor', sinceSha, headSha], top).then(() => true, () => false); - if (ancestor) { - const files = (await run(['diff', '--name-only', mergeBase, headSha], top)).split('\n').filter(Boolean); - sinceDiff = files.length ? await git(['diff', '--no-color', '--find-renames', sinceSha, headSha, '--', ...files], { cwd: top, signal }) : ''; - } - } // Folder name plus a short hash of the path: two checkouts with the same folder name never share a copy. const name = `${path.basename(top).replace(/[^A-Za-z0-9_.-]/g, '_')}-${createHash('sha1').update(top).digest('hex').slice(0, 8)}`; @@ -194,10 +212,59 @@ export async function prepareLocalCheckout(input: { path: string; base?: string; await fs.rm(worktree, { recursive: true, force: true }); await fs.mkdir(path.dirname(worktree), { recursive: true }); await git(['clone', '--quiet', '--shared', '--no-checkout', top, worktree], { signal }); - await git(['checkout', '--quiet', '--detach', headSha], { cwd: worktree, signal }); - await fs.mkdir(path.join(worktree, REVIEW_DIR), { recursive: true }); - await fs.writeFile(path.join(worktree, REVIEW_DIR, 'pr.diff'), diff, 'utf-8'); - return { worktree, headSha, baseRef, diff, sinceDiff, branch, originUrl, author }; + try { + await git(['checkout', '--quiet', '--detach', headSha], { cwd: worktree, signal }); + + const baseNotes: string[] = []; + const fetchedRef = 'refs/rds/base'; + const fetched = input.remote && canFetch + ? await git(['fetch', '--force', '--no-tags', input.remote.url, `+refs/heads/${baseRef}:${fetchedRef}`], { cwd: worktree, token: input.remote.token, signal: signal ?? AbortSignal.timeout(BASE_FETCH_MS) }).then( + () => true, + () => false + ) + : false; + let baseSha: string; + let baseStale = false; + if (fetched) { + baseSha = await run(['rev-parse', fetchedRef], worktree); + } else { + let found: string | undefined; + for (const ref of localRefs) { + if (await exists(ref)) { + found = ref; + break; + } + } + if (!found) throw new Error(`Base branch "${input.base ?? baseRef}" not found locally or on origin.`); + baseSha = await run(['rev-parse', found], top); + if (found.startsWith('refs/heads/')) { + baseNotes.push(`${baseRef} is not on GitHub or could not be fetched, so the diff uses the local branch ${found} (${baseSha.slice(0, 7)}).`); + } else { + baseNotes.push(`${baseRef} could not be refreshed from GitHub, so the diff uses the local ${found} (${baseSha.slice(0, 7)}), which may be stale.`); + baseStale = !foreign; + } + } + + const mergeBase = await run(['merge-base', baseSha, headSha], worktree); + if (mergeBase === headSha) throw new Error(`Nothing to review: no commits on ${branch} since ${baseRef}.`); + const diff = await git(['diff', '--no-color', '--find-renames', mergeBase, headSha], { cwd: worktree, signal }); + + let sinceDiff: string | undefined; + if (sinceSha && /^[0-9a-f]{40}$/.test(sinceSha) && sinceSha !== headSha) { + const ancestor = await run(['merge-base', '--is-ancestor', sinceSha, headSha], worktree).then(() => true, () => false); + if (ancestor) { + const files = (await run(['diff', '--name-only', mergeBase, headSha], worktree)).split('\n').filter(Boolean); + sinceDiff = files.length ? await git(['diff', '--no-color', '--find-renames', sinceSha, headSha, '--', ...files], { cwd: worktree, signal }) : ''; + } + } + + await fs.mkdir(path.join(worktree, REVIEW_DIR), { recursive: true }); + await fs.writeFile(path.join(worktree, REVIEW_DIR, 'pr.diff'), diff, 'utf-8'); + return { worktree, headSha, baseRef, baseNotes, baseStale, diff, sinceDiff, branch, originUrl, author }; + } catch (err) { + await removeLocalCheckout(worktree); + throw err; + } } /** Removes a local review copy; errors are ignored. */ diff --git a/packages/roku-review/verify-review.ts b/packages/roku-review/verify-review.ts index c33fdc80..1e7a12a6 100644 --- a/packages/roku-review/verify-review.ts +++ b/packages/roku-review/verify-review.ts @@ -18,7 +18,7 @@ import { claudeArgs, parseClaudeOutput, toAgentOutput } from './claude-cli'; import { prepareLocalCheckout, removeLocalCheckout } from './git'; import { execFileSync } from 'node:child_process'; import { ciFindings, ciInfraFailures, ciPromptBlock, isCodeAnnotation } from './ci'; -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs'; +import { mkdtempSync, mkdirSync, readdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -269,6 +269,102 @@ async function localCheckoutChecks(): Promise { await removeLocalCheckout(co2.worktree); assert.equal(existsSync(co2.worktree), false); + // The true base: fetched into the review copy, whatever state the user's own refs are in. + const up = join(root, 'stale'); + const upstream = join(root, 'upstream.git'); + g(root, 'init', '-q', '--bare', '-b', 'main', upstream); + g(root, 'clone', '-q', upstream, up); + g(up, 'checkout', '-q', '-b', 'develop'); + commit(up, 'base1.brs', '1\n'); + g(up, 'push', '-q', 'origin', 'develop'); + const staleRef = g(up, 'rev-parse', 'refs/remotes/origin/develop'); + const fresher = join(root, 'fresher'); + g(root, 'clone', '-q', '-b', 'develop', upstream, fresher); + commit(fresher, 'moved.brs', 'moved on\n'); + g(fresher, 'push', '-q', 'origin', 'develop'); + // The user's branch merged the newer base, while their origin/develop never moved. + g(up, 'remote', 'add', 'live', upstream); + g(up, 'fetch', '-q', 'live'); + assert.equal(g(up, 'rev-parse', 'refs/remotes/origin/develop'), staleRef); + g(up, 'checkout', '-q', '-b', 'feat/y', 'live/develop'); + commit(up, 'mine.brs', 'mine\n'); + g(up, 'branch', 'origin/develop', staleRef); // a stray local branch named like a remote ref + const refsBefore = g(up, 'for-each-ref'); + const remote = { url: upstream, owns: (u: string) => u === upstream }; + + const fresh = await prepareLocalCheckout({ path: up, base: 'develop', dataDir, remote }); + assert.equal(fresh.baseRef, 'develop'); + assert.match(fresh.diff, /mine\.brs/); + assert.doesNotMatch(fresh.diff, /moved\.brs/, 'a stale origin ref must not widen the diff'); + assert.deepEqual(fresh.baseNotes, []); + assert.equal(g(up, 'for-each-ref'), refsBefore, "the user's refs are untouched"); + + const noFetch = await prepareLocalCheckout({ path: up, base: 'develop', dataDir }); + assert.match(noFetch.diff, /moved\.brs/, 'without a remote the local ref is all there is'); + assert.match(noFetch.baseNotes.join(), /could not be refreshed.*may be stale/); + + const failed = await prepareLocalCheckout({ path: up, base: 'develop', dataDir, remote: { url: join(root, 'missing.git'), owns: () => false } }); + assert.match(failed.baseNotes.join(), /could not be refreshed.*may be stale/); + + for (const named of ['origin/develop', 'live/develop']) { + const co3 = await prepareLocalCheckout({ path: up, base: named, dataDir, remote }); + assert.equal(co3.baseRef, 'develop', `${named} names the branch on a remote`); + assert.doesNotMatch(co3.diff, /moved\.brs/); + } + assert.doesNotMatch((await prepareLocalCheckout({ path: up, base: 'live/develop', dataDir })).diff, /moved\.brs/, 'a named remote ref is used as is'); + assert.match((await prepareLocalCheckout({ path: up, base: 'origin/develop', dataDir })).diff, /moved\.brs/); + assert.equal( + (await prepareLocalCheckout({ path: up, base: 'origin/develop', dataDir })).diff, + g(up, 'diff', '--no-color', '--find-renames', g(up, 'merge-base', 'refs/remotes/origin/develop', 'HEAD'), 'HEAD') + '\n', + 'origin/develop is the remote ref, not the stray local branch' + ); + await assert.rejects(prepareLocalCheckout({ path: up, base: 'nowhere', dataDir, remote }), /"nowhere" not found/); + assert.equal((await prepareLocalCheckout({ path: up, base: 'develop', dataDir, remote })).baseStale, false); + assert.equal(noFetch.baseStale, true, 'a base that could not be refreshed is marked, not only described'); + + // A remote of another repo: its develop is not this repo's, so it is neither fetched nor renamed. + const forkUp = join(root, 'canonical.git'); + g(root, 'init', '-q', '--bare', '-b', 'develop', forkUp); + g(up, 'push', '-q', forkUp, 'refs/remotes/live/develop:refs/heads/develop'); + const canon = join(root, 'canonical'); + g(root, 'clone', '-q', '-b', 'develop', forkUp, canon); + commit(canon, 'canon-only.brs', 'canon\n'); + g(canon, 'push', '-q', 'origin', 'develop'); + g(up, 'remote', 'add', 'other', forkUp); + g(up, 'fetch', '-q', 'other'); + const onOther = await prepareLocalCheckout({ path: up, base: 'other/develop', dataDir, remote }); + assert.equal(onOther.baseRef, 'other/develop', 'kept apart from this repo\'s develop'); + assert.match(onOther.baseNotes.join(), /may be stale/); + assert.equal(onOther.baseStale, false, 'the exact ref the user named: a re-review may build on it'); + assert.doesNotMatch(onOther.diff, /moved\.brs/, 'the ref the user named, not develop from another repo'); + + // A branch whose first segment equals a remote's name is a branch, not that remote's ref. + g(up, 'push', '-q', upstream, 'refs/remotes/live/develop:refs/heads/other/wip'); + const onSlash = await prepareLocalCheckout({ path: up, base: 'other/wip', dataDir, remote }); + assert.equal(onSlash.baseRef, 'other/wip'); + assert.deepEqual(onSlash.baseNotes, []); + assert.doesNotMatch(onSlash.diff, /moved\.brs/); + + // A PR's base is always a plain branch name, even when it looks like a remote's ref. + g(up, 'push', '-q', upstream, 'refs/remotes/live/develop:refs/heads/live/develop-old'); + g(up, 'fetch', '-q', 'live'); + const prBased = await prepareLocalCheckout({ path: up, prBase: 'live/develop-old', dataDir, remote }); + assert.equal(prBased.baseRef, 'live/develop-old'); + assert.deepEqual(prBased.baseNotes, []); + assert.equal((await prepareLocalCheckout({ path: up, prBase: 'develop', base: 'stack-parent-missing', dataDir, remote }).catch((e: Error) => e.message)), 'Base branch "stack-parent-missing" not found locally or on origin.', 'an explicit base wins over the PR'); + g(up, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/develop'); + assert.equal((await prepareLocalCheckout({ path: up, prBase: 'release/1.0+hf', dataDir, remote })).baseRef, 'develop', 'a PR base git refs here cannot name falls back to the default'); + g(up, 'branch', 'stack-parent', 'live/develop'); + const onStack = await prepareLocalCheckout({ path: up, base: 'stack-parent', dataDir, remote }); + assert.equal(onStack.baseRef, 'stack-parent', 'a branch only on this machine still works as a base'); + assert.equal(onStack.baseStale, false, 'there is no fresher copy of a local branch'); + assert.doesNotMatch(onStack.baseNotes.join(), /may be stale/); + assert.match(onStack.baseNotes.join(), /local branch refs\/heads\/stack-parent/); + assert.doesNotMatch(onStack.diff, /moved\.brs/); + g(up, 'checkout', '-q', 'stack-parent'); + await assert.rejects(prepareLocalCheckout({ path: up, base: 'live/develop', dataDir, remote }), /Nothing to review/); + assert.equal(readdirSync(join(dataDir, 'local')).some((n) => n.includes('stack-parent')), false, 'a refused review leaves no copy behind'); + const notRepo = join(root, 'plain'); mkdirSync(notRepo); await assert.rejects(prepareLocalCheckout({ path: notRepo, dataDir }), /not a git checkout/);