Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
109 changes: 84 additions & 25 deletions apps/roku-dev-studio/main/review/local-review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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<string, LocalSummary>();

const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '_');
Expand Down Expand Up @@ -94,28 +111,55 @@ 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<OpenPr[]> {
const owner = repo.split('/')[0];
return githubJson<OpenPr[]>(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<void> {
const update = (patch: Partial<LocalSummary>) => Object.assign(job, patch);
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;
Expand All @@ -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,
Expand All @@ -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);

Expand All @@ -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),
Expand All @@ -170,31 +224,36 @@ 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,
headSha: checkout.headSha,
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<StoredLocal, 'baseNotes' | 'baseStale' | 'pullRequest'>, 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');
Expand Down
4 changes: 3 additions & 1 deletion apps/roku-dev-studio/main/review/review-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } : {}),
};
}
Expand Down Expand Up @@ -87,7 +89,7 @@ export async function reviewRoute(pathname: string, body: Record<string, unknown
if (!local.result) return { status: 409, body: { error: `The review is ${local.summary.status}, not done yet.`, status: statusBody(jobId, local.summary) } };
return {
status: 200,
body: { jobId, kind: 'local', repo: id.repo, branch: id.branch, base: local.base, ...resultBody(local.result), findings: draftView(local.result, { edits: {}, posted: {} }) },
body: { jobId, kind: 'local', repo: id.repo, branch: id.branch, base: local.base, ...(local.baseNotes?.length ? { baseNotes: local.baseNotes } : {}), ...(local.pullRequest ? { pullRequest: local.pullRequest } : {}), ...resultBody(local.result), findings: draftView(local.result, { edits: {}, posted: {} }) },
};
}

Expand Down
2 changes: 1 addition & 1 deletion apps/roku-dev-studio/main/review/review-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ function update(job: Job, patch: Partial<ReviewSummary>): void {
broadcast(publicSummary(job));
}

async function githubJson<T>(token: string, url: string): Promise<T> {
export async function githubJson<T>(token: string, url: string): Promise<T> {
// 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' },
Expand Down
2 changes: 1 addition & 1 deletion apps/roku-dev-studio/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
9 changes: 8 additions & 1 deletion apps/roku-dev-studio/scripts/verify-review-mcp.ts
Original file line number Diff line number Diff line change
@@ -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');
Expand Down Expand Up @@ -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');
12 changes: 12 additions & 0 deletions apps/roku-dev-studio/shared/review-mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T extends { version: number; base: string; baseStale?: boolean }>(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;
Expand Down
Loading
Loading