From ce910e5d523438d1af6903933dc7f628e584328e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 16 Jul 2026 18:33:34 -0700 Subject: [PATCH] fix(naming): keep the built-in branch-name prompt general (#9088) * fix(naming): keep the built-in branch-name prompt general The shipped auto-rename prompt no longer hard-codes style rules (word count, kebab-case, no prefixes). Users can already override naming via Source Control AI instructions and the branch-name command template; a prescriptive default fought those overrides. Git-safe sanitization still runs after generation. * fix(naming): preserve branch prompt overrides * chore(skills): refresh rc.2 manifest version --- .../first-work-branch-rename.test.ts | 2 +- .../agent-hooks/first-work-branch-rename.ts | 5 +- src/main/persistence.test.ts | 2 +- .../commit-message-text-generation.test.ts | 10 ++- src/shared/branch-name-from-work.test.ts | 20 +++++- src/shared/branch-name-from-work.ts | 67 ++++++++++--------- src/shared/source-control-ai.test.ts | 16 ++++- src/shared/source-control-ai.ts | 67 ++++++++++++++++--- 8 files changed, 136 insertions(+), 53 deletions(-) diff --git a/src/main/agent-hooks/first-work-branch-rename.test.ts b/src/main/agent-hooks/first-work-branch-rename.test.ts index c1f46a602..1df5dbba9 100644 --- a/src/main/agent-hooks/first-work-branch-rename.test.ts +++ b/src/main/agent-hooks/first-work-branch-rename.test.ts @@ -140,7 +140,7 @@ describe('maybeAutoRenameBranchOnFirstWork', () => { }) it('strips a prefix the model leaked into the slug from both branch and display name', async () => { - // Model ignored "no prefixes" and echoed `you/worktree-spinner`, which the + // Model echoed `you/worktree-spinner`, which the // sanitizer folds to `you-worktree-spinner`; without stripping it would // double-prefix the branch (`you/you-...`) and show "You worktree spinner". generateBranchNameMock.mockResolvedValue({ success: true, slug: 'you-worktree-spinner' }) diff --git a/src/main/agent-hooks/first-work-branch-rename.ts b/src/main/agent-hooks/first-work-branch-rename.ts index c6e7fb8d1..d66919290 100644 --- a/src/main/agent-hooks/first-work-branch-rename.ts +++ b/src/main/agent-hooks/first-work-branch-rename.ts @@ -283,9 +283,8 @@ async function runAutoRename( const username = provider ? (await getSshGitUsername(provider, repo.path)) || null : (await resolveLocalGitUsername(repo.path)) || null - // The model is told not to add a prefix, but sometimes echoes the configured - // one (e.g. `tmchow/...`); strip it so it doesn't double-prefix the branch or - // leak into the display name. + // The model sometimes echoes the configured prefix (e.g. `tmchow/...`); strip + // it so it doesn't double-prefix the branch or leak into the display name. const slug = stripConfiguredBranchPrefix( generated.slug, getConfiguredBranchPrefix(settings, username) diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index 2cd0c36ef..39771208b 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -2508,7 +2508,7 @@ describe('Store', () => { }) expect(persisted.settings.sourceControlAi.actions.branchName).toEqual({ agentId: 'claude', - commandInputTemplate: '{basePrompt}\n\nRollback commit prompt' + commandInputTemplate: 'Rollback commit prompt\n\n{basePrompt}' }) }) diff --git a/src/main/text-generation/commit-message-text-generation.test.ts b/src/main/text-generation/commit-message-text-generation.test.ts index 4464bb8f4..3b921daf6 100644 --- a/src/main/text-generation/commit-message-text-generation.test.ts +++ b/src/main/text-generation/commit-message-text-generation.test.ts @@ -1853,7 +1853,7 @@ describe('generateBranchNameFromContext', () => { }) }) - it('includes the branch-name custom prompt in the generated prompt', async () => { + it('keeps branch-name guidance first without dropping the output contract', async () => { let prompt = '' await generateBranchNameFromContext( { firstPrompt: 'Fix login flow' }, @@ -1861,7 +1861,8 @@ describe('generateBranchNameFromContext', () => { agentId: 'custom', model: '', customAgentCommand: 'agent', - customPrompt: 'Prefer auth terminology.' + customPrompt: 'Prefer auth terminology.', + commandInputTemplate: 'Prefer auth terminology.\n\n{basePrompt}' }, { kind: 'remote', @@ -1879,8 +1880,11 @@ describe('generateBranchNameFromContext', () => { } ) - expect(prompt).toContain('Additional user prompt:') + expect(prompt.startsWith('Prefer auth terminology.')).toBe(true) expect(prompt).toContain('Prefer auth terminology.') + expect(prompt).not.toContain('Additional user prompt:') + expect(prompt).toContain('Generate a short git branch name') + expect(prompt).toContain('Output ONLY the branch name on a single line') }) }) diff --git a/src/shared/branch-name-from-work.test.ts b/src/shared/branch-name-from-work.test.ts index a30c324cb..9b754cd92 100644 --- a/src/shared/branch-name-from-work.test.ts +++ b/src/shared/branch-name-from-work.test.ts @@ -100,6 +100,16 @@ describe('buildBranchNamePrompt', () => { expect(prompt).not.toContain("Agent's initial response") }) + it('keeps the default prompt general without style rules', () => { + const prompt = buildBranchNamePrompt({ firstPrompt: 'Add a logout button' }) + expect(prompt).toContain('Generate a short git branch name') + expect(prompt).toContain('Output ONLY the branch name on a single line') + expect(prompt).not.toContain('Rules:') + expect(prompt).not.toMatch(/kebab-case/i) + expect(prompt).not.toMatch(/between \d+ and \d+ words/i) + expect(prompt).not.toMatch(/no prefixes/i) + }) + it('includes the assistant response when present', () => { const prompt = buildBranchNamePrompt({ firstPrompt: 'Add a logout button', @@ -109,12 +119,16 @@ describe('buildBranchNamePrompt', () => { expect(prompt).toContain("I'll wire it into the header.") }) - it('appends a custom branch-name prompt when present', () => { + it('leads with a custom naming prompt so overrides can own style', () => { const prompt = buildBranchNamePrompt( { firstPrompt: 'Add a logout button' }, 'Prefer product nouns.' ) - expect(prompt).toContain('Additional user prompt:') - expect(prompt).toContain('Prefer product nouns.') + expect(prompt.startsWith('Prefer product nouns.')).toBe(true) + expect(prompt).not.toContain('Additional user prompt:') + expect(prompt).not.toContain('Rules:') + expect(prompt).toContain('Generate a git branch name') + expect(prompt).toContain('Output ONLY the branch name on a single line') + expect(prompt).toContain('Add a logout button') }) }) diff --git a/src/shared/branch-name-from-work.ts b/src/shared/branch-name-from-work.ts index abf30f386..68880b385 100644 --- a/src/shared/branch-name-from-work.ts +++ b/src/shared/branch-name-from-work.ts @@ -1,10 +1,9 @@ import { MARINE_CREATURES } from './marine-creatures' -// Why: the work-derived branch name stays short on purpose — long, sentence-like -// branches read worse than the creature name they replace. Two-to-four words is -// the sweet spot the feature targets. +// Why: post-generation sanitization still bounds the leaf so a long model dump +// cannot become an unreadable branch. The *prompt* stays general — users can +// override naming style via Source Control AI instructions / templates. export const MAX_BRANCH_NAME_WORDS = 4 -const MIN_BRANCH_NAME_WORDS = 2 const CREATURE_NAMES_LOWER = new Set(MARINE_CREATURES.map((name) => name.toLowerCase())) @@ -46,16 +45,15 @@ export function sanitizeBranchSlug(raw: string, maxWords = MAX_BRANCH_NAME_WORDS } /** - * Drop a leading prefix segment the generation model prepended despite the - * "no prefixes" instruction — e.g. with a `tmchow/` branch prefix the model - * emits `tmchow/worktree-spinner`, which `sanitizeBranchSlug` folds to - * `tmchow-worktree-spinner`. Left alone, that leaks the prefix into both the - * branch leaf (yielding a doubled `tmchow/tmchow-...`) and the humanized - * display name. Strips only when the leading segment matches the *configured* - * prefix, so a work-derived name that merely starts with a real word survives. - * Prefix-only output (the model echoed just `tmchow`) yields an empty slug so - * the caller skips the rename — otherwise it would double-prefix to - * `tmchow/tmchow`. + * Drop a leading prefix segment the generation model sometimes prepends (e.g. + * with a `tmchow/` branch prefix it emits `tmchow/worktree-spinner`, which + * `sanitizeBranchSlug` folds to `tmchow-worktree-spinner`). Left alone, that + * leaks the prefix into both the branch leaf (yielding a doubled + * `tmchow/tmchow-...`) and the humanized display name. Strips only when the + * leading segment matches the *configured* prefix, so a work-derived name that + * merely starts with a real word survives. Prefix-only output (the model + * echoed just `tmchow`) yields an empty slug so the caller skips the rename — + * otherwise it would double-prefix to `tmchow/tmchow`. */ export function stripConfiguredBranchPrefix( slug: string, @@ -100,30 +98,33 @@ export type BranchNameWorkContext = { } /** - * Build the text-generation prompt that asks the configured agent to summarize - * the work into a branch name. Kept in shared so the prompt is identical across - * local and SSH generation targets. + * Build the text-generation prompt that asks the configured agent to name the + * work. Kept in shared so the prompt is identical across local and SSH targets. + * + * Why: the shipped default stays general. Naming style is left open so users + * who override via Source Control AI instructions / the branch-name command + * template are not fighting a rigid built-in rule list. Git-safety (kebab, + * length) is enforced after generation by sanitizeBranchSlug. */ export function buildBranchNamePrompt(context: BranchNameWorkContext, customPrompt = ''): string { - const sections = [ - 'Generate a git branch name that summarizes the coding task described below.', - 'Rules:', - `- Use between ${MIN_BRANCH_NAME_WORDS} and ${MAX_BRANCH_NAME_WORDS} words.`, - '- Lowercase kebab-case only (words joined by single hyphens).', - '- No slashes, no prefixes, no quotes, no trailing punctuation.', - '- Describe the work itself, not the agent or the repository.', - '- Output ONLY the branch name on a single line, nothing else.', - '', - 'User request:', - context.firstPrompt.trim() - ] + const sections: string[] = [] + const prompt = customPrompt.trim() + // Why: when the user supplies naming guidance, lead with it so their + // override owns style rather than sitting under a prescriptive default. + if (prompt) { + sections.push(prompt, '') + } + sections.push( + prompt + ? 'Generate a git branch name that summarizes the coding task described below.' + : 'Generate a short git branch name that summarizes the coding task described below.', + 'Output ONLY the branch name on a single line, nothing else.', + '' + ) + sections.push('User request:', context.firstPrompt.trim()) const assistant = context.assistantMessage?.trim() if (assistant) { sections.push('', "Agent's initial response:", assistant) } - const prompt = customPrompt.trim() - if (prompt) { - sections.push('', 'Additional user prompt:', prompt) - } return sections.join('\n') } diff --git a/src/shared/source-control-ai.test.ts b/src/shared/source-control-ai.test.ts index 2b560889b..54a35115b 100644 --- a/src/shared/source-control-ai.test.ts +++ b/src/shared/source-control-ai.test.ts @@ -313,11 +313,19 @@ describe('source-control AI resolution', () => { }).params.customPrompt ).toBe('Repo commit style') expect(resolve('branchName').params.customPrompt).toBe('Global branch style') + expect(resolve('branchName').params.commandInputTemplate).toBe( + 'Global branch style\n\n{basePrompt}' + ) expect( resolve('branchName', { instructionsByOperation: { branchName: 'Repo branch style' } }).params.customPrompt ).toBe('Repo branch style') + expect( + resolve('branchName', { + instructionsByOperation: { branchName: 'Repo branch style' } + }).params.commandInputTemplate + ).toBe('Repo branch style\n\n{basePrompt}') }) it('does not treat null repo instructions as configured overrides', () => { @@ -368,6 +376,12 @@ describe('source-control AI resolution', () => { expect(migrated.instructionsByOperation.commitMessage).toBe('Legacy commit prompt') expect(migrated.instructionsByOperation.pullRequest).toBe('') expect(migrated.instructionsByOperation.branchName).toBe('Legacy commit prompt') + expect(migrated.actions?.commitMessage?.commandInputTemplate).toBe( + '{basePrompt}\n\nLegacy commit prompt' + ) + expect(migrated.actions?.branchName?.commandInputTemplate).toBe( + 'Legacy commit prompt\n\n{basePrompt}' + ) }) it('merges legacy commit-message updates without wiping PR-only settings', () => { @@ -702,7 +716,7 @@ describe('source-control AI resolution', () => { commandInputTemplate: '{basePrompt}' }, branchName: { - commandInputTemplate: '{basePrompt}\n\nbranch style' + commandInputTemplate: 'branch style\n\n{basePrompt}' } }, prCreationDefaults: { diff --git a/src/shared/source-control-ai.ts b/src/shared/source-control-ai.ts index 31adf5ac7..2ca354191 100644 --- a/src/shared/source-control-ai.ts +++ b/src/shared/source-control-ai.ts @@ -296,13 +296,15 @@ export function normalizeRepoSourceControlAiOverrides( const migratedActionOverrides = { ...actionOverrides } for (const operation of SOURCE_CONTROL_TEXT_ACTION_IDS) { const instruction = instructionsByOperation?.[operation] + const existingTemplate = migratedActionOverrides[operation]?.commandInputTemplate if ( typeof instruction === 'string' && - migratedActionOverrides[operation]?.commandInputTemplate === undefined + (existingTemplate === undefined || + isLegacyBranchInstructionTemplate(operation, instruction, existingTemplate)) ) { migratedActionOverrides[operation] = { ...migratedActionOverrides[operation], - commandInputTemplate: commandTemplateFromInstruction(instruction) + commandInputTemplate: commandTemplateFromOperationInstruction(operation, instruction) } } } @@ -324,6 +326,35 @@ function commandTemplateFromInstruction(instruction: string | null | undefined): return ['{basePrompt}', '', trimmed].join('\n') } +function commandTemplateFromOperationInstruction( + operation: SourceControlAiOperation, + instruction: string | null | undefined +): string { + const trimmed = instruction?.trim() + if (!trimmed) { + return '{basePrompt}' + } + // Why: branch naming instructions define naming style, so they must precede + // the general built-in prompt. Other operations retain their released order. + return operation === 'branchName' + ? [trimmed, '', '{basePrompt}'].join('\n') + : commandTemplateFromInstruction(trimmed) +} + +function isLegacyBranchInstructionTemplate( + operation: SourceControlAiOperation, + instruction: string | null | undefined, + template: string | null | undefined +): boolean { + // Why: reorder only the exact template older settings derived automatically; + // a user-authored command template remains authoritative. + return ( + operation === 'branchName' && + Boolean(instruction?.trim()) && + template === commandTemplateFromInstruction(instruction) + ) +} + function actionRecipeFromLegacyCommitMessageAi(legacy: CommitMessageAiSettings): { agentId?: TuiAgent | CustomAgentId | null commandInputTemplate: string @@ -400,7 +431,10 @@ function shouldImportLegacyBranchPrompt( projectedLegacy: CommitMessageAiSettings ): boolean { const branchRecipe = readSourceControlActionDefault(base.actions, 'branchName') - const projectedTemplate = commandTemplateFromInstruction(projectedLegacy.customPrompt) + const projectedTemplate = commandTemplateFromOperationInstruction( + 'branchName', + projectedLegacy.customPrompt + ) return ( branchRecipe.commandInputTemplate === undefined || branchRecipe.commandInputTemplate === @@ -473,7 +507,13 @@ export function sourceControlAiSettingsFromLegacy( actions: { ...defaults.actions, commitMessage: legacyActionRecipe, - branchName: legacyActionRecipe + branchName: { + ...legacyActionRecipe, + commandInputTemplate: commandTemplateFromOperationInstruction( + 'branchName', + legacy.customPrompt + ) + } } } } @@ -640,7 +680,12 @@ export function mergeLegacyCommitMessageAiIntoSourceControlAi( ? applyLegacyAgentToActionRecipe(base.actions?.branchName, legacy.agentId) : base.actions?.branchName), ...(shouldMergeBranchPrompt - ? { commandInputTemplate: legacyActionRecipe.commandInputTemplate } + ? { + commandInputTemplate: commandTemplateFromOperationInstruction( + 'branchName', + legacy.customPrompt + ) + } : {}) } } @@ -693,15 +738,21 @@ export function normalizeSourceControlAiSettings( const existing = readSourceControlActionDefault(normalizedActions, actionId) const instruction = base.instructionsByOperation?.[actionId] const legacyInstruction = actionId === 'commitMessage' ? legacy?.customPrompt : undefined + const resolvedInstruction = instruction ?? legacyInstruction const instructionTemplate = instruction || legacyInstruction - ? commandTemplateFromInstruction(instruction ?? legacyInstruction) + ? commandTemplateFromOperationInstruction(actionId, resolvedInstruction) : undefined const shouldApplyInstructionTemplate = instructionTemplate !== undefined && (existing.commandInputTemplate === undefined || existing.commandInputTemplate === - DEFAULT_SOURCE_CONTROL_ACTION_COMMAND_TEMPLATES[actionId]) + DEFAULT_SOURCE_CONTROL_ACTION_COMMAND_TEMPLATES[actionId] || + isLegacyBranchInstructionTemplate( + actionId, + resolvedInstruction, + existing.commandInputTemplate + )) return [ actionId, { @@ -1048,7 +1099,7 @@ function resolveActionRecipeForTextOperation( ) const fallbackTemplate = repoInstruction !== undefined - ? commandTemplateFromInstruction(repoInstruction) + ? commandTemplateFromOperationInstruction(operation, repoInstruction) : resolveSourceControlActionCommandTemplate(source.actions, operation) const repoTemplate = typeof repoRecipe?.commandInputTemplate === 'string'