Skip to content

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

docs: Update README with current snapshot content

Maximilian Roos01cc7b1be156
diff --git a/.claude-plugin/skills/worktrunk/reference/README.md b/.claude-plugin/skills/worktrunk/reference/README.md
index 2609545b7..29c8a9ae5 100644
--- a/.claude-plugin/skills/worktrunk/reference/README.md
+++ b/.claude-plugin/skills/worktrunk/reference/README.md
@@ -28,36 +28,34 @@ List worktrees, create a worktree, make a trivial change, merge the change:
**Create a worktree:**
-<!-- Output from: tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_simple_switch.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_simple_switch.snap -->
```bash
$ wt switch --create fix-auth
-✅ Created new worktree for fix-auth from main at ../repo.fix-auth/
+✅ Created new worktree for fix-auth from main at ../repo.fix-auth
```
+<!-- README:end -->
...then do work. Then, when ready...
**Merge it:**
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_simple.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__merge__readme_example_simple.snap -->
```bash
$ wt merge
🔄 Merging 1 commit to main @ a1b2c3d (no commit/squash/rebase needed)
-
* a1b2c3d (HEAD -> fix-auth) Implement JWT validation
auth.rs | 13 +++++++++++++
1 file changed, 13 insertions(+)
✅ Merged to main (1 commit, 1 file, +13)
🔄 Removing fix-auth worktree & branch in background
```
+<!-- README:end -->
See [`wt merge`](#wt-merge) for all options.
**List worktrees:**
-<!-- Output from: tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap -->
```bash
$ wt list
Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
@@ -67,6 +65,7 @@ $ wt list
⚪ Showing 3 worktrees, 1 with changes, 2 ahead
```
+<!-- README:end -->
See [`wt list`](#wt-list) for all options.
@@ -117,23 +116,37 @@ args = ["-m", "claude-haiku-4-5-20251001"]
Then `wt merge` will generate commit messages automatically:
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap -->
```bash
$ wt merge
-🔄 Squashing 3 commits into 1 (3 files, +33)...
+🔄 Squashing 3 commits into a single commit (3 files, +33)...
🔄 Generating squash commit message...
- feat(auth): Implement JWT authentication system
+ feat(auth): Implement JWT authentication system
- Add comprehensive JWT token handling including validation, refresh logic,
- and authentication tests. This establishes the foundation for secure
- API authentication.
+ Add comprehensive JWT token handling including validation, refresh logic,
+ and authentication tests. This establishes the foundation for secure
+ API authentication.
- - Implement token refresh mechanism with expiry handling
- - Add JWT encoding/decoding with signature verification
- - Create test suite covering all authentication flows
+ - Implement token refresh mechanism with expiry handling
+ - Add JWT encoding/decoding with signature verification
+ - Create test suite covering all authentication flows
✅ Squashed @ a1b2c3d
+🔄 Running pre-merge test:
+ cargo test
+🔄 Running pre-merge lint:
+ cargo clippy
+🔄 Merging 1 commit to main @ a1b2c3d (no rebase needed)
+ * a1b2c3d (HEAD -> feature-auth) feat(auth): Implement JWT authentication system
+ auth.rs | 8 ++++++++
+ auth_test.rs | 17 +++++++++++++++++
+ jwt.rs | 8 ++++++++
+ 3 files changed, 33 insertions(+)
+✅ Merged to main (1 commit, 3 files, +33)
+🔄 Removing feature-auth worktree & branch in background
+🔄 Running post-merge install:
+ cargo install --path .
```
+<!-- README:end -->
For more details, including custom prompt templates: `wt config --help`
@@ -164,59 +177,59 @@ Automate tasks at different points in the worktree lifecycle. Configure hooks in
"lint" = "uv run ruff check"
```
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_post_create.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_post_create.snap -->
```bash
$ wt switch --create feature-x
🔄 Running post-create install:
- uv sync
-✅ Created new worktree for feature-x from main at ../repo.feature-x/
-🔄 Running post-start dev:
- uv run dev
+ uv sync
Resolved 24 packages in 145ms
Installed 24 packages in 1.2s
+✅ Created new worktree for feature-x from main at ../repo.feature-x
+🔄 Running post-start dev:
+ uv run dev
```
+<!-- README:end -->
<details>
<summary>Merging with pre-merge hooks</summary>
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_pre_merge.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_pre_merge.snap -->
```bash
$ wt merge
-🔄 Squashing 3 commits into 1 (2 files, +45)...
+🔄 Squashing 3 commits into a single commit (2 files, +45)...
🔄 Generating squash commit message...
- feat(api): Add user authentication endpoints
+ feat(api): Add user authentication endpoints
- Implement login and token refresh endpoints with JWT validation.
- Includes comprehensive test coverage and input validation.
+ Implement login and token refresh endpoints with JWT validation.
+ Includes comprehensive test coverage and input validation.
✅ Squashed @ a1b2c3d
🔄 Running pre-merge test:
- uv run pytest
+ uv run pytest
- ============================= test session starts ==============================
- collected 3 items
+============================= test session starts ==============================
+collected 3 items
- tests/test_auth.py::test_login_success PASSED [ 33%]
- tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
- tests/test_auth.py::test_token_validation PASSED [100%]
+tests/test_auth.py::test_login_success PASSED [ 33%]
+tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
+tests/test_auth.py::test_token_validation PASSED [100%]
- ============================== 3 passed in 0.8s ===============================
+============================== 3 passed in 0.8s ===============================
🔄 Running pre-merge lint:
- uv run ruff check
+ uv run ruff check
- All checks passed!
+All checks passed!
🔄 Merging 1 commit to main @ a1b2c3d (no rebase needed)
- * a1b2c3d (HEAD -> feature-auth) feat(api): Add user authentication endpoints
- api/auth.py | 31 +++++++++++++++++++++++++++++++
- tests/test_auth.py | 14 ++++++++++++++
- 2 files changed, 45 insertions(+)
+ * a1b2c3d (HEAD -> feature-auth) feat(api): Add user authentication endpoints
+ api/auth.py | 31 +++++++++++++++++++++++++++++++
+ tests/test_auth.py | 14 ++++++++++++++
+ 2 files changed, 45 insertions(+)
✅ Merged to main (1 commit, 2 files, +45)
🔄 Removing feature-auth worktree & branch in background
```
+<!-- README:end -->
</details>
@@ -785,8 +798,7 @@ git config worktrunk.status.feature-x "💬"
**Status appears in the Status column:**
-<!-- Output from: tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
```
Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
@ main ^ ./test-repo b834638e 10mo Initial commit
@@ -795,6 +807,7 @@ git config worktrunk.status.feature-x "💬"
+ dirty-no-status ! +1 -1 ./dirty-no-status b834638e 10mo Initial commit
+ dirty-with-status ?∅ 🤖 ./dirty-with-status b834638e 10mo Initial commit
```
+<!-- README:end -->
The custom emoji appears directly after the git status symbols.
@@ -809,8 +822,7 @@ When using Claude:
- Changes to `💬` when Claude needs input (waiting for permission or idle)
- Clears the status completely when the session ends
-<!-- Output from: tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
```bash
$ wt list
Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
@@ -822,6 +834,7 @@ $ wt list
⚪ Showing 5 worktrees, 1 with changes
```
+<!-- README:end -->
**How it works:**
@@ -885,8 +898,7 @@ Commands from project hooks and LLM configuration require approval on first run.
**Example approval prompt:**
-<!-- Output from: tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap -->
```
🟡 test-repo needs approval to execute 3 commands:
@@ -901,6 +913,7 @@ Commands from project hooks and LLM configuration require approval on first run.
💡 Allow and remember? [y/N]
```
+<!-- README:end -->
Use `--force` to bypass prompts (useful for CI/automation).
diff --git a/README.md b/README.md
index 2609545b7..29c8a9ae5 100644
--- a/README.md
+++ b/README.md
@@ -28,36 +28,34 @@ List worktrees, create a worktree, make a trivial change, merge the change:
**Create a worktree:**
-<!-- Output from: tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_simple_switch.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_simple_switch.snap -->
```bash
$ wt switch --create fix-auth
-✅ Created new worktree for fix-auth from main at ../repo.fix-auth/
+✅ Created new worktree for fix-auth from main at ../repo.fix-auth
```
+<!-- README:end -->
...then do work. Then, when ready...
**Merge it:**
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_simple.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__merge__readme_example_simple.snap -->
```bash
$ wt merge
🔄 Merging 1 commit to main @ a1b2c3d (no commit/squash/rebase needed)
-
* a1b2c3d (HEAD -> fix-auth) Implement JWT validation
auth.rs | 13 +++++++++++++
1 file changed, 13 insertions(+)
✅ Merged to main (1 commit, 1 file, +13)
🔄 Removing fix-auth worktree & branch in background
```
+<!-- README:end -->
See [`wt merge`](#wt-merge) for all options.
**List worktrees:**
-<!-- Output from: tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap -->
```bash
$ wt list
Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
@@ -67,6 +65,7 @@ $ wt list
⚪ Showing 3 worktrees, 1 with changes, 2 ahead
```
+<!-- README:end -->
See [`wt list`](#wt-list) for all options.
@@ -117,23 +116,37 @@ args = ["-m", "claude-haiku-4-5-20251001"]
Then `wt merge` will generate commit messages automatically:
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap -->
```bash
$ wt merge
-🔄 Squashing 3 commits into 1 (3 files, +33)...
+🔄 Squashing 3 commits into a single commit (3 files, +33)...
🔄 Generating squash commit message...
- feat(auth): Implement JWT authentication system
+ feat(auth): Implement JWT authentication system
- Add comprehensive JWT token handling including validation, refresh logic,
- and authentication tests. This establishes the foundation for secure
- API authentication.
+ Add comprehensive JWT token handling including validation, refresh logic,
+ and authentication tests. This establishes the foundation for secure
+ API authentication.
- - Implement token refresh mechanism with expiry handling
- - Add JWT encoding/decoding with signature verification
- - Create test suite covering all authentication flows
+ - Implement token refresh mechanism with expiry handling
+ - Add JWT encoding/decoding with signature verification
+ - Create test suite covering all authentication flows
✅ Squashed @ a1b2c3d
+🔄 Running pre-merge test:
+ cargo test
+🔄 Running pre-merge lint:
+ cargo clippy
+🔄 Merging 1 commit to main @ a1b2c3d (no rebase needed)
+ * a1b2c3d (HEAD -> feature-auth) feat(auth): Implement JWT authentication system
+ auth.rs | 8 ++++++++
+ auth_test.rs | 17 +++++++++++++++++
+ jwt.rs | 8 ++++++++
+ 3 files changed, 33 insertions(+)
+✅ Merged to main (1 commit, 3 files, +33)
+🔄 Removing feature-auth worktree & branch in background
+🔄 Running post-merge install:
+ cargo install --path .
```
+<!-- README:end -->
For more details, including custom prompt templates: `wt config --help`
@@ -164,59 +177,59 @@ Automate tasks at different points in the worktree lifecycle. Configure hooks in
"lint" = "uv run ruff check"
```
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_post_create.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_post_create.snap -->
```bash
$ wt switch --create feature-x
🔄 Running post-create install:
- uv sync
-✅ Created new worktree for feature-x from main at ../repo.feature-x/
-🔄 Running post-start dev:
- uv run dev
+ uv sync
Resolved 24 packages in 145ms
Installed 24 packages in 1.2s
+✅ Created new worktree for feature-x from main at ../repo.feature-x
+🔄 Running post-start dev:
+ uv run dev
```
+<!-- README:end -->
<details>
<summary>Merging with pre-merge hooks</summary>
-<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_pre_merge.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_pre_merge.snap -->
```bash
$ wt merge
-🔄 Squashing 3 commits into 1 (2 files, +45)...
+🔄 Squashing 3 commits into a single commit (2 files, +45)...
🔄 Generating squash commit message...
- feat(api): Add user authentication endpoints
+ feat(api): Add user authentication endpoints
- Implement login and token refresh endpoints with JWT validation.
- Includes comprehensive test coverage and input validation.
+ Implement login and token refresh endpoints with JWT validation.
+ Includes comprehensive test coverage and input validation.
✅ Squashed @ a1b2c3d
🔄 Running pre-merge test:
- uv run pytest
+ uv run pytest
- ============================= test session starts ==============================
- collected 3 items
+============================= test session starts ==============================
+collected 3 items
- tests/test_auth.py::test_login_success PASSED [ 33%]
- tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
- tests/test_auth.py::test_token_validation PASSED [100%]
+tests/test_auth.py::test_login_success PASSED [ 33%]
+tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
+tests/test_auth.py::test_token_validation PASSED [100%]
- ============================== 3 passed in 0.8s ===============================
+============================== 3 passed in 0.8s ===============================
🔄 Running pre-merge lint:
- uv run ruff check
+ uv run ruff check
- All checks passed!
+All checks passed!
🔄 Merging 1 commit to main @ a1b2c3d (no rebase needed)
- * a1b2c3d (HEAD -> feature-auth) feat(api): Add user authentication endpoints
- api/auth.py | 31 +++++++++++++++++++++++++++++++
- tests/test_auth.py | 14 ++++++++++++++
- 2 files changed, 45 insertions(+)
+ * a1b2c3d (HEAD -> feature-auth) feat(api): Add user authentication endpoints
+ api/auth.py | 31 +++++++++++++++++++++++++++++++
+ tests/test_auth.py | 14 ++++++++++++++
+ 2 files changed, 45 insertions(+)
✅ Merged to main (1 commit, 2 files, +45)
🔄 Removing feature-auth worktree & branch in background
```
+<!-- README:end -->
</details>
@@ -785,8 +798,7 @@ git config worktrunk.status.feature-x "💬"
**Status appears in the Status column:**
-<!-- Output from: tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
```
Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
@ main ^ ./test-repo b834638e 10mo Initial commit
@@ -795,6 +807,7 @@ git config worktrunk.status.feature-x "💬"
+ dirty-no-status ! +1 -1 ./dirty-no-status b834638e 10mo Initial commit
+ dirty-with-status ?∅ 🤖 ./dirty-with-status b834638e 10mo Initial commit
```
+<!-- README:end -->
The custom emoji appears directly after the git status symbols.
@@ -809,8 +822,7 @@ When using Claude:
- Changes to `💬` when Claude needs input (waiting for permission or idle)
- Clears the status completely when the session ends
-<!-- Output from: tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
-
+<!-- README:snapshot:tests/snapshots/integration__integration_tests__list__with_user_status.snap -->
```bash
$ wt list
Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
@@ -822,6 +834,7 @@ $ wt list
⚪ Showing 5 worktrees, 1 with changes
```
+<!-- README:end -->
**How it works:**
@@ -885,8 +898,7 @@ Commands from project hooks and LLM configuration require approval on first run.
**Example approval prompt:**
-<!-- Output from: tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap -->
-
+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap -->
```
🟡 test-repo needs approval to execute 3 commands:
@@ -901,6 +913,7 @@ Commands from project hooks and LLM configuration require approval on first run.
💡 Allow and remember? [y/N]
```
+<!-- README:end -->
Use `--force` to bypass prompts (useful for CI/automation).
diff --git a/dev/update-readme.py b/dev/update-readme.py
new file mode 100755
index 000000000..f5e1a8b19
--- /dev/null
+++ b/dev/update-readme.py
@@ -0,0 +1,338 @@
+#!/usr/bin/env python3
+"""Update README.md with content from snapshot files.
+
+This script manages README sections that reference snapshot test output.
+
+USAGE:
+
+1. Update README from snapshots:
+ python dev/update-readme.py
+
+ Replaces marked sections with normalized snapshot content:
+ - Strips ANSI color codes
+ - Converts [SHA] to a1b2c3d
+ - Normalizes temp paths to relative paths
+
+2. Check for staleness (useful in CI):
+ python dev/update-readme.py --check
+
+MARKER FORMAT (add manually to README):
+
+<!-- README:snapshot:path/to/snapshot.snap -->
+```bash
+$ command
+... content from snapshot ...
+```
+<!-- README:end -->
+"""
+
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+
+def strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes from text.
+
+ Handles both actual escape sequences (\x1b[...) and literal bracket
+ notation ([0m, [1m, etc.) as stored in snapshot files.
+ """
+ # Actual ANSI escape sequences
+ text = re.sub(r'\x1b\[[0-9;]*m', '', text)
+ # Literal bracket notation (as stored in snapshots)
+ text = re.sub(r'\[[0-9;]*m', '', text)
+ return text
+
+
+def parse_snapshot(path: Path) -> str:
+ """Extract content from an insta snapshot file."""
+ content = path.read_text()
+
+ # Remove YAML front matter
+ if content.startswith('---'):
+ # Find the end of YAML front matter
+ parts = content.split('---', 2)
+ if len(parts) >= 3:
+ content = parts[2].strip()
+
+ # Handle insta_cmd format with stdout/stderr sections
+ if '----- stdout -----' in content:
+ stdout_match = re.search(r'----- stdout -----\n(.*?)----- stderr -----', content, re.DOTALL)
+ stderr_match = re.search(r'----- stderr -----\n(.*?)(?:\Z|----- )', content, re.DOTALL)
+
+ # Use stdout if it has content (worktrunk output), otherwise use stderr
+ # Don't combine them - they're not temporally ordered
+ stdout_content = stdout_match.group(1).rstrip() if stdout_match else ""
+ stderr_content = stderr_match.group(1).rstrip() if stderr_match else ""
+
+ if stdout_content:
+ content = stdout_content
+ else:
+ content = stderr_content
+
+ # Strip ANSI codes
+ content = strip_ansi(content)
+
+ return content
+
+
+def get_help_output(command: str) -> str:
+ """Run a command and capture its help output.
+
+ For long help (--help), extracts only the Usage section (before
+ documentation sections like "Operation", "Hooks", etc).
+ """
+ args = command.split()
+ result = subprocess.run(
+ args,
+ capture_output=True,
+ text=True,
+ cwd=Path(__file__).parent.parent
+ )
+ # Help goes to stdout
+ output = result.stdout if result.stdout else result.stderr
+ output = strip_ansi(output).strip()
+
+ # For --help, extract only the Usage section
+ # Stop at first documentation section (indicated by title without indentation)
+ if '--help' in command:
+ lines = output.split('\n')
+ result_lines = []
+ in_header = True
+
+ for line in lines:
+ # Check if we've reached a documentation section
+ # These are lines that start without indentation and aren't options
+ if not in_header and line and not line.startswith(' ') and not line.startswith('-'):
+ # Check for section headers (e.g., "Operation", "Hooks", "Examples")
+ if line[0].isupper() and not line.startswith('Usage:') and ':' not in line:
+ break
+
+ result_lines.append(line)
+
+ # We're past the title line after first line
+ if 'Usage:' in line:
+ in_header = False
+
+ return '\n'.join(result_lines).strip()
+
+ return output
+
+
+def normalize_for_readme(content: str) -> str:
+ """Normalize snapshot output for README display.
+
+ Converts test placeholders to realistic-looking values:
+ - [SHA] -> a1b2c3d (realistic commit hash)
+ - [TMPDIR]/test-repo.branch -> ../repo.branch/
+ - ./test-repo -> ./repo
+ """
+ # Replace SHA/HASH placeholders with a consistent realistic hash
+ content = re.sub(r'\[SHA\]', 'a1b2c3d', content)
+ content = re.sub(r'\[HASH\]', 'a1b2c3d', content)
+
+ # Replace temp dir paths with readable relative paths
+ # Match [TMPDIR]/test-repo.branch (no trailing slash in replacement)
+ content = re.sub(
+ r'\[TMPDIR\]/test-repo\.(\S+?)(?=/|\s|$)',
+ r'../repo.\1',
+ content
+ )
+ # Also handle other temp path patterns
+ content = re.sub(
+ r'/(?:var/folders|tmp|private/tmp)[^/\s]*/[^/\s]*/test-repo\.(\S+?)(?=/|\s|$)',
+ r'../repo.\1',
+ content
+ )
+
+ # Replace [REPO] placeholder with repo
+ content = re.sub(r'\[REPO\]', '../repo', content)
+
+ return content
+
+
+def update_readme(readme_path: Path, dry_run: bool = False) -> list[tuple[str, str, str]]:
+ """Update README with content from markers.
+
+ Returns list of (marker_type, identifier, status) tuples.
+ """
+ content = readme_path.read_text()
+ updates = []
+
+ # Pattern for snapshot markers
+ # <!-- README:snapshot:path/to/file.snap -->
+ # ```bash
+ # $ command
+ # content
+ # ```
+ # <!-- README:end -->
+ snapshot_pattern = re.compile(
+ r'(<!-- README:snapshot:([^\s]+) -->)\n'
+ r'```(\w+)\n'
+ r'(\$ [^\n]+\n)?' # Optional command line
+ r'(.*?)'
+ r'```\n'
+ r'(<!-- README:end -->)',
+ re.DOTALL
+ )
+
+ # Pattern for help markers - finds first code block in section
+ help_pattern = re.compile(
+ r'(<!-- README:help:([^\n]+) -->)\n'
+ r'(.*?)' # Content before first code block
+ r'(```\n)'
+ r'(.*?)' # Code block content
+ r'(```)\n'
+ r'(.*?)' # Content after code block until end marker
+ r'(<!-- README:end -->)',
+ re.DOTALL
+ )
+
+ project_root = readme_path.parent
+
+ def replace_snapshot(match):
+ start_marker = match.group(1)
+ snap_path = match.group(2)
+ lang = match.group(3)
+ command = match.group(4) or ""
+ end_marker = match.group(6)
+
+ full_path = project_root / snap_path
+ if not full_path.exists():
+ updates.append(('snapshot', snap_path, f'NOT FOUND: {full_path}'))
+ return match.group(0)
+
+ try:
+ new_content = parse_snapshot(full_path)
+ new_content = normalize_for_readme(new_content)
+ updates.append(('snapshot', snap_path, 'updated'))
+ return f'{start_marker}\n```{lang}\n{command}{new_content}\n```\n{end_marker}'
+ except Exception as e:
+ updates.append(('snapshot', snap_path, f'ERROR: {e}'))
+ return match.group(0)
+
+ def replace_help(match):
+ start_marker = match.group(1)
+ command = match.group(2)
+ before_code = match.group(3)
+ code_start = match.group(4)
+ after_code = match.group(7)
+ end_marker = match.group(8)
+
+ try:
+ new_content = get_help_output(command)
+ updates.append(('help', command, 'updated'))
+ return f'{start_marker}\n{before_code}{code_start}{new_content}\n```\n{after_code}{end_marker}'
+ except Exception as e:
+ updates.append(('help', command, f'ERROR: {e}'))
+ return match.group(0)
+
+ # Apply replacements
+ new_content = snapshot_pattern.sub(replace_snapshot, content)
+ new_content = help_pattern.sub(replace_help, new_content)
+
+ if not dry_run and new_content != content:
+ readme_path.write_text(new_content)
+
+ return updates
+
+
+def check_staleness(readme_path: Path) -> list[tuple[str, str, bool]]:
+ """Check if README sections are stale compared to their source snapshots.
+
+ Returns list of (snap_path, status, is_different) tuples.
+ """
+ content = readme_path.read_text()
+ results = []
+
+ # Pattern for snapshot markers
+ snapshot_pattern = re.compile(
+ r'<!-- README:snapshot:([^\s]+) -->\n'
+ r'```\w*\n'
+ r'(?:\$ [^\n]+\n)?'
+ r'(.*?)'
+ r'```\n'
+ r'<!-- README:end -->',
+ re.DOTALL
+ )
+
+ project_root = readme_path.parent
+
+ for match in snapshot_pattern.finditer(content):
+ snap_path = match.group(1)
+ current_content = match.group(2).strip()
+
+ full_path = project_root / snap_path
+ if not full_path.exists():
+ results.append((snap_path, 'NOT FOUND', True))
+ continue
+
+ try:
+ snap_content = parse_snapshot(full_path)
+ snap_content = normalize_for_readme(snap_content)
+ is_different = snap_content.strip() != current_content
+ status = 'needs review' if is_different else 'ok'
+ results.append((snap_path, status, is_different))
+ except Exception as e:
+ results.append((snap_path, f'ERROR: {e}', True))
+
+ return results
+
+
+def main():
+ import argparse
+
+ parser = argparse.ArgumentParser(description='Update README.md from snapshot files')
+ parser.add_argument('--check', action='store_true',
+ help='Check if sections are stale without updating')
+ parser.add_argument('--dry-run', action='store_true',
+ help='Show what would be updated without making changes')
+ parser.add_argument('--readme', type=Path, default=Path('README.md'),
+ help='Path to README.md')
+
+ args = parser.parse_args()
+
+ readme_path = args.readme
+ if not readme_path.is_absolute():
+ readme_path = Path(__file__).parent.parent / readme_path
+
+ if not readme_path.exists():
+ print(f"Error: {readme_path} not found", file=sys.stderr)
+ sys.exit(1)
+
+ if args.check:
+ results = check_staleness(readme_path)
+
+ if not results:
+ print("No markers found in README.md")
+ sys.exit(0)
+
+ has_stale = False
+ for snap_path, status, is_different in results:
+ indicator = "⚠️ " if is_different else "✅"
+ print(f"{indicator} {snap_path}: {status}")
+ if is_different:
+ has_stale = True
+
+ if has_stale:
+ print("\nSome sections may need manual review")
+ sys.exit(1)
+ else:
+ print("\nAll sections are up to date")
+ else:
+ updates = update_readme(readme_path, dry_run=args.dry_run)
+
+ if not updates:
+ print("No markers found in README.md")
+ sys.exit(0)
+
+ for marker_type, identifier, status in updates:
+ print(f"[{marker_type}] {identifier}: {status}")
+
+ if args.dry_run:
+ print("\nDry run - no changes made")
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 3c3d63b74..e63e950b2 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -431,6 +431,23 @@ fn exec_through_wrapper_interactive(
args: &[&str],
working_dir: &std::path::Path,
inputs: &[&str],
+) -> ShellOutput {
+ exec_through_wrapper_with_env(shell, repo, subcommand, args, working_dir, inputs, &[])
+}
+
+/// Execute a command through a shell wrapper with custom environment variables
+///
+/// Like `exec_through_wrapper_interactive` but allows additional env vars to be set.
+/// Useful for tests that need custom PATH (e.g., for mock binaries).
+#[cfg(test)]
+fn exec_through_wrapper_with_env(
+ shell: &str,
+ repo: &TestRepo,
+ subcommand: &str,
+ args: &[&str],
+ working_dir: &std::path::Path,
+ inputs: &[&str],
+ extra_env: &[(&str, &str)],
) -> ShellOutput {
let script = build_shell_script(shell, repo, subcommand, args);
@@ -442,7 +459,7 @@ fn exec_through_wrapper_interactive(
let config_path = repo.test_config_path().to_string_lossy().to_string();
// Same environment setup as exec_through_wrapper_from
- let env_vars: Vec<(&str, &str)> = vec![
+ let mut env_vars: Vec<(&str, &str)> = vec![
("CLICOLOR_FORCE", "1"),
("WORKTRUNK_CONFIG_PATH", &config_path),
("TERM", "xterm"),
@@ -457,6 +474,9 @@ fn exec_through_wrapper_interactive(
("SOURCE_DATE_EPOCH", "1761609600"),
];
+ // Add extra env vars (these can override defaults if needed)
+ env_vars.extend(extra_env.iter().copied());
+
let (combined, exit_code) =
exec_in_pty_interactive(shell, &script, working_dir, &env_vars, inputs);
@@ -1879,4 +1899,382 @@ approved-commands = ["echo 'cleanup test'"]
shell
);
}
+
+ // ========================================================================
+ // README Example Tests (PTY-based for interleaved output)
+ // ========================================================================
+ //
+ // These tests generate snapshots for README.md examples. They use PTY execution
+ // to capture stdout/stderr interleaved in the order users see them.
+ //
+ // See tests/CLAUDE.md for background on why PTY-based tests are needed for README examples.
+
+ /// README example: Pre-merge hooks with squash and LLM commit message
+ ///
+ /// This test demonstrates:
+ /// - Multiple commits being squashed with LLM-generated message
+ /// - Pre-merge hooks (test, lint) running before merge
+ ///
+ /// Source: tests/snapshots/shell_wrapper__tests__readme_example_hooks_pre_merge.snap
+ #[test]
+ fn test_readme_example_hooks_pre_merge() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create project config with pre-merge hooks
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");
+
+ // Create mock commands for realistic output
+ let bin_dir = repo.root_path().join(".bin");
+ fs::create_dir_all(&bin_dir).expect("Failed to create bin dir");
+
+ // Mock pytest command
+ let pytest_script = r#"#!/bin/sh
+cat << 'EOF'
+
+============================= test session starts ==============================
+collected 3 items
+
+tests/test_auth.py::test_login_success PASSED [ 33%]
+tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
+tests/test_auth.py::test_token_validation PASSED [100%]
+
+============================== 3 passed in 0.8s ===============================
+
+EOF
+exit 0
+"#;
+ fs::write(bin_dir.join("pytest"), pytest_script).expect("Failed to write pytest script");
+
+ // Mock ruff command
+ let ruff_script = r#"#!/bin/sh
+if [ "$1" = "check" ]; then
+ echo ""
+ echo "All checks passed!"
+ echo ""
+ exit 0
+else
+ echo "ruff: unknown command '$1'"
+ exit 1
+fi
+"#;
+ fs::write(bin_dir.join("ruff"), ruff_script).expect("Failed to write ruff script");
+
+ // Mock llm command for commit message
+ let llm_script = r#"#!/bin/sh
+cat > /dev/null
+cat << 'EOF'
+feat(api): Add user authentication endpoints
+
+Implement login and token refresh endpoints with JWT validation.
+Includes comprehensive test coverage and input validation.
+EOF
+"#;
+ fs::write(bin_dir.join("llm"), llm_script).expect("Failed to write llm script");
+
+ // Mock uv command for running pytest and ruff
+ let uv_script = r#"#!/bin/sh
+if [ "$1" = "run" ] && [ "$2" = "pytest" ]; then
+ exec pytest
+elif [ "$1" = "run" ] && [ "$2" = "ruff" ]; then
+ shift 2
+ exec ruff "$@"
+else
+ echo "uv: unknown command '$1 $2'"
+ exit 1
+fi
+"#;
+ fs::write(bin_dir.join("uv"), uv_script).expect("Failed to write uv script");
+
+ // Make scripts executable (Unix only)
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ for script in &["pytest", "ruff", "llm", "uv"] {
+ let mut perms = fs::metadata(bin_dir.join(script)).unwrap().permissions();
+ perms.set_mode(0o755);
+ fs::set_permissions(bin_dir.join(script), perms).unwrap();
+ }
+ }
+
+ let config_content = r#"
+[pre-merge-command]
+"test" = "uv run pytest"
+"lint" = "uv run ruff check"
+"#;
+
+ fs::write(config_dir.join("wt.toml"), config_content)
+ .expect("Failed to write project config");
+
+ // Commit the config
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", ".config/wt.toml", ".bin"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add config");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add pre-merge hooks"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to commit config");
+
+ // Create a worktree for main
+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add worktree");
+
+ // Create a feature worktree and make multiple commits
+ let feature_wt = repo.add_worktree("feature-auth", "feature-auth");
+
+ // First commit - create initial auth.py with login endpoint
+ fs::create_dir_all(feature_wt.join("api")).expect("Failed to create api dir");
+ let auth_py_v1 = r#"# Authentication API endpoints
+from typing import Dict, Optional
+import jwt
+from datetime import datetime, timedelta, timezone
+
+def login(username: str, password: str) -> Optional[Dict]:
+ """Authenticate user and return JWT token."""
+ # Validate credentials (stub)
+ if not username or not password:
+ return None
+
+ # Generate JWT token
+ payload = {
+ 'sub': username,
+ 'exp': datetime.now(timezone.utc) + timedelta(hours=1)
+ }
+ token = jwt.encode(payload, 'secret', algorithm='HS256')
+ return {'token': token, 'expires_in': 3600}
+"#;
+ std::fs::write(feature_wt.join("api/auth.py"), auth_py_v1).expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "api/auth.py"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add login endpoint"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Second commit - add tests
+ fs::create_dir_all(feature_wt.join("tests")).expect("Failed to create tests dir");
+ let test_auth_py = r#"# Authentication endpoint tests
+import pytest
+from api.auth import login
+
+def test_login_success():
+ result = login('user', 'pass')
+ assert result and 'token' in result
+
+def test_login_invalid_password():
+ result = login('user', '')
+ assert result is None
+
+def test_token_validation():
+ assert login('valid_user', 'valid_pass')['expires_in'] == 3600
+"#;
+ std::fs::write(feature_wt.join("tests/test_auth.py"), test_auth_py)
+ .expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "tests/test_auth.py"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add authentication tests"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Third commit - add refresh endpoint
+ let auth_py_v2 = r#"# Authentication API endpoints
+from typing import Dict, Optional
+import jwt
+from datetime import datetime, timedelta, timezone
+
+def login(username: str, password: str) -> Optional[Dict]:
+ """Authenticate user and return JWT token."""
+ # Validate credentials (stub)
+ if not username or not password:
+ return None
+
+ # Generate JWT token
+ payload = {
+ 'sub': username,
+ 'exp': datetime.now(timezone.utc) + timedelta(hours=1)
+ }
+ token = jwt.encode(payload, 'secret', algorithm='HS256')
+ return {'token': token, 'expires_in': 3600}
+
+def refresh_token(token: str) -> Optional[Dict]:
+ """Refresh an existing JWT token."""
+ try:
+ payload = jwt.decode(token, 'secret', algorithms=['HS256'])
+ new_payload = {
+ 'sub': payload['sub'],
+ 'exp': datetime.now(timezone.utc) + timedelta(hours=1)
+ }
+ new_token = jwt.encode(new_payload, 'secret', algorithm='HS256')
+ return {'token': new_token, 'expires_in': 3600}
+ except jwt.InvalidTokenError:
+ return None
+"#;
+ std::fs::write(feature_wt.join("api/auth.py"), auth_py_v2).expect("Failed to write file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", "api/auth.py"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to add file");
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add validation"])
+ .current_dir(&feature_wt)
+ .output()
+ .expect("Failed to commit");
+
+ // Configure LLM in worktrunk config
+ let llm_path = bin_dir.join("llm");
+ let worktrunk_config = format!(
+ r#"worktree-path = "../test-repo.{{{{ branch }}}}"
+
+[commit-generation]
+command = "{}"
+"#,
+ llm_path.display()
+ );
+ fs::write(repo.test_config_path(), worktrunk_config)
+ .expect("Failed to write worktrunk config");
+
+ // Set PATH with mock binaries and run merge
+ let path_with_bin = format!(
+ "{}:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
+ bin_dir.display()
+ );
+
+ let output = exec_through_wrapper_with_env(
+ "bash",
+ &repo,
+ "merge",
+ &["main", "--force"],
+ &feature_wt,
+ &[],
+ &[("PATH", &path_with_bin)],
+ );
+
+ assert_eq!(output.exit_code, 0, "Merge should succeed");
+ assert_snapshot!(output.normalized());
+ }
+
+ /// README example: Creating worktree with post-create and post-start hooks
+ ///
+ /// This test demonstrates:
+ /// - Post-create hooks (install dependencies)
+ /// - Post-start hooks (start dev server)
+ ///
+ /// Uses shell wrapper to avoid "To enable automatic cd" hint.
+ ///
+ /// Source: tests/snapshots/shell_wrapper__tests__readme_example_hooks_post_create.snap
+ #[test]
+ fn test_readme_example_hooks_post_create() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create project config with post-create and post-start hooks
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");
+
+ // Create mock commands for realistic output
+ let bin_dir = repo.root_path().join(".bin");
+ fs::create_dir_all(&bin_dir).expect("Failed to create bin dir");
+
+ // Mock uv command that simulates dependency installation
+ let uv_script = r#"#!/bin/sh
+if [ "$1" = "sync" ]; then
+ echo ""
+ echo " Resolved 24 packages in 145ms"
+ echo " Installed 24 packages in 1.2s"
+ exit 0
+elif [ "$1" = "run" ] && [ "$2" = "dev" ]; then
+ echo ""
+ echo " Starting dev server on http://localhost:3000..."
+ exit 0
+else
+ echo "uv: unknown command '$1 $2'"
+ exit 1
+fi
+"#;
+ fs::write(bin_dir.join("uv"), uv_script).expect("Failed to write uv script");
+
+ // Make scripts executable (Unix only)
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut perms = fs::metadata(bin_dir.join("uv")).unwrap().permissions();
+ perms.set_mode(0o755);
+ fs::set_permissions(bin_dir.join("uv"), perms).unwrap();
+ }
+
+ let config_content = r#"
+[post-create-command]
+"install" = "uv sync"
+
+[post-start-command]
+"dev" = "uv run dev"
+"#;
+
+ fs::write(config_dir.join("wt.toml"), config_content)
+ .expect("Failed to write project config");
+
+ // Commit the config
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["add", ".config/wt.toml", ".bin"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to add config");
+
+ let mut cmd = Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["commit", "-m", "Add project hooks"])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to commit config");
+
+ // Set PATH with mock binaries and run switch --create
+ let path_with_bin = format!(
+ "{}:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
+ bin_dir.display()
+ );
+
+ let output = exec_through_wrapper_with_env(
+ "bash",
+ &repo,
+ "switch",
+ &["--create", "feature-x", "--force"],
+ repo.root_path(),
+ &[],
+ &[("PATH", &path_with_bin)],
+ );
+
+ assert_eq!(output.exit_code, 0, "Switch should succeed");
+ assert_snapshot!(output.normalized());
+ }
}
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_post_create.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_post_create.snap
new file mode 100644
index 000000000..532658f8d
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_post_create.snap
@@ -0,0 +1,13 @@
+---
+source: tests/integration_tests/shell_wrapper.rs
+assertion_line: 2278
+expression: output.normalized()
+---
+🔄 Running post-create install:
+  uv sync
+
+ Resolved 24 packages in 145ms
+ Installed 24 packages in 1.2s
+✅ Created new worktree for feature-x from main at [TMPDIR]/test-repo.feature-x
+🔄 Running post-start dev:
+  uv run dev
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_pre_merge.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_pre_merge.snap
new file mode 100644
index 000000000..9eab15628
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_pre_merge.snap
@@ -0,0 +1,36 @@
+---
+source: tests/integration_tests/shell_wrapper.rs
+assertion_line: 2186
+expression: output.normalized()
+---
+🔄 Squashing 3 commits into a single commit (2 files, +45)...
+🔄 Generating squash commit message...
+  feat(api): Add user authentication endpoints
+ 
+  Implement login and token refresh endpoints with JWT validation.
+  Includes comprehensive test coverage and input validation.
+✅ Squashed @ [HASH]
+🔄 Running pre-merge test:
+  uv run pytest
+
+============================= test session starts ==============================
+collected 3 items
+
+tests/test_auth.py::test_login_success PASSED [ 33%]
+tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
+tests/test_auth.py::test_token_validation PASSED [100%]
+
+============================== 3 passed in 0.8s ===============================
+
+🔄 Running pre-merge lint:
+  uv run ruff check
+
+All checks passed!
+
+🔄 Merging 1 commit to main @ [HASH] (no rebase needed)
+  * [HASH] (HEAD -> feature-auth) feat(api): Add user authentication endpoints
+  api/auth.py | 31 +++++++++++++++++++++++++++++++
+  tests/test_auth.py | 14 ++++++++++++++
+  2 files changed, 45 insertions(+)
+✅ Merged to main (1 commit, 2 files, +45)
+🔄 Removing feature-auth worktree & branch in background