diff --git a/src/support/publicationVersionLabel.test.ts b/src/support/publicationVersionLabel.test.ts new file mode 100644 index 00000000..b208d26f --- /dev/null +++ b/src/support/publicationVersionLabel.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { planVersionLabel, versionLabelForTitle } from './publicationVersionLabel.js'; + +const ALL = new Set(['version:major', 'version:minor', 'version:patch', 'version:skip']); + +describe('versionLabelForTitle (AGT-4269)', () => { + it.each([ + ['[test] cover the parser', 'version:skip'], + ['[CI] openswarm PRs carry no label', 'version:skip'], + ['[docs] runbook', 'version:skip'], + ['[chore] bump deps', 'version:skip'], + ['[BUG] crash on empty input', 'version:patch'], + ['[fix] wrong total', 'version:patch'], + ['[perf] cache the index', 'version:patch'], + ['[feature] export to CSV', 'version:minor'], + ['[FEAT] export to CSV', 'version:minor'], + ['fix: wrong total', 'version:patch'], + ['ci(gate): loc-gate fails instead of warning', 'version:skip'], + ['chore(hooks): versioned pre-commit hook', 'version:skip'], + ['feat(desktop): stop and retry', 'version:minor'], + ['perf(index): cache', 'version:patch'], + ['AGT-4269: [CI] label PRs', 'version:skip'], + ['[AGT-4269] fix: label PRs', 'version:patch'], + ])('%s -> %s', (title, label) => { + expect(versionLabelForTitle(title).label).toBe(label); + }); + + it.each([ + 'refactor(support): split dashboardHtml.ts', + 'Improve the dashboard', + '[Improvement] activity timeline', + 'feat!: drop the v1 API', + '', + ])('leaves %j unlabelled with a reason', (title) => { + const decision = versionLabelForTitle(title); + expect(decision.label).toBeNull(); + expect(decision.label === null && decision.reason.length > 0).toBe(true); + }); +}); + +describe('planVersionLabel', () => { + it('adds exactly one --label when the repository defines it', () => { + expect(planVersionLabel('[BUG] x', ALL)).toEqual({ createArgs: ['--label', 'version:patch'], bodySection: '' }); + }); + + it('opens unlabelled with the reason in the body when the title does not decide', () => { + const plan = planVersionLabel('refactor: split module', ALL); + expect(plan.createArgs).toEqual([]); + expect(plan.bodySection).toContain('## Version label'); + expect(plan.bodySection).toContain('`refactor`'); + }); + + it('touches nothing in a repository without version labels', () => { + expect(planVersionLabel('[BUG] x', new Set())).toEqual({ createArgs: [], bodySection: '' }); + expect(planVersionLabel('refactor: y', new Set())).toEqual({ createArgs: [], bodySection: '' }); + }); + + it('never passes a label the repository lacks (gh would fail the create)', () => { + const plan = planVersionLabel('[feature] x', new Set(['version:patch', 'version:skip'])); + expect(plan.createArgs).toEqual([]); + expect(plan.bodySection).toContain('does not define'); + }); +}); diff --git a/src/support/publicationVersionLabel.ts b/src/support/publicationVersionLabel.ts new file mode 100644 index 00000000..3587de01 --- /dev/null +++ b/src/support/publicationVersionLabel.ts @@ -0,0 +1,116 @@ +// ============================================ +// OpenSwarm — version:* label on the PRs it opens (AGT-4269) +// ============================================ +// +// vega-agent gates every PR on exactly one `version:*` label (version-label.yml): +// a PR merged without one bumps nothing, so the release never fires and the +// change silently never reaches the installed app. On 2026-09-10 all five open +// swarm PRs failed that check with `LABELS: []` — not a human slip, OpenSwarm +// simply never labelled. A check that is red by default hides the real failures +// behind it (#690's type error and #691's regression were buried that way). +// +// The label is derived from the title's kind prefix. When the kind does not +// decide it, the PR opens unlabelled and the body says why: a wrong label is +// worse than none, because a human reviewing a red check will pick one, while a +// wrong green one is never looked at again. +// +// Repositories that do not define the version:* labels are left alone — `gh pr +// create --label` with an unknown label fails the whole create. + +import { gh } from './ghPullRequests.js'; + +export type VersionLabel = 'version:skip' | 'version:patch' | 'version:minor'; + +const KIND_TO_LABEL: Readonly> = { + test: 'version:skip', + tests: 'version:skip', + ci: 'version:skip', + docs: 'version:skip', + doc: 'version:skip', + chore: 'version:skip', + bug: 'version:patch', + bugfix: 'version:patch', + fix: 'version:patch', + hotfix: 'version:patch', + perf: 'version:patch', + feature: 'version:minor', + feat: 'version:minor', +}; + +// Leading issue identifiers a caller may prepend: "AGT-123:", "[AGT-123]", "(AGT-123)". +const LEADING_ISSUE_ID_RE = /^\s*(?:\[[A-Z][A-Z0-9]*-\d+\]|\([A-Z][A-Z0-9]*-\d+\)|[A-Z][A-Z0-9]*-\d+:?)\s*/; +// "[CI] …", "[BUG] …" +const BRACKET_KIND_RE = /^\s*\[([A-Za-z]+)\]/; +// "fix: …", "ci(gate): …", "feat!: …" — the "!" (breaking) is captured so it is not mapped. +const CONVENTIONAL_KIND_RE = /^\s*([A-Za-z]+)(?:\([^)]*\))?(!?):/; + +export type VersionLabelDecision = + | { label: VersionLabel; kind: string } + | { label: null; reason: string }; + +/** Decide the version:* label from a PR/issue title. Pure. */ +export function versionLabelForTitle(title: string): VersionLabelDecision { + let rest = title; + // Strip any number of leading issue identifiers. + for (let i = 0; i < 3; i++) { + const stripped = rest.replace(LEADING_ISSUE_ID_RE, ''); + if (stripped === rest) break; + rest = stripped; + } + + const bracket = BRACKET_KIND_RE.exec(rest); + const conventional = bracket ? null : CONVENTIONAL_KIND_RE.exec(rest); + const rawKind = bracket?.[1] ?? conventional?.[1]; + if (!rawKind) { + return { label: null, reason: 'the title has no kind prefix (e.g. `[BUG]`, `fix:`, `feat(scope):`)' }; + } + const kind = rawKind.toLowerCase(); + if (conventional?.[2] === '!') { + return { label: null, reason: `\`${rawKind}!\` marks a breaking change — major or minor is a release decision` }; + } + const label = KIND_TO_LABEL[kind]; + if (!label) { + return { label: null, reason: `the kind \`${rawKind}\` does not decide whether this ships (skip, patch or minor)` }; + } + return { label, kind }; +} + +/** + * The version:* labels the repository defines. Empty when it defines none or + * the lookup fails — either way the PR is opened exactly as before. + */ +export async function repoVersionLabels(cwd: string): Promise> { + try { + const out = await gh(cwd, 'label', 'list', '--search', 'version:', '--limit', '100', '--json', 'name', '--jq', '.[].name'); + return new Set(out.split('\n').map((s) => s.trim()).filter((s) => s.startsWith('version:'))); + } catch (e) { + console.warn('[Worktree] version label lookup failed — opening the PR without one:', e); + return new Set(); + } +} + +export interface VersionLabelPlan { + /** Extra `gh pr create` arguments (`--label …`), possibly empty. */ + createArgs: string[]; + /** PR body section explaining a missing label, or ''. */ + bodySection: string; +} + +/** Combine the title decision with what the repository supports. Pure. */ +export function planVersionLabel(title: string, available: ReadonlySet): VersionLabelPlan { + if (available.size === 0) return { createArgs: [], bodySection: '' }; + const decision = versionLabelForTitle(title); + if (decision.label !== null && available.has(decision.label)) { + return { createArgs: ['--label', decision.label], bodySection: '' }; + } + const reason = decision.label === null + ? decision.reason + : `the title maps to \`${decision.label}\`, but this repository does not define that label`; + return { + createArgs: [], + bodySection: [ + '## Version label', + `Opened without a \`version:*\` label: ${reason}. A reviewer picks one before merging.`, + ].join('\n'), + }; +} diff --git a/src/support/worktreeManager.ts b/src/support/worktreeManager.ts index d1747f9e..aee56f8e 100644 --- a/src/support/worktreeManager.ts +++ b/src/support/worktreeManager.ts @@ -22,6 +22,7 @@ import { publicationCommitSubject } from './publicationCommitMessage.js'; import { changeShapeSection } from './publicationChangeShape.js'; import { baseFreshnessSection, probeBaseFreshness } from './publicationBaseFreshness.js'; import { publicationClaimEvidence } from './publicationClaimEvidence.js'; +import { planVersionLabel, repoVersionLabels } from './publicationVersionLabel.js'; import { loadRepoMetadata } from './repoMetadata.js'; import { detectSharedPaths, emptyDetectionWarning, resolveSharedPaths, type SandboxConfig } from './sharedPathDetection.js'; import { copyIsolatedPath } from './isolatedPath.js'; @@ -1213,15 +1214,14 @@ export async function commitAndCreatePRWithHead( } const freshnessSection = baseFreshnessSection(freshness, base.branch); + // vega-agent-style repos gate every PR on one version:* label (AGT-4269). + const versionLabel = planVersionLabel(title, await repoVersionLabels(worktreePath)); // Create PR const basePrBody = [ '## Summary', description || `${issueIdentifier}: ${title}`, - ...(shapeSection ? ['', shapeSection] : []), - ...(freshnessSection ? ['', freshnessSection] : []), - ...(overlapSection ? ['', overlapSection] : []), - ...(duplicateSection ? ['', duplicateSection] : []), + ...[shapeSection, freshnessSection, overlapSection, duplicateSection, versionLabel.bodySection].filter(Boolean).flatMap((s) => ['', s]), '', '## Linear', `Closes ${issueIdentifier}`, @@ -1232,7 +1232,7 @@ export async function commitAndCreatePRWithHead( const claimEvidence = publicationClaimEvidence(basePrBody, headSha); const prBody = claimEvidence.section ? `${basePrBody}\n\n${claimEvidence.section}` : basePrBody; - const createArgs = ['pr', 'create', '--head', branchName, '--base', base.branch, '--title', title, '--body', prBody]; + const createArgs = ['pr', 'create', '--head', branchName, '--base', base.branch, '--title', title, '--body', prBody, ...versionLabel.createArgs]; // Draft when the work never earned a review: a duplicate implementation must // not masquerade as the sole one, and work published because a run parked // (AGT-4076) never reached a reviewer at all. diff --git a/src/support/worktreeManager.versionLabel.test.ts b/src/support/worktreeManager.versionLabel.test.ts new file mode 100644 index 00000000..e9139a8c --- /dev/null +++ b/src/support/worktreeManager.versionLabel.test.ts @@ -0,0 +1,81 @@ +import { execFileSync } from 'node:child_process'; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { commitAndCreatePRWithHead } from './worktreeManager.js'; + +function git(cwd: string, ...args: string[]): string { + return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8' }); +} + +// 2026-09-10: every open swarm PR on vega-agent failed version-label with +// `LABELS: []` — OpenSwarm opened them unlabelled (AGT-4269). +describe('commitAndCreatePRWithHead version:* label', () => { + let root = ''; + + afterEach(() => { + if (root) rmSync(root, { recursive: true, force: true }); + }); + + async function publish(title: string, repoLabels: string[]): Promise { + root = mkdtempSync(join(tmpdir(), 'openswarm-version-label-')); + const origin = join(root, 'origin.git'); + const repo = join(root, 'repo'); + execFileSync('git', ['init', '--bare', '-q', origin]); + execFileSync('git', ['init', '-q', '-b', 'main', repo]); + git(repo, 'config', 'user.email', 'test@example.com'); + git(repo, 'config', 'user.name', 'Test User'); + writeFileSync(join(repo, 'a.ts'), 'a\n'); + git(repo, 'add', '-A'); + git(repo, 'commit', '-qm', 'initial'); + git(repo, 'remote', 'add', 'origin', origin); + git(repo, 'push', '-q', '-u', 'origin', 'main'); + const branchName = 'swarm/AGT-LBL-x'; + git(repo, 'checkout', '-qb', branchName); + writeFileSync(join(repo, 'a.ts'), 'changed\n'); + + const bin = join(root, 'bin'); + mkdirSync(bin, { recursive: true }); + const captured = join(root, 'pr-create-args.txt'); + const labels = repoLabels.join('\\n'); + writeFileSync( + join(bin, 'gh'), + `#!/bin/sh\ncase "$*" in\n *"label list"*) printf '${labels}\\n';;\n *"pr create"*) printf '%s\\n' "$@" > '${captured}'; echo "https://example.test/pr/1";;\nesac\n`, + ); + chmodSync(join(bin, 'gh'), 0o755); + const prevPath = process.env.PATH; + process.env.PATH = `${bin}:${prevPath}`; + try { + await commitAndCreatePRWithHead( + { worktreePath: repo, originalPath: repo, branchName, issueId: 'AGT-LBL' }, + title, 'AGT-LBL', '', { draft: true }, + ); + } finally { + process.env.PATH = prevPath; + } + return readFileSync(captured, 'utf8').split('\n'); + } + + const VERSION_LABELS = ['version:major', 'version:minor', 'version:patch', 'version:skip']; + + it('opens the PR with exactly one mapped label', async () => { + const args = await publish('[BUG] crash on empty input', VERSION_LABELS); + const at = args.indexOf('--label'); + expect(at).toBeGreaterThan(-1); + expect(args[at + 1]).toBe('version:patch'); + expect(args.filter((a) => a === '--label')).toHaveLength(1); + }); + + it('opens unlabelled with the reason in the body when the title does not decide', async () => { + const args = await publish('refactor: split a module', VERSION_LABELS); + expect(args).not.toContain('--label'); + expect(args.join('\n')).toContain('## Version label'); + }); + + it('leaves a repository without version labels exactly as before', async () => { + const args = await publish('[BUG] crash', ['bug', 'enhancement']); + expect(args).not.toContain('--label'); + expect(args.join('\n')).not.toContain('## Version label'); + }); +});