Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(config): keep hook pipelines' spelling and comments on save; expand ~ in PI_CODING_AGENT_DIR (#4151)
Maximilian Roos55d87b3f41ed
diff --git a/src/commands/config/pi.rs b/src/commands/config/pi.rsindex 94aa8ecd8..d6d6ac26b 100644--- a/src/commands/config/pi.rs+++ b/src/commands/config/pi.rs@@ -7,7 +7,7 @@//! oh-my-pi (`omp`) is a separate agent, with its own config root and hook//! API; it has its own command — see [`super::omp`].-use std::path::PathBuf;+use std::path::{Path, PathBuf};use anyhow::{Context, Result};use color_print::cformat;@@ -16,12 +16,17 @@ use worktrunk::styling::{eprintln, hint_message, warning_message};/// The extension source, embedded at compile time.const EXTENSION_SOURCE: &str = include_str!("../../../dev/pi-extension.ts");+/// Pi expands a leading `~` in `$PI_CODING_AGENT_DIR` (`getAgentDir` →+/// `normalizePath`), so a quoted `~/x` names a directory under home, not a+/// literal `~` beneath the current directory. oh-my-pi resolves the same+/// variable with a plain `path.resolve`, which is why [`super::omp`] leaves it+/// unexpanded.fn pi_agent_dir() -> Result<PathBuf> {if let Some(path) = std::env::var("PI_CODING_AGENT_DIR").ok().filter(|value| !value.is_empty()){- return Ok(PathBuf::from(path));+ return Ok(worktrunk::path::expand_tilde(Path::new(&path)).into_owned());}let home = worktrunk::path::home_dir().context("Could not determine home directory")?;diff --git a/src/config/user/persistence.rs b/src/config/user/persistence.rsindex 2aba08823..68a11e911 100644--- a/src/config/user/persistence.rs+++ b/src/config/user/persistence.rs@@ -8,6 +8,8 @@//! handles any new fields without manual wiring — if a struct field is//! serializable, save_to persists it.+use std::borrow::Cow;+use crate::config::{ConfigError, UnknownTree, compute_unknown_tree};use super::UserConfig;@@ -49,6 +51,8 @@ impl UserConfig {/// - Existing inline table, desired standard table: merge through the same/// recursive path, so nested `preserve` applies; the inline format is kept/// when that merge changed nothing+ /// - A pipeline: compared in the spelling the file uses (see+ /// `in_existing_spelling`); `[[…]]` blocks merge block by block/// - Both exist, values differ: update existing to desired/// - Both exist, values equal: leave existing unchanged (preserves comments)fn merge_tables(@@ -67,6 +71,8 @@ impl UserConfig {let empty_tree = UnknownTree::default();for (key, desired_item) in desired.iter() {+ let desired_item = &*Self::in_existing_spelling(existing.get(key), desired_item);+// Existing inline table, desired standard table: merge into a table// view so the same nested preservation applies as in the// standard-table branch, then write back only if that changed@@ -100,6 +106,18 @@ impl UserConfig {nested_preserve,);}+ // Both `[[…]]` blocks, as many of each: merge block by block, so+ // each block keeps its comments and formatting+ Some(toml_edit::Item::ArrayOfTables(blocks))+ if desired_item+ .as_array_of_tables()+ .is_some_and(|desired_blocks| desired_blocks.len() == blocks.len()) =>+ {+ let desired_blocks = desired_item.as_array_of_tables().unwrap();+ for (block, desired_block) in blocks.iter_mut().zip(desired_blocks.iter()) {+ Self::merge_tables(block, desired_block, &empty_tree);+ }+ }Some(existing_item) => {if !Self::items_equal(existing_item, desired_item) {Self::replace_keeping_decor(existing_item, desired_item);@@ -112,6 +130,46 @@ impl UserConfig {}}+ /// Re-spell a desired hook pipeline the way the file already writes it.+ ///+ /// A pipeline serializes in one spelling whatever the file used: one step as+ /// its lone table, more as an inline array of tables. The file may write+ /// either as `[[post-start]]` blocks — the documented form — or as an inline+ /// array. Compared as serialized, an untouched pipeline reads as changed on+ /// every save, and the rewrite moves it to the serialized spelling and drops+ /// the comments on its blocks. So desired steps become blocks where the file+ /// has blocks, and a lone step becomes a one-element array where the file has+ /// an inline array; anything else stays as serialized. Only a pipeline meets+ /// its serialized form in these shapes, so the match keys on shape alone.+ fn in_existing_spelling<'a>(+ existing: Option<&toml_edit::Item>,+ desired: &'a toml_edit::Item,+ ) -> Cow<'a, toml_edit::Item> {+ use toml_edit::{Array, ArrayOfTables, Item, Value};+ match (existing, desired) {+ (Some(Item::ArrayOfTables(_)), Item::Table(step)) => {+ let mut blocks = ArrayOfTables::new();+ blocks.push(step.clone());+ Cow::Owned(Item::ArrayOfTables(blocks))+ }+ (Some(Item::ArrayOfTables(_)), Item::Value(Value::Array(steps)))+ if steps.iter().all(Value::is_inline_table) =>+ {+ let mut blocks = ArrayOfTables::new();+ for step in steps.iter().filter_map(Value::as_inline_table) {+ blocks.push(step.clone().into_table());+ }+ Cow::Owned(Item::ArrayOfTables(blocks))+ }+ (Some(Item::Value(Value::Array(_))), Item::Table(step)) => {+ let mut steps = Array::new();+ steps.push(step.clone().into_inline_table());+ Cow::Owned(Item::Value(Value::Array(steps)))+ }+ _ => Cow::Borrowed(desired),+ }+ }+/// Overwrite an item, keeping the value's own decor — the spacing after `=`/// and the trailing comment after the value.///diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rsindex 39bb5eb65..727c44afc 100644--- a/tests/integration_tests/approval_save.rs+++ b/tests/integration_tests/approval_save.rs@@ -915,3 +915,63 @@ command = "llm -m claude-haiku-4.5"command = "llm -m claude-sonnet-4""#);}++/// A hook pipeline serializes in one spelling — one step as its lone table, more+/// as an inline array — while the file may write `[[post-start]]` blocks (the+/// documented form) or an inline array. An unrelated save must keep each+/// pipeline in the file's spelling with its comments, changing only the steps+/// the load rewrote (template migration renaming `repo_root`).+#[test]+fn test_saving_config_mutation_keeps_each_pipeline_spelling_and_its_comments() {+ let temp_dir = TempDir::new().unwrap();+ let config_path = temp_dir.path().join("config.toml");++ let initial_content = r#"worktree-path = "../x"++# start the dev server+post-start = [{ server = "cd {{ repo_root }} && npm run dev" }] # port 3000++# announce the switch+[[post-switch]]+notify = "echo switched"++# share the build cache, then install+[[pre-start]]+copy = "wt step copy-ignored"++[[pre-start]]+install = "cd {{ repo_root }} && pnpm install" # after the copy+"#;+ fs::write(&config_path, initial_content).unwrap();++ let toml_str = fs::read_to_string(&config_path).unwrap();+ let mut config: UserConfig = toml::from_str(&toml_str).unwrap();+ config+ .set_commit_generation_command("llm -m claude-sonnet-4".to_string(), &config_path)+ .unwrap();++ let saved_content = fs::read_to_string(&config_path).unwrap();+ toml::from_str::<toml::Table>(&saved_content).unwrap();+ assert_snapshot!(saved_content, @r#"+ worktree-path = "../x"++ # start the dev server+ post-start = [{ server = "cd {{ repo_path }} && npm run dev" }] # port 3000++ # announce the switch+ [[post-switch]]+ notify = "echo switched"++ # share the build cache, then install+ [[pre-start]]+ copy = "wt step copy-ignored"++ [[pre-start]]+ install = "cd {{ repo_path }} && pnpm install" # after the copy++ [projects]++ [commit.generation]+ command = "llm -m claude-sonnet-4"+ "#);+}diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex c539d6f17..14cce168f 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -3157,6 +3157,25 @@ fn test_pi_install_honors_agent_dir_override(temp_home: TempDir) {let output = cmd.output().expect("install command should run");assert!(output.status.success(), "install failed: {output:?}");assert!(agent_dir.join("extensions/worktrunk.ts").exists());++ // Pi expands a leading `~` in the override, so a quoted `~/…` lands under+ // home rather than in a literal `~` directory beneath the cwd.+ let cwd = tempfile::tempdir().unwrap();+ let mut cmd = wt_command();+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.current_dir(cwd.path());+ cmd.env("PI_CODING_AGENT_DIR", "~/tilde-pi-agent");+ cmd.args(["config", "plugins", "pi", "install", "--yes"]);++ let output = cmd.output().expect("install command should run");+ assert!(output.status.success(), "install failed: {output:?}");+ assert!(+ temp_home+ .path()+ .join("tilde-pi-agent/extensions/worktrunk.ts")+ .exists()+ );+ assert!(!cwd.path().join("~").exists());}/// Pi has no profile concept: the oh-my-pi profile variables must not move the