Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(cli): link pull requests to acceptances with lh acceptance link-pr (#20427)

Arvin Xu95d94decb4d1
diff --git a/.agents/skills/pr/SKILL.md b/.agents/skills/pr/SKILL.md
index 475240f8de8..ef6167bad0d 100644
--- a/.agents/skills/pr/SKILL.md
+++ b/.agents/skills/pr/SKILL.md
@@ -62,7 +62,17 @@ A feature or fix needs a published acceptance round before the PR is opened (AGE
- Follow the source-label, privacy, and AI assistance rules in **PR Template** below when creating or updating a PR. Do not request prompt disclosure or block the normal PR workflow waiting for consent to publish a conversation.
- Write the body to a temporary file and use `--body-file` to preserve formatting.
-### 7. Open in browser
+### 7. Link the PR to its acceptance
+
+An acceptance round published before the PR existed carries no PR, and reusing that round is correct, so nothing else ever tells the acceptance about the PR. Right after `gh pr create`, record the link through the production publish environment. If step 1 reused a known acceptance and skipped the lookup, `publish_lh` is not defined yet: run [Publish auth preflight](../../acceptance/PROCESS.md#publish-auth-preflight) now to define and verify it.
+
+```bash
+publish_lh acceptance link-pr <acceptanceId> "$(gh pr view --json url --jq .url)"
+```
+
+Do this for each PR in a stack; they share one acceptance. Skip it when the PR states that no acceptance is needed. A later round links itself only when its `result.json` names the PR (`pullRequest`); a PR inferred from the branch is recorded on the round but never linked. If the installed CLI lacks `link-pr`, or the server rejects it as unknown, mention that in the reply instead of retrying.
+
+### 8. Open in browser
`gh pr view --web`
diff --git a/apps/cli/src/commands/acceptanceRun.test.ts b/apps/cli/src/commands/acceptanceRun.test.ts
index 16fa650a50a..217eb463569 100644
--- a/apps/cli/src/commands/acceptanceRun.test.ts
+++ b/apps/cli/src/commands/acceptanceRun.test.ts
@@ -13,11 +13,17 @@ import { resolveServerUrl } from '../settings';
import { log } from '../utils/logger';
import { uploadLocalFile } from '../utils/uploadLocalFile';
import { attachAcceptanceRunCommands } from './acceptanceRun';
+import type * as VerifyHelpers from './verifyHelpers';
+import { pullRequestFromBranch } from './verifyHelpers';
vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));
vi.mock('../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));
vi.mock('../settings', () => ({ resolveServerUrl: vi.fn() }));
vi.mock('../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));
+vi.mock('./verifyHelpers', async (importOriginal) => ({
+ ...(await importOriginal<typeof VerifyHelpers>()),
+ pullRequestFromBranch: vi.fn(),
+}));
describe('acceptance publication with missing evidence', () => {
const client = {
@@ -25,6 +31,7 @@ describe('acceptance publication with missing evidence', () => {
attachRun: { mutate: vi.fn() },
ensure: { mutate: vi.fn() },
getBundle: { query: vi.fn() },
+ linkPullRequest: { mutate: vi.fn() },
},
verify: {
createRun: { mutate: vi.fn() },
@@ -131,6 +138,60 @@ describe('acceptance publication with missing evidence', () => {
expect(await readFile(path.join(dir, 'result.json'), 'utf8')).toBe(original);
});
+ it('links the reported pull request to the acceptance, and survives a failed link', async () => {
+ const pullRequest = {
+ number: 20171,
+ title: 'Durable waits',
+ url: 'https://github.com/lobehub/lobehub/pull/20171',
+ };
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [
+ { evidence: ['output.txt'], id: 'screen', name: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ', status: 'passed' },
+ ],
+ plan: [{ id: 'screen', requiredEvidence: ['text'], title: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ' }],
+ pullRequest,
+ summary: { passed: 1, total: 1, verdict: 'passed' },
+ title: 'ε€„η†η»“ζžœε±•η€Ί',
+ }),
+ );
+ client.acceptance.linkPullRequest.mutate.mockRejectedValue(new Error('CONFLICT'));
+
+ await run('ingest', dir, '--json');
+
+ expect(client.acceptance.linkPullRequest.mutate).toHaveBeenCalledExactlyOnceWith({
+ id: 'acceptance-1',
+ title: 'Durable waits',
+ url: pullRequest.url,
+ });
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('not linked'));
+ expect(result()).toMatchObject({ publicationStatus: 'complete', pullRequest });
+ });
+
+ it('keeps a branch-inferred PR as round provenance without linking it to the acceptance', async () => {
+ const inferred = { number: 7, url: 'https://github.com/lobehub/lobehub/pull/7' };
+ vi.mocked(pullRequestFromBranch).mockReturnValue(inferred);
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ branch: 'canary',
+ cases: [
+ { evidence: ['output.txt'], id: 'screen', name: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ', status: 'passed' },
+ ],
+ plan: [{ id: 'screen', requiredEvidence: ['text'], title: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ' }],
+ summary: { passed: 1, total: 1, verdict: 'passed' },
+ title: 'ε€„η†η»“ζžœε±•η€Ί',
+ }),
+ );
+
+ await run('ingest', dir, '--json');
+
+ expect(pullRequestFromBranch).toHaveBeenCalledWith('canary');
+ expect(result()).toMatchObject({ pullRequest: inferred });
+ expect(client.acceptance.linkPullRequest.mutate).not.toHaveBeenCalled();
+ });
+
it('does not downgrade a pass when only an optional medium failed', async () => {
vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));
await report(['text'], ['output.txt', "screen's shot.png"]);
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.ts
index 2494348b178..56725de1e21 100644
--- a/apps/cli/src/commands/acceptanceRun.ts
+++ b/apps/cli/src/commands/acceptanceRun.ts
@@ -654,12 +654,16 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
// the PR link after the ingest, whatever the scenario resolved to.
let context: Record<string, unknown> | undefined;
let pullRequest: ReturnType<typeof pullRequestFromResult>;
+ // Only a PR the report names is a delivery claim; the branch lookup below is
+ // best-effort provenance and may find a long-lived branch's unrelated PR.
+ let authoredPullRequest: ReturnType<typeof pullRequestFromResult>;
if (scenario === 'coding') {
const branch = typeof result.branch === 'string' ? result.branch : undefined;
const surfaces = surfacesFromResult(result);
// An authored PR wins; otherwise ask `gh` what the branch's PR is, so the
// report links to it without the author having to remember the field.
- pullRequest = pullRequestFromResult(result) ?? pullRequestFromBranch(branch);
+ authoredPullRequest = pullRequestFromResult(result);
+ pullRequest = authoredPullRequest ?? pullRequestFromBranch(branch);
const contextEntries = Object.entries({
branch,
commit: typeof result.commit === 'string' ? result.commit : undefined,
@@ -988,6 +992,24 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
}
}
+ // 5. Link the PR to the acceptance itself. The round's context is a
+ // snapshot of this ingest; the acceptance is what the PR delivers, and
+ // the page reads its PRs from there. Only the report's own PR is linked:
+ // a branch-inferred one stays round provenance. Never fatal: an older
+ // server lacks the procedure, and the round itself is the deliverable.
+ if (authoredPullRequest?.url) {
+ try {
+ await client.acceptance.linkPullRequest.mutate({
+ id: acceptanceId,
+ title:
+ typeof authoredPullRequest.title === 'string' ? authoredPullRequest.title : undefined,
+ url: String(authoredPullRequest.url),
+ });
+ } catch (e) {
+ log.warn(`pull request not linked to the acceptance: ${String(e)}`);
+ }
+ }
+
// A case with no matching plan item means the run checked something it
// never planned β€” worth saying out loud, but not a failure. Only
// meaningful against a plan that actually names something: with no plan
diff --git a/apps/cli/src/commands/verifyAcceptance.linkPr.test.ts b/apps/cli/src/commands/verifyAcceptance.linkPr.test.ts
new file mode 100644
index 00000000000..35ef7b76e40
--- /dev/null
+++ b/apps/cli/src/commands/verifyAcceptance.linkPr.test.ts
@@ -0,0 +1,64 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTrpcClient } from '../api/client';
+import { registerAcceptanceCommands } from './verifyAcceptance';
+
+vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));
+
+const acceptanceId = '598ebab1-74a3-4a7f-9bcb-9bfa71c654cb';
+const prUrl = 'https://github.com/lobehub/lobehub/pull/20171';
+const linkPullRequest = vi.fn();
+const unlinkPullRequest = vi.fn();
+let output: ReturnType<typeof vi.spyOn>;
+
+const run = async (args: string[]) => {
+ const program = new Command().exitOverride().configureOutput({ writeErr: () => {} });
+ registerAcceptanceCommands(program);
+ await program.parseAsync(['node', 'lh', 'acceptance', ...args]);
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ output = vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.mocked(getTrpcClient).mockResolvedValue({
+ acceptance: {
+ linkPullRequest: { mutate: linkPullRequest },
+ unlinkPullRequest: { mutate: unlinkPullRequest },
+ },
+ } as unknown as Awaited<ReturnType<typeof getTrpcClient>>);
+ linkPullRequest.mockResolvedValue({ number: 20171, repoFullName: 'lobehub/lobehub', url: prUrl });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('acceptance link-pr', () => {
+ it('links a pull request to the acceptance, not to a round', async () => {
+ await run(['link-pr', acceptanceId, prUrl, '--title', 'Durable waits']);
+
+ expect(linkPullRequest).toHaveBeenCalledExactlyOnceWith({
+ id: acceptanceId,
+ title: 'Durable waits',
+ url: prUrl,
+ });
+ expect(String(output.mock.calls.at(-1)?.[0])).toContain('lobehub/lobehub#20171');
+ });
+
+ it('unlinks by the URL the user has', async () => {
+ await run(['link-pr', acceptanceId, `${prUrl}/files`, '--unlink']);
+
+ expect(unlinkPullRequest).toHaveBeenCalledExactlyOnceWith({
+ id: acceptanceId,
+ url: `${prUrl}/files`,
+ });
+ expect(linkPullRequest).not.toHaveBeenCalled();
+ });
+
+ it('honors a JSON field selector when unlinking', async () => {
+ await run(['link-pr', acceptanceId, prUrl, '--unlink', '--json', 'url']);
+
+ expect(JSON.parse(String(output.mock.calls.at(-1)?.[0]))).toEqual({ url: prUrl });
+ });
+});
diff --git a/apps/cli/src/commands/verifyAcceptance.ts b/apps/cli/src/commands/verifyAcceptance.ts
index 4336df76699..74259a514cd 100644
--- a/apps/cli/src/commands/verifyAcceptance.ts
+++ b/apps/cli/src/commands/verifyAcceptance.ts
@@ -469,6 +469,51 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
},
);
+ acceptance
+ .command('link-pr <idOrSubject> <url>')
+ .description(
+ 'Record that a pull request delivers this acceptance (works for PRs opened after the last round)',
+ )
+ .option('--title <text>', 'Pull request title, until the provider reports it')
+ .option('--unlink', 'Remove the link instead')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (
+ idOrSubject: string,
+ url: string,
+ options: { json?: boolean | string; title?: string; unlink?: boolean },
+ ) => {
+ const id = await resolveAcceptanceId(idOrSubject);
+ const client = await getTrpcClient();
+
+ if (options.unlink) {
+ await client.acceptance.unlinkPullRequest.mutate({ id, url });
+ if (options.json !== undefined) {
+ outputJson(
+ { unlinked: true, url },
+ typeof options.json === 'string' ? options.json : undefined,
+ );
+ return;
+ }
+ console.log(`${pc.green('βœ“')} Unlinked ${url}`);
+ return;
+ }
+
+ const linked = await client.acceptance.linkPullRequest.mutate({
+ id,
+ title: options.title,
+ url,
+ });
+ if (options.json !== undefined) {
+ outputJson(linked, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(
+ `${pc.green('βœ“')} Linked ${linked.repoFullName}#${linked.number} to acceptance ${id}`,
+ );
+ },
+ );
+
acceptance
.command('accept <idOrSubject>')
.description('Accept the delivery β€” the terminal user decision that closes the acceptance')