{"record":{"id":"367f195141715da1","repo":"gitbutlerapp/gitbutler","slug":"bug-failed-to-apply-head-ref-head-name-failed-with","errorCode":null,"errorMessage":"BUG: failed to apply head ref ({head_name}). Failed with {:?}","messagePattern":"BUG: failed to apply head ref \\((.+?)\\)\\. Failed with (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/but/src/command/legacy/branch/new.rs","lineNumber":370,"sourceCode":"            // if the branch had no commits `set_base_branch` doesn't apply it\n            //\n            // this also has the effect of entering the workspace with one branch applied\n            {\n                let (repo, mut ws, _db) = ctx.workspace_mut_and_db_with_perm(perm)?;\n                let outcome = but_workspace::branch::apply(\n                    head_name.as_ref(),\n                    ws.clone(),\n                    &repo,\n                    meta,\n                    but_workspace::branch::apply::Options {\n                        allow_applying_already_applied_branch_when_outside_workspace: true,\n                        ..Default::default()\n                    },\n                )?;\n                if outcome.status.persisted_mutation() {\n                    *ws = outcome.workspace.clone();\n                } else {\n                    bail!(\n                        \"BUG: failed to apply head ref ({head_name}). Failed with {:?}\",\n                        outcome.status\n                    )\n                }\n            };\n\n            let (did_rollback, _) = but_transaction::with_transaction_with_perm_only(\n                ctx,\n                meta,\n                perm,\n                DryRun::No,\n                |mut tx| {\n                    tx.create_reference(new_ref.as_ref(), None, |_| StackId::generate(), Some(0))?;\n\n                    Ok(())\n                },\n            )?;\n","sourceCodeStart":352,"sourceCodeEnd":388,"githubUrl":"https://github.com/gitbutlerapp/gitbutler/blob/58e5313667b857ef39a730e380af31816a7b1768/crates/but/src/command/legacy/branch/new.rs#L352-L388","documentation":"When creating a branch in single-branch mode, the operation applies the current head ref via an operation/outcome API. The outcome's status must report a persisted mutation; if it does not, the head ref could not be applied to the new branch and the code bails with a BUG-prefixed message including the head name and status — signaling an internal invariant violation rather than user error.","triggerScenarios":"`but branch new <name>` in single-branch mode where the workspace operation that applies head_name returns an outcome whose status does not count as persisted_mutation() (e.g. a rejected/conflicted/failed apply), after the earlier operation call already returned Ok.","commonSituations":"Corrupted or locked workspace state; refs moved concurrently by another process (IDE, second CLI invocation); stack-engine edge cases after a rebase or external git mutation; genuine bug in the operation pipeline.","solutions":["Retry the command — transient locks or concurrent edits often resolve on a second attempt","Run `but status` / re-open the workspace to refresh stale state, then retry","Check for and dismiss external git processes touching the repo, then retry","If reproducible, report a bug with the head ref name and the status payload from the message"],"exampleFix":"// before\nbut branch new my-branch   # fails with BUG: failed to apply head ref\n// after\ngit -C . status   # ensure repo is healthy / no concurrent process\nbut status && but branch new my-branch","handlingStrategy":"retry","validationCode":"// Pre-check workspace health before branch creation\nawait exec('but status'); // non-zero output/errors indicate stale or locked workspace state","typeGuard":"const isBugApplyFailure = (e) => e instanceof Error && /BUG: failed to apply head ref/.test(e.message);","tryCatchPattern":"try {\n  await exec(`but branch new ${name}`);\n} catch (e) {\n  if (isBugApplyFailure(e)) {\n    // refresh workspace state and retry once\n    await exec('but status');\n    await exec(`but branch new ${name}`);\n  } else throw e;\n}","preventionTips":["Avoid running multiple but/IDE workspace mutations concurrently","Refresh workspace state (but status) after external git operations like rebase/reset","Report reproducible occurrences upstream — the BUG prefix marks an internal invariant break"],"tags":["bug","git","workspace","internal"],"backgroundTag":"internal-invariant-violation","analyzedSha":"58e5313667b857ef39a730e380af31816a7b1768","analyzedAt":"2026-09-18T06:50:32.052Z","contentChangedAt":"2026-09-18T06:50:32.052Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}