feat(worktree): add session mapping and improve pre-edit check#29
feat(worktree): add session mapping and improve pre-edit check#29marcusquinn merged 1 commit intomainfrom
Conversation
- Add worktree-sessions.sh to map worktrees to likely OpenCode sessions - Portable date/stat commands (GNU and BSD compatible) - Dynamic default branch detection (main/master) - Input validation for interactive mode - Cross-platform OpenCode launch (CLI, app bundle, xdg-open) - Strengthen pre-edit check with explicit trigger words - Now lists: create, add, write, update, modify, change, fix, implement, refactor - Explicitly covers creating new files, not just editing - Add self-verification prompt for file operations - Clarify dual-location workflow for aidevops framework - Document session recovery in worktree.md
WalkthroughThis PR enhances agent workflows and introduces session recovery tooling. It expands pre-edit check requirements and procedures in workflow documentation, adds a new Bash script for mapping git worktrees to OpenCode sessions with scoring-based matching logic, and documents session recovery guidance with best practices. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Script as worktree-sessions.sh
participant Git
participant FileSystem as Project Storage
participant Sessions as Session Files
User->>Script: cmd_list or cmd_open
Script->>Git: git worktree list / get_default_branch()
Script->>FileSystem: Detect repo root & name
Script->>FileSystem: get_project_id() - scan JSON for match
Script->>Git: get_branch_start_date() - commit date on branch
Script->>Sessions: Read ses_*.json files
Script->>Script: find_matching_sessions() - score candidates<br/>(branch name: 100, slug: 80, terms: 20, temporal: 40)
Script->>User: Output top 3 matches with confidence levels
alt cmd_open selected
User->>Script: Select worktree
Script->>Script: Resolve OpenCode or fallback editor
Script->>User: Open session in IDE
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Summary of ChangesHello @marcusquinn, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a new utility to streamline the developer workflow by helping users quickly locate and resume their OpenCode sessions associated with specific Git worktrees. It also refines the existing pre-edit Git check mechanism to ensure better adherence to branching policies and provides clear documentation for these new capabilities, enhancing overall development efficiency and consistency. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
🔍 Code Quality Report�[0;35m[MONITOR]�[0m Code Review Monitoring Report �[0;34m[INFO]�[0m Latest Quality Status: �[0;34m[INFO]�[0m Recent monitoring activity: 📈 Current Quality Metrics
Generated on: Sun Jan 11 01:17:23 UTC 2026 Generated by AI DevOps Framework Code Review Monitoring |
There was a problem hiding this comment.
Code Review
This pull request introduces a very useful worktree-sessions.sh script for mapping git worktrees to OpenCode sessions, along with improved documentation for the pre-edit check and worktree workflows. The new script is well-structured and demonstrates good practices for portability.
My review focuses on the new script. I've identified a few areas for improvement:
- Portability: The script hardcodes paths that are specific to Linux, which could be improved to support other operating systems like macOS.
- Correctness: The session scoring logic has a flaw where scores for different name matches accumulate, which can lead to counter-intuitive results.
- Maintainability: There's some code duplication and an unused function that could be cleaned up.
- Robustness: The script could be made more robust by checking for its
jqdependency.
I've provided specific suggestions to address these points. The documentation changes are clear and valuable.
| readonly SESSION_BASE="$HOME/.local/share/opencode/storage/session" | ||
| readonly PROJECT_BASE="$HOME/.local/share/opencode/storage/project" |
There was a problem hiding this comment.
The script hardcodes paths to ~/.local/share/opencode/..., which is specific to Linux systems following the XDG standard. On macOS, these paths are different (typically under ~/Library/Application Support). To improve portability, which is a goal of this PR, the script should dynamically determine the correct base path for OpenCode data.
| readonly SESSION_BASE="$HOME/.local/share/opencode/storage/session" | |
| readonly PROJECT_BASE="$HOME/.local/share/opencode/storage/project" | |
| opencode_data_dir="${XDG_DATA_HOME:-$HOME/.local/share}/opencode" | |
| if [[ "$(uname)" == "Darwin" ]]; then | |
| opencode_data_dir="$HOME/Library/Application Support/opencode" | |
| fi | |
| readonly SESSION_BASE="$opencode_data_dir/storage/session" | |
| readonly PROJECT_BASE="$opencode_data_dir/storage/project" |
| if [[ "$session_title" == "$branch" ]]; then | ||
| score=$((score + 100)) | ||
| fi | ||
|
|
||
| # Scoring: branch slug in title (case-insensitive) | ||
| if echo "$session_title" | grep -qi "$branch_slug"; then | ||
| score=$((score + 80)) | ||
| fi | ||
|
|
||
| # Scoring: branch name (without type prefix) in title | ||
| if echo "$session_title" | grep -qi "$branch_name"; then | ||
| score=$((score + 60)) | ||
| fi |
There was a problem hiding this comment.
The scoring logic for matching session titles is cumulative. For example, if a session title is an exact match for the branch name (+100), it will also likely match the branch name without the prefix (+60) and some key terms (+20 each), leading to an inflated and less predictable score. The documentation in worktree.md implies these are alternative matching strategies. To make the scoring more intuitive, you should use if/elif/else for the name-based scoring so that only the best possible name match is counted.
| if [[ "$session_title" == "$branch" ]]; then | |
| score=$((score + 100)) | |
| fi | |
| # Scoring: branch slug in title (case-insensitive) | |
| if echo "$session_title" | grep -qi "$branch_slug"; then | |
| score=$((score + 80)) | |
| fi | |
| # Scoring: branch name (without type prefix) in title | |
| if echo "$session_title" | grep -qi "$branch_name"; then | |
| score=$((score + 60)) | |
| fi | |
| if [[ "$session_title" == "$branch" ]]; then | |
| score=$((score + 100)) | |
| elif echo "$session_title" | grep -qi "$branch_slug"; then | |
| score=$((score + 80)) | |
| elif echo "$session_title" | grep -qi "$branch_name"; then | |
| score=$((score + 60)) | |
| fi |
| readonly BOLD='\033[1m' | ||
| readonly DIM='\033[2m' | ||
| readonly NC='\033[0m' | ||
|
|
There was a problem hiding this comment.
This script depends on jq for parsing JSON files, but it doesn't check if jq is installed. If jq is missing, the script will fail with potentially confusing errors. It's good practice to add a check for dependencies at the beginning of the script and provide a clear error message if they are not found.
| if ! command -v jq &>/dev/null; then | |
| echo -e "${RED}Error: 'jq' is not installed. Please install it to use this script.${NC}" >&2 | |
| exit 1 | |
| fi | |
| get_repo_name() { | ||
| local root | ||
| root=$(get_repo_root) | ||
| if [[ -n "$root" ]]; then | ||
| basename "$root" | ||
| fi | ||
| } |
| time_diff=$((time_diff * -1)) | ||
| fi | ||
| # Within 1 hour | ||
| if [[ $time_diff -lt 3600000 ]]; then |
There was a problem hiding this comment.
| while IFS= read -r line; do | ||
| if [[ "$line" =~ ^worktree\ (.+)$ ]]; then | ||
| worktree_path="${BASH_REMATCH[1]}" | ||
| elif [[ "$line" =~ ^branch\ refs/heads/(.+)$ ]]; then | ||
| worktree_branch="${BASH_REMATCH[1]}" | ||
| elif [[ -z "$line" ]]; then | ||
| if [[ -n "$worktree_path" ]] && [[ -n "$worktree_branch" ]]; then | ||
| if [[ "$worktree_branch" != "main" ]] && [[ "$worktree_branch" != "master" ]]; then | ||
| worktrees+=("$worktree_path") | ||
| branches+=("$worktree_branch") | ||
| fi | ||
| fi | ||
| worktree_path="" | ||
| worktree_branch="" | ||
| fi | ||
| done < <(git worktree list --porcelain; echo "") |
There was a problem hiding this comment.
The logic for parsing the output of git worktree list --porcelain is duplicated in cmd_list (lines 276-350) and here in cmd_open. To improve maintainability and reduce redundancy, this parsing logic should be extracted into a dedicated helper function. This function could populate the worktrees and branches arrays, which can then be used by both cmd_list and cmd_open.
🤖 Augment PR SummarySummary: Adds tooling and documentation to better recover and resume OpenCode sessions when working with multiple Git worktrees. Changes:
Technical Notes: Branch “start time” is inferred from the first commit unique to the branch (or worktree mtime if none), then compared to session timestamps to boost likely matches. 🤖 Was this summary useful? React with 👍 or 👎 |
| fi | ||
|
|
||
| # Scoring: branch slug in title (case-insensitive) | ||
| if echo "$session_title" | grep -qi "$branch_slug"; then |
There was a problem hiding this comment.
grep -qi "$branch_slug" treats the branch value as a regex, so branch names containing regex metacharacters can mis-score (or emit regex errors). Consider using fixed-string matching (e.g., grep -Fqi) here (also applies to the other grep -qi checks below).
Other Locations
.agent/scripts/worktree-sessions.sh:201.agent/scripts/worktree-sessions.sh:207
🤖 Was this useful? React with 👍 or 👎
| return 1 | ||
| fi | ||
|
|
||
| local index=$((choice - 1)) |
| for project_file in "$PROJECT_BASE"/*.json; do | ||
| if [[ -f "$project_file" ]]; then | ||
| local project_dir | ||
| project_dir=$(jq -r '.worktree // .path // .directory // ""' "$project_file" 2>/dev/null) |
There was a problem hiding this comment.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
.agent/scripts/worktree-sessions.sh (1)
71-86: Minor: Redundant stderr redirection.Line 76 has
&>/dev/null 2>&1where&>/dev/nullalone suffices (it already redirects both stdout and stderr). The script functions correctly, but this is a small cleanup opportunity.🧹 Optional cleanup
- if date --version &>/dev/null 2>&1; then + if date --version &>/dev/null; then
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
.agent/AGENTS.md.agent/scripts/worktree-sessions.sh.agent/workflows/worktree.md
🧰 Additional context used
📓 Path-based instructions (1)
.agent/scripts/*.sh
⚙️ CodeRabbit configuration file
.agent/scripts/*.sh: Automation scripts - focus on:
- Reliability and robustness
- Clear logging and feedback
- Proper exit codes
- Error recovery mechanisms
Files:
.agent/scripts/worktree-sessions.sh
🧠 Learnings (14)
📓 Common learnings
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Follow all security protocols and working directory specifications defined in ~/Git/aidevops/AGENTS.md
📚 Learning: 2026-01-06T15:57:56.008Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-06T15:57:56.008Z
Learning: Applies to **/AGENTS.md : Limit root AGENTS.md to ~50-100 max instructions with universal applicability to >80% of tasks
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-11-29T04:34:42.033Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: AGENT.md:0-0
Timestamp: 2025-11-29T04:34:42.033Z
Learning: Reference AGENTS.md (authoritative) instead of AGENT.md for AI assistant guidance
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-11-29T04:34:27.158Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-29T04:34:27.158Z
Learning: All instructions, documentation, and operational guidance should be maintained in AGENTS.md as the single source of truth
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-11-29T04:34:30.742Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: GEMINI.md:0-0
Timestamp: 2025-11-29T04:34:30.742Z
Learning: Maintain all instructions, documentation, and operational guidance in AGENTS.md as the single source of truth
Applied to files:
.agent/AGENTS.md
📚 Learning: 2026-01-06T15:57:56.007Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-06T15:57:56.007Z
Learning: Applies to **/.agent/scripts/linters-local.sh : Run quality checks before committing using .agent/scripts/linters-local.sh
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-12-22T01:24:53.937Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Follow all security protocols and working directory specifications defined in ~/Git/aidevops/AGENTS.md
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-11-29T04:34:30.742Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: GEMINI.md:0-0
Timestamp: 2025-11-29T04:34:30.742Z
Learning: Reference AGENTS.md for authoritative AI assistant guidance instead of GEMINI.md
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-11-29T04:34:42.033Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: AGENT.md:0-0
Timestamp: 2025-11-29T04:34:42.033Z
Learning: Maintain all AI assistant instructions, documentation, and operational guidance in AGENTS.md as the single source of truth
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-12-22T01:25:03.138Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/git/AGENTS.md:0-0
Timestamp: 2025-12-22T01:25:03.138Z
Learning: Follow security protocols for all git and DevOps operations
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-12-22T01:24:53.937Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Never store credentials in working directories (~/.aidevops/.agent-workspace/), Git repositories, home directory root, or hardcoded in code and scripts
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-12-22T01:24:53.937Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Reference the authoritative repository at ~/Git/aidevops/ for all detailed AI assistant instructions and configurations
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-12-22T01:25:03.138Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/git/AGENTS.md:0-0
Timestamp: 2025-12-22T01:25:03.138Z
Learning: NEVER store credentials or API keys in ~/.aidevops/.agent-workspace/ directories - working files are not secure
Applied to files:
.agent/AGENTS.md
📚 Learning: 2025-12-22T01:24:53.937Z
Learnt from: CR
Repo: marcusquinn/aidevops PR: 0
File: templates/home/AGENTS.md:0-0
Timestamp: 2025-12-22T01:24:53.937Z
Learning: Use only the specified working directories: ~/.aidevops/.agent-workspace/work/[project]/ for work files, ~/.aidevops/.agent-workspace/tmp/ for temporary files, and ~/.aidevops/.agent-workspace/memory/ for persistent memory
Applied to files:
.agent/AGENTS.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (11)
.agent/workflows/worktree.md (1)
290-318: LGTM! Well-documented session recovery workflow.The scoring system and confidence levels are clearly explained and match the implementation in
worktree-sessions.sh. The best practice recommendation forsession-rename_sync_branchhelps ensure reliable future lookups..agent/AGENTS.md (3)
13-24: LGTM! Comprehensive pre-edit triggers.The expanded trigger list and explicit trigger words provide clear, actionable guidance. This helps ensure consistent pre-edit checks across all file modification scenarios.
54-61: LGTM! Essential dual-location clarification.The self-verification prompt and dual-location guidance address a real source of confusion when working on the aidevops framework itself. This prevents accidental commits to protected branches from the deployed (non-git) location.
177-178: LGTM! Good integration with existing worktree workflow.The new session listing command fits naturally alongside the existing worktree commands, providing a clear path to session recovery.
.agent/scripts/worktree-sessions.sh (7)
1-35: LGTM! Solid script foundation with strict mode enabled.The
set -euo pipefailensures fail-fast behavior. The ShellCheck disables are justified—SC2034 for potentially unused color constants and SC2155 for the commonlocal var=$(...)pattern.
41-69: LGTM! Robust utility functions with good defensive parsing.The
jqfallback chain (.worktree // .path // .directory) handles schema variations gracefully. The[[ -f "$project_file" ]]guard correctly handles the case when no JSON files exist.
98-144: LGTM! Well-designed fallback chains for cross-platform compatibility.The default branch detection gracefully handles remote HEAD, then falls back to checking for
mainormaster. The|| trueon line 131 correctly preventsset -efrom terminating the script when the branch has no unique commits.Same minor note: line 138 has redundant
&>/dev/null 2>&1.
146-243: LGTM! Well-implemented scoring algorithm.The scoring system is comprehensive and matches the documented behavior in
worktree.md. The portablegrep -qifor case-insensitive matching and the manual absolute value calculation are appropriate. The2>/dev/nullon the printf correctly handles empty arrays.
249-366: LGTM! Clean command implementation with good UX.The
git worktree list --porcelainparsing is robust, and the trailingecho ""ensures the final entry is processed. Clear error messages, informative output, and helpful tips make this user-friendly.
368-462: LGTM! Solid interactive selection with cross-platform launch support.Input validation is thorough—checking for numeric input and valid range. The multi-tier launch strategy (CLI → macOS app bundle → xdg-open → manual instructions) provides good fallback coverage across platforms.
464-535: LGTM! Clean command dispatch with helpful aliases.The quoted heredoc
'EOF'correctly prevents variable expansion in the help text. Command aliases (ls,o,-h) provide convenient shortcuts, and all paths return appropriate exit codes.



Summary
worktree-sessions.shscript to map git worktrees to likely OpenCode sessionsChanges
New:
worktree-sessions.shMaps worktrees to OpenCode sessions using scoring based on:
Portability fixes (addressing previous review feedback):
datecommand (GNU-d @vs BSD-r)statcommand (GNU-cvs BSD-f)Commands:
list- Show worktrees with likely matching sessionsopen- Interactive selection to open worktree in OpenCodeImproved: Pre-Edit Git Check (AGENTS.md)
Based on agent-review analysis of why the check was skipped:
~/Git/aidevops/) vs deployed (~/.aidevops/agents/)Updated:
workflows/worktree.mdAdded "Session Recovery" section documenting how to find and resume sessions for worktrees.
Testing
Summary by CodeRabbit
New Features
Documentation
✏️ Tip: You can customize this high-level summary in your review settings.