Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat(commit): experimental project-level commit-message guidance (#2774)

Maximilian Roosf522357e1167
diff --git a/dev/config.example.toml b/dev/config.example.toml
index 13c298838..1f03bb992 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -181,6 +181,7 @@
# - `{{ git_diff }}`, `{{ git_diff_stat }}` — diff content
# - `{{ branch }}`, `{{ repo }}` — context
# - `{{ recent_commits }}` — recent commit messages
+# - `{{ user_guidance }}`, `{{ project_guidance }}` — rendered append fragments (see Appending to the prompt (https://worktrunk.dev/config/#appending-to-the-prompt))
#
# Default template:
#
@@ -200,7 +201,15 @@
# - Match recent commit style (conventional commits if used)
# - Describe the change, not the intent or benefit
# </style>
-#
+# {% if user_guidance %}
+# <user-guidance>
+# {{ user_guidance }}
+# </user-guidance>
+# {% endif %}{% if project_guidance %}
+# <project-guidance>
+# {{ project_guidance }}
+# </project-guidance>
+# {% endif %}
# <diffstat>
# {{ git_diff_stat }}
# </diffstat>
@@ -244,7 +253,15 @@
# - Match the style of commits being squashed (conventional commits if used)
# - Describe the change, not the intent or benefit
# </style>
-#
+# {% if user_guidance %}
+# <user-guidance>
+# {{ user_guidance }}
+# </user-guidance>
+# {% endif %}{% if project_guidance %}
+# <project-guidance>
+# {{ project_guidance }}
+# </project-guidance>
+# {% endif %}
# <commits branch="{{ branch }}" target="{{ target_branch }}">
# {% for commit in commits %}- {{ commit }}
# {% endfor %}</commits>
@@ -260,6 +277,17 @@
# """
# <!-- DEFAULT_SQUASH_TEMPLATE_END -->
#
+# #### Appending to the prompt [experimental]
+#
+# `template-append` adds to the prompt instead of replacing it. The value is rendered as its own minijinja template (same variables) and injected into the default templates' `{{ user_guidance }}` slot — a `<user-guidance>` block right after `<style>`. It applies to both commit and squash. Use it for personal preferences without restating the whole template:
+#
+# [commit.generation]
+# template-append = """
+# - Explain the rationale in the body, not just the change
+# """
+#
+# The project config (https://worktrunk.dev/config/#project-configuration) has a `template-append` of its own; it renders into a separate `<project-guidance>` block right after `<user-guidance>`.
+#
# ## Hooks
#
# See `wt hook` (https://worktrunk.dev/hook/) for hook types, execution order, template variables, and examples. User hooks apply to all projects; project hooks (https://worktrunk.dev/config/#project-configuration) apply only to that repository.
diff --git a/dev/wt.example.toml b/dev/wt.example.toml
index 2d7d1b377..4091239b7 100644
--- a/dev/wt.example.toml
+++ b/dev/wt.example.toml
@@ -27,6 +27,18 @@
# platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (experimental)
# hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)
#
+# ## Commit-message append [experimental]
+#
+# Project-wide commit-message conventions appended to the LLM commit and squash prompts inside a `<project-guidance>` block, after the main template's `<style>` section (and after any user `<user-guidance>`). Rendered as a minijinja (https://docs.rs/minijinja/) template with the same variables as the main commit template (`{{ branch }}`, `{{ git_diff }}`, etc.), so it can reference them directly. The first time the fragment changes, `wt` prompts the user to approve it — the same one-shot gate as project-defined hooks.
+#
+# [commit.generation]
+# template-append = """
+# - Use conventional commits (feat:, fix:, docs:, …)
+# - Reference the relevant issue ID in the body
+# """
+#
+# Only `template-append` is honored from the project file. The LLM command and the main prompt template stay in user config (https://worktrunk.dev/config/) — they describe per-developer environment (which CLI is installed, which agent the developer prefers). User config has a `[commit.generation] template-append` of its own; it renders into a separate `<user-guidance>` block immediately before this one.
+#
# ## Copy-ignored excludes
#
# Additional excludes for `wt step copy-ignored`:
diff --git a/docs/content/config.md b/docs/content/config.md
index 0afb85069..4a19117d7 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -283,6 +283,7 @@ Available variables:
- `{{ git_diff }}`, `{{ git_diff_stat }}` — diff content
- `{{ branch }}`, `{{ repo }}` — context
- `{{ recent_commits }}` — recent commit messages
+- `{{ user_guidance }}`, `{{ project_guidance }}` — rendered append fragments (see [Appending to the prompt](@/config.md#appending-to-the-prompt))
Default template:
@@ -303,7 +304,15 @@ template = """
- Match recent commit style (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<diffstat>
{{ git_diff_stat }}
</diffstat>
@@ -349,7 +358,15 @@ squash-template = """
- Match the style of commits being squashed (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<commits branch="{{ branch }}" target="{{ target_branch }}">
{% for commit in commits %}- {{ commit }}
{% endfor %}</commits>
@@ -366,6 +383,21 @@ squash-template = """
```
<!-- DEFAULT_SQUASH_TEMPLATE_END -->
+#### Appending to the prompt
+
+<span class="badge-experimental"></span>
+
+`template-append` adds to the prompt instead of replacing it. The value is rendered as its own minijinja template (same variables) and injected into the default templates' `{{ user_guidance }}` slot — a `<user-guidance>` block right after `<style>`. It applies to both commit and squash. Use it for personal preferences without restating the whole template:
+
+```toml
+[commit.generation]
+template-append = """
+- Explain the rationale in the body, not just the change
+"""
+```
+
+The [project config](@/config.md#project-configuration) has a `template-append` of its own; it renders into a separate `<project-guidance>` block right after `<user-guidance>`.
+
## Hooks
See [`wt hook`](@/hook.md) for hook types, execution order, template variables, and examples. User hooks apply to all projects; [project hooks](@/config.md#project-configuration) apply only to that repository.
@@ -406,6 +438,22 @@ platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (expe
hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)
```
+## Commit-message append
+
+<span class="badge-experimental"></span>
+
+Project-wide commit-message conventions appended to the LLM commit and squash prompts inside a `<project-guidance>` block, after the main template's `<style>` section (and after any user `<user-guidance>`). Rendered as a [minijinja](https://docs.rs/minijinja/) template with the same variables as the main commit template (`{{ branch }}`, `{{ git_diff }}`, etc.), so it can reference them directly. The first time the fragment changes, `wt` prompts the user to approve it — the same one-shot gate as project-defined hooks.
+
+```toml
+[commit.generation]
+template-append = """
+- Use conventional commits (feat:, fix:, docs:, …)
+- Reference the relevant issue ID in the body
+"""
+```
+
+Only `template-append` is honored from the project file. The LLM command and the main prompt template stay in [user config](@/config.md) — they describe per-developer environment (which CLI is installed, which agent the developer prefers). User config has a `[commit.generation] template-append` of its own; it renders into a separate `<user-guidance>` block immediately before this one.
+
## Copy-ignored excludes
Additional excludes for `wt step copy-ignored`:
diff --git a/docs/content/llm-commits.md b/docs/content/llm-commits.md
index 64fc41fb8..01dd1c0af 100644
--- a/docs/content/llm-commits.md
+++ b/docs/content/llm-commits.md
@@ -187,6 +187,8 @@ Diff:
| `{{ recent_commits }}` | Recent commit subjects (for style reference) |
| `{{ commits }}` | Commits being squashed (squash template only) |
| `{{ target_branch }}` | Merge target branch (squash template only) |
+| `{{ user_guidance }}` | Rendered user `template-append` fragment (see below) |
+| `{{ project_guidance }}` | Rendered project `template-append` fragment (see below) |
### Template syntax
@@ -201,6 +203,27 @@ Templates use [minijinja](https://docs.rs/minijinja/latest/minijinja/syntax/inde
See `wt config create --help` for the full default templates.
+## Appending to the prompt
+
+<span class="badge-experimental"></span>
+
+`template-append` adds to the commit and squash prompts instead of replacing them. It lives in both user config (personal preferences) and project config (`.config/wt.toml`, shared so every teammate's LLM sees the same style guide). Each fragment is itself a [minijinja](https://docs.rs/minijinja/) template — Worktrunk renders it with the same variables as the main template (`{{ branch }}`, `{{ git_diff }}`, …), then appends the result after `<style>`. The user fragment renders into a `<user-guidance>` block and the project fragment into a `<project-guidance>` block, so the LLM can tell personal preference from shared convention:
+
+```toml
+# .config/wt.toml
+[commit.generation]
+template-append = """
+- Use conventional commits (feat:, fix:, docs:, …)
+- Reference the related issue ID in the body
+"""
+```
+
+When both the user and project set `template-append`, the `<user-guidance>` block comes first, then `<project-guidance>`.
+
+The user fragment needs no approval — it's the developer's own config. For the project fragment, the first time the rendered text is sent to the LLM, Worktrunk shows the raw fragment in an approval prompt — the same one-shot gate as project-defined hooks. Subsequent commits don't re-prompt unless the fragment changes. Declining is non-fatal: the LLM runs with just the user fragment (if any).
+
+Custom user templates that don't reference `{{ user_guidance }}` / `{{ project_guidance }}` opt out of the appended blocks — the rendered values are injected only where the template places them.
+
## Fallback behavior
When no LLM is configured, worktrunk generates deterministic messages based on changed filenames (e.g., "Changes to auth.rs & config.rs").
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 3e300ed15..8fd081c00 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -282,6 +282,7 @@ Available variables:
- `{{ git_diff }}`, `{{ git_diff_stat }}` — diff content
- `{{ branch }}`, `{{ repo }}` — context
- `{{ recent_commits }}` — recent commit messages
+- `{{ user_guidance }}`, `{{ project_guidance }}` — rendered append fragments (see [Appending to the prompt](https://worktrunk.dev/config/#appending-to-the-prompt))
Default template:
@@ -302,7 +303,15 @@ template = """
- Match recent commit style (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<diffstat>
{{ git_diff_stat }}
</diffstat>
@@ -348,7 +357,15 @@ squash-template = """
- Match the style of commits being squashed (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<commits branch="{{ branch }}" target="{{ target_branch }}">
{% for commit in commits %}- {{ commit }}
{% endfor %}</commits>
@@ -365,6 +382,19 @@ squash-template = """
```
<!-- DEFAULT_SQUASH_TEMPLATE_END -->
+#### Appending to the prompt [experimental]
+
+`template-append` adds to the prompt instead of replacing it. The value is rendered as its own minijinja template (same variables) and injected into the default templates' `{{ user_guidance }}` slot — a `<user-guidance>` block right after `<style>`. It applies to both commit and squash. Use it for personal preferences without restating the whole template:
+
+```toml
+[commit.generation]
+template-append = """
+- Explain the rationale in the body, not just the change
+"""
+```
+
+The [project config](https://worktrunk.dev/config/#project-configuration) has a `template-append` of its own; it renders into a separate `<project-guidance>` block right after `<user-guidance>`.
+
## Hooks
See [`wt hook`](https://worktrunk.dev/hook/) for hook types, execution order, template variables, and examples. User hooks apply to all projects; [project hooks](https://worktrunk.dev/config/#project-configuration) apply only to that repository.
@@ -405,6 +435,20 @@ platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (expe
hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)
```
+## Commit-message append [experimental]
+
+Project-wide commit-message conventions appended to the LLM commit and squash prompts inside a `<project-guidance>` block, after the main template's `<style>` section (and after any user `<user-guidance>`). Rendered as a [minijinja](https://docs.rs/minijinja/) template with the same variables as the main commit template (`{{ branch }}`, `{{ git_diff }}`, etc.), so it can reference them directly. The first time the fragment changes, `wt` prompts the user to approve it — the same one-shot gate as project-defined hooks.
+
+```toml
+[commit.generation]
+template-append = """
+- Use conventional commits (feat:, fix:, docs:, …)
+- Reference the relevant issue ID in the body
+"""
+```
+
+Only `template-append` is honored from the project file. The LLM command and the main prompt template stay in [user config](https://worktrunk.dev/config/) — they describe per-developer environment (which CLI is installed, which agent the developer prefers). User config has a `[commit.generation] template-append` of its own; it renders into a separate `<user-guidance>` block immediately before this one.
+
## Copy-ignored excludes
Additional excludes for `wt step copy-ignored`:
diff --git a/skills/worktrunk/reference/llm-commits.md b/skills/worktrunk/reference/llm-commits.md
index 254bba572..be5247c50 100644
--- a/skills/worktrunk/reference/llm-commits.md
+++ b/skills/worktrunk/reference/llm-commits.md
@@ -161,6 +161,8 @@ Diff:
| `{{ recent_commits }}` | Recent commit subjects (for style reference) |
| `{{ commits }}` | Commits being squashed (squash template only) |
| `{{ target_branch }}` | Merge target branch (squash template only) |
+| `{{ user_guidance }}` | Rendered user `template-append` fragment (see below) |
+| `{{ project_guidance }}` | Rendered project `template-append` fragment (see below) |
### Template syntax
@@ -175,6 +177,27 @@ Templates use [minijinja](https://docs.rs/minijinja/latest/minijinja/syntax/inde
See `wt config create --help` for the full default templates.
+## Appending to the prompt
+
+[experimental]
+
+`template-append` adds to the commit and squash prompts instead of replacing them. It lives in both user config (personal preferences) and project config (`.config/wt.toml`, shared so every teammate's LLM sees the same style guide). Each fragment is itself a [minijinja](https://docs.rs/minijinja/) template — Worktrunk renders it with the same variables as the main template (`{{ branch }}`, `{{ git_diff }}`, …), then appends the result after `<style>`. The user fragment renders into a `<user-guidance>` block and the project fragment into a `<project-guidance>` block, so the LLM can tell personal preference from shared convention:
+
+```toml
+# .config/wt.toml
+[commit.generation]
+template-append = """
+- Use conventional commits (feat:, fix:, docs:, …)
+- Reference the related issue ID in the body
+"""
+```
+
+When both the user and project set `template-append`, the `<user-guidance>` block comes first, then `<project-guidance>`.
+
+The user fragment needs no approval — it's the developer's own config. For the project fragment, the first time the rendered text is sent to the LLM, Worktrunk shows the raw fragment in an approval prompt — the same one-shot gate as project-defined hooks. Subsequent commits don't re-prompt unless the fragment changes. Declining is non-fatal: the LLM runs with just the user fragment (if any).
+
+Custom user templates that don't reference `{{ user_guidance }}` / `{{ project_guidance }}` opt out of the appended blocks — the rendered values are injected only where the template places them.
+
## Fallback behavior
When no LLM is configured, worktrunk generates deterministic messages based on changed filenames (e.g., "Changes to auth.rs & config.rs").
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index a3d83b9b4..4745682ec 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1819,6 +1819,7 @@ Available variables:
- `{{ git_diff }}`, `{{ git_diff_stat }}` — diff content
- `{{ branch }}`, `{{ repo }}` — context
- `{{ recent_commits }}` — recent commit messages
+- `{{ user_guidance }}`, `{{ project_guidance }}` — rendered append fragments (see [Appending to the prompt](@/config.md#appending-to-the-prompt))
Default template:
@@ -1839,7 +1840,15 @@ template = """
- Match recent commit style (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<diffstat>
{{ git_diff_stat }}
</diffstat>
@@ -1885,7 +1894,15 @@ squash-template = """
- Match the style of commits being squashed (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<commits branch="{{ branch }}" target="{{ target_branch }}">
{% for commit in commits %}- {{ commit }}
{% endfor %}</commits>
@@ -1902,6 +1919,19 @@ squash-template = """
```
<!-- DEFAULT_SQUASH_TEMPLATE_END -->
+#### Appending to the prompt [experimental]
+
+`template-append` adds to the prompt instead of replacing it. The value is rendered as its own minijinja template (same variables) and injected into the default templates' `{{ user_guidance }}` slot — a `<user-guidance>` block right after `<style>`. It applies to both commit and squash. Use it for personal preferences without restating the whole template:
+
+```toml
+[commit.generation]
+template-append = """
+- Explain the rationale in the body, not just the change
+"""
+```
+
+The [project config](@/config.md#project-configuration) has a `template-append` of its own; it renders into a separate `<project-guidance>` block right after `<user-guidance>`.
+
## Hooks
See [`wt hook`](@/hook.md) for hook types, execution order, template variables, and examples. User hooks apply to all projects; [project hooks](@/config.md#project-configuration) apply only to that repository.
@@ -1942,6 +1972,20 @@ platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (expe
hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)
```
+## Commit-message append [experimental]
+
+Project-wide commit-message conventions appended to the LLM commit and squash prompts inside a `<project-guidance>` block, after the main template's `<style>` section (and after any user `<user-guidance>`). Rendered as a [minijinja](https://docs.rs/minijinja/) template with the same variables as the main commit template (`{{ branch }}`, `{{ git_diff }}`, etc.), so it can reference them directly. The first time the fragment changes, `wt` prompts the user to approve it — the same one-shot gate as project-defined hooks.
+
+```toml
+[commit.generation]
+template-append = """
+- Use conventional commits (feat:, fix:, docs:, …)
+- Reference the relevant issue ID in the body
+"""
+```
+
+Only `template-append` is honored from the project file. The LLM command and the main prompt template stay in [user config](@/config.md) — they describe per-developer environment (which CLI is installed, which agent the developer prefers). User config has a `[commit.generation] template-append` of its own; it renders into a separate `<user-guidance>` block immediately before this one.
+
## Copy-ignored excludes
Additional excludes for `wt step copy-ignored`:
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index b994ec5cc..b36ab3325 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -25,8 +25,8 @@ use color_print::cformat;
use worktrunk::config::Approvals;
use worktrunk::git::{GitError, HookType};
use worktrunk::styling::{
- INFO_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_bash_with_gutter, hint_message,
- prompt_message, stderr, warning_message,
+ INFO_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_bash_with_gutter, format_with_gutter,
+ hint_message, prompt_message, stderr, warning_message,
};
use super::hook_filter::{HookSource, ParsedFilter};
@@ -120,7 +120,14 @@ fn prompt_for_batch_approval(
None => format!("{INFO_SYMBOL} {phase}:"),
};
eprintln!("{}", label);
- eprintln!("{}", format_bash_with_gutter(&cmd.command.template));
+ // Shell commands get bash syntax highlighting; the commit template
+ // fragment is plain text (markdown-ish) and shouldn't be tokenized as
+ // bash.
+ let body = match cmd.phase {
+ Phase::CommitTemplateAppend => format_with_gutter(&cmd.command.template, None),
+ _ => format_bash_with_gutter(&cmd.command.template),
+ };
+ eprintln!("{}", body);
}
// Check if stdin is a TTY before attempting to prompt
@@ -277,6 +284,71 @@ pub fn approve_or_skip(
Ok(approved)
}
+/// Resolve the project commit template for a preview path (`--show-prompt` /
+/// `--dry-run`).
+///
+/// `--show-prompt` doesn't invoke the LLM, so it always returns the configured
+/// fragment verbatim. `--dry-run` does invoke the LLM, so when an LLM is
+/// configured it goes through the same approval gate as a real commit.
+pub fn resolve_template_for_preview(
+ ctx: &super::command_executor::CommandContext<'_>,
+ commit_config: &worktrunk::config::CommitGenerationConfig,
+ dry_run: bool,
+) -> anyhow::Result<Option<String>> {
+ if dry_run && commit_config.is_configured() {
+ approve_commit_template_append(ctx)
+ } else {
+ Ok(ctx
+ .repo
+ .load_project_config()?
+ .as_ref()
+ .and_then(|cfg| cfg.commit_template_append().map(str::to_string)))
+ }
+}
+
+/// Approve the project-level commit append fragment before sending it to the LLM.
+///
+/// Returns `Ok(Some(fragment))` when approved (or already approved), `Ok(None)`
+/// when no fragment is configured or the user declined. Declining is non-fatal:
+/// the LLM still runs, just without the project append, mirroring the
+/// "commands declined, continuing without hooks" pattern. The user-level
+/// `template-append` is not gated here — it's the developer's own config.
+///
+/// Callers should invoke this on every LLM-bearing path (`wt commit`, `wt step
+/// commit`, `wt step squash`, `wt merge`, `wt step commit --dry-run`, etc.).
+/// `--show-prompt` paths skip the gate — they don't execute the LLM, so showing
+/// the fragment is a preview, not a send.
+pub fn approve_commit_template_append(
+ ctx: &super::command_executor::CommandContext<'_>,
+) -> anyhow::Result<Option<String>> {
+ let Some(project_config) = ctx.repo.load_project_config()? else {
+ return Ok(None);
+ };
+ let Some(fragment) = project_config.commit_template_append() else {
+ return Ok(None);
+ };
+
+ let project_id = ctx.repo.project_identifier()?;
+ let approvals = Approvals::load().context("Failed to load approvals")?;
+ let owned = fragment.to_string();
+ if approvals.is_command_approved(&project_id, &owned) {
+ return Ok(Some(owned));
+ }
+
+ let batch = vec![ApprovableCommand::commit_template_append(owned.clone())];
+ let approved = approve_command_batch(&batch, &project_id, &approvals, ctx.yes, true)?;
+ if !approved {
+ worktrunk::styling::eprintln!(
+ "{}",
+ worktrunk::styling::info_message(
+ "Project commit guidance declined; generating without it",
+ )
+ );
+ return Ok(None);
+ }
+ Ok(Some(owned))
+}
+
/// Like [`approve_or_skip`] but approves against an already-resolved
/// `ProjectConfig` rather than `ctx.repo.load_project_config()`.
///
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 303e7cc23..228abdb7b 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -66,6 +66,10 @@ pub struct CommitOptions<'a> {
pub stage_mode: StageMode,
pub warn_about_untracked: bool,
pub show_no_squash_note: bool,
+ /// Whether `commit()` runs its own guidance approval gate or trusts a
+ /// value supplied by the caller (`wt merge` bundles the guidance into
+ /// its hook-approval batch so the user sees one combined prompt).
+ pub guidance: super::step::PreApprovedGuidance,
}
impl<'a> CommitOptions<'a> {
@@ -78,17 +82,25 @@ impl<'a> CommitOptions<'a> {
stage_mode: StageMode::All,
warn_about_untracked: true,
show_no_squash_note: false,
+ guidance: super::step::PreApprovedGuidance::RunOwnGate,
}
}
}
pub(crate) struct CommitGenerator<'a> {
config: &'a CommitGenerationConfig,
+ /// Approved project-level append fragment for the LLM prompt. `None` if
+ /// not configured or the user declined approval. The user-level
+ /// `template-append` rides along inside `config` and needs no approval.
+ project_append: Option<&'a str>,
}
impl<'a> CommitGenerator<'a> {
- pub fn new(config: &'a CommitGenerationConfig) -> Self {
- Self { config }
+ pub fn new(config: &'a CommitGenerationConfig, project_append: Option<&'a str>) -> Self {
+ Self {
+ config,
+ project_append,
+ }
}
pub fn format_message_for_display(&self, message: &str) -> String {
@@ -175,7 +187,8 @@ impl<'a> CommitGenerator<'a> {
}
self.emit_hint_if_needed();
- let commit_message = crate::llm::generate_commit_message(self.config, None)?;
+ let commit_message =
+ crate::llm::generate_commit_message(self.config, None, self.project_append)?;
let formatted_message = self.format_message_for_display(&commit_message);
eprintln!("{}", format_with_gutter(&formatted_message, None));
@@ -269,12 +282,23 @@ impl CommitOptions<'_> {
}
let effective_config = self.ctx.commit_generation();
- let outcome = CommitGenerator::new(&effective_config).commit_staged_changes(
- &wt,
- true, // show_progress
- self.show_no_squash_note,
- self.stage_mode,
- )?;
+ // Skip the approval gate when the LLM isn't configured — the fallback
+ // message generator doesn't render the prompt template, so guidance
+ // would never reach an LLM anyway.
+ let project_append = match self.guidance {
+ super::step::PreApprovedGuidance::Resolved(value) => value,
+ super::step::PreApprovedGuidance::RunOwnGate if effective_config.is_configured() => {
+ super::command_approval::approve_commit_template_append(self.ctx)?
+ }
+ super::step::PreApprovedGuidance::RunOwnGate => None,
+ };
+ let outcome = CommitGenerator::new(&effective_config, project_append.as_deref())
+ .commit_staged_changes(
+ &wt,
+ true, // show_progress
+ self.show_no_squash_note,
+ self.stage_mode,
+ )?;
// Register post-commit hooks onto the caller's announcer (respects --no-hooks).
if self.hooks.run() {
@@ -294,7 +318,7 @@ mod tests {
fn test_format_message_for_display() {
use insta::assert_snapshot;
let config = CommitGenerationConfig::default();
- let generator = CommitGenerator::new(&config);
+ let generator = CommitGenerator::new(&config, None);
assert_snapshot!(generator.format_message_for_display("Simple commit message"), @"Simple commit message");
assert_snapshot!(generator.format_message_for_display("First line\nSecond line\nThird line"), @"
@@ -307,7 +331,7 @@ mod tests {
#[test]
fn test_format_message_for_display_empty() {
let config = CommitGenerationConfig::default();
- let generator = CommitGenerator::new(&config);
+ let generator = CommitGenerator::new(&config, None);
let result = generator.format_message_for_display("");
assert_eq!(result, "");
}
diff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rs
index 20d8aea1d..b273aea1f 100644
--- a/src/commands/config/approvals.rs
+++ b/src/commands/config/approvals.rs
@@ -11,7 +11,9 @@ use worktrunk::git::{GitError, Repository};
use worktrunk::styling::{eprintln, info_message, success_message};
use crate::commands::command_approval::approve_command_batch;
-use crate::commands::project_config::{collect_commands_for_aliases, collect_commands_for_hooks};
+use crate::commands::project_config::{
+ ApprovableCommand, collect_commands_for_aliases, collect_commands_for_hooks,
+};
/// Handle `wt config approvals add` command - approve all hook and alias commands in the project
pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
@@ -28,10 +30,15 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
.ok_or(GitError::ProjectConfigNotFound { config_path })?;
// Collect all commands from the project config: hooks first (lifecycle order),
- // then aliases (alphabetical via BTreeMap).
+ // then aliases (alphabetical via BTreeMap), then any commit-message guidance.
let all_hooks: Vec<_> = HookType::iter().collect();
let mut commands = collect_commands_for_hooks(&project_config, &all_hooks);
commands.extend(collect_commands_for_aliases(&project_config));
+ if let Some(fragment) = project_config.commit_template_append() {
+ commands.push(ApprovableCommand::commit_template_append(
+ fragment.to_string(),
+ ));
+ }
if commands.is_empty() {
eprintln!("{}", info_message("No commands configured in project"));
diff --git a/src/commands/config/snapshots/wt__commands__config__tests__warn_unknown_keys_deprecated_in_wrong_config.snap b/src/commands/config/snapshots/wt__commands__config__tests__warn_unknown_keys_deprecated_in_wrong_config.snap
index 25487f6ec..1d25988e5 100644
--- a/src/commands/config/snapshots/wt__commands__config__tests__warn_unknown_keys_deprecated_in_wrong_config.snap
+++ b/src/commands/config/snapshots/wt__commands__config__tests__warn_unknown_keys_deprecated_in_wrong_config.snap
@@ -1,5 +1,5 @@
---
source: src/commands/config/mod.rs
-expression: "warn_unknown_keys::<ProjectConfig>(&unknown)"
+expression: "warn_unknown_keys::<ProjectConfig>(\"[commit-generation]\\ncommand = \\\"llm\\\"\\n\")"
---
-▲ Key commit-generation belongs in user config as [commit.generation]
+▲ Unknown key commit.generation.command will be ignored
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 21e0fdd8a..22108310a 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -215,7 +215,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let remove_requested = remove && !on_target;
// Collect and approve all commands upfront for batch permission request
- let (all_commands, project_id) = collect_merge_commands(
+ let (mut all_commands, project_id) = collect_merge_commands(
repo,
&destination_path,
commit,
@@ -224,6 +224,26 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
squash_enabled,
)?;
+ // Bundle commit guidance into the same batch as hooks so an LLM-bound
+ // merge produces one approval prompt, not two. Only when a commit will
+ // actually be created and an LLM is configured.
+ let will_create_commit = current_wt.is_dirty()? || squash_enabled;
+ let llm_configured = env
+ .config
+ .commit_generation(Some(&project_id))
+ .is_configured();
+ let project_append_text: Option<String> = if commit && will_create_commit && llm_configured {
+ env.repo
+ .load_project_config()?
+ .as_ref()
+ .and_then(|cfg| cfg.commit_template_append().map(str::to_string))
+ } else {
+ None
+ };
+ if let Some(ref g) = project_append_text {
+ all_commands.push(ApprovableCommand::commit_template_append(g.clone()));
+ }
+
// Approve all commands in a single batch (shows templates, not expanded values)
let approvals = Approvals::load().context("Failed to load approvals")?;
let approved = approve_command_batch(&all_commands, &project_id, &approvals, yes, false)?;
@@ -249,6 +269,10 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// the end.
let mut announcer = HookAnnouncer::new(repo, config, false);
+ let guidance = super::step::PreApprovedGuidance::Resolved(
+ approved.then_some(project_append_text).flatten(),
+ );
+
// Handle uncommitted changes (skip if --no-commit) - track whether commit occurred
let committed = if commit && current_wt.is_dirty()? {
if squash_enabled {
@@ -261,6 +285,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
options.stage_mode = stage_mode;
options.warn_about_untracked = stage_mode == super::commit::StageMode::All;
options.show_no_squash_note = true;
+ options.guidance = guidance.clone();
let _ = options.commit(&mut announcer)?;
true // Committed directly
@@ -280,6 +305,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
commit_hooks,
Some(stage_mode),
&mut announcer,
+ guidance,
)?,
super::step::SquashResult::Squashed { .. }
)
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 0759194a0..4a2e728f9 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -56,9 +56,9 @@ pub(crate) use picker::handle_picker;
pub(crate) use repository_ext::RemoveTarget;
pub(crate) use run_pipeline::run_pipeline;
pub(crate) use step::{
- PromoteResult, RebaseResult, SquashResult, handle_promote, handle_rebase, handle_squash,
- step_commit, step_copy_ignored, step_diff, step_dry_run_squash, step_prune, step_relocate,
- step_show_squash_prompt,
+ PreApprovedGuidance, PromoteResult, RebaseResult, SquashResult, handle_promote, handle_rebase,
+ handle_squash, step_commit, step_copy_ignored, step_diff, step_dry_run_squash, step_prune,
+ step_relocate, step_show_squash_prompt,
};
pub(crate) use worktree::{
OperationMode, SwitchOptions, is_worktree_at_expected_path, resolve_worktree_arg, run_switch,
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index d4829d305..40a23769b 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -10,6 +10,10 @@ use worktrunk::git::{HookType, Repository};
pub enum Phase {
Hook(HookType),
Alias,
+ /// Project-level commit-message append fragment — not a shell command.
+ /// Approving records the raw fragment as "approved" so subsequent LLM
+ /// calls include it without re-prompting.
+ CommitTemplateAppend,
}
impl fmt::Display for Phase {
@@ -17,6 +21,7 @@ impl fmt::Display for Phase {
match self {
Phase::Hook(hook_type) => write!(f, "{hook_type}"),
Phase::Alias => write!(f, "alias"),
+ Phase::CommitTemplateAppend => write!(f, "commit-template-append"),
}
}
}
@@ -28,6 +33,19 @@ pub struct ApprovableCommand {
pub command: Command,
}
+impl ApprovableCommand {
+ /// Build an approvable for the project-level commit append fragment.
+ /// The raw fragment is reused as the `Command::template` so the
+ /// approvals store (`approved-commands`) treats it like any other
+ /// approved input.
+ pub fn commit_template_append(text: String) -> Self {
+ Self {
+ phase: Phase::CommitTemplateAppend,
+ command: Command::new(None, text),
+ }
+ }
+}
+
/// Collect commands for the given hook types, preserving order of the provided hooks.
pub fn collect_commands_for_hooks(
project_config: &ProjectConfig,
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 75c9f6810..82525cae5 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -223,13 +223,17 @@ pub struct ValidationResult {
/// Check each candidate for locked/dirty state and optionally auto-commit.
///
-/// Returns validated candidates ready for relocation.
+/// Returns validated candidates ready for relocation. `project_append` is
+/// the approved project-level append fragment added to each auto-commit
+/// prompt. Resolved once upfront by the caller so per-worktree commits share
+/// the same approved value rather than each running its own approval gate.
pub fn validate_candidates(
repo: &Repository,
config: &UserConfig,
candidates: Vec<RelocationCandidate>,
auto_commit: bool,
repo_path: &Path,
+ project_append: Option<&str>,
) -> anyhow::Result<ValidationResult> {
let mut validated = Vec::new();
let mut skipped: Vec<SkippedEntry> = Vec::new();
@@ -270,7 +274,7 @@ pub fn validate_candidates(
// Commit using shared pipeline
let project_id = repo.project_identifier().ok();
let commit_config = config.commit_generation(project_id.as_deref());
- CommitGenerator::new(&commit_config).commit_staged_changes(
+ CommitGenerator::new(&commit_config, project_append).commit_staged_changes(
&worktree,
false, // show_progress - already showing "Committing changes in..."
false, // show_no_squash_note
diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rs
index 380d52170..8b6cf217c 100644
--- a/src/commands/step/commit.rs
+++ b/src/commands/step/commit.rs
@@ -9,7 +9,7 @@ use worktrunk::git::Repository;
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::println;
-use super::super::command_approval::approve_or_skip;
+use super::super::command_approval::{approve_or_skip, resolve_template_for_preview};
use super::super::commit::{CommitOptions, CommitOutcome, HookGate, StageMode};
use super::super::context::CommandEnv;
use super::super::hooks::HookAnnouncer;
@@ -30,7 +30,7 @@ pub fn step_commit(
// mirrors --stage against a temp index so the previewed prompt matches what a real
// run would send the LLM. Neither path produces a CommitOutcome.
if show_prompt || dry_run {
- preview_commit(stage, dry_run)?;
+ preview_commit(stage, dry_run, yes)?;
return Ok(None);
}
@@ -78,7 +78,7 @@ pub fn step_commit(
/// `--stage` against a temp index — so the previewed prompt matches what a real run
/// would send — then calls the LLM and prints the command and message in three labeled
/// sections. The user's real index is never modified.
-fn preview_commit(stage: Option<StageMode>, dry_run: bool) -> anyhow::Result<()> {
+fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow::Result<()> {
let env = CommandEnv::for_action(UserConfig::load().context("Failed to load config")?)?;
let commit_config = env.resolved().commit_generation.clone();
@@ -99,12 +99,20 @@ fn preview_commit(stage: Option<StageMode>, dry_run: bool) -> anyhow::Result<()>
};
let index_override = temp_index.as_ref().map(|t| t.path());
- let prompt = crate::llm::build_commit_prompt(&commit_config, index_override)?;
+ let ctx = env.context(yes);
+ let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;
+
+ let prompt =
+ crate::llm::build_commit_prompt(&commit_config, index_override, project_append.as_deref())?;
if !dry_run {
println!("{}", prompt);
return Ok(());
}
- let message = crate::llm::generate_commit_message(&commit_config, index_override)?;
+ let message = crate::llm::generate_commit_message(
+ &commit_config,
+ index_override,
+ project_append.as_deref(),
+ )?;
print_dry_run(&prompt, &commit_config, &message)
}
diff --git a/src/commands/step/mod.rs b/src/commands/step/mod.rs
index 0b6b4e926..3b276dd63 100644
--- a/src/commands/step/mod.rs
+++ b/src/commands/step/mod.rs
@@ -31,5 +31,5 @@ pub(crate) use prune::step_prune;
pub(crate) use rebase::{RebaseResult, handle_rebase};
pub(crate) use relocate::step_relocate;
pub(crate) use squash::{
- SquashResult, handle_squash, step_dry_run_squash, step_show_squash_prompt,
+ PreApprovedGuidance, SquashResult, handle_squash, step_dry_run_squash, step_show_squash_prompt,
};
diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rs
index 1b4798c15..5681febc9 100644
--- a/src/commands/step/relocate.rs
+++ b/src/commands/step/relocate.rs
@@ -88,10 +88,35 @@ pub fn step_relocate(
}
// Phase 2: Validate candidates (check locked/dirty, optionally auto-commit)
+ // Approve the project commit append once for the whole batch so per-worktree
+ // commits share a single approval prompt rather than one per worktree.
+ // Skip approval when the LLM isn't configured for this project — the
+ // fallback message generator doesn't render the prompt template.
+ let project_append = if commit {
+ use super::super::command_approval::approve_commit_template_append;
+ use super::super::command_executor::CommandContext;
+ let project_id = repo.project_identifier().ok();
+ let commit_config = config.commit_generation(project_id.as_deref());
+ if commit_config.is_configured() {
+ let ctx = CommandContext::new(&repo, &config, None, &repo_path, false);
+ approve_commit_template_append(&ctx)?
+ } else {
+ None
+ }
+ } else {
+ None
+ };
let ValidationResult {
validated,
skipped: validation_skipped,
- } = validate_candidates(&repo, &config, candidates, commit, &repo_path)?;
+ } = validate_candidates(
+ &repo,
+ &config,
+ candidates,
+ commit,
+ &repo_path,
+ project_append.as_deref(),
+ )?;
if validated.is_empty() {
if json_mode {
diff --git a/src/commands/step/shared.rs b/src/commands/step/shared.rs
index 821a9bde5..9c4c18d86 100644
--- a/src/commands/step/shared.rs
+++ b/src/commands/step/shared.rs
@@ -37,7 +37,7 @@ pub(super) fn print_dry_run(
Some(cmd) => format_bash_with_gutter(&crate::llm::render_llm_invocation(cmd)?),
None => format_with_gutter("(LLM not configured — using built-in fallback)", None),
};
- let formatted = CommitGenerator::new(commit_config).format_message_for_display(message);
+ let formatted = CommitGenerator::new(commit_config, None).format_message_for_display(message);
let out = format!(
"{prompt_heading}\n{prompt}\n\n{command_heading}\n{command_block}\n\n{message_heading}\n{message_block}\n",
prompt_heading = format_heading("PROMPT", None),
diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rs
index ff40bb374..6a6709b28 100644
--- a/src/commands/step/squash.rs
+++ b/src/commands/step/squash.rs
@@ -10,7 +10,9 @@ use worktrunk::styling::{
success_message,
};
-use super::super::command_approval::approve_or_skip;
+use super::super::command_approval::{
+ approve_commit_template_append, approve_or_skip, resolve_template_for_preview,
+};
use super::super::command_executor::FailureStrategy;
use super::super::commit::{CommitGenerator, CommitOutcome, HookGate, StageMode};
use super::super::context::CommandEnv;
@@ -19,6 +21,22 @@ use super::super::repository_ext::RepositoryCliExt;
use super::super::template_vars::TemplateVars;
use super::shared::print_dry_run;
+/// Caller's stance on project commit-message guidance approval.
+///
+/// `wt step squash` runs its own gate (the user invokes squash directly, so
+/// there's no upstream batch to attach to). `wt merge` bundles the append
+/// into its hook-approval batch and passes the result here so the user
+/// doesn't see a second prompt mid-flow.
+#[derive(Debug, Clone)]
+pub enum PreApprovedGuidance {
+ /// No pre-approval — `handle_squash` runs its own gate via
+ /// `approve_commit_template_append` (only if the LLM is configured).
+ RunOwnGate,
+ /// Caller already resolved the guidance through an upstream batch.
+ /// `None` means "guidance not configured or user declined".
+ Resolved(Option<String>),
+}
+
/// Result of a squash operation
#[derive(Debug, Clone)]
pub enum SquashResult {
@@ -55,6 +73,7 @@ pub fn handle_squash(
hooks: HookGate,
stage: Option<StageMode>,
announcer: &mut HookAnnouncer<'_>,
+ pre_approved_guidance: PreApprovedGuidance,
) -> anyhow::Result<SquashResult> {
// Load config once, run LLM setup prompt, then reuse config
let mut config = UserConfig::load().context("Failed to load config")?;
@@ -67,7 +86,20 @@ pub fn handle_squash(
let current_branch = env.require_branch("squash")?.to_string();
let ctx = env.context(yes);
let resolved = env.resolved();
- let generator = CommitGenerator::new(&resolved.commit_generation);
+ // Defer project-guidance approval until we know an LLM call will happen
+ // (after the NoCommitsAhead / AlreadySingleCommit early-exits). When the
+ // caller pre-approved via an upstream batch (e.g. `wt merge`), use that
+ // value directly to avoid a second prompt mid-flow.
+ let llm_configured = resolved.commit_generation.is_configured();
+ let approve_guidance = || -> anyhow::Result<Option<String>> {
+ match &pre_approved_guidance {
+ PreApprovedGuidance::Resolved(value) => Ok(value.clone()),
+ PreApprovedGuidance::RunOwnGate if llm_configured => {
+ approve_commit_template_append(&ctx)
+ }
+ PreApprovedGuidance::RunOwnGate => Ok(None),
+ }
+ };
// CLI flag overrides config value
let stage_mode = stage.unwrap_or(resolved.commit.stage());
@@ -153,6 +185,15 @@ pub fn handle_squash(
return Ok(SquashResult::NoCommitsAhead(integration_target));
}
+ if commit_count == 1 && !has_staged {
+ // Single commit, no staged changes - already squashed
+ return Ok(SquashResult::AlreadySingleCommit);
+ }
+
+ // From here on, an LLM call may happen — gate the project append.
+ let project_append = approve_guidance()?;
+ let generator = CommitGenerator::new(&resolved.commit_generation, project_append.as_deref());
+
if commit_count == 0 && has_staged {
// Just staged changes, no commits - commit them directly (no squashing needed)
let CommitOutcome {
@@ -167,11 +208,6 @@ pub fn handle_squash(
});
}
- if commit_count == 1 && !has_staged {
- // Single commit, no staged changes - already squashed
- return Ok(SquashResult::AlreadySingleCommit);
- }
-
// Either multiple commits OR single commit with staged changes - squash them
// Get diff stats early for display in progress message
let range = format!("{}..HEAD", merge_base);
@@ -245,6 +281,7 @@ pub fn handle_squash(
&current_branch,
repo_name,
&resolved.commit_generation,
+ project_append.as_deref(),
)?;
// Display the generated commit message
@@ -303,21 +340,23 @@ pub fn handle_squash(
///
/// Builds and outputs the squash prompt without running the LLM or squashing.
pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {
- preview_squash(target, false)
+ // `--show-prompt` never invokes the LLM, so the `yes` flag is irrelevant
+ // — pass false; the guidance gate inside `preview_squash` is dry-run only.
+ preview_squash(target, false, false)
}
/// Handle `wt step squash --dry-run`
///
/// Renders the squash prompt, prints the LLM command, generates the message, and prints
/// it without resetting, running hooks, or committing.
-pub fn step_dry_run_squash(target: Option<&str>) -> anyhow::Result<()> {
- preview_squash(target, true)
+pub fn step_dry_run_squash(target: Option<&str>, yes: bool) -> anyhow::Result<()> {
+ preview_squash(target, true, yes)
}
/// Shared implementation for `--show-prompt` and `--dry-run` on squash. `--show-prompt`
/// (`dry_run = false`) outputs only the rendered prompt; `--dry-run` additionally calls
/// the LLM and prints the command and the generated message.
-fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {
+fn preview_squash(target: Option<&str>, dry_run: bool, yes: bool) -> anyhow::Result<()> {
let repo = Repository::current()?;
let config = UserConfig::load().context("Failed to load config")?;
let project_id = repo.project_identifier().ok();
@@ -341,6 +380,10 @@ fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {
.and_then(|n| n.to_str())
.unwrap_or("repo");
+ let env = CommandEnv::for_action(config)?;
+ let ctx = env.context(yes);
+ let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;
+
let prompt = crate::llm::build_squash_prompt(
&integration_target,
&merge_base,
@@ -348,6 +391,7 @@ fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {
&current_branch,
repo_name,
&commit_config,
+ project_append.as_deref(),
)?;
if !dry_run {
println!("{}", prompt);
@@ -360,6 +404,7 @@ fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {
&current_branch,
repo_name,
&commit_config,
+ project_append.as_deref(),
)?;
print_dry_run(&prompt, &commit_config, &message)
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 35d3f777c..09c3766f0 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -128,7 +128,10 @@ pub use expansion::{
validate_template_syntax, vars_available_in,
};
pub use hooks::HooksConfig;
-pub use project::{ProjectCiConfig, ProjectConfig, ProjectListConfig, valid_project_config_keys};
+pub use project::{
+ ProjectCiConfig, ProjectCommitConfig, ProjectCommitGenerationConfig, ProjectConfig,
+ ProjectListConfig, valid_project_config_keys,
+};
pub use unknown_tree::{
UnknownAnalysis, UnknownTree, UnknownWarning, collect_unknown_warnings, compute_unknown_tree,
};
@@ -603,6 +606,7 @@ squash-template-file = "~/file.txt"
template_file: None,
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
assert_snapshot!(toml::to_string(&config).unwrap(), @r#"
diff --git a/src/config/project.rs b/src/config/project.rs
index 3b25dd9cf..7cfded836 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -59,6 +59,39 @@ pub struct ProjectCiConfig {
pub platform: Option<String>,
}
+/// Project-level commit message configuration. *(Experimental — fields may
+/// change in future releases.)*
+///
+/// Only fields appropriate as shared, checked-in settings live here. The LLM
+/// command and full prompt template stay in user/system config — they
+/// describe per-developer environment (which CLI is installed, which agent
+/// they prefer).
+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
+pub struct ProjectCommitConfig {
+ /// Commit message generation settings shared across the team.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub generation: Option<ProjectCommitGenerationConfig>,
+}
+
+/// Project-level commit message generation settings.
+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, JsonSchema)]
+pub struct ProjectCommitGenerationConfig {
+ /// Text appended to the commit and squash prompts inside a
+ /// `<project-guidance>` block.
+ ///
+ /// Rendered with the same minijinja context as the main commit/squash
+ /// template (`{{ branch }}`, `{{ git_diff }}`, etc.), so it can
+ /// reference template variables directly. Use this for project-wide
+ /// commit conventions (e.g. "use conventional commits", "reference
+ /// issue numbers"). The user config has a `[commit.generation]
+ /// template-append` of its own; it renders into a separate
+ /// `<user-guidance>` block immediately before this one. The first time
+ /// the rendered text would reach the LLM, worktrunk prompts the user to
+ /// approve the raw fragment — the same gate as project-defined commands.
+ #[serde(default, rename = "template-append")]
+ pub template_append: Option<String>,
+}
+
/// Project-level forge configuration.
///
/// Names the forge explicitly, for repos where URL-based detection can't
@@ -124,6 +157,22 @@ impl ProjectConfig {
pub fn copy_ignored(&self) -> Option<&CopyIgnoredConfig> {
self.step.copy_ignored.as_ref()
}
+
+ /// Project-level commit-message append fragment (trimmed, empty
+ /// treated as unset).
+ ///
+ /// Rendered with the main commit/squash template's variable context and
+ /// appended to the LLM prompt inside a `<project-guidance>` block.
+ /// Callers must gate the first use through the approval system before
+ /// sending the rendered output to the LLM.
+ pub fn commit_template_append(&self) -> Option<&str> {
+ self.commit
+ .generation
+ .as_ref()
+ .and_then(|g| g.template_append.as_deref())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ }
}
/// Project-specific configuration with hooks.
@@ -172,6 +221,10 @@ pub struct ProjectConfig {
#[serde(default, skip_serializing_if = "is_default")]
pub forge: ProjectForgeConfig,
+ /// Project-wide commit message settings (shared across teammates)
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub commit: ProjectCommitConfig,
+
/// Configuration for `wt step` subcommands.
#[serde(default, skip_serializing_if = "is_default")]
pub step: StepConfig,
@@ -458,4 +511,55 @@ platform = "github"
let cloned = config.clone();
assert_eq!(config, cloned);
}
+
+ // ============================================================================
+ // ProjectCommitConfig Tests
+ // ============================================================================
+
+ #[test]
+ fn test_commit_template_append_parses() {
+ let toml = r#"
+[commit.generation]
+template-append = "Use conventional commits"
+"#;
+ let config: ProjectConfig = toml::from_str(toml).unwrap();
+ assert_eq!(
+ config.commit_template_append(),
+ Some("Use conventional commits")
+ );
+ }
+
+ /// `commit_template_append()` trims whitespace and treats a blank value
+ /// as unset. Otherwise an empty `<project-guidance>` block would still
+ /// render (confusing the LLM) and an empty approval would prompt.
+ #[test]
+ fn test_commit_template_append_blank_treated_as_unset() {
+ let toml = r#"
+[commit.generation]
+template-append = " \n\t "
+"#;
+ let config: ProjectConfig = toml::from_str(toml).unwrap();
+ assert_eq!(config.commit_template_append(), None);
+
+ // Whitespace inside the body is preserved — only leading/trailing trimmed.
+ let toml = r#"
+[commit.generation]
+template-append = " - a\n - b "
+"#;
+ let config: ProjectConfig = toml::from_str(toml).unwrap();
+ assert_eq!(config.commit_template_append(), Some("- a\n - b"));
+ }
+
+ #[test]
+ fn test_commit_template_append_missing_returns_none() {
+ let config = ProjectConfig::default();
+ assert_eq!(config.commit_template_append(), None);
+
+ // `[commit.generation]` present but no `template-append` field also returns None.
+ let toml = r#"
+[commit.generation]
+"#;
+ let config: ProjectConfig = toml::from_str(toml).unwrap();
+ assert_eq!(config.commit_template_append(), None);
+ }
}
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 1c805f2b1..bf4c88717 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -64,6 +64,20 @@ pub struct CommitGenerationConfig {
/// Supports tilde expansion (e.g., "~/.config/worktrunk/squash-template.txt")
#[serde(default, rename = "squash-template-file")]
pub squash_template_file: Option<String>,
+
+ /// Inline text appended to the commit and squash prompts inside a
+ /// `<user-guidance>` block, after the main template's `<style>`
+ /// section. Rendered as a minijinja template with the same variables
+ /// (`{{ branch }}`, `{{ git_diff }}`, etc.). Unlike `template`, this
+ /// *adds to* the default prompt instead of replacing it — use it for
+ /// personal commit-message preferences without restating the whole
+ /// template. The project config has a `[commit.generation]
+ /// template-append` of its own; it renders into a separate
+ /// `<project-guidance>` block right after this one.
+ ///
+ /// *(Experimental — may change in future releases.)*
+ #[serde(default, rename = "template-append")]
+ pub template_append: Option<String>,
}
impl CommitGenerationConfig {
@@ -105,6 +119,10 @@ impl Merge for CommitGenerationConfig {
template_file,
squash_template,
squash_template_file,
+ template_append: other
+ .template_append
+ .clone()
+ .or_else(|| self.template_append.clone()),
}
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 3971d427e..80a445533 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -750,6 +750,7 @@ fn test_merge_commit_generation_config() {
template_file: Some("~/.config/template.txt".to_string()),
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let override_config = CommitGenerationConfig {
command: Some("claude -p --model=haiku".to_string()), // Override
@@ -757,6 +758,7 @@ fn test_merge_commit_generation_config() {
template_file: None, // Fall back to base
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let merged = base.merge_with(&override_config);
@@ -766,6 +768,28 @@ fn test_merge_commit_generation_config() {
assert_eq!(merged.template_file, None);
}
+#[test]
+fn test_merge_commit_generation_template_append() {
+ // Override wins when set; otherwise the base value carries through.
+ let base = CommitGenerationConfig {
+ template_append: Some("base append".to_string()),
+ ..Default::default()
+ };
+ let override_config = CommitGenerationConfig {
+ template_append: Some("override append".to_string()),
+ ..Default::default()
+ };
+ assert_eq!(
+ base.merge_with(&override_config).template_append,
+ Some("override append".to_string())
+ );
+ assert_eq!(
+ base.merge_with(&CommitGenerationConfig::default())
+ .template_append,
+ Some("base append".to_string())
+ );
+}
+
#[test]
fn test_commit_generation_merge_mutual_exclusivity() {
// Global has template_file, project has template
diff --git a/src/llm.rs b/src/llm.rs
index 3481d7900..5bdaeb297 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -251,6 +251,15 @@ struct TemplateContext<'a> {
commits: &'a [String],
/// Target branch for merge (squash only)
target_branch: Option<&'a str>,
+ /// Approved project-level append fragment. `None` when no project
+ /// `template-append` is set or the user declined approval. The
+ /// user-level append fragment is read from the [`CommitGenerationConfig`]
+ /// directly (it needs no approval). Both fragments are themselves
+ /// minijinja templates — `build_prompt` renders each one and exposes
+ /// them as the `user_guidance` and `project_guidance` variables, which
+ /// the default templates wrap in `<user-guidance>` / `<project-guidance>`
+ /// blocks.
+ project_append: Option<&'a str>,
}
/// Default template for commit message prompts
@@ -269,7 +278,15 @@ const DEFAULT_TEMPLATE: &str = r#"<task>Write a commit message for the staged ch
- Match recent commit style (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<diffstat>
{{ git_diff_stat }}
</diffstat>
@@ -302,7 +319,15 @@ const DEFAULT_SQUASH_TEMPLATE: &str = r#"<task>Write a commit message for the co
- Match the style of commits being squashed (conventional commits if used)
- Describe the change, not the intent or benefit
</style>
-
+{% if user_guidance %}
+<user-guidance>
+{{ user_guidance }}
+</user-guidance>
+{% endif %}{% if project_guidance %}
+<project-guidance>
+{{ project_guidance }}
+</project-guidance>
+{% endif %}
<commits branch="{{ branch }}" target="{{ target_branch }}">
{% for commit in commits %}- {{ commit }}
{% endfor %}</commits>
@@ -486,15 +511,53 @@ fn build_prompt(
// Reverse commits so they're in chronological order (oldest first)
let commits_chronological: Vec<&String> = context.commits.iter().rev().collect();
+ let empty_commits: Vec<String> = vec![];
+
+ // The append fragments are themselves minijinja templates. Render each
+ // one in its own pass with the same variable context so it doesn't share
+ // scope with the parent template (and can't recursively reference
+ // itself), then expose them separately as `user_guidance` /
+ // `project_guidance` so the default templates can label each by
+ // provenance. The user fragment needs no approval (it's the developer's
+ // own config); the project fragment is gated upstream and arrives here
+ // as `context.project_append` (or `None` if declined). Empty string when
+ // a source is absent — the templates gate the block on truthiness.
+ let render_fragment = |fragment: &str| -> anyhow::Result<String> {
+ let frag_tmpl = env.template_from_str(fragment)?;
+ Ok(frag_tmpl.render(minijinja::context! {
+ git_diff => context.git_diff,
+ git_diff_stat => context.git_diff_stat,
+ branch => context.branch,
+ recent_commits => context.recent_commits.unwrap_or(&empty_commits),
+ repo => context.repo_name,
+ commits => &commits_chronological,
+ target_branch => context.target_branch.unwrap_or(""),
+ })?)
+ };
+ let user_guidance = match config
+ .template_append
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ {
+ Some(fragment) => render_fragment(fragment)?,
+ None => String::new(),
+ };
+ let project_guidance = match context.project_append {
+ Some(fragment) => render_fragment(fragment)?,
+ None => String::new(),
+ };
let rendered = tmpl.render(minijinja::context! {
git_diff => context.git_diff,
git_diff_stat => context.git_diff_stat,
branch => context.branch,
- recent_commits => context.recent_commits.unwrap_or(&vec![]),
+ recent_commits => context.recent_commits.unwrap_or(&empty_commits),
repo => context.repo_name,
commits => commits_chronological,
target_branch => context.target_branch.unwrap_or(""),
+ user_guidance => user_guidance,
+ project_guidance => project_guidance,
})?;
Ok(rendered)
@@ -502,26 +565,38 @@ fn build_prompt(
/// `index_override` is forwarded to git operations that read the staging area, so
/// `--dry-run` can preview against a temp index without touching the user's real one.
+///
+/// `project_append` is the approved project-level append fragment (or
+/// `None` to skip). It is rendered with the main template's context and
+/// appended to the prompt inside a `<project-guidance>` block; the
+/// user-level append fragment from the [`CommitGenerationConfig`] renders
+/// separately into `<user-guidance>`.
pub(crate) fn generate_commit_message(
commit_generation_config: &CommitGenerationConfig,
index_override: Option<&Path>,
+ project_append: Option<&str>,
) -> anyhow::Result<String> {
// Check if commit generation is configured (non-empty command)
if commit_generation_config.is_configured() {
let command = commit_generation_config.command.as_ref().unwrap();
// Commit generation is explicitly configured - fail if it doesn't work
- return try_generate_commit_message(command, commit_generation_config, index_override)
- .map_err(|e| {
- worktrunk::git::GitError::LlmCommandFailed {
- command: command.clone(),
- error: e.to_string(),
- reproduction_command: Some(format_reproduction_command(
- "wt step commit --show-prompt",
- command,
- )),
- }
- .into()
- });
+ return try_generate_commit_message(
+ command,
+ commit_generation_config,
+ index_override,
+ project_append,
+ )
+ .map_err(|e| {
+ worktrunk::git::GitError::LlmCommandFailed {
+ command: command.clone(),
+ error: e.to_string(),
+ reproduction_command: Some(format_reproduction_command(
+ "wt step commit --show-prompt",
+ command,
+ )),
+ }
+ .into()
+ });
}
// Fallback: generate a descriptive commit message based on changed files
@@ -563,8 +638,9 @@ fn try_generate_commit_message(
command: &str,
config: &CommitGenerationConfig,
index_override: Option<&Path>,
+ project_append: Option<&str>,
) -> anyhow::Result<String> {
- let prompt = build_commit_prompt(config, index_override)?;
+ let prompt = build_commit_prompt(config, index_override, project_append)?;
execute_llm_command(command, &prompt)
}
@@ -596,6 +672,7 @@ fn run_git_capture(cmd: Cmd, what: &str) -> anyhow::Result<String> {
pub(crate) fn build_commit_prompt(
config: &CommitGenerationConfig,
index_override: Option<&Path>,
+ project_append: Option<&str>,
) -> anyhow::Result<String> {
let repo = Repository::current()?;
let cwd = repo.discovery_path().to_path_buf();
@@ -645,6 +722,7 @@ pub(crate) fn build_commit_prompt(
repo_name,
commits: &[],
target_branch: None,
+ project_append,
};
build_prompt(config, TemplateType::Commit, &context)
}
@@ -656,6 +734,7 @@ pub(crate) fn generate_squash_message(
current_branch: &str,
repo_name: &str,
commit_generation_config: &CommitGenerationConfig,
+ project_append: Option<&str>,
) -> anyhow::Result<String> {
// Check if commit generation is configured (non-empty command)
if commit_generation_config.is_configured() {
@@ -668,6 +747,7 @@ pub(crate) fn generate_squash_message(
current_branch,
repo_name,
commit_generation_config,
+ project_append,
)?;
return execute_llm_command(command, &prompt).map_err(|e| {
@@ -704,6 +784,7 @@ pub(crate) fn build_squash_prompt(
current_branch: &str,
repo_name: &str,
config: &CommitGenerationConfig,
+ project_append: Option<&str>,
) -> anyhow::Result<String> {
let repo = Repository::current()?;
@@ -733,6 +814,7 @@ pub(crate) fn build_squash_prompt(
repo_name,
commits: subjects,
target_branch: Some(target_branch),
+ project_append,
};
build_prompt(config, TemplateType::Squash, &context)
}
@@ -784,6 +866,10 @@ pub(crate) fn test_commit_generation(
repo_name: "test-repo",
commits: &[],
target_branch: None,
+ // The connectivity test sends a synthetic prompt — keep it independent
+ // of any project guidance so it doesn't surface team-policy text in
+ // `wt config show`.
+ project_append: None,
};
let prompt = build_prompt(commit_generation_config, TemplateType::Commit, &context)?;
@@ -860,6 +946,7 @@ mod tests {
repo_name,
commits: &[],
target_branch: None,
+ project_append: None,
}
}
@@ -880,6 +967,7 @@ mod tests {
repo_name,
commits,
target_branch: Some(target_branch),
+ project_append: None,
}
}
@@ -997,6 +1085,7 @@ mod tests {
template_file: None,
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let context = commit_context("my diff", "feature", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
@@ -1012,6 +1101,7 @@ mod tests {
template_file: None,
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
@@ -1026,6 +1116,7 @@ mod tests {
template_file: None,
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
@@ -1043,6 +1134,7 @@ mod tests {
template_file: None,
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let commits = vec!["commit1".to_string(), "commit2".to_string()];
let context = commit_context("my diff", "feature", Some(&commits), "myrepo");
@@ -1055,6 +1147,195 @@ mod tests {
);
}
+ #[test]
+ fn test_default_commit_template_renders_project_fragment() {
+ let config = CommitGenerationConfig::default();
+ let mut context = commit_context("diff content", "main", None, "myrepo");
+ context.project_append = Some("- Use conventional commits\n- Reference the issue");
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ // The block lives between `<style>` and `<diffstat>`, only when guidance is set.
+ assert_snapshot!(prompt, @r#"
+ <task>Write a commit message for the staged changes below.</task>
+
+ <format>
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
+ - Output only the commit message, no quotes or code blocks
+ </format>
+
+ <style>
+ - Imperative mood: "Add feature" not "Added feature"
+ - Match recent commit style (conventional commits if used)
+ - Describe the change, not the intent or benefit
+ </style>
+
+ <project-guidance>
+ - Use conventional commits
+ - Reference the issue
+ </project-guidance>
+
+ <diffstat>
+
+ </diffstat>
+
+ <diff>
+ diff content
+ </diff>
+
+ <context>
+ Branch: main
+
+ </context>
+ "#);
+ }
+
+ /// The user-level `template-append` (from `CommitGenerationConfig`,
+ /// no approval) renders into a `<user-guidance>` block.
+ #[test]
+ fn test_user_template_append_renders() {
+ let config = CommitGenerationConfig {
+ template_append: Some("- Personal: explain the why".to_string()),
+ ..Default::default()
+ };
+ let context = commit_context("diff content", "main", None, "myrepo");
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert!(
+ prompt.contains("<user-guidance>\n- Personal: explain the why\n</user-guidance>"),
+ "user append should render in <user-guidance>, got:\n{prompt}"
+ );
+ }
+
+ /// User and project appends render into separate provenance-labeled
+ /// blocks, `<user-guidance>` before `<project-guidance>`.
+ #[test]
+ fn test_user_and_project_append_combined() {
+ let config = CommitGenerationConfig {
+ template_append: Some("USER LINE".to_string()),
+ ..Default::default()
+ };
+ let mut context = commit_context("d", "main", None, "repo");
+ context.project_append = Some("PROJECT LINE");
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ let user_at = prompt.find("<user-guidance>\nUSER LINE\n</user-guidance>");
+ let project_at = prompt.find("<project-guidance>\nPROJECT LINE\n</project-guidance>");
+ assert!(
+ matches!((user_at, project_at), (Some(u), Some(p)) if u < p),
+ "<user-guidance> should precede <project-guidance>, got:\n{prompt}"
+ );
+ }
+
+ /// A blank user append is treated as unset — no empty block rendered.
+ #[test]
+ fn test_user_template_append_blank_is_unset() {
+ let config = CommitGenerationConfig {
+ template_append: Some(" \n\t ".to_string()),
+ ..Default::default()
+ };
+ let context = commit_context("d", "main", None, "repo");
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert!(
+ !prompt.contains("<user-guidance>"),
+ "blank user append must not render a block, got:\n{prompt}"
+ );
+ }
+
+ /// The user append is itself a minijinja template, rendered against the
+ /// same context as the main template.
+ #[test]
+ fn test_user_template_append_expands_variables() {
+ let config = CommitGenerationConfig {
+ template_append: Some("Repo {{ repo }} on {{ branch }}".to_string()),
+ ..Default::default()
+ };
+ let context = commit_context("d", "feat/x", None, "myrepo");
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert!(
+ prompt.contains("Repo myrepo on feat/x"),
+ "user append should expand variables, got:\n{prompt}"
+ );
+ assert!(
+ !prompt.contains("{{ repo }}"),
+ "user append was not rendered:\n{prompt}"
+ );
+ }
+
+ /// The project fragment is itself a minijinja template — variables in it
+ /// expand against the same context as the main template. Without this
+ /// test, the pre-render pass in `build_prompt` could regress to a raw
+ /// string injection and nothing else would catch it.
+ #[test]
+ fn test_project_fragment_expands_template_variables() {
+ let config = CommitGenerationConfig::default();
+ let mut context = commit_context("diff", "feature/auth", None, "myrepo");
+ context.project_append = Some("Branch: {{ branch }} ({{ repo }})");
+ let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
+ assert!(
+ prompt.contains("Branch: feature/auth (myrepo)"),
+ "expected minijinja-expanded fragment in prompt, got:\n{prompt}"
+ );
+ // Make sure the unexpanded form didn't sneak through.
+ assert!(
+ !prompt.contains("{{ branch }}"),
+ "fragment was not rendered:\n{prompt}"
+ );
+ }
+
+ /// A malformed fragment must surface its render error rather than slipping
+ /// into the LLM prompt as literal text.
+ #[test]
+ fn test_project_fragment_render_error_propagates() {
+ let config = CommitGenerationConfig::default();
+ let mut context = commit_context("diff", "main", None, "repo");
+ context.project_append = Some("Unclosed {{ branch");
+ let err = build_prompt(&config, TemplateType::Commit, &context).unwrap_err();
+ assert!(
+ err.to_string().contains("syntax error")
+ || err.to_string().to_lowercase().contains("unexpected"),
+ "expected minijinja syntax error, got: {err}"
+ );
+ }
+
+ #[test]
+ fn test_default_squash_template_renders_project_fragment() {
+ let config = CommitGenerationConfig::default();
+ let commits = vec!["feat: A".to_string(), "fix: B".to_string()];
+ let mut context = squash_context("diff content", "feature", None, "repo", &commits, "main");
+ context.project_append = Some("- Reference the related issue");
+ let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
+ assert_snapshot!(prompt, @r#"
+ <task>Write a commit message for the combined effect of these commits.</task>
+
+ <format>
+ - Subject line under 50 chars
+ - For material changes, add a blank line then a body paragraph explaining the change
+ - Output only the commit message, no quotes or code blocks
+ </format>
+
+ <style>
+ - Imperative mood: "Add feature" not "Added feature"
+ - Match the style of commits being squashed (conventional commits if used)
+ - Describe the change, not the intent or benefit
+ </style>
+
+ <project-guidance>
+ - Reference the related issue
+ </project-guidance>
+
+ <commits branch="feature" target="main">
+ - fix: B
+ - feat: A
+ </commits>
+
+ <diffstat>
+
+ </diffstat>
+
+ <diff>
+ diff content
+ </diff>
+ "#);
+ }
+
#[test]
fn test_build_squash_prompt_with_default_template() {
let config = CommitGenerationConfig::default();
@@ -1102,6 +1383,7 @@ mod tests {
.to_string(),
),
squash_template_file: None,
+ template_append: None,
};
let commits = vec!["A".to_string(), "B".to_string()];
let context = squash_context("diff", "feature", None, "repo", &commits, "main");
@@ -1128,6 +1410,7 @@ mod tests {
template_file: None,
squash_template: Some("{% for x in commits %}{{ x }".to_string()),
squash_template_file: None,
+ template_append: None,
};
let commits: Vec<String> = vec![];
let context = squash_context("diff", "feature", None, "repo", &commits, "main");
@@ -1143,6 +1426,7 @@ mod tests {
template_file: None,
squash_template: Some(" \n ".to_string()),
squash_template_file: None,
+ template_append: None,
};
let commits: Vec<String> = vec![];
let context = squash_context("diff", "feature", None, "repo", &commits, "main");
@@ -1162,6 +1446,7 @@ mod tests {
.to_string(),
),
squash_template_file: None,
+ template_append: None,
};
let commits = vec!["A".to_string(), "B".to_string()];
let recent = vec!["prev1".to_string(), "prev2".to_string()];
@@ -1206,6 +1491,7 @@ Diff follows:
template_file: None,
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
// With commits — exercises if-branch, filters, loop.index, whitespace control
@@ -1261,6 +1547,7 @@ Single commit: {{ commits[0] }}
.to_string(),
),
squash_template_file: None,
+ template_append: None,
};
// Multiple commits — reversed for chronological order (C, B, A)
@@ -1305,6 +1592,7 @@ Single commit: {{ commits[0] }}
template_file: Some(template_path.to_string_lossy().to_string()),
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let context = commit_context("my diff", "feature", None, "myrepo");
let result = build_prompt(&config, TemplateType::Commit, &context);
@@ -1326,6 +1614,7 @@ Single commit: {{ commits[0] }}
template_file: Some("/nonexistent/path/template.txt".to_string()),
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
@@ -1351,6 +1640,7 @@ Single commit: {{ commits[0] }}
template_file: None,
squash_template: None,
squash_template_file: Some(template_path.to_string_lossy().to_string()),
+ template_append: None,
};
let commits = vec!["A".to_string(), "B".to_string()];
let context = squash_context("diff", "feature", None, "repo", &commits, "main");
@@ -1373,6 +1663,7 @@ Single commit: {{ commits[0] }}
template_file: Some("~/nonexistent_template_for_test.txt".to_string()),
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let context = commit_context("diff", "main", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
@@ -1396,6 +1687,7 @@ Single commit: {{ commits[0] }}
template_file: None,
squash_template: None,
squash_template_file: None,
+ template_append: None,
};
let context = commit_context("diff", "feature", None, "repo");
let result = build_prompt(&config, TemplateType::Commit, &context);
diff --git a/src/main.rs b/src/main.rs
index 0d57b2c3e..da0f7e668 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -248,7 +248,7 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
if args.show_prompt {
commands::step_show_squash_prompt(args.target.as_deref())
} else if args.dry_run {
- commands::step_dry_run_squash(args.target.as_deref())
+ commands::step_dry_run_squash(args.target.as_deref(), yes)
} else {
// Approval is handled inside handle_squash (like step_commit).
let repo = Repository::current()?;
@@ -266,6 +266,7 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
hooks,
args.stage,
&mut announcer,
+ commands::PreApprovedGuidance::RunOwnGate,
)?;
announcer.flush()?;
if format == SwitchFormat::Json {
diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rs
index 201036b40..2f93b08db 100644
--- a/tests/integration_tests/approval_pty.rs
+++ b/tests/integration_tests/approval_pty.rs
@@ -8,7 +8,7 @@
//! to simulate interactive terminals. The non-PTY tests in `approval_ui.rs` verify the
//! error case (non-TTY environments).
-use crate::common::pty::{build_pty_command, exec_cmd_in_pty_prompted};
+use crate::common::pty::{build_pty_command, exec_cmd_in_pty, exec_cmd_in_pty_prompted};
use crate::common::{TestRepo, add_pty_binary_path_filters, add_pty_filters, repo, wt_bin};
use insta::assert_snapshot;
use rstest::rstest;
@@ -594,12 +594,209 @@ command = "cat >/dev/null && echo 'feat: test commit message'"
assert_no_spurious_no_hooks(&output);
}
+/// Project commit-message append must be approved before the LLM sees it.
+///
+/// Accept → the fragment is included in the prompt the LLM receives.
+#[rstest]
+fn test_commit_template_append_approval_accept(mut repo: TestRepo) {
+ // Remove origin so worktrunk uses directory name as project identifier.
+ repo.run_git(&["remote", "remove", "origin"]);
+
+ repo.write_project_config(
+ r#"
+[commit.generation]
+template-append = "Use conventional commits"
+"#,
+ );
+ repo.commit("Add project commit append");
+
+ let feature_wt = repo.add_worktree("feature-guidance-accept");
+ std::fs::write(feature_wt.join("new-file.txt"), "new content").unwrap();
+
+ // Sink the LLM prompt to a file so we can confirm the guidance reached it.
+ let prompt_capture = repo.root_path().join("captured-prompt.txt");
+ let prompt_capture_str = prompt_capture.display().to_string();
+ repo.write_test_config(&format!(
+ r#"
+[commit.generation]
+command = "tee {prompt_capture_str} > /dev/null && echo 'feat: accept guidance'"
+"#
+ ));
+
+ let env_vars = test_env_vars_with_shell(&repo);
+
+ let (output, exit_code) =
+ exec_wt_in_pty_cwd(&feature_wt, &["step", "commit"], &env_vars, "y\n");
+
+ assert_eq!(
+ exit_code, 0,
+ "Commit should succeed when guidance approved. Output:\n{output}"
+ );
+ assert!(
+ output.contains("commit-template-append"),
+ "Approval prompt should label the append phase. Output:\n{output}"
+ );
+ assert!(
+ output.contains("Use conventional commits"),
+ "Approval prompt should display the append text. Output:\n{output}"
+ );
+
+ let captured = std::fs::read_to_string(&prompt_capture).expect("captured prompt");
+ assert!(
+ captured.contains("<project-guidance>") && captured.contains("Use conventional commits"),
+ "Append should be sent to the LLM inside <project-guidance>. Captured:\n{captured}"
+ );
+
+ // Second run: the fragment is already approved, so it must NOT re-prompt
+ // — exercises the `is_command_approved` cache-hit path in
+ // `approve_commit_template_append`.
+ std::fs::write(feature_wt.join("second.txt"), "more content").unwrap();
+ let cmd = build_pty_command(
+ wt_bin().to_str().unwrap(),
+ &["step", "commit"],
+ &feature_wt,
+ &env_vars,
+ None,
+ );
+ let (output2, exit2) = exec_cmd_in_pty(cmd, "");
+ assert_eq!(
+ exit2, 0,
+ "Second commit should succeed without re-prompting. Output:\n{output2}"
+ );
+ assert!(
+ !output2.contains("Allow and remember?"),
+ "Already-approved append must not prompt again. Output:\n{output2}"
+ );
+ let captured2 = std::fs::read_to_string(&prompt_capture).expect("captured prompt (2)");
+ assert!(
+ captured2.contains("<project-guidance>") && captured2.contains("Use conventional commits"),
+ "Approved append should still reach the LLM on re-run. Captured:\n{captured2}"
+ );
+}
+
+/// Declining the append prompt continues without it — the LLM receives the
+/// rest of the prompt as if no project append were configured.
+#[rstest]
+fn test_commit_template_append_approval_decline(mut repo: TestRepo) {
+ repo.run_git(&["remote", "remove", "origin"]);
+
+ repo.write_project_config(
+ r#"
+[commit.generation]
+template-append = "Reference the issue ID"
+"#,
+ );
+ repo.commit("Add project commit append");
+
+ let feature_wt = repo.add_worktree("feature-guidance-decline");
+ std::fs::write(feature_wt.join("new-file.txt"), "new content").unwrap();
+
+ let prompt_capture = repo.root_path().join("captured-prompt.txt");
+ let prompt_capture_str = prompt_capture.display().to_string();
+ repo.write_test_config(&format!(
+ r#"
+[commit.generation]
+command = "tee {prompt_capture_str} > /dev/null && echo 'feat: decline guidance'"
+"#
+ ));
+
+ let env_vars = test_env_vars_with_shell(&repo);
+
+ let (output, exit_code) =
+ exec_wt_in_pty_cwd(&feature_wt, &["step", "commit"], &env_vars, "n\n");
+
+ assert_eq!(
+ exit_code, 0,
+ "Commit should succeed even when template declined. Output:\n{output}"
+ );
+ assert!(
+ output.contains("Project commit guidance declined"),
+ "Should announce that the append was declined. Output:\n{output}"
+ );
+
+ let captured = std::fs::read_to_string(&prompt_capture).expect("captured prompt");
+ assert!(
+ !captured.contains("Reference the issue ID"),
+ "Declined append must not reach the LLM. Captured:\n{captured}"
+ );
+ assert!(
+ !captured.contains("<project-guidance>"),
+ "No <project-guidance> block when append declined. Captured:\n{captured}"
+ );
+}
+
+/// `wt merge` with both project hooks and a commit append bundles the two
+/// items into the same approval prompt — the user sees one prompt covering
+/// both, not one for hooks and a second for the append mid-merge.
+#[rstest]
+fn test_merge_bundles_append_into_hook_approval(mut repo: TestRepo) {
+ repo.run_git(&["remote", "remove", "origin"]);
+ repo.write_project_config(
+ r#"
+pre-commit = "echo 'pre-commit hook'"
+
+[commit.generation]
+template-append = "Reference the related issue"
+"#,
+ );
+ repo.commit("Add project config with hook + guidance");
+
+ let feature_wt = repo.add_worktree("feature-merge-bundle");
+ std::fs::write(feature_wt.join("new-file.txt"), "new content").unwrap();
+
+ let prompt_capture = repo.root_path().join("captured-prompt.txt");
+ let prompt_capture_str = prompt_capture.display().to_string();
+ repo.write_test_config(&format!(
+ r#"
+[commit.generation]
+command = "tee {prompt_capture_str} > /dev/null && echo 'feat: bundled'"
+"#
+ ));
+
+ let env_vars = test_env_vars_with_shell(&repo);
+
+ let (output, exit_code) = exec_wt_in_pty_cwd(&feature_wt, &["merge"], &env_vars, "y\n");
+
+ assert_eq!(
+ exit_code, 0,
+ "Merge should succeed when both prompts approved. Output:\n{output}"
+ );
+ assert!(
+ output.contains("pre-commit hook"),
+ "Bundled prompt should list the pre-commit hook command. Output:\n{output}"
+ );
+ assert!(
+ output.contains("commit-template-append") && output.contains("Reference the related issue"),
+ "Bundled prompt should list the commit append. Output:\n{output}"
+ );
+ // The downstream commit step must not present a second prompt.
+ let prompts = output.matches("Allow and remember?").count();
+ assert_eq!(
+ prompts, 1,
+ "Bundled approval should produce exactly one [y/N] prompt. Saw {prompts}. Output:\n{output}"
+ );
+
+ let captured = std::fs::read_to_string(&prompt_capture).expect("captured prompt");
+ assert!(
+ captured.contains("<project-guidance>") && captured.contains("Reference the related issue"),
+ "Approved append should reach the LLM. Captured:\n{captured}"
+ );
+}
+
/// `wt config approvals add` accepts the prompt — covers the success branch of
/// `add_approvals` after `approve_command_batch` returns Ok(true).
#[rstest]
fn test_config_approvals_add_accept(repo: TestRepo) {
repo.run_git(&["remote", "remove", "origin"]);
- repo.write_project_config(r#"pre-start = "echo 'test command'""#);
+ // Include a project commit append so `add_approvals` also collects the
+ // `commit-template-append` entry (covers that branch in add_approvals).
+ repo.write_project_config(
+ r#"pre-start = "echo 'test command'"
+
+[commit.generation]
+template-append = "Use conventional commits"
+"#,
+ );
repo.commit("Add config");
let env_vars = repo.test_env_vars();
@@ -611,6 +808,10 @@ fn test_config_approvals_add_accept(repo: TestRepo) {
output.contains("Commands approved"),
"Should show approval success. Output:\n{output}"
);
+ assert!(
+ output.contains("commit-template-append") && output.contains("Use conventional commits"),
+ "add should list the project commit append. Output:\n{output}"
+ );
}
/// `wt config approvals add` declines the prompt — covers the declined branch
diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rs
index c223ada45..eef5e66a0 100644
--- a/tests/integration_tests/help.rs
+++ b/tests/integration_tests/help.rs
@@ -11,7 +11,7 @@
//! only the presentation varies.
#![cfg(not(windows))]
-use crate::common::wt_command;
+use crate::common::{add_standard_env_redactions, wt_command};
use insta::Settings;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -19,6 +19,7 @@ use rstest::rstest;
fn snapshot_help(test_name: &str, args: &[&str]) {
let mut settings = Settings::clone_current();
settings.set_snapshot_path("../snapshots");
+ add_standard_env_redactions(&mut settings);
settings.bind(|| {
let mut cmd = wt_command();
cmd.args(args);
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap
index d56f79643..1af5065f8 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_suggests_user_config_for_commit_generation.snap
@@ -23,6 +23,7 @@ info:
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
NO_COLOR: ""
OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
@@ -69,7 +70,7 @@ exit_code: 0
  \ No newline at end of file
  +[commit.generation]
  +command = "claude"
-▲ Key commit-generation belongs in user config as [commit.generation]
+▲ Unknown key commit.generation.command will be ignored
SHELL INTEGRATION
▲ Shell integration not configured
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index f5a744882..2630fa246 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -12,14 +12,15 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
NO_COLOR: ""
PSModulePath: ""
RUST_LOG: warn
SHELL: ""
TERM: alacritty
- WORKTRUNK_APPROVALS_PATH: /nonexistent/wt/approvals.toml
- WORKTRUNK_CONFIG_PATH: /nonexistent/wt/config.toml
- WORKTRUNK_SYSTEM_CONFIG_PATH: /etc/xdg/worktrunk/config.toml
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
@@ -246,6 +247,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # - `{{ git_diff }}`, `{{ git_diff_stat }}` — diff content
  # - `{{ branch }}`, `{{ repo }}` — context
  # - `{{ recent_commits }}` — recent commit messages
+  # - `{{ user_guidance }}`, `{{ project_guidance }}` — rendered append fragments (see Appending to the prompt (https://worktrunk.dev/config/#appending-to-the-prompt))
  #
  # Default template:
  #
@@ -265,7 +267,15 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # - Match recent commit style (conventional commits if used)
  # - Describe the change, not the intent or benefit
  # </style>
-  #
+  # {% if user_guidance %}
+  # <user-guidance>
+  # {{ user_guidance }}
+  # </user-guidance>
+  # {% endif %}{% if project_guidance %}
+  # <project-guidance>
+  # {{ project_guidance }}
+  # </project-guidance>
+  # {% endif %}
  # <diffstat>
  # {{ git_diff_stat }}
  # </diffstat>
@@ -309,7 +319,15 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # - Match the style of commits being squashed (conventional commits if used)
  # - Describe the change, not the intent or benefit
  # </style>
-  #
+  # {% if user_guidance %}
+  # <user-guidance>
+  # {{ user_guidance }}
+  # </user-guidance>
+  # {% endif %}{% if project_guidance %}
+  # <project-guidance>
+  # {{ project_guidance }}
+  # </project-guidance>
+  # {% endif %}
  # <commits branch="{{ branch }}" target="{{ target_branch }}">
  # {% for commit in commits %}- {{ commit }}
  # {% endfor %}</commits>
@@ -325,6 +343,17 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # """
  # <!-- DEFAULT_SQUASH_TEMPLATE_END -->
  #
+  # #### Appending to the prompt [experimental]
+  #
+  # `template-append` adds to the prompt instead of replacing it. The value is rendered as its own minijinja template (same variables) and injected into the default templates' `{{ user_guidance }}` slot — a `<user-guidance>` block right after `<style>`. It applies to both commit and squash. Use it for personal preferences without restating the whole template:
+  #
+  # [commit.generation]
+  # template-append = """
+  # - Explain the rationale in the body, not just the change
+  # """
+  #
+  # The project config (https://worktrunk.dev/config/#project-configuration) has a `template-append` of its own; it renders into a separate `<project-guidance>` block right after `<user-guidance>`.
+  #
  # ## Hooks
  #
  # See `wt hook` (https://worktrunk.dev/hook/) for hook types, execution order, template variables, and examples. User hooks apply to all projects; project hooks (https://worktrunk.dev/config/#project-configuration) apply only to that repository.
@@ -362,6 +391,19 @@ With --project, creates .config/wt.toml in the current repositor
  # platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (experimental)
  # hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)
  #
+  # ## Commit-message append [experimental]
+  #
+  # Project-wide commit-message conventions appended to the LLM commit and squash prompts inside a `<project-guidance>` block, after the main template's `<style>` section (and after any user `<user-guidance>`). Rendered as a minijinja (https://docs.rs/minijinja/) template with the same variables as the main commit template (`{{ branch }}`, `{{ git_diff }}`, etc.), so it can reference them directly. The first time the fragment changes, `wt` prompts the user to approve it — the same one-shot gate
+  as project-defined hooks.
+  #
+  # [commit.generation]
+  # template-append = """
+  # - Use conventional commits (feat:, fix:, docs:, …)
+  # - Reference the relevant issue ID in the body
+  # """
+  #
+  # Only `template-append` is honored from the project file. The LLM command and the main prompt template stay in user config (https://worktrunk.dev/config/) — they describe per-developer environment (which CLI is installed, which agent the developer prefers). User config has a `[commit.generation] template-append` of its own; it renders into a separate `<user-guidance>` block immediately before this one.
+  #
  # ## Copy-ignored excludes
  #
  # Additional excludes for `wt step copy-ignored`:
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 01e6c57fe..86c305903 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -11,14 +11,15 @@ info:
GIT_EDITOR: ""
LANG: C
LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
NO_COLOR: ""
PSModulePath: ""
RUST_LOG: warn
SHELL: ""
TERM: alacritty
- WORKTRUNK_APPROVALS_PATH: /nonexistent/wt/approvals.toml
- WORKTRUNK_CONFIG_PATH: /nonexistent/wt/config.toml
- WORKTRUNK_SYSTEM_CONFIG_PATH: /etc/xdg/worktrunk/config.toml
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
@@ -294,6 +295,7 @@ Available variables:
- {{ git_diff }}, {{ git_diff_stat }} — diff content
- {{ branch }}, {{ repo }} — context
- {{ recent_commits }} — recent commit messages
+- {{ user_guidance }}, {{ project_guidance }} — rendered append fragments (see Appending to the prompt)
Default template:
@@ -312,7 +314,15 @@ Default template:
  - Match recent commit style (conventional commits if used)
  - Describe the change, not the intent or benefit
  </style>
- 
+  {% if user_guidance %}
+  <user-guidance>
+  {{ user_guidance }}
+  </user-guidance>
+  {% endif %}{% if project_guidance %}
+  <project-guidance>
+  {{ project_guidance }}
+  </project-guidance>
+  {% endif %}
  <diffstat>
  {{ git_diff_stat }}
  </diffstat>
@@ -354,7 +364,15 @@ Default template:
  - Match the style of commits being squashed (conventional commits if used)
  - Describe the change, not the intent or benefit
  </style>
- 
+  {% if user_guidance %}
+  <user-guidance>
+  {{ user_guidance }}
+  </user-guidance>
+  {% endif %}{% if project_guidance %}
+  <project-guidance>
+  {{ project_guidance }}
+  </project-guidance>
+  {% endif %}
  <commits branch="{{ branch }}" target="{{ target_branch }}">
  {% for commit in commits %}- {{ commit }}
  {% endfor %}</commits>
@@ -369,6 +387,17 @@ Default template:
 
  """
+Appending to the prompt [experimental]
+
+template-append adds to the prompt instead of replacing it. The value is rendered as its own minijinja template (same variables) and injected into the default templates' {{ user_guidance }} slot — a <user-guidance> block right after <style>. It applies to both commit and squash. Use it for personal preferences without restating the whole template:
+
+  [commit.generation]
+  template-append = """
+  - Explain the rationale in the body, not just the change
+  """
+
+The project config has a template-append of its own; it renders into a separate <project-guidance> block right after <user-guidance>.
+
Hooks
See wt hook for hook types, execution order, template variables, and examples. User hooks apply to all projects; project hooks apply only to that repository.
@@ -401,6 +430,18 @@ Name the forge explicitly for SSH aliases or self-hosted instances, where it can
  platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (experimental)
  hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)
+Commit-message append [experimental]
+
+Project-wide commit-message conventions appended to the LLM commit and squash prompts inside a <project-guidance> block, after the main template's <style> section (and after any user <user-guidance>). Rendered as a minijinja template with the same variables as the main commit template ({{ branch }}, {{ git_diff }}, etc.), so it can reference them directly. The first time the fragment changes, wt prompts the user to approve it — the same one-shot gate as project-defined hooks.
+
+  [commit.generation]
+  template-append = """
+  - Use conventional commits (feat:, fix:, docs:, …)
+  - Reference the relevant issue ID in the body
+  """
+
+Only template-append is honored from the project file. The LLM command and the main prompt template stay in user config — they describe per-developer environment (which CLI is installed, which agent the developer prefers). User config has a [commit.generation] template-append of its own; it renders into a separate <user-guidance> block immediately before this one.
+
Copy-ignored excludes
Additional excludes for wt step copy-ignored: