feat(worktree): add session mapping and improve pre-edit check#28
feat(worktree): add session mapping and improve pre-edit check#28marcusquinn wants to merge 3 commits intomainfrom
Conversation
- Add worktree-sessions.sh to map worktrees to likely OpenCode sessions - Strengthen pre-edit check with explicit trigger words (create, add, write, etc.) - Add self-verification prompt for file operations - Clarify dual-location workflow for aidevops framework - Document session recovery in worktree.md
|
Warning Rate limit exceeded@marcusquinn has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 14 minutes and 24 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
WalkthroughExpands AGENTS.md with a detailed pre-edit checklist, trigger-word rules, self-check commands and fallback branch workflow; adds Changes
Sequence DiagramsequenceDiagram
actor User
participant Script as worktree-sessions.sh
participant Git as Git Worktrees
participant FS as File System
participant Store as Session Store (JSON)
participant OpenCode
User->>Script: worktree-sessions list
Script->>Git: discover worktrees & branch names
Git-->>Script: worktree list & branch refs
loop per worktree
Script->>Git: get branch start commit date
alt commit exists
Git-->>Script: commit date
else
Script->>FS: read worktree dir mtime
FS-->>Script: mtime fallback
end
end
Script->>Store: load sessions for project
Store-->>Script: session entries
loop score sessions
Script->>Script: check exact branch match
Script->>Script: check slug/terms in session title
Script->>Script: compare temporal proximity
end
Script->>User: display ranked matches with confidence
alt User requests open
User->>Script: worktree-sessions open <worktree>
Script->>OpenCode: launch or show open guidance
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 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. 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 significantly improves the developer experience by streamlining the management of Git worktrees and their associated OpenCode sessions. It introduces a new utility to intelligently link worktrees with relevant sessions, making it easier to pick up where you left off. Concurrently, it reinforces critical safeguards within the agent workflow to ensure proper Git practices are followed, enhancing overall system reliability and preventing common development errors. 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 00:45:15 UTC 2026 Generated by AI DevOps Framework Code Review Monitoring |
There was a problem hiding this comment.
Code Review
This pull request introduces a helpful worktree-sessions.sh script for mapping git worktrees to OpenCode sessions and improves the pre-edit check documentation. The new script is well-structured, but I've identified a few areas for improvement, primarily concerning portability to non-macOS systems, code duplication, and robustness in determining the git default branch. I've also pointed out a minor inefficiency. The documentation changes are clear and enhance the developer/agent workflow.
.agent/scripts/worktree-sessions.sh
Outdated
|
|
||
| # Get the first commit unique to this branch | ||
| local first_commit_date | ||
| first_commit_date=$(git -C "$worktree_path" log main.."$branch" --format="%ct" --reverse 2>/dev/null | head -1) |
There was a problem hiding this comment.
The script hardcodes main as the base branch when searching for the first commit. This will fail in repositories that use master or another name for the default branch. While you handle both main and master elsewhere, it's missing here.
You could make this more robust by first checking for the existence of main and falling back to master, like this:
local main_branch="main"
if ! git -C "$worktree_path" show-ref --verify --quiet "refs/heads/$main_branch"; then
main_branch="master"
fi
first_commit_date=$(git -C "$worktree_path" log "$main_branch".."$branch" --format="%ct" --reverse 2>/dev/null | head -1)
.agent/scripts/worktree-sessions.sh
Outdated
| # No unique commits, use worktree creation time (directory mtime) | ||
| stat -f "%m" "$worktree_path" 2>/dev/null || echo "" |
There was a problem hiding this comment.
The stat -f "%m" command is specific to BSD/macOS. On GNU/Linux systems, the equivalent is stat -c "%Y". This will cause the script to fail or behave incorrectly on Linux. You should add a check for the operating system to use the correct stat command for better portability.
| # No unique commits, use worktree creation time (directory mtime) | |
| stat -f "%m" "$worktree_path" 2>/dev/null || echo "" | |
| # No unique commits, use worktree creation time (directory mtime) | |
| if [[ "$(uname)" == "Darwin" ]]; then | |
| stat -f "%m" "$worktree_path" 2>/dev/null || echo "" | |
| else | |
| stat -c "%Y" "$worktree_path" 2>/dev/null || echo "" | |
| fi |
.agent/scripts/worktree-sessions.sh
Outdated
|
|
||
| # Scoring: key terms from branch name | ||
| for part in "${branch_parts[@]}"; do | ||
| if [[ ${#part} -gt 3 ]] && echo "$session_title" | tr '[:upper:]' '[:lower:]' | grep -qi "$part"; then |
There was a problem hiding this comment.
The tr '[:upper:]' '[:lower:]' command is redundant here because you are using grep -qi, which performs a case-insensitive search. You can remove the tr pipe for slightly better performance and cleaner code.
| if [[ ${#part} -gt 3 ]] && echo "$session_title" | tr '[:upper:]' '[:lower:]' | grep -qi "$part"; then | |
| if [[ ${#part} -gt 3 ]] && echo "$session_title" | grep -qi "$part"; then |
| 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.
This while loop for parsing the output of git worktree list --porcelain is almost identical to the one in cmd_list (lines 228-302). Duplicating this logic makes the script harder to maintain. Consider extracting it into a helper function that populates the worktrees and branches arrays. This function could then be called by both cmd_list and cmd_open.
.agent/scripts/worktree-sessions.sh
Outdated
| if [[ -d "/Applications/OpenCode.app" ]]; then | ||
| echo "Launching OpenCode..." | ||
| open -a "OpenCode" "$selected_path" | ||
| else | ||
| echo "OpenCode.app not found. To open manually:" | ||
| echo " cd $selected_path" | ||
| echo " # Then launch your preferred editor/terminal" | ||
| fi |
There was a problem hiding this comment.
This block is specific to macOS, checking for /Applications/OpenCode.app and using open -a. This makes the open command of the script non-portable to other environments like Linux. For better portability, you could check the OS and use the appropriate command (xdg-open on Linux).
| if [[ -d "/Applications/OpenCode.app" ]]; then | |
| echo "Launching OpenCode..." | |
| open -a "OpenCode" "$selected_path" | |
| else | |
| echo "OpenCode.app not found. To open manually:" | |
| echo " cd $selected_path" | |
| echo " # Then launch your preferred editor/terminal" | |
| fi | |
| if [[ "$(uname)" == "Darwin" ]] && [[ -d "/Applications/OpenCode.app" ]]; then | |
| echo "Launching OpenCode..." | |
| open -a "OpenCode" "$selected_path" | |
| elif command -v xdg-open &>/dev/null; then | |
| echo "Opening with default application..." | |
| xdg-open "$selected_path" | |
| else | |
| echo "Could not open automatically. To open manually:" | |
| echo " cd $selected_path" | |
| echo " # Then launch your preferred editor/terminal" | |
| fi |
🤖 Augment PR SummarySummary: This PR improves worktree ergonomics by helping correlate Git worktrees with their likely OpenCode sessions, and reinforces the agent workflow guardrails to prevent accidental edits on protected branches. Changes:
Technical Notes: The session matcher reads OpenCode project/session JSON from 🤖 Was this summary useful? React with 👍 or 👎 |
.agent/scripts/worktree-sessions.sh
Outdated
|
|
||
| # Get the first commit unique to this branch | ||
| local first_commit_date | ||
| first_commit_date=$(git -C "$worktree_path" log main.."$branch" --format="%ct" --reverse 2>/dev/null | head -1) |
There was a problem hiding this comment.
get_branch_start_date() runs under set -euo pipefail, so if git log main.."$branch" fails (e.g., no main branch), the script will exit before reaching the fallback stat path. Consider resolving the default branch (similar to worktree-helper.sh) and/or making this probe non-fatal so the fallback can execute.
🤖 Was this useful? React with 👍 or 👎
| return 0 | ||
| fi | ||
|
|
||
| local index=$((choice - 1)) |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @.agent/scripts/worktree-sessions.sh:
- Around line 72-79: The epoch_to_date function uses the BSD/macOS-specific
`date -r` which breaks on GNU/Linux; update epoch_to_date to convert epoch_ms to
seconds and attempt a portable command: prefer `date -d @<seconds>` on GNU
coreutils, fall back to `date -r <seconds>` on BSD, and if neither is available
use a small POSIX-safe fallback (e.g., call python/perl to format the timestamp)
so the function works across platforms; locate the epoch_to_date function and
implement the detection and fallback logic around `date` usage.
🧹 Nitpick comments (4)
.agent/scripts/worktree-sessions.sh (4)
2-2: Verify SC2034 disable is justified.The blanket disable of SC2034 (unused variables) can hide legitimate issues. After reviewing the script, the color constants
RED,BOLD, andDIMare defined but never used - onlyGREEN,YELLOW,BLUE,CYAN, andNCare referenced.🧹 Proposed cleanup
-readonly RED='\033[0;31m' readonly GREEN='\033[0;32m' readonly YELLOW='\033[1;33m' readonly BLUE='\033[0;34m' readonly CYAN='\033[0;36m' -readonly BOLD='\033[1m' -readonly DIM='\033[2m' readonly NC='\033[0m'Or keep them for future use but add a comment explaining why SC2034 is disabled.
34-35: Consider XDG Base Directory support for better portability.The hardcoded paths assume
~/.local/share/opencode/which works for macOS and many Linux distros, but doesn't follow XDG Base Directory specification. Consider using${XDG_DATA_HOME:-$HOME/.local/share}for better Linux compatibility.♻️ Proposed portability improvement
+# OpenCode session storage (XDG-compliant) +readonly OPENCODE_DATA="${XDG_DATA_HOME:-$HOME/.local/share}/opencode" +readonly SESSION_BASE="$OPENCODE_DATA/storage/session" +readonly PROJECT_BASE="$OPENCODE_DATA/storage/project" -# OpenCode session storage -readonly SESSION_BASE="$HOME/.local/share/opencode/storage/session" -readonly PROJECT_BASE="$HOME/.local/share/opencode/storage/project"
228-302: Consider adding error handling for the worktree parsing loop.The state machine pattern for parsing
git worktree list --porcelainis correct, but there's no error handling if the git command itself fails. Whileset -euo pipefailwill catch this, it might be better to provide a more user-friendly error message.♻️ Proposed improvement
+ # Verify git worktree command is available + if ! git worktree list --porcelain &>/dev/null; then + echo -e "${RED}Error: Failed to list worktrees${NC}" + echo "This repository may not support worktrees or git version is too old" + return 1 + fi + # Parse worktrees local worktree_path=""
392-399: macOS-specific OpenCode launch could be more robust.Line 392 checks for
/Applications/OpenCode.appbut this assumes a system-wide installation. OpenCode could also be installed in~/Applications/or launched via theopencodeCLI command.♻️ Proposed improvement for better compatibility
- # Check if OpenCode.app exists - if [[ -d "/Applications/OpenCode.app" ]]; then + # Try to launch OpenCode (CLI first, then app bundle) + if command -v opencode &>/dev/null; then + echo "Launching OpenCode via CLI..." + cd "$selected_path" && opencode . + elif [[ -d "/Applications/OpenCode.app" ]] || [[ -d "$HOME/Applications/OpenCode.app" ]]; then echo "Launching OpenCode..." open -a "OpenCode" "$selected_path" else - echo "OpenCode.app not found. To open manually:" + echo "OpenCode not found. To open manually:" echo " cd $selected_path" - echo " # Then launch your preferred editor/terminal" + echo " opencode . # or launch your preferred editor" fi
📜 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 (16)
📓 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
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
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
📚 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: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: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.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: 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: 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 : Use progressive disclosure in AGENTS.md with pointers to subagents rather than inline content
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: 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: 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 : Include code examples in AGENTS.md only when authoritative, otherwise use file:line references
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 (9)
.agent/workflows/worktree.md (2)
290-318: Excellent addition to the workflow documentation.The Session Recovery section provides clear, actionable guidance with well-documented scoring methodology and confidence levels. The best practice recommendation to use
session-rename_sync_branchfor reliability is particularly helpful.
321-329: LGTM - Improved clarity on worktree organization.The updated wording makes the main worktree convention clearer, and the path pattern generalization (
{repo}-feature-*/) better reflects actual usage patterns..agent/AGENTS.md (4)
13-22: Strong improvement to pre-edit workflow clarity.The expanded trigger list (creating, editing, writing) and explicit trigger words (create, add, write, update, modify, change, fix, implement, refactor) remove ambiguity about when pre-edit checks are required. This should significantly reduce accidental commits to protected branches.
24-28: Good practice to make the check explicit.The instruction to say "Checking git branch..." before running the script provides useful feedback and makes the workflow visible to users.
32-59: Comprehensive fallback and workflow guidance.The manual check provides clear step-by-step instructions with numbered options. The self-verification prompt ("Have I run pre-edit-check.sh in this session?") is an excellent forcing function. The two-location workflow explanation (Source vs Deployed) is critical context for the aidevops framework.
174-176: Good integration of session discovery into the workflow.The placement of the
worktree-sessions.sh listcommand in the worktree workflow section provides a natural discovery point for users managing multiple sessions..agent/scripts/worktree-sessions.sh (3)
99-195: Scoring algorithm is well-implemented and matches documentation.The session matching logic correctly implements the documented scoring system with appropriate weights and thresholds. The temporal proximity calculations and branch name normalization are sound.
404-447: Help text is comprehensive and well-formatted.The help documentation is clear, includes practical examples, explains the matching methodology, and provides useful tips. Well done.
453-475: Main function is well-structured with good command dispatch.The command routing is clean with sensible aliases (ls, o, -h, --help) and proper error handling for unknown commands. The default to
listis intuitive.
- Make epoch_to_date portable (GNU date -d vs BSD date -r) - Add get_default_branch to detect main/master dynamically - Make stat command portable (GNU -c vs BSD -f) - Remove redundant tr before grep -qi - Add input validation for numeric choice in cmd_open - Improve OpenCode launch with CLI fallback and xdg-open for Linux
🔍 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 00:52:31 UTC 2026 Generated by AI DevOps Framework Code Review Monitoring |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @.agent/scripts/worktree-sessions.sh:
- Around line 291-295: The use of `date -r "$branch_start"` is BSD-specific and
nonportable; replace this call by reusing the existing portable conversion
function `epoch_to_date()` (or add it if missing) to convert `branch_start` into
a human timestamp, assign that result to the `start_date` local variable, and
keep the same fallback to "unknown" and the existing echo formatting with
`${DIM}` and `${NC}`.
- Around line 209-221: The arithmetic using values from jq (session_created and
session_updated) is not validated and can break under set -euo pipefail if they
are non-numeric; before computing time_diff or calling epoch_to_date, validate
the variables with the existing numeric regex (e.g., [[ "$session_created" =~
^[0-9]+$ ]]) and only perform the subtraction/time-diff/epoch_to_date call when
numeric, otherwise skip or handle gracefully; update the block that uses
session_created with this check and add the same validation for session_updated
where epoch_to_date is invoked, referencing the session_created,
session_updated, branch_start_ms, score arithmetic and the epoch_to_date
function names to locate and modify the code.
🧹 Nitpick comments (3)
.agent/scripts/worktree-sessions.sh (3)
33-35: Consider XDG Base Directory compliance.The paths assume OpenCode uses
$HOME/.local/share/, but users may haveXDG_DATA_HOMEset to a custom location. This is a minor portability consideration.♻️ Suggested improvement
# OpenCode session storage -readonly SESSION_BASE="$HOME/.local/share/opencode/storage/session" -readonly PROJECT_BASE="$HOME/.local/share/opencode/storage/project" +readonly XDG_DATA="${XDG_DATA_HOME:-$HOME/.local/share}" +readonly SESSION_BASE="$XDG_DATA/opencode/storage/session" +readonly PROJECT_BASE="$XDG_DATA/opencode/storage/project"
77-77: Minor: redundant redirect.
&>/dev/nullalready redirects both stdout and stderr; the trailing2>&1is superfluous.♻️ Suggested fix
- if date --version &>/dev/null 2>&1; then + if date --version &>/dev/null; then
129-129: Minor: same redundant redirect pattern.For consistency with the earlier comment on
epoch_to_date:♻️ Suggested fix
- if stat --version &>/dev/null 2>&1; then + if stat --version &>/dev/null; then
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
.agent/scripts/worktree-sessions.sh
🧰 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 (1)
📓 Common learnings
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
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
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
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
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
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
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
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 : Use progressive disclosure in AGENTS.md with pointers to subagents rather than inline content
⏰ 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 (7)
.agent/scripts/worktree-sessions.sh (7)
1-21: LGTM — solid script foundation.Good use of
set -euo pipefailfor fail-fast behavior. The shellcheck pragmas are reasonable given the script's pattern of inline variable assignments and color constants.
41-51: LGTM — clean repository detection.Fallback to empty string on non-repo contexts is handled gracefully, and callers check for empty results appropriately.
53-69: LGTM — project ID lookup is well-guarded.The
[[ -f "$project_file" ]]check handles the case where the glob doesn't match any files, and jq errors are appropriately suppressed.
89-109: LGTM — robust default branch detection.The three-tier fallback (remote HEAD → local refs → hardcoded "main") handles various repository configurations gracefully.
417-427: LGTM — solid input validation.Numeric check with regex followed by bounds validation is the right approach. Good error messages guide users clearly.
443-445: Note:xdg-openon a directory may not launch OpenCode.The
xdg-openfallback opens the directory with the system's default handler for directories (likely a file manager, not OpenCode). Consider whether this is the intended behavior or if the manual instructions fallback would be more appropriate for Linux without the CLI.This is likely acceptable as a "best effort" fallback, but worth confirming the expected user experience on Linux systems without the
opencodeCLI.
504-526: LGTM — clean command dispatch.Default command, aliases (
ls,o), and proper error handling for unknown commands. Theshift || truepattern safely handles the case where no arguments are provided.
| if [[ "$session_created" != "0" ]] && [[ "$session_created" != "null" ]]; then | ||
| time_diff=$((session_created - branch_start_ms)) | ||
| if [[ $time_diff -lt 0 ]]; then | ||
| time_diff=$((time_diff * -1)) | ||
| fi | ||
| # Within 1 hour | ||
| if [[ $time_diff -lt 3600000 ]]; then | ||
| score=$((score + 40)) | ||
| # Within 4 hours | ||
| elif [[ $time_diff -lt 14400000 ]]; then | ||
| score=$((score + 20)) | ||
| fi | ||
| fi |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n .agent/scripts/worktree-sessions.sh | sed -n '137,234p'Repository: marcusquinn/aidevops
Length of output: 4168
🏁 Script executed:
head -50 .agent/scripts/worktree-sessions.shRepository: marcusquinn/aidevops
Length of output: 1546
🏁 Script executed:
wc -l .agent/scripts/worktree-sessions.shRepository: marcusquinn/aidevops
Length of output: 103
🏁 Script executed:
# Search for where session files are written or created
rg -i "time\.created|session.*created" --type shell --type json -A 2 -B 2Repository: marcusquinn/aidevops
Length of output: 93
🏁 Script executed:
# Check if there's any session file format validation or schema
fd -e json . "$HOME/.local/share/opencode/storage/" 2>/dev/null | head -5 | xargs -I {} sh -c 'echo "=== {} ===" && jq . {} 2>/dev/null | head -20'Repository: marcusquinn/aidevops
Length of output: 46
🏁 Script executed:
# Look for session creation logic
rg "ses_.*\.json|SESSION_BASE" --type shell -B 3 -A 3Repository: marcusquinn/aidevops
Length of output: 93
🏁 Script executed:
# Search for session creation or time.created patterns
rg "time\.created|session.*created" -i -A 2 -B 2Repository: marcusquinn/aidevops
Length of output: 1788
🏁 Script executed:
# Look for where session files are written
rg "ses_.*\.json" -A 3 -B 3Repository: marcusquinn/aidevops
Length of output: 501
🏁 Script executed:
# Check script for jq usage and data handling
rg "jq.*time" -A 1 -B 1Repository: marcusquinn/aidevops
Length of output: 775
🏁 Script executed:
# Check if set -e is active and what error handling exists
head -100 .agent/scripts/worktree-sessions.sh | grep -E "set |trap|error"Repository: marcusquinn/aidevops
Length of output: 81
🏁 Script executed:
# Check the full scoring section and surrounding error handling
sed -n '200,230p' .agent/scripts/worktree-sessions.shRepository: marcusquinn/aidevops
Length of output: 1239
🏁 Script executed:
# Look for any validation or type checking patterns elsewhere in the script
rg "=~|isdigit|numeric" .agent/scripts/worktree-sessions.shRepository: marcusquinn/aidevops
Length of output: 332
🏁 Script executed:
# Check for any trap handlers or error handling
grep -n "trap\|error\|Error\|ERROR" .agent/scripts/worktree-sessions.shRepository: marcusquinn/aidevops
Length of output: 191
🏁 Script executed:
# Search for how session_updated is used (same jq extraction pattern)
rg "session_updated" -A 5 -B 2 .agent/scripts/worktree-sessions.shRepository: marcusquinn/aidevops
Length of output: 926
🏁 Script executed:
# Find the epoch_to_date function to see how it handles session_updated
rg "epoch_to_date" -A 15 .agent/scripts/worktree-sessions.shRepository: marcusquinn/aidevops
Length of output: 1136
🏁 Script executed:
# Check if there's any documentation on the session file format
find . -name "*.md" -o -name "*.json" | xargs grep -l "time\.created\|session.*format" 2>/dev/null | head -5Repository: marcusquinn/aidevops
Length of output: 46
🏁 Script executed:
# Test what happens with non-numeric values in arithmetic in bash with set -euo pipefail
bash -c 'set -euo pipefail; val="abc"; result=$((val + 1)); echo "$result"' 2>&1 || echo "Failed as expected"Repository: marcusquinn/aidevops
Length of output: 118
🏁 Script executed:
# Check if any sample session files exist in the repo
fd "ses_" --type f 2>/dev/null | head -3Repository: marcusquinn/aidevops
Length of output: 46
🏁 Script executed:
# Test if arithmetic with non-numeric string fails under set -euo pipefail
bash -c 'set -euo pipefail; session_created="abc"; branch_start_ms=1000; time_diff=$((session_created - branch_start_ms))' 2>&1 || trueRepository: marcusquinn/aidevops
Length of output: 99
🏁 Script executed:
# Test if the check pattern catches "0" and "null" correctly
bash -c '
session_created="0"
if [[ "$session_created" != "0" ]] && [[ "$session_created" != "null" ]]; then
echo "Would attempt arithmetic"
else
echo "Skipped safely"
fi
'Repository: marcusquinn/aidevops
Length of output: 78
🏁 Script executed:
# Test what jq returns for missing/malformed JSON
bash -c '
echo "{\"time\":{\"created\":\"not-a-number\"}}" | jq -r ".time.created // 0"
echo "{\"time\":{}}" | jq -r ".time.created // 0"
echo "{\"time\":{\"created\":1234567890}}" | jq -r ".time.created // 0"
'Repository: marcusquinn/aidevops
Length of output: 89
Add numeric validation before arithmetic operations on timestamps.
Lines 209–220 and the epoch_to_date function (line 227, 279) perform arithmetic on values extracted via jq without validating they are numeric. While jq defaults to 0 for missing/null fields, it returns the literal string if .time.created or .time.updated contains a non-numeric value. Under set -euo pipefail, arithmetic with non-numeric values fails and crashes the script.
Add regex validation before arithmetic, using the pattern already established elsewhere in the script:
if [[ "$session_created" =~ ^[0-9]+$ ]]; then
time_diff=$((session_created - branch_start_ms))
# ... rest of logic
fiApply the same check to session_updated before it's used in epoch_to_date.
🤖 Prompt for AI Agents
In @.agent/scripts/worktree-sessions.sh around lines 209 - 221, The arithmetic
using values from jq (session_created and session_updated) is not validated and
can break under set -euo pipefail if they are non-numeric; before computing
time_diff or calling epoch_to_date, validate the variables with the existing
numeric regex (e.g., [[ "$session_created" =~ ^[0-9]+$ ]]) and only perform the
subtraction/time-diff/epoch_to_date call when numeric, otherwise skip or handle
gracefully; update the block that uses session_created with this check and add
the same validation for session_updated where epoch_to_date is invoked,
referencing the session_created, session_updated, branch_start_ms, score
arithmetic and the epoch_to_date function names to locate and modify the code.
| if [[ -n "$branch_start" ]]; then | ||
| local start_date | ||
| start_date=$(date -r "$branch_start" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "unknown") | ||
| echo -e " ${DIM}Branch started: $start_date${NC}" | ||
| fi |
There was a problem hiding this comment.
Portability issue: date -r is BSD-only.
The script correctly handles GNU/BSD differences in epoch_to_date(), but here date -r is used directly. On GNU systems, this will fail or produce incorrect output.
🔧 Suggested fix — reuse the portable function
if [[ -n "$branch_start" ]]; then
local start_date
- start_date=$(date -r "$branch_start" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "unknown")
+ # branch_start is in seconds, epoch_to_date expects milliseconds
+ start_date=$(epoch_to_date "$((branch_start * 1000))")
echo -e " ${DIM}Branch started: $start_date${NC}"
fi🤖 Prompt for AI Agents
In @.agent/scripts/worktree-sessions.sh around lines 291 - 295, The use of `date
-r "$branch_start"` is BSD-specific and nonportable; replace this call by
reusing the existing portable conversion function `epoch_to_date()` (or add it
if missing) to convert `branch_start` into a human timestamp, assign that result
to the `start_date` local variable, and keep the same fallback to "unknown" and
the existing echo formatting with `${DIM}` and `${NC}`.
Reuse the portable date formatting function instead of direct date -r which only works on BSD/macOS.
|
🔍 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 00:59:54 UTC 2026 Generated by AI DevOps Framework Code Review Monitoring |



Summary
worktree-sessions.shscript to map git worktrees to likely OpenCode sessionsChanges
New:
worktree-sessions.shMaps worktrees to OpenCode sessions using scoring based on:
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
✏️ Tip: You can customize this high-level summary in your review settings.