From ab80a81ea0184f642b945f18871a03e3e67bc7b2 Mon Sep 17 00:00:00 2001 From: Logan Gagne Date: Tue, 10 Nov 2026 17:08:44 -0500 Subject: [PATCH 1/6] =?UTF-8?q?feat(opencode):=20M0=20foundation=20?= =?UTF-8?q?=E2=80=94=20target-aware=20vendoring,=20validator,=20scaffold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Canonicalize branch + sitrep into utils/ and vendor them back into plugins-claude/session byte-for-byte (previously unmanaged copies that could drift silently; now covered by sync --check). - sync.sh manifest becomes target-aware (NEEDS_CLAUDE / NEEDS_OPENCODE); --check covers plugins-opencode drift with the same CI gate. - New validate-opencode.sh (separate from the Claude/Copilot-specific validate-plugins.sh) wired into CI + validate-all.sh parity. - plugins-opencode/ scaffold: inbox (RPC + server + TUI stub proving the install shape) and session (server stub); vendored scripts in place. - tests/opencode: sync target-awareness/drift, validator clean/dirty fixtures. Refs #236 --- .github/scripts/validate-all.sh | 37 +- .github/scripts/validate-opencode.sh | 168 +++ .github/workflows/ci.yml | 2 + plugins-opencode/README.md | 48 + plugins-opencode/git-tools/scripts/branch | 38 + plugins-opencode/git-tools/scripts/git-wait | 1460 +++++++++++++++++++ plugins-opencode/git-tools/scripts/sitrep | 246 ++++ plugins-opencode/inbox/package.json | 19 + plugins-opencode/inbox/scripts/inbox | 465 ++++++ plugins-opencode/inbox/src/index.ts | 56 + plugins-opencode/inbox/src/rpc.ts | 70 + plugins-opencode/inbox/src/tui.tsx | 17 + plugins-opencode/session/package.json | 12 + plugins-opencode/session/scripts/branch | 38 + plugins-opencode/session/scripts/git-wait | 1460 +++++++++++++++++++ plugins-opencode/session/scripts/sitrep | 246 ++++ plugins-opencode/session/src/index.ts | 8 + tests/opencode/test-sync.sh | 126 ++ tests/opencode/test-validate-opencode.sh | 122 ++ utils/branch | 38 + utils/sitrep | 246 ++++ utils/sync.sh | 130 +- 22 files changed, 4980 insertions(+), 72 deletions(-) create mode 100644 .github/scripts/validate-opencode.sh create mode 100644 plugins-opencode/README.md create mode 100755 plugins-opencode/git-tools/scripts/branch create mode 100755 plugins-opencode/git-tools/scripts/git-wait create mode 100755 plugins-opencode/git-tools/scripts/sitrep create mode 100644 plugins-opencode/inbox/package.json create mode 100755 plugins-opencode/inbox/scripts/inbox create mode 100644 plugins-opencode/inbox/src/index.ts create mode 100644 plugins-opencode/inbox/src/rpc.ts create mode 100644 plugins-opencode/inbox/src/tui.tsx create mode 100644 plugins-opencode/session/package.json create mode 100755 plugins-opencode/session/scripts/branch create mode 100755 plugins-opencode/session/scripts/git-wait create mode 100755 plugins-opencode/session/scripts/sitrep create mode 100644 plugins-opencode/session/src/index.ts create mode 100644 tests/opencode/test-sync.sh create mode 100644 tests/opencode/test-validate-opencode.sh create mode 100755 utils/branch create mode 100755 utils/sitrep diff --git a/.github/scripts/validate-all.sh b/.github/scripts/validate-all.sh index b7f5345..e1cb62b 100755 --- a/.github/scripts/validate-all.sh +++ b/.github/scripts/validate-all.sh @@ -20,24 +20,25 @@ declare -a names=() results=() failed=0 run_check() { - local name="$1" - shift - echo "===============================" - echo "=== $name" - echo "===============================" - names+=("$name") - if "$@"; then - results+=("PASS") - else - results+=("FAIL") - failed=1 - fi - echo "" + local name="$1" + shift + echo "===============================" + echo "=== $name" + echo "===============================" + names+=("$name") + if "$@"; then + results+=("PASS") + else + results+=("FAIL") + failed=1 + fi + echo "" } run_check "ci parity" bash .github/scripts/check-ci-parity.sh run_check "plugin tests" bash test.sh run_check "plugin structure" bash .github/scripts/validate-plugins.sh +run_check "opencode structure" bash .github/scripts/validate-opencode.sh run_check "frontmatter" bash .github/scripts/validate-frontmatter.sh # Not a pass/fail check (it only warns), so it is not a run_check and has no CI # job; the note is repeated after the summary so it is not lost in the output. @@ -51,19 +52,19 @@ echo "===============================" echo "=== Summary" echo "===============================" for i in "${!names[@]}"; do - printf " %-20s [%s]\n" "${names[$i]}" "${results[$i]}" + printf " %-20s [%s]\n" "${names[$i]}" "${results[$i]}" done echo "" if [[ "$rumdl_note" == WARNING* ]]; then - echo "$rumdl_note" - echo "" + echo "$rumdl_note" + echo "" fi if [[ $failed -eq 0 ]]; then - echo "All checks passed." + echo "All checks passed." else - echo "Some checks failed." + echo "Some checks failed." fi exit "$failed" diff --git a/.github/scripts/validate-opencode.sh b/.github/scripts/validate-opencode.sh new file mode 100644 index 0000000..cb488e9 --- /dev/null +++ b/.github/scripts/validate-opencode.sh @@ -0,0 +1,168 @@ +#!/usr/bin/env bash +# validate-opencode.sh — structural validation for the plugins-opencode/ tree. +# +# Deliberately separate from validate-plugins.sh: those checks are +# Claude/Copilot-specific (hooks.json casing, _PLUGIN_ROOT vars, marketplace +# files) and none of those artifacts exist for OpenCode. +# +# Checks: +# 1. JSON validity — all .json files under plugins-opencode parse +# 2. JSONC snippets — config snippets parse after stripping line comments +# 3. Code plugin packages — inbox/session carry a package.json whose exports +# point at files that exist +# 4. Skill frontmatter — SKILL.md files have name and description +# 5. Command bodies — command .md files have a non-empty body +# 6. No Claude leakage — no ${CLAUDE_PLUGIN_ROOT}/${CLAUDE_SESSION_ID} refs +# 7. Vendored scripts — plugins-opencode/*/scripts/* are executable +# +# Exit codes: 0 = all passed, 1 = one or more failures. + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +cd "$REPO_ROOT" + +TARGET="plugins-opencode" +ERRORS=0 +CHECKS=0 + +pass() { + CHECKS=$((CHECKS + 1)) + echo " ✓ $1" +} +fail() { + CHECKS=$((CHECKS + 1)) + ERRORS=$((ERRORS + 1)) + echo " ✗ $1" >&2 +} + +# --------------------------------------------------------------------------- +# 1. JSON validity +# --------------------------------------------------------------------------- +echo "=== JSON validity ===" +while IFS= read -r f; do + if jq empty "$f" 2>/dev/null; then + pass "$f" + else + fail "$f — invalid JSON" + fi +done < <(find "$TARGET" -name '*.json' -type f | sort) + +# --------------------------------------------------------------------------- +# 2. JSONC config snippets +# --------------------------------------------------------------------------- +echo "" +echo "=== JSONC snippet validity ===" +while IFS= read -r f; do + # Strip full-line // comments and trailing commas, then parse with node + # (CI runners have it; this is a syntax gate only, not a schema check). + if node -e ' + const s = require("fs").readFileSync(process.argv[1], "utf8") + .replace(/^\s*\/\/.*$/gm, "") + .replace(/,(\s*[}\]])/g, "$1"); + JSON.parse(s); + ' "$f" 2>/dev/null; then + pass "$f" + else + fail "$f — invalid JSONC" + fi +done < <(find "$TARGET" -name '*.jsonc' -type f | sort) + +# --------------------------------------------------------------------------- +# 3. Code plugin packages +# --------------------------------------------------------------------------- +echo "" +echo "=== Code plugin packages ===" +for plugin in inbox session; do + pj="$TARGET/$plugin/package.json" + if [[ ! -f "$pj" ]]; then + fail "$pj missing (behavioral plugins ship a package.json)" + continue + fi + name=$(jq -r '.name // empty' "$pj") + type_=$(jq -r '.type // empty' "$pj") + if [[ -z "$name" ]]; then + fail "$pj — missing name" + elif [[ "$type_" != "module" ]]; then + fail "$pj — type must be \"module\" (got: ${type_:-missing})" + else + pass "$pj — name=$name type=module" + fi + while IFS= read -r target; do + [[ -z "$target" ]] && continue + if [[ -f "$TARGET/$plugin/${target#./}" ]]; then + pass "$plugin export → $target" + else + fail "$plugin export target missing: $target" + fi + done < <(jq -r '.exports[]? // empty' "$pj") +done + +# --------------------------------------------------------------------------- +# 4. Skill frontmatter +# --------------------------------------------------------------------------- +echo "" +echo "=== Skill frontmatter ===" +while IFS= read -r f; do + fm=$(awk '/^---$/ { n++; next } n==1 { print } n>=2 { exit }' "$f") + if [[ -z "$fm" ]]; then + fail "$f — no frontmatter found" + continue + fi + ok=1 + for field in name description; do + if ! echo "$fm" | grep -q "^${field}:"; then + fail "$f — missing required field: $field" + ok=0 + fi + done + [[ $ok -eq 1 ]] && pass "$f" +done < <(find "$TARGET" -path '*/skills/*/SKILL.md' -type f | sort) + +# --------------------------------------------------------------------------- +# 5. Command bodies +# --------------------------------------------------------------------------- +echo "" +echo "=== Command bodies ===" +while IFS= read -r f; do + body=$(awk '/^---$/{n++; next} n>=2' "$f" | sed '/./,$!d') + if [[ -n "$body" ]]; then + pass "$f" + else + fail "$f — empty command body (the body is the prompt template)" + fi +done < <(find "$TARGET" -path '*/commands/*.md' -type f | sort) + +# --------------------------------------------------------------------------- +# 6. No Claude harness leakage +# --------------------------------------------------------------------------- +echo "" +echo "=== No Claude harness leakage ===" +if hits=$(grep -rn 'CLAUDE_PLUGIN_ROOT\|CLAUDE_SESSION_ID' "$TARGET" 2>/dev/null); then + while IFS= read -r line; do + fail "Claude var in OpenCode tree: $line" + done <<<"$hits" +else + pass "no \${CLAUDE_*} vars under $TARGET" +fi + +# --------------------------------------------------------------------------- +# 7. Vendored scripts executable +# --------------------------------------------------------------------------- +echo "" +echo "=== Vendored scripts executable ===" +while IFS= read -r f; do + if [[ -x "$f" ]]; then + pass "$f" + else + fail "$f — not executable" + fi +done < <(find "$TARGET" -path '*/scripts/*' -type f | sort) + +# --------------------------------------------------------------------------- +# Summary +# --------------------------------------------------------------------------- +echo "" +echo "=== Summary ===" +echo "$CHECKS checks, $ERRORS failures" +exit "$([[ "$ERRORS" -eq 0 ]] && echo 0 || echo 1)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b53081c..5d2a143 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,8 @@ jobs: run: sudo apt-get update && sudo apt-get install -y jq - name: Validate plugins run: bash .github/scripts/validate-plugins.sh + - name: Validate OpenCode plugins + run: bash .github/scripts/validate-opencode.sh - name: Check CI/validate-all parity run: bash .github/scripts/check-ci-parity.sh diff --git a/plugins-opencode/README.md b/plugins-opencode/README.md new file mode 100644 index 0000000..4c38231 --- /dev/null +++ b/plugins-opencode/README.md @@ -0,0 +1,48 @@ +# plugins-opencode + +OpenCode V2 ports of four agent-toolkit plugins. This tree is a **pure +addition**: nothing here changes Claude Code or Copilot behavior, and the +Claude/Copilot plugins are not loaded from here. + +The intent, same as the Claude versions: the agent keeps working without +bugging you, while recording blockers, decisions, and followups for review +later. Where OpenCode has a better native mechanism (TUI slots instead of +`Stop`-hook banners, `question` tool instead of prompt re-injection), the +OpenCode port uses it. + +## Plugins + +| Plugin | Shape | Install | +| --- | --- | --- | +| `format-on-save` | config snippet only (no code) | copy `formatter` block into your config | +| `git-tools` | skills + commands config snippet (no code) | copy `skills` + `commands` entries | +| `inbox` | server plugin + TUI plugin + shared CLI | `opencode plugin add` (see below) | +| `session` | server plugin + skills + commands | `opencode plugin add` (see below) | + +Shared scripts (`git-wait`, `branch`, `sitrep`, `inbox`) are vendored from +`../utils/` by `utils/sync.sh` — edit the canonical copy there and re-run +sync; CI fails on drift for this tree exactly like it does for +`plugins-claude/`. + +## Install + +Config snippets (`format-on-save`, `git-tools`): copy the `opencode.jsonc` +block from the plugin's README into your global `~/.config/opencode/opencode.jsonc` +or a project `opencode.jsonc`. + +Code plugins (`inbox`, `session`) install from this repo's subdirectory: + +```sh +opencode plugin add 'github:St0nefish/agent-toolkit#master::path:plugins-opencode/inbox' +opencode plugin add 'github:St0nefish/agent-toolkit#master::path:plugins-opencode/session' +``` + +Local paths work too (`plugins` array in `opencode.jsonc`, or a directory +under `.opencode/plugins/`), which is what you want while developing. + +## State sharing + +`inbox` keeps its state in `${INBOX_STATE_DIR:-${XDG_STATE_HOME:-~/.local/state}/claude-inbox}` +— the same directory the Claude plugin uses. Session IDs differ per harness, +so the two can share the directory with no collision, and the `utils/inbox` +CLI is the single source of truth for both. diff --git a/plugins-opencode/git-tools/scripts/branch b/plugins-opencode/git-tools/scripts/branch new file mode 100755 index 0000000..98f16e5 --- /dev/null +++ b/plugins-opencode/git-tools/scripts/branch @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# branch - Git branch operations for session workflows +# Exit codes: 0 success (including -h/--help), 1 bad usage or invalid name, 2 git error +# +# Subcommands: +# create Create and switch to a new branch + +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: branch [args] + +Subcommands: + create Create and switch to a new branch +EOF +} + +die() { echo "Error: $*" >&2; exit 2; } + +[[ $# -ge 1 ]] || { usage >&2; exit 1; } + +cmd="$1"; shift + +case "$cmd" in + create) + [[ $# -eq 1 ]] || { echo "Usage: branch create " >&2; exit 1; } + name="$1" + [[ "$name" != -* ]] || { echo "Error: branch name must not start with '-': $name" >&2; exit 1; } + git check-ref-format --branch "$name" >/dev/null 2>&1 || { echo "Error: invalid branch name: $name" >&2; exit 1; } + if git show-ref --verify --quiet "refs/heads/$name"; then + die "branch '$name' already exists" + fi + git switch -c "$name" || die "failed to create branch '$name'" + ;; + -h|--help) usage ;; + *) echo "Unknown subcommand: $cmd" >&2; usage >&2; exit 1 ;; +esac diff --git a/plugins-opencode/git-tools/scripts/git-wait b/plugins-opencode/git-tools/scripts/git-wait new file mode 100755 index 0000000..335f658 --- /dev/null +++ b/plugins-opencode/git-tools/scripts/git-wait @@ -0,0 +1,1460 @@ +#!/usr/bin/env bash +# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. +# +# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: +# listing, creating, commenting, merging, closing, viewing logs. This script +# exists only for the three things neither CLI gives you: +# +# 1. Platform detection — matching the git remote hostname against configured +# tea logins, so a caller knows whether to reach for `gh` or `tea`. +# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a +# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on +# the merge itself; `tea` has no equivalent at all). +# 3. `run watch` — block until CI finishes, aggregating per-job status and +# dumping failed job logs. `gh run watch` is GitHub-only and misses +# job-level failures masked by a run-level success; `tea` has no watcher. +# +# Usage: +# git-wait [-C DIR] ... +# Operate on the git repo at DIR instead of the current directory (like +# `git -C`). Must come before the command. gh/tea resolve the repo from the +# working directory, so this retargets every call without a caller-side cd. +# +# git-wait platform +# Echo "github" or "gitea" for the current repo's origin remote. +# +# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] +# [--alert-interval 300] +# Block until the PR for BRANCH reaches a terminal state. +# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, +# url, duration, and (when relevant) reason. +# +# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] +# [--timeout 14400] [--idle-timeout 0] [--interval 15] +# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] +# [--max-poll-failures 10] +# Block until CI finishes. Output: "status: pass|fail|closed|timeout| +# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed +# job logs go to stderr. +# +# --branch follows ONE run: the newest correlated to that branch (via the +# PR's check rollup when a PR exists, else the newest run in the list). +# That is right for a PR branch, where one push means one run. It is NOT +# sufficient on a default branch, where two merges landing close together +# produce two runs and the newest passing says nothing about the older +# one still executing. +# +# --sha watches EVERY run for one commit and is the correct flag for a +# post-merge/release watch: it stays pending while any run for the commit +# is pending, and fails if any run — or any job inside one — failed. Pass +# one or the other, not both. +# +# A running CI is never aborted for lack of visible progress: `run watch +# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress +# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO +# check is pending (running CI, or auto-merge armed, resets it), so a PR that +# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long +# jobs (VM boot + integration suite + teardown) can go quiet for a long time. +# While still waiting, a heartbeat alert goes to STDERR every --alert-interval +# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) +# pending: ...)". stdout key:value output is unchanged. +# +# --no-run-timeout is how long to wait for the FIRST run to appear before +# reporting no-workflow, counted from the end of --initial-delay. Default 600s +# for --sha (post-merge workflows queue late, or start only after another +# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty +# check. A stderr alert is printed each poll while waiting. A FAILED run-list +# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not +# counted toward this deadline and polling continues, but after +# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the +# watch gives up with "status: error" and exit 4. A successful poll resets the +# count. +# +# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the +# commit is terminal and passing, keep polling SECS more before reporting pass, +# so a chained workflow_run workflow that appears late is still watched. A +# stderr line is printed while settling; a new run restarts the watch. +# +# Exit codes: 0 terminal state reached (check "status:" for pass/fail), +# 1 usage error, 2 timeout, 3 platform detection failure or no +# PR/workflow found, 4 command failed + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +die() { echo "git-wait: $*" >&2; exit 1; } +die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } + +# Run a CLI command and pipe its stdout through a jq filter. +# If the command fails, die with its stderr instead of feeding junk to jq. +# Usage: cli_json [jq-flags...] [args...] +# +# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. +# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, +# auth warnings, progress text) into the JSON, silently corrupting jq +# parsing and producing wrong results downstream (e.g. run watch seeing +# unexpected status values). +cli_json() { + local jq_flags=() + while [[ "$1" =~ ^-[a-zA-Z] ]]; do + # Collect jq flags (e.g. -r, -e) — stop at the filter string + case "$1" in + -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; + *) break ;; + esac + done + local filter="$1"; shift + local raw stderr_file rc=0 + stderr_file=$(mktemp) + raw=$("$@" 2>"$stderr_file") || rc=$? + if [[ $rc -ne 0 ]]; then + local err + err=$(cat "$stderr_file") + rm -f "$stderr_file" + die "$err" + fi + rm -f "$stderr_file" + echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" +} + +# --------------------------------------------------------------------------- +# Target repo (-C DIR) +# +# Handled before platform detection. The cd happens inside this script's own +# process, so the caller's working directory is never touched. +# --------------------------------------------------------------------------- + +if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then + [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" + target_dir="$2" + [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" + git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die_usage "$1: not a git repository: $target_dir" + # Resolve the script path first: a relative $0 breaks once we cd (help reads it). + SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + cd "$target_dir" + shift 2 +fi +SELF="${SELF:-$0}" + +# --------------------------------------------------------------------------- +# Platform detection +# --------------------------------------------------------------------------- + +detect_platform() { + local remote_url hostname login_url login_host + remote_url=$(git remote get-url origin 2>/dev/null) \ + || die "no git remote 'origin' found — run from a git repository" + + # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) + # or HTTPS (https://host/org/repo or https://host:port/org/repo) + if [[ "$remote_url" =~ ^ssh:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') + elif [[ "$remote_url" =~ ^git@ ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') + elif [[ "$remote_url" =~ ^https?:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') + else + die "unrecognised remote URL format: $remote_url" + fi + + # Check if this hostname matches any configured tea login + if command -v tea >/dev/null 2>&1; then + while IFS= read -r login_url; do + login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') + if [[ "$login_host" == "$hostname" ]]; then + echo "gitea" + return + fi + done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) + fi + + # Not a known tea login — fall back to gh (GitHub) + if [[ "$hostname" == "github.com" ]]; then + echo "github" + return + fi + + die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" +} + +PLATFORM=$(detect_platform) + +case "$PLATFORM" in + github) CLI=gh ;; + gitea) CLI=tea ;; +esac + +command -v "$CLI" >/dev/null 2>&1 \ + || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } + +# --------------------------------------------------------------------------- +# Internal reads +# +# These are NOT public subcommands — they are the normalized queries the two +# waiters below need. Every one of them dies on backend failure, so callers +# invoke them inside $( ) with a fallback: a probe failure must degrade the +# poll loop, never abort it. +# --------------------------------------------------------------------------- + +# List PRs as normalized JSON. Flags: --state, --limit, --assignee. +_pr_list() { + local limit assignee state args + limit=30; assignee=""; state="open" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; + --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") + # gh uses 'merged' as a state but tea uses 'closed' for merged PRs + [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") + [[ -n "$assignee" ]] && args+=(--assignee "$assignee") + cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ + env GH_NO_COLOR=1 gh pr list "${args[@]}" + ;; + gitea) + args=(--output json --limit "$limit" + --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") + [[ "$state" == "merged" ]] && state="closed" + args+=(--state "$state") + cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ + env NO_COLOR=1 tea pr list "${args[@]}" + ;; + esac +} + +# Show one PR as normalized JSON. Takes or --branch NAME. +_pr_show() { + local num branch pr_json pr_stderr pr_rc pr_detail err + num=""; branch="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --*) die_usage "unknown flag: $1" ;; + *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; + esac + shift + done + [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass or --branch NAME, not both" + if [[ -n "$branch" ]]; then + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + num=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + [[ -n "$num" ]] || die "no PR found for branch '$branch'" + fi + [[ -n "$num" ]] || die_usage "usage: git-wait pr show | --branch NAME" + case "$PLATFORM" in + github) + cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ + env GH_NO_COLOR=1 gh pr view "$num" \ + --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" + ;; + gitea) + # `tea pr list` omits the `merged` boolean and `merged_at` timestamp + # entirely (tea only encodes merge state into the `state` string) and + # emits `mergeable` as a string, so a merged PR reports + # merged:false / mergedAt:null and consumers think it is still open + # (#140). Fetch the PR detail via the REST API instead, mirroring the + # run:show/run:list `tea api` pattern, so merge fields are reliable. + pr_stderr=$(mktemp); pr_rc=0 + pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ + || pr_rc=$? + if [[ $pr_rc -ne 0 ]]; then + err=$(cat "$pr_stderr"); rm -f "$pr_stderr" + die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" + fi + rm -f "$pr_stderr" + # Derive `state` from `merged` so it stays consistent with the merge + # flags (Gitea REST reports state:"closed" for a merged PR) and matches + # the GitHub path, which emits state:"merged". + echo "$pr_detail" | jq '{ + number: (.number // .index), + title: (.title // ""), + body: (.body // ""), + state: (if (.merged // false) then "merged" else (.state // "") end), + merged: (.merged // false), + merged_at: (.merged_at // null), + author: (.user.login // .user.username // ""), + head: (.head.ref // .head.label // ""), + base: (.base.ref // .base.label // ""), + labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), + assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), + mergeable: (.mergeable // null), + created_at: (.created_at // ""), + updated_at: (.updated_at // null), + url: (.html_url // .url // ""), + comments: [] + }' + ;; + esac +} + +# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. +_auto_merge_status() { + local branch number pr_json am + branch=""; number="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) shift; branch="$1" ;; + --number) shift; number="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + + # Resolve PR number from branch if needed + if [[ -z "$number" ]]; then + [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" + pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" + number=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + if [[ -z "$number" || "$number" == "null" ]]; then + echo "auto_merge: false" + echo "No open PR found for branch '$branch'" >&2 + exit 3 + fi + fi + + case "$PLATFORM" in + github) + am=$(cli_json -r '.autoMergeRequest != null' \ + env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) + echo "auto_merge: $am" + ;; + gitea) + echo "auto_merge: false" + echo "Gitea does not support auto-merge detection" >&2 + ;; + esac +} + +# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. +# +# --sha filters to runs for one commit. GitHub has a server-side filter for it +# (`gh run list --commit`); Gitea does not, so it is applied client-side over +# an unfiltered fetch, the same way --branch already is there. Both platforms +# emit head_sha in the normalized output — GitHub did not used to, which is +# why `run watch --sha` needs the headSha field added below. +_run_list() { + local limit status branch sha args query raw_stderr raw_rc raw err + limit=20; status=""; branch=""; sha="" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") + [[ -n "$status" ]] && args+=(--status "$status") + [[ -n "$branch" ]] && args+=(--branch "$branch") + [[ -n "$sha" ]] && args+=(--commit "$sha") + cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ + env GH_NO_COLOR=1 gh run list "${args[@]}" + ;; + gitea) + # Source from Gitea REST API directly. `tea actions runs list` + # filters server-side by a `branch` column that Gitea leaves empty + # on `pull_request` runs, so the watcher's --branch lookup misses + # correlated runs (#103). Fetch unfiltered via `tea api`, normalize + # `branch` from `head_branch`, and apply --branch client-side. + query="limit=$limit" + [[ -n "$status" ]] && query+="&status=$status" + raw_stderr=$(mktemp); raw_rc=0 + raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ + || raw_rc=$? + if [[ $raw_rc -ne 0 ]]; then + err=$(cat "$raw_stderr"); rm -f "$raw_stderr" + die "tea api repos/{owner}/{repo}/actions/runs failed: $err" + fi + rm -f "$raw_stderr" + echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' + [(.workflow_runs // []) | .[] | { + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + head_sha: (.head_sha // ""), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // "") + }] + | if $b == "" then . else [.[] | select(.branch == $b)] end + | if $s == "" then . else + [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] + end + ' + ;; + esac +} + +# Show one CI run as normalized JSON, including per-job status. +_run_show() { + local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err + [[ $# -ge 1 ]] || die_usage "usage: git-wait run show " + run_id="$1" + case "$PLATFORM" in + github) + cli_json \ + 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ + env GH_NO_COLOR=1 gh run view "$run_id" \ + --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" + ;; + gitea) + # Fetch the run object via the REST API. `tea actions runs view` + # ignores `--output json` (tea 0.14.1) and prints a human key/value + # table while still exiting 0, so jq downstream chokes (#133). Use the + # same `tea api` pattern as run:list and the jobs lookup below. + view_stderr=$(mktemp); view_rc=0 + view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ + || view_rc=$? + if [[ $view_rc -ne 0 ]]; then + err=$(cat "$view_stderr"); rm -f "$view_stderr" + die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" + fi + rm -f "$view_stderr" + + # Fetch per-job data via the actions API so callers (run watch) can + # detect job-level failures masked by run-level status=success on + # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. + jobs_array='[]' + jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) + if [[ -n "$jobs_json" ]]; then + jobs_array=$(echo "$jobs_json" | jq -c ' + def to_status: + if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) + end; + [(.jobs // .) | (if type == "array" then .[]? else empty end) | + {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] + ' 2>/dev/null) || jobs_array='[]' + fi + + # Older Gitea versions may not expose the jobs API; fall back to + # scanning the run logs for "Job '' failed" lines. + if [[ "$jobs_array" == '[]' ]]; then + failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ + | grep -oE "Job '[^']+' failed" \ + | sed -E "s/Job '(.+)' failed/\1/" \ + | sort -u || true) + if [[ -n "$failed_log" ]]; then + jobs_array=$(printf '%s\n' "$failed_log" \ + | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') + fi + fi + + # Normalize REST field names into the output contract, mirroring the + # run:list jq above (conclusion-first status, head_branch//branch, + # run_started_at//created, name//workflow_id). + echo "$view_json" | jq --argjson jobs "$jobs_array" '{ + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // ""), + jobs: $jobs + }' + ;; + esac +} + +# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; +# Gitea has no server-side filter and returns every job's log). +_run_logs() { + local run_id failed_only + [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs [--failed-only]" + run_id="$1"; shift + failed_only=false + while [[ $# -gt 0 ]]; do + case "$1" in + --failed-only) failed_only=true ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + if [[ "$failed_only" == "true" ]]; then + GH_NO_COLOR=1 gh run view "$run_id" --log-failed + else + GH_NO_COLOR=1 gh run view "$run_id" --log + fi + ;; + gitea) + # tea actions runs logs outputs all job logs; no built-in failed-only filter + NO_COLOR=1 tea actions runs logs "$run_id" + ;; + esac +} + +# --------------------------------------------------------------------------- +# Run helpers +# --------------------------------------------------------------------------- + +# Return comma-separated names of any jobs in whose status is +# "failure", or empty if none. Used by run watch to detect job-level failures +# even when the run-level status reports success — Gitea sets run.status to +# "success" on a multi-job workflow if at least one job ran successfully, +# masking failures in earlier jobs (see issue #87). Calls "run show" to +# normalize per-platform JSON, so it works for both gh and tea paths. +_run_failed_jobs() { + local run_id="$1" show_json + show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 + echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' +} + +# Progress-aware timeout decision shared by `pr wait` and `run watch`. +# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress +# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. +# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ +# minutes: this lets callers keep waiting while CI is actively progressing and +# give up only after a stretch of no progress, with a hard ceiling backstop. +_wait_timed_out() { + local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" + if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then + echo "ceiling"; return 0 + fi + if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then + echo "idle"; return 0 + fi + return 1 +} + +# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. +_fmt_dur() { + local s="$1" + if [[ "$s" -lt 60 ]]; then echo "${s}s" + elif [[ "$s" -lt 3600 ]]; then + if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi + else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi +} + +# Periodic stderr heartbeat while a wait is still running. Callers set +# alert_interval (0 disables) and next_alert (initialised to alert_interval), +# and call `_heartbeat "$elapsed" ""` once per poll. Emits at most one +# alert per poll, then re-arms for the next multiple of alert_interval, so a +# slow poll never produces a burst. stderr only: stdout stays parseable. +_heartbeat() { + local el="$1" detail="$2" + [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 + echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 + next_alert=$(( (el / alert_interval + 1) * alert_interval )) +} + +# Coarse CI status — pending|success|failure|none — for a PR/branch, used by +# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the +# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is +# guarded so a probe failure degrades to "none" and never aborts the wait loop. +_ci_status() { + local pr_number="$1" branch="$2" view_json run_status + case "$PLATFORM" in + github) + view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } + echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) else "pending" end + else (.state // "pending" | ascii_downcase) end + ] | + if length == 0 then "none" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" end' 2>/dev/null || echo "none" + ;; + gitea) + run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) echo "pending" ;; + failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; + ""|none|null) echo "none" ;; + *) echo "success" ;; + esac + ;; + *) echo "none" ;; + esac +} + +# --------------------------------------------------------------------------- +# Command routing +# --------------------------------------------------------------------------- + +cmd="${1:-}" +sub="${2:-}" +shift 2 || shift || true + +case "$cmd:$sub" in + + # Echo the detected platform so callers know which CLI to reach for. + # PLATFORM is already resolved above; detection failure exited long before + # we got here. + platform:) + echo "$PLATFORM" + ;; + + pr:wait) + # timeout is the hard ceiling; idle_timeout is the no-progress window. + branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" ]] || die_usage "pr wait requires --branch" + + # Find PR for this branch + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + # Match branch — handle Gitea owner:branch format with endswith + pr=$(echo "$pr_json" | jq --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') + + if [[ -z "$pr" || "$pr" == "null" ]]; then + echo "status: no-pr" + echo "duration: 0s" + echo "No PR found for branch '$branch'" >&2 + exit 3 + fi + + pr_number=$(echo "$pr" | jq -r '.number') + pr_url=$(echo "$pr" | jq -r '.url // ""') + elapsed=0 + idle=0; idle_mark=0 + last_signal="" + unknown_streak=0 + + # Poll loop + while true; do + show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" + pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') + pr_merged=$(echo "$show_json" | jq -r '.merged // false') + pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') + + # Progress signals: CI still running or auto-merge pending means the PR is + # actively advancing toward merge, so the idle clock must not count down. + checks=$(_ci_status "$pr_number" "$branch") + if [[ "$PLATFORM" == "github" ]]; then + auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" + [[ "$auto_merge" == "true" ]] || auto_merge="false" + else + auto_merge="false" + fi + signal="$pr_state|$pr_mergeable|$checks|$auto_merge" + if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then + idle=0 + fi + last_signal="$signal" + + echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 + [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true + + case "$pr_state" in + merged) + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + closed) + if [[ "$pr_merged" == "true" ]]; then + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + fi + echo "status: closed" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR was closed without merging" >&2 + exit 0 + ;; + open) + # Check for merge conflicts + if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then + echo "status: blocked" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR has merge conflicts" >&2 + exit 0 + fi + # Still open — keep polling + ;; + *) + unknown_streak=$(( unknown_streak + 1 )) + if [[ "$unknown_streak" -ge 3 ]]; then + echo "status: error" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 + exit 4 + fi + echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 + ;; + esac + + # Reset unknown streak on any recognized state + [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 + + # Check timeout — only give up after a stretch of no progress (idle) or + # the absolute ceiling, never while CI/auto-merge is still working. + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + run:watch) + # timeout is the hard ceiling; idle_timeout is the no-progress backstop. + # While CI is actively pending the idle clock is reset each poll, so a long + # (15+ min) suite runs to completion up to the ceiling rather than being cut + # off by a flat wall-clock timeout. + branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 + alert_interval=300; next_alert=300; no_run_timeout="" + settle=0; settle_given=0; no_run_skew=0 + max_poll_failures=10; poll_fails=0 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; + --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; + --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" + [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" + [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" + # How long to wait for the FIRST run to appear (counted from the end of + # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ + # workflow_run and can queue minutes late, so that scope gets longer. + if [[ -z "$no_run_timeout" ]]; then + if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi + fi + + # `gh run list --commit` matches only on a FULL 40-character SHA -- a short + # one returns zero rows with no error, which this watcher would report as + # "no-workflow" rather than as the caller's mistake. Expand a short SHA via + # git when the commit is local, and refuse it outright when it is not, + # rather than silently watching nothing. (Gitea matches client-side on the + # first 12 chars, so a full SHA is correct there too.) + if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" + if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha="$_full_sha" + else + die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" + fi + fi + + elapsed=0 + idle=0; idle_mark=0 + + # A failed run-list call (network, auth, rate limit) is NOT an empty list. + # Note it, keep polling, and exclude the time from the no-workflow deadline + # (accumulated in no_run_skew). The hard ceiling still applies. After + # --max-poll-failures consecutive failures it gives up (exit 4). + _poll_failed() { + local what="$1" before="$elapsed" + poll_fails=$(( poll_fails + 1 )) + echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 + if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then + echo "status: error" + echo "duration: ${elapsed}s" + echo "reason: run list failed ${poll_fails} consecutive times" + echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 + exit 4 + fi + elapsed=$(( SECONDS - _t0 )) + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 + exit 2 + fi + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + no_run_skew=$(( no_run_skew + elapsed - before )) + } + + # Enforce the hard --timeout ceiling on paths that otherwise `continue` + # (no runs yet, settling, no checks registered) so they cannot outlive it. + _ceiling_check() { + local what="$1" + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what}" >&2 + exit 2 + fi + } + + # ------------------------------------------------------------------ + # --sha: watch EVERY run for one commit, not just the newest. + # + # `--branch` deliberately follows a single run (the newest correlated + # one). That is right for a PR branch, where one push means one run, but + # wrong for a default branch: two merges landing close together produce + # two runs, and the newest going green says nothing about the older one + # still executing. Watching a post-merge release run by branch reported + # "pass" while a second run was mid-flight. + # + # A commit is the honest scope for that question — the caller wants the + # runs *their* merge caused, not whatever else is landing on the branch. + # So this path aggregates: it stays non-terminal while ANY run for the + # commit is non-terminal, and fails if ANY run (or any job within one) + # failed. + # + # The CRITICAL DESIGN RULE below applies here too: only explicitly + # non-terminal statuses keep polling; anything unrecognized counts as + # terminal so an unexpected status cannot loop until timeout. + # ------------------------------------------------------------------ + if [[ -n "$sha" ]]; then + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + echo "Watching all runs for commit ${sha:0:12}..." >&2 + + # Settle window: after every run is terminal and passing, keep polling + # --settle seconds for a chained (workflow_run) run before reporting pass. + settle_start=-1; settle_ids="" + + while true; do + if ! sha_json=$(_run_list --sha "$sha" --limit 50); then + _poll_failed "commit ${sha:0:12}" + continue + fi + poll_fails=0 + sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) + + if [[ "$sha_count" -eq 0 ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + # Non-terminal set is explicit; everything else is terminal. + pending=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested")] + | length') + + echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 + + if [[ "$pending" -gt 0 ]]; then + pending_names=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested") + | (.workflow // .id)] | join(", ")') + _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" + # Active CI is progress — reset the idle clock, same as --branch. + idle=0 + settle_start=-1 + else + # Every run terminal. Collect run-level and job-level failures + # across ALL of them before declaring pass (#87 applies per run). + all_failed="" + fail_url="" + while IFS=$'\t' read -r r_id r_status r_url; do + [[ -n "$r_id" ]] || continue + case "$r_status" in + failure|timed_out|cancelled|canceled|skipped) + all_failed+="${all_failed:+,}run-$r_id:$r_status" + [[ -n "$fail_url" ]] || fail_url="$r_url" + ;; + *) + r_failed=$(_run_failed_jobs "$r_id") + if [[ -n "$r_failed" ]]; then + all_failed+="${all_failed:+,}$r_failed" + [[ -n "$fail_url" ]] || fail_url="$r_url" + fi + ;; + esac + done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') + + if [[ -n "$all_failed" ]]; then + echo "status: fail" + [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $all_failed" + echo "--- Failed job logs (last 80 lines) ---" >&2 + echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do + _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true + done + exit 0 + fi + + if [[ "$settle" -gt 0 ]]; then + cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') + if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then + echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 + settle_start=-1 + fi + if [[ "$settle_start" -lt 0 ]]; then + settle_start=$elapsed; settle_ids="$cur_ids" + fi + if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then + echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + fi + + echo "status: pass" + first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') + [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" + echo "duration: ${elapsed}s" + echo "runs: $sha_count" >&2 + exit 0 + fi + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so + # `run list --branch` correlates nothing and the watcher times out into + # no-workflow even when CI ran (#140). Resolve the branch head SHA up front + # (only on Gitea) and fall back to head_sha correlation when the + # branch-filtered lookup is empty. The run object's head_sha equals the + # branch head on Gitea (confirmed in #140); if a variant ever records a + # merge-ref SHA the fallback simply misses and degrades to today's + # behaviour rather than returning a wrong run. + _watch_branch_sha="" + if [[ "$PLATFORM" == "gitea" ]]; then + _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ + || git rev-parse "origin/$branch" 2>/dev/null || true) + fi + + # Echo a run-list JSON array for $branch: branch-name correlation first, + # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the + # server-side --branch filter populates the first call and _watch_branch_sha + # stays empty, so the SHA path is never taken. + _runs_for_branch() { + local lim="${1:-1}" out + # A failed call returns 1 (distinct from a successful empty "[]"). + out=$(_run_list --branch "$branch" --limit "$lim") || return 1 + if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then + echo "$out"; return 0 + fi + if [[ -n "$_watch_branch_sha" ]]; then + _run_list --limit 50 | jq \ + --arg s "$_watch_branch_sha" --argjson n "$lim" \ + '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ + || return 1 + return 0 + fi + echo "[]" + } + + # On GitHub, prefer PR-based status checking — one API call gives us both + # merge state and all CI check results via statusCheckRollup, avoiding the + # flaky run-level polling that produces "unknown" statuses. + pr_number="" + pr_url="" + use_pr=false + if [[ "$PLATFORM" == "github" ]]; then + pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { + pr_number=$(echo "$pr_json" | jq -r '.number // empty') + pr_url=$(echo "$pr_json" | jq -r '.url // ""') + [[ -n "$pr_number" ]] && use_pr=true + } + fi + + # Pre-check: look for an already-terminal state before sleeping the + # initial delay. If the PR already merged or CI already finished, + # report immediately instead of waiting. + _precheck_done=false + if [[ "$use_pr" == "true" ]]; then + _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" + _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') + + if [[ "$_pre_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already merged" >&2 + exit 0 + fi + if [[ "$_pre_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already closed without merging" >&2 + exit 0 + fi + + _pre_checks=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + if [[ "$_pre_checks" == "success" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "CI already passed on PR #$pr_number" >&2 + exit 0 + fi + + if [[ "$_pre_checks" == "failure" ]]; then + _pre_failed=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "failed_jobs: $_pre_failed" + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + fi + else + # Fallback path: check if a completed run already exists + _pre_list=$(_runs_for_branch 1) || _pre_list="[]" + _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') + if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then + _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') + _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') + _pre_id=$(echo "$_pre_latest" | jq -r '.id') + case "$_pre_status" in + success|completed) + # Run-level status can read "success" on Gitea even when a + # job inside the run failed (issue #87). Aggregate per-job + # status before declaring pass. + failed_jobs=$(_run_failed_jobs "$_pre_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "CI already passed for branch '$branch'" >&2 + exit 0 + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$_pre_id") + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$_pre_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a + # reason so consumers (ship/session-end) gating on + # status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "reason: $_pre_status" + echo "CI run $_pre_status for branch '$branch'" >&2 + exit 0 + ;; + esac + fi + fi + + # Initial delay — CI run may not exist immediately after push + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + if [[ "$use_pr" == "true" ]]; then + echo "Watching PR #$pr_number for branch '$branch'..." >&2 + + while true; do + # A failed gh call is not "unknown" -- count it, cap consecutive failures. + if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then + _poll_failed "PR #$pr_number" + continue + fi + poll_fails=0 + pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') + + # PR merged — all done + if [[ "$pr_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number merged" >&2 + exit 0 + fi + + # PR closed without merge + if [[ "$pr_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number closed without merging" >&2 + exit 0 + fi + + # Summarize CI check statuses from statusCheckRollup + # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state + checks_summary=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 + + case "$checks_summary" in + success) + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + failure) + failed_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_names" + # Try to fetch failed logs from the latest run + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + pending) + # Still running — keep polling. Active CI is progress, so reset idle. + check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') + if [[ "$check_count" -eq 0 ]]; then + # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + else + # Active CI is progress, so reset idle. + idle=0 + fi + pending_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select(if .__typename == "CheckRun" then (.conclusion // "") == "" + else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) + | .name // .context // "unknown"] | unique | join(", ")') + _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" + ;; + esac + + # Check timeout — idle window or absolute ceiling (see _wait_timed_out). + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Fallback: no PR found — poll run list directly (skip flaky run show). + # + # CRITICAL DESIGN RULE — default-terminal polling: + # + # This loop has caused repeated regressions (#53, #57, #58, #60). + # The recurring bug pattern is: + # 1. The API returns an unexpected status value (e.g. "completed" + # with null conclusion, or a new status GitHub adds later). + # 2. The case statement doesn't recognise it. + # 3. A catch-all `*) keep polling` silently loops until timeout. + # + # The fix (applied here) inverts the logic: + # - ONLY explicitly non-terminal states keep polling. + # - The `*` catch-all EXITS (as pass). + # + # DO NOT add a `*) keep polling` catch-all to this case statement. + # If a new non-terminal status appears, add it to the explicit list. + # If you're unsure whether a status is terminal, it's safer to exit + # early (the caller can retry) than to loop for 5 minutes. + # + run_url="" + while true; do + if ! list_json=$(_runs_for_branch 1); then + _poll_failed "branch '$branch'" + continue + fi + poll_fails=0 + latest=$(echo "$list_json" | jq -r '.[0] // empty') + + if [[ -z "$latest" || "$latest" == "null" ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + # Distinguish "no workflow registered at all" from "runs exist + # but none correlate to this branch" so callers (#103) can tell + # a real CI absence from a branch-correlation gap. + any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" + if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then + echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + else + echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + fi + exit 3 + fi + echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "branch '$branch'" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + run_id=$(echo "$latest" | jq -r '.id') + run_status=$(echo "$latest" | jq -r '.status // "unknown"') + run_url=$(echo "$latest" | jq -r '.url // ""') + + echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 + + # See "CRITICAL DESIGN RULE" above — non-terminal states are listed + # explicitly; everything else exits. Do NOT add a `*) keep polling`. + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) + # Non-terminal — keep polling. Active CI is progress, so reset idle. + idle=0 + _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$run_id") + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a reason + # so consumers gating on status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $run_status" + echo "CI run $run_status on branch '$branch'" >&2 + exit 0 + ;; + *) + # Terminal — covers success and any future/unexpected status. + # Even when the run-level status reports success, an individual + # job may have failed (Gitea reports run.status=success on a + # multi-job run if any job succeeded; see #87). Aggregate + # per-job status before declaring pass. + failed_jobs=$(_run_failed_jobs "$run_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + esac + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + --help:|-h:|:) + sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' + exit 0 + ;; + + *) + die_usage "unknown command: $cmd${sub:+ $sub}" + ;; +esac diff --git a/plugins-opencode/git-tools/scripts/sitrep b/plugins-opencode/git-tools/scripts/sitrep new file mode 100755 index 0000000..558f9e3 --- /dev/null +++ b/plugins-opencode/git-tools/scripts/sitrep @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# sitrep - Situation report for a git repository +# Always shows working-tree state (staged/unstaged/untracked) together with +# committed context, and falls back to broader repo activity only when +# nothing else is actionable. +# +# Sections: +# 1. Working tree (staged/unstaged/untracked) +# 2. Unpushed commits (ahead of remote tracking branch) +# 3. Branch work (commits on feature branch vs base) +# 4. Repo activity (active branches, open issues) - only when 1-3 are empty +# +# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). +# +# Exit codes: 0 success (including -h/--help), 1 bad usage + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" + +usage() { + cat <<'EOF' +Usage: sitrep [directory] + +Situation report for a git repository. Shows working-tree changes plus +unpushed and branch commits, expanding to broader repo activity only +when everything is clean. + +If directory is omitted, uses the current working directory. +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +if [[ $# -gt 1 ]]; then + usage >&2 + exit 1 +fi + +dir="${1:-.}" +cd "$dir" + +gitq() { + git -c core.quotepath=false "$@" +} + +# Print a diff section, truncated to MAX_DIFF_LINES. +emit_diff() { + local title="$1" text="$2" total + [[ -n "$text" ]] || return 0 + total="$(printf '%s\n' "$text" | wc -l)" + echo "" + echo "=== $title ===" + if ((total > MAX_DIFF_LINES)); then + printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" + echo "[truncated $((total - MAX_DIFF_LINES)) lines]" + else + printf '%s\n' "$text" + fi +} + +# --- Not a git repo --- +if ! gitq rev-parse --git-dir >/dev/null 2>&1; then + echo "=== REPO ===" + echo "is_git_repo: false" + exit 0 +fi + +# --- Basic repo info (always shown) --- +head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" +head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" + +echo "=== REPO ===" +if [[ -n "$head_branch" ]]; then + echo "branch: $head_branch" +else + echo "detached_at: $head_sha" +fi + +# Detect base branch: origin/HEAD, then origin/main|master, then local main|master +base_ref="" +origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" +for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do + [[ -n "$candidate" ]] || continue + if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then + base_ref="$candidate" + break + fi +done + +on_base=false +if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then + on_base=true +fi + +has_merge_base=false +if [[ -n "$base_ref" ]]; then + echo "base: $base_ref" + if ! $on_base; then + if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then + has_merge_base=true + else + echo "note: no merge base between $base_ref and HEAD (unrelated histories)" + fi + ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" + behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" + echo "ahead: $ahead" + echo "behind: $behind" + fi +fi + +found_activity=false + +# --- Working tree: staged / unstaged / untracked --- +staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" +unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" +untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" + +if [[ -n "$staged_files" ]]; then + found_activity=true + echo "" + echo "=== STAGED ===" + echo "$staged_files" + emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$unstaged_files" ]]; then + found_activity=true + echo "" + echo "=== UNSTAGED ===" + echo "$unstaged_files" + emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$untracked_files" ]]; then + found_activity=true + echo "" + echo "=== UNTRACKED ===" + echo "$untracked_files" +fi + +# --- Unpushed commits --- +tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" +unpushed="" + +if [[ -n "$tracking_branch" ]]; then + unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" +fi + +if [[ -n "$unpushed" ]]; then + found_activity=true + echo "" + echo "=== UNPUSHED ===" + echo "tracking: $tracking_branch" + echo "$unpushed" +fi + +# --- Branch work (feature branch vs base) --- +if ! $on_base && [[ -n "$base_ref" ]]; then + branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" + if [[ -n "$branch_commits" ]]; then + found_activity=true + echo "" + echo "=== BRANCH COMMITS ===" + echo "$branch_commits" + fi + + if $has_merge_base; then + committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + if [[ -n "$committed_files" ]]; then + found_activity=true + echo "" + echo "=== CHANGED FILES ===" + echo "$committed_files" + emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + fi + fi +fi + +if $found_activity; then + exit 0 +fi + +# --- Repo activity (everything clean, nothing ahead) --- +active_branches="" +if [[ -n "$base_ref" ]]; then + active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" +fi + +if [[ -n "$active_branches" ]]; then + echo "" + echo "=== ACTIVE BRANCHES ===" + echo "$active_branches" +fi + +# Open issues (requires git-wait for platform detection, plus gh or tea) +if [[ -x "$SCRIPT_DIR/git-wait" ]]; then + platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" + issues="" + issues_err="" + errfile="$(mktemp)" + case "$platform" in + github) + if command -v gh >/dev/null 2>&1; then + issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" + fi + ;; + gitea) + if command -v tea >/dev/null 2>&1; then + issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" + fi + ;; + esac + if [[ -n "$issues_err" ]]; then + detail="$(head -n 1 "$errfile" 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + echo "note: $issues_err${detail:+: $detail}" + elif [[ -n "$issues" && "$issues" != "[]" ]]; then + formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + if [[ -n "$formatted" ]]; then + echo "$formatted" + else + echo "note: could not parse issue list" + fi + fi + rm -f "$errfile" +fi + +# Recent commits on default branch for context +echo "" +echo "=== RECENT COMMITS ===" +gitq log --oneline -10 2>/dev/null || true + +# Nothing at all +if [[ -z "$active_branches" ]]; then + echo "" + echo "=== STATUS ===" + echo "clean: true" +fi diff --git a/plugins-opencode/inbox/package.json b/plugins-opencode/inbox/package.json new file mode 100644 index 0000000..18268a5 --- /dev/null +++ b/plugins-opencode/inbox/package.json @@ -0,0 +1,19 @@ +{ + "name": "opencode-agent-toolkit-inbox", + "version": "0.1.0", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./tui": "./src/tui.tsx", + "./rpc": "./src/rpc.ts" + }, + "files": ["src"], + "dependencies": { + "@opencode/plugin": "latest" + }, + "peerDependencies": { + "@opentui/core": ">=0.6.6", + "@opentui/solid": ">=0.6.6", + "solid-js": ">=1.9.0" + } +} diff --git a/plugins-opencode/inbox/scripts/inbox b/plugins-opencode/inbox/scripts/inbox new file mode 100755 index 0000000..5069ed2 --- /dev/null +++ b/plugins-opencode/inbox/scripts/inbox @@ -0,0 +1,465 @@ +#!/usr/bin/env bash +# inbox — track a session's parked items for the user in a state file so +# hooks/statusline can show a deterministic "input needed" flag. +# +# Three item kinds: +# question blocks on the user; drives the "input needed" flag (Q) +# decision the agent already acted on a default; the user reviews it later; +# never drives the flag (D) +# followup work to consider before wrapping up (noticed, deferred, undone); +# quiet like decisions, never drives the flag (F) +# +# State: ${INBOX_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/claude-inbox}/.json +set -euo pipefail + +usage() { + cat <<'USAGE' +Usage: inbox [--session ID] [args] + +Session id comes from --session or $INBOX_SESSION (one is required, +except for 'prune' and help). + +Items are referenced as Q (question), D (decision) or F (followup). + +Commands: + add question --title T [--context C] [--option O]... [--recommend R] [--new] + Park a question that blocks on the user. Refused (exit 3) if a similar + open question exists unless --new is given. + add decision --title T [--context C] [--option O]... [--chosen X] [--new] + Record a decision already made on a default; --chosen is what was + picked, --option the alternatives considered. Refused (exit 3) if a + similar open decision exists unless --new is given. + add followup --title T [--context C] [--new] + Log work to consider before wrapping up (noticed but deferred, docs or + tests not done, an issue to file). Quiet: never drives the input flag. + Refused (exit 3) if a similar open followup exists unless --new. + update |D|F> [--title T] [--context C] [--option O]... + [--recommend R (question)] [--chosen X (decision)] + Replace provided fields (any --option replaces the options list). + answer Q [--note N] + Remove a question. --note is reserved and currently ignored. + resolve D [--note N] + Remove a decision. --note is reserved and currently ignored. + done F [--note N] + Remove a followup. --note is reserved and currently ignored. + list [--kind question|decision|followup] [--format line|text|md] [--full] [--json] + One line per open item (questions first). --format text|md renders + cards: the question, then the pick (decisions) or the options and + recommendation (questions); alternatives on one line, context hidden + for decisions and clipped for questions; followups are a checklist. + --full shows everything + uncut (one line per alternative, full context) and implies + --format text unless one is given. md adds markdown for the terminal. + --json prints the array for --kind, or + {"questions":[...],"decisions":[...],"followups":[...]} without it. + count [--kind question|decision|followup] + Print the number of open items (total of all kinds without --kind). + prune [--days N] + Delete state/lock files older than N days (default 7). + help Show this text. + +Writing convention (a hint is printed to stderr when it is broken): + --title is the question, ending in '?'; --chosen/--recommend is a short + answer phrase (<=100 chars); each --option is a short phrase (<=100 chars); + put reasons in --context. + +State dir: $INBOX_STATE_DIR, else ${XDG_STATE_HOME:-~/.local/state}/claude-inbox +USAGE +} + +STATE_DIR="${INBOX_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/claude-inbox}" +SESSION="${INBOX_SESSION:-}" + +die() { + echo "inbox: $1" >&2 + exit "${2:-1}" +} + +if [[ "${1:-}" == "--session" ]]; then + [[ $# -ge 2 ]] || die "--session requires a value" 2 + SESSION="$2" + shift 2 +fi + +cmd="${1:-}" +[[ $# -gt 0 ]] && shift + +case "$cmd" in + -h | --help | help) + usage + exit 0 + ;; + "") + usage >&2 + exit 2 + ;; + add | update | answer | resolve | done | list | count | prune) ;; + *) + usage >&2 + exit 2 + ;; +esac + +if [[ "$cmd" != "prune" ]]; then + [[ -n "$SESSION" ]] || die "no session: pass --session ID or set INBOX_SESSION" 2 + [[ "$SESSION" =~ ^[A-Za-z0-9._-]+$ ]] || die "invalid session id: $SESSION" 2 + [[ "$SESSION" != "." && "$SESSION" != ".." ]] || die "invalid session id: $SESSION" 2 + STATE_FILE="$STATE_DIR/$SESSION.json" + LOCK_FILE="$STATE_DIR/$SESSION.lock" +fi + +# Take the per-session lock (held until the process exits). +lock() { + mkdir -p "$STATE_DIR" + exec 9>"$LOCK_FILE" + flock 9 +} + +# Fill in any keys an older (questions-only) state file lacks. +NORMALIZE='. + { + next_id: (.next_id // 1), + questions: (.questions // []), + next_decision_id: (.next_decision_id // 1), + decisions: (.decisions // []), + next_followup_id: (.next_followup_id // 1), + followups: (.followups // []) +}' + +read_state() { + if [[ -f "$STATE_FILE" ]]; then + jq "$NORMALIZE" "$STATE_FILE" + else + echo '{}' | jq "$NORMALIZE" + fi +} + +# write_state : atomic tmp+mv in the same dir. +write_state() { + local tmp + tmp=$(mktemp "$STATE_DIR/.$SESSION.XXXXXX") + printf '%s\n' "$1" >"$tmp" + mv -f "$tmp" "$STATE_FILE" +} + +# kind_keys : sets ARR (items array key) and CTR (counter key) and PFX. +kind_keys() { + case "$1" in + question) ARR=questions CTR=next_id PFX=Q ;; + decision) ARR=decisions CTR=next_decision_id PFX=D ;; + followup) ARR=followups CTR=next_followup_id PFX=F ;; + *) usage >&2; exit 2 ;; + esac +} + +# parse_ref : sets REF_KIND (question|decision|followup) and REF_ID (number). +parse_ref() { + local ref="${1:-}" + if [[ ! "$ref" =~ ^[QqDdFf][0-9]+$ ]]; then + die "expected item id like Q1, D1 or F1, got '$ref'" 2 + fi + case "${ref:0:1}" in + Q | q) REF_KIND=question ;; + F | f) REF_KIND=followup ;; + *) REF_KIND=decision ;; + esac + REF_ID=$((10#${ref:1})) +} + +# Normalize + tokenize jq defs, shared by dedupe. +# shellcheck disable=SC2016 # jq program, not shell +JQ_TOK=' +def stop: ["a","an","the","of","to","for","is","should","we","i","it","in","on","and","or","be","do","does","which","what","how"]; +def toks: ascii_downcase | gsub("[^a-z0-9]+"; " ") | split(" ") + | map(select(length > 0 and (. as $w | stop | index($w) | not))) | unique; +' + +# lint_item <answer> [option...]: advisory hints on stderr (never fatal) +# for the writing convention; empty title/answer are skipped and followups +# (imperative notes) are not required to be questions. +lint_item() { + local kind="$1" t="$2" e="$3" o + shift 3 + [[ "$kind" == followup || -z "$t" || "$t" == *"?"* ]] || echo "inbox: hint: write --title as a question ending in '?'" >&2 + [[ ${#e} -le 100 ]] || echo "inbox: hint: --chosen/--recommend is ${#e} chars; keep it a short answer phrase (<=100) and put reasons in --context" >&2 + for o in "$@"; do + [[ ${#o} -le 100 ]] || { + echo "inbox: hint: an --option is over 100 chars; shorten it" >&2 + break + } + done +} + +cmd_add() { + local kind="${1:-}" + case "$kind" in + question | decision | followup) shift ;; + *) die "add: expected 'question', 'decision' or 'followup', got '$kind'" 2 ;; + esac + kind_keys "$kind" + local title="" context="" extra="" force=0 + local -a opts=() + while [[ $# -gt 0 ]]; do + case "$1" in + --title) title="${2:?--title needs a value}"; shift 2 ;; + --context) context="${2:?--context needs a value}"; shift 2 ;; + --option) + [[ "$kind" != followup ]] || die "add followup: takes --title and --context only" 2 + opts+=("${2:?--option needs a value}"); shift 2 ;; + --recommend) + [[ "$kind" == question ]] || die "add $kind: --recommend is only for questions" 2 + extra="${2:?--recommend needs a value}"; shift 2 ;; + --chosen) + [[ "$kind" == decision ]] || die "add $kind: --chosen is only for decisions" 2 + extra="${2:?--chosen needs a value}"; shift 2 ;; + --new) force=1; shift ;; + *) die "add $kind: unknown argument: $1" 2 ;; + esac + done + [[ -n "$title" ]] || die "add $kind: --title is required" 2 + lock + local state + state=$(read_state) + if [[ $force -eq 0 ]]; then + local hit + hit=$(jq -r --arg t "$title" --arg k "$ARR" "$JQ_TOK"' + ($t | toks) as $nt + | [ .[$k][] + | (.title | toks) as $ot + | (($nt - ($nt - $ot)) | length) as $inter + | (($nt + $ot) | unique | length) as $uni + | {id, title, sim: (if $uni == 0 then 0 else ($inter / $uni) end)} ] + | map(select(.sim >= 0.6)) | sort_by(-.sim) | first // empty + | "\(.id)\t\(.title)"' <<<"$state") + if [[ -n "$hit" ]]; then + printf "similar to %s%s: %s — use 'update %s%s' or pass --new\n" \ + "$PFX" "${hit%%$'\t'*}" "${hit#*$'\t'}" "$PFX" "${hit%%$'\t'*}" >&2 + exit 3 + fi + fi + lint_item "$kind" "$title" "$extra" "${opts[@]+"${opts[@]}"}" + local opts_json id new + opts_json=$(if [[ ${#opts[@]} -gt 0 ]]; then printf '%s\0' "${opts[@]}" | jq -Rsc 'split("\u0000")[:-1]'; else echo '[]'; fi) + id=$(jq -r --arg c "$CTR" '.[$c]' <<<"$state") + new=$(jq --arg k "$ARR" --arg c "$CTR" --arg kind "$kind" \ + --arg t "$title" --arg x "$context" --arg e "$extra" \ + --argjson o "$opts_json" --argjson now "$(date +%s)" ' + (if $kind == "question" then {options: $o, recommendation: $e} + elif $kind == "decision" then {options: $o, chosen: $e} + else {} end) as $extra + | .[$k] += [{id: .[$c], title: $t, context: $x} + $extra + {added: $now}] + | .[$c] += 1' <<<"$state") + write_state "$new" + echo "$PFX$id added" +} + +cmd_update() { + parse_ref "${1:-}" + shift + local kind="$REF_KIND" id="$REF_ID" + kind_keys "$kind" + local title="" context="" extra="" have_t=0 have_c=0 have_e=0 + local -a opts=() + while [[ $# -gt 0 ]]; do + case "$1" in + --title) title="${2:?--title needs a value}"; have_t=1; shift 2 ;; + --context) context="${2:?--context needs a value}"; have_c=1; shift 2 ;; + --option) + [[ "$kind" != followup ]] || die "update $PFX$id: followups take --title and --context only" 1 + opts+=("${2:?--option needs a value}"); shift 2 ;; + --recommend) + [[ "$kind" == question ]] || die "update $PFX$id: --recommend applies to questions only (use --chosen)" 1 + extra="${2:?--recommend needs a value}"; have_e=1; shift 2 ;; + --chosen) + [[ "$kind" == decision ]] || die "update $PFX$id: --chosen applies to decisions only (use --recommend)" 1 + extra="${2:?--chosen needs a value}"; have_e=1; shift 2 ;; + *) die "update: unknown argument: $1" 2 ;; + esac + done + lint_item "$kind" "$title" "$extra" "${opts[@]+"${opts[@]}"}" + lock + local state + state=$(read_state) + jq -e --arg k "$ARR" --argjson id "$id" 'any(.[$k][]; .id == $id)' <<<"$state" >/dev/null || die "no such $kind: $PFX$id" 1 + local opts_json='null' + if [[ ${#opts[@]} -gt 0 ]]; then + opts_json=$(printf '%s\0' "${opts[@]}" | jq -Rsc 'split("\u0000")[:-1]') + fi + local new + new=$(jq --arg k "$ARR" --arg kind "$kind" --argjson id "$id" \ + --arg t "$title" --arg c "$context" --arg e "$extra" \ + --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" ' + (if $kind == "question" then "recommendation" else "chosen" end) as $ek + | .[$k] |= map(if .id == $id then + (if $ht == 1 then .title = $t else . end) + | (if $hc == 1 then .context = $c else . end) + | (if $he == 1 then .[$ek] = $e else . end) + | (if $o != null then .options = $o else . end) + else . end)' <<<"$state") + write_state "$new" + echo "$PFX$id updated" +} + +# remove_item <verb-past> <expected-kind> <wrong-kind-hint> <args...> +remove_item() { + local past="$1" want="$2" verb="$3" + shift 3 + parse_ref "${1:-}" + shift + local kind="$REF_KIND" id="$REF_ID" + kind_keys "$kind" + if [[ "$kind" != "$want" ]]; then + local other + case "$kind" in + question) other="answer Q$id" ;; + decision) other="resolve D$id" ;; + followup) other="done F$id" ;; + esac + die "$PFX$id is a $kind; use '$other'" 1 + fi + while [[ $# -gt 0 ]]; do + case "$1" in + --note) [[ $# -ge 2 ]] || die "$verb: --note needs a value" 2; shift 2 ;; # reserved; ignored + *) die "$verb: unknown argument: $1" 2 ;; + esac + done + lock + local state + state=$(read_state) + jq -e --arg k "$ARR" --argjson id "$id" 'any(.[$k][]; .id == $id)' <<<"$state" >/dev/null || die "no such $kind: $PFX$id" 1 + write_state "$(jq --arg k "$ARR" --argjson id "$id" '.[$k] |= map(select(.id != $id))' <<<"$state")" + echo "$PFX$id $past" +} + +cmd_answer() { remove_item answered question answer "$@"; } +cmd_resolve() { remove_item resolved decision resolve "$@"; } +cmd_done() { remove_item done followup done "$@"; } + +check_kind() { + case "$1" in + question | decision | followup) ;; + *) usage >&2; exit 2 ;; + esac +} + +cmd_list() { + local full=0 as_json=0 kind="" fmt="" + while [[ $# -gt 0 ]]; do + case "$1" in + --kind) kind="${2:?--kind needs a value}"; check_kind "$kind"; shift 2 ;; + --format) + fmt="${2:?--format needs a value}" + case "$fmt" in line | text | md) ;; *) die "list: --format must be line, text or md, got '$fmt'" 2 ;; esac + shift 2 ;; + --full) full=1; shift ;; + --json) as_json=1; shift ;; + *) die "list: unknown argument: $1" 2 ;; + esac + done + if [[ -z "$fmt" ]]; then + if [[ $full -eq 1 ]]; then fmt=text; else fmt=line; fi + fi + local state + state=$(read_state) + if [[ $as_json -eq 1 ]]; then + case "$kind" in + question) jq '.questions' <<<"$state" ;; + decision) jq '.decisions' <<<"$state" ;; + followup) jq '.followups' <<<"$state" ;; + *) jq '{questions, decisions, followups}' <<<"$state" ;; + esac + return + fi + jq -r --arg kind "$kind" --arg fmt "$fmt" --argjson full "$full" ' + def flat: gsub("\\s+"; " ") | sub("^ "; "") | sub(" $"; ""); + def clip($n): flat | if length > $n then + (if (.[$n:$n + 1] | test("\\s")) then .[0:$n] else (.[0:$n] | sub("\\s+\\S*$"; "")) end) + "…" + else . end; + def m: if $fmt == "md" then gsub("\\*"; "\\*") else . end; + def card($p; $ek): + (.title | flat | m) as $t + | ((.context // "") | if $full == 1 then flat else clip(200) end | m) as $ctx + | ((.options // []) | map(flat | m) | map(select(. != ""))) as $opts + | ((.[$ek] // "") | flat | m) as $ans + | "\($p)\(.id)" as $id + | if $p == "F" then + (if $fmt == "md" then + ["- ☐ **\($id)** \($t)"] + + (if $full == 1 and $ctx != "" then [" - *why:* \($ctx)"] else [] end) + else + ["\($id) \($t)"] + + (if $full == 1 and $ctx != "" then [" why: \($ctx)"] else [] end) + end) + elif $p == "Q" then + (if $fmt == "md" then + ["**\($id) · \($t)**"] + + (if $ctx != "" then ["> \($ctx)"] else [] end) + + ($opts | to_entries | map("- **\([.key + 97] | implode))** \(.value)")) + + (if $ans != "" then ["- 👉 *recommend:* \($ans)"] else [] end) + else + ["\($id) \($t)"] + + (if $ctx != "" then [" why: \($ctx)"] else [] end) + + ($opts | to_entries | map(" \([.key + 97] | implode)) \(.value)")) + + (if $ans != "" then [" → recommend: \($ans)"] else [] end) + end) + else + ($opts | join(" · ") | clip(160)) as $joined + | (if $fmt == "md" then + ["**\($id) · \($t)**"] + + (if $ans != "" then ["- ✅ **\($ans)**"] else [] end) + + (if $full == 1 then ($opts | map("- *instead:* \(.)")) + elif $joined != "" then ["- *instead:* \($joined)"] else [] end) + + (if $full == 1 and $ctx != "" then ["- *why:* \($ctx)"] else [] end) + else + ["\($id) \($t)"] + + (if $ans != "" then [" ✓ \($ans)"] else [] end) + + (if $full == 1 then ($opts | map(" instead: \(.)")) + elif $joined != "" then [" instead: \($joined)"] else [] end) + + (if $full == 1 and $ctx != "" then [" why: \($ctx)"] else [] end) + end) + end + | join("\n"); + def section($label; $p; $ek; $tail): + if length == 0 then empty + else ((if $fmt == "md" then ["### \($label) · \(length)\($tail)"] else [] end) + + (if $p == "F" and $fmt == "md" then [map(card($p; $ek)) | join("\n")] else map(card($p; $ek)) end))[] end; + if $fmt == "line" then + (if ($kind == "" or $kind == "question") then (.questions[] | "Q\(.id) \(.title)") else empty end), + (if ($kind == "" or $kind == "decision") then (.decisions[] | "D\(.id) \(.title)") else empty end), + (if ($kind == "" or $kind == "followup") then (.followups[] | "F\(.id) \(.title)") else empty end) + else + [ (if ($kind == "" or $kind == "question") then (.questions | section("Questions"; "Q"; "recommendation"; " need you")) else empty end), + (if ($kind == "" or $kind == "decision") then (.decisions | section("Decisions"; "D"; "chosen"; " to review")) else empty end), + (if ($kind == "" or $kind == "followup") then (.followups | section("Followups"; "F"; "none"; " open")) else empty end) ] + | if length == 0 then empty else join("\n\n") end + end' <<<"$state" +} + +cmd_count() { + local kind="" + while [[ $# -gt 0 ]]; do + case "$1" in + --kind) kind="${2:?--kind needs a value}"; check_kind "$kind"; shift 2 ;; + *) die "count: unknown argument: $1" 2 ;; + esac + done + read_state | jq --arg kind "$kind" ' + if $kind == "question" then (.questions | length) + elif $kind == "decision" then (.decisions | length) + elif $kind == "followup" then (.followups | length) + else ((.questions | length) + (.decisions | length) + (.followups | length)) end' +} + +cmd_prune() { + local days=7 + while [[ $# -gt 0 ]]; do + case "$1" in + --days) days="${2:?--days needs a value}"; shift 2 ;; + *) die "prune: unknown argument: $1" 2 ;; + esac + done + [[ "$days" =~ ^[0-9]+$ ]] || die "prune: --days must be a non-negative integer" 2 + [[ -d "$STATE_DIR" ]] || exit 0 + find "$STATE_DIR" -maxdepth 1 -type f \( -name '*.json' -o -name '*.lock' \) -mtime "+$days" -delete +} + +"cmd_$cmd" "$@" diff --git a/plugins-opencode/inbox/src/index.ts b/plugins-opencode/inbox/src/index.ts new file mode 100644 index 0000000..2eeef64 --- /dev/null +++ b/plugins-opencode/inbox/src/index.ts @@ -0,0 +1,56 @@ +import { Plugin } from "@opencode/plugin" +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { fileURLToPath } from "node:url" +import path from "node:path" +import { Inbox } from "./rpc.js" + +const exec = promisify(execFile) + +// Vendored from utils/inbox by utils/sync.sh — same CLI the Claude plugin +// uses, so both harnesses share one state file and the CLI's dedupe/locking +// stays the single source of truth. +const scriptDir = path.dirname(fileURLToPath(import.meta.url)) +const INBOX_CLI = path.resolve(scriptDir, "..", "scripts", "inbox") + +type Counts = { questions: number; decisions: number; followups: number; blocking: number } + +type InboxItem = { id?: string; title?: string; blocking?: boolean; [k: string]: unknown } + +type Snapshot = { counts: Counts; items: { questions: InboxItem[]; decisions: InboxItem[]; followups: InboxItem[] } } + +export async function readSnapshot(sessionID: string): Promise<Snapshot> { + const { stdout } = await exec(INBOX_CLI, ["--session", sessionID, "list", "--json"]) + const parsed = JSON.parse(stdout) as { + questions: InboxItem[] + decisions: InboxItem[] + followups: InboxItem[] + } + const items = { + questions: parsed.questions ?? [], + decisions: parsed.decisions ?? [], + followups: parsed.followups ?? [], + } + return { + counts: { + questions: items.questions.length, + decisions: items.decisions.length, + followups: items.followups.length, + blocking: items.questions.filter((q) => q.blocking === true).length, + }, + items, + } +} + +export default Plugin.define({ + id: "agent-toolkit.inbox", + async setup(ctx) { + const registration = await ctx.rpc.register(Inbox, { + snapshot: async (input) => { + const { sessionID } = input as { sessionID: string } + return readSnapshot(sessionID) + }, + }) + return () => void registration.dispose() + }, +}) diff --git a/plugins-opencode/inbox/src/rpc.ts b/plugins-opencode/inbox/src/rpc.ts new file mode 100644 index 0000000..9ec5404 --- /dev/null +++ b/plugins-opencode/inbox/src/rpc.ts @@ -0,0 +1,70 @@ +import { Rpc } from "@opencode/plugin/rpc" + +// Shared contract between the server part, the TUI part, and any external +// client. The server implements it over the vendored `scripts/inbox` CLI so +// every harness shares one state file; the TUI only ever talks RPC (it may be +// attached to a remote server and must not read local files). +export const Inbox = Rpc.define({ + id: "agent-toolkit.inbox", + methods: { + snapshot: { + input: { + type: "object", + properties: { sessionID: { type: "string" } }, + required: ["sessionID"], + additionalProperties: false, + }, + output: { + type: "object", + properties: { + counts: { + type: "object", + properties: { + questions: { type: "number" }, + decisions: { type: "number" }, + followups: { type: "number" }, + blocking: { type: "number" }, + }, + required: ["questions", "decisions", "followups", "blocking"], + additionalProperties: false, + }, + items: { + type: "object", + properties: { + questions: { type: "array", items: { type: "object" } }, + decisions: { type: "array", items: { type: "object" } }, + followups: { type: "array", items: { type: "object" } }, + }, + required: ["questions", "decisions", "followups"], + additionalProperties: false, + }, + }, + required: ["counts", "items"], + additionalProperties: false, + }, + }, + }, + events: { + changed: { + schema: { + type: "object", + properties: { + sessionID: { type: "string" }, + counts: { + type: "object", + properties: { + questions: { type: "number" }, + decisions: { type: "number" }, + followups: { type: "number" }, + blocking: { type: "number" }, + }, + required: ["questions", "decisions", "followups", "blocking"], + additionalProperties: false, + }, + }, + required: ["sessionID", "counts"], + additionalProperties: false, + }, + }, + }, +}) diff --git a/plugins-opencode/inbox/src/tui.tsx b/plugins-opencode/inbox/src/tui.tsx new file mode 100644 index 0000000..804be1e --- /dev/null +++ b/plugins-opencode/inbox/src/tui.tsx @@ -0,0 +1,17 @@ +import { Plugin } from "@opencode/plugin/tui" +import { Inbox } from "./rpc.js" + +// M0 scaffold: proves the RPC + TUI slot wiring end to end. M3 replaces this +// with the seeded signal, sidebar block, and triage panel. +export default Plugin.define({ + id: "agent-toolkit.inbox.tui", + setup(context) { + return context.ui.slot({ + append: "home.footer.status", + render: () => { + void context.client.rpc(Inbox) + return null + }, + }) + }, +}) diff --git a/plugins-opencode/session/package.json b/plugins-opencode/session/package.json new file mode 100644 index 0000000..9b85bf2 --- /dev/null +++ b/plugins-opencode/session/package.json @@ -0,0 +1,12 @@ +{ + "name": "opencode-agent-toolkit-session", + "version": "0.1.0", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "files": ["src"], + "dependencies": { + "@opencode/plugin": "latest" + } +} diff --git a/plugins-opencode/session/scripts/branch b/plugins-opencode/session/scripts/branch new file mode 100755 index 0000000..98f16e5 --- /dev/null +++ b/plugins-opencode/session/scripts/branch @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# branch - Git branch operations for session workflows +# Exit codes: 0 success (including -h/--help), 1 bad usage or invalid name, 2 git error +# +# Subcommands: +# create <name> Create and switch to a new branch + +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: branch <subcommand> [args] + +Subcommands: + create <name> Create and switch to a new branch +EOF +} + +die() { echo "Error: $*" >&2; exit 2; } + +[[ $# -ge 1 ]] || { usage >&2; exit 1; } + +cmd="$1"; shift + +case "$cmd" in + create) + [[ $# -eq 1 ]] || { echo "Usage: branch create <name>" >&2; exit 1; } + name="$1" + [[ "$name" != -* ]] || { echo "Error: branch name must not start with '-': $name" >&2; exit 1; } + git check-ref-format --branch "$name" >/dev/null 2>&1 || { echo "Error: invalid branch name: $name" >&2; exit 1; } + if git show-ref --verify --quiet "refs/heads/$name"; then + die "branch '$name' already exists" + fi + git switch -c "$name" || die "failed to create branch '$name'" + ;; + -h|--help) usage ;; + *) echo "Unknown subcommand: $cmd" >&2; usage >&2; exit 1 ;; +esac diff --git a/plugins-opencode/session/scripts/git-wait b/plugins-opencode/session/scripts/git-wait new file mode 100755 index 0000000..335f658 --- /dev/null +++ b/plugins-opencode/session/scripts/git-wait @@ -0,0 +1,1460 @@ +#!/usr/bin/env bash +# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. +# +# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: +# listing, creating, commenting, merging, closing, viewing logs. This script +# exists only for the three things neither CLI gives you: +# +# 1. Platform detection — matching the git remote hostname against configured +# tea logins, so a caller knows whether to reach for `gh` or `tea`. +# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a +# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on +# the merge itself; `tea` has no equivalent at all). +# 3. `run watch` — block until CI finishes, aggregating per-job status and +# dumping failed job logs. `gh run watch` is GitHub-only and misses +# job-level failures masked by a run-level success; `tea` has no watcher. +# +# Usage: +# git-wait [-C DIR] <command> ... +# Operate on the git repo at DIR instead of the current directory (like +# `git -C`). Must come before the command. gh/tea resolve the repo from the +# working directory, so this retargets every call without a caller-side cd. +# +# git-wait platform +# Echo "github" or "gitea" for the current repo's origin remote. +# +# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] +# [--alert-interval 300] +# Block until the PR for BRANCH reaches a terminal state. +# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, +# url, duration, and (when relevant) reason. +# +# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] +# [--timeout 14400] [--idle-timeout 0] [--interval 15] +# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] +# [--max-poll-failures 10] +# Block until CI finishes. Output: "status: pass|fail|closed|timeout| +# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed +# job logs go to stderr. +# +# --branch follows ONE run: the newest correlated to that branch (via the +# PR's check rollup when a PR exists, else the newest run in the list). +# That is right for a PR branch, where one push means one run. It is NOT +# sufficient on a default branch, where two merges landing close together +# produce two runs and the newest passing says nothing about the older +# one still executing. +# +# --sha watches EVERY run for one commit and is the correct flag for a +# post-merge/release watch: it stays pending while any run for the commit +# is pending, and fails if any run — or any job inside one — failed. Pass +# one or the other, not both. +# +# A running CI is never aborted for lack of visible progress: `run watch +# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress +# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO +# check is pending (running CI, or auto-merge armed, resets it), so a PR that +# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long +# jobs (VM boot + integration suite + teardown) can go quiet for a long time. +# While still waiting, a heartbeat alert goes to STDERR every --alert-interval +# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) +# pending: ...)". stdout key:value output is unchanged. +# +# --no-run-timeout is how long to wait for the FIRST run to appear before +# reporting no-workflow, counted from the end of --initial-delay. Default 600s +# for --sha (post-merge workflows queue late, or start only after another +# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty +# check. A stderr alert is printed each poll while waiting. A FAILED run-list +# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not +# counted toward this deadline and polling continues, but after +# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the +# watch gives up with "status: error" and exit 4. A successful poll resets the +# count. +# +# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the +# commit is terminal and passing, keep polling SECS more before reporting pass, +# so a chained workflow_run workflow that appears late is still watched. A +# stderr line is printed while settling; a new run restarts the watch. +# +# Exit codes: 0 terminal state reached (check "status:" for pass/fail), +# 1 usage error, 2 timeout, 3 platform detection failure or no +# PR/workflow found, 4 command failed + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +die() { echo "git-wait: $*" >&2; exit 1; } +die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } + +# Run a CLI command and pipe its stdout through a jq filter. +# If the command fails, die with its stderr instead of feeding junk to jq. +# Usage: cli_json [jq-flags...] <jq-filter> <cmd> [args...] +# +# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. +# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, +# auth warnings, progress text) into the JSON, silently corrupting jq +# parsing and producing wrong results downstream (e.g. run watch seeing +# unexpected status values). +cli_json() { + local jq_flags=() + while [[ "$1" =~ ^-[a-zA-Z] ]]; do + # Collect jq flags (e.g. -r, -e) — stop at the filter string + case "$1" in + -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; + *) break ;; + esac + done + local filter="$1"; shift + local raw stderr_file rc=0 + stderr_file=$(mktemp) + raw=$("$@" 2>"$stderr_file") || rc=$? + if [[ $rc -ne 0 ]]; then + local err + err=$(cat "$stderr_file") + rm -f "$stderr_file" + die "$err" + fi + rm -f "$stderr_file" + echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" +} + +# --------------------------------------------------------------------------- +# Target repo (-C DIR) +# +# Handled before platform detection. The cd happens inside this script's own +# process, so the caller's working directory is never touched. +# --------------------------------------------------------------------------- + +if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then + [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" + target_dir="$2" + [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" + git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die_usage "$1: not a git repository: $target_dir" + # Resolve the script path first: a relative $0 breaks once we cd (help reads it). + SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + cd "$target_dir" + shift 2 +fi +SELF="${SELF:-$0}" + +# --------------------------------------------------------------------------- +# Platform detection +# --------------------------------------------------------------------------- + +detect_platform() { + local remote_url hostname login_url login_host + remote_url=$(git remote get-url origin 2>/dev/null) \ + || die "no git remote 'origin' found — run from a git repository" + + # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) + # or HTTPS (https://host/org/repo or https://host:port/org/repo) + if [[ "$remote_url" =~ ^ssh:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') + elif [[ "$remote_url" =~ ^git@ ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') + elif [[ "$remote_url" =~ ^https?:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') + else + die "unrecognised remote URL format: $remote_url" + fi + + # Check if this hostname matches any configured tea login + if command -v tea >/dev/null 2>&1; then + while IFS= read -r login_url; do + login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') + if [[ "$login_host" == "$hostname" ]]; then + echo "gitea" + return + fi + done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) + fi + + # Not a known tea login — fall back to gh (GitHub) + if [[ "$hostname" == "github.com" ]]; then + echo "github" + return + fi + + die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" +} + +PLATFORM=$(detect_platform) + +case "$PLATFORM" in + github) CLI=gh ;; + gitea) CLI=tea ;; +esac + +command -v "$CLI" >/dev/null 2>&1 \ + || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } + +# --------------------------------------------------------------------------- +# Internal reads +# +# These are NOT public subcommands — they are the normalized queries the two +# waiters below need. Every one of them dies on backend failure, so callers +# invoke them inside $( ) with a fallback: a probe failure must degrade the +# poll loop, never abort it. +# --------------------------------------------------------------------------- + +# List PRs as normalized JSON. Flags: --state, --limit, --assignee. +_pr_list() { + local limit assignee state args + limit=30; assignee=""; state="open" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; + --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") + # gh uses 'merged' as a state but tea uses 'closed' for merged PRs + [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") + [[ -n "$assignee" ]] && args+=(--assignee "$assignee") + cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ + env GH_NO_COLOR=1 gh pr list "${args[@]}" + ;; + gitea) + args=(--output json --limit "$limit" + --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") + [[ "$state" == "merged" ]] && state="closed" + args+=(--state "$state") + cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ + env NO_COLOR=1 tea pr list "${args[@]}" + ;; + esac +} + +# Show one PR as normalized JSON. Takes <N> or --branch NAME. +_pr_show() { + local num branch pr_json pr_stderr pr_rc pr_detail err + num=""; branch="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --*) die_usage "unknown flag: $1" ;; + *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; + esac + shift + done + [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass <N> or --branch NAME, not both" + if [[ -n "$branch" ]]; then + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + num=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + [[ -n "$num" ]] || die "no PR found for branch '$branch'" + fi + [[ -n "$num" ]] || die_usage "usage: git-wait pr show <N> | --branch NAME" + case "$PLATFORM" in + github) + cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ + env GH_NO_COLOR=1 gh pr view "$num" \ + --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" + ;; + gitea) + # `tea pr list` omits the `merged` boolean and `merged_at` timestamp + # entirely (tea only encodes merge state into the `state` string) and + # emits `mergeable` as a string, so a merged PR reports + # merged:false / mergedAt:null and consumers think it is still open + # (#140). Fetch the PR detail via the REST API instead, mirroring the + # run:show/run:list `tea api` pattern, so merge fields are reliable. + pr_stderr=$(mktemp); pr_rc=0 + pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ + || pr_rc=$? + if [[ $pr_rc -ne 0 ]]; then + err=$(cat "$pr_stderr"); rm -f "$pr_stderr" + die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" + fi + rm -f "$pr_stderr" + # Derive `state` from `merged` so it stays consistent with the merge + # flags (Gitea REST reports state:"closed" for a merged PR) and matches + # the GitHub path, which emits state:"merged". + echo "$pr_detail" | jq '{ + number: (.number // .index), + title: (.title // ""), + body: (.body // ""), + state: (if (.merged // false) then "merged" else (.state // "") end), + merged: (.merged // false), + merged_at: (.merged_at // null), + author: (.user.login // .user.username // ""), + head: (.head.ref // .head.label // ""), + base: (.base.ref // .base.label // ""), + labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), + assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), + mergeable: (.mergeable // null), + created_at: (.created_at // ""), + updated_at: (.updated_at // null), + url: (.html_url // .url // ""), + comments: [] + }' + ;; + esac +} + +# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. +_auto_merge_status() { + local branch number pr_json am + branch=""; number="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) shift; branch="$1" ;; + --number) shift; number="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + + # Resolve PR number from branch if needed + if [[ -z "$number" ]]; then + [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" + pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" + number=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + if [[ -z "$number" || "$number" == "null" ]]; then + echo "auto_merge: false" + echo "No open PR found for branch '$branch'" >&2 + exit 3 + fi + fi + + case "$PLATFORM" in + github) + am=$(cli_json -r '.autoMergeRequest != null' \ + env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) + echo "auto_merge: $am" + ;; + gitea) + echo "auto_merge: false" + echo "Gitea does not support auto-merge detection" >&2 + ;; + esac +} + +# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. +# +# --sha filters to runs for one commit. GitHub has a server-side filter for it +# (`gh run list --commit`); Gitea does not, so it is applied client-side over +# an unfiltered fetch, the same way --branch already is there. Both platforms +# emit head_sha in the normalized output — GitHub did not used to, which is +# why `run watch --sha` needs the headSha field added below. +_run_list() { + local limit status branch sha args query raw_stderr raw_rc raw err + limit=20; status=""; branch=""; sha="" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") + [[ -n "$status" ]] && args+=(--status "$status") + [[ -n "$branch" ]] && args+=(--branch "$branch") + [[ -n "$sha" ]] && args+=(--commit "$sha") + cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ + env GH_NO_COLOR=1 gh run list "${args[@]}" + ;; + gitea) + # Source from Gitea REST API directly. `tea actions runs list` + # filters server-side by a `branch` column that Gitea leaves empty + # on `pull_request` runs, so the watcher's --branch lookup misses + # correlated runs (#103). Fetch unfiltered via `tea api`, normalize + # `branch` from `head_branch`, and apply --branch client-side. + query="limit=$limit" + [[ -n "$status" ]] && query+="&status=$status" + raw_stderr=$(mktemp); raw_rc=0 + raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ + || raw_rc=$? + if [[ $raw_rc -ne 0 ]]; then + err=$(cat "$raw_stderr"); rm -f "$raw_stderr" + die "tea api repos/{owner}/{repo}/actions/runs failed: $err" + fi + rm -f "$raw_stderr" + echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' + [(.workflow_runs // []) | .[] | { + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + head_sha: (.head_sha // ""), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // "") + }] + | if $b == "" then . else [.[] | select(.branch == $b)] end + | if $s == "" then . else + [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] + end + ' + ;; + esac +} + +# Show one CI run as normalized JSON, including per-job status. +_run_show() { + local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err + [[ $# -ge 1 ]] || die_usage "usage: git-wait run show <run-id>" + run_id="$1" + case "$PLATFORM" in + github) + cli_json \ + 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ + env GH_NO_COLOR=1 gh run view "$run_id" \ + --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" + ;; + gitea) + # Fetch the run object via the REST API. `tea actions runs view` + # ignores `--output json` (tea 0.14.1) and prints a human key/value + # table while still exiting 0, so jq downstream chokes (#133). Use the + # same `tea api` pattern as run:list and the jobs lookup below. + view_stderr=$(mktemp); view_rc=0 + view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ + || view_rc=$? + if [[ $view_rc -ne 0 ]]; then + err=$(cat "$view_stderr"); rm -f "$view_stderr" + die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" + fi + rm -f "$view_stderr" + + # Fetch per-job data via the actions API so callers (run watch) can + # detect job-level failures masked by run-level status=success on + # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. + jobs_array='[]' + jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) + if [[ -n "$jobs_json" ]]; then + jobs_array=$(echo "$jobs_json" | jq -c ' + def to_status: + if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) + end; + [(.jobs // .) | (if type == "array" then .[]? else empty end) | + {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] + ' 2>/dev/null) || jobs_array='[]' + fi + + # Older Gitea versions may not expose the jobs API; fall back to + # scanning the run logs for "Job '<name>' failed" lines. + if [[ "$jobs_array" == '[]' ]]; then + failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ + | grep -oE "Job '[^']+' failed" \ + | sed -E "s/Job '(.+)' failed/\1/" \ + | sort -u || true) + if [[ -n "$failed_log" ]]; then + jobs_array=$(printf '%s\n' "$failed_log" \ + | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') + fi + fi + + # Normalize REST field names into the output contract, mirroring the + # run:list jq above (conclusion-first status, head_branch//branch, + # run_started_at//created, name//workflow_id). + echo "$view_json" | jq --argjson jobs "$jobs_array" '{ + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // ""), + jobs: $jobs + }' + ;; + esac +} + +# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; +# Gitea has no server-side filter and returns every job's log). +_run_logs() { + local run_id failed_only + [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs <run-id> [--failed-only]" + run_id="$1"; shift + failed_only=false + while [[ $# -gt 0 ]]; do + case "$1" in + --failed-only) failed_only=true ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + if [[ "$failed_only" == "true" ]]; then + GH_NO_COLOR=1 gh run view "$run_id" --log-failed + else + GH_NO_COLOR=1 gh run view "$run_id" --log + fi + ;; + gitea) + # tea actions runs logs outputs all job logs; no built-in failed-only filter + NO_COLOR=1 tea actions runs logs "$run_id" + ;; + esac +} + +# --------------------------------------------------------------------------- +# Run helpers +# --------------------------------------------------------------------------- + +# Return comma-separated names of any jobs in <run_id> whose status is +# "failure", or empty if none. Used by run watch to detect job-level failures +# even when the run-level status reports success — Gitea sets run.status to +# "success" on a multi-job workflow if at least one job ran successfully, +# masking failures in earlier jobs (see issue #87). Calls "run show" to +# normalize per-platform JSON, so it works for both gh and tea paths. +_run_failed_jobs() { + local run_id="$1" show_json + show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 + echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' +} + +# Progress-aware timeout decision shared by `pr wait` and `run watch`. +# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress +# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. +# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ +# minutes: this lets callers keep waiting while CI is actively progressing and +# give up only after a stretch of no progress, with a hard ceiling backstop. +_wait_timed_out() { + local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" + if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then + echo "ceiling"; return 0 + fi + if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then + echo "idle"; return 0 + fi + return 1 +} + +# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. +_fmt_dur() { + local s="$1" + if [[ "$s" -lt 60 ]]; then echo "${s}s" + elif [[ "$s" -lt 3600 ]]; then + if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi + else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi +} + +# Periodic stderr heartbeat while a wait is still running. Callers set +# alert_interval (0 disables) and next_alert (initialised to alert_interval), +# and call `_heartbeat "$elapsed" "<detail>"` once per poll. Emits at most one +# alert per poll, then re-arms for the next multiple of alert_interval, so a +# slow poll never produces a burst. stderr only: stdout stays parseable. +_heartbeat() { + local el="$1" detail="$2" + [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 + echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 + next_alert=$(( (el / alert_interval + 1) * alert_interval )) +} + +# Coarse CI status — pending|success|failure|none — for a PR/branch, used by +# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the +# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is +# guarded so a probe failure degrades to "none" and never aborts the wait loop. +_ci_status() { + local pr_number="$1" branch="$2" view_json run_status + case "$PLATFORM" in + github) + view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } + echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) else "pending" end + else (.state // "pending" | ascii_downcase) end + ] | + if length == 0 then "none" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" end' 2>/dev/null || echo "none" + ;; + gitea) + run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) echo "pending" ;; + failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; + ""|none|null) echo "none" ;; + *) echo "success" ;; + esac + ;; + *) echo "none" ;; + esac +} + +# --------------------------------------------------------------------------- +# Command routing +# --------------------------------------------------------------------------- + +cmd="${1:-}" +sub="${2:-}" +shift 2 || shift || true + +case "$cmd:$sub" in + + # Echo the detected platform so callers know which CLI to reach for. + # PLATFORM is already resolved above; detection failure exited long before + # we got here. + platform:) + echo "$PLATFORM" + ;; + + pr:wait) + # timeout is the hard ceiling; idle_timeout is the no-progress window. + branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" ]] || die_usage "pr wait requires --branch" + + # Find PR for this branch + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + # Match branch — handle Gitea owner:branch format with endswith + pr=$(echo "$pr_json" | jq --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') + + if [[ -z "$pr" || "$pr" == "null" ]]; then + echo "status: no-pr" + echo "duration: 0s" + echo "No PR found for branch '$branch'" >&2 + exit 3 + fi + + pr_number=$(echo "$pr" | jq -r '.number') + pr_url=$(echo "$pr" | jq -r '.url // ""') + elapsed=0 + idle=0; idle_mark=0 + last_signal="" + unknown_streak=0 + + # Poll loop + while true; do + show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" + pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') + pr_merged=$(echo "$show_json" | jq -r '.merged // false') + pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') + + # Progress signals: CI still running or auto-merge pending means the PR is + # actively advancing toward merge, so the idle clock must not count down. + checks=$(_ci_status "$pr_number" "$branch") + if [[ "$PLATFORM" == "github" ]]; then + auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" + [[ "$auto_merge" == "true" ]] || auto_merge="false" + else + auto_merge="false" + fi + signal="$pr_state|$pr_mergeable|$checks|$auto_merge" + if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then + idle=0 + fi + last_signal="$signal" + + echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 + [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true + + case "$pr_state" in + merged) + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + closed) + if [[ "$pr_merged" == "true" ]]; then + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + fi + echo "status: closed" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR was closed without merging" >&2 + exit 0 + ;; + open) + # Check for merge conflicts + if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then + echo "status: blocked" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR has merge conflicts" >&2 + exit 0 + fi + # Still open — keep polling + ;; + *) + unknown_streak=$(( unknown_streak + 1 )) + if [[ "$unknown_streak" -ge 3 ]]; then + echo "status: error" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 + exit 4 + fi + echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 + ;; + esac + + # Reset unknown streak on any recognized state + [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 + + # Check timeout — only give up after a stretch of no progress (idle) or + # the absolute ceiling, never while CI/auto-merge is still working. + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + run:watch) + # timeout is the hard ceiling; idle_timeout is the no-progress backstop. + # While CI is actively pending the idle clock is reset each poll, so a long + # (15+ min) suite runs to completion up to the ceiling rather than being cut + # off by a flat wall-clock timeout. + branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 + alert_interval=300; next_alert=300; no_run_timeout="" + settle=0; settle_given=0; no_run_skew=0 + max_poll_failures=10; poll_fails=0 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; + --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; + --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" + [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" + [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" + # How long to wait for the FIRST run to appear (counted from the end of + # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ + # workflow_run and can queue minutes late, so that scope gets longer. + if [[ -z "$no_run_timeout" ]]; then + if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi + fi + + # `gh run list --commit` matches only on a FULL 40-character SHA -- a short + # one returns zero rows with no error, which this watcher would report as + # "no-workflow" rather than as the caller's mistake. Expand a short SHA via + # git when the commit is local, and refuse it outright when it is not, + # rather than silently watching nothing. (Gitea matches client-side on the + # first 12 chars, so a full SHA is correct there too.) + if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" + if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha="$_full_sha" + else + die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" + fi + fi + + elapsed=0 + idle=0; idle_mark=0 + + # A failed run-list call (network, auth, rate limit) is NOT an empty list. + # Note it, keep polling, and exclude the time from the no-workflow deadline + # (accumulated in no_run_skew). The hard ceiling still applies. After + # --max-poll-failures consecutive failures it gives up (exit 4). + _poll_failed() { + local what="$1" before="$elapsed" + poll_fails=$(( poll_fails + 1 )) + echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 + if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then + echo "status: error" + echo "duration: ${elapsed}s" + echo "reason: run list failed ${poll_fails} consecutive times" + echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 + exit 4 + fi + elapsed=$(( SECONDS - _t0 )) + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 + exit 2 + fi + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + no_run_skew=$(( no_run_skew + elapsed - before )) + } + + # Enforce the hard --timeout ceiling on paths that otherwise `continue` + # (no runs yet, settling, no checks registered) so they cannot outlive it. + _ceiling_check() { + local what="$1" + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what}" >&2 + exit 2 + fi + } + + # ------------------------------------------------------------------ + # --sha: watch EVERY run for one commit, not just the newest. + # + # `--branch` deliberately follows a single run (the newest correlated + # one). That is right for a PR branch, where one push means one run, but + # wrong for a default branch: two merges landing close together produce + # two runs, and the newest going green says nothing about the older one + # still executing. Watching a post-merge release run by branch reported + # "pass" while a second run was mid-flight. + # + # A commit is the honest scope for that question — the caller wants the + # runs *their* merge caused, not whatever else is landing on the branch. + # So this path aggregates: it stays non-terminal while ANY run for the + # commit is non-terminal, and fails if ANY run (or any job within one) + # failed. + # + # The CRITICAL DESIGN RULE below applies here too: only explicitly + # non-terminal statuses keep polling; anything unrecognized counts as + # terminal so an unexpected status cannot loop until timeout. + # ------------------------------------------------------------------ + if [[ -n "$sha" ]]; then + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + echo "Watching all runs for commit ${sha:0:12}..." >&2 + + # Settle window: after every run is terminal and passing, keep polling + # --settle seconds for a chained (workflow_run) run before reporting pass. + settle_start=-1; settle_ids="" + + while true; do + if ! sha_json=$(_run_list --sha "$sha" --limit 50); then + _poll_failed "commit ${sha:0:12}" + continue + fi + poll_fails=0 + sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) + + if [[ "$sha_count" -eq 0 ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + # Non-terminal set is explicit; everything else is terminal. + pending=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested")] + | length') + + echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 + + if [[ "$pending" -gt 0 ]]; then + pending_names=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested") + | (.workflow // .id)] | join(", ")') + _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" + # Active CI is progress — reset the idle clock, same as --branch. + idle=0 + settle_start=-1 + else + # Every run terminal. Collect run-level and job-level failures + # across ALL of them before declaring pass (#87 applies per run). + all_failed="" + fail_url="" + while IFS=$'\t' read -r r_id r_status r_url; do + [[ -n "$r_id" ]] || continue + case "$r_status" in + failure|timed_out|cancelled|canceled|skipped) + all_failed+="${all_failed:+,}run-$r_id:$r_status" + [[ -n "$fail_url" ]] || fail_url="$r_url" + ;; + *) + r_failed=$(_run_failed_jobs "$r_id") + if [[ -n "$r_failed" ]]; then + all_failed+="${all_failed:+,}$r_failed" + [[ -n "$fail_url" ]] || fail_url="$r_url" + fi + ;; + esac + done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') + + if [[ -n "$all_failed" ]]; then + echo "status: fail" + [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $all_failed" + echo "--- Failed job logs (last 80 lines) ---" >&2 + echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do + _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true + done + exit 0 + fi + + if [[ "$settle" -gt 0 ]]; then + cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') + if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then + echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 + settle_start=-1 + fi + if [[ "$settle_start" -lt 0 ]]; then + settle_start=$elapsed; settle_ids="$cur_ids" + fi + if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then + echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + fi + + echo "status: pass" + first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') + [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" + echo "duration: ${elapsed}s" + echo "runs: $sha_count" >&2 + exit 0 + fi + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so + # `run list --branch` correlates nothing and the watcher times out into + # no-workflow even when CI ran (#140). Resolve the branch head SHA up front + # (only on Gitea) and fall back to head_sha correlation when the + # branch-filtered lookup is empty. The run object's head_sha equals the + # branch head on Gitea (confirmed in #140); if a variant ever records a + # merge-ref SHA the fallback simply misses and degrades to today's + # behaviour rather than returning a wrong run. + _watch_branch_sha="" + if [[ "$PLATFORM" == "gitea" ]]; then + _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ + || git rev-parse "origin/$branch" 2>/dev/null || true) + fi + + # Echo a run-list JSON array for $branch: branch-name correlation first, + # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the + # server-side --branch filter populates the first call and _watch_branch_sha + # stays empty, so the SHA path is never taken. + _runs_for_branch() { + local lim="${1:-1}" out + # A failed call returns 1 (distinct from a successful empty "[]"). + out=$(_run_list --branch "$branch" --limit "$lim") || return 1 + if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then + echo "$out"; return 0 + fi + if [[ -n "$_watch_branch_sha" ]]; then + _run_list --limit 50 | jq \ + --arg s "$_watch_branch_sha" --argjson n "$lim" \ + '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ + || return 1 + return 0 + fi + echo "[]" + } + + # On GitHub, prefer PR-based status checking — one API call gives us both + # merge state and all CI check results via statusCheckRollup, avoiding the + # flaky run-level polling that produces "unknown" statuses. + pr_number="" + pr_url="" + use_pr=false + if [[ "$PLATFORM" == "github" ]]; then + pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { + pr_number=$(echo "$pr_json" | jq -r '.number // empty') + pr_url=$(echo "$pr_json" | jq -r '.url // ""') + [[ -n "$pr_number" ]] && use_pr=true + } + fi + + # Pre-check: look for an already-terminal state before sleeping the + # initial delay. If the PR already merged or CI already finished, + # report immediately instead of waiting. + _precheck_done=false + if [[ "$use_pr" == "true" ]]; then + _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" + _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') + + if [[ "$_pre_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already merged" >&2 + exit 0 + fi + if [[ "$_pre_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already closed without merging" >&2 + exit 0 + fi + + _pre_checks=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + if [[ "$_pre_checks" == "success" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "CI already passed on PR #$pr_number" >&2 + exit 0 + fi + + if [[ "$_pre_checks" == "failure" ]]; then + _pre_failed=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "failed_jobs: $_pre_failed" + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + fi + else + # Fallback path: check if a completed run already exists + _pre_list=$(_runs_for_branch 1) || _pre_list="[]" + _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') + if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then + _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') + _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') + _pre_id=$(echo "$_pre_latest" | jq -r '.id') + case "$_pre_status" in + success|completed) + # Run-level status can read "success" on Gitea even when a + # job inside the run failed (issue #87). Aggregate per-job + # status before declaring pass. + failed_jobs=$(_run_failed_jobs "$_pre_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "CI already passed for branch '$branch'" >&2 + exit 0 + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$_pre_id") + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$_pre_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a + # reason so consumers (ship/session-end) gating on + # status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "reason: $_pre_status" + echo "CI run $_pre_status for branch '$branch'" >&2 + exit 0 + ;; + esac + fi + fi + + # Initial delay — CI run may not exist immediately after push + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + if [[ "$use_pr" == "true" ]]; then + echo "Watching PR #$pr_number for branch '$branch'..." >&2 + + while true; do + # A failed gh call is not "unknown" -- count it, cap consecutive failures. + if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then + _poll_failed "PR #$pr_number" + continue + fi + poll_fails=0 + pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') + + # PR merged — all done + if [[ "$pr_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number merged" >&2 + exit 0 + fi + + # PR closed without merge + if [[ "$pr_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number closed without merging" >&2 + exit 0 + fi + + # Summarize CI check statuses from statusCheckRollup + # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state + checks_summary=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 + + case "$checks_summary" in + success) + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + failure) + failed_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_names" + # Try to fetch failed logs from the latest run + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + pending) + # Still running — keep polling. Active CI is progress, so reset idle. + check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') + if [[ "$check_count" -eq 0 ]]; then + # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + else + # Active CI is progress, so reset idle. + idle=0 + fi + pending_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select(if .__typename == "CheckRun" then (.conclusion // "") == "" + else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) + | .name // .context // "unknown"] | unique | join(", ")') + _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" + ;; + esac + + # Check timeout — idle window or absolute ceiling (see _wait_timed_out). + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Fallback: no PR found — poll run list directly (skip flaky run show). + # + # CRITICAL DESIGN RULE — default-terminal polling: + # + # This loop has caused repeated regressions (#53, #57, #58, #60). + # The recurring bug pattern is: + # 1. The API returns an unexpected status value (e.g. "completed" + # with null conclusion, or a new status GitHub adds later). + # 2. The case statement doesn't recognise it. + # 3. A catch-all `*) keep polling` silently loops until timeout. + # + # The fix (applied here) inverts the logic: + # - ONLY explicitly non-terminal states keep polling. + # - The `*` catch-all EXITS (as pass). + # + # DO NOT add a `*) keep polling` catch-all to this case statement. + # If a new non-terminal status appears, add it to the explicit list. + # If you're unsure whether a status is terminal, it's safer to exit + # early (the caller can retry) than to loop for 5 minutes. + # + run_url="" + while true; do + if ! list_json=$(_runs_for_branch 1); then + _poll_failed "branch '$branch'" + continue + fi + poll_fails=0 + latest=$(echo "$list_json" | jq -r '.[0] // empty') + + if [[ -z "$latest" || "$latest" == "null" ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + # Distinguish "no workflow registered at all" from "runs exist + # but none correlate to this branch" so callers (#103) can tell + # a real CI absence from a branch-correlation gap. + any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" + if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then + echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + else + echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + fi + exit 3 + fi + echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "branch '$branch'" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + run_id=$(echo "$latest" | jq -r '.id') + run_status=$(echo "$latest" | jq -r '.status // "unknown"') + run_url=$(echo "$latest" | jq -r '.url // ""') + + echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 + + # See "CRITICAL DESIGN RULE" above — non-terminal states are listed + # explicitly; everything else exits. Do NOT add a `*) keep polling`. + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) + # Non-terminal — keep polling. Active CI is progress, so reset idle. + idle=0 + _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$run_id") + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a reason + # so consumers gating on status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $run_status" + echo "CI run $run_status on branch '$branch'" >&2 + exit 0 + ;; + *) + # Terminal — covers success and any future/unexpected status. + # Even when the run-level status reports success, an individual + # job may have failed (Gitea reports run.status=success on a + # multi-job run if any job succeeded; see #87). Aggregate + # per-job status before declaring pass. + failed_jobs=$(_run_failed_jobs "$run_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + esac + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + --help:|-h:|:) + sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' + exit 0 + ;; + + *) + die_usage "unknown command: $cmd${sub:+ $sub}" + ;; +esac diff --git a/plugins-opencode/session/scripts/sitrep b/plugins-opencode/session/scripts/sitrep new file mode 100755 index 0000000..558f9e3 --- /dev/null +++ b/plugins-opencode/session/scripts/sitrep @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# sitrep - Situation report for a git repository +# Always shows working-tree state (staged/unstaged/untracked) together with +# committed context, and falls back to broader repo activity only when +# nothing else is actionable. +# +# Sections: +# 1. Working tree (staged/unstaged/untracked) +# 2. Unpushed commits (ahead of remote tracking branch) +# 3. Branch work (commits on feature branch vs base) +# 4. Repo activity (active branches, open issues) - only when 1-3 are empty +# +# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). +# +# Exit codes: 0 success (including -h/--help), 1 bad usage + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" + +usage() { + cat <<'EOF' +Usage: sitrep [directory] + +Situation report for a git repository. Shows working-tree changes plus +unpushed and branch commits, expanding to broader repo activity only +when everything is clean. + +If directory is omitted, uses the current working directory. +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +if [[ $# -gt 1 ]]; then + usage >&2 + exit 1 +fi + +dir="${1:-.}" +cd "$dir" + +gitq() { + git -c core.quotepath=false "$@" +} + +# Print a diff section, truncated to MAX_DIFF_LINES. +emit_diff() { + local title="$1" text="$2" total + [[ -n "$text" ]] || return 0 + total="$(printf '%s\n' "$text" | wc -l)" + echo "" + echo "=== $title ===" + if ((total > MAX_DIFF_LINES)); then + printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" + echo "[truncated $((total - MAX_DIFF_LINES)) lines]" + else + printf '%s\n' "$text" + fi +} + +# --- Not a git repo --- +if ! gitq rev-parse --git-dir >/dev/null 2>&1; then + echo "=== REPO ===" + echo "is_git_repo: false" + exit 0 +fi + +# --- Basic repo info (always shown) --- +head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" +head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" + +echo "=== REPO ===" +if [[ -n "$head_branch" ]]; then + echo "branch: $head_branch" +else + echo "detached_at: $head_sha" +fi + +# Detect base branch: origin/HEAD, then origin/main|master, then local main|master +base_ref="" +origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" +for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do + [[ -n "$candidate" ]] || continue + if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then + base_ref="$candidate" + break + fi +done + +on_base=false +if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then + on_base=true +fi + +has_merge_base=false +if [[ -n "$base_ref" ]]; then + echo "base: $base_ref" + if ! $on_base; then + if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then + has_merge_base=true + else + echo "note: no merge base between $base_ref and HEAD (unrelated histories)" + fi + ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" + behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" + echo "ahead: $ahead" + echo "behind: $behind" + fi +fi + +found_activity=false + +# --- Working tree: staged / unstaged / untracked --- +staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" +unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" +untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" + +if [[ -n "$staged_files" ]]; then + found_activity=true + echo "" + echo "=== STAGED ===" + echo "$staged_files" + emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$unstaged_files" ]]; then + found_activity=true + echo "" + echo "=== UNSTAGED ===" + echo "$unstaged_files" + emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$untracked_files" ]]; then + found_activity=true + echo "" + echo "=== UNTRACKED ===" + echo "$untracked_files" +fi + +# --- Unpushed commits --- +tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" +unpushed="" + +if [[ -n "$tracking_branch" ]]; then + unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" +fi + +if [[ -n "$unpushed" ]]; then + found_activity=true + echo "" + echo "=== UNPUSHED ===" + echo "tracking: $tracking_branch" + echo "$unpushed" +fi + +# --- Branch work (feature branch vs base) --- +if ! $on_base && [[ -n "$base_ref" ]]; then + branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" + if [[ -n "$branch_commits" ]]; then + found_activity=true + echo "" + echo "=== BRANCH COMMITS ===" + echo "$branch_commits" + fi + + if $has_merge_base; then + committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + if [[ -n "$committed_files" ]]; then + found_activity=true + echo "" + echo "=== CHANGED FILES ===" + echo "$committed_files" + emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + fi + fi +fi + +if $found_activity; then + exit 0 +fi + +# --- Repo activity (everything clean, nothing ahead) --- +active_branches="" +if [[ -n "$base_ref" ]]; then + active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" +fi + +if [[ -n "$active_branches" ]]; then + echo "" + echo "=== ACTIVE BRANCHES ===" + echo "$active_branches" +fi + +# Open issues (requires git-wait for platform detection, plus gh or tea) +if [[ -x "$SCRIPT_DIR/git-wait" ]]; then + platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" + issues="" + issues_err="" + errfile="$(mktemp)" + case "$platform" in + github) + if command -v gh >/dev/null 2>&1; then + issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" + fi + ;; + gitea) + if command -v tea >/dev/null 2>&1; then + issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" + fi + ;; + esac + if [[ -n "$issues_err" ]]; then + detail="$(head -n 1 "$errfile" 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + echo "note: $issues_err${detail:+: $detail}" + elif [[ -n "$issues" && "$issues" != "[]" ]]; then + formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + if [[ -n "$formatted" ]]; then + echo "$formatted" + else + echo "note: could not parse issue list" + fi + fi + rm -f "$errfile" +fi + +# Recent commits on default branch for context +echo "" +echo "=== RECENT COMMITS ===" +gitq log --oneline -10 2>/dev/null || true + +# Nothing at all +if [[ -z "$active_branches" ]]; then + echo "" + echo "=== STATUS ===" + echo "clean: true" +fi diff --git a/plugins-opencode/session/src/index.ts b/plugins-opencode/session/src/index.ts new file mode 100644 index 0000000..9b7a482 --- /dev/null +++ b/plugins-opencode/session/src/index.ts @@ -0,0 +1,8 @@ +import { Plugin } from "@opencode/plugin" + +// M0 scaffold: proves the server part loads. M4 adds the orchestrate_build +// tool and the worktree/plan/rename native surfaces. +export default Plugin.define({ + id: "agent-toolkit.session", + setup() {}, +}) diff --git a/tests/opencode/test-sync.sh b/tests/opencode/test-sync.sh new file mode 100644 index 0000000..a89e49b --- /dev/null +++ b/tests/opencode/test-sync.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# test-sync.sh — target-aware vendoring in utils/sync.sh. +# +# Builds a sandbox repo (fake utils/ + plugin dirs for both targets), then +# exercises sync, --check cleanliness, and drift detection on each target. +# Never touches the real plugins-* trees. +# +# Usage: bash tests/opencode/test-sync.sh [filter] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)" +REPO="$SCRIPT_DIR/.." + +PASS=0 +FAIL=0 +FILTER="${1:-}" + +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +pass() { + printf " \033[32m✓\033[0m %s\n" "$1" + ((PASS++)) || true +} +fail() { + printf " \033[31m✗\033[0m %s (%s)\n" "$1" "$2" + ((FAIL++)) || true +} +# check <label> <expected: "0" or "nonzero"> <actual-exit-code> [detail] +check() { + if [[ -n "$FILTER" ]] && ! echo "$1" | grep -qi "$FILTER"; then return; fi + local ok + if [[ "$2" == "0" ]]; then + [[ "$3" -eq 0 ]] && ok=1 || ok=0 + else + [[ "$3" -ne 0 ]] && ok=1 || ok=0 + fi + if [[ $ok -eq 1 ]]; then pass "$1"; else fail "$1" "exit=$3 ${4:-}"; fi +} + +# run <cmd...> — runs possibly-failing command, sets RC/OUT/ERR +RC=0 +OUT="" +ERR="" +run() { + RC=0 + OUT=$("$@" 2>"$TMP/stderr") || RC=$? + ERR=$(cat "$TMP/stderr") +} + +# --- sandbox --------------------------------------------------------------- +# Mirror the real manifest's plugin dirs so the real sync.sh runs unmodified. +S="$TMP/repo" +mkdir -p "$S/utils" +cp "$REPO/utils/sync.sh" "$S/utils/" +for util in inbox git-wait branch sitrep hook-compat.sh detect-schema.sh validate-frontmatter.sh; do + cp "$REPO/utils/$util" "$S/utils/" +done +for p in format-on-save git-tools kb-capture inbox notify-on-stop session; do + mkdir -p "$S/plugins-claude/$p" +done +for p in git-tools inbox session; do + mkdir -p "$S/plugins-opencode/$p" +done + +sync() { bash "$S/utils/sync.sh" "$@"; } + +# --- sync populates both targets ------------------------------------------- +run sync +check "sync exits 0" 0 "$RC" "$OUT$ERR" +run cmp -s "$S/utils/inbox" "$S/plugins-claude/inbox/scripts/inbox" +check "claude inbox vendored" 0 "$RC" +run cmp -s "$S/utils/git-wait" "$S/plugins-opencode/git-tools/scripts/git-wait" +check "opencode git-tools vendored git-wait" 0 "$RC" +run cmp -s "$S/utils/branch" "$S/plugins-opencode/git-tools/scripts/branch" +check "opencode git-tools vendored branch" 0 "$RC" +run cmp -s "$S/utils/sitrep" "$S/plugins-opencode/git-tools/scripts/sitrep" +check "opencode git-tools vendored sitrep" 0 "$RC" +# claude git-tools must NOT receive branch/sitrep (manifest is per-target) +run test ! -e "$S/plugins-claude/git-tools/scripts/branch" +check "claude git-tools does not receive branch (target-aware manifest)" 0 "$RC" + +# claude session receives branch + sitrep (canonicalized from its scripts dir) +run cmp -s "$S/utils/branch" "$S/plugins-claude/session/scripts/branch" +check "claude session vendored branch" 0 "$RC" +run cmp -s "$S/utils/sitrep" "$S/plugins-claude/session/scripts/sitrep" +check "claude session vendored sitrep" 0 "$RC" + +# --- --check clean after sync ------------------------------------------------ +run sync --check +check "--check clean after sync" 0 "$RC" "$OUT$ERR" + +# --- drift on the claude target is detected ---------------------------------- +echo "# tampered" >>"$S/plugins-claude/inbox/scripts/inbox" +run sync --check +check "--check fails on claude-target drift" nonzero "$RC" + +# --- drift on the opencode target is detected --------------------------------- +run sync # resync first +echo "# tampered" >>"$S/plugins-opencode/inbox/scripts/inbox" +run sync --check +check "--check fails on opencode-target drift" nonzero "$RC" +if [[ -z "$FILTER" ]] || echo "opencode drift names path" | grep -qi "$FILTER"; then + if echo "$ERR" | grep -q "plugins-opencode/inbox/scripts/inbox"; then + pass "--check names the drifted opencode path" + else + fail "--check names the drifted opencode path" "stderr: $ERR" + fi +fi + +# --- missing vendored file is drift -------------------------------------------- +run sync +rm "$S/plugins-opencode/session/scripts/git-wait" +run sync --check +check "--check fails on missing vendored file" nonzero "$RC" + +# --- missing canonical source is a hard error ----------------------------------- +run sync +rm "$S/utils/branch" +run sync --check +check "missing canonical source exits non-zero" nonzero "$RC" + +echo "" +echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" +[[ $FAIL -eq 0 ]] diff --git a/tests/opencode/test-validate-opencode.sh b/tests/opencode/test-validate-opencode.sh new file mode 100644 index 0000000..149c0ab --- /dev/null +++ b/tests/opencode/test-validate-opencode.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# test-validate-opencode.sh — the OpenCode structural validator itself. +# +# Copies .github/scripts/validate-opencode.sh into a sandbox repo layout and +# feeds it a clean fixture tree (must pass) and a dirty one (must fail with +# each failure class named). Also asserts the real plugins-opencode/ tree +# passes the real validator. +# +# Usage: bash tests/opencode/test-validate-opencode.sh [filter] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)" +REPO="$SCRIPT_DIR/.." +VALIDATOR="$REPO/.github/scripts/validate-opencode.sh" + +PASS=0 +FAIL=0 +FILTER="${1:-}" + +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +pass() { + printf " \033[32m✓\033[0m %s\n" "$1" + ((PASS++)) || true +} +fail() { + printf " \033[31m✗\033[0m %s (%s)\n" "$1" "$2" + ((FAIL++)) || true +} + +RC=0 +OUT="" +run() { + RC=0 + OUT=$("$@" 2>&1) || RC=$? +} + +# expect_output <label> <pattern> +expect_output() { + if [[ -n "$FILTER" ]] && ! echo "$1" | grep -qi "$FILTER"; then return; fi + if echo "$OUT" | grep -q "$2"; then pass "$1"; else fail "$1" "no match for: $2"; fi +} + +# --- build a clean fixture repo -------------------------------------------- +mk_clean() { + local S="$1" + mkdir -p "$S/.github/scripts" "$S/plugins-opencode/inbox/src" \ + "$S/plugins-opencode/inbox/scripts" "$S/plugins-opencode/inbox/skills/show" \ + "$S/plugins-opencode/inbox/commands" "$S/plugins-opencode/session/src" + cp "$VALIDATOR" "$S/.github/scripts/" + cat >"$S/plugins-opencode/inbox/package.json" <<'EOF' +{ + "name": "opencode-agent-toolkit-inbox", + "version": "0.1.0", + "type": "module", + "exports": { ".": "./src/index.ts" } +} +EOF + cat >"$S/plugins-opencode/session/package.json" <<'EOF' +{ + "name": "opencode-agent-toolkit-session", + "version": "0.1.0", + "type": "module", + "exports": { ".": "./src/index.ts" } +} +EOF + echo 'export default {}' >"$S/plugins-opencode/session/src/index.ts" + echo 'export default {}' >"$S/plugins-opencode/inbox/src/index.ts" + printf -- '---\nname: Show\ndescription: Show open items\n---\n\nList the inbox.\n' \ + >"$S/plugins-opencode/inbox/skills/show/SKILL.md" + printf -- '---\ndescription: show inbox\n---\n\n!`echo hi`\n' \ + >"$S/plugins-opencode/inbox/commands/show.md" + printf '{\n // a comment\n "formatter": true,\n}\n' >"$S/plugins-opencode/inbox/opencode.jsonc" + printf '#!/usr/bin/env bash\necho hi\n' >"$S/plugins-opencode/inbox/scripts/inbox" + chmod +x "$S/plugins-opencode/inbox/scripts/inbox" +} + +# --- clean fixture passes ---------------------------------------------------- +S="$TMP/clean" +mk_clean "$S" +run bash "$S/.github/scripts/validate-opencode.sh" +if [[ -z "$FILTER" ]] || echo "clean fixture passes" | grep -qi "$FILTER"; then + if [[ $RC -eq 0 ]]; then pass "clean fixture passes"; else fail "clean fixture passes" "exit=$RC: $OUT"; fi +fi + +# --- dirty fixture fails, naming every failure class ------------------------ +S="$TMP/dirty" +mk_clean "$S" +P="$S/plugins-opencode/inbox" +echo '{ broken' >"$P/broken.json" +cat >"$P/package.json" <<'EOF' +{ + "name": "opencode-agent-toolkit-inbox", + "version": "0.1.0", + "type": "module", + "exports": { ".": "./src/missing.ts" } +} +EOF +printf -- '---\nname: NoDesc\n---\n\nbody\n' >"$P/skills/show/SKILL.md" +printf -- '---\ndescription: empty body\n---\n\n' >"$P/commands/show.md" +printf 'uses ${CLAUDE_PLUGIN_ROOT}/scripts/inbox\n' >"$P/leak.md" +chmod -x "$P/scripts/inbox" +run bash "$S/.github/scripts/validate-opencode.sh" +if [[ $RC -ne 0 ]]; then pass "dirty fixture fails"; else fail "dirty fixture fails" "exit=0: $OUT"; fi +expect_output "names invalid JSON" "broken.json — invalid JSON" +expect_output "names missing export target" "export target missing" +expect_output "names missing skill description" "missing required field: description" +expect_output "names empty command body" "empty command body" +expect_output "names Claude leakage" "Claude var in OpenCode tree" +expect_output "names non-executable script" "not executable" + +# --- real tree passes the real validator -------------------------------------- +run bash "$VALIDATOR" +if [[ -z "$FILTER" ]] || echo "real tree passes" | grep -qi "$FILTER"; then + if [[ $RC -eq 0 ]]; then pass "real plugins-opencode/ passes validator"; else fail "real plugins-opencode/ passes validator" "exit=$RC: $OUT"; fi +fi + +echo "" +echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" +[[ $FAIL -eq 0 ]] diff --git a/utils/branch b/utils/branch new file mode 100755 index 0000000..98f16e5 --- /dev/null +++ b/utils/branch @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# branch - Git branch operations for session workflows +# Exit codes: 0 success (including -h/--help), 1 bad usage or invalid name, 2 git error +# +# Subcommands: +# create <name> Create and switch to a new branch + +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: branch <subcommand> [args] + +Subcommands: + create <name> Create and switch to a new branch +EOF +} + +die() { echo "Error: $*" >&2; exit 2; } + +[[ $# -ge 1 ]] || { usage >&2; exit 1; } + +cmd="$1"; shift + +case "$cmd" in + create) + [[ $# -eq 1 ]] || { echo "Usage: branch create <name>" >&2; exit 1; } + name="$1" + [[ "$name" != -* ]] || { echo "Error: branch name must not start with '-': $name" >&2; exit 1; } + git check-ref-format --branch "$name" >/dev/null 2>&1 || { echo "Error: invalid branch name: $name" >&2; exit 1; } + if git show-ref --verify --quiet "refs/heads/$name"; then + die "branch '$name' already exists" + fi + git switch -c "$name" || die "failed to create branch '$name'" + ;; + -h|--help) usage ;; + *) echo "Unknown subcommand: $cmd" >&2; usage >&2; exit 1 ;; +esac diff --git a/utils/sitrep b/utils/sitrep new file mode 100755 index 0000000..558f9e3 --- /dev/null +++ b/utils/sitrep @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# sitrep - Situation report for a git repository +# Always shows working-tree state (staged/unstaged/untracked) together with +# committed context, and falls back to broader repo activity only when +# nothing else is actionable. +# +# Sections: +# 1. Working tree (staged/unstaged/untracked) +# 2. Unpushed commits (ahead of remote tracking branch) +# 3. Branch work (commits on feature branch vs base) +# 4. Repo activity (active branches, open issues) - only when 1-3 are empty +# +# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). +# +# Exit codes: 0 success (including -h/--help), 1 bad usage + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" + +usage() { + cat <<'EOF' +Usage: sitrep [directory] + +Situation report for a git repository. Shows working-tree changes plus +unpushed and branch commits, expanding to broader repo activity only +when everything is clean. + +If directory is omitted, uses the current working directory. +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +if [[ $# -gt 1 ]]; then + usage >&2 + exit 1 +fi + +dir="${1:-.}" +cd "$dir" + +gitq() { + git -c core.quotepath=false "$@" +} + +# Print a diff section, truncated to MAX_DIFF_LINES. +emit_diff() { + local title="$1" text="$2" total + [[ -n "$text" ]] || return 0 + total="$(printf '%s\n' "$text" | wc -l)" + echo "" + echo "=== $title ===" + if ((total > MAX_DIFF_LINES)); then + printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" + echo "[truncated $((total - MAX_DIFF_LINES)) lines]" + else + printf '%s\n' "$text" + fi +} + +# --- Not a git repo --- +if ! gitq rev-parse --git-dir >/dev/null 2>&1; then + echo "=== REPO ===" + echo "is_git_repo: false" + exit 0 +fi + +# --- Basic repo info (always shown) --- +head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" +head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" + +echo "=== REPO ===" +if [[ -n "$head_branch" ]]; then + echo "branch: $head_branch" +else + echo "detached_at: $head_sha" +fi + +# Detect base branch: origin/HEAD, then origin/main|master, then local main|master +base_ref="" +origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" +for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do + [[ -n "$candidate" ]] || continue + if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then + base_ref="$candidate" + break + fi +done + +on_base=false +if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then + on_base=true +fi + +has_merge_base=false +if [[ -n "$base_ref" ]]; then + echo "base: $base_ref" + if ! $on_base; then + if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then + has_merge_base=true + else + echo "note: no merge base between $base_ref and HEAD (unrelated histories)" + fi + ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" + behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" + echo "ahead: $ahead" + echo "behind: $behind" + fi +fi + +found_activity=false + +# --- Working tree: staged / unstaged / untracked --- +staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" +unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" +untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" + +if [[ -n "$staged_files" ]]; then + found_activity=true + echo "" + echo "=== STAGED ===" + echo "$staged_files" + emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$unstaged_files" ]]; then + found_activity=true + echo "" + echo "=== UNSTAGED ===" + echo "$unstaged_files" + emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$untracked_files" ]]; then + found_activity=true + echo "" + echo "=== UNTRACKED ===" + echo "$untracked_files" +fi + +# --- Unpushed commits --- +tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" +unpushed="" + +if [[ -n "$tracking_branch" ]]; then + unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" +fi + +if [[ -n "$unpushed" ]]; then + found_activity=true + echo "" + echo "=== UNPUSHED ===" + echo "tracking: $tracking_branch" + echo "$unpushed" +fi + +# --- Branch work (feature branch vs base) --- +if ! $on_base && [[ -n "$base_ref" ]]; then + branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" + if [[ -n "$branch_commits" ]]; then + found_activity=true + echo "" + echo "=== BRANCH COMMITS ===" + echo "$branch_commits" + fi + + if $has_merge_base; then + committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + if [[ -n "$committed_files" ]]; then + found_activity=true + echo "" + echo "=== CHANGED FILES ===" + echo "$committed_files" + emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + fi + fi +fi + +if $found_activity; then + exit 0 +fi + +# --- Repo activity (everything clean, nothing ahead) --- +active_branches="" +if [[ -n "$base_ref" ]]; then + active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" +fi + +if [[ -n "$active_branches" ]]; then + echo "" + echo "=== ACTIVE BRANCHES ===" + echo "$active_branches" +fi + +# Open issues (requires git-wait for platform detection, plus gh or tea) +if [[ -x "$SCRIPT_DIR/git-wait" ]]; then + platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" + issues="" + issues_err="" + errfile="$(mktemp)" + case "$platform" in + github) + if command -v gh >/dev/null 2>&1; then + issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" + fi + ;; + gitea) + if command -v tea >/dev/null 2>&1; then + issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" + fi + ;; + esac + if [[ -n "$issues_err" ]]; then + detail="$(head -n 1 "$errfile" 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + echo "note: $issues_err${detail:+: $detail}" + elif [[ -n "$issues" && "$issues" != "[]" ]]; then + formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + if [[ -n "$formatted" ]]; then + echo "$formatted" + else + echo "note: could not parse issue list" + fi + fi + rm -f "$errfile" +fi + +# Recent commits on default branch for context +echo "" +echo "=== RECENT COMMITS ===" +gitq log --oneline -10 2>/dev/null || true + +# Nothing at all +if [[ -z "$active_branches" ]]; then + echo "" + echo "=== STATUS ===" + echo "clean: true" +fi diff --git a/utils/sync.sh b/utils/sync.sh index 7eaea7b..9a9adaf 100755 --- a/utils/sync.sh +++ b/utils/sync.sh @@ -9,8 +9,15 @@ # Edit the canonical file in utils/, run this script, commit the result. # CI calls `sync.sh --check` to fail on drift. # +# Vendoring is target-aware: each harness (plugins-claude/, plugins-opencode/) +# has its own manifest because the two harnesses consume different util sets +# per plugin (e.g. opencode git-tools vendors branch + sitrep; claude git-tools +# does not). A plugin dir listed in a manifest must already exist; --check +# covers every target, so OpenCode drift fails CI the same way Claude drift +# does. +# # Usage: -# utils/sync.sh # copy canonical → each plugin's scripts/ +# utils/sync.sh # copy canonical → each target's plugin scripts/ # utils/sync.sh --check # exit non-zero on drift, no changes set -euo pipefail @@ -18,71 +25,86 @@ set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" MODE="${1:-sync}" -# Vendoring manifest: PLUGIN → space-separated list of utils/ filenames. -# Every plugin listed below will receive a real copy of each util in its -# plugins-claude/<plugin>/scripts/ directory. Keys are quoted because shfmt +# Vendoring manifests: PLUGIN → space-separated list of utils/ filenames, +# per target. Every plugin listed receives a real copy of each util in its +# <target>/<plugin>/scripts/ directory. Keys are quoted because shfmt # otherwise reformats hyphens as arithmetic operators. -declare -A NEEDS=( - ["format-on-save"]="hook-compat.sh" - ["git-tools"]="git-wait" - ["kb-capture"]="detect-schema.sh validate-frontmatter.sh" - ["inbox"]="inbox" - ["notify-on-stop"]="hook-compat.sh inbox" - ["session"]="git-wait" +declare -A NEEDS_CLAUDE=( + ["format-on-save"]="hook-compat.sh" + ["git-tools"]="git-wait" + ["kb-capture"]="detect-schema.sh validate-frontmatter.sh" + ["inbox"]="inbox" + ["notify-on-stop"]="hook-compat.sh inbox" + # branch and sitrep are canonical in utils/ and vendored back here; they + # used to live only in this plugin's scripts/ dir. + ["session"]="git-wait branch sitrep" +) + +declare -A NEEDS_OPENCODE=( + ["git-tools"]="git-wait branch sitrep" + ["inbox"]="inbox" + ["session"]="git-wait branch sitrep" ) drift=0 synced=0 -for plugin in "${!NEEDS[@]}"; do - for util in ${NEEDS[$plugin]}; do - src="$ROOT/utils/$util" - dst="$ROOT/plugins-claude/$plugin/scripts/$util" +for target in claude opencode; do + declare -n NEEDS="NEEDS_${target^^}" + target_dir="$ROOT/plugins-$target" + + for plugin in "${!NEEDS[@]}"; do + for util in ${NEEDS[$plugin]}; do + src="$ROOT/utils/$util" + dst="$target_dir/$plugin/scripts/$util" - if [[ ! -f "$src" ]]; then - echo "ERROR: canonical source missing: utils/$util" >&2 - exit 1 - fi + if [[ ! -f "$src" ]]; then + echo "ERROR: canonical source missing: utils/$util" >&2 + exit 1 + fi - if [[ ! -d "$ROOT/plugins-claude/$plugin" ]]; then - echo "ERROR: plugin dir missing: plugins-claude/$plugin" >&2 - exit 1 - fi + if [[ ! -d "$target_dir/$plugin" ]]; then + echo "ERROR: plugin dir missing: plugins-$target/$plugin" >&2 + exit 1 + fi - case "$MODE" in - --check) - if [[ -L "$dst" ]]; then - echo "DRIFT: $dst is a symlink (run utils/sync.sh)" >&2 - drift=1 - elif [[ ! -f "$dst" ]]; then - echo "DRIFT: $dst missing (run utils/sync.sh)" >&2 - drift=1 - elif ! cmp -s "$src" "$dst"; then - echo "DRIFT: $dst differs from utils/$util (run utils/sync.sh)" >&2 - drift=1 - fi - ;; - sync) - [[ -L "$dst" ]] && rm "$dst" - if ! cmp -s "$src" "$dst" 2>/dev/null; then - cp -p "$src" "$dst" - synced=$((synced + 1)) - echo "synced: plugins-claude/$plugin/scripts/$util" - fi - ;; - *) - echo "Usage: $0 [--check]" >&2 - exit 2 - ;; - esac - done + case "$MODE" in + --check) + if [[ -L "$dst" ]]; then + echo "DRIFT: $dst is a symlink (run utils/sync.sh)" >&2 + drift=1 + elif [[ ! -f "$dst" ]]; then + echo "DRIFT: $dst missing (run utils/sync.sh)" >&2 + drift=1 + elif ! cmp -s "$src" "$dst"; then + echo "DRIFT: $dst differs from utils/$util (run utils/sync.sh)" >&2 + drift=1 + fi + ;; + sync) + [[ -L "$dst" ]] && rm "$dst" + if ! cmp -s "$src" "$dst" 2>/dev/null; then + mkdir -p "$target_dir/$plugin/scripts" + cp -p "$src" "$dst" + synced=$((synced + 1)) + echo "synced: plugins-$target/$plugin/scripts/$util" + fi + ;; + *) + echo "Usage: $0 [--check]" >&2 + exit 2 + ;; + esac + done + done + unset -n NEEDS done if [[ "$MODE" == "--check" ]]; then - [[ $drift -eq 0 ]] || exit 1 - echo "no drift — all vendored copies match utils/" + [[ $drift -eq 0 ]] || exit 1 + echo "no drift — all vendored copies match utils/" elif [[ $synced -eq 0 ]]; then - echo "already in sync — nothing to do" + echo "already in sync — nothing to do" else - echo "$synced file(s) synced" + echo "$synced file(s) synced" fi From eabf4ad51cb3e254e2062be2330d4d2ee695b47b Mon Sep 17 00:00:00 2001 From: Logan Gagne <logan.gagne@gmail.com> Date: Tue, 10 Nov 2026 17:12:19 -0500 Subject: [PATCH 2/6] =?UTF-8?q?feat(opencode):=20M1=20format-on-save=20?= =?UTF-8?q?=E2=80=94=20formatter=20config=20mirroring=20the=20Claude=20hoo?= =?UTF-8?q?k?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Config-only port: OpenCode's built-in formatter replaces the PostToolUse hook. The snippet mirrors the hook's dispatch table exactly (same tools, flags, extension set) so cross-harness edits produce no second diff; the prettier built-in's extension set is narrowed to drop its .md/.toml collision with rumdl/taplo. test-format-on-save-parity.sh parses both the hook's case block and the jsonc and fails on any drift in either direction (39 checks). Refs #236 --- plugins-opencode/format-on-save/README.md | 39 ++++++ .../format-on-save/opencode.jsonc | 24 ++++ tests/opencode/test-format-on-save-parity.sh | 115 ++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 plugins-opencode/format-on-save/README.md create mode 100644 plugins-opencode/format-on-save/opencode.jsonc create mode 100644 tests/opencode/test-format-on-save-parity.sh diff --git a/plugins-opencode/format-on-save/README.md b/plugins-opencode/format-on-save/README.md new file mode 100644 index 0000000..9017b0e --- /dev/null +++ b/plugins-opencode/format-on-save/README.md @@ -0,0 +1,39 @@ +# format-on-save (OpenCode) + +Config-only port of the Claude `format-on-save` hook. **No code, no plugin** — +OpenCode's built-in `formatter` runs after `write`/`edit`/`patch`, which is +exactly what the Claude `PostToolUse` hook did. + +The `formatter` object in [`opencode.jsonc`](opencode.jsonc) mirrors the repo's +dispatch table (same tools, same flags, same extension set) so a file formatted +by either harness is byte-identical. A parity test +(`tests/opencode/test-format-on-save-parity.sh`) fails CI if the Claude script +and this snippet ever disagree. + +## Install + +Copy the `formatter` object from [`opencode.jsonc`](opencode.jsonc) into your +global `~/.config/opencode/opencode.jsonc` (mirrors the global Claude plugin) +or a project `opencode.jsonc` (stricter: shared repos all get the same rules). + +Formatters are **opt-in** in OpenCode: setting the `formatter` object is what +enables them. A bare `"formatter": true` enables OpenCode's built-in defaults +instead, which differ from this repo's (prettier claims `.md`/`.toml`, shfmt +flags differ, bare `rustfmt` ≠ `cargo fmt`). + +## Parity notes + +- **Never blocks**: OpenCode logs a formatter failure and keeps the edit — + same always-exit-0 behavior as the hook. +- **Missing tool → skip**: built-ins run only when their executable is found; + a custom command that isn't found fails and is skipped. +- **`.rs` divergence (accepted)**: the hook prefers `cargo fmt` from the + nearest `Cargo.toml`; OpenCode formatters are per-file, so this uses + `rustfmt "$FILE"`. `rustfmt` still reads `rustfmt.toml` upward; only the + cargo manifest walk is not replicated. +- **Built-in detection rules**: OpenCode gates some built-ins on project + context (e.g. built-in `prettier` wants a `prettier` dependency in + `package.json`, `ruff` wants a Ruff config). The Claude hook only checks + `command -v`. In a project without those markers, prettier/ruff may not run + in OpenCode even when installed globally — add the project marker or accept + the skip. diff --git a/plugins-opencode/format-on-save/opencode.jsonc b/plugins-opencode/format-on-save/opencode.jsonc new file mode 100644 index 0000000..b71a073 --- /dev/null +++ b/plugins-opencode/format-on-save/opencode.jsonc @@ -0,0 +1,24 @@ +{ + "$schema": "https://opencode.ai/config.json", + // Mirror of plugins-claude/format-on-save/scripts/format-on-save.sh. + // Same tools, same flags, same extension set, so a file edited in Claude + // Code and then OpenCode produces no further diff. Requires "formatter" + // to be enabled (this object enables it). tests/opencode/ + // test-format-on-save-parity.sh fails CI if the two dispatch tables drift. + "formatter": { + // Override the built-in: repo pins -i 2 -ci, built-in flags differ. + "shfmt": { "command": ["shfmt", "-w", "-i", "2", "-ci", "$FILE"], "extensions": [".sh", ".bash"] }, + // Override the built-in's extension set: prettier also claims .md/.toml/ + // .mdx/…, which this repo formats with rumdl/taplo instead. + "prettier": { "command": ["prettier", "--write", "$FILE"], "extensions": [".js", ".jsx", ".ts", ".tsx", ".json", ".yml", ".yaml", ".css", ".html"] }, + "ktlint": { "command": ["ktlint", "--format", "$FILE"], "extensions": [".kt", ".kts"] }, + "ruff": { "command": ["ruff", "format", "$FILE"], "extensions": [".py", ".pyi"] }, + // The hook prefers `cargo fmt` (walks to Cargo.toml); OpenCode formatters + // are per-file, so rustfmt runs directly. rustfmt still reads + // rustfmt.toml upward; only the cargo-manifest walk is not replicated. + "rustfmt": { "command": ["rustfmt", "$FILE"], "extensions": [".rs"] }, + "rumdl": { "command": ["rumdl", "check", "--fix", "$FILE"], "extensions": [".md"] }, + "google-java-format": { "command": ["google-java-format", "--replace", "$FILE"], "extensions": [".java"] }, + "taplo": { "command": ["taplo", "format", "$FILE"], "extensions": [".toml"] } + } +} diff --git a/tests/opencode/test-format-on-save-parity.sh b/tests/opencode/test-format-on-save-parity.sh new file mode 100644 index 0000000..eb6fe45 --- /dev/null +++ b/tests/opencode/test-format-on-save-parity.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# test-format-on-save-parity.sh — the OpenCode formatter config must mirror +# the Claude hook's dispatch table (plugins-claude/format-on-save/ +# scripts/format-on-save.sh). Same extension set, same tool + flags, so a +# file formatted by either harness is byte-identical. If someone edits one +# side and forgets the other, this fails. +# +# Usage: bash tests/opencode/test-format-on-save-parity.sh [filter] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)" +REPO="$SCRIPT_DIR/.." +HOOK="$REPO/plugins-claude/format-on-save/scripts/format-on-save.sh" +SNIPPET="$REPO/plugins-opencode/format-on-save/opencode.jsonc" + +PASS=0 +FAIL=0 +FILTER="${1:-}" + +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +pass() { + printf " \033[32m✓\033[0m %s\n" "$1" + ((PASS++)) || true +} +fail() { + printf " \033[31m✗\033[0m %s (%s)\n" "$1" "$2" + ((FAIL++)) || true +} + +# --- extract the hook's dispatch: one "ext<TAB>fmt_fn" line per extension --- +# Drop the `case`/`esac` lines, flatten, split arms on ;;, split alternates on |. +sed -n '/^case "\$ext" in/,/^esac/p' "$HOOK" | sed '1d;$d' | tr '\n' ' ' | + sed -E 's/ *\| */ /g; s/;;/\n/g' | + awk -F')' '/fmt_/ { + fn = $2; sub(/^ +/, "", fn); sub(/ +.*$/, "", fn) + n = split($1, a, / +/) + for (i = 1; i <= n; i++) if (a[i] ~ /^[a-z]+$/) print a[i] "\t" fn + }' >"$TMP/extfn" + +if [[ ! -s "$TMP/extfn" ]]; then + fail "parsed hook dispatch table" "empty parse — did the case block shape change?" + echo "" + echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" + exit 1 +fi +pass "parsed hook dispatch table ($(wc -l <"$TMP/extfn") extensions)" + +# fmt_<fn> → argv: the `if ! <cmd> "$file_path" 2>&1` line, with $FILE for +# "$file_path". fmt_cargo_fmt is special-cased: per-file OpenCode formatters +# run rustfmt directly (documented divergence). +argv_for() { + local fn="$1" + if [[ "$fn" == "fmt_cargo_fmt" ]]; then + echo "rustfmt \$FILE" + return + fi + awk -v fn="$fn" '$0 == fn"() {" {infn=1} infn && /if ! / && !/command -v/ { + sub(/^ +if ! /, "") + sub(/ "[$]file_path" 2>&1; then/, " $FILE") + print + exit + } infn && /^}/ {infn=0}' "$HOOK" +} + +: >"$TMP/script_table" +while IFS=$'\t' read -r ext fn; do + argv=$(argv_for "$fn") + if [[ -z "$argv" ]]; then + fail "extract command for $fn" "no 'if ! …' invocation found — did the function shape change?" + continue + fi + printf '%s\t%s\n' "$ext" "$argv" >>"$TMP/script_table" +done <"$TMP/extfn" + +# --- extract the snippet's table: one "ext<TAB>argv" line per extension ---- +node -e ' + const s = require("fs").readFileSync(process.argv[1], "utf8") + .replace(/^\s*\/\/.*$/gm, "") + .replace(/,(\s*[}\]])/g, "$1"); + const fmt = JSON.parse(s).formatter + for (const [name, def] of Object.entries(fmt)) + for (const ext of def.extensions) + console.log(ext.slice(1) + "\t" + def.command.join(" ")) +' "$SNIPPET" >"$TMP/snippet_table" + +# --- compare ----------------------------------------------------------------- +# Every extension the hook formats must be formatted identically by the snippet. +while IFS=$'\t' read -r ext argv; do + if [[ -n "$FILTER" ]] && ! echo "$ext" | grep -qi "$FILTER"; then continue; fi + actual=$(awk -F'\t' -v e="$ext" '$1 == e {print $2}' "$TMP/snippet_table") + if [[ -z "$actual" ]]; then + fail "$ext covered by snippet" "missing from formatter config" + elif [[ "$actual" == "$argv" ]]; then + pass "$ext → $argv" + else + fail "$ext command parity" "hook: '$argv' vs snippet: '$actual'" + fi +done <"$TMP/script_table" + +# No extra extensions in the snippet the hook doesn't format (prettier's +# built-in grab-bag must not sneak .md/.toml back in). +while IFS=$'\t' read -r ext argv; do + if ! grep -q "^$ext"$'\t' "$TMP/script_table"; then + fail "snippet has no extra ext: $ext" "not formatted by the Claude hook" + else + pass "snippet has no extra ext: $ext" + fi +done <"$TMP/snippet_table" + +echo "" +echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" +[[ $FAIL -eq 0 ]] From a8e46a916eea90602b8a0390ebb11924aa103e6d Mon Sep 17 00:00:00 2001 From: Logan Gagne <logan.gagne@gmail.com> Date: Tue, 10 Nov 2026 17:16:50 -0500 Subject: [PATCH 3/6] =?UTF-8?q?feat(opencode):=20M2=20git-tools=20?= =?UTF-8?q?=E2=80=94=20skills=20+=20/ship=20command,=20vendored=20scripts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port git-wait + ship skills with OpenCode-only edits: skill-relative script paths (base dir is provided at load), Claude frontmatter dropped, $ARGUMENTS wording generalized. /ship command door passes arguments through. Ships as a config snippet (skills array + commands), no code. sync.sh OpenCode manifest now supports nested keys so scripts vendor into each skill's own dir (private base dir pattern). tests/opencode: git-tools port fidelity suite (27 checks: vendored copies byte-identical, no Claude leakage, ship's 9 steps intact, body diff vs Claude original modulo intended edits); sync fixture updated. Refs #236 --- plugins-opencode/git-tools/README.md | 42 + plugins-opencode/git-tools/commands/ship.md | 11 + plugins-opencode/git-tools/opencode.jsonc | 15 + plugins-opencode/git-tools/scripts/branch | 38 - plugins-opencode/git-tools/scripts/sitrep | 246 --- .../git-tools/skills/git-wait/SKILL.md | 158 ++ .../{ => skills/git-wait}/scripts/git-wait | 0 .../git-tools/skills/ship/SKILL.md | 435 +++++ .../git-tools/skills/ship/scripts/git-wait | 1460 +++++++++++++++++ tests/opencode/test-git-tools-port.sh | 107 ++ tests/opencode/test-sync.sh | 14 +- utils/sync.sh | 6 +- 12 files changed, 2240 insertions(+), 292 deletions(-) create mode 100644 plugins-opencode/git-tools/README.md create mode 100644 plugins-opencode/git-tools/commands/ship.md create mode 100644 plugins-opencode/git-tools/opencode.jsonc delete mode 100755 plugins-opencode/git-tools/scripts/branch delete mode 100755 plugins-opencode/git-tools/scripts/sitrep create mode 100644 plugins-opencode/git-tools/skills/git-wait/SKILL.md rename plugins-opencode/git-tools/{ => skills/git-wait}/scripts/git-wait (100%) create mode 100644 plugins-opencode/git-tools/skills/ship/SKILL.md create mode 100755 plugins-opencode/git-tools/skills/ship/scripts/git-wait create mode 100644 tests/opencode/test-git-tools-port.sh diff --git a/plugins-opencode/git-tools/README.md b/plugins-opencode/git-tools/README.md new file mode 100644 index 0000000..b2e1ee3 --- /dev/null +++ b/plugins-opencode/git-tools/README.md @@ -0,0 +1,42 @@ +# git-tools (OpenCode) + +Skills + commands port of the Claude `git-tools` plugin. **No plugin code** — +`git-wait`, `branch`, and `sitrep` are platform-neutral bash over `gh`/`tea`/git +and run unchanged; they're vendored from `../../utils/` by `utils/sync.sh` +(CI fails on drift). + +## What's here + +- `skills/git-wait/` — the gh-vs-tea command map, platform detection, and the + blocking `pr wait` / `run watch` waiters. `scripts/git-wait` is vendored + inside the skill dir so the skill's relative paths resolve from its base dir. +- `skills/ship/` — the full merge-lifecycle orchestrator (stage → commit → + push → PR → CI watch → merge wait → post-merge run watch → default branch → + worktree cleanup). Same procedure as the Claude skill; `$ARGUMENTS` wording + became "arguments provided with the invocation". +- `commands/ship.md` — the `/ship` slash-command door for the ship skill. + +## Install + +Copy the `skills` and `commands` entries from [`opencode.jsonc`](opencode.jsonc) +into your `~/.config/opencode/opencode.jsonc`, pointing the skills path at your +checkout of this repo: + +```jsonc +{ + "skills": ["~/agent-toolkit/plugins-opencode/git-tools/skills"], + "commands": { "ship": { … } } +} +``` + +(OpenCode also auto-discovers `~/.claude/skills` and `.agents/skills` — if you +symlink this `skills/` dir into one of those, the `skills` entry is unnecessary.) + +## Notes + +- The Claude skill's `allowed-tools: Bash` frontmatter has no OpenCode + per-skill equivalent; these skills only run bash, which is allowed by + default. Tighten with a `permissions[]` rule or a dedicated agent if you + want a gate. +- `branch` and `sitrep` are vendored for the `session` plugin's skills; this + plugin only ships `git-wait` (same as its Claude counterpart). diff --git a/plugins-opencode/git-tools/commands/ship.md b/plugins-opencode/git-tools/commands/ship.md new file mode 100644 index 0000000..ffc4a82 --- /dev/null +++ b/plugins-opencode/git-tools/commands/ship.md @@ -0,0 +1,11 @@ +--- +description: Drive in-flight work through the full merge lifecycle (commit → PR → CI → merge → back to default branch) +--- + +Use the **ship** skill to take the current work through the full merge +lifecycle, following its procedure exactly. + +Additional arguments provided with this command (commit/PR title hints, +merge intent, `Closes #N` lines — see the skill's Arguments section): + +$ARGUMENTS diff --git a/plugins-opencode/git-tools/opencode.jsonc b/plugins-opencode/git-tools/opencode.jsonc new file mode 100644 index 0000000..b2165b7 --- /dev/null +++ b/plugins-opencode/git-tools/opencode.jsonc @@ -0,0 +1,15 @@ +{ + "$schema": "https://opencode.ai/config.json", + // git-tools for OpenCode: skills + a /ship command door, no plugin code. + // Point the skills entry at YOUR checkout of agent-toolkit (clone the repo + // once, reference it forever). Relative paths resolve from the directory + // OpenCode was started in, so prefer ~ or an absolute path here. + "skills": ["~/agent-toolkit/plugins-opencode/git-tools/skills"], + "commands": { + "ship": { + "description": "Drive in-flight work through the full merge lifecycle (commit → PR → CI → merge → back to default branch)", + "subtask": false, + "template": "Use the **ship** skill to take the current work through the full merge lifecycle, following its procedure exactly.\n\nAdditional arguments provided with this command (commit/PR title hints, merge intent, `Closes #N` lines — see the skill's Arguments section):\n\n$ARGUMENTS" + } + } +} diff --git a/plugins-opencode/git-tools/scripts/branch b/plugins-opencode/git-tools/scripts/branch deleted file mode 100755 index 98f16e5..0000000 --- a/plugins-opencode/git-tools/scripts/branch +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -# branch - Git branch operations for session workflows -# Exit codes: 0 success (including -h/--help), 1 bad usage or invalid name, 2 git error -# -# Subcommands: -# create <name> Create and switch to a new branch - -set -euo pipefail - -usage() { - cat <<'EOF' -Usage: branch <subcommand> [args] - -Subcommands: - create <name> Create and switch to a new branch -EOF -} - -die() { echo "Error: $*" >&2; exit 2; } - -[[ $# -ge 1 ]] || { usage >&2; exit 1; } - -cmd="$1"; shift - -case "$cmd" in - create) - [[ $# -eq 1 ]] || { echo "Usage: branch create <name>" >&2; exit 1; } - name="$1" - [[ "$name" != -* ]] || { echo "Error: branch name must not start with '-': $name" >&2; exit 1; } - git check-ref-format --branch "$name" >/dev/null 2>&1 || { echo "Error: invalid branch name: $name" >&2; exit 1; } - if git show-ref --verify --quiet "refs/heads/$name"; then - die "branch '$name' already exists" - fi - git switch -c "$name" || die "failed to create branch '$name'" - ;; - -h|--help) usage ;; - *) echo "Unknown subcommand: $cmd" >&2; usage >&2; exit 1 ;; -esac diff --git a/plugins-opencode/git-tools/scripts/sitrep b/plugins-opencode/git-tools/scripts/sitrep deleted file mode 100755 index 558f9e3..0000000 --- a/plugins-opencode/git-tools/scripts/sitrep +++ /dev/null @@ -1,246 +0,0 @@ -#!/usr/bin/env bash -# sitrep - Situation report for a git repository -# Always shows working-tree state (staged/unstaged/untracked) together with -# committed context, and falls back to broader repo activity only when -# nothing else is actionable. -# -# Sections: -# 1. Working tree (staged/unstaged/untracked) -# 2. Unpushed commits (ahead of remote tracking branch) -# 3. Branch work (commits on feature branch vs base) -# 4. Repo activity (active branches, open issues) - only when 1-3 are empty -# -# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). -# -# Exit codes: 0 success (including -h/--help), 1 bad usage - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" - -usage() { - cat <<'EOF' -Usage: sitrep [directory] - -Situation report for a git repository. Shows working-tree changes plus -unpushed and branch commits, expanding to broader repo activity only -when everything is clean. - -If directory is omitted, uses the current working directory. -EOF -} - -if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then - usage - exit 0 -fi - -if [[ $# -gt 1 ]]; then - usage >&2 - exit 1 -fi - -dir="${1:-.}" -cd "$dir" - -gitq() { - git -c core.quotepath=false "$@" -} - -# Print a diff section, truncated to MAX_DIFF_LINES. -emit_diff() { - local title="$1" text="$2" total - [[ -n "$text" ]] || return 0 - total="$(printf '%s\n' "$text" | wc -l)" - echo "" - echo "=== $title ===" - if ((total > MAX_DIFF_LINES)); then - printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" - echo "[truncated $((total - MAX_DIFF_LINES)) lines]" - else - printf '%s\n' "$text" - fi -} - -# --- Not a git repo --- -if ! gitq rev-parse --git-dir >/dev/null 2>&1; then - echo "=== REPO ===" - echo "is_git_repo: false" - exit 0 -fi - -# --- Basic repo info (always shown) --- -head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" -head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" - -echo "=== REPO ===" -if [[ -n "$head_branch" ]]; then - echo "branch: $head_branch" -else - echo "detached_at: $head_sha" -fi - -# Detect base branch: origin/HEAD, then origin/main|master, then local main|master -base_ref="" -origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" -for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do - [[ -n "$candidate" ]] || continue - if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then - base_ref="$candidate" - break - fi -done - -on_base=false -if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then - on_base=true -fi - -has_merge_base=false -if [[ -n "$base_ref" ]]; then - echo "base: $base_ref" - if ! $on_base; then - if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then - has_merge_base=true - else - echo "note: no merge base between $base_ref and HEAD (unrelated histories)" - fi - ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" - behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" - echo "ahead: $ahead" - echo "behind: $behind" - fi -fi - -found_activity=false - -# --- Working tree: staged / unstaged / untracked --- -staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" -unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" -untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" - -if [[ -n "$staged_files" ]]; then - found_activity=true - echo "" - echo "=== STAGED ===" - echo "$staged_files" - emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" -fi - -if [[ -n "$unstaged_files" ]]; then - found_activity=true - echo "" - echo "=== UNSTAGED ===" - echo "$unstaged_files" - emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" -fi - -if [[ -n "$untracked_files" ]]; then - found_activity=true - echo "" - echo "=== UNTRACKED ===" - echo "$untracked_files" -fi - -# --- Unpushed commits --- -tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" -unpushed="" - -if [[ -n "$tracking_branch" ]]; then - unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" -fi - -if [[ -n "$unpushed" ]]; then - found_activity=true - echo "" - echo "=== UNPUSHED ===" - echo "tracking: $tracking_branch" - echo "$unpushed" -fi - -# --- Branch work (feature branch vs base) --- -if ! $on_base && [[ -n "$base_ref" ]]; then - branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" - if [[ -n "$branch_commits" ]]; then - found_activity=true - echo "" - echo "=== BRANCH COMMITS ===" - echo "$branch_commits" - fi - - if $has_merge_base; then - committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" - if [[ -n "$committed_files" ]]; then - found_activity=true - echo "" - echo "=== CHANGED FILES ===" - echo "$committed_files" - emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" - fi - fi -fi - -if $found_activity; then - exit 0 -fi - -# --- Repo activity (everything clean, nothing ahead) --- -active_branches="" -if [[ -n "$base_ref" ]]; then - active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" -fi - -if [[ -n "$active_branches" ]]; then - echo "" - echo "=== ACTIVE BRANCHES ===" - echo "$active_branches" -fi - -# Open issues (requires git-wait for platform detection, plus gh or tea) -if [[ -x "$SCRIPT_DIR/git-wait" ]]; then - platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" - issues="" - issues_err="" - errfile="$(mktemp)" - case "$platform" in - github) - if command -v gh >/dev/null 2>&1; then - issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" - fi - ;; - gitea) - if command -v tea >/dev/null 2>&1; then - issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" - fi - ;; - esac - if [[ -n "$issues_err" ]]; then - detail="$(head -n 1 "$errfile" 2>/dev/null || true)" - echo "" - echo "=== OPEN ISSUES ===" - echo "note: $issues_err${detail:+: $detail}" - elif [[ -n "$issues" && "$issues" != "[]" ]]; then - formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" - echo "" - echo "=== OPEN ISSUES ===" - if [[ -n "$formatted" ]]; then - echo "$formatted" - else - echo "note: could not parse issue list" - fi - fi - rm -f "$errfile" -fi - -# Recent commits on default branch for context -echo "" -echo "=== RECENT COMMITS ===" -gitq log --oneline -10 2>/dev/null || true - -# Nothing at all -if [[ -z "$active_branches" ]]; then - echo "" - echo "=== STATUS ===" - echo "clean: true" -fi diff --git a/plugins-opencode/git-tools/skills/git-wait/SKILL.md b/plugins-opencode/git-tools/skills/git-wait/SKILL.md new file mode 100644 index 0000000..7e73488 --- /dev/null +++ b/plugins-opencode/git-tools/skills/git-wait/SKILL.md @@ -0,0 +1,158 @@ +--- +name: git-wait +description: >- + Guide for GitHub/Gitea CLI work. Use `gh` and `tea` DIRECTLY for issues, + PRs, CI runs, repo, and API calls — there is no wrapper anymore. Reach for + `git-wait` only to detect which platform a repo uses, and to block until a + PR merges or a CI run finishes, instead of hand-rolling a poll loop. +--- + +# git-wait + +All `scripts/...` paths below are relative to this skill's base directory +(provided when the skill loads). + +`git-wait` is **not** a CLI wrapper. It replaced `git-cli`, which was deleted. +For every GitHub/Gitea operation — listing, creating, commenting, merging, +closing, viewing logs, raw API calls — invoke `gh` or `tea` **directly**. +`git-wait` exists only for two things neither CLI gives you on its own: + +1. **Platform detection** — matching the git remote hostname against + configured `tea` logins, so a caller knows whether to reach for `gh` or + `tea`. +2. **Blocking waits** — `pr wait` blocks until a PR reaches a terminal state, + and `run watch` blocks until CI finishes, both with a progress-aware idle + timeout. Neither `gh` nor `tea` has an equivalent that covers both + platforms. + +**Never hand-roll a polling loop** (`until gh pr view ... | grep MERGED; do +sleep ...; done`) — use `git-wait pr wait` / `git-wait run watch` instead. +They already handle timeouts, idle detection, and terminal-state parsing +correctly on both platforms. + +## The three commands + +```bash +bash scripts/git-wait platform +``` + +Echoes `github` or `gitea` for the current repo's `origin` remote. Call this +once per session/task and branch on the result — every subsequent hosted-CLI +call needs to know which tool to use. + +```bash +bash scripts/git-wait pr wait --branch NAME \ + [--timeout 14400] [--idle-timeout 300] [--interval 15] [--alert-interval 300] +``` + +Blocks until the PR for `NAME` merges, closes, or conflicts. +Output: `status: merged|closed|blocked|timeout|error`, plus `pr_number`, +`url`, `duration`, and (when relevant) `reason`. + +```bash +bash scripts/git-wait run watch (--branch NAME | --sha SHA) \ + [--initial-delay 60] [--timeout 14400] [--idle-timeout 0] [--interval 15] \ + [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] [--max-poll-failures 10] +``` + +Blocks until CI finishes. +Output: `status: pass|fail|closed|timeout|no-workflow|error`, plus `url`, +`duration`, and (on failure) `failed_jobs`. Failed job logs are printed to +stderr. + +**Pick the right scope — this is a real trap.** `--branch` follows **one** run: +the newest correlated to that branch. That is correct for a PR branch, where a +push means a run. It is wrong on a **default branch**, where two merges landing +close together produce two runs — the newest going green ends the watch while +the other is still executing, and the watcher reports `status: pass`. + +`--sha` watches **every** run for one commit: pending while any of them is +pending, failing if any run (or any job inside one) failed. Use it for anything +post-merge — a release, publish, or deploy run — where you care about the runs +one specific merge caused. Pass one flag or the other, never both. + +`--sha` needs a full 40-character SHA. A short one is expanded via git when the +commit is resolvable locally and rejected otherwise, because `gh run list +--commit` matches nothing on a short SHA without erroring — which would +otherwise surface as a misleading `no-workflow`. + +**Patience defaults.** A running CI is never aborted for lack of visible +progress: `run watch --idle-timeout` defaults to `0` (disabled; pass N to opt in to +a no-progress window). `pr wait --idle-timeout` defaults to `300` but only +advances while no check is pending (running CI or armed auto-merge resets it), so +a PR waiting on review gives up while a long CI never does; `0` disables. +`--timeout` is a generous hard ceiling (`14400`s = 4h; `0` disables it). Long jobs (start a VM, run an integration suite, tear down) +can stay quiet for a long time. If `status: timeout` does come back, CI was +still running: **re-run the watch**, do not treat it as a result. + +**Heartbeat alerts.** While waiting, a line like `git-wait: still running +after 5m (2 run(s) pending: CI, Release)` goes to **stderr** every +`--alert-interval` seconds (default `300`; `0` disables). stdout `key: value` +output is unchanged. Relay these to the user so a long wait is visibly alive. + +**`no-workflow` is patient.** `--no-run-timeout` is how long to wait for the +*first* run to appear (counted from the end of `--initial-delay`): `600`s for +`--sha`, `900`s for `--branch` (PR checks can register late). Post-merge workflows trigger by push/tag/ +`workflow_run` and can queue minutes late or start only after another workflow +finishes, so `no-workflow` is reported only after that window, with a stderr +line (`no runs yet for <sha>, still waiting (Ns of 600s)`) on every poll. A +*failed* run-list call (network/auth) is not "no runs": it is noted on stderr, +excluded from that window and retried, but `--max-poll-failures N` +consecutive failures (default `10`; `0` disables) end the watch with +`status: error` and exit `4`. A successful poll resets the count. + +**`--settle SECS`** (`--sha` only, a usage error with `--branch`; default `0` = off): once every run +is terminal and passing, keep polling `SECS` more before reporting `pass`, so a +chained `workflow_run` workflow that starts late is still watched. Opt in with +`--settle 30` only when such a chain exists. + +The `--timeout` ceiling is enforced on every poll, including while waiting for +the first run, settling, or waiting for checks to register. On the `--branch` +PR path, a failed `gh pr view` counts toward `--max-poll-failures`, and a PR +with no checks registered ends as `no-workflow` after `--no-run-timeout`. + +Exit codes: `0` terminal state reached (check `status:` for pass/fail), +`1` usage error, `2` timeout, `3` platform detection failure or no PR/workflow +found, `4` command failed. + +## Targeting another repo + +Put `-C DIR` before the command to run against a repo other than the current +directory — use it instead of `cd`: + +```bash +bash scripts/git-wait -C /path/to/other-repo run watch --branch NAME +``` + +Only `git-wait` honors `-C`; direct `gh`/`tea` calls against another repo still +need their own `-R OWNER/REPO` / `--repo` flag. + +## gh vs. tea command map + +Verified against `gh` 2.100.0 and `tea` 0.15.1. Don't guess beyond this +table — if you need a flag that isn't listed, run `gh <cmd> --help` or +`tea <cmd> --help` yourself and confirm before using it. + +| task | gh | tea | +|---|---|---| +| open PR | `gh pr create --title T --head B --base M --body-file -` (`-F -` reads stdin) | `tea pr create --title T --head B --base M --description D` — NO `--body`, NO `--body-file`; only `-d`/`--description`, inline text. From a file: `--description "$(cat FILE)"` | +| list PRs | `gh pr list --state open --json number,title,headRefName,url` | `tea pr list --state open --output json --fields index,title,head,url` | +| PR states | `open` / `closed` / `merged` / `all` | `all` / `open` / `closed` ONLY — no `merged`; a merged PR reports state `closed`, and `tea pr list` omits the `merged` boolean entirely. To tell merged from closed: `tea api repos/{owner}/{repo}/pulls/N \| jq -r .merged` | +| merge PR | `gh pr merge N --merge --delete-branch`; `--auto` enables auto-merge | `tea pr merge N --style merge` — no `--auto`; **Gitea has no auto-merge at all** | +| create issue | `gh issue create --title T --body-file - --label L --assignee U` | `tea issues create --title T --description D --labels L --assignees U` (PLURAL flags, comma-separated single string) | +| comment | `gh issue comment N --body-file -` | `tea comment N "text"` | +| close issue | `gh issue close N` | `tea issues close N` | +| CI runs | `gh run list --branch B --json databaseId,status,conclusion,workflowName --limit N`; `gh run view ID --log-failed` | `tea actions runs list` — its server-side `--branch` filter is UNRELIABLE (Gitea leaves `head_branch` empty on `pull_request` runs), and `tea actions runs view` IGNORES `--output json` and prints a human table. Use `tea api repos/{owner}/{repo}/actions/runs` instead. | +| default branch | `gh repo view --json defaultBranchRef --jq .defaultBranchRef.name` | `tea api repos/{owner}/{repo} \| jq -r .default_branch` | +| whoami | `gh api user --jq .login` | `tea whoami` | +| raw API | `gh api PATH` | `tea api PATH` — both substitute `{owner}`/`{repo}` | + +Notes: + +- `tea pulls` is the canonical subcommand name; `tea pr` is an alias for it. +- Suppress color with `GH_NO_COLOR=1` / `NO_COLOR=1` when parsing CLI output + as text or JSON — ANSI codes otherwise corrupt `jq`/`grep` parsing. +- When a task doesn't fit the map above (e.g. reviews, labels, milestones), + check `gh <cmd> --help` / `tea <cmd> --help` rather than assuming parity + between the two CLIs — their flag sets diverge in ways that aren't always + intuitive (see the PR-create and PR-state rows above). diff --git a/plugins-opencode/git-tools/scripts/git-wait b/plugins-opencode/git-tools/skills/git-wait/scripts/git-wait similarity index 100% rename from plugins-opencode/git-tools/scripts/git-wait rename to plugins-opencode/git-tools/skills/git-wait/scripts/git-wait diff --git a/plugins-opencode/git-tools/skills/ship/SKILL.md b/plugins-opencode/git-tools/skills/ship/SKILL.md new file mode 100644 index 0000000..d26f9c1 --- /dev/null +++ b/plugins-opencode/git-tools/skills/ship/SKILL.md @@ -0,0 +1,435 @@ +--- +name: ship +description: >- + Use this skill whenever the user asks to take in-flight work through the + full merge lifecycle. Triggers on shorthand prompts like + "branch/commit/pr/watch/master/pull", "pr/watch/master/pull", + "watch/master/pull", "push+pr then watch and master/pull", "branch/pr/merge/master/pull", + "send it", "ship it", "merge it", or terse single words "watch", "merge", + "pull" when the context implies finishing a PR. Drives staging → commit → + push → PR create → CI watch → merge wait → post-merge release watch → + checkout master → pull, using `gh`/`tea` directly (platform detected once + via git-wait) for every GitHub/Gitea call, and cleans up the worktree if one + was used. Waits for every CI job to reach a terminal state — including any + release/publish/deploy workflow that only starts after the merge — before + reporting success. Skips steps that are already complete instead of redoing + them. +--- + +# ship — full merge lifecycle orchestrator + +All `scripts/...` paths below are relative to this skill's base directory +(provided when the skill loads). + +**Purpose.** Take whatever in-progress work exists and drive it through the canonical lifecycle: stage → commit → push → PR → watch CI → wait for merge → watch the post-merge release run → return to default branch → pull → clean up the worktree if one was used. Skip any step that's already done. + +**The bar for "shipped" is that CI is finished, not that CI is green.** Two +distinct waits are mandatory and are the two most commonly skipped steps: +every job on the PR (step 6), and every job in whatever runs *after* the merge +(step 8). Reporting success while any job is still in flight is a failure of +this skill, even if everything eventually passes. + +**Detect the platform once, then call `gh` or `tea` directly.** There is no +wrapper. Step 1 below calls `git-wait platform` a single time; every later +step that needs a hosted-CLI call branches on that result with an explicit +`github:` block (`gh`) and `gitea:` block (`tea`). See the sibling `git-wait` +skill for the full gh-vs-tea command map — don't invent flags beyond what's +documented there. + +## When to use + +Trigger on any shorthand that means "finish this PR": + +- `branch/commit/pr/watch/master/pull` (and reorderings) +- `pr/watch/master/pull` +- `watch/master/pull` +- `push+pr, then watch and master/pull` +- `branch/pr/merge/master/pull` +- `send it`, `ship it`, `merge it`, `let's merge that` +- terse single words `watch`, `merge`, `pull` when the surrounding context already involves a PR + +If the user explicitly invokes `/ship`, use this same procedure. + +## Procedure + +Run these steps in order. **Detect and skip** any step that is already complete; do not redo work. + +### 0. Read state + +```bash +git status --porcelain=v1 -b +git rev-parse --abbrev-ref HEAD +``` + +Establish: dirty working tree? on default branch or feature branch? upstream set? + +Also detect **whether this checkout is a linked git worktree** — this gates the cleanup in step 9: + +```bash +git_dir=$(git rev-parse --git-dir) +git_common_dir=$(git rev-parse --git-common-dir) +# Linked worktree iff the two differ. Normalize with realpath first — on macOS +# /tmp is a symlink to /private/tmp, so a raw string compare can falsely differ. +if [ "$(realpath "$git_dir")" != "$(realpath "$git_common_dir")" ]; then + echo "linked worktree" # step 9 cleans it up after a confirmed merge +else + echo "main checkout" # step 9 keeps its current behavior +fi +``` + +This read is non-destructive; it only records context for later. + +### 1. Detect platform + +```bash +platform=$(bash scripts/git-wait platform) +``` + +`platform` is `github` or `gitea`. Every later step that talks to the hosted +CLI branches on this value once — resolved here, not re-detected per step. + +Also resolve the default branch now, since both `github:` and `gitea:` need it later: + +```bash +github: default=$(gh repo view --json defaultBranchRef --jq .defaultBranchRef.name) +gitea: default=$(tea api repos/{owner}/{repo} | jq -r .default_branch) +``` + +### 2. Stage and commit + +If there are uncommitted changes: + +- Show the user what will be staged (`git status --short` + `git diff --stat`). +- Stage **specific files** by name; never `git add -A` or `git add .` (avoids accidentally including secrets or generated files). +- Write a structured commit message: imperative-mood title (e.g. `feat: add tea CLI classifier`), optional body paragraph for larger changes, optional bullet list of specific changes. Match the repo's existing commit-log style — check `git log --oneline -20` first. + +Skip this step if the working tree is clean. + +### 3. Ensure feature branch + +If on the default branch (`master`/`main`), create a feature branch with a conventional prefix (`feat-`, `fix-`, `chore-`, `docs-`, `refactor-`, `test-`) before pushing: + +```bash +git checkout -b <prefix>-<short-description> +``` + +Skip if already on a non-default branch. + +### 4. Push + +```bash +git push -u origin HEAD +``` + +`-u` is needed only on first push; if upstream is already tracked, plain `git push` is fine. If the push fails because the remote has new commits, do not force-push — investigate first (someone else may have pushed; `git pull --rebase`, resolve, retry). Never plain `--force`/`-f`/`+refspec`, and never force to a shared or default branch unless the user explicitly names it; `--force-with-lease` on your own PR branch is fine. "Your own PR branch" means a branch you created this session for this PR and that no one else has pushed to. + +### 5. Create PR (if not already open) + +Check first: + +```bash +github: gh pr list --state open --json number,headRefName \ + --jq --arg b "$(git rev-parse --abbrev-ref HEAD)" '.[] | select(.headRefName==$b) | .number' +gitea: tea pr list --state open --output json --fields index,head \ + | jq -r --arg b "$(git rev-parse --abbrev-ref HEAD)" '.[] | select(.head==$b) | .index' +``` + +If no PR exists for the current branch: + +```bash +github: gh pr create --title "..." --head "$(git rev-parse --abbrev-ref HEAD)" --base "$default" --body-file - <<'EOF' +## Summary +... + +## Test plan +... +EOF + +gitea: tea pr create --title "..." --head "$(git rev-parse --abbrev-ref HEAD)" --base "$default" --description "$(cat <<'EOF' +## Summary +... + +## Test plan +... +EOF +)" +``` + +Pull a concise title from the most recent commit message; pull the body from the commit body plus a short test plan. Append every argument line matching `^([Cc]loses|[Ff]ixes) #[0-9]+` verbatim to the PR body (after the test plan) so the linked issues auto-close on merge. Note `tea pr create` takes `-d`/`--description` only — no `--body`/`--body-file`. + +**If a PR already exists** (the idempotency check above found one), the +creation-time append never ran, so reconcile the closing lines now. For each +`^([Cc]loses|[Ff]ixes) #[0-9]+` argument line, check whether the PR body already +contains it; append only the missing ones (never rewrite or drop existing text): + +```bash +# github: fetch the body once, append each missing closing line on its own line, +# then a single edit. $CLOSING = the matching argument lines, one per line. +body=$(gh pr view N --json body --jq .body) +new=$body +while IFS= read -r line; do + [ -n "$line" ] || continue + printf '%s\n' "$new" | grep -qxF -- "$line" && continue + new+=$'\n'"$line" +done <<<"$CLOSING" +[ "$new" = "$body" ] || printf '%s\n' "$new" | gh pr edit N --body-file - +# gitea: tea pulls N --output json --fields description # read, append missing lines, then: +tea pulls edit N --description "<existing body + missing lines>" +``` + +`tea pulls edit` (alias `tea pr edit`) supports `-d`/`--description`, which +replaces the whole body — so always send the full existing body plus the new +lines. If the edit fails, post the missing lines as a PR comment +(`tea comment N "Closes #N"`) and tell the user the body could not be updated, +since a comment does not auto-close the issue on merge. + +### 6. Watch CI — **every job, to completion** + +```bash +bash scripts/git-wait run watch --branch "$(git rev-parse --abbrev-ref HEAD)" --interval 30 +``` + +This is platform-agnostic — it works the same on `github` and `gitea`. It polls until CI passes, fails, or no run ever appears. It never aborts a running CI for lack of progress (hard ceiling 4h) and prints heartbeat alerts to stderr every 5 minutes (`still running after 5m (N run(s) pending: ...)`) — relay those to the user. If it returns `status: timeout`, CI was still running: re-run the watch, do not report success. Output includes `status` (`pass|fail|closed|timeout|no-workflow|error`), `url`, `duration`, and on fail `failed_jobs` with logs piped to stderr. `error` means the watch could not talk to the API (exit 4): surface it to the user, do not treat it as no CI. + +**`no-workflow` is not automatically "no CI".** The `--branch` watcher already +waits 900s for the first check, but PR checks can still be legitimately late +(saturated runners, a fork approval gate). On `no-workflow`, look for a +PR-triggered workflow: + +```bash +grep -lE 'pull_request' .github/workflows/*.y*ml .gitea/workflows/*.y*ml 2>/dev/null +``` + +If any workflow has a `pull_request` trigger, do **not** treat it as no CI: +re-run the watcher once with a longer window (for example `--no-run-timeout 1800`) +and tell the user it is waiting on late-registering checks. Accept `no-workflow` +only when no PR-triggered workflow exists. + +**"CI passed" means every job on the PR reached a terminal state — not just the +required ones, not just the ones that had registered when you first looked.** +This is the step most often called done too early. Before you treat step 6 as +complete: + +- **Enumerate the checks and confirm none are still pending.** On GitHub the + watcher reads the PR's `statusCheckRollup`, which is a snapshot of the checks + *registered at that moment*. List them explicitly and eyeball the set: + + ```bash + github: gh pr view "$(git rev-parse --abbrev-ref HEAD)" \ + --json statusCheckRollup \ + --jq '.statusCheckRollup[] | "\(.name // .context): \(.conclusion // .state // "PENDING")"' + gitea: tea api "repos/{owner}/{repo}/actions/runs?limit=20" \ + | jq -r --arg b "$(git rev-parse --abbrev-ref HEAD)" \ + '.workflow_runs[] | select((.head_branch // .branch) == $b) + | "\(.name): \(.conclusion // .status)"' + ``` + + `git-wait` itself exposes only `platform`, `pr wait`, and `run watch` — there + is no `run show`/`run list` subcommand to call here, which is why this + enumeration goes through `gh`/`tea` directly. + +- **A green rollup that is missing a workflow you expected is not a pass.** + If a workflow is slow to queue, the rollup can read "all success" while that + workflow has not been added to it yet — the watcher returns `pass` and the + orchestrator marches on. Compare the check names against the repo's + workflows (`ls .github/workflows/`, or `gh workflow list`) and re-run the + watcher if something that should be there is absent. + +- **Fan-in checks do not excuse the rest.** A repo may gate merge on a single + aggregate check (this repo uses `ci-pass`). That check going green is the + *merge* gate, not proof that every job finished — report the individual job + results, not just the fan-in. + +**On failure:** if the failure is clearly caused by this change, fix forward within the unit (commit, push, re-watch step 6), at most twice for the same PR. Otherwise (flaky, infra, unrelated, unclear, or still failing after two attempts) stop the orchestrator and surface the failure to the user. + +### 7. Wait for merge + +**Gitea has no auto-merge at all** — nothing merges until you do. On `gitea`, once +the required checks are green (step 6 complete), merge yourself first, and only +then run the wait below to confirm the merge landed. CI is the gate: + +```bash +gitea: tea pr merge N --style merge +``` + +On `github`, if the repo's auto-merge bot will merge the PR (configured and enabled +on it), just run the wait below. If no bot will merge (none configured, or it has +not enabled auto-merge on the PR), merge once the required checks are green, then +wait: + +```bash +github: gh pr merge N --merge --delete-branch +``` + +Then confirm with the blocking waiter (platform-agnostic): + +```bash +bash scripts/git-wait pr wait --branch "$(git rev-parse --abbrev-ref HEAD)" --interval 15 +``` + +### 8. Watch the post-merge run (release, publish, deploy) + +**The lifecycle is not finished when the PR merges.** Step 6 only ever sees +checks attached to the *PR head*. Any workflow triggered by the merge itself — +`on: push` to the default branch, `on: release`, a tag build, a publish or +deploy job — runs **after** step 7 returns and appears **nowhere** in the PR's +checks. Skipping this step is how a ship reports success while the release job +is still running, or has already failed. + +**Check locally first — it only picks the watch window, never whether to watch.** +`run watch --sha` waits out a long no-run window (about 10 minutes) when nothing +was triggered, so look for post-merge triggers to decide how long to wait. The +grep covers block keys (`push:`, `release:`, `workflow_run:`, `tags:`) and the +inline forms (`on: push`, `on: [push, pull_request]`, `on: {push: ...}`): + +```bash +grep -lE '^[[:space:]]*(push|release|workflow_run|tag)s?:|^[[:space:]]*on:.*(push|release|workflow_run|tag)' .github/workflows/*.y*ml .gitea/workflows/*.y*ml 2>/dev/null +``` + +A grep miss must **never** become a silent skip — a trigger form the pattern +does not know would then hide a release job. Always watch; the grep only sizes +the window. Resolve **your merge commit** and watch the runs it caused by SHA: + +```bash +github: merge_sha=$(gh pr view N --json mergeCommit --jq '.mergeCommit.oid') +gitea: merge_sha=$(tea api repos/{owner}/{repo}/pulls/N | jq -r .merge_commit_sha) +``` + +- **Grep found nothing** → short window; `no-workflow` then confirms none: + + ```bash + bash scripts/git-wait run watch --sha "$merge_sha" --no-run-timeout 90 --settle 0 + ``` + +- **Grep found triggers** → default window (add `--settle 30` only if any match + is a `workflow_run` trigger, so chained runs get time to appear; settle + defaults to off): + + ```bash + bash scripts/git-wait run watch --sha "$merge_sha" --interval 30 # + --settle 30 if workflow_run present + ``` + +**Watch by SHA, not by branch.** `run watch --branch` follows a single run — +the newest correlated to that branch. On a PR branch that is right, because one +push means one run. On a default branch it is not: two merges landing close +together produce two runs, and the newest going green says nothing about the +other. Watching `--branch "$default"` here reported `status: pass` off the +second merge's run while the first merge's run was still executing. + +`--sha` is scoped to the commit *your* merge produced, so it neither misses a +run nor blocks on somebody else's push. It stays pending while any run for that +commit is pending, and fails if any run — or any job inside one — failed. Apply +the same completeness rule as step 6: every job, not the first to report. +On `status: timeout` re-run the watch (the run is still going). On `no-workflow` +report "no post-merge workflow on this repo" (the watcher already waited its +no-run window; with the short 90s window that is a confirmed none, and saying so +is a finding — silence is indistinguishable from not having looked). + +Note `gh` calls the field `mergeCommit` (an object; take `.oid`) — there is no +`mergeCommitSha`. `--sha` needs a full 40-character SHA; it will expand a short +one only when git can resolve it locally, and errors rather than silently +watching nothing. + +If the watched run **fails**, surface it immediately. A merged PR with a failed +release run is a worse state than a blocked PR, because the change is already on +the default branch. Do not attempt a fix or a revert on your own — tell the user. + +### 9. Return to default branch (and clean up the worktree if one was used) + +`default` was already resolved in step 1. + +**Case A — main checkout** (step 0 reported `main checkout`): unchanged behavior. + +```bash +git checkout "$default" +git pull +``` + +**Case B — linked worktree** (step 0 reported `linked worktree`): only proceed **after the branch has actually merged** (step 7 confirmed the merge). Worktree teardown is destructive and hard to reverse — never run this block on an unmerged branch. + +1. Capture identifiers **while still inside the linked worktree** (these are per-worktree): + + ```bash + linked_wt=$(git rev-parse --show-toplevel) + feature_branch=$(git rev-parse --abbrev-ref HEAD) # literal "HEAD" if detached + main_wt=$(git worktree list --porcelain | awk 'NR==1 && /^worktree /{sub(/^worktree /,""); print}') + ``` + +2. **Cleanliness gate.** If the worktree has uncommitted or untracked changes, do **not** remove it automatically: + + ```bash + git -C "$linked_wt" status --porcelain + ``` + + - Empty output → clean; proceed to remove it automatically. + - Non-empty → stop and ask the user whether to discard those changes (`git worktree remove --force`) before doing anything destructive. + +3. Move into the main worktree and refresh — you cannot reliably remove the worktree you are standing in (its working directory becomes invalid): + + ```bash + cd "$main_wt" + git checkout "$default" + git pull + ``` + +4. Remove the merged worktree and prune stale metadata: + + ```bash + git worktree remove "$linked_wt" # add --force ONLY after explicit user approval when dirty + git worktree prune + ``` + +5. Delete the now-merged local branch (skip when `feature_branch` is `HEAD`, i.e. detached): + + ```bash + git branch -d "$feature_branch" + ``` + + PRs merge with a merge commit, so once the base branch is pulled (step 3) the branch tip is an ancestor of it and `-d` succeeds. `-d` refuses when git does not see the branch as fully merged. Treat a refusal as a real signal, never as something to force: the PR may not actually be merged, the base may not be pulled yet, or the branch carries commits that never landed. Investigate (`git log "$default".."$feature_branch"`, re-pull, check the PR state) and report to the user. Do not run `git branch -D` to get past it. + +Returning to the default branch is the step most often forgotten — always run it after merge (in either case) unless the user explicitly says otherwise. + +## Arguments + +When invoked with arguments (e.g. `/ship merge` via the ship command, or a prompt that carries them), treat those arguments as additional context for the commit message or PR title: + +- `ship merge` — merge-commit intent +- `ship "fix: drop stale lock"` — use as the commit/PR title verbatim + +Any argument line matching `^([Cc]loses|[Ff]ixes) #[0-9]+` is a closing line: do not treat it as title/commit text — append it verbatim to the PR body (step 5). + +If no arguments were given, infer title and body from the diff and recent commit log. + +## Idempotency + +Each step probes state first and skips when there's nothing to do. Re-running the orchestrator after a partial run should pick up from wherever it left off — e.g. if the PR is already open, jump to step 6; if CI is already passing, jump to step 7; if the PR is already merged, jump to step 8 (post-merge run), then step 9. + +The step-9 worktree cleanup is gated twice: it runs only when step 0 detected a linked worktree **and** the branch has merged. In the main checkout it is skipped entirely (current behavior preserved), and re-running after the worktree is already removed is a no-op — the worktree detection short-circuits. + +## What NOT to do + +- Do **not** guess `gh`/`tea` flags — use the map in the sibling `git-wait` skill, or run `--help` to confirm. +- Do **not** use plain `--force`/`-f`/`+refspec`, and do **not** force-push a shared or default branch unless the user explicitly names it; `--force-with-lease` on your own PR branch (one you created this session for this PR that no one else has pushed to) is fine. +- Do **not** merge before the required checks are green or while the PR is blocked — on GitHub the auto-merge bot normally merges; use `gh pr merge` / `tea pr merge` only when no bot will (always on Gitea). +- Do **not** end the session on a feature branch after a merge — return to the default branch and pull. +- Do **not** report "CI passed" off a partial check set — a rollup that is green only because a workflow has not been queued yet is not a pass. Confirm every expected check is present *and* terminal. +- Do **not** stop watching at the merge. A release/publish/deploy workflow triggered by the merge is invisible to the PR's checks; step 8 exists specifically to catch it, and skipping it is how a failed release gets reported as a successful ship. +- Do **not** treat a single fan-in check (e.g. `ci-pass`) as proof that every job finished — it is the merge gate, not the completion signal. +- Do **not** invent your own polling loop (`until gh pr view ... | grep MERGED; do sleep`) — `git-wait pr wait` and `git-wait run watch` already handle this with proper timeouts and failure detection, on both platforms. +- Do **not** `git worktree remove` the worktree you are standing in — `cd` into the main worktree first, then remove. +- Do **not** `--force`-remove a worktree with uncommitted or untracked changes without explicit user approval. +- Do **not** `git branch -D` (force-delete) to get past a `git branch -d` refusal — it means the branch is genuinely unmerged or the base is not pulled yet. Investigate first; force-delete only if the user explicitly asks. +- Do **not** check out a branch that is already live in another worktree (`git` refuses with `already used by worktree at ...`). + +## Reporting back + +After the lifecycle completes, give the user a one-line summary: PR number + URL, CI status, final state (merged/blocked), and that the workspace is back on the default branch. + +State the two waits separately, and never imply a job finished that you did not +actually see finish: + +- **PR CI** — the individual job results, not just the fan-in check. +- **Post-merge run** — its result, or an explicit "no post-merge workflow on + this repo" when step 8 found none. If you stopped watching early (timeout + not re-run, the user interrupted, a job was still queued), say exactly that rather than + rounding it up to a pass. diff --git a/plugins-opencode/git-tools/skills/ship/scripts/git-wait b/plugins-opencode/git-tools/skills/ship/scripts/git-wait new file mode 100755 index 0000000..335f658 --- /dev/null +++ b/plugins-opencode/git-tools/skills/ship/scripts/git-wait @@ -0,0 +1,1460 @@ +#!/usr/bin/env bash +# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. +# +# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: +# listing, creating, commenting, merging, closing, viewing logs. This script +# exists only for the three things neither CLI gives you: +# +# 1. Platform detection — matching the git remote hostname against configured +# tea logins, so a caller knows whether to reach for `gh` or `tea`. +# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a +# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on +# the merge itself; `tea` has no equivalent at all). +# 3. `run watch` — block until CI finishes, aggregating per-job status and +# dumping failed job logs. `gh run watch` is GitHub-only and misses +# job-level failures masked by a run-level success; `tea` has no watcher. +# +# Usage: +# git-wait [-C DIR] <command> ... +# Operate on the git repo at DIR instead of the current directory (like +# `git -C`). Must come before the command. gh/tea resolve the repo from the +# working directory, so this retargets every call without a caller-side cd. +# +# git-wait platform +# Echo "github" or "gitea" for the current repo's origin remote. +# +# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] +# [--alert-interval 300] +# Block until the PR for BRANCH reaches a terminal state. +# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, +# url, duration, and (when relevant) reason. +# +# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] +# [--timeout 14400] [--idle-timeout 0] [--interval 15] +# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] +# [--max-poll-failures 10] +# Block until CI finishes. Output: "status: pass|fail|closed|timeout| +# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed +# job logs go to stderr. +# +# --branch follows ONE run: the newest correlated to that branch (via the +# PR's check rollup when a PR exists, else the newest run in the list). +# That is right for a PR branch, where one push means one run. It is NOT +# sufficient on a default branch, where two merges landing close together +# produce two runs and the newest passing says nothing about the older +# one still executing. +# +# --sha watches EVERY run for one commit and is the correct flag for a +# post-merge/release watch: it stays pending while any run for the commit +# is pending, and fails if any run — or any job inside one — failed. Pass +# one or the other, not both. +# +# A running CI is never aborted for lack of visible progress: `run watch +# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress +# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO +# check is pending (running CI, or auto-merge armed, resets it), so a PR that +# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long +# jobs (VM boot + integration suite + teardown) can go quiet for a long time. +# While still waiting, a heartbeat alert goes to STDERR every --alert-interval +# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) +# pending: ...)". stdout key:value output is unchanged. +# +# --no-run-timeout is how long to wait for the FIRST run to appear before +# reporting no-workflow, counted from the end of --initial-delay. Default 600s +# for --sha (post-merge workflows queue late, or start only after another +# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty +# check. A stderr alert is printed each poll while waiting. A FAILED run-list +# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not +# counted toward this deadline and polling continues, but after +# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the +# watch gives up with "status: error" and exit 4. A successful poll resets the +# count. +# +# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the +# commit is terminal and passing, keep polling SECS more before reporting pass, +# so a chained workflow_run workflow that appears late is still watched. A +# stderr line is printed while settling; a new run restarts the watch. +# +# Exit codes: 0 terminal state reached (check "status:" for pass/fail), +# 1 usage error, 2 timeout, 3 platform detection failure or no +# PR/workflow found, 4 command failed + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +die() { echo "git-wait: $*" >&2; exit 1; } +die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } + +# Run a CLI command and pipe its stdout through a jq filter. +# If the command fails, die with its stderr instead of feeding junk to jq. +# Usage: cli_json [jq-flags...] <jq-filter> <cmd> [args...] +# +# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. +# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, +# auth warnings, progress text) into the JSON, silently corrupting jq +# parsing and producing wrong results downstream (e.g. run watch seeing +# unexpected status values). +cli_json() { + local jq_flags=() + while [[ "$1" =~ ^-[a-zA-Z] ]]; do + # Collect jq flags (e.g. -r, -e) — stop at the filter string + case "$1" in + -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; + *) break ;; + esac + done + local filter="$1"; shift + local raw stderr_file rc=0 + stderr_file=$(mktemp) + raw=$("$@" 2>"$stderr_file") || rc=$? + if [[ $rc -ne 0 ]]; then + local err + err=$(cat "$stderr_file") + rm -f "$stderr_file" + die "$err" + fi + rm -f "$stderr_file" + echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" +} + +# --------------------------------------------------------------------------- +# Target repo (-C DIR) +# +# Handled before platform detection. The cd happens inside this script's own +# process, so the caller's working directory is never touched. +# --------------------------------------------------------------------------- + +if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then + [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" + target_dir="$2" + [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" + git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die_usage "$1: not a git repository: $target_dir" + # Resolve the script path first: a relative $0 breaks once we cd (help reads it). + SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + cd "$target_dir" + shift 2 +fi +SELF="${SELF:-$0}" + +# --------------------------------------------------------------------------- +# Platform detection +# --------------------------------------------------------------------------- + +detect_platform() { + local remote_url hostname login_url login_host + remote_url=$(git remote get-url origin 2>/dev/null) \ + || die "no git remote 'origin' found — run from a git repository" + + # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) + # or HTTPS (https://host/org/repo or https://host:port/org/repo) + if [[ "$remote_url" =~ ^ssh:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') + elif [[ "$remote_url" =~ ^git@ ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') + elif [[ "$remote_url" =~ ^https?:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') + else + die "unrecognised remote URL format: $remote_url" + fi + + # Check if this hostname matches any configured tea login + if command -v tea >/dev/null 2>&1; then + while IFS= read -r login_url; do + login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') + if [[ "$login_host" == "$hostname" ]]; then + echo "gitea" + return + fi + done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) + fi + + # Not a known tea login — fall back to gh (GitHub) + if [[ "$hostname" == "github.com" ]]; then + echo "github" + return + fi + + die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" +} + +PLATFORM=$(detect_platform) + +case "$PLATFORM" in + github) CLI=gh ;; + gitea) CLI=tea ;; +esac + +command -v "$CLI" >/dev/null 2>&1 \ + || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } + +# --------------------------------------------------------------------------- +# Internal reads +# +# These are NOT public subcommands — they are the normalized queries the two +# waiters below need. Every one of them dies on backend failure, so callers +# invoke them inside $( ) with a fallback: a probe failure must degrade the +# poll loop, never abort it. +# --------------------------------------------------------------------------- + +# List PRs as normalized JSON. Flags: --state, --limit, --assignee. +_pr_list() { + local limit assignee state args + limit=30; assignee=""; state="open" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; + --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") + # gh uses 'merged' as a state but tea uses 'closed' for merged PRs + [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") + [[ -n "$assignee" ]] && args+=(--assignee "$assignee") + cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ + env GH_NO_COLOR=1 gh pr list "${args[@]}" + ;; + gitea) + args=(--output json --limit "$limit" + --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") + [[ "$state" == "merged" ]] && state="closed" + args+=(--state "$state") + cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ + env NO_COLOR=1 tea pr list "${args[@]}" + ;; + esac +} + +# Show one PR as normalized JSON. Takes <N> or --branch NAME. +_pr_show() { + local num branch pr_json pr_stderr pr_rc pr_detail err + num=""; branch="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --*) die_usage "unknown flag: $1" ;; + *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; + esac + shift + done + [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass <N> or --branch NAME, not both" + if [[ -n "$branch" ]]; then + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + num=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + [[ -n "$num" ]] || die "no PR found for branch '$branch'" + fi + [[ -n "$num" ]] || die_usage "usage: git-wait pr show <N> | --branch NAME" + case "$PLATFORM" in + github) + cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ + env GH_NO_COLOR=1 gh pr view "$num" \ + --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" + ;; + gitea) + # `tea pr list` omits the `merged` boolean and `merged_at` timestamp + # entirely (tea only encodes merge state into the `state` string) and + # emits `mergeable` as a string, so a merged PR reports + # merged:false / mergedAt:null and consumers think it is still open + # (#140). Fetch the PR detail via the REST API instead, mirroring the + # run:show/run:list `tea api` pattern, so merge fields are reliable. + pr_stderr=$(mktemp); pr_rc=0 + pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ + || pr_rc=$? + if [[ $pr_rc -ne 0 ]]; then + err=$(cat "$pr_stderr"); rm -f "$pr_stderr" + die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" + fi + rm -f "$pr_stderr" + # Derive `state` from `merged` so it stays consistent with the merge + # flags (Gitea REST reports state:"closed" for a merged PR) and matches + # the GitHub path, which emits state:"merged". + echo "$pr_detail" | jq '{ + number: (.number // .index), + title: (.title // ""), + body: (.body // ""), + state: (if (.merged // false) then "merged" else (.state // "") end), + merged: (.merged // false), + merged_at: (.merged_at // null), + author: (.user.login // .user.username // ""), + head: (.head.ref // .head.label // ""), + base: (.base.ref // .base.label // ""), + labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), + assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), + mergeable: (.mergeable // null), + created_at: (.created_at // ""), + updated_at: (.updated_at // null), + url: (.html_url // .url // ""), + comments: [] + }' + ;; + esac +} + +# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. +_auto_merge_status() { + local branch number pr_json am + branch=""; number="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) shift; branch="$1" ;; + --number) shift; number="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + + # Resolve PR number from branch if needed + if [[ -z "$number" ]]; then + [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" + pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" + number=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + if [[ -z "$number" || "$number" == "null" ]]; then + echo "auto_merge: false" + echo "No open PR found for branch '$branch'" >&2 + exit 3 + fi + fi + + case "$PLATFORM" in + github) + am=$(cli_json -r '.autoMergeRequest != null' \ + env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) + echo "auto_merge: $am" + ;; + gitea) + echo "auto_merge: false" + echo "Gitea does not support auto-merge detection" >&2 + ;; + esac +} + +# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. +# +# --sha filters to runs for one commit. GitHub has a server-side filter for it +# (`gh run list --commit`); Gitea does not, so it is applied client-side over +# an unfiltered fetch, the same way --branch already is there. Both platforms +# emit head_sha in the normalized output — GitHub did not used to, which is +# why `run watch --sha` needs the headSha field added below. +_run_list() { + local limit status branch sha args query raw_stderr raw_rc raw err + limit=20; status=""; branch=""; sha="" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") + [[ -n "$status" ]] && args+=(--status "$status") + [[ -n "$branch" ]] && args+=(--branch "$branch") + [[ -n "$sha" ]] && args+=(--commit "$sha") + cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ + env GH_NO_COLOR=1 gh run list "${args[@]}" + ;; + gitea) + # Source from Gitea REST API directly. `tea actions runs list` + # filters server-side by a `branch` column that Gitea leaves empty + # on `pull_request` runs, so the watcher's --branch lookup misses + # correlated runs (#103). Fetch unfiltered via `tea api`, normalize + # `branch` from `head_branch`, and apply --branch client-side. + query="limit=$limit" + [[ -n "$status" ]] && query+="&status=$status" + raw_stderr=$(mktemp); raw_rc=0 + raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ + || raw_rc=$? + if [[ $raw_rc -ne 0 ]]; then + err=$(cat "$raw_stderr"); rm -f "$raw_stderr" + die "tea api repos/{owner}/{repo}/actions/runs failed: $err" + fi + rm -f "$raw_stderr" + echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' + [(.workflow_runs // []) | .[] | { + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + head_sha: (.head_sha // ""), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // "") + }] + | if $b == "" then . else [.[] | select(.branch == $b)] end + | if $s == "" then . else + [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] + end + ' + ;; + esac +} + +# Show one CI run as normalized JSON, including per-job status. +_run_show() { + local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err + [[ $# -ge 1 ]] || die_usage "usage: git-wait run show <run-id>" + run_id="$1" + case "$PLATFORM" in + github) + cli_json \ + 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ + env GH_NO_COLOR=1 gh run view "$run_id" \ + --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" + ;; + gitea) + # Fetch the run object via the REST API. `tea actions runs view` + # ignores `--output json` (tea 0.14.1) and prints a human key/value + # table while still exiting 0, so jq downstream chokes (#133). Use the + # same `tea api` pattern as run:list and the jobs lookup below. + view_stderr=$(mktemp); view_rc=0 + view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ + || view_rc=$? + if [[ $view_rc -ne 0 ]]; then + err=$(cat "$view_stderr"); rm -f "$view_stderr" + die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" + fi + rm -f "$view_stderr" + + # Fetch per-job data via the actions API so callers (run watch) can + # detect job-level failures masked by run-level status=success on + # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. + jobs_array='[]' + jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) + if [[ -n "$jobs_json" ]]; then + jobs_array=$(echo "$jobs_json" | jq -c ' + def to_status: + if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) + end; + [(.jobs // .) | (if type == "array" then .[]? else empty end) | + {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] + ' 2>/dev/null) || jobs_array='[]' + fi + + # Older Gitea versions may not expose the jobs API; fall back to + # scanning the run logs for "Job '<name>' failed" lines. + if [[ "$jobs_array" == '[]' ]]; then + failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ + | grep -oE "Job '[^']+' failed" \ + | sed -E "s/Job '(.+)' failed/\1/" \ + | sort -u || true) + if [[ -n "$failed_log" ]]; then + jobs_array=$(printf '%s\n' "$failed_log" \ + | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') + fi + fi + + # Normalize REST field names into the output contract, mirroring the + # run:list jq above (conclusion-first status, head_branch//branch, + # run_started_at//created, name//workflow_id). + echo "$view_json" | jq --argjson jobs "$jobs_array" '{ + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // ""), + jobs: $jobs + }' + ;; + esac +} + +# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; +# Gitea has no server-side filter and returns every job's log). +_run_logs() { + local run_id failed_only + [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs <run-id> [--failed-only]" + run_id="$1"; shift + failed_only=false + while [[ $# -gt 0 ]]; do + case "$1" in + --failed-only) failed_only=true ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + if [[ "$failed_only" == "true" ]]; then + GH_NO_COLOR=1 gh run view "$run_id" --log-failed + else + GH_NO_COLOR=1 gh run view "$run_id" --log + fi + ;; + gitea) + # tea actions runs logs outputs all job logs; no built-in failed-only filter + NO_COLOR=1 tea actions runs logs "$run_id" + ;; + esac +} + +# --------------------------------------------------------------------------- +# Run helpers +# --------------------------------------------------------------------------- + +# Return comma-separated names of any jobs in <run_id> whose status is +# "failure", or empty if none. Used by run watch to detect job-level failures +# even when the run-level status reports success — Gitea sets run.status to +# "success" on a multi-job workflow if at least one job ran successfully, +# masking failures in earlier jobs (see issue #87). Calls "run show" to +# normalize per-platform JSON, so it works for both gh and tea paths. +_run_failed_jobs() { + local run_id="$1" show_json + show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 + echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' +} + +# Progress-aware timeout decision shared by `pr wait` and `run watch`. +# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress +# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. +# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ +# minutes: this lets callers keep waiting while CI is actively progressing and +# give up only after a stretch of no progress, with a hard ceiling backstop. +_wait_timed_out() { + local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" + if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then + echo "ceiling"; return 0 + fi + if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then + echo "idle"; return 0 + fi + return 1 +} + +# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. +_fmt_dur() { + local s="$1" + if [[ "$s" -lt 60 ]]; then echo "${s}s" + elif [[ "$s" -lt 3600 ]]; then + if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi + else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi +} + +# Periodic stderr heartbeat while a wait is still running. Callers set +# alert_interval (0 disables) and next_alert (initialised to alert_interval), +# and call `_heartbeat "$elapsed" "<detail>"` once per poll. Emits at most one +# alert per poll, then re-arms for the next multiple of alert_interval, so a +# slow poll never produces a burst. stderr only: stdout stays parseable. +_heartbeat() { + local el="$1" detail="$2" + [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 + echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 + next_alert=$(( (el / alert_interval + 1) * alert_interval )) +} + +# Coarse CI status — pending|success|failure|none — for a PR/branch, used by +# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the +# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is +# guarded so a probe failure degrades to "none" and never aborts the wait loop. +_ci_status() { + local pr_number="$1" branch="$2" view_json run_status + case "$PLATFORM" in + github) + view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } + echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) else "pending" end + else (.state // "pending" | ascii_downcase) end + ] | + if length == 0 then "none" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" end' 2>/dev/null || echo "none" + ;; + gitea) + run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) echo "pending" ;; + failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; + ""|none|null) echo "none" ;; + *) echo "success" ;; + esac + ;; + *) echo "none" ;; + esac +} + +# --------------------------------------------------------------------------- +# Command routing +# --------------------------------------------------------------------------- + +cmd="${1:-}" +sub="${2:-}" +shift 2 || shift || true + +case "$cmd:$sub" in + + # Echo the detected platform so callers know which CLI to reach for. + # PLATFORM is already resolved above; detection failure exited long before + # we got here. + platform:) + echo "$PLATFORM" + ;; + + pr:wait) + # timeout is the hard ceiling; idle_timeout is the no-progress window. + branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" ]] || die_usage "pr wait requires --branch" + + # Find PR for this branch + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + # Match branch — handle Gitea owner:branch format with endswith + pr=$(echo "$pr_json" | jq --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') + + if [[ -z "$pr" || "$pr" == "null" ]]; then + echo "status: no-pr" + echo "duration: 0s" + echo "No PR found for branch '$branch'" >&2 + exit 3 + fi + + pr_number=$(echo "$pr" | jq -r '.number') + pr_url=$(echo "$pr" | jq -r '.url // ""') + elapsed=0 + idle=0; idle_mark=0 + last_signal="" + unknown_streak=0 + + # Poll loop + while true; do + show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" + pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') + pr_merged=$(echo "$show_json" | jq -r '.merged // false') + pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') + + # Progress signals: CI still running or auto-merge pending means the PR is + # actively advancing toward merge, so the idle clock must not count down. + checks=$(_ci_status "$pr_number" "$branch") + if [[ "$PLATFORM" == "github" ]]; then + auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" + [[ "$auto_merge" == "true" ]] || auto_merge="false" + else + auto_merge="false" + fi + signal="$pr_state|$pr_mergeable|$checks|$auto_merge" + if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then + idle=0 + fi + last_signal="$signal" + + echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 + [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true + + case "$pr_state" in + merged) + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + closed) + if [[ "$pr_merged" == "true" ]]; then + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + fi + echo "status: closed" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR was closed without merging" >&2 + exit 0 + ;; + open) + # Check for merge conflicts + if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then + echo "status: blocked" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR has merge conflicts" >&2 + exit 0 + fi + # Still open — keep polling + ;; + *) + unknown_streak=$(( unknown_streak + 1 )) + if [[ "$unknown_streak" -ge 3 ]]; then + echo "status: error" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 + exit 4 + fi + echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 + ;; + esac + + # Reset unknown streak on any recognized state + [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 + + # Check timeout — only give up after a stretch of no progress (idle) or + # the absolute ceiling, never while CI/auto-merge is still working. + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + run:watch) + # timeout is the hard ceiling; idle_timeout is the no-progress backstop. + # While CI is actively pending the idle clock is reset each poll, so a long + # (15+ min) suite runs to completion up to the ceiling rather than being cut + # off by a flat wall-clock timeout. + branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 + alert_interval=300; next_alert=300; no_run_timeout="" + settle=0; settle_given=0; no_run_skew=0 + max_poll_failures=10; poll_fails=0 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; + --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; + --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" + [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" + [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" + # How long to wait for the FIRST run to appear (counted from the end of + # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ + # workflow_run and can queue minutes late, so that scope gets longer. + if [[ -z "$no_run_timeout" ]]; then + if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi + fi + + # `gh run list --commit` matches only on a FULL 40-character SHA -- a short + # one returns zero rows with no error, which this watcher would report as + # "no-workflow" rather than as the caller's mistake. Expand a short SHA via + # git when the commit is local, and refuse it outright when it is not, + # rather than silently watching nothing. (Gitea matches client-side on the + # first 12 chars, so a full SHA is correct there too.) + if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" + if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha="$_full_sha" + else + die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" + fi + fi + + elapsed=0 + idle=0; idle_mark=0 + + # A failed run-list call (network, auth, rate limit) is NOT an empty list. + # Note it, keep polling, and exclude the time from the no-workflow deadline + # (accumulated in no_run_skew). The hard ceiling still applies. After + # --max-poll-failures consecutive failures it gives up (exit 4). + _poll_failed() { + local what="$1" before="$elapsed" + poll_fails=$(( poll_fails + 1 )) + echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 + if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then + echo "status: error" + echo "duration: ${elapsed}s" + echo "reason: run list failed ${poll_fails} consecutive times" + echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 + exit 4 + fi + elapsed=$(( SECONDS - _t0 )) + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 + exit 2 + fi + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + no_run_skew=$(( no_run_skew + elapsed - before )) + } + + # Enforce the hard --timeout ceiling on paths that otherwise `continue` + # (no runs yet, settling, no checks registered) so they cannot outlive it. + _ceiling_check() { + local what="$1" + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what}" >&2 + exit 2 + fi + } + + # ------------------------------------------------------------------ + # --sha: watch EVERY run for one commit, not just the newest. + # + # `--branch` deliberately follows a single run (the newest correlated + # one). That is right for a PR branch, where one push means one run, but + # wrong for a default branch: two merges landing close together produce + # two runs, and the newest going green says nothing about the older one + # still executing. Watching a post-merge release run by branch reported + # "pass" while a second run was mid-flight. + # + # A commit is the honest scope for that question — the caller wants the + # runs *their* merge caused, not whatever else is landing on the branch. + # So this path aggregates: it stays non-terminal while ANY run for the + # commit is non-terminal, and fails if ANY run (or any job within one) + # failed. + # + # The CRITICAL DESIGN RULE below applies here too: only explicitly + # non-terminal statuses keep polling; anything unrecognized counts as + # terminal so an unexpected status cannot loop until timeout. + # ------------------------------------------------------------------ + if [[ -n "$sha" ]]; then + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + echo "Watching all runs for commit ${sha:0:12}..." >&2 + + # Settle window: after every run is terminal and passing, keep polling + # --settle seconds for a chained (workflow_run) run before reporting pass. + settle_start=-1; settle_ids="" + + while true; do + if ! sha_json=$(_run_list --sha "$sha" --limit 50); then + _poll_failed "commit ${sha:0:12}" + continue + fi + poll_fails=0 + sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) + + if [[ "$sha_count" -eq 0 ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + # Non-terminal set is explicit; everything else is terminal. + pending=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested")] + | length') + + echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 + + if [[ "$pending" -gt 0 ]]; then + pending_names=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested") + | (.workflow // .id)] | join(", ")') + _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" + # Active CI is progress — reset the idle clock, same as --branch. + idle=0 + settle_start=-1 + else + # Every run terminal. Collect run-level and job-level failures + # across ALL of them before declaring pass (#87 applies per run). + all_failed="" + fail_url="" + while IFS=$'\t' read -r r_id r_status r_url; do + [[ -n "$r_id" ]] || continue + case "$r_status" in + failure|timed_out|cancelled|canceled|skipped) + all_failed+="${all_failed:+,}run-$r_id:$r_status" + [[ -n "$fail_url" ]] || fail_url="$r_url" + ;; + *) + r_failed=$(_run_failed_jobs "$r_id") + if [[ -n "$r_failed" ]]; then + all_failed+="${all_failed:+,}$r_failed" + [[ -n "$fail_url" ]] || fail_url="$r_url" + fi + ;; + esac + done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') + + if [[ -n "$all_failed" ]]; then + echo "status: fail" + [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $all_failed" + echo "--- Failed job logs (last 80 lines) ---" >&2 + echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do + _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true + done + exit 0 + fi + + if [[ "$settle" -gt 0 ]]; then + cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') + if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then + echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 + settle_start=-1 + fi + if [[ "$settle_start" -lt 0 ]]; then + settle_start=$elapsed; settle_ids="$cur_ids" + fi + if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then + echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + fi + + echo "status: pass" + first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') + [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" + echo "duration: ${elapsed}s" + echo "runs: $sha_count" >&2 + exit 0 + fi + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so + # `run list --branch` correlates nothing and the watcher times out into + # no-workflow even when CI ran (#140). Resolve the branch head SHA up front + # (only on Gitea) and fall back to head_sha correlation when the + # branch-filtered lookup is empty. The run object's head_sha equals the + # branch head on Gitea (confirmed in #140); if a variant ever records a + # merge-ref SHA the fallback simply misses and degrades to today's + # behaviour rather than returning a wrong run. + _watch_branch_sha="" + if [[ "$PLATFORM" == "gitea" ]]; then + _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ + || git rev-parse "origin/$branch" 2>/dev/null || true) + fi + + # Echo a run-list JSON array for $branch: branch-name correlation first, + # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the + # server-side --branch filter populates the first call and _watch_branch_sha + # stays empty, so the SHA path is never taken. + _runs_for_branch() { + local lim="${1:-1}" out + # A failed call returns 1 (distinct from a successful empty "[]"). + out=$(_run_list --branch "$branch" --limit "$lim") || return 1 + if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then + echo "$out"; return 0 + fi + if [[ -n "$_watch_branch_sha" ]]; then + _run_list --limit 50 | jq \ + --arg s "$_watch_branch_sha" --argjson n "$lim" \ + '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ + || return 1 + return 0 + fi + echo "[]" + } + + # On GitHub, prefer PR-based status checking — one API call gives us both + # merge state and all CI check results via statusCheckRollup, avoiding the + # flaky run-level polling that produces "unknown" statuses. + pr_number="" + pr_url="" + use_pr=false + if [[ "$PLATFORM" == "github" ]]; then + pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { + pr_number=$(echo "$pr_json" | jq -r '.number // empty') + pr_url=$(echo "$pr_json" | jq -r '.url // ""') + [[ -n "$pr_number" ]] && use_pr=true + } + fi + + # Pre-check: look for an already-terminal state before sleeping the + # initial delay. If the PR already merged or CI already finished, + # report immediately instead of waiting. + _precheck_done=false + if [[ "$use_pr" == "true" ]]; then + _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" + _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') + + if [[ "$_pre_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already merged" >&2 + exit 0 + fi + if [[ "$_pre_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already closed without merging" >&2 + exit 0 + fi + + _pre_checks=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + if [[ "$_pre_checks" == "success" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "CI already passed on PR #$pr_number" >&2 + exit 0 + fi + + if [[ "$_pre_checks" == "failure" ]]; then + _pre_failed=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "failed_jobs: $_pre_failed" + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + fi + else + # Fallback path: check if a completed run already exists + _pre_list=$(_runs_for_branch 1) || _pre_list="[]" + _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') + if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then + _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') + _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') + _pre_id=$(echo "$_pre_latest" | jq -r '.id') + case "$_pre_status" in + success|completed) + # Run-level status can read "success" on Gitea even when a + # job inside the run failed (issue #87). Aggregate per-job + # status before declaring pass. + failed_jobs=$(_run_failed_jobs "$_pre_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "CI already passed for branch '$branch'" >&2 + exit 0 + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$_pre_id") + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$_pre_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a + # reason so consumers (ship/session-end) gating on + # status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "reason: $_pre_status" + echo "CI run $_pre_status for branch '$branch'" >&2 + exit 0 + ;; + esac + fi + fi + + # Initial delay — CI run may not exist immediately after push + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + if [[ "$use_pr" == "true" ]]; then + echo "Watching PR #$pr_number for branch '$branch'..." >&2 + + while true; do + # A failed gh call is not "unknown" -- count it, cap consecutive failures. + if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then + _poll_failed "PR #$pr_number" + continue + fi + poll_fails=0 + pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') + + # PR merged — all done + if [[ "$pr_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number merged" >&2 + exit 0 + fi + + # PR closed without merge + if [[ "$pr_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number closed without merging" >&2 + exit 0 + fi + + # Summarize CI check statuses from statusCheckRollup + # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state + checks_summary=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 + + case "$checks_summary" in + success) + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + failure) + failed_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_names" + # Try to fetch failed logs from the latest run + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + pending) + # Still running — keep polling. Active CI is progress, so reset idle. + check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') + if [[ "$check_count" -eq 0 ]]; then + # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + else + # Active CI is progress, so reset idle. + idle=0 + fi + pending_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select(if .__typename == "CheckRun" then (.conclusion // "") == "" + else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) + | .name // .context // "unknown"] | unique | join(", ")') + _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" + ;; + esac + + # Check timeout — idle window or absolute ceiling (see _wait_timed_out). + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Fallback: no PR found — poll run list directly (skip flaky run show). + # + # CRITICAL DESIGN RULE — default-terminal polling: + # + # This loop has caused repeated regressions (#53, #57, #58, #60). + # The recurring bug pattern is: + # 1. The API returns an unexpected status value (e.g. "completed" + # with null conclusion, or a new status GitHub adds later). + # 2. The case statement doesn't recognise it. + # 3. A catch-all `*) keep polling` silently loops until timeout. + # + # The fix (applied here) inverts the logic: + # - ONLY explicitly non-terminal states keep polling. + # - The `*` catch-all EXITS (as pass). + # + # DO NOT add a `*) keep polling` catch-all to this case statement. + # If a new non-terminal status appears, add it to the explicit list. + # If you're unsure whether a status is terminal, it's safer to exit + # early (the caller can retry) than to loop for 5 minutes. + # + run_url="" + while true; do + if ! list_json=$(_runs_for_branch 1); then + _poll_failed "branch '$branch'" + continue + fi + poll_fails=0 + latest=$(echo "$list_json" | jq -r '.[0] // empty') + + if [[ -z "$latest" || "$latest" == "null" ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + # Distinguish "no workflow registered at all" from "runs exist + # but none correlate to this branch" so callers (#103) can tell + # a real CI absence from a branch-correlation gap. + any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" + if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then + echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + else + echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + fi + exit 3 + fi + echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "branch '$branch'" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + run_id=$(echo "$latest" | jq -r '.id') + run_status=$(echo "$latest" | jq -r '.status // "unknown"') + run_url=$(echo "$latest" | jq -r '.url // ""') + + echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 + + # See "CRITICAL DESIGN RULE" above — non-terminal states are listed + # explicitly; everything else exits. Do NOT add a `*) keep polling`. + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) + # Non-terminal — keep polling. Active CI is progress, so reset idle. + idle=0 + _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$run_id") + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a reason + # so consumers gating on status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $run_status" + echo "CI run $run_status on branch '$branch'" >&2 + exit 0 + ;; + *) + # Terminal — covers success and any future/unexpected status. + # Even when the run-level status reports success, an individual + # job may have failed (Gitea reports run.status=success on a + # multi-job run if any job succeeded; see #87). Aggregate + # per-job status before declaring pass. + failed_jobs=$(_run_failed_jobs "$run_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + esac + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + --help:|-h:|:) + sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' + exit 0 + ;; + + *) + die_usage "unknown command: $cmd${sub:+ $sub}" + ;; +esac diff --git a/tests/opencode/test-git-tools-port.sh b/tests/opencode/test-git-tools-port.sh new file mode 100644 index 0000000..c4337f1 --- /dev/null +++ b/tests/opencode/test-git-tools-port.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# test-git-tools-port.sh — the OpenCode git-tools port stays faithful to the +# Claude original: same procedure content, OpenCode-only edits (skill-relative +# script paths, no Claude frontmatter/vars), and working vendored scripts. +# +# Usage: bash tests/opencode/test-git-tools-port.sh [filter] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)" +REPO="$SCRIPT_DIR/.." +CLAUDE="$REPO/plugins-claude/git-tools" +OC="$REPO/plugins-opencode/git-tools" + +PASS=0 +FAIL=0 +FILTER="${1:-}" + +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +pass() { + printf " \033[32m✓\033[0m %s\n" "$1" + ((PASS++)) || true +} +fail() { + printf " \033[31m✗\033[0m %s (%s)\n" "$1" "$2" + ((FAIL++)) || true +} +t2() { + local label="$1" + shift + if [[ -n "$FILTER" ]] && ! echo "$label" | grep -qi "$FILTER"; then return; fi + if "$@" >/dev/null 2>&1; then pass "$label"; else fail "$label" "assertion failed"; fi +} + +# --- vendored scripts present, executable, byte-identical to canonical ------ +for skill in git-wait ship; do + v="$OC/skills/$skill/scripts/git-wait" + t2 "$skill vendors git-wait" test -x "$v" + t2 "$skill copy matches utils/git-wait" cmp -s "$REPO/utils/git-wait" "$v" +done + +# --- no Claude harness leakage in the port ---------------------------------- +t2 "no CLAUDE_PLUGIN_ROOT in port" sh -c "! grep -rq 'CLAUDE_PLUGIN_ROOT' '$OC'" +t2 "no allowed-tools frontmatter in port" sh -c "! grep -rq 'allowed-tools:' '$OC/skills'" +t2 "no \$ARGUMENTS in skill bodies" sh -c "! grep -rq 'ARGUMENTS' '$OC/skills'" + +# --- frontmatter: name + description on both skills -------------------------- +for skill in git-wait ship; do + f="$OC/skills/$skill/SKILL.md" + t2 "$skill has name" sh -c "awk '/^---\$/{n++; next} n==1' '$f' | grep -q '^name: '" + t2 "$skill has description" sh -c "awk '/^---\$/{n++; next} n==1' '$f' | grep -q '^description: '" +done + +# --- content fidelity vs the Claude original --------------------------------- +# After normalizing the intended edits (script paths, frontmatter, argument +# wording), the ported bodies must match the originals — catches accidental +# content loss during the port. +for skill in git-wait ship; do + c="$CLAUDE/skills/$skill/SKILL.md" + o="$OC/skills/$skill/SKILL.md" + # strip frontmatter from both, then compare bodies after path normalization + awk '/^---$/{n++; next} n>=2' "$c" >"$TMP/c.body" + awk '/^---$/{n++; next} n>=2' "$o" | + sed -E -e 's#bash scripts/git-wait#bash ${CLAUDE_PLUGIN_ROOT}/scripts/git-wait#g' \ + -e '/^All `scripts\/\.\.\.` paths below/,/^\(provided when the skill loads\)\.$/d' \ + -e 's#If the user explicitly invokes `/ship`#If the user explicitly invokes `/git-tools:ship`#' \ + >"$TMP/o.body" + if [[ "$skill" == "git-wait" ]]; then + # git-wait body must be otherwise identical + if diff -q -B "$TMP/c.body" "$TMP/o.body" >/dev/null; then + pass "git-wait body matches Claude original (modulo intended edits)" + else + fail "git-wait body matches Claude original (modulo intended edits)" "$(diff "$TMP/c.body" "$TMP/o.body" | head -5)" + fi + fi +done + +# ship: full procedure intact — all numbered steps present +for step in "### 0. Read state" "### 1. Detect platform" "### 2. Stage and commit" \ + "### 3. Ensure feature branch" "### 4. Push" "### 5. Create PR" \ + "### 6. Watch CI" "### 7. Wait for merge" "### 8. Watch the post-merge run" \ + "### 9. Return to default branch"; do + t2 "ship has step: $step" grep -qF "$step" "$OC/skills/ship/SKILL.md" +done + +# gh-vs-tea command map survived +t2 "ship/git-wait keep the gh-vs-tea map" grep -qF "tea pulls" "$OC/skills/git-wait/SKILL.md" + +# --- /ship command door ------------------------------------------------------- +t2 "ship command exists" test -s "$OC/commands/ship.md" +t2 "ship command points at the skill" grep -qi "ship.*skill" "$OC/commands/ship.md" +t2 "ship command passes \$ARGUMENTS through" grep -q '\$ARGUMENTS' "$OC/commands/ship.md" + +# --- config snippet ----------------------------------------------------------- +t2 "config snippet has skills array" sh -c "node -e ' + const s = require(\"fs\").readFileSync(\"$OC/opencode.jsonc\", \"utf8\") + .replace(/^\s*\/\/.*\$/gm, \"\").replace(/,(\s*[}\]])/g, \"\$1\"); + const c = JSON.parse(s); + if (!Array.isArray(c.skills) || c.skills.length === 0) process.exit(1); + if (!c.commands || !c.commands.ship || !c.commands.ship.template) process.exit(1); +'" + +echo "" +echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" +[[ $FAIL -eq 0 ]] diff --git a/tests/opencode/test-sync.sh b/tests/opencode/test-sync.sh index a89e49b..d003bc3 100644 --- a/tests/opencode/test-sync.sh +++ b/tests/opencode/test-sync.sh @@ -60,7 +60,7 @@ done for p in format-on-save git-tools kb-capture inbox notify-on-stop session; do mkdir -p "$S/plugins-claude/$p" done -for p in git-tools inbox session; do +for p in git-tools/skills/git-wait git-tools/skills/ship inbox session; do mkdir -p "$S/plugins-opencode/$p" done @@ -71,12 +71,12 @@ run sync check "sync exits 0" 0 "$RC" "$OUT$ERR" run cmp -s "$S/utils/inbox" "$S/plugins-claude/inbox/scripts/inbox" check "claude inbox vendored" 0 "$RC" -run cmp -s "$S/utils/git-wait" "$S/plugins-opencode/git-tools/scripts/git-wait" -check "opencode git-tools vendored git-wait" 0 "$RC" -run cmp -s "$S/utils/branch" "$S/plugins-opencode/git-tools/scripts/branch" -check "opencode git-tools vendored branch" 0 "$RC" -run cmp -s "$S/utils/sitrep" "$S/plugins-opencode/git-tools/scripts/sitrep" -check "opencode git-tools vendored sitrep" 0 "$RC" +run cmp -s "$S/utils/git-wait" "$S/plugins-opencode/git-tools/skills/git-wait/scripts/git-wait" +check "opencode git-wait skill vendored git-wait" 0 "$RC" +run cmp -s "$S/utils/git-wait" "$S/plugins-opencode/git-tools/skills/ship/scripts/git-wait" +check "opencode ship skill vendored git-wait" 0 "$RC" +run test ! -e "$S/plugins-opencode/git-tools/skills/git-wait/scripts/branch" +check "opencode git-tools skills do not receive branch (target-aware manifest)" 0 "$RC" # claude git-tools must NOT receive branch/sitrep (manifest is per-target) run test ! -e "$S/plugins-claude/git-tools/scripts/branch" check "claude git-tools does not receive branch (target-aware manifest)" 0 "$RC" diff --git a/utils/sync.sh b/utils/sync.sh index 9a9adaf..75ec9d8 100755 --- a/utils/sync.sh +++ b/utils/sync.sh @@ -41,7 +41,11 @@ declare -A NEEDS_CLAUDE=( ) declare -A NEEDS_OPENCODE=( - ["git-tools"]="git-wait branch sitrep" + # OpenCode skills get a private base dir (paths in SKILL.md resolve + # relative to it), so scripts are vendored into the skill dir that uses + # them, not the plugin root. Keys may be nested paths. + ["git-tools/skills/git-wait"]="git-wait" + ["git-tools/skills/ship"]="git-wait" ["inbox"]="inbox" ["session"]="git-wait branch sitrep" ) From 409f64afa13a42585e935b498a52a6e91d72bf33 Mon Sep 17 00:00:00 2001 From: Logan Gagne <logan.gagne@gmail.com> Date: Tue, 10 Nov 2026 17:30:55 -0500 Subject: [PATCH 4/6] =?UTF-8?q?feat(opencode):=20M3=20inbox=20=E2=80=94=20?= =?UTF-8?q?RPC=20server=20+=20TUI=20visibility/triage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit utils/inbox gains an optional `blocking` field on questions (--blocking, default false, backfilled via NORMALIZE). Question semantics unchanged: notify-on-stop's count-questions contract holds (149 existing inbox tests green). Server plugin: agent-toolkit.inbox RPC (snapshot/triage) implemented over the vendored CLI so all harnesses share one state file; fs.watch on the state dir emits debounced `changed` events; session.created drops one keyed instruction hint (replaces the Claude hook loop); registers inbox:questions/decisions/followups/show commands. Answer feedback: synthetic message (resume) or instruction entry (stay parked), best-effort. TUI plugin: home.footer.status flag, sidebar open-questions block, /inbox triage panel (answer/acknowledge/refresh, zero model tokens), attention.notify on blocking questions + native form/permission stops. Snapshot-on-mount seeds the store (RPC events are live-only). Verified live against opencode 2.2.6: plugin loads, RPC snapshot/triage round-trip through the HTTP API, commands register. TS typechecks against @opencode/plugin 2.2.7 (tsc --noEmit clean). tests: inbox blocking suite (10), core module node suite (10), existing suites untouched and green. Refs #236 --- plugins-claude/inbox/scripts/inbox | 25 ++- plugins-claude/notify-on-stop/scripts/inbox | 25 ++- plugins-opencode/inbox/README.md | 51 +++++ plugins-opencode/inbox/scripts/inbox | 25 ++- plugins-opencode/inbox/src/core.ts | 97 ++++++++ plugins-opencode/inbox/src/index.ts | 199 ++++++++++++----- plugins-opencode/inbox/src/rpc.ts | 143 ++++++------ plugins-opencode/inbox/src/tui.tsx | 233 ++++++++++++++++++-- tests/inbox/test-inbox-blocking.sh | 99 +++++++++ tests/opencode/test-inbox-core.mjs | 98 ++++++++ tests/opencode/test-inbox-core.sh | 19 ++ utils/inbox | 25 ++- 12 files changed, 886 insertions(+), 153 deletions(-) create mode 100644 plugins-opencode/inbox/README.md create mode 100644 plugins-opencode/inbox/src/core.ts create mode 100644 tests/inbox/test-inbox-blocking.sh create mode 100644 tests/opencode/test-inbox-core.mjs create mode 100644 tests/opencode/test-inbox-core.sh diff --git a/plugins-claude/inbox/scripts/inbox b/plugins-claude/inbox/scripts/inbox index 5069ed2..86be29b 100755 --- a/plugins-claude/inbox/scripts/inbox +++ b/plugins-claude/inbox/scripts/inbox @@ -22,9 +22,12 @@ except for 'prune' and help). Items are referenced as Q<n> (question), D<n> (decision) or F<n> (followup). Commands: - add question --title T [--context C] [--option O]... [--recommend R] [--new] + add question --title T [--context C] [--option O]... [--recommend R] [--blocking] [--new] Park a question that blocks on the user. Refused (exit 3) if a similar - open question exists unless --new is given. + open question exists unless --new is given. --blocking marks the rare + "I cannot proceed at all" stop; harnesses may ping on blocking + questions only. Default false: record the question, state the + assumption, and keep working. add decision --title T [--context C] [--option O]... [--chosen X] [--new] Record a decision already made on a default; --chosen is what was picked, --option the alternatives considered. Refused (exit 3) if a @@ -115,10 +118,14 @@ lock() { flock 9 } -# Fill in any keys an older (questions-only) state file lacks. +# Fill in any keys an older (questions-only) state file lacks. Questions also +# get the `blocking` field backfilled (see below): an item is only `blocking` +# when the agent explicitly parked it with --blocking; everything recorded +# before the field existed defaults to false. Consumers that count questions +# (notify-on-stop, statusline) ignore this field entirely. NORMALIZE='. + { next_id: (.next_id // 1), - questions: (.questions // []), + questions: ((.questions // []) | map(if has("blocking") then . else . + {blocking: false} end)), next_decision_id: (.next_decision_id // 1), decisions: (.decisions // []), next_followup_id: (.next_followup_id // 1), @@ -196,7 +203,7 @@ cmd_add() { *) die "add: expected 'question', 'decision' or 'followup', got '$kind'" 2 ;; esac kind_keys "$kind" - local title="" context="" extra="" force=0 + local title="" context="" extra="" force=0 blocking=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -211,6 +218,9 @@ cmd_add() { --chosen) [[ "$kind" == decision ]] || die "add $kind: --chosen is only for decisions" 2 extra="${2:?--chosen needs a value}"; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "add $kind: --blocking is only for questions" 2 + blocking=1; shift ;; --new) force=1; shift ;; *) die "add $kind: unknown argument: $1" 2 ;; esac @@ -242,8 +252,9 @@ cmd_add() { id=$(jq -r --arg c "$CTR" '.[$c]' <<<"$state") new=$(jq --arg k "$ARR" --arg c "$CTR" --arg kind "$kind" \ --arg t "$title" --arg x "$context" --arg e "$extra" \ - --argjson o "$opts_json" --argjson now "$(date +%s)" ' - (if $kind == "question" then {options: $o, recommendation: $e} + --argjson o "$opts_json" --argjson now "$(date +%s)" \ + --argjson blocking "$( [[ $blocking -eq 1 ]] && echo true || echo false )" ' + (if $kind == "question" then {options: $o, recommendation: $e, blocking: $blocking} elif $kind == "decision" then {options: $o, chosen: $e} else {} end) as $extra | .[$k] += [{id: .[$c], title: $t, context: $x} + $extra + {added: $now}] diff --git a/plugins-claude/notify-on-stop/scripts/inbox b/plugins-claude/notify-on-stop/scripts/inbox index 5069ed2..86be29b 100755 --- a/plugins-claude/notify-on-stop/scripts/inbox +++ b/plugins-claude/notify-on-stop/scripts/inbox @@ -22,9 +22,12 @@ except for 'prune' and help). Items are referenced as Q<n> (question), D<n> (decision) or F<n> (followup). Commands: - add question --title T [--context C] [--option O]... [--recommend R] [--new] + add question --title T [--context C] [--option O]... [--recommend R] [--blocking] [--new] Park a question that blocks on the user. Refused (exit 3) if a similar - open question exists unless --new is given. + open question exists unless --new is given. --blocking marks the rare + "I cannot proceed at all" stop; harnesses may ping on blocking + questions only. Default false: record the question, state the + assumption, and keep working. add decision --title T [--context C] [--option O]... [--chosen X] [--new] Record a decision already made on a default; --chosen is what was picked, --option the alternatives considered. Refused (exit 3) if a @@ -115,10 +118,14 @@ lock() { flock 9 } -# Fill in any keys an older (questions-only) state file lacks. +# Fill in any keys an older (questions-only) state file lacks. Questions also +# get the `blocking` field backfilled (see below): an item is only `blocking` +# when the agent explicitly parked it with --blocking; everything recorded +# before the field existed defaults to false. Consumers that count questions +# (notify-on-stop, statusline) ignore this field entirely. NORMALIZE='. + { next_id: (.next_id // 1), - questions: (.questions // []), + questions: ((.questions // []) | map(if has("blocking") then . else . + {blocking: false} end)), next_decision_id: (.next_decision_id // 1), decisions: (.decisions // []), next_followup_id: (.next_followup_id // 1), @@ -196,7 +203,7 @@ cmd_add() { *) die "add: expected 'question', 'decision' or 'followup', got '$kind'" 2 ;; esac kind_keys "$kind" - local title="" context="" extra="" force=0 + local title="" context="" extra="" force=0 blocking=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -211,6 +218,9 @@ cmd_add() { --chosen) [[ "$kind" == decision ]] || die "add $kind: --chosen is only for decisions" 2 extra="${2:?--chosen needs a value}"; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "add $kind: --blocking is only for questions" 2 + blocking=1; shift ;; --new) force=1; shift ;; *) die "add $kind: unknown argument: $1" 2 ;; esac @@ -242,8 +252,9 @@ cmd_add() { id=$(jq -r --arg c "$CTR" '.[$c]' <<<"$state") new=$(jq --arg k "$ARR" --arg c "$CTR" --arg kind "$kind" \ --arg t "$title" --arg x "$context" --arg e "$extra" \ - --argjson o "$opts_json" --argjson now "$(date +%s)" ' - (if $kind == "question" then {options: $o, recommendation: $e} + --argjson o "$opts_json" --argjson now "$(date +%s)" \ + --argjson blocking "$( [[ $blocking -eq 1 ]] && echo true || echo false )" ' + (if $kind == "question" then {options: $o, recommendation: $e, blocking: $blocking} elif $kind == "decision" then {options: $o, chosen: $e} else {} end) as $extra | .[$k] += [{id: .[$c], title: $t, context: $x} + $extra + {added: $now}] diff --git a/plugins-opencode/inbox/README.md b/plugins-opencode/inbox/README.md new file mode 100644 index 0000000..ec9caeb --- /dev/null +++ b/plugins-opencode/inbox/README.md @@ -0,0 +1,51 @@ +# inbox (OpenCode) + +The OpenCode port of the inbox tracker — and where the port gets *better* than +the original. Claude Code has no persistent per-session UI, so the Claude +version re-injects a "🛑 INPUT NEEDED" banner at `Stop` and a statusline mod. +OpenCode has real TUI slots, so state is **continuously visible** and triage is +**keyboard-driven with zero model tokens**. + +## Shape + +- **Server plugin** (`src/index.ts`): registers the `agent-toolkit.inbox` RPC + (implemented over the vendored `scripts/inbox` CLI — the same state file and + state machine every harness shares), watches the state dir and emits + `changed` events, drops a one-time session instruction hint at + `session.created` (replaces the Claude `SessionStart`/`UserPromptSubmit` + hook loop), and registers the `inbox:questions|decisions|followups|show` + commands. +- **TUI plugin** (`src/tui.tsx`): footer flag (`🛑 N · ✎ D · ☐ F`), sidebar + block with the session's open questions, and an `/inbox` triage panel + (↑/↓ move, `a` answer, `d` acknowledge, `r` refresh). Answering writes + through the CLI and feeds the answer back into the session — as a synthetic + message when you resume it, as an instruction entry otherwise. +- **Shared CLI** (`scripts/inbox`, vendored from `utils/inbox`): the single + source of truth. The new optional `blocking` field on questions defaults to + `false` and does not change what a "question" means for Claude consumers. + +## Non-blocking by default + +Recording a question never stops the agent: it parks the question, states its +assumption (as a decision if it matters), and keeps working. `--blocking` is +the rare genuine "I cannot proceed" stop. The footer/sidebar show everything +passively; only **pings** fire on real stop signals: a `blocking` question +when a run ends, a `question`-tool form, or a permission request +(`attention.notify`, blurred-terminal aware). + +## Install + +```sh +opencode plugin add 'github:St0nefish/agent-toolkit#master::path:plugins-opencode/inbox' +``` + +or point a `plugins` entry at a local checkout. State lives in +`${INBOX_STATE_DIR:-${XDG_STATE_HOME:-~/.local/state}/claude-inbox}` — shared +with the Claude plugin; session IDs differ per harness so there is no +collision. + +## What did NOT port (deliberately) + +- The `Stop`-hook banner, the prompt re-injection loop, the statusline mod — + all replaced by continuous TUI visibility. +- `/inbox:triage` as a conversation — the panel does it with zero model tokens. diff --git a/plugins-opencode/inbox/scripts/inbox b/plugins-opencode/inbox/scripts/inbox index 5069ed2..86be29b 100755 --- a/plugins-opencode/inbox/scripts/inbox +++ b/plugins-opencode/inbox/scripts/inbox @@ -22,9 +22,12 @@ except for 'prune' and help). Items are referenced as Q<n> (question), D<n> (decision) or F<n> (followup). Commands: - add question --title T [--context C] [--option O]... [--recommend R] [--new] + add question --title T [--context C] [--option O]... [--recommend R] [--blocking] [--new] Park a question that blocks on the user. Refused (exit 3) if a similar - open question exists unless --new is given. + open question exists unless --new is given. --blocking marks the rare + "I cannot proceed at all" stop; harnesses may ping on blocking + questions only. Default false: record the question, state the + assumption, and keep working. add decision --title T [--context C] [--option O]... [--chosen X] [--new] Record a decision already made on a default; --chosen is what was picked, --option the alternatives considered. Refused (exit 3) if a @@ -115,10 +118,14 @@ lock() { flock 9 } -# Fill in any keys an older (questions-only) state file lacks. +# Fill in any keys an older (questions-only) state file lacks. Questions also +# get the `blocking` field backfilled (see below): an item is only `blocking` +# when the agent explicitly parked it with --blocking; everything recorded +# before the field existed defaults to false. Consumers that count questions +# (notify-on-stop, statusline) ignore this field entirely. NORMALIZE='. + { next_id: (.next_id // 1), - questions: (.questions // []), + questions: ((.questions // []) | map(if has("blocking") then . else . + {blocking: false} end)), next_decision_id: (.next_decision_id // 1), decisions: (.decisions // []), next_followup_id: (.next_followup_id // 1), @@ -196,7 +203,7 @@ cmd_add() { *) die "add: expected 'question', 'decision' or 'followup', got '$kind'" 2 ;; esac kind_keys "$kind" - local title="" context="" extra="" force=0 + local title="" context="" extra="" force=0 blocking=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -211,6 +218,9 @@ cmd_add() { --chosen) [[ "$kind" == decision ]] || die "add $kind: --chosen is only for decisions" 2 extra="${2:?--chosen needs a value}"; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "add $kind: --blocking is only for questions" 2 + blocking=1; shift ;; --new) force=1; shift ;; *) die "add $kind: unknown argument: $1" 2 ;; esac @@ -242,8 +252,9 @@ cmd_add() { id=$(jq -r --arg c "$CTR" '.[$c]' <<<"$state") new=$(jq --arg k "$ARR" --arg c "$CTR" --arg kind "$kind" \ --arg t "$title" --arg x "$context" --arg e "$extra" \ - --argjson o "$opts_json" --argjson now "$(date +%s)" ' - (if $kind == "question" then {options: $o, recommendation: $e} + --argjson o "$opts_json" --argjson now "$(date +%s)" \ + --argjson blocking "$( [[ $blocking -eq 1 ]] && echo true || echo false )" ' + (if $kind == "question" then {options: $o, recommendation: $e, blocking: $blocking} elif $kind == "decision" then {options: $o, chosen: $e} else {} end) as $extra | .[$k] += [{id: .[$c], title: $t, context: $x} + $extra + {added: $now}] diff --git a/plugins-opencode/inbox/src/core.ts b/plugins-opencode/inbox/src/core.ts new file mode 100644 index 0000000..9ee86e3 --- /dev/null +++ b/plugins-opencode/inbox/src/core.ts @@ -0,0 +1,97 @@ +// Core inbox access: everything here is harness-free (no @opencode/plugin +// imports) so it can be unit-tested directly with node. The server part wires +// this to RPC; the TUI never touches the filesystem (it may be attached to a +// remote server) and goes through RPC instead. +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { fileURLToPath } from "node:url" +import path from "node:path" +import os from "node:os" + +const exec = promisify(execFile) + +// Vendored from utils/inbox by utils/sync.sh — same CLI the Claude plugin +// uses, so both harnesses share one state file and the CLI's dedupe/locking +// stays the single source of truth. +export function inboxCliPath(): string { + return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "scripts", "inbox") +} + +export function inboxStateDir(): string { + const xdg = process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state") + return process.env.INBOX_STATE_DIR || path.join(xdg, "claude-inbox") +} + +export type InboxItem = { + id: number + title: string + context?: string + options?: string[] + recommendation?: string + chosen?: string + blocking?: boolean + added?: number + [k: string]: unknown +} + +export type Counts = { + questions: number + decisions: number + followups: number + blocking: number +} + +export type Snapshot = { + counts: Counts + items: { questions: InboxItem[]; decisions: InboxItem[]; followups: InboxItem[] } +} + +export const EMPTY_COUNTS: Counts = { questions: 0, decisions: 0, followups: 0, blocking: 0 } + +export function countsOf(items: Snapshot["items"]): Counts { + return { + questions: items.questions.length, + decisions: items.decisions.length, + followups: items.followups.length, + blocking: items.questions.filter((q) => q.blocking === true).length, + } +} + +// The CLI is the state machine: dedupe, locking, and the schema all live +// there. A missing state file is an empty inbox (the CLI prints empty arrays). +export async function readSnapshot(sessionID: string, cli = inboxCliPath()): Promise<Snapshot> { + const { stdout } = await exec("bash", [cli, "--session", sessionID, "list", "--json"]) + const parsed = JSON.parse(stdout) as Partial<Snapshot["items"]> + const items = { + questions: parsed.questions ?? [], + decisions: parsed.decisions ?? [], + followups: parsed.followups ?? [], + } + return { counts: countsOf(items), items } +} + +export type TriageAction = "answer" | "resolve" | "done" + +const TRIAGE_VERBS: Record<TriageAction, string> = { answer: "answered", resolve: "resolved", done: "completed" } + +// Run a triage action through the CLI (source of truth), then re-read. +export async function runTriage( + sessionID: string, + action: TriageAction, + id: string, + note?: string, + cli = inboxCliPath(), +): Promise<Snapshot> { + const args = ["--session", sessionID, action, id] + if (note) args.push("--note", note) + await exec("bash", [cli, ...args]) + return readSnapshot(sessionID, cli) +} + +// Feedback text fed back into the session after an answer, so the parked +// agent (or the next step boundary) learns the user's reply. +export function answerFeedback(id: string, note: string): string { + return `The user answered inbox question ${id}: ${note}. Take this as settled and proceed accordingly; record any resulting choice as a decision if you deviate from the stated assumption.` +} + +export { TRIAGE_VERBS } diff --git a/plugins-opencode/inbox/src/index.ts b/plugins-opencode/inbox/src/index.ts index 2eeef64..8f447a7 100644 --- a/plugins-opencode/inbox/src/index.ts +++ b/plugins-opencode/inbox/src/index.ts @@ -1,56 +1,155 @@ import { Plugin } from "@opencode/plugin" -import { execFile } from "node:child_process" -import { promisify } from "node:util" -import { fileURLToPath } from "node:url" -import path from "node:path" +import fs from "node:fs" +import { + readSnapshot, + runTriage, + inboxCliPath, + inboxStateDir, + answerFeedback, + type TriageAction, + type Snapshot, +} from "./core.js" import { Inbox } from "./rpc.js" -const exec = promisify(execFile) - -// Vendored from utils/inbox by utils/sync.sh — same CLI the Claude plugin -// uses, so both harnesses share one state file and the CLI's dedupe/locking -// stays the single source of truth. -const scriptDir = path.dirname(fileURLToPath(import.meta.url)) -const INBOX_CLI = path.resolve(scriptDir, "..", "scripts", "inbox") - -type Counts = { questions: number; decisions: number; followups: number; blocking: number } - -type InboxItem = { id?: string; title?: string; blocking?: boolean; [k: string]: unknown } - -type Snapshot = { counts: Counts; items: { questions: InboxItem[]; decisions: InboxItem[]; followups: InboxItem[] } } - -export async function readSnapshot(sessionID: string): Promise<Snapshot> { - const { stdout } = await exec(INBOX_CLI, ["--session", sessionID, "list", "--json"]) - const parsed = JSON.parse(stdout) as { - questions: InboxItem[] - decisions: InboxItem[] - followups: InboxItem[] - } - const items = { - questions: parsed.questions ?? [], - decisions: parsed.decisions ?? [], - followups: parsed.followups ?? [], - } - return { - counts: { - questions: items.questions.length, - decisions: items.decisions.length, - followups: items.followups.length, - blocking: items.questions.filter((q) => q.blocking === true).length, - }, - items, - } -} +const HINT_KEY = "agent-toolkit-inbox" +const WATCH_DEBOUNCE_MS = 200 + +const LIST_KINDS = { + "inbox:questions": { kind: "question", header: "Open inbox questions for this session" }, + "inbox:decisions": { kind: "decision", header: "Open inbox decisions for this session" }, + "inbox:followups": { kind: "followup", header: "Open inbox followups for this session" }, + "inbox:show": { kind: "", header: "Full inbox for this session" }, +} as const export default Plugin.define({ - id: "agent-toolkit.inbox", - async setup(ctx) { - const registration = await ctx.rpc.register(Inbox, { - snapshot: async (input) => { - const { sessionID } = input as { sessionID: string } - return readSnapshot(sessionID) - }, - }) - return () => void registration.dispose() - }, + id: "agent-toolkit.inbox", + async setup(ctx) { + const cli = inboxCliPath() + const stateDir = inboxStateDir() + fs.mkdirSync(stateDir, { recursive: true }) + + const registration = await ctx.rpc.register(Inbox, { + snapshot: async (input) => { + const { sessionID } = input as { sessionID: string } + return (await readSnapshot(sessionID, cli)) as Snapshot + }, + triage: async (input, context) => { + const { sessionID, action, id, note, resume } = input as { + sessionID: string + action: TriageAction + id: string + note?: string + resume?: boolean + } + let snap: Snapshot + try { + snap = await runTriage(sessionID, action, id, note, cli) + } catch (err) { + const message = String(err instanceof Error ? err.message : err) + return context.error("cli_failed", message, { message }) + } + // Feed the answer back so the parked agent learns it. Default: + // instruction entry applied at the next step boundary (stay + // parked). resume: true → synthetic message, continue now. + // Best-effort: the state change already landed; a dead session + // must not turn a successful triage into an RPC error. + if (action === "answer" && note) { + const text = answerFeedback(id, note) + try { + if (resume) await ctx.session.synthetic({ sessionID, text }) + else await ctx.session.instructions.entry.put({ sessionID, key: `${HINT_KEY}:answer:${id}`, value: text }) + } catch { + /* session gone or not promptable; the answer is still recorded */ + } + } + await registration.events.emit("changed", { sessionID, counts: snap.counts }) + return snap + }, + }) + + // --- state dir watch → changed events --------------------------------- + // The CLI is the writer (any harness); fs.watch keeps every connected + // TUI current without polling. Debounced per session; a failed read is + // just a missed beat — the next event or a fresh snapshot() recovers. + const timers = new Map<string, NodeJS.Timeout>() + const watcher = fs.watch(stateDir, (_event, filename) => { + if (!filename || !filename.endsWith(".json")) return + const sessionID = filename.slice(0, -".json".length) + const existing = timers.get(sessionID) + if (existing) clearTimeout(existing) + timers.set( + sessionID, + setTimeout(async () => { + timers.delete(sessionID) + try { + const snap = await readSnapshot(sessionID, cli) + await registration.events.emit("changed", { sessionID, counts: snap.counts }) + } catch { + /* transient write race; next event retries */ + } + }, WATCH_DEBOUNCE_MS), + ) + }) + + // --- session hint (replaces Claude's SessionStart hook) --------------- + // One keyed instruction entry per session: survives compaction, applies + // at the next step boundary, costs no extra model turn. + const controller = new AbortController() + void (async () => { + for await (const event of ctx.event.subscribe({ types: ["session.created"], signal: controller.signal })) { + const data = event.data as { id?: string; sessionID?: string; session?: { id?: string } } + const sessionID = data.session?.id ?? data.id ?? data.sessionID + if (!sessionID) continue + await ctx.session.instructions + .entry.put({ + sessionID, + key: HINT_KEY, + value: + `Inbox tracker is active for this session. Record blockers, decisions, and followups with: ` + + `bash ${cli} --session ${sessionID} add question|decision|followup --title T [--context C] [--option O]... ` + + `Questions are NON-BLOCKING by default: park the question, state your assumption as a decision if needed, and keep working. ` + + `Pass --blocking only when you genuinely cannot proceed without the user. ` + + `Never poll or ask the user to check the inbox; the user reviews it from the sidebar/panel.`, + }) + .catch(() => { + /* session may already be gone */ + }) + } + })() + + // --- read commands (parity with the Claude inbox skills) -------------- + // Claude ran the CLI through `!` blocks in skill bodies; OpenCode skills + // can't, and command files can't resolve plugin-relative paths — so the + // plugin registers the commands and shells out itself. + const commandReg = await ctx.command.transform((editor) => { + for (const [name, { kind, header }] of Object.entries(LIST_KINDS)) { + editor.add({ + name, + description: `Show ${name.split(":")[1]} from the session inbox`, + execute: async ({ sessionID, prompt, delivery }) => { + const args = ["--session", sessionID, "list", "--format", "text"] + if (kind) args.push("--kind", kind) + const { execFile } = await import("node:child_process") + const { promisify } = await import("node:util") + const output = await promisify(execFile)("bash", [cli, ...args]).then((r) => r.stdout.trim()) + await ctx.session.prompt({ + ...prompt, + sessionID, + delivery, + text: `${header} (present the list to the user as-is; do not act on it unless they ask):\n\n${output || "(inbox empty)"}`, + }) + }, + }) + } + }) + + return () => { + controller.abort() + watcher.close() + for (const t of timers.values()) clearTimeout(t) + timers.clear() + void commandReg.dispose() + void registration.dispose() + } + }, }) diff --git a/plugins-opencode/inbox/src/rpc.ts b/plugins-opencode/inbox/src/rpc.ts index 9ec5404..39134d3 100644 --- a/plugins-opencode/inbox/src/rpc.ts +++ b/plugins-opencode/inbox/src/rpc.ts @@ -4,67 +4,86 @@ import { Rpc } from "@opencode/plugin/rpc" // client. The server implements it over the vendored `scripts/inbox` CLI so // every harness shares one state file; the TUI only ever talks RPC (it may be // attached to a remote server and must not read local files). +const countsSchema = { + type: "object", + properties: { + questions: { type: "number" }, + decisions: { type: "number" }, + followups: { type: "number" }, + blocking: { type: "number" }, + }, + required: ["questions", "decisions", "followups", "blocking"], + additionalProperties: false, +} as const + +const itemsSchema = { + type: "object", + properties: { + questions: { type: "array", items: { type: "object" } }, + decisions: { type: "array", items: { type: "object" } }, + followups: { type: "array", items: { type: "object" } }, + }, + required: ["questions", "decisions", "followups"], + additionalProperties: false, +} as const + +const snapshotSchema = { + type: "object", + properties: { counts: countsSchema, items: itemsSchema }, + required: ["counts", "items"], + additionalProperties: false, +} as const + export const Inbox = Rpc.define({ - id: "agent-toolkit.inbox", - methods: { - snapshot: { - input: { - type: "object", - properties: { sessionID: { type: "string" } }, - required: ["sessionID"], - additionalProperties: false, - }, - output: { - type: "object", - properties: { - counts: { - type: "object", - properties: { - questions: { type: "number" }, - decisions: { type: "number" }, - followups: { type: "number" }, - blocking: { type: "number" }, - }, - required: ["questions", "decisions", "followups", "blocking"], - additionalProperties: false, - }, - items: { - type: "object", - properties: { - questions: { type: "array", items: { type: "object" } }, - decisions: { type: "array", items: { type: "object" } }, - followups: { type: "array", items: { type: "object" } }, - }, - required: ["questions", "decisions", "followups"], - additionalProperties: false, - }, - }, - required: ["counts", "items"], - additionalProperties: false, - }, - }, - }, - events: { - changed: { - schema: { - type: "object", - properties: { - sessionID: { type: "string" }, - counts: { - type: "object", - properties: { - questions: { type: "number" }, - decisions: { type: "number" }, - followups: { type: "number" }, - blocking: { type: "number" }, - }, - required: ["questions", "decisions", "followups", "blocking"], - additionalProperties: false, - }, - }, - required: ["sessionID", "counts"], - additionalProperties: false, - }, - }, - }, + id: "agent-toolkit.inbox", + methods: { + snapshot: { + input: { + type: "object", + properties: { sessionID: { type: "string" } }, + required: ["sessionID"], + additionalProperties: false, + }, + output: snapshotSchema, + }, + // Triage from the TUI panel: answer Q<n> / resolve D<n> / done F<n>. + // `resume: true` on an answer pushes a synthetic message so a parked + // session continues now; otherwise the answer lands as a session + // instruction entry applied at the next step boundary. + triage: { + input: { + type: "object", + properties: { + sessionID: { type: "string" }, + action: { type: "string", enum: ["answer", "resolve", "done"] }, + // ref shape (Q1/D2/F3) is validated by the CLI itself; + // JSON Schema `pattern` is disabled in RPC validation. + id: { type: "string" }, + note: { type: "string" }, + resume: { type: "boolean" }, + }, + required: ["sessionID", "action", "id"], + additionalProperties: false, + }, + output: snapshotSchema, + errors: { + cli_failed: { + type: "object", + properties: { message: { type: "string" } }, + required: ["message"], + additionalProperties: false, + }, + }, + }, + }, + events: { + changed: { + schema: { + type: "object", + properties: { sessionID: { type: "string" }, counts: countsSchema }, + required: ["sessionID", "counts"], + additionalProperties: false, + }, + }, + }, }) diff --git a/plugins-opencode/inbox/src/tui.tsx b/plugins-opencode/inbox/src/tui.tsx index 804be1e..9da2e88 100644 --- a/plugins-opencode/inbox/src/tui.tsx +++ b/plugins-opencode/inbox/src/tui.tsx @@ -1,17 +1,224 @@ -import { Plugin } from "@opencode/plugin/tui" +import { Plugin, usePlugin } from "@opencode/plugin/tui" +import type { PanelInput } from "@opencode/plugin/tui/context" +import { createSignal, createEffect, For, Show } from "solid-js" import { Inbox } from "./rpc.js" +import type { Counts, InboxItem, Snapshot } from "./core.js" + +const PANEL = "agent-toolkit.inbox" + +const EMPTY: Counts = { questions: 0, decisions: 0, followups: 0, blocking: 0 } + +// Client-side store of snapshots, seeded by RPC (the TUI may be attached to a +// remote server — never read the state dir here). RPC events are live-only, +// so every consumer pulls a snapshot on mount and patches from then on. +function useInboxStore(context: { client: { rpc: (def: typeof Inbox) => any } }) { + const rpc = context.client.rpc(Inbox) + const [store, setStore] = createSignal<Record<string, Snapshot>>({}) + const inflight = new Set<string>() + + async function refresh(sessionID: string) { + if (inflight.has(sessionID)) return + inflight.add(sessionID) + try { + const snap = (await rpc.snapshot({ sessionID })) as unknown as Snapshot + setStore((s) => ({ ...s, [sessionID]: snap })) + } catch { + /* server unreachable or session gone; next event or mount retries */ + } finally { + inflight.delete(sessionID) + } + } + + const stop = rpc.events.on("changed", (event: { data: { sessionID: string } }) => { + const { sessionID } = event.data + void refresh(sessionID) + }) + + return { rpc, store, refresh, stop, counts: (id: string): Counts => store()[id]?.counts ?? EMPTY } +} + +type Store = ReturnType<typeof useInboxStore> + +// --- triage panel ------------------------------------------------------------- + +function InboxPanel(props: { panel: PanelInput }) { + const context = usePlugin() + const store = (context as unknown as { __inbox: Store }).__inbox + const sessionID = () => props.panel.sessionID + + type Row = { ref: string; kind: "question" | "decision" | "followup"; title: string; blocking: boolean } + const rows = (): Row[] => { + const snap = store.store()[sessionID()] + if (!snap) return [] + const map = (items: InboxItem[], kind: Row["kind"], pfx: string): Row[] => + items.map((it) => ({ + ref: `${pfx}${it.id}`, + kind, + title: it.title, + blocking: kind === "question" && it.blocking === true, + })) + return [ + ...map(snap.items.questions, "question", "Q"), + ...map(snap.items.decisions, "decision", "D"), + ...map(snap.items.followups, "followup", "F"), + ] + } + + const [sel, setSel] = createSignal(0) + createEffect(() => void store.refresh(sessionID())) + context.keymap.layer(() => { + const n = rows().length + const clamp = (i: number) => (n === 0 ? 0 : Math.max(0, Math.min(n - 1, i))) + return { + commands: [ + { id: "inbox.down", title: "Next item", bind: "down", run: () => { setSel((i) => clamp(i + 1)) } }, + { id: "inbox.up", title: "Previous item", bind: "up", run: () => { setSel((i) => clamp(i - 1)) } }, + { + id: "inbox.answer", + title: "Answer question", + bind: "a", + run: async () => { + const row = rows()[sel()] + if (!row || row.kind !== "question") return + const note = await context.ui.dialog.prompt({ + title: `Answer ${row.ref}`, + placeholder: "Your answer…", + }) + if (note === undefined) return + await store.rpc.triage({ sessionID: sessionID(), action: "answer", id: row.ref, note, resume: true }) + }, + }, + { + id: "inbox.resolve", + title: "Acknowledge decision/followup", + bind: "d", + run: async () => { + const row = rows()[sel()] + if (!row || row.kind === "question") return + await store.rpc.triage({ sessionID: sessionID(), action: row.kind === "decision" ? "resolve" : "done", id: row.ref }) + }, + }, + { id: "inbox.refresh", title: "Refresh", bind: "r", run: () => store.refresh(sessionID()) }, + ], + } + }) + + const kindLabel = { question: "🛑 question", decision: "✎ decision", followup: "☐ followup" } as const + return ( + <box> + <text fg={context.theme.text.base}>Inbox — {sessionID()}</text> + <Show when={rows().length === 0}> + <text fg={context.theme.text.muted}>Nothing open. </text> + </Show> + <For each={rows()}> + {(row, i) => ( + <text fg={i() === sel() ? context.theme.background.base : context.theme.text.muted} bg={i() === sel() ? context.theme.text.base : undefined}> + {`${row.blocking ? "🛑" : kindLabel[row.kind].slice(0, 1)} ${row.ref} ${row.title}`} + </text> + )} + </For> + <text fg={context.theme.text.muted}>↑/↓ move · a answer · d acknowledge · r refresh</text> + </box> + ) +} + +// --- plugin ------------------------------------------------------------------- -// M0 scaffold: proves the RPC + TUI slot wiring end to end. M3 replaces this -// with the seeded signal, sidebar block, and triage panel. export default Plugin.define({ - id: "agent-toolkit.inbox.tui", - setup(context) { - return context.ui.slot({ - append: "home.footer.status", - render: () => { - void context.client.rpc(Inbox) - return null - }, - }) - }, + id: "agent-toolkit.inbox.tui", + setup(context) { + const store = useInboxStore(context) + // The panel component needs the store; usePlugin() hands it the context. + ;(context as unknown as { __inbox: Store }).__inbox = store + + // Footer flag for the current session (home screen has no session, so + // resolve the most recently updated one and re-render on switch). + const currentSession = (): string | undefined => { + const sessions = context.data.session.list() as Array<{ id: string; time?: { updated?: number } }> + if (!sessions?.length) return undefined + return sessions.toSorted((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0))[0]?.id + } + const unFooter = context.ui.slot({ + append: "home.footer.status", + render: () => { + const id = currentSession() + if (!id) return null + const c = store.counts(id) + if (c.questions + c.decisions + c.followups === 0) return null + return <text>{`🛑 ${c.questions} · ✎ ${c.decisions} · ☐ ${c.followups}`}</text> + }, + }) + + // Sidebar: open questions for the session being rendered. + const unSidebar = context.ui.slot({ + append: "sidebar.content", + render: ({ sessionID }: { sessionID: string }) => { + createEffect(() => void store.refresh(sessionID)) + const snap = () => store.store()[sessionID] + return ( + <Show when={(snap()?.items.questions.length ?? 0) > 0}> + <text fg={context.theme.text.base}>Inbox</text> + <For each={snap()?.items.questions ?? []}> + {(q) => <text fg={context.theme.text.muted}>{`${q.blocking ? "🛑" : "·"} ${q.title}`}</text>} + </For> + </Show> + ) + }, + }) + + // Triage panel + /inbox door. + const unPanel = context.ui.slot({ + append: "session.panel", + render: (panel: PanelInput) => ( + <Show when={panel.name === PANEL}> + <InboxPanel panel={panel} /> + </Show> + ), + }) + context.keymap.layer(() => ({ + mode: "global", + priority: 10, + commands: [ + { + id: "agent-toolkit.inbox.open", + title: "Open inbox", + group: "Inbox", + palette: true, + slash: { name: "inbox" }, + run: () => { + context.ui.panel.open(PANEL) + }, + }, + ], + bindings: [], + })) + + // Attention: ping only on genuine stop signals — a blocking question + // when a run ends, or the native question-tool form / permission ask. + // Open non-blocking items stay passive (sidebar/footer only). + const ping = (message: string) => + context.attention + .notify({ title: "agent-toolkit inbox", message, notification: { when: "blurred" }, sound: { name: "done", volume: 0.5, when: "always" } }) + .catch(() => {}) + const offs = [ + context.data.on("session.execution.succeeded", (event) => { + const sid = (event.data as { sessionID?: string })?.sessionID + if (!sid) return + void (async () => { + await store.refresh(sid) + if (store.counts(sid).blocking > 0) void ping("A blocking question needs you") + })() + }), + context.data.on("form.created", () => void ping("The agent is waiting for your answer")), + context.data.on("permission.asked", () => void ping("The agent needs permission")), + ] + + return () => { + store.stop() + unFooter() + unSidebar() + unPanel() + for (const off of offs) off() + } + }, }) diff --git a/tests/inbox/test-inbox-blocking.sh b/tests/inbox/test-inbox-blocking.sh new file mode 100644 index 0000000..c43445c --- /dev/null +++ b/tests/inbox/test-inbox-blocking.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# test-inbox-blocking.sh — the optional `blocking` field on questions: +# default false, --blocking sets it, question-only, backfilled on legacy +# state files, and invisible to the "count questions" contract that +# notify-on-stop depends on. +# +# Usage: bash tests/inbox/test-inbox-blocking.sh [filter] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +Q="$SCRIPT_DIR/../../utils/inbox" + +PASS=0 +FAIL=0 +FILTER="${1:-}" + +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT +export INBOX_STATE_DIR="$TMP/state" +unset INBOX_SESSION + +pass() { + printf " \033[32m✓\033[0m %s\n" "$1" + ((PASS++)) || true +} +fail() { + printf " \033[31m✗\033[0m %s (%s)\n" "$1" "$2" + ((FAIL++)) || true +} + +RC=0 +OUT="" +q() { + RC=0 + OUT=$("$@" 2>&1) || RC=$? +} +t() { # <label> <expect: 0|nonzero> — check $RC from last q + local label="$1" expect="$2" + if [[ -n "$FILTER" ]] && ! echo "$label" | grep -qi "$FILTER"; then return; fi + if [[ "$expect" == "0" && $RC -eq 0 ]] || [[ "$expect" == "nonzero" && $RC -ne 0 ]]; then + pass "$label" + else + fail "$label" "exit=$RC out=$OUT" + fi +} + +S=(--session blocktest) + +# default: blocking=false +q bash "$Q" "${S[@]}" add question --title "Default question?" +t "add question succeeds" 0 +q bash "$Q" "${S[@]}" list --kind question --json +echo "$OUT" | jq -e '.[0].blocking == false' >/dev/null +t "default question has blocking=false" 0 + +# --blocking sets true +q bash "$Q" "${S[@]}" add question --blocking --title "Hard stop?" +t "add question --blocking succeeds" 0 +q bash "$Q" "${S[@]}" list --kind question --json +echo "$OUT" | jq -e '[.[] | select(.blocking == true)] | length == 1' >/dev/null +t "blocking question has blocking=true" 0 + +# question-only flags +q bash "$Q" "${S[@]}" add decision --blocking --title "A decision" +t "decision --blocking rejected" nonzero +q bash "$Q" "${S[@]}" add followup --blocking --title "A followup" +t "followup --blocking rejected" nonzero + +# count contract unchanged: counts ALL questions regardless of blocking +q bash "$Q" "${S[@]}" count --kind question +if [[ "$OUT" == "2" ]]; then pass "count --kind question counts both (notify-on-stop contract)"; else fail "count --kind question counts both (notify-on-stop contract)" "got: $OUT"; fi + +# legacy state file backfill: hand-write a pre-blocking question +LEG="$TMP/state/legacy.json" +mkdir -p "$TMP/state" +cat >"$LEG" <<'EOF' +{"next_id":2,"questions":[{"id":1,"title":"Old question?","context":"","options":[],"recommendation":"","added":1}]} +EOF +q bash "$Q" --session legacy list --kind question --json +echo "$OUT" | jq -e '.[0].blocking == false' >/dev/null +t "legacy question backfilled with blocking=false" 0 + +# answer works on legacy state and removes the item +q bash "$Q" --session legacy answer Q1 +if [[ $RC -eq 0 ]] && jq -e '.questions | length == 0' "$LEG" >/dev/null; then + pass "answer on legacy state works" +else + fail "answer on legacy state works" "exit=$RC state=$(cat "$LEG")" +fi + +# json shape: blocking present on every question in combined --json too +q bash "$Q" "${S[@]}" list --json +echo "$OUT" | jq -e '.questions | all(has("blocking"))' >/dev/null +t "combined --json questions all carry blocking" 0 + +echo "" +echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" +[[ $FAIL -eq 0 ]] diff --git a/tests/opencode/test-inbox-core.mjs b/tests/opencode/test-inbox-core.mjs new file mode 100644 index 0000000..b041fcc --- /dev/null +++ b/tests/opencode/test-inbox-core.mjs @@ -0,0 +1,98 @@ +// test-inbox-core.mjs — unit tests for the harness-free inbox core module +// (snapshot parsing, counts, blocking, triage round-trips against the real +// vendored CLI with a sandboxed state dir). Run via test-inbox-core.sh. +import assert from "node:assert/strict" +import { execFileSync } from "node:child_process" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" + +const repo = path.resolve(import.meta.dirname, "../..") +const CLI = path.join(repo, "plugins-opencode/inbox/scripts/inbox") + +const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "inbox-core-")) +process.env.INBOX_STATE_DIR = path.join(TMP, "state") + +const core = await import(path.join(repo, "plugins-opencode/inbox/src/core.ts")) + +let pass = 0 +let fail = 0 +const t = async (label, fn) => { + try { + await fn() + console.log(` \x1b[32m✓\x1b[0m ${label}`) + pass++ + } catch (err) { + console.log(` \x1b[31m✗\x1b[0m ${label} (${err.message})`) + fail++ + } +} + +const cli = (...args) => execFileSync("bash", [CLI, ...args], { encoding: "utf8" }) + +await t("inboxStateDir honors INBOX_STATE_DIR", () => { + assert.equal(core.inboxStateDir(), process.env.INBOX_STATE_DIR) +}) + +await t("inboxCliPath resolves inside the plugin", () => { + assert.ok(fs.existsSync(core.inboxCliPath()), core.inboxCliPath()) +}) + +await t("empty session snapshot is all zeros", async () => { + const snap = await core.readSnapshot("core-empty") + assert.deepEqual(snap.counts, { questions: 0, decisions: 0, followups: 0, blocking: 0 }) +}) + +cli("--session", "core-mixed", "add", "question", "--title", "Plain?") +cli("--session", "core-mixed", "add", "question", "--blocking", "--title", "Hard stop?") +cli("--session", "core-mixed", "add", "decision", "--title", "Chose X", "--chosen", "X") +cli("--session", "core-mixed", "add", "followup", "--title", "Add docs") + +await t("counts reflect all kinds and blocking", async () => { + const snap = await core.readSnapshot("core-mixed") + assert.deepEqual(snap.counts, { questions: 2, decisions: 1, followups: 1, blocking: 1 }) +}) + +await t("items carry titles and blocking flags", async () => { + const snap = await core.readSnapshot("core-mixed") + assert.equal(snap.items.questions[1].blocking, true) + assert.equal(snap.items.questions[0].blocking, false) + assert.equal(snap.items.questions[1].title, "Hard stop?") +}) + +await t("countsOf computes from items", () => { + const c = core.countsOf({ + questions: [{ id: 1, title: "a", blocking: true }, { id: 2, title: "b" }], + decisions: [], + followups: [{ id: 1, title: "f" }], + }) + assert.deepEqual(c, { questions: 2, decisions: 0, followups: 1, blocking: 1 }) +}) + +await t("runTriage answer removes the question and returns fresh snapshot", async () => { + const snap = await core.runTriage("core-mixed", "answer", "Q1") + assert.equal(snap.counts.questions, 1) + assert.equal(snap.counts.blocking, 1) // the blocking one remains +}) + +await t("runTriage resolve/done clear decisions/followups", async () => { + let snap = await core.runTriage("core-mixed", "resolve", "D1") + assert.equal(snap.counts.decisions, 0) + snap = await core.runTriage("core-mixed", "done", "F1") + assert.equal(snap.counts.followups, 0) +}) + +await t("runTriage on a missing item rejects (caller surfaces cli_failed)", async () => { + await assert.rejects(() => core.runTriage("core-mixed", "answer", "Q99")) +}) + +await t("answerFeedback names the item and the note", () => { + const text = core.answerFeedback("Q3", "use postgres") + assert.match(text, /Q3/) + assert.match(text, /use postgres/) +}) + +console.log("") +console.log(`Total: ${pass + fail} PASS: ${pass} FAIL: ${fail}`) +fs.rmSync(TMP, { recursive: true, force: true }) +process.exit(fail === 0 ? 0 : 1) diff --git a/tests/opencode/test-inbox-core.sh b/tests/opencode/test-inbox-core.sh new file mode 100644 index 0000000..00350c6 --- /dev/null +++ b/tests/opencode/test-inbox-core.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# test-inbox-core.sh — run the inbox core module's node unit tests. +# Requires a node that can import .ts directly (node >= 23 with type +# stripping). Skips with a note on older runtimes, mirroring the +# lint-shell.sh philosophy: hard in CI, warning locally. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +if ! node --version | grep -qE 'v(2[3-9]|[3-9][0-9])'; then + if [[ -n "${CI:-}" ]]; then + echo "node >= 23 required for TS type stripping and CI is set — refusing to skip" >&2 + exit 1 + fi + echo "node >= 23 required — skipping inbox core tests" >&2 + exit 0 +fi + +exec node "$SCRIPT_DIR/test-inbox-core.mjs" "$@" diff --git a/utils/inbox b/utils/inbox index 5069ed2..86be29b 100755 --- a/utils/inbox +++ b/utils/inbox @@ -22,9 +22,12 @@ except for 'prune' and help). Items are referenced as Q<n> (question), D<n> (decision) or F<n> (followup). Commands: - add question --title T [--context C] [--option O]... [--recommend R] [--new] + add question --title T [--context C] [--option O]... [--recommend R] [--blocking] [--new] Park a question that blocks on the user. Refused (exit 3) if a similar - open question exists unless --new is given. + open question exists unless --new is given. --blocking marks the rare + "I cannot proceed at all" stop; harnesses may ping on blocking + questions only. Default false: record the question, state the + assumption, and keep working. add decision --title T [--context C] [--option O]... [--chosen X] [--new] Record a decision already made on a default; --chosen is what was picked, --option the alternatives considered. Refused (exit 3) if a @@ -115,10 +118,14 @@ lock() { flock 9 } -# Fill in any keys an older (questions-only) state file lacks. +# Fill in any keys an older (questions-only) state file lacks. Questions also +# get the `blocking` field backfilled (see below): an item is only `blocking` +# when the agent explicitly parked it with --blocking; everything recorded +# before the field existed defaults to false. Consumers that count questions +# (notify-on-stop, statusline) ignore this field entirely. NORMALIZE='. + { next_id: (.next_id // 1), - questions: (.questions // []), + questions: ((.questions // []) | map(if has("blocking") then . else . + {blocking: false} end)), next_decision_id: (.next_decision_id // 1), decisions: (.decisions // []), next_followup_id: (.next_followup_id // 1), @@ -196,7 +203,7 @@ cmd_add() { *) die "add: expected 'question', 'decision' or 'followup', got '$kind'" 2 ;; esac kind_keys "$kind" - local title="" context="" extra="" force=0 + local title="" context="" extra="" force=0 blocking=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -211,6 +218,9 @@ cmd_add() { --chosen) [[ "$kind" == decision ]] || die "add $kind: --chosen is only for decisions" 2 extra="${2:?--chosen needs a value}"; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "add $kind: --blocking is only for questions" 2 + blocking=1; shift ;; --new) force=1; shift ;; *) die "add $kind: unknown argument: $1" 2 ;; esac @@ -242,8 +252,9 @@ cmd_add() { id=$(jq -r --arg c "$CTR" '.[$c]' <<<"$state") new=$(jq --arg k "$ARR" --arg c "$CTR" --arg kind "$kind" \ --arg t "$title" --arg x "$context" --arg e "$extra" \ - --argjson o "$opts_json" --argjson now "$(date +%s)" ' - (if $kind == "question" then {options: $o, recommendation: $e} + --argjson o "$opts_json" --argjson now "$(date +%s)" \ + --argjson blocking "$( [[ $blocking -eq 1 ]] && echo true || echo false )" ' + (if $kind == "question" then {options: $o, recommendation: $e, blocking: $blocking} elif $kind == "decision" then {options: $o, chosen: $e} else {} end) as $extra | .[$k] += [{id: .[$c], title: $t, context: $x} + $extra + {added: $now}] From 99a2467171c32500c5b54e448279993243b3b3e5 Mon Sep 17 00:00:00 2001 From: Logan Gagne <logan.gagne@gmail.com> Date: Tue, 10 Nov 2026 17:51:55 -0500 Subject: [PATCH 5/6] =?UTF-8?q?feat(opencode):=20M4=20session=20=E2=80=94?= =?UTF-8?q?=20skills,=20spine,=20and=20orchestrate=5Fbuild=20tool?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Canonicalize spine.md into utils/ and vendor it back into plugins-claude/session byte-for-byte (proven via git show | cmp); sync.sh gains util:dir destination syntax and renders markdown for the opencode target through utils/opencode-port.py — the single-source Claude→OpenCode harness mapping (EnterWorktree→worktree_create/ session_move, ExitWorktree→session_move/worktree_remove, EnterPlanMode→ plan agent, AskUserQuestion→question tool, subagent_type→agent, Workflow script→orchestrate_build, rename-session→session_rename, slash doors). sync also carries the exec bit through rendered vendoring. Five session skills ported via utils/port-session-skills.py (re-runnable; test-session-port.sh fails if the tree diverges from porter(original)). orchestrate-core.ts is a pure port of the Claude Workflow script's deterministic half (tier bump, wave/dependency skip, output-block parse as retry trigger, 3-attempt escalation, findings dedupe/split, capped semaphore); src/index.ts wires it to ctx.session children as the orchestrate_build tool and registers the five slash doors. Model tiers fuzzy-match ctx.model.list() with options.modelTiers override. Live-verified on opencode 2.2.6: plugin loads, all five skills discovered, all five door commands registered; TS typechecks clean. tests: session-core node suite (25: bump/parse/validate/planWave/ findings/semaphore/prompts), session port fidelity (65: leakage grep, porter-output equality, byte-identical vendored scripts, rendered spine == opencode-port output), sync suite extended for util:dir + rendered markdown drift (21). Full repo suite 956 green; Claude/Copilot trees byte-for-byte unchanged. Refs #236 --- plugins-opencode/session/README.md | 59 + plugins-opencode/session/opencode.jsonc | 25 + .../session/skills/session-end/SKILL.md | 250 +++ .../skills/session-end/scripts/git-wait | 1460 +++++++++++++++++ .../session/skills/session-end/scripts/sitrep | 246 +++ .../session/skills/session-issue/SKILL.md | 135 ++ .../skills/session-issue/reference/spine.md | 316 ++++ .../skills/session-issue/scripts/branch | 38 + .../skills/session-issue/scripts/git-wait | 1460 +++++++++++++++++ .../skills/session-orchestrate/SKILL.md | 240 +++ .../session-orchestrate/scripts/git-wait | 1460 +++++++++++++++++ .../skills/session-orchestrate/scripts/sitrep | 246 +++ .../session/skills/session-start/SKILL.md | 88 + .../skills/session-start/reference/spine.md | 316 ++++ .../skills/session-start/scripts/branch | 38 + .../skills/session-start/scripts/git-wait | 1460 +++++++++++++++++ .../session/skills/session-summarize/SKILL.md | 48 + .../skills/session-summarize/scripts/sitrep | 246 +++ plugins-opencode/session/src/index.ts | 288 +++- .../session/src/orchestrate-core.ts | 276 ++++ tests/opencode/test-session-core.mjs | 234 +++ tests/opencode/test-session-core.sh | 19 + tests/opencode/test-session-port.sh | 146 ++ tests/opencode/test-sync.sh | 33 +- utils/opencode-port.py | 119 ++ utils/port-session-skills.py | 86 + utils/spine.md | 316 ++++ utils/sync.sh | 64 +- 28 files changed, 9690 insertions(+), 22 deletions(-) create mode 100644 plugins-opencode/session/README.md create mode 100644 plugins-opencode/session/opencode.jsonc create mode 100644 plugins-opencode/session/skills/session-end/SKILL.md create mode 100755 plugins-opencode/session/skills/session-end/scripts/git-wait create mode 100755 plugins-opencode/session/skills/session-end/scripts/sitrep create mode 100644 plugins-opencode/session/skills/session-issue/SKILL.md create mode 100644 plugins-opencode/session/skills/session-issue/reference/spine.md create mode 100755 plugins-opencode/session/skills/session-issue/scripts/branch create mode 100755 plugins-opencode/session/skills/session-issue/scripts/git-wait create mode 100644 plugins-opencode/session/skills/session-orchestrate/SKILL.md create mode 100755 plugins-opencode/session/skills/session-orchestrate/scripts/git-wait create mode 100755 plugins-opencode/session/skills/session-orchestrate/scripts/sitrep create mode 100644 plugins-opencode/session/skills/session-start/SKILL.md create mode 100644 plugins-opencode/session/skills/session-start/reference/spine.md create mode 100755 plugins-opencode/session/skills/session-start/scripts/branch create mode 100755 plugins-opencode/session/skills/session-start/scripts/git-wait create mode 100644 plugins-opencode/session/skills/session-summarize/SKILL.md create mode 100755 plugins-opencode/session/skills/session-summarize/scripts/sitrep create mode 100644 plugins-opencode/session/src/orchestrate-core.ts create mode 100644 tests/opencode/test-session-core.mjs create mode 100644 tests/opencode/test-session-core.sh create mode 100644 tests/opencode/test-session-port.sh create mode 100644 utils/opencode-port.py create mode 100644 utils/port-session-skills.py create mode 100644 utils/spine.md diff --git a/plugins-opencode/session/README.md b/plugins-opencode/session/README.md new file mode 100644 index 0000000..9c9e732 --- /dev/null +++ b/plugins-opencode/session/README.md @@ -0,0 +1,59 @@ +# session (OpenCode) + +The OpenCode port of the session workflow plugin: the five session skills +(start / issue / end / orchestrate / summarize), the shared spine reference, +and the headless build orchestrator that `session-orchestrate` dispatches. + +## Shape + +- **Server plugin** (`src/index.ts`): registers the `orchestrate_build` tool + (the deterministic Execute-waves + Review/auto-fix half of + `session-orchestrate`, ported from the Claude `Workflow` script) and the + five slash doors (`/session-start` … — OpenCode skills take no slash + arguments, so each door forwards its invocation text into the prompt). +- **`src/orchestrate-core.ts`**: the pure logic — tier bump, wave/dependency + planning with transitive skip, output-block parsing (unparseable = retry, + never a silent pass), 3-attempt failure escalation, findings dedupe/split. + Unit-tested directly (`tests/opencode/test-session-core.sh`). +- **Skills** (`skills/*/SKILL.md`): ported from the Claude originals through + `utils/opencode-port.py` — the same shared mapping `utils/sync.sh` uses for + vendored markdown, so the port is single-sourced and re-runnable + (`utils/port-session-skills.py`). `reference/spine.md` and the scripts + (`git-wait`, `branch`, `sitrep`) are vendored per-skill by sync; CI fails + on drift or on a stale port. + +## Harness mapping (what changed vs Claude) + +| Claude | OpenCode | +| --- | --- | +| `EnterWorktree` | `opencode.worktree_create` + `opencode.session_move` | +| `ExitWorktree` | `opencode.session_move` back / `opencode.worktree_remove` | +| `EnterPlanMode` | the built-in `plan` agent | +| `AskUserQuestion` | the `question` tool | +| `Agent` + `subagent_type` | the `subagent` tool + `agent` | +| `Workflow` script | the `orchestrate_build` tool (this plugin) | +| `rename-session` script | `opencode.session_rename` (Code Mode) | +| `/session:session-start` etc. | `/session-start` doors registered by the plugin | + +`orchestrate_build` runs each chunk/review as its own top-level session +(create → prompt → wait → parse), not via the subagent tool — so the depth-1 +subagent limit doesn't apply, and only the parent session ever has the tool +(no recursion). + +## Install + +Copy the `plugins` + `skills` entries from [`opencode.jsonc`](opencode.jsonc) +into your `~/.config/opencode/opencode.jsonc`, pointing both paths at your +checkout. Optional: pin model tiers via the plugin `options.modelTiers` +(see the commented block in the snippet); without it the plugin fuzzy-matches +your enabled model list for `haiku`/`sonnet`/`opus` and falls back to the +session default. + +## Notes + +- The Claude `SessionStart` hook has no OpenCode equivalent and none is + needed: the skills are the entry points, and the doors make them one + keystroke away. +- `orchestrate_build` children edit the session's working tree directly (the + Phase 0b worktree, if one was created) — same shared-tree model as the + Claude workflow. diff --git a/plugins-opencode/session/opencode.jsonc b/plugins-opencode/session/opencode.jsonc new file mode 100644 index 0000000..5d06daf --- /dev/null +++ b/plugins-opencode/session/opencode.jsonc @@ -0,0 +1,25 @@ +{ + "$schema": "https://opencode.ai/config.json", + // session for OpenCode: the plugin registers the orchestrate_build tool and + // the five slash doors; the skills array points at the ported skills in YOUR + // checkout of agent-toolkit. Relative paths resolve from the directory + // OpenCode was started in, so prefer ~ or an absolute path. + "plugins": ["/home/you/agent-toolkit/plugins-opencode/session"], + "skills": ["/home/you/agent-toolkit/plugins-opencode/session/skills"], + // Optional: pin the haiku/sonnet/opus tiers used by orchestrate_build's + // sub-agents to concrete provider/model ids. Without this the plugin + // fuzzy-matches your enabled model list for a model whose id contains the + // tier name, and falls back to the session default. + // "plugins": [ + // { + // "package": "/home/you/agent-toolkit/plugins-opencode/session", + // "options": { + // "modelTiers": { + // "haiku": "anthropic/claude-haiku-4-5", + // "sonnet": "anthropic/claude-sonnet-4-5", + // "opus": "anthropic/claude-opus-4-5" + // } + // } + // } + // ] +} diff --git a/plugins-opencode/session/skills/session-end/SKILL.md b/plugins-opencode/session/skills/session-end/SKILL.md new file mode 100644 index 0000000..fe64793 --- /dev/null +++ b/plugins-opencode/session/skills/session-end/SKILL.md @@ -0,0 +1,250 @@ +--- +name: session-end +description: "Use when the user signals the session's work is complete and ready to land (wrap up, close out, finalize, ready for a PR): loads the full end checklist — docs, review, issue sweep so resolved issues get closed, then ship. Not for mid-task 'done'/'finish'." +--- + +Close out the session's work, then hand off to `/ship` for the +commit → PR → CI → merge → cleanup lifecycle. This skill owns only the +pre-ship quality pass; `ship` owns everything git/PR/worktree. This is where the +last (or only) unit of the scope gets shipped, exactly once; earlier units were +already landed via `ship`. Run straight +through steps 1-4 with no routine prompts; the one deliberate stop is step 5, +**before** anything is shipped: summarize the work and caveats and wait for the +user's go. Only after that go do steps 6-8 run (ship, CI, re-merge if needed, +cleanup, final summary) without stopping again. + +**Preflight:** this skill hands off to `git-tools:ship`. If that skill is not +available (the `git-tools` plugin is not installed or enabled), say so and stop +before doing any docs or review work. The `code-review` skill is optional: step 3 +falls back to a review agent when it is missing. + +Then, before any docs or review work, detect the platform: + +```bash +bash scripts/git-wait platform +``` + +If it fails, stop and tell the user, or offer to proceed locally without the +issue and PR steps (skip steps 4, 6 and 7 and do not invoke `ship`); in that mode step 5 offers only +**Done** and **Make changes first**, leaves the issue lines out of the summary, and +step 8 reports the local state instead of a PR. On success, capture +the `owner/repo` and the platform now (for example +`gh repo view --json nameWithOwner -q .nameWithOwner`, or parse +`git remote get-url origin`). Use `gh -R owner/repo` / `tea --repo owner/repo` +for every later issue command so they still work after `ship` removes the +worktree. + +Work from what you already know about this session. **Do not** start by running +a pile of `git diff` / log commands to rediscover it. One cheap orientation is +enough. Determine the default branch (`git symbolic-ref --short +refs/remotes/origin/HEAD`, falling back to `main`, then `master`) and run: + +```bash +git status --short -b +git rev-list --count <default>..HEAD +``` + +If the working tree is clean and the count is `0`, say there is nothing to +finalize and stop. Do not rely on the "ahead" count from `git status -b`: a +never-pushed branch has no upstream and shows none. + +### 1. Docs + +Update every doc the work made stale: README, CLAUDE.md, docs/, changelogs, +help text, comments, and version fields where the repo requires a bump. Edit +what is wrong; do not write new docs nobody asked for. + +### 2. Finish adjacent work + +Complete anything this change obviously implies and left dangling: tests for +new behavior, call sites or mirrors that need the same change, leftover TODOs +or debug code you added, temp files. Stay in scope — note unrelated problems +instead of fixing them. Do not run repo validation here; step 3 runs it once. + +### 3. Review and fix (hard gate) + +Shipping requires a review of the current state of the work. First decide whether +one already happened **in this session** and is still current: + +- **Already reviewed and still current** — a review-and-fix run earlier in the + conversation, followed by no code or test edits other than that review's own + *minor* fixes. Docs edits from steps 1-2 count as non-code. Skip the review and + say so in one line (for example "Review already ran this session; skipping"). +- **Stale** — any code or test edit since the review, or review fixes that were + *significant*: they changed logic or behavior, added or removed more than a few + lines, or touched files outside the reviewed diff. Typos, wording, formatting, + and comment tweaks are minor and do not make a review stale. + +Otherwise run the loop below. + +**Scale the effort to the change.** Pick the review level from the diff's size and +risk, not a fixed default: prose, docs, or config only, or a few lines in one +file → `low`; a handful of files with simple logic → `medium`; multi-file logic or +behavior changes → `high`; large, cross-cutting, or security-sensitive changes +(auth, hooks, shared utils, anything hard to reverse) → `xhigh`. + +**Review → triage → fix, at most three passes:** + +1. **Review.** Invoke the `code-review` skill at that level **without** `--fix`, + so findings come back unapplied. If the `code-review` skill is not available, + use the Agent tool to spawn a general-purpose review agent over the + working-tree diff: it reports findings (correctness bugs, edge cases, error + handling, missing tests, with file:line) and changes nothing. +2. **Triage.** Do not fix findings on the reviewer's word alone. Spawn one triage + `Agent` with a model matched to the change: `haiku` for trivial diffs, + `sonnet` for ordinary ones, `opus` for complex or security-sensitive ones. Give + it the findings and the diff and ask, per finding, whether it is **real** (a + defect that can actually occur) and **significant** (worth fixing in this PR), + with a one-line reason. Findings judged not real, or real but minor, are + dropped and reported with that reason. They never trigger another pass. +3. **Fix.** Apply the real, significant findings, then run the repo's documented + validation **once** (for example `validate-all.sh` or the test command in + CLAUDE.md) and fix what fails. +4. **Decide whether to loop.** If the fixes were significant (see "Stale" above) + and this was not pass 3, run another pass from step 1; otherwise the review is + satisfied. + +Pass 3 is the last pass; do not re-review after its fixes. If pass 3 produced +significant fixes, real significant findings remain, or validation still fails, +**stop**: do not invoke `ship`. Ask the user via the `question` tool, listing what +remains with a one-line reason each, and let them choose whether to ship as is or +direct changes. Never start a fourth pass on your own. + +This is a hard gate: never invoke `ship` while a required review is outstanding, +and do not offer the user a way to skip it. Skip only if the user explicitly +tells you to. + +### 4. Issue sweep + +Decide which issues this work resolves. + +1. Collect candidates. Find the issue(s) linked to this session, in this order + (never parse them from the branch name): + 1. `git config --get branch.<branch>.session-issues` — comma-separated + closing lines such as `Closes #12,Fixes #13`; split on commas. + 2. Issues already known in this conversation's context. + 3. Explicit `#N` references in the skill arguments. + 4. Otherwise ask the user via the `question` tool which issues this work + resolves (none is a valid answer). + + Fetch just those (`gh -R owner/repo issue view N --json + number,title,body,state` or `tea issues N --repo owner/repo --output json`). + Optionally list open issues (`gh -R owner/repo issue list --state open + --limit 20 --json number,title`; `tea issues list --repo owner/repo --limit + 20` on Gitea) to **suggest** title-overlap candidates; treat these only as + suggestions that need the user's confirmation, never as the silent primary + path. +2. Classify each as **resolved** (the diff fully addresses it), **partial** + (progress but not done), or **unrelated**. Read an issue body only when the + title is ambiguous. +3. Resolved → will be closed via the PR. Partial → leave open and write down the list of partial issue numbers + now (with a one-line note of the progress made on each), so it survives the + ship step; the comment is posted in step 7 after the merge. If the call is + genuinely unclear, ask once via the `question` tool, batched across all unclear + issues. +4. If something should be pushed through to completion and is small, finish it + now with **one** extra pass (steps 2-3 once more, no further loop) rather than + leaving it open; anything still unfinished stays open as partial. + +Also list any new problems found along the way that deserve their own issue; +carry them to the step 5 summary rather than filing them unprompted. + +**Inbox review (conditional).** Only if this session's context contains `Inbox +tracker is active for this session`; otherwise skip silently, never error, warn, +or block. + +1. Using the command prefix from that context, run `<prefix> list --kind decision + --format md --full`, `<prefix> list --kind question --format md --full` and + `<prefix> list --kind followup --format md --full`. If nothing is pending, skip + silently. +2. Pending decisions: present each (stable D-number, what was chosen, + alternatives, why) and review them with the user in chat, not via + the `question` tool. Accept → `<prefix> resolve D<n>`. Change or reject → make + the adjustment to the work first, then `<prefix> resolve D<n>`, telling the user + what changed. Leave any the user defers open and say so. +3. Open questions: surface them to the user; do not resolve them yourself. They + may defer or answer, but never drop them silently. +4. Open followups (F-numbers): these are the things logged for "before we wrap + up". Present them as a checklist and, for each, ask whether to do it now, + skip it, or leave it for later. Do it now → do the work in this unit (re-run + validation once if code changed), then `<prefix> done F<n>`. Skip (the user + says it is not needed) → `<prefix> done F<n>`. Later → leave it open and fold + it into the step 5 summary as a proposed new issue or a left-open note. Never + `done` one the user has not settled. + +### 5. Summarize and wait for the user's go (STOP) + +Nothing has been committed, pushed, or opened as a PR yet. Build the summary, then +**stop and wait for the user's reply** with the `question` tool (not a plain-text +question), so the user can answer from `/rc` on their phone. Print the full summary +as text first, and put a condensed version (outcome, validation, top caveats) in +the question text itself, because the remote client may not show the text above it. +Ask one question with these options: **Ship it** (recommended) and **Make changes +first**; the user's own words, including a cancel, arrive through "Other". The +summary covers: + +- One-line outcome and the branch. +- What changed, per file (or per area for a large diff), including the docs edits. +- Validation status (what ran and passed; say plainly if something was not run) + and the review outcome: findings fixed, and any you chose not to fix with the + reason. +- **Caveats** — known or potential problems, assumptions, and uncovered edge + cases, stated specifically. Omit only if there are genuinely none. +- Issues this work will close, partial issues, and proposed new issues. + +If the user cancels or says to keep the work local, stop: do not invoke `ship`, +and report the branch and working-tree state. If they pick **Make changes first** +without saying what to change, ask. If they pick it or answer with changes, make them, +re-run validation once, redo the step 3 review if the edits made it stale, and ask +again with a fresh summary. Do not invoke `ship`, commit, push, or open a PR until +the user picks **Ship it** for the current state of the work; an earlier approval +(for example of the plan) does not count. + +### 6. Ship + +Only once the user has given the go in step 5, and step 3 is satisfied, invoke +`git-tools:ship` via the `Skill` tool. Pass as arguments the closing +lines the PR body must contain — `Fixes #N` for bugs, `Closes #N` otherwise, +one per resolved issue — and tell it the PR body should summarize the review +and docs changes. `ship` handles staging, branch, push, PR, CI, merge wait, +post-merge run, return to the default branch, and worktree teardown. + +The user's go covers the whole lifecycle: watch CI, fix forward a failure clearly +caused by this change and re-merge (`ship` caps this at two attempts), and clean +up. Do not ask again between those steps. If `ship` still stops on a CI failure +or a blocked merge, stop too: report the state and do not comment on any issue. +Distinguish "merged" from "auto-merge enabled but not yet merged": post no +"resolved" or progress comment until the PR is actually merged. Offer to wait for +the merge, or tell the user to re-run the sweep (step 7) once it lands. + +### 7. Comment on partial issues + +`ship` step 9 removes the worktree, so the current directory may no longer +exist. Before running any command here, if it is gone, move this session out with `opencode.session_move` (see step 8), or switch to a valid directory such as the main +checkout. Always use the `-R owner/repo` / `--repo` form captured in preflight. + +Only after ship reports the PR merged, post a short comment on each partial issue +recorded in step 4, referencing the merged PR (number or URL) and what remains: + +```bash +gh -R owner/repo issue comment N --body "Progress in PR #P (merged): <what was done>. Remaining: <what is left>." +``` + +Use `tea comment --repo owner/repo N "<same text>"` on Gitea. If the PR did not +merge (closed, blocked, timed out, or auto-merge pending), do not comment; say +so in the report instead. Skip this step when there are no partial issues. + +### 8. Final report + +After `ship` finishes and partial-issue comments are posted, give a short summary +of the final state: PR URL and merge/CI state (including any fix-forward commits +or re-merges), issues closed, partial issues commented (only those actually +commented), cleanup / worktree teardown done, and anything skipped or left for +the user. List the proposed new issues from step 4 and file them only if the user +asks. This is a report, not a further confirmation stop. + +If this session was moved into a worktree with `opencode.worktree_create` and that +directory no longer exists after `ship` (ship removes it with plain git), call +`opencode.session_move` back to the main checkout to reset the session's working +directory (do this at the start of step 7 when that step has work to do). Do not +re-create or delete anything here; `ship` already removed the directory. diff --git a/plugins-opencode/session/skills/session-end/scripts/git-wait b/plugins-opencode/session/skills/session-end/scripts/git-wait new file mode 100755 index 0000000..335f658 --- /dev/null +++ b/plugins-opencode/session/skills/session-end/scripts/git-wait @@ -0,0 +1,1460 @@ +#!/usr/bin/env bash +# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. +# +# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: +# listing, creating, commenting, merging, closing, viewing logs. This script +# exists only for the three things neither CLI gives you: +# +# 1. Platform detection — matching the git remote hostname against configured +# tea logins, so a caller knows whether to reach for `gh` or `tea`. +# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a +# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on +# the merge itself; `tea` has no equivalent at all). +# 3. `run watch` — block until CI finishes, aggregating per-job status and +# dumping failed job logs. `gh run watch` is GitHub-only and misses +# job-level failures masked by a run-level success; `tea` has no watcher. +# +# Usage: +# git-wait [-C DIR] <command> ... +# Operate on the git repo at DIR instead of the current directory (like +# `git -C`). Must come before the command. gh/tea resolve the repo from the +# working directory, so this retargets every call without a caller-side cd. +# +# git-wait platform +# Echo "github" or "gitea" for the current repo's origin remote. +# +# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] +# [--alert-interval 300] +# Block until the PR for BRANCH reaches a terminal state. +# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, +# url, duration, and (when relevant) reason. +# +# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] +# [--timeout 14400] [--idle-timeout 0] [--interval 15] +# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] +# [--max-poll-failures 10] +# Block until CI finishes. Output: "status: pass|fail|closed|timeout| +# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed +# job logs go to stderr. +# +# --branch follows ONE run: the newest correlated to that branch (via the +# PR's check rollup when a PR exists, else the newest run in the list). +# That is right for a PR branch, where one push means one run. It is NOT +# sufficient on a default branch, where two merges landing close together +# produce two runs and the newest passing says nothing about the older +# one still executing. +# +# --sha watches EVERY run for one commit and is the correct flag for a +# post-merge/release watch: it stays pending while any run for the commit +# is pending, and fails if any run — or any job inside one — failed. Pass +# one or the other, not both. +# +# A running CI is never aborted for lack of visible progress: `run watch +# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress +# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO +# check is pending (running CI, or auto-merge armed, resets it), so a PR that +# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long +# jobs (VM boot + integration suite + teardown) can go quiet for a long time. +# While still waiting, a heartbeat alert goes to STDERR every --alert-interval +# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) +# pending: ...)". stdout key:value output is unchanged. +# +# --no-run-timeout is how long to wait for the FIRST run to appear before +# reporting no-workflow, counted from the end of --initial-delay. Default 600s +# for --sha (post-merge workflows queue late, or start only after another +# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty +# check. A stderr alert is printed each poll while waiting. A FAILED run-list +# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not +# counted toward this deadline and polling continues, but after +# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the +# watch gives up with "status: error" and exit 4. A successful poll resets the +# count. +# +# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the +# commit is terminal and passing, keep polling SECS more before reporting pass, +# so a chained workflow_run workflow that appears late is still watched. A +# stderr line is printed while settling; a new run restarts the watch. +# +# Exit codes: 0 terminal state reached (check "status:" for pass/fail), +# 1 usage error, 2 timeout, 3 platform detection failure or no +# PR/workflow found, 4 command failed + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +die() { echo "git-wait: $*" >&2; exit 1; } +die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } + +# Run a CLI command and pipe its stdout through a jq filter. +# If the command fails, die with its stderr instead of feeding junk to jq. +# Usage: cli_json [jq-flags...] <jq-filter> <cmd> [args...] +# +# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. +# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, +# auth warnings, progress text) into the JSON, silently corrupting jq +# parsing and producing wrong results downstream (e.g. run watch seeing +# unexpected status values). +cli_json() { + local jq_flags=() + while [[ "$1" =~ ^-[a-zA-Z] ]]; do + # Collect jq flags (e.g. -r, -e) — stop at the filter string + case "$1" in + -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; + *) break ;; + esac + done + local filter="$1"; shift + local raw stderr_file rc=0 + stderr_file=$(mktemp) + raw=$("$@" 2>"$stderr_file") || rc=$? + if [[ $rc -ne 0 ]]; then + local err + err=$(cat "$stderr_file") + rm -f "$stderr_file" + die "$err" + fi + rm -f "$stderr_file" + echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" +} + +# --------------------------------------------------------------------------- +# Target repo (-C DIR) +# +# Handled before platform detection. The cd happens inside this script's own +# process, so the caller's working directory is never touched. +# --------------------------------------------------------------------------- + +if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then + [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" + target_dir="$2" + [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" + git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die_usage "$1: not a git repository: $target_dir" + # Resolve the script path first: a relative $0 breaks once we cd (help reads it). + SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + cd "$target_dir" + shift 2 +fi +SELF="${SELF:-$0}" + +# --------------------------------------------------------------------------- +# Platform detection +# --------------------------------------------------------------------------- + +detect_platform() { + local remote_url hostname login_url login_host + remote_url=$(git remote get-url origin 2>/dev/null) \ + || die "no git remote 'origin' found — run from a git repository" + + # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) + # or HTTPS (https://host/org/repo or https://host:port/org/repo) + if [[ "$remote_url" =~ ^ssh:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') + elif [[ "$remote_url" =~ ^git@ ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') + elif [[ "$remote_url" =~ ^https?:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') + else + die "unrecognised remote URL format: $remote_url" + fi + + # Check if this hostname matches any configured tea login + if command -v tea >/dev/null 2>&1; then + while IFS= read -r login_url; do + login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') + if [[ "$login_host" == "$hostname" ]]; then + echo "gitea" + return + fi + done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) + fi + + # Not a known tea login — fall back to gh (GitHub) + if [[ "$hostname" == "github.com" ]]; then + echo "github" + return + fi + + die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" +} + +PLATFORM=$(detect_platform) + +case "$PLATFORM" in + github) CLI=gh ;; + gitea) CLI=tea ;; +esac + +command -v "$CLI" >/dev/null 2>&1 \ + || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } + +# --------------------------------------------------------------------------- +# Internal reads +# +# These are NOT public subcommands — they are the normalized queries the two +# waiters below need. Every one of them dies on backend failure, so callers +# invoke them inside $( ) with a fallback: a probe failure must degrade the +# poll loop, never abort it. +# --------------------------------------------------------------------------- + +# List PRs as normalized JSON. Flags: --state, --limit, --assignee. +_pr_list() { + local limit assignee state args + limit=30; assignee=""; state="open" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; + --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") + # gh uses 'merged' as a state but tea uses 'closed' for merged PRs + [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") + [[ -n "$assignee" ]] && args+=(--assignee "$assignee") + cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ + env GH_NO_COLOR=1 gh pr list "${args[@]}" + ;; + gitea) + args=(--output json --limit "$limit" + --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") + [[ "$state" == "merged" ]] && state="closed" + args+=(--state "$state") + cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ + env NO_COLOR=1 tea pr list "${args[@]}" + ;; + esac +} + +# Show one PR as normalized JSON. Takes <N> or --branch NAME. +_pr_show() { + local num branch pr_json pr_stderr pr_rc pr_detail err + num=""; branch="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --*) die_usage "unknown flag: $1" ;; + *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; + esac + shift + done + [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass <N> or --branch NAME, not both" + if [[ -n "$branch" ]]; then + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + num=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + [[ -n "$num" ]] || die "no PR found for branch '$branch'" + fi + [[ -n "$num" ]] || die_usage "usage: git-wait pr show <N> | --branch NAME" + case "$PLATFORM" in + github) + cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ + env GH_NO_COLOR=1 gh pr view "$num" \ + --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" + ;; + gitea) + # `tea pr list` omits the `merged` boolean and `merged_at` timestamp + # entirely (tea only encodes merge state into the `state` string) and + # emits `mergeable` as a string, so a merged PR reports + # merged:false / mergedAt:null and consumers think it is still open + # (#140). Fetch the PR detail via the REST API instead, mirroring the + # run:show/run:list `tea api` pattern, so merge fields are reliable. + pr_stderr=$(mktemp); pr_rc=0 + pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ + || pr_rc=$? + if [[ $pr_rc -ne 0 ]]; then + err=$(cat "$pr_stderr"); rm -f "$pr_stderr" + die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" + fi + rm -f "$pr_stderr" + # Derive `state` from `merged` so it stays consistent with the merge + # flags (Gitea REST reports state:"closed" for a merged PR) and matches + # the GitHub path, which emits state:"merged". + echo "$pr_detail" | jq '{ + number: (.number // .index), + title: (.title // ""), + body: (.body // ""), + state: (if (.merged // false) then "merged" else (.state // "") end), + merged: (.merged // false), + merged_at: (.merged_at // null), + author: (.user.login // .user.username // ""), + head: (.head.ref // .head.label // ""), + base: (.base.ref // .base.label // ""), + labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), + assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), + mergeable: (.mergeable // null), + created_at: (.created_at // ""), + updated_at: (.updated_at // null), + url: (.html_url // .url // ""), + comments: [] + }' + ;; + esac +} + +# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. +_auto_merge_status() { + local branch number pr_json am + branch=""; number="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) shift; branch="$1" ;; + --number) shift; number="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + + # Resolve PR number from branch if needed + if [[ -z "$number" ]]; then + [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" + pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" + number=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + if [[ -z "$number" || "$number" == "null" ]]; then + echo "auto_merge: false" + echo "No open PR found for branch '$branch'" >&2 + exit 3 + fi + fi + + case "$PLATFORM" in + github) + am=$(cli_json -r '.autoMergeRequest != null' \ + env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) + echo "auto_merge: $am" + ;; + gitea) + echo "auto_merge: false" + echo "Gitea does not support auto-merge detection" >&2 + ;; + esac +} + +# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. +# +# --sha filters to runs for one commit. GitHub has a server-side filter for it +# (`gh run list --commit`); Gitea does not, so it is applied client-side over +# an unfiltered fetch, the same way --branch already is there. Both platforms +# emit head_sha in the normalized output — GitHub did not used to, which is +# why `run watch --sha` needs the headSha field added below. +_run_list() { + local limit status branch sha args query raw_stderr raw_rc raw err + limit=20; status=""; branch=""; sha="" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") + [[ -n "$status" ]] && args+=(--status "$status") + [[ -n "$branch" ]] && args+=(--branch "$branch") + [[ -n "$sha" ]] && args+=(--commit "$sha") + cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ + env GH_NO_COLOR=1 gh run list "${args[@]}" + ;; + gitea) + # Source from Gitea REST API directly. `tea actions runs list` + # filters server-side by a `branch` column that Gitea leaves empty + # on `pull_request` runs, so the watcher's --branch lookup misses + # correlated runs (#103). Fetch unfiltered via `tea api`, normalize + # `branch` from `head_branch`, and apply --branch client-side. + query="limit=$limit" + [[ -n "$status" ]] && query+="&status=$status" + raw_stderr=$(mktemp); raw_rc=0 + raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ + || raw_rc=$? + if [[ $raw_rc -ne 0 ]]; then + err=$(cat "$raw_stderr"); rm -f "$raw_stderr" + die "tea api repos/{owner}/{repo}/actions/runs failed: $err" + fi + rm -f "$raw_stderr" + echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' + [(.workflow_runs // []) | .[] | { + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + head_sha: (.head_sha // ""), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // "") + }] + | if $b == "" then . else [.[] | select(.branch == $b)] end + | if $s == "" then . else + [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] + end + ' + ;; + esac +} + +# Show one CI run as normalized JSON, including per-job status. +_run_show() { + local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err + [[ $# -ge 1 ]] || die_usage "usage: git-wait run show <run-id>" + run_id="$1" + case "$PLATFORM" in + github) + cli_json \ + 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ + env GH_NO_COLOR=1 gh run view "$run_id" \ + --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" + ;; + gitea) + # Fetch the run object via the REST API. `tea actions runs view` + # ignores `--output json` (tea 0.14.1) and prints a human key/value + # table while still exiting 0, so jq downstream chokes (#133). Use the + # same `tea api` pattern as run:list and the jobs lookup below. + view_stderr=$(mktemp); view_rc=0 + view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ + || view_rc=$? + if [[ $view_rc -ne 0 ]]; then + err=$(cat "$view_stderr"); rm -f "$view_stderr" + die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" + fi + rm -f "$view_stderr" + + # Fetch per-job data via the actions API so callers (run watch) can + # detect job-level failures masked by run-level status=success on + # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. + jobs_array='[]' + jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) + if [[ -n "$jobs_json" ]]; then + jobs_array=$(echo "$jobs_json" | jq -c ' + def to_status: + if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) + end; + [(.jobs // .) | (if type == "array" then .[]? else empty end) | + {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] + ' 2>/dev/null) || jobs_array='[]' + fi + + # Older Gitea versions may not expose the jobs API; fall back to + # scanning the run logs for "Job '<name>' failed" lines. + if [[ "$jobs_array" == '[]' ]]; then + failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ + | grep -oE "Job '[^']+' failed" \ + | sed -E "s/Job '(.+)' failed/\1/" \ + | sort -u || true) + if [[ -n "$failed_log" ]]; then + jobs_array=$(printf '%s\n' "$failed_log" \ + | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') + fi + fi + + # Normalize REST field names into the output contract, mirroring the + # run:list jq above (conclusion-first status, head_branch//branch, + # run_started_at//created, name//workflow_id). + echo "$view_json" | jq --argjson jobs "$jobs_array" '{ + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // ""), + jobs: $jobs + }' + ;; + esac +} + +# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; +# Gitea has no server-side filter and returns every job's log). +_run_logs() { + local run_id failed_only + [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs <run-id> [--failed-only]" + run_id="$1"; shift + failed_only=false + while [[ $# -gt 0 ]]; do + case "$1" in + --failed-only) failed_only=true ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + if [[ "$failed_only" == "true" ]]; then + GH_NO_COLOR=1 gh run view "$run_id" --log-failed + else + GH_NO_COLOR=1 gh run view "$run_id" --log + fi + ;; + gitea) + # tea actions runs logs outputs all job logs; no built-in failed-only filter + NO_COLOR=1 tea actions runs logs "$run_id" + ;; + esac +} + +# --------------------------------------------------------------------------- +# Run helpers +# --------------------------------------------------------------------------- + +# Return comma-separated names of any jobs in <run_id> whose status is +# "failure", or empty if none. Used by run watch to detect job-level failures +# even when the run-level status reports success — Gitea sets run.status to +# "success" on a multi-job workflow if at least one job ran successfully, +# masking failures in earlier jobs (see issue #87). Calls "run show" to +# normalize per-platform JSON, so it works for both gh and tea paths. +_run_failed_jobs() { + local run_id="$1" show_json + show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 + echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' +} + +# Progress-aware timeout decision shared by `pr wait` and `run watch`. +# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress +# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. +# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ +# minutes: this lets callers keep waiting while CI is actively progressing and +# give up only after a stretch of no progress, with a hard ceiling backstop. +_wait_timed_out() { + local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" + if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then + echo "ceiling"; return 0 + fi + if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then + echo "idle"; return 0 + fi + return 1 +} + +# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. +_fmt_dur() { + local s="$1" + if [[ "$s" -lt 60 ]]; then echo "${s}s" + elif [[ "$s" -lt 3600 ]]; then + if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi + else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi +} + +# Periodic stderr heartbeat while a wait is still running. Callers set +# alert_interval (0 disables) and next_alert (initialised to alert_interval), +# and call `_heartbeat "$elapsed" "<detail>"` once per poll. Emits at most one +# alert per poll, then re-arms for the next multiple of alert_interval, so a +# slow poll never produces a burst. stderr only: stdout stays parseable. +_heartbeat() { + local el="$1" detail="$2" + [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 + echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 + next_alert=$(( (el / alert_interval + 1) * alert_interval )) +} + +# Coarse CI status — pending|success|failure|none — for a PR/branch, used by +# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the +# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is +# guarded so a probe failure degrades to "none" and never aborts the wait loop. +_ci_status() { + local pr_number="$1" branch="$2" view_json run_status + case "$PLATFORM" in + github) + view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } + echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) else "pending" end + else (.state // "pending" | ascii_downcase) end + ] | + if length == 0 then "none" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" end' 2>/dev/null || echo "none" + ;; + gitea) + run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) echo "pending" ;; + failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; + ""|none|null) echo "none" ;; + *) echo "success" ;; + esac + ;; + *) echo "none" ;; + esac +} + +# --------------------------------------------------------------------------- +# Command routing +# --------------------------------------------------------------------------- + +cmd="${1:-}" +sub="${2:-}" +shift 2 || shift || true + +case "$cmd:$sub" in + + # Echo the detected platform so callers know which CLI to reach for. + # PLATFORM is already resolved above; detection failure exited long before + # we got here. + platform:) + echo "$PLATFORM" + ;; + + pr:wait) + # timeout is the hard ceiling; idle_timeout is the no-progress window. + branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" ]] || die_usage "pr wait requires --branch" + + # Find PR for this branch + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + # Match branch — handle Gitea owner:branch format with endswith + pr=$(echo "$pr_json" | jq --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') + + if [[ -z "$pr" || "$pr" == "null" ]]; then + echo "status: no-pr" + echo "duration: 0s" + echo "No PR found for branch '$branch'" >&2 + exit 3 + fi + + pr_number=$(echo "$pr" | jq -r '.number') + pr_url=$(echo "$pr" | jq -r '.url // ""') + elapsed=0 + idle=0; idle_mark=0 + last_signal="" + unknown_streak=0 + + # Poll loop + while true; do + show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" + pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') + pr_merged=$(echo "$show_json" | jq -r '.merged // false') + pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') + + # Progress signals: CI still running or auto-merge pending means the PR is + # actively advancing toward merge, so the idle clock must not count down. + checks=$(_ci_status "$pr_number" "$branch") + if [[ "$PLATFORM" == "github" ]]; then + auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" + [[ "$auto_merge" == "true" ]] || auto_merge="false" + else + auto_merge="false" + fi + signal="$pr_state|$pr_mergeable|$checks|$auto_merge" + if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then + idle=0 + fi + last_signal="$signal" + + echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 + [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true + + case "$pr_state" in + merged) + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + closed) + if [[ "$pr_merged" == "true" ]]; then + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + fi + echo "status: closed" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR was closed without merging" >&2 + exit 0 + ;; + open) + # Check for merge conflicts + if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then + echo "status: blocked" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR has merge conflicts" >&2 + exit 0 + fi + # Still open — keep polling + ;; + *) + unknown_streak=$(( unknown_streak + 1 )) + if [[ "$unknown_streak" -ge 3 ]]; then + echo "status: error" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 + exit 4 + fi + echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 + ;; + esac + + # Reset unknown streak on any recognized state + [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 + + # Check timeout — only give up after a stretch of no progress (idle) or + # the absolute ceiling, never while CI/auto-merge is still working. + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + run:watch) + # timeout is the hard ceiling; idle_timeout is the no-progress backstop. + # While CI is actively pending the idle clock is reset each poll, so a long + # (15+ min) suite runs to completion up to the ceiling rather than being cut + # off by a flat wall-clock timeout. + branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 + alert_interval=300; next_alert=300; no_run_timeout="" + settle=0; settle_given=0; no_run_skew=0 + max_poll_failures=10; poll_fails=0 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; + --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; + --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" + [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" + [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" + # How long to wait for the FIRST run to appear (counted from the end of + # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ + # workflow_run and can queue minutes late, so that scope gets longer. + if [[ -z "$no_run_timeout" ]]; then + if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi + fi + + # `gh run list --commit` matches only on a FULL 40-character SHA -- a short + # one returns zero rows with no error, which this watcher would report as + # "no-workflow" rather than as the caller's mistake. Expand a short SHA via + # git when the commit is local, and refuse it outright when it is not, + # rather than silently watching nothing. (Gitea matches client-side on the + # first 12 chars, so a full SHA is correct there too.) + if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" + if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha="$_full_sha" + else + die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" + fi + fi + + elapsed=0 + idle=0; idle_mark=0 + + # A failed run-list call (network, auth, rate limit) is NOT an empty list. + # Note it, keep polling, and exclude the time from the no-workflow deadline + # (accumulated in no_run_skew). The hard ceiling still applies. After + # --max-poll-failures consecutive failures it gives up (exit 4). + _poll_failed() { + local what="$1" before="$elapsed" + poll_fails=$(( poll_fails + 1 )) + echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 + if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then + echo "status: error" + echo "duration: ${elapsed}s" + echo "reason: run list failed ${poll_fails} consecutive times" + echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 + exit 4 + fi + elapsed=$(( SECONDS - _t0 )) + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 + exit 2 + fi + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + no_run_skew=$(( no_run_skew + elapsed - before )) + } + + # Enforce the hard --timeout ceiling on paths that otherwise `continue` + # (no runs yet, settling, no checks registered) so they cannot outlive it. + _ceiling_check() { + local what="$1" + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what}" >&2 + exit 2 + fi + } + + # ------------------------------------------------------------------ + # --sha: watch EVERY run for one commit, not just the newest. + # + # `--branch` deliberately follows a single run (the newest correlated + # one). That is right for a PR branch, where one push means one run, but + # wrong for a default branch: two merges landing close together produce + # two runs, and the newest going green says nothing about the older one + # still executing. Watching a post-merge release run by branch reported + # "pass" while a second run was mid-flight. + # + # A commit is the honest scope for that question — the caller wants the + # runs *their* merge caused, not whatever else is landing on the branch. + # So this path aggregates: it stays non-terminal while ANY run for the + # commit is non-terminal, and fails if ANY run (or any job within one) + # failed. + # + # The CRITICAL DESIGN RULE below applies here too: only explicitly + # non-terminal statuses keep polling; anything unrecognized counts as + # terminal so an unexpected status cannot loop until timeout. + # ------------------------------------------------------------------ + if [[ -n "$sha" ]]; then + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + echo "Watching all runs for commit ${sha:0:12}..." >&2 + + # Settle window: after every run is terminal and passing, keep polling + # --settle seconds for a chained (workflow_run) run before reporting pass. + settle_start=-1; settle_ids="" + + while true; do + if ! sha_json=$(_run_list --sha "$sha" --limit 50); then + _poll_failed "commit ${sha:0:12}" + continue + fi + poll_fails=0 + sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) + + if [[ "$sha_count" -eq 0 ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + # Non-terminal set is explicit; everything else is terminal. + pending=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested")] + | length') + + echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 + + if [[ "$pending" -gt 0 ]]; then + pending_names=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested") + | (.workflow // .id)] | join(", ")') + _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" + # Active CI is progress — reset the idle clock, same as --branch. + idle=0 + settle_start=-1 + else + # Every run terminal. Collect run-level and job-level failures + # across ALL of them before declaring pass (#87 applies per run). + all_failed="" + fail_url="" + while IFS=$'\t' read -r r_id r_status r_url; do + [[ -n "$r_id" ]] || continue + case "$r_status" in + failure|timed_out|cancelled|canceled|skipped) + all_failed+="${all_failed:+,}run-$r_id:$r_status" + [[ -n "$fail_url" ]] || fail_url="$r_url" + ;; + *) + r_failed=$(_run_failed_jobs "$r_id") + if [[ -n "$r_failed" ]]; then + all_failed+="${all_failed:+,}$r_failed" + [[ -n "$fail_url" ]] || fail_url="$r_url" + fi + ;; + esac + done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') + + if [[ -n "$all_failed" ]]; then + echo "status: fail" + [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $all_failed" + echo "--- Failed job logs (last 80 lines) ---" >&2 + echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do + _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true + done + exit 0 + fi + + if [[ "$settle" -gt 0 ]]; then + cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') + if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then + echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 + settle_start=-1 + fi + if [[ "$settle_start" -lt 0 ]]; then + settle_start=$elapsed; settle_ids="$cur_ids" + fi + if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then + echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + fi + + echo "status: pass" + first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') + [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" + echo "duration: ${elapsed}s" + echo "runs: $sha_count" >&2 + exit 0 + fi + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so + # `run list --branch` correlates nothing and the watcher times out into + # no-workflow even when CI ran (#140). Resolve the branch head SHA up front + # (only on Gitea) and fall back to head_sha correlation when the + # branch-filtered lookup is empty. The run object's head_sha equals the + # branch head on Gitea (confirmed in #140); if a variant ever records a + # merge-ref SHA the fallback simply misses and degrades to today's + # behaviour rather than returning a wrong run. + _watch_branch_sha="" + if [[ "$PLATFORM" == "gitea" ]]; then + _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ + || git rev-parse "origin/$branch" 2>/dev/null || true) + fi + + # Echo a run-list JSON array for $branch: branch-name correlation first, + # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the + # server-side --branch filter populates the first call and _watch_branch_sha + # stays empty, so the SHA path is never taken. + _runs_for_branch() { + local lim="${1:-1}" out + # A failed call returns 1 (distinct from a successful empty "[]"). + out=$(_run_list --branch "$branch" --limit "$lim") || return 1 + if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then + echo "$out"; return 0 + fi + if [[ -n "$_watch_branch_sha" ]]; then + _run_list --limit 50 | jq \ + --arg s "$_watch_branch_sha" --argjson n "$lim" \ + '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ + || return 1 + return 0 + fi + echo "[]" + } + + # On GitHub, prefer PR-based status checking — one API call gives us both + # merge state and all CI check results via statusCheckRollup, avoiding the + # flaky run-level polling that produces "unknown" statuses. + pr_number="" + pr_url="" + use_pr=false + if [[ "$PLATFORM" == "github" ]]; then + pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { + pr_number=$(echo "$pr_json" | jq -r '.number // empty') + pr_url=$(echo "$pr_json" | jq -r '.url // ""') + [[ -n "$pr_number" ]] && use_pr=true + } + fi + + # Pre-check: look for an already-terminal state before sleeping the + # initial delay. If the PR already merged or CI already finished, + # report immediately instead of waiting. + _precheck_done=false + if [[ "$use_pr" == "true" ]]; then + _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" + _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') + + if [[ "$_pre_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already merged" >&2 + exit 0 + fi + if [[ "$_pre_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already closed without merging" >&2 + exit 0 + fi + + _pre_checks=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + if [[ "$_pre_checks" == "success" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "CI already passed on PR #$pr_number" >&2 + exit 0 + fi + + if [[ "$_pre_checks" == "failure" ]]; then + _pre_failed=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "failed_jobs: $_pre_failed" + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + fi + else + # Fallback path: check if a completed run already exists + _pre_list=$(_runs_for_branch 1) || _pre_list="[]" + _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') + if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then + _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') + _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') + _pre_id=$(echo "$_pre_latest" | jq -r '.id') + case "$_pre_status" in + success|completed) + # Run-level status can read "success" on Gitea even when a + # job inside the run failed (issue #87). Aggregate per-job + # status before declaring pass. + failed_jobs=$(_run_failed_jobs "$_pre_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "CI already passed for branch '$branch'" >&2 + exit 0 + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$_pre_id") + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$_pre_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a + # reason so consumers (ship/session-end) gating on + # status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "reason: $_pre_status" + echo "CI run $_pre_status for branch '$branch'" >&2 + exit 0 + ;; + esac + fi + fi + + # Initial delay — CI run may not exist immediately after push + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + if [[ "$use_pr" == "true" ]]; then + echo "Watching PR #$pr_number for branch '$branch'..." >&2 + + while true; do + # A failed gh call is not "unknown" -- count it, cap consecutive failures. + if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then + _poll_failed "PR #$pr_number" + continue + fi + poll_fails=0 + pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') + + # PR merged — all done + if [[ "$pr_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number merged" >&2 + exit 0 + fi + + # PR closed without merge + if [[ "$pr_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number closed without merging" >&2 + exit 0 + fi + + # Summarize CI check statuses from statusCheckRollup + # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state + checks_summary=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 + + case "$checks_summary" in + success) + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + failure) + failed_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_names" + # Try to fetch failed logs from the latest run + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + pending) + # Still running — keep polling. Active CI is progress, so reset idle. + check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') + if [[ "$check_count" -eq 0 ]]; then + # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + else + # Active CI is progress, so reset idle. + idle=0 + fi + pending_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select(if .__typename == "CheckRun" then (.conclusion // "") == "" + else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) + | .name // .context // "unknown"] | unique | join(", ")') + _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" + ;; + esac + + # Check timeout — idle window or absolute ceiling (see _wait_timed_out). + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Fallback: no PR found — poll run list directly (skip flaky run show). + # + # CRITICAL DESIGN RULE — default-terminal polling: + # + # This loop has caused repeated regressions (#53, #57, #58, #60). + # The recurring bug pattern is: + # 1. The API returns an unexpected status value (e.g. "completed" + # with null conclusion, or a new status GitHub adds later). + # 2. The case statement doesn't recognise it. + # 3. A catch-all `*) keep polling` silently loops until timeout. + # + # The fix (applied here) inverts the logic: + # - ONLY explicitly non-terminal states keep polling. + # - The `*` catch-all EXITS (as pass). + # + # DO NOT add a `*) keep polling` catch-all to this case statement. + # If a new non-terminal status appears, add it to the explicit list. + # If you're unsure whether a status is terminal, it's safer to exit + # early (the caller can retry) than to loop for 5 minutes. + # + run_url="" + while true; do + if ! list_json=$(_runs_for_branch 1); then + _poll_failed "branch '$branch'" + continue + fi + poll_fails=0 + latest=$(echo "$list_json" | jq -r '.[0] // empty') + + if [[ -z "$latest" || "$latest" == "null" ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + # Distinguish "no workflow registered at all" from "runs exist + # but none correlate to this branch" so callers (#103) can tell + # a real CI absence from a branch-correlation gap. + any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" + if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then + echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + else + echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + fi + exit 3 + fi + echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "branch '$branch'" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + run_id=$(echo "$latest" | jq -r '.id') + run_status=$(echo "$latest" | jq -r '.status // "unknown"') + run_url=$(echo "$latest" | jq -r '.url // ""') + + echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 + + # See "CRITICAL DESIGN RULE" above — non-terminal states are listed + # explicitly; everything else exits. Do NOT add a `*) keep polling`. + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) + # Non-terminal — keep polling. Active CI is progress, so reset idle. + idle=0 + _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$run_id") + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a reason + # so consumers gating on status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $run_status" + echo "CI run $run_status on branch '$branch'" >&2 + exit 0 + ;; + *) + # Terminal — covers success and any future/unexpected status. + # Even when the run-level status reports success, an individual + # job may have failed (Gitea reports run.status=success on a + # multi-job run if any job succeeded; see #87). Aggregate + # per-job status before declaring pass. + failed_jobs=$(_run_failed_jobs "$run_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + esac + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + --help:|-h:|:) + sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' + exit 0 + ;; + + *) + die_usage "unknown command: $cmd${sub:+ $sub}" + ;; +esac diff --git a/plugins-opencode/session/skills/session-end/scripts/sitrep b/plugins-opencode/session/skills/session-end/scripts/sitrep new file mode 100755 index 0000000..558f9e3 --- /dev/null +++ b/plugins-opencode/session/skills/session-end/scripts/sitrep @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# sitrep - Situation report for a git repository +# Always shows working-tree state (staged/unstaged/untracked) together with +# committed context, and falls back to broader repo activity only when +# nothing else is actionable. +# +# Sections: +# 1. Working tree (staged/unstaged/untracked) +# 2. Unpushed commits (ahead of remote tracking branch) +# 3. Branch work (commits on feature branch vs base) +# 4. Repo activity (active branches, open issues) - only when 1-3 are empty +# +# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). +# +# Exit codes: 0 success (including -h/--help), 1 bad usage + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" + +usage() { + cat <<'EOF' +Usage: sitrep [directory] + +Situation report for a git repository. Shows working-tree changes plus +unpushed and branch commits, expanding to broader repo activity only +when everything is clean. + +If directory is omitted, uses the current working directory. +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +if [[ $# -gt 1 ]]; then + usage >&2 + exit 1 +fi + +dir="${1:-.}" +cd "$dir" + +gitq() { + git -c core.quotepath=false "$@" +} + +# Print a diff section, truncated to MAX_DIFF_LINES. +emit_diff() { + local title="$1" text="$2" total + [[ -n "$text" ]] || return 0 + total="$(printf '%s\n' "$text" | wc -l)" + echo "" + echo "=== $title ===" + if ((total > MAX_DIFF_LINES)); then + printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" + echo "[truncated $((total - MAX_DIFF_LINES)) lines]" + else + printf '%s\n' "$text" + fi +} + +# --- Not a git repo --- +if ! gitq rev-parse --git-dir >/dev/null 2>&1; then + echo "=== REPO ===" + echo "is_git_repo: false" + exit 0 +fi + +# --- Basic repo info (always shown) --- +head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" +head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" + +echo "=== REPO ===" +if [[ -n "$head_branch" ]]; then + echo "branch: $head_branch" +else + echo "detached_at: $head_sha" +fi + +# Detect base branch: origin/HEAD, then origin/main|master, then local main|master +base_ref="" +origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" +for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do + [[ -n "$candidate" ]] || continue + if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then + base_ref="$candidate" + break + fi +done + +on_base=false +if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then + on_base=true +fi + +has_merge_base=false +if [[ -n "$base_ref" ]]; then + echo "base: $base_ref" + if ! $on_base; then + if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then + has_merge_base=true + else + echo "note: no merge base between $base_ref and HEAD (unrelated histories)" + fi + ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" + behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" + echo "ahead: $ahead" + echo "behind: $behind" + fi +fi + +found_activity=false + +# --- Working tree: staged / unstaged / untracked --- +staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" +unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" +untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" + +if [[ -n "$staged_files" ]]; then + found_activity=true + echo "" + echo "=== STAGED ===" + echo "$staged_files" + emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$unstaged_files" ]]; then + found_activity=true + echo "" + echo "=== UNSTAGED ===" + echo "$unstaged_files" + emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$untracked_files" ]]; then + found_activity=true + echo "" + echo "=== UNTRACKED ===" + echo "$untracked_files" +fi + +# --- Unpushed commits --- +tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" +unpushed="" + +if [[ -n "$tracking_branch" ]]; then + unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" +fi + +if [[ -n "$unpushed" ]]; then + found_activity=true + echo "" + echo "=== UNPUSHED ===" + echo "tracking: $tracking_branch" + echo "$unpushed" +fi + +# --- Branch work (feature branch vs base) --- +if ! $on_base && [[ -n "$base_ref" ]]; then + branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" + if [[ -n "$branch_commits" ]]; then + found_activity=true + echo "" + echo "=== BRANCH COMMITS ===" + echo "$branch_commits" + fi + + if $has_merge_base; then + committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + if [[ -n "$committed_files" ]]; then + found_activity=true + echo "" + echo "=== CHANGED FILES ===" + echo "$committed_files" + emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + fi + fi +fi + +if $found_activity; then + exit 0 +fi + +# --- Repo activity (everything clean, nothing ahead) --- +active_branches="" +if [[ -n "$base_ref" ]]; then + active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" +fi + +if [[ -n "$active_branches" ]]; then + echo "" + echo "=== ACTIVE BRANCHES ===" + echo "$active_branches" +fi + +# Open issues (requires git-wait for platform detection, plus gh or tea) +if [[ -x "$SCRIPT_DIR/git-wait" ]]; then + platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" + issues="" + issues_err="" + errfile="$(mktemp)" + case "$platform" in + github) + if command -v gh >/dev/null 2>&1; then + issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" + fi + ;; + gitea) + if command -v tea >/dev/null 2>&1; then + issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" + fi + ;; + esac + if [[ -n "$issues_err" ]]; then + detail="$(head -n 1 "$errfile" 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + echo "note: $issues_err${detail:+: $detail}" + elif [[ -n "$issues" && "$issues" != "[]" ]]; then + formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + if [[ -n "$formatted" ]]; then + echo "$formatted" + else + echo "note: could not parse issue list" + fi + fi + rm -f "$errfile" +fi + +# Recent commits on default branch for context +echo "" +echo "=== RECENT COMMITS ===" +gitq log --oneline -10 2>/dev/null || true + +# Nothing at all +if [[ -z "$active_branches" ]]; then + echo "" + echo "=== STATUS ===" + echo "clean: true" +fi diff --git a/plugins-opencode/session/skills/session-issue/SKILL.md b/plugins-opencode/session/skills/session-issue/SKILL.md new file mode 100644 index 0000000..6349f16 --- /dev/null +++ b/plugins-opencode/session/skills/session-issue/SKILL.md @@ -0,0 +1,135 @@ +--- +disable-model-invocation: true +name: session-issue +description: "Browse open issues, pick one or more, and start work on them" +--- + +The **discovery** door: rank the open issues, pick one or several, then run the +shared begin-work spine (resolve target → isolate → explore → plan). To start from +your own description instead, use `session-start`. + +> **CRITICAL**: You MUST drive this to a plan. NEVER print "suggested first steps" +> or ask "ready to start?" — the flow does not end until you have explored the code +> and called the `plan` agent. Plan approval then authorizes the whole stated scope +> for every unit before the last through merge: land each via `/ship` +> without stopping, then run the last unit through `session-end` (spine +> Phase 4). The one stop is before that final ship: summarize the work and caveats +> and wait for the user's go. Only then ship, watch CI, fix, re-merge, close out, and +> give a final summary. + +### Phase 1 — Pick issues + +1. **Detect the platform once** (the spine reuses it — do not detect again): + + ```bash + bash scripts/git-wait platform + ``` + + If detection fails (no remote, no CLI, or no supported platform), say there is no + issue tracker here, suggest `session-start`, and stop. + +2. **Issue numbers in the invocation arguments** (`#127 #125 #115`, `127 and 125`, `127,125`): + skip the ranked list. Validate each number first: fetch it (github: + `gh issue view <N> --json number,title,state`; gitea: `tea issues <N> --output json`) + and, if the fetch fails, the state is not open, or it is a pull request, tell the + user and drop it or stop (ask when unclear). If any remain, go to Phase 2. + Also warn and ask before proceeding when a number already appears in + `git config --get-regexp 'branch\..*\.session-issues'` or has an open PR. + +3. **Otherwise fetch and rank ALL open issues.** Fetch the JSON in the shell (not in + a subagent), saving it to a scratch file (`tmp=$(mktemp)`), and compute the count + there: + + - **github:** + + ```bash + gh issue list --state open --limit 200 \ + --json number,title,body,labels,milestone,comments,createdAt > "$tmp" + ``` + + - **gitea:** + + ```bash + tea issues list --state open --limit 200 --output json \ + --fields index,title,body,labels,milestone,comments,created > "$tmp" + ``` + + Then `COUNT=$(jq length "$tmp")`. Use this `COUNT` for the pick step — never ask + the model to count. Also compute the **deferred** issue numbers in the shell (an + issue is deferred when any label's last path segment is `deferred`, case-insensitive; + Gitea's number field is `index`): + + ```bash + DEFERRED=$(jq -c '[.[] | select(any((.labels // [])[]; (.name // .) | test("(^|/)deferred$"; "i"))) | (.number // .index)]' "$tmp") + ``` + + If `COUNT` is 0 or 1, skip the ranking agent (the pick step + needs only that issue's title and a one-line summary you write yourself). + Otherwise launch an `Agent` (`agent: general-purpose`, `model: haiku`) + with the scratch file path, `DEFERRED`, and this prompt: + + > Read the JSON array of open issues in `<path>` (GitHub calls the issue number + > `number` and the age field `createdAt`; Gitea calls them `index` and `created` — + > treat them the same). The deferred issue numbers are `<DEFERRED>`. Rank ALL + > issues by priority, highest first: + > +> - Labels indicating urgency: `critical`, `blocker`, `high-priority`, `bug` rank higher +> - Issues with a milestone set rank higher than those without +> - More comments → higher priority (community signal) +> - Older issues rank higher than newer (age as proxy for neglect) +> - **Deferred issues ALWAYS go last**, as a group after every non-deferred issue, + > regardless of any signal above; apply the ranking above within each group + > + > Return EVERY issue in that order, in this compact format — a `*` bullet, the + > number, then the title, with the summary on an indented second line: + > + > ```text + > * #NNN - <title> + > <one-sentence summary of the issue body, ≤25 words> + > ``` + > + > Do not list labels. Summarise only what is returned; do not quote bodies in + > full. If a body is empty, write `(no description)`. Do not fetch issues + > individually. + + Before showing the list, check it: every `DEFERRED` number must appear after + every non-deferred one. Fix the order yourself if not. + + Warn on any displayed issue that already appears in + `git config --get-regexp 'branch\..*\.session-issues'` or has an open PR. + +4. **Pick** based on the total `COUNT` of open issues: + - **0** — tell the user there are no open issues and suggest + `session-start` to begin from your own description. Stop here. + - **1** — state the single issue (`#N — Title`) plus its one-line summary, then + go straight to Phase 2 (no confirmation prompt). + - **2–4** — present them via the `question` tool with `multiSelect: true` (the + picker caps at 4 options, so the whole set fits). Each option label is + `#N — Title` (deferred options last); the description + carries the one-line summary. + - **5 or more** — too many for the picker. Do NOT use the `question` tool. Print the + full ranked list as plain text in the compact format above (deferred issues + last) — then ask the user to **type the + number(s)** they want (one or several, e.g. `127`, `127 125`, `#127 and #125`). + Wait for their text reply. (Do not pre-truncate to a "top N" — let the user + scan the whole list.) + + Several issues are fine: they share one branch/worktree and one plan. + +### Phase 2 — Run the spine + +5. **Read the shared begin-work spine and execute it** (use the Read tool): + + ```text + reference/spine.md + ``` + + Ground `continuing` first: run `git status --short -b`; if on a non-default branch + with commits ahead or uncommitted work, `continuing` is **true** (the spine skips + Isolate and reuses the branch), otherwise **false**. + + Hand the spine the chosen issue number(s), the detected platform, and `continuing`. + The spine fetches every issue, builds the base branch name, isolates, records issue + linkage, renames the session, explores (including the trivial fast path), plans one + plan covering **all** chosen issues, and, in Phase 4, lands each unit with one closing line per issue (the last unit via `session-end`). Complete every MANDATORY phase — + the flow ends only once you have presented a plan. diff --git a/plugins-opencode/session/skills/session-issue/reference/spine.md b/plugins-opencode/session/skills/session-issue/reference/spine.md new file mode 100644 index 0000000..efc0289 --- /dev/null +++ b/plugins-opencode/session/skills/session-issue/reference/spine.md @@ -0,0 +1,316 @@ +# Begin-work spine + +The shared playbook for the lightweight session entrypoints (`session-start` and +`session-issue`). Both doors differ only in **how the work is chosen** — once the +work is identified, they run these phases identically: resolve target → isolate → +explore → plan → build the approved scope. + +**Lightweight is the only flow here.** Do not ask "lightweight vs orchestrate", and +do not ask about worktree vs in-place, dependency symlinks, latency, or scope — +decide silently using the defaults below. Ask only when something is genuinely +ambiguous about **what to build** (the exceptions are the explicit prompts in Phase 0 +validation and Phase 1 collisions / dirty default branch). If the user asks for a +heavier multi-agent flow, mention once that `session-orchestrate` exists and +invoke it; never raise it unprompted. + +> **CRITICAL**: You MUST drive this through to a plan. After the branch exists you +> explore and enter plan mode. NEVER print "suggested first steps" or ask "ready to +> start?" — the flow does not end until you have switched to the `plan` agent with a plan +> built from real code exploration. +> +> **EQUALLY CRITICAL — the other end of the flow**: plan approval authorizes the +> whole stated scope, but the last unit is reviewed by the user before it ships. +> Implement each unit; land every unit before the last via `/ship` and move +> on without stopping, then run the last unit through `session-end` +> (Phase 4). The one deliberate stop is **before** that final ship: `session-end` +> summarizes the work and caveats and waits for the user's go. After the go it ships, +> watches CI, fixes and re-merges if needed, cleans up, and ends with a final-state +> summary. A one-PR session always pauses before its PR; a multi-PR scope pauses once, +> before the last PR. + +## Inputs (supplied by the calling door) + +- One of: **issue number(s)** (from `session-issue`, or `#N` references in a + `session-start` description or its related-issue lookup) or a **freeform + description**. +- Whether the door already knows the hosting `platform` (reuse it; never detect + twice). +- `continuing` (both doors determine it): **true** when the current branch is not the + default branch and has commits ahead of it or uncommitted work; otherwise false. + When true, skip Phase 1's Isolate steps and keep the current branch. + +If you reach this spine with neither issues nor a description, stop and return to +the calling door — it owns target selection. + +## Phase 0 — Resolve target + +Run this once, for both doors. + +1. **Fetch and validate issues** (skip for freeform work). Detect the platform once + unless the door already did, then fetch **every** referenced issue: + + ```bash + bash scripts/git-wait platform + ``` + + - **github:** `gh issue view <N> --json number,title,body,state,labels,comments` + - **gitea:** `tea issues <N> --output json` + + For anything beyond issue viewing (PR create, CI runs, state values), use the + command map in the `git-tools:git-wait` skill rather than guessing flags. + Keep each issue's title, body, and labels as context for the whole session. + + **Validate each issue.** If the fetch fails, the state is not open, or the number + is a pull request (not an issue), tell the user and either drop that number or + stop — ask which when it is not obvious. Also warn (and ask whether to proceed) + when an issue is already claimed: it appears in + `git config --get-regexp 'branch\..*\.session-issues'` or has an open PR. + +2. **Pick the branch type** from labels. Compare case-insensitively on the label's + **last path segment** (`kind/bug` and `Kind/Enhancement` match `bug` and + `enhancement`). With several issues, a `bug` label on any of them wins; otherwise + use the first issue's labels: + - `bug`, `fix` → `bug` + - `enhancement`, `feature`, `improvement` → `enhancement` + - `docs`, `chore`, `refactor`, `maintenance` → `chore` + - no matching label → `feature` + +3. **Name the work.** + - **Continuing** (`continuing` is true): do **not** build a new base name or + branch type. The session name is the current branch name with any leading + `worktree-` stripped. + - **Otherwise** build the base name: issue-linked `<type>-<slug>`; freeform + `wip-<slug>`. The slug is a kebab-case 3-5 word summary (of the first issue's + title, or the common theme when several issues are bundled; of the description + for freeform). The branch never encodes issue numbers — linkage is the closing + lines in the PR body. + + Actual branch names: created in place, the branch is `<base-name>`; created via + `opencode.worktree_create` (Phase 1), it is `worktree-<base-name>`. The session name is + `<base-name>`. + +4. **Closing lines.** One line per issue: `Fixes #N` for `bug` issues, `Closes #N` + otherwise. Phase 1 persists them. + +## Phase 1 — Isolate, record, rename + +**Skip the Isolate steps** (everything through "In place on a new branch") when +`continuing` is true, or when already inside a linked worktree. Detect the latter +with: + +```bash +git_dir=$(realpath "$(git rev-parse --path-format=absolute --git-dir)") +git_common_dir=$(realpath "$(git rev-parse --path-format=absolute --git-common-dir)") +[ "$git_dir" != "$git_common_dir" ] && echo "linked worktree" +``` + +(`realpath` avoids false differences from symlinked paths; same test as +`/ship` step 0.) Then go straight to "Record issue linkage" and "Rename the +session" below on the current checkout. + +Decide silently: + +- **Repo's `CLAUDE.md` says to work directly on the default branch / master** (as + `homelab-admin` does): do not create a branch or worktree; work on the default + branch in place and skip the rest of Isolate. There is no branch to record + linkage on; skip that step. +- **Otherwise: worktree by default.** It keeps the main checkout clean and lets + parallel sessions coexist. + +**Before creating anything:** + +- **Dirty default branch.** If on the default branch with uncommitted changes, warn + once that those edits stay in the main checkout (they are not carried into the + worktree) and ask whether to proceed with the worktree or work in place. This is a + genuine ambiguity, so ask. +- **Name collisions.** Check for `<base-name>` and `worktree-<base-name>`: + + ```bash + git worktree list + git branch --list "<base-name>" "worktree-<base-name>" + ``` + + If either exists, offer to **resume** it (enter the existing worktree via + `opencode.session_move` with that `directory`, or `git switch` to the branch) or to use a short + numeric suffix (`<base-name>-2`). Decide silently only when unambiguous (e.g. it + is clearly stale or clearly this same work); ask when it could be someone's other + work. If you resume, treat the run as `continuing`. + +**Worktree:** + +1. **Provision dependencies first.** A fresh worktree is a clean checkout — gitignored + deps don't carry over, and native provisioning only runs at creation time, so + configure it **before** creating the worktree. Symlink **dependency directories + only** — never build output (`target`, `build`, `dist`, `.next`, `.gradle`, + `.tox`), which is stale or wrong in another checkout. Detect those present: + + ```bash + for d in node_modules .venv venv vendor; do + [ -e "$d" ] && git check-ignore -q "$d" && echo "$d" + done + ``` + + Add the detected names **without asking** to `worktree.symlinkDirectories` in the + project's **`.claude/settings.local.json`** (`Local` scope — per-checkout, + normally gitignored; never the tracked `.claude/settings.json`, never global). + Merge with `jq`, unioning with any existing list and preserving all other keys; + create the file if absent. With the detected names in `$dirs` as a JSON array + (e.g. `'["node_modules",".venv"]'`): + + ```bash + f=.claude/settings.local.json + mkdir -p .claude + [ -s "$f" ] || echo '{}' > "$f" + jq --argjson d "$dirs" \ + '.worktree.symlinkDirectories = ((.worktree.symlinkDirectories // []) + $d | unique)' \ + "$f" > "$f.tmp" && mv "$f.tmp" "$f" + git check-ignore -q "$f" \ + || echo "/$f" >> "$(git rev-parse --path-format=absolute --git-path info/exclude)" + ``` + + Skip this step if no dependency directory was detected. Add `.env` / `.env.*` to a + root `.worktreeinclude` only if they exist. That file has no documented + alternative location, so keep it out of `git status` instead: if it is untracked, + add `/.worktreeinclude` to the same `info/exclude`. If the repo already tracks a + `.worktreeinclude`, append to it only when a needed pattern is missing and + mention the resulting diff in the Phase 4 report, since that one is a real change. + +2. **Create + enter the worktree:** call `opencode.worktree_create` with `name` set to the base + name (already dash form, no `/`). This creates the worktree (with its own branch) and returns its + directory; then move this session into it with `opencode.session_move` + (Code Mode). Do **not** also run `branch create`. + + This assumes `worktree.symlinkDirectories` is read at `worktree_create` time. As a + fallback, for each detected dependency directory missing in the new worktree, + create it yourself: `ln -s "<main-checkout>/<dir>" "<dir>"`. + +3. **Keep the tree clean for `ship`.** A directory pattern with a trailing slash + (e.g. `node_modules/`) does not match a *symlink*, so a symlinked dependency + directory can show up as untracked and trip `/ship`'s worktree + cleanliness gate. Inside the new worktree, exclude **only the dependency-directory + names detected in step 1** (not every untracked symlink): + + ```bash + exclude=$(git rev-parse --path-format=absolute --git-path info/exclude) + for d in $detected; do # names from step 1, e.g. node_modules .venv + [ -L "$d" ] && { grep -qxF "/$d" "$exclude" 2>/dev/null || printf '/%s\n' "$d" >> "$exclude"; } + done + git status --porcelain # expect no symlinked dependency dirs listed + ``` + + `info/exclude` is shared by every worktree of the repo, so these entries apply + everywhere; that is acceptable because root-relative dependency dirs are + normally ignored anyway. The `grep -qxF` guard prevents duplicates. + +**In place on a new branch** (only when the work genuinely cannot use a worktree): + +```bash +bash scripts/branch create <base-name> +``` + +**Record issue linkage** (always, once the branch exists — including when +`continuing`; skip when there are no linked issues or no branch). Store the closing +lines from Phase 0 step 4 as one comma-separated value, one entry per issue: + +```bash +git config "branch.$(git branch --show-current).session-issues" "Closes #12,Fixes #13" +``` + +The Phase 4 report, `session-end`, and `session-orchestrate` read this +key. When `continuing`, union with any existing value rather than overwriting. + +**Rename the session** (always, last). Use the session name from Phase 0 step 3: + +```ts +// Code Mode — no script, no ~/.claude writes +await tools.opencode.session_rename({ title: "<session-name>" }) +``` + +A rename failure is non-fatal: warn and continue. When working on the default +branch in place with no meaningful name, skip the rename (warn only). + +## Phase 2 — Explore the codebase + +> You MUST complete this phase. Do NOT stop after Phase 1. Do NOT print +> "suggested first steps". + +**Trivial fast path.** When the change is small and obvious — a typo, a one-line or +single-file fix, a config tweak, an issue that names the exact file and change — +skip the research subagents: read the few relevant files yourself and go straight to +Phase 3 with a short plan inside the `plan` agent. + +Otherwise launch **2-3 research agents in parallel** in a single message, using +`subagent` tool with `agent: explore`. Every agent prompt MUST include the full +context — the issue title/body/labels for **all** linked issues and/or the freeform +description — so the agent can work without seeing this conversation. Pick 2-3 +angles that fit: + +- **Locate the code** — files, functions, types, or modules implied by the work. + Report what each does, the change point, and surrounding signatures. +- **Find tests and related config** — existing coverage of the area, related config, + CI, docs. Report what exists, what is missing, how the suite is structured. +- **Trace the data/call flow** — entry points, intermediate steps, dependencies, and + edge cases. + +If an agent needs the issue tracker or repo API, tell it to use `gh` or `tea` +directly, per the `git-tools:git-wait` skill's command map. + +## Phase 3 — Plan + +> You MUST complete this phase. Do NOT stop after Phase 2. + +Switch the session to the built-in `plan` agent, then present a concrete plan for approval before any +implementation begins. Cover **all** linked issues in one plan. + +- **Changes** — the specific files and line ranges, and what each change does. + Describe the actual code change, not "fix the bug". +- **Testing** — include only when behavior changes: what tests to add or update, + using the project's existing framework. Omit for purely cosmetic changes + (comments, docs, formatting). +- **Risks & open questions** — edge cases and unknowns; omit when there are none. +- **Scope line, always last:** `Scope: <the PR(s)/unit(s) this plan covers>`. The + user defines the scope; approving the plan authorizes every unit listed through + merge. A single unit is a one-item scope. + +For trivial work keep the whole plan short — a few lines, not a document. Do **not** +otherwise describe the commit / push / PR / merge steps in the plan; Phase 4 defines +them. + +## Phase 4 — Report, continue the scope, pause before the final ship + +> Plan approval authorizes every unit before the last through merge: do **not** stop +> between those units or ask before their commit / push / PR / merge. The last (or +> only) unit is different: do not commit, push, or open its PR until the user has +> reviewed `session-end`'s summary and given the go. That is the only deliberate +> stop. + +After each unit is implemented: + +1. Print a **short progress note** (not a wait): one-line outcome, the per-file list + of what changed, branch, test/build status (say so plainly if tests were not + run), and any caveats — known or potential problems and assumptions, stated + specifically. Omit caveats only if there are genuinely none. +2. **If this is the last unit** (a single-unit scope is just this), do **not** ship + it here: go to `session-end`, which does docs, review, and the issue + sweep, then **stops before shipping** to summarize what was done and any + caveats and wait for the user's go. After the go it ships the unit once, watches + CI, fixes and re-merges if needed, closes out (issue closing, cleanup / + worktree teardown), and finishes with a final-state summary. +3. Otherwise (a unit before the last), optionally run + `/code-review <level> --fix` (e.g. `/code-review high --fix`), then land the unit: + commit → push → open PR → watch CI → merge, via `/ship` (a CI failure + clearly caused by the change is fixed forward within the unit, at most twice; + anything else is surfaced). If issues are linked, put one closing line per issue + (`Closes #N` / `Fixes #N`) in the PR body — read them from + `git config branch.$(git branch --show-current).session-issues` + (comma-separated) if they are no longer in context. +4. Start the next unit (re-isolate from the updated default branch, implement) and + repeat from step 1. + +- **Worked on the default branch in place** (repo `CLAUDE.md` says so): there is no + feature branch; `/ship` and `session-end` run from the default + branch. + +`/ship` step 9 tears down the worktree after each merge (the last unit's +ship runs inside `session-end`); the user can also +remove it later with `opencode.worktree_remove`. diff --git a/plugins-opencode/session/skills/session-issue/scripts/branch b/plugins-opencode/session/skills/session-issue/scripts/branch new file mode 100755 index 0000000..98f16e5 --- /dev/null +++ b/plugins-opencode/session/skills/session-issue/scripts/branch @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# branch - Git branch operations for session workflows +# Exit codes: 0 success (including -h/--help), 1 bad usage or invalid name, 2 git error +# +# Subcommands: +# create <name> Create and switch to a new branch + +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: branch <subcommand> [args] + +Subcommands: + create <name> Create and switch to a new branch +EOF +} + +die() { echo "Error: $*" >&2; exit 2; } + +[[ $# -ge 1 ]] || { usage >&2; exit 1; } + +cmd="$1"; shift + +case "$cmd" in + create) + [[ $# -eq 1 ]] || { echo "Usage: branch create <name>" >&2; exit 1; } + name="$1" + [[ "$name" != -* ]] || { echo "Error: branch name must not start with '-': $name" >&2; exit 1; } + git check-ref-format --branch "$name" >/dev/null 2>&1 || { echo "Error: invalid branch name: $name" >&2; exit 1; } + if git show-ref --verify --quiet "refs/heads/$name"; then + die "branch '$name' already exists" + fi + git switch -c "$name" || die "failed to create branch '$name'" + ;; + -h|--help) usage ;; + *) echo "Unknown subcommand: $cmd" >&2; usage >&2; exit 1 ;; +esac diff --git a/plugins-opencode/session/skills/session-issue/scripts/git-wait b/plugins-opencode/session/skills/session-issue/scripts/git-wait new file mode 100755 index 0000000..335f658 --- /dev/null +++ b/plugins-opencode/session/skills/session-issue/scripts/git-wait @@ -0,0 +1,1460 @@ +#!/usr/bin/env bash +# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. +# +# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: +# listing, creating, commenting, merging, closing, viewing logs. This script +# exists only for the three things neither CLI gives you: +# +# 1. Platform detection — matching the git remote hostname against configured +# tea logins, so a caller knows whether to reach for `gh` or `tea`. +# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a +# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on +# the merge itself; `tea` has no equivalent at all). +# 3. `run watch` — block until CI finishes, aggregating per-job status and +# dumping failed job logs. `gh run watch` is GitHub-only and misses +# job-level failures masked by a run-level success; `tea` has no watcher. +# +# Usage: +# git-wait [-C DIR] <command> ... +# Operate on the git repo at DIR instead of the current directory (like +# `git -C`). Must come before the command. gh/tea resolve the repo from the +# working directory, so this retargets every call without a caller-side cd. +# +# git-wait platform +# Echo "github" or "gitea" for the current repo's origin remote. +# +# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] +# [--alert-interval 300] +# Block until the PR for BRANCH reaches a terminal state. +# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, +# url, duration, and (when relevant) reason. +# +# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] +# [--timeout 14400] [--idle-timeout 0] [--interval 15] +# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] +# [--max-poll-failures 10] +# Block until CI finishes. Output: "status: pass|fail|closed|timeout| +# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed +# job logs go to stderr. +# +# --branch follows ONE run: the newest correlated to that branch (via the +# PR's check rollup when a PR exists, else the newest run in the list). +# That is right for a PR branch, where one push means one run. It is NOT +# sufficient on a default branch, where two merges landing close together +# produce two runs and the newest passing says nothing about the older +# one still executing. +# +# --sha watches EVERY run for one commit and is the correct flag for a +# post-merge/release watch: it stays pending while any run for the commit +# is pending, and fails if any run — or any job inside one — failed. Pass +# one or the other, not both. +# +# A running CI is never aborted for lack of visible progress: `run watch +# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress +# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO +# check is pending (running CI, or auto-merge armed, resets it), so a PR that +# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long +# jobs (VM boot + integration suite + teardown) can go quiet for a long time. +# While still waiting, a heartbeat alert goes to STDERR every --alert-interval +# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) +# pending: ...)". stdout key:value output is unchanged. +# +# --no-run-timeout is how long to wait for the FIRST run to appear before +# reporting no-workflow, counted from the end of --initial-delay. Default 600s +# for --sha (post-merge workflows queue late, or start only after another +# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty +# check. A stderr alert is printed each poll while waiting. A FAILED run-list +# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not +# counted toward this deadline and polling continues, but after +# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the +# watch gives up with "status: error" and exit 4. A successful poll resets the +# count. +# +# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the +# commit is terminal and passing, keep polling SECS more before reporting pass, +# so a chained workflow_run workflow that appears late is still watched. A +# stderr line is printed while settling; a new run restarts the watch. +# +# Exit codes: 0 terminal state reached (check "status:" for pass/fail), +# 1 usage error, 2 timeout, 3 platform detection failure or no +# PR/workflow found, 4 command failed + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +die() { echo "git-wait: $*" >&2; exit 1; } +die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } + +# Run a CLI command and pipe its stdout through a jq filter. +# If the command fails, die with its stderr instead of feeding junk to jq. +# Usage: cli_json [jq-flags...] <jq-filter> <cmd> [args...] +# +# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. +# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, +# auth warnings, progress text) into the JSON, silently corrupting jq +# parsing and producing wrong results downstream (e.g. run watch seeing +# unexpected status values). +cli_json() { + local jq_flags=() + while [[ "$1" =~ ^-[a-zA-Z] ]]; do + # Collect jq flags (e.g. -r, -e) — stop at the filter string + case "$1" in + -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; + *) break ;; + esac + done + local filter="$1"; shift + local raw stderr_file rc=0 + stderr_file=$(mktemp) + raw=$("$@" 2>"$stderr_file") || rc=$? + if [[ $rc -ne 0 ]]; then + local err + err=$(cat "$stderr_file") + rm -f "$stderr_file" + die "$err" + fi + rm -f "$stderr_file" + echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" +} + +# --------------------------------------------------------------------------- +# Target repo (-C DIR) +# +# Handled before platform detection. The cd happens inside this script's own +# process, so the caller's working directory is never touched. +# --------------------------------------------------------------------------- + +if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then + [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" + target_dir="$2" + [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" + git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die_usage "$1: not a git repository: $target_dir" + # Resolve the script path first: a relative $0 breaks once we cd (help reads it). + SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + cd "$target_dir" + shift 2 +fi +SELF="${SELF:-$0}" + +# --------------------------------------------------------------------------- +# Platform detection +# --------------------------------------------------------------------------- + +detect_platform() { + local remote_url hostname login_url login_host + remote_url=$(git remote get-url origin 2>/dev/null) \ + || die "no git remote 'origin' found — run from a git repository" + + # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) + # or HTTPS (https://host/org/repo or https://host:port/org/repo) + if [[ "$remote_url" =~ ^ssh:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') + elif [[ "$remote_url" =~ ^git@ ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') + elif [[ "$remote_url" =~ ^https?:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') + else + die "unrecognised remote URL format: $remote_url" + fi + + # Check if this hostname matches any configured tea login + if command -v tea >/dev/null 2>&1; then + while IFS= read -r login_url; do + login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') + if [[ "$login_host" == "$hostname" ]]; then + echo "gitea" + return + fi + done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) + fi + + # Not a known tea login — fall back to gh (GitHub) + if [[ "$hostname" == "github.com" ]]; then + echo "github" + return + fi + + die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" +} + +PLATFORM=$(detect_platform) + +case "$PLATFORM" in + github) CLI=gh ;; + gitea) CLI=tea ;; +esac + +command -v "$CLI" >/dev/null 2>&1 \ + || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } + +# --------------------------------------------------------------------------- +# Internal reads +# +# These are NOT public subcommands — they are the normalized queries the two +# waiters below need. Every one of them dies on backend failure, so callers +# invoke them inside $( ) with a fallback: a probe failure must degrade the +# poll loop, never abort it. +# --------------------------------------------------------------------------- + +# List PRs as normalized JSON. Flags: --state, --limit, --assignee. +_pr_list() { + local limit assignee state args + limit=30; assignee=""; state="open" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; + --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") + # gh uses 'merged' as a state but tea uses 'closed' for merged PRs + [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") + [[ -n "$assignee" ]] && args+=(--assignee "$assignee") + cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ + env GH_NO_COLOR=1 gh pr list "${args[@]}" + ;; + gitea) + args=(--output json --limit "$limit" + --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") + [[ "$state" == "merged" ]] && state="closed" + args+=(--state "$state") + cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ + env NO_COLOR=1 tea pr list "${args[@]}" + ;; + esac +} + +# Show one PR as normalized JSON. Takes <N> or --branch NAME. +_pr_show() { + local num branch pr_json pr_stderr pr_rc pr_detail err + num=""; branch="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --*) die_usage "unknown flag: $1" ;; + *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; + esac + shift + done + [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass <N> or --branch NAME, not both" + if [[ -n "$branch" ]]; then + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + num=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + [[ -n "$num" ]] || die "no PR found for branch '$branch'" + fi + [[ -n "$num" ]] || die_usage "usage: git-wait pr show <N> | --branch NAME" + case "$PLATFORM" in + github) + cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ + env GH_NO_COLOR=1 gh pr view "$num" \ + --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" + ;; + gitea) + # `tea pr list` omits the `merged` boolean and `merged_at` timestamp + # entirely (tea only encodes merge state into the `state` string) and + # emits `mergeable` as a string, so a merged PR reports + # merged:false / mergedAt:null and consumers think it is still open + # (#140). Fetch the PR detail via the REST API instead, mirroring the + # run:show/run:list `tea api` pattern, so merge fields are reliable. + pr_stderr=$(mktemp); pr_rc=0 + pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ + || pr_rc=$? + if [[ $pr_rc -ne 0 ]]; then + err=$(cat "$pr_stderr"); rm -f "$pr_stderr" + die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" + fi + rm -f "$pr_stderr" + # Derive `state` from `merged` so it stays consistent with the merge + # flags (Gitea REST reports state:"closed" for a merged PR) and matches + # the GitHub path, which emits state:"merged". + echo "$pr_detail" | jq '{ + number: (.number // .index), + title: (.title // ""), + body: (.body // ""), + state: (if (.merged // false) then "merged" else (.state // "") end), + merged: (.merged // false), + merged_at: (.merged_at // null), + author: (.user.login // .user.username // ""), + head: (.head.ref // .head.label // ""), + base: (.base.ref // .base.label // ""), + labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), + assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), + mergeable: (.mergeable // null), + created_at: (.created_at // ""), + updated_at: (.updated_at // null), + url: (.html_url // .url // ""), + comments: [] + }' + ;; + esac +} + +# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. +_auto_merge_status() { + local branch number pr_json am + branch=""; number="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) shift; branch="$1" ;; + --number) shift; number="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + + # Resolve PR number from branch if needed + if [[ -z "$number" ]]; then + [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" + pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" + number=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + if [[ -z "$number" || "$number" == "null" ]]; then + echo "auto_merge: false" + echo "No open PR found for branch '$branch'" >&2 + exit 3 + fi + fi + + case "$PLATFORM" in + github) + am=$(cli_json -r '.autoMergeRequest != null' \ + env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) + echo "auto_merge: $am" + ;; + gitea) + echo "auto_merge: false" + echo "Gitea does not support auto-merge detection" >&2 + ;; + esac +} + +# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. +# +# --sha filters to runs for one commit. GitHub has a server-side filter for it +# (`gh run list --commit`); Gitea does not, so it is applied client-side over +# an unfiltered fetch, the same way --branch already is there. Both platforms +# emit head_sha in the normalized output — GitHub did not used to, which is +# why `run watch --sha` needs the headSha field added below. +_run_list() { + local limit status branch sha args query raw_stderr raw_rc raw err + limit=20; status=""; branch=""; sha="" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") + [[ -n "$status" ]] && args+=(--status "$status") + [[ -n "$branch" ]] && args+=(--branch "$branch") + [[ -n "$sha" ]] && args+=(--commit "$sha") + cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ + env GH_NO_COLOR=1 gh run list "${args[@]}" + ;; + gitea) + # Source from Gitea REST API directly. `tea actions runs list` + # filters server-side by a `branch` column that Gitea leaves empty + # on `pull_request` runs, so the watcher's --branch lookup misses + # correlated runs (#103). Fetch unfiltered via `tea api`, normalize + # `branch` from `head_branch`, and apply --branch client-side. + query="limit=$limit" + [[ -n "$status" ]] && query+="&status=$status" + raw_stderr=$(mktemp); raw_rc=0 + raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ + || raw_rc=$? + if [[ $raw_rc -ne 0 ]]; then + err=$(cat "$raw_stderr"); rm -f "$raw_stderr" + die "tea api repos/{owner}/{repo}/actions/runs failed: $err" + fi + rm -f "$raw_stderr" + echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' + [(.workflow_runs // []) | .[] | { + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + head_sha: (.head_sha // ""), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // "") + }] + | if $b == "" then . else [.[] | select(.branch == $b)] end + | if $s == "" then . else + [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] + end + ' + ;; + esac +} + +# Show one CI run as normalized JSON, including per-job status. +_run_show() { + local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err + [[ $# -ge 1 ]] || die_usage "usage: git-wait run show <run-id>" + run_id="$1" + case "$PLATFORM" in + github) + cli_json \ + 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ + env GH_NO_COLOR=1 gh run view "$run_id" \ + --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" + ;; + gitea) + # Fetch the run object via the REST API. `tea actions runs view` + # ignores `--output json` (tea 0.14.1) and prints a human key/value + # table while still exiting 0, so jq downstream chokes (#133). Use the + # same `tea api` pattern as run:list and the jobs lookup below. + view_stderr=$(mktemp); view_rc=0 + view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ + || view_rc=$? + if [[ $view_rc -ne 0 ]]; then + err=$(cat "$view_stderr"); rm -f "$view_stderr" + die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" + fi + rm -f "$view_stderr" + + # Fetch per-job data via the actions API so callers (run watch) can + # detect job-level failures masked by run-level status=success on + # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. + jobs_array='[]' + jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) + if [[ -n "$jobs_json" ]]; then + jobs_array=$(echo "$jobs_json" | jq -c ' + def to_status: + if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) + end; + [(.jobs // .) | (if type == "array" then .[]? else empty end) | + {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] + ' 2>/dev/null) || jobs_array='[]' + fi + + # Older Gitea versions may not expose the jobs API; fall back to + # scanning the run logs for "Job '<name>' failed" lines. + if [[ "$jobs_array" == '[]' ]]; then + failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ + | grep -oE "Job '[^']+' failed" \ + | sed -E "s/Job '(.+)' failed/\1/" \ + | sort -u || true) + if [[ -n "$failed_log" ]]; then + jobs_array=$(printf '%s\n' "$failed_log" \ + | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') + fi + fi + + # Normalize REST field names into the output contract, mirroring the + # run:list jq above (conclusion-first status, head_branch//branch, + # run_started_at//created, name//workflow_id). + echo "$view_json" | jq --argjson jobs "$jobs_array" '{ + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // ""), + jobs: $jobs + }' + ;; + esac +} + +# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; +# Gitea has no server-side filter and returns every job's log). +_run_logs() { + local run_id failed_only + [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs <run-id> [--failed-only]" + run_id="$1"; shift + failed_only=false + while [[ $# -gt 0 ]]; do + case "$1" in + --failed-only) failed_only=true ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + if [[ "$failed_only" == "true" ]]; then + GH_NO_COLOR=1 gh run view "$run_id" --log-failed + else + GH_NO_COLOR=1 gh run view "$run_id" --log + fi + ;; + gitea) + # tea actions runs logs outputs all job logs; no built-in failed-only filter + NO_COLOR=1 tea actions runs logs "$run_id" + ;; + esac +} + +# --------------------------------------------------------------------------- +# Run helpers +# --------------------------------------------------------------------------- + +# Return comma-separated names of any jobs in <run_id> whose status is +# "failure", or empty if none. Used by run watch to detect job-level failures +# even when the run-level status reports success — Gitea sets run.status to +# "success" on a multi-job workflow if at least one job ran successfully, +# masking failures in earlier jobs (see issue #87). Calls "run show" to +# normalize per-platform JSON, so it works for both gh and tea paths. +_run_failed_jobs() { + local run_id="$1" show_json + show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 + echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' +} + +# Progress-aware timeout decision shared by `pr wait` and `run watch`. +# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress +# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. +# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ +# minutes: this lets callers keep waiting while CI is actively progressing and +# give up only after a stretch of no progress, with a hard ceiling backstop. +_wait_timed_out() { + local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" + if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then + echo "ceiling"; return 0 + fi + if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then + echo "idle"; return 0 + fi + return 1 +} + +# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. +_fmt_dur() { + local s="$1" + if [[ "$s" -lt 60 ]]; then echo "${s}s" + elif [[ "$s" -lt 3600 ]]; then + if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi + else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi +} + +# Periodic stderr heartbeat while a wait is still running. Callers set +# alert_interval (0 disables) and next_alert (initialised to alert_interval), +# and call `_heartbeat "$elapsed" "<detail>"` once per poll. Emits at most one +# alert per poll, then re-arms for the next multiple of alert_interval, so a +# slow poll never produces a burst. stderr only: stdout stays parseable. +_heartbeat() { + local el="$1" detail="$2" + [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 + echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 + next_alert=$(( (el / alert_interval + 1) * alert_interval )) +} + +# Coarse CI status — pending|success|failure|none — for a PR/branch, used by +# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the +# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is +# guarded so a probe failure degrades to "none" and never aborts the wait loop. +_ci_status() { + local pr_number="$1" branch="$2" view_json run_status + case "$PLATFORM" in + github) + view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } + echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) else "pending" end + else (.state // "pending" | ascii_downcase) end + ] | + if length == 0 then "none" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" end' 2>/dev/null || echo "none" + ;; + gitea) + run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) echo "pending" ;; + failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; + ""|none|null) echo "none" ;; + *) echo "success" ;; + esac + ;; + *) echo "none" ;; + esac +} + +# --------------------------------------------------------------------------- +# Command routing +# --------------------------------------------------------------------------- + +cmd="${1:-}" +sub="${2:-}" +shift 2 || shift || true + +case "$cmd:$sub" in + + # Echo the detected platform so callers know which CLI to reach for. + # PLATFORM is already resolved above; detection failure exited long before + # we got here. + platform:) + echo "$PLATFORM" + ;; + + pr:wait) + # timeout is the hard ceiling; idle_timeout is the no-progress window. + branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" ]] || die_usage "pr wait requires --branch" + + # Find PR for this branch + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + # Match branch — handle Gitea owner:branch format with endswith + pr=$(echo "$pr_json" | jq --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') + + if [[ -z "$pr" || "$pr" == "null" ]]; then + echo "status: no-pr" + echo "duration: 0s" + echo "No PR found for branch '$branch'" >&2 + exit 3 + fi + + pr_number=$(echo "$pr" | jq -r '.number') + pr_url=$(echo "$pr" | jq -r '.url // ""') + elapsed=0 + idle=0; idle_mark=0 + last_signal="" + unknown_streak=0 + + # Poll loop + while true; do + show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" + pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') + pr_merged=$(echo "$show_json" | jq -r '.merged // false') + pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') + + # Progress signals: CI still running or auto-merge pending means the PR is + # actively advancing toward merge, so the idle clock must not count down. + checks=$(_ci_status "$pr_number" "$branch") + if [[ "$PLATFORM" == "github" ]]; then + auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" + [[ "$auto_merge" == "true" ]] || auto_merge="false" + else + auto_merge="false" + fi + signal="$pr_state|$pr_mergeable|$checks|$auto_merge" + if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then + idle=0 + fi + last_signal="$signal" + + echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 + [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true + + case "$pr_state" in + merged) + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + closed) + if [[ "$pr_merged" == "true" ]]; then + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + fi + echo "status: closed" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR was closed without merging" >&2 + exit 0 + ;; + open) + # Check for merge conflicts + if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then + echo "status: blocked" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR has merge conflicts" >&2 + exit 0 + fi + # Still open — keep polling + ;; + *) + unknown_streak=$(( unknown_streak + 1 )) + if [[ "$unknown_streak" -ge 3 ]]; then + echo "status: error" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 + exit 4 + fi + echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 + ;; + esac + + # Reset unknown streak on any recognized state + [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 + + # Check timeout — only give up after a stretch of no progress (idle) or + # the absolute ceiling, never while CI/auto-merge is still working. + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + run:watch) + # timeout is the hard ceiling; idle_timeout is the no-progress backstop. + # While CI is actively pending the idle clock is reset each poll, so a long + # (15+ min) suite runs to completion up to the ceiling rather than being cut + # off by a flat wall-clock timeout. + branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 + alert_interval=300; next_alert=300; no_run_timeout="" + settle=0; settle_given=0; no_run_skew=0 + max_poll_failures=10; poll_fails=0 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; + --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; + --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" + [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" + [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" + # How long to wait for the FIRST run to appear (counted from the end of + # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ + # workflow_run and can queue minutes late, so that scope gets longer. + if [[ -z "$no_run_timeout" ]]; then + if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi + fi + + # `gh run list --commit` matches only on a FULL 40-character SHA -- a short + # one returns zero rows with no error, which this watcher would report as + # "no-workflow" rather than as the caller's mistake. Expand a short SHA via + # git when the commit is local, and refuse it outright when it is not, + # rather than silently watching nothing. (Gitea matches client-side on the + # first 12 chars, so a full SHA is correct there too.) + if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" + if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha="$_full_sha" + else + die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" + fi + fi + + elapsed=0 + idle=0; idle_mark=0 + + # A failed run-list call (network, auth, rate limit) is NOT an empty list. + # Note it, keep polling, and exclude the time from the no-workflow deadline + # (accumulated in no_run_skew). The hard ceiling still applies. After + # --max-poll-failures consecutive failures it gives up (exit 4). + _poll_failed() { + local what="$1" before="$elapsed" + poll_fails=$(( poll_fails + 1 )) + echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 + if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then + echo "status: error" + echo "duration: ${elapsed}s" + echo "reason: run list failed ${poll_fails} consecutive times" + echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 + exit 4 + fi + elapsed=$(( SECONDS - _t0 )) + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 + exit 2 + fi + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + no_run_skew=$(( no_run_skew + elapsed - before )) + } + + # Enforce the hard --timeout ceiling on paths that otherwise `continue` + # (no runs yet, settling, no checks registered) so they cannot outlive it. + _ceiling_check() { + local what="$1" + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what}" >&2 + exit 2 + fi + } + + # ------------------------------------------------------------------ + # --sha: watch EVERY run for one commit, not just the newest. + # + # `--branch` deliberately follows a single run (the newest correlated + # one). That is right for a PR branch, where one push means one run, but + # wrong for a default branch: two merges landing close together produce + # two runs, and the newest going green says nothing about the older one + # still executing. Watching a post-merge release run by branch reported + # "pass" while a second run was mid-flight. + # + # A commit is the honest scope for that question — the caller wants the + # runs *their* merge caused, not whatever else is landing on the branch. + # So this path aggregates: it stays non-terminal while ANY run for the + # commit is non-terminal, and fails if ANY run (or any job within one) + # failed. + # + # The CRITICAL DESIGN RULE below applies here too: only explicitly + # non-terminal statuses keep polling; anything unrecognized counts as + # terminal so an unexpected status cannot loop until timeout. + # ------------------------------------------------------------------ + if [[ -n "$sha" ]]; then + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + echo "Watching all runs for commit ${sha:0:12}..." >&2 + + # Settle window: after every run is terminal and passing, keep polling + # --settle seconds for a chained (workflow_run) run before reporting pass. + settle_start=-1; settle_ids="" + + while true; do + if ! sha_json=$(_run_list --sha "$sha" --limit 50); then + _poll_failed "commit ${sha:0:12}" + continue + fi + poll_fails=0 + sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) + + if [[ "$sha_count" -eq 0 ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + # Non-terminal set is explicit; everything else is terminal. + pending=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested")] + | length') + + echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 + + if [[ "$pending" -gt 0 ]]; then + pending_names=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested") + | (.workflow // .id)] | join(", ")') + _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" + # Active CI is progress — reset the idle clock, same as --branch. + idle=0 + settle_start=-1 + else + # Every run terminal. Collect run-level and job-level failures + # across ALL of them before declaring pass (#87 applies per run). + all_failed="" + fail_url="" + while IFS=$'\t' read -r r_id r_status r_url; do + [[ -n "$r_id" ]] || continue + case "$r_status" in + failure|timed_out|cancelled|canceled|skipped) + all_failed+="${all_failed:+,}run-$r_id:$r_status" + [[ -n "$fail_url" ]] || fail_url="$r_url" + ;; + *) + r_failed=$(_run_failed_jobs "$r_id") + if [[ -n "$r_failed" ]]; then + all_failed+="${all_failed:+,}$r_failed" + [[ -n "$fail_url" ]] || fail_url="$r_url" + fi + ;; + esac + done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') + + if [[ -n "$all_failed" ]]; then + echo "status: fail" + [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $all_failed" + echo "--- Failed job logs (last 80 lines) ---" >&2 + echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do + _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true + done + exit 0 + fi + + if [[ "$settle" -gt 0 ]]; then + cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') + if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then + echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 + settle_start=-1 + fi + if [[ "$settle_start" -lt 0 ]]; then + settle_start=$elapsed; settle_ids="$cur_ids" + fi + if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then + echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + fi + + echo "status: pass" + first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') + [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" + echo "duration: ${elapsed}s" + echo "runs: $sha_count" >&2 + exit 0 + fi + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so + # `run list --branch` correlates nothing and the watcher times out into + # no-workflow even when CI ran (#140). Resolve the branch head SHA up front + # (only on Gitea) and fall back to head_sha correlation when the + # branch-filtered lookup is empty. The run object's head_sha equals the + # branch head on Gitea (confirmed in #140); if a variant ever records a + # merge-ref SHA the fallback simply misses and degrades to today's + # behaviour rather than returning a wrong run. + _watch_branch_sha="" + if [[ "$PLATFORM" == "gitea" ]]; then + _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ + || git rev-parse "origin/$branch" 2>/dev/null || true) + fi + + # Echo a run-list JSON array for $branch: branch-name correlation first, + # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the + # server-side --branch filter populates the first call and _watch_branch_sha + # stays empty, so the SHA path is never taken. + _runs_for_branch() { + local lim="${1:-1}" out + # A failed call returns 1 (distinct from a successful empty "[]"). + out=$(_run_list --branch "$branch" --limit "$lim") || return 1 + if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then + echo "$out"; return 0 + fi + if [[ -n "$_watch_branch_sha" ]]; then + _run_list --limit 50 | jq \ + --arg s "$_watch_branch_sha" --argjson n "$lim" \ + '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ + || return 1 + return 0 + fi + echo "[]" + } + + # On GitHub, prefer PR-based status checking — one API call gives us both + # merge state and all CI check results via statusCheckRollup, avoiding the + # flaky run-level polling that produces "unknown" statuses. + pr_number="" + pr_url="" + use_pr=false + if [[ "$PLATFORM" == "github" ]]; then + pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { + pr_number=$(echo "$pr_json" | jq -r '.number // empty') + pr_url=$(echo "$pr_json" | jq -r '.url // ""') + [[ -n "$pr_number" ]] && use_pr=true + } + fi + + # Pre-check: look for an already-terminal state before sleeping the + # initial delay. If the PR already merged or CI already finished, + # report immediately instead of waiting. + _precheck_done=false + if [[ "$use_pr" == "true" ]]; then + _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" + _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') + + if [[ "$_pre_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already merged" >&2 + exit 0 + fi + if [[ "$_pre_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already closed without merging" >&2 + exit 0 + fi + + _pre_checks=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + if [[ "$_pre_checks" == "success" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "CI already passed on PR #$pr_number" >&2 + exit 0 + fi + + if [[ "$_pre_checks" == "failure" ]]; then + _pre_failed=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "failed_jobs: $_pre_failed" + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + fi + else + # Fallback path: check if a completed run already exists + _pre_list=$(_runs_for_branch 1) || _pre_list="[]" + _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') + if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then + _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') + _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') + _pre_id=$(echo "$_pre_latest" | jq -r '.id') + case "$_pre_status" in + success|completed) + # Run-level status can read "success" on Gitea even when a + # job inside the run failed (issue #87). Aggregate per-job + # status before declaring pass. + failed_jobs=$(_run_failed_jobs "$_pre_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "CI already passed for branch '$branch'" >&2 + exit 0 + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$_pre_id") + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$_pre_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a + # reason so consumers (ship/session-end) gating on + # status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "reason: $_pre_status" + echo "CI run $_pre_status for branch '$branch'" >&2 + exit 0 + ;; + esac + fi + fi + + # Initial delay — CI run may not exist immediately after push + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + if [[ "$use_pr" == "true" ]]; then + echo "Watching PR #$pr_number for branch '$branch'..." >&2 + + while true; do + # A failed gh call is not "unknown" -- count it, cap consecutive failures. + if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then + _poll_failed "PR #$pr_number" + continue + fi + poll_fails=0 + pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') + + # PR merged — all done + if [[ "$pr_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number merged" >&2 + exit 0 + fi + + # PR closed without merge + if [[ "$pr_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number closed without merging" >&2 + exit 0 + fi + + # Summarize CI check statuses from statusCheckRollup + # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state + checks_summary=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 + + case "$checks_summary" in + success) + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + failure) + failed_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_names" + # Try to fetch failed logs from the latest run + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + pending) + # Still running — keep polling. Active CI is progress, so reset idle. + check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') + if [[ "$check_count" -eq 0 ]]; then + # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + else + # Active CI is progress, so reset idle. + idle=0 + fi + pending_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select(if .__typename == "CheckRun" then (.conclusion // "") == "" + else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) + | .name // .context // "unknown"] | unique | join(", ")') + _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" + ;; + esac + + # Check timeout — idle window or absolute ceiling (see _wait_timed_out). + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Fallback: no PR found — poll run list directly (skip flaky run show). + # + # CRITICAL DESIGN RULE — default-terminal polling: + # + # This loop has caused repeated regressions (#53, #57, #58, #60). + # The recurring bug pattern is: + # 1. The API returns an unexpected status value (e.g. "completed" + # with null conclusion, or a new status GitHub adds later). + # 2. The case statement doesn't recognise it. + # 3. A catch-all `*) keep polling` silently loops until timeout. + # + # The fix (applied here) inverts the logic: + # - ONLY explicitly non-terminal states keep polling. + # - The `*` catch-all EXITS (as pass). + # + # DO NOT add a `*) keep polling` catch-all to this case statement. + # If a new non-terminal status appears, add it to the explicit list. + # If you're unsure whether a status is terminal, it's safer to exit + # early (the caller can retry) than to loop for 5 minutes. + # + run_url="" + while true; do + if ! list_json=$(_runs_for_branch 1); then + _poll_failed "branch '$branch'" + continue + fi + poll_fails=0 + latest=$(echo "$list_json" | jq -r '.[0] // empty') + + if [[ -z "$latest" || "$latest" == "null" ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + # Distinguish "no workflow registered at all" from "runs exist + # but none correlate to this branch" so callers (#103) can tell + # a real CI absence from a branch-correlation gap. + any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" + if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then + echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + else + echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + fi + exit 3 + fi + echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "branch '$branch'" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + run_id=$(echo "$latest" | jq -r '.id') + run_status=$(echo "$latest" | jq -r '.status // "unknown"') + run_url=$(echo "$latest" | jq -r '.url // ""') + + echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 + + # See "CRITICAL DESIGN RULE" above — non-terminal states are listed + # explicitly; everything else exits. Do NOT add a `*) keep polling`. + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) + # Non-terminal — keep polling. Active CI is progress, so reset idle. + idle=0 + _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$run_id") + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a reason + # so consumers gating on status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $run_status" + echo "CI run $run_status on branch '$branch'" >&2 + exit 0 + ;; + *) + # Terminal — covers success and any future/unexpected status. + # Even when the run-level status reports success, an individual + # job may have failed (Gitea reports run.status=success on a + # multi-job run if any job succeeded; see #87). Aggregate + # per-job status before declaring pass. + failed_jobs=$(_run_failed_jobs "$run_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + esac + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + --help:|-h:|:) + sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' + exit 0 + ;; + + *) + die_usage "unknown command: $cmd${sub:+ $sub}" + ;; +esac diff --git a/plugins-opencode/session/skills/session-orchestrate/SKILL.md b/plugins-opencode/session/skills/session-orchestrate/SKILL.md new file mode 100644 index 0000000..13d747c --- /dev/null +++ b/plugins-opencode/session/skills/session-orchestrate/SKILL.md @@ -0,0 +1,240 @@ +--- +name: session-orchestrate +description: "User-invoked multi-phase, multi-agent feature workflow: spec → plan → refine → divide → execute → review. Run via session-orchestrate for a non-trivial feature (multiple files, design ambiguity, cross-cutting concerns, correctness-critical paths) that needs a heavier flow than session-start/session-issue. For small fixes, prefer session-start." +disable-model-invocation: true +--- + +Run a complex feature through a structured multi-agent workflow with explicit model tiering, user gates, and an automated review pass. Use this when work is non-trivial — multiple files, design ambiguity, cross-cutting concerns, or correctness-critical paths. For small fixes, prefer `session-start` directly. + +The workflow has seven phases. Two have hard user gates (Refine and Execute). The build-and-verify half (Execute + Review) runs as a single deterministic `orchestrate_build` tool call. + +This skill is split across two execution surfaces, and the split is deliberate: + +- **Interactive, in the main session** — Phases 0–4, the Phase 3/5 gates, the Phase 6 concerns gate, and Phase 7. These need a human in the loop (refinement conversation, approvals, the pre-ship review of the last unit), so they stay in the main session where you can call the `question` tool and talk to the user. +- **Headless, in the `orchestrate_build` tool** — the Execute waves and the Review/blocker-auto-fix loop (implemented by the `agent-toolkit.session` plugin). This is a closed-loop machine — fan out by wave, escalate failures, review, re-dispatch blockers, re-review, cap the loop — with no human decision inside it. Expressing it as JS makes the control flow deterministic instead of something you have to police by hand. + +> **CRITICAL**: You MUST drive every phase to completion. Do NOT collapse the workflow into a single in-line plan, and do NOT hand-roll the build loop in the main session — Phase 5 dispatches the `orchestrate_build` tool and Phase 6 consumes its structured result. Sub-agent dispatch is the point — the user is paying for parallelism and model tiering, not for you to do everything serially in the main session. + +### Inputs + +- The invocation arguments — optional initial description. If absent and no context inherited from `session-start`, ask the user to describe the feature before starting Phase 1. +- Inherited context — if invoked after `session-start` or `session-issue`, the branch is already created and the issue/description is known. Do not re-ask for a description. +- Issue refs (`#N`) in the invocation arguments with no prior spine run in this session — there is no inherited context. Run `reference/spine.md` Phase 0 (fetch the issues, derive the description, record one closing line per issue) before Phase 1 instead of assuming it was done. + +### Phase 0 — Detect existing context + +Orchestrate persists its state under the git dir so a later session can resume. Define `STATE=$(git rev-parse --git-path session-orchestrate)`; the files are `$STATE/spec.md`, `$STATE/plan.md`, and `$STATE/chunks.json` (the full Phase 5 `args` once divided). Branch names and commit messages are **not** evidence of prior orchestrate work — only these files are. + +1. If `$STATE` does not exist or has none of the files, there is nothing to resume: skip the menu and proceed to Phase 0b with a fresh run. +2. Otherwise ask via the `question` tool, offering only the options the existing files can honour: + - **Resume from Plan** — needs `spec.md`; re-use the saved spec, regenerate the plan + - **Resume from Divide** — needs `plan.md`; plan is good, re-chunk and execute + - **Resume from Execute** — needs `chunks.json`; re-present the saved chunk plan at the Phase 5 gate + - **Start fresh** — delete `$STATE` and run all phases + + Load the saved files into context for the chosen phase. Resuming from Review is not supported: execution results are not persisted, so re-run Execute (orchestrate_build reviews what it executes). + +### Phase 0b — Isolate in a worktree (default for fresh runs) + +Orchestrate runs are heavy and long-lived — **isolate them in a git worktree by default** so the main checkout stays clean and parallel sessions can coexist. + +- **Already isolated** — if the session is already in a worktree, or a feature branch is already checked out (inherited from `session-start` or `session-issue`, or the current branch is not the default), proceed in the current checkout. Do **not** create another worktree. +- **Fresh run on the default branch** — create the work's branch as a worktree by default. Derive the name: `<type>-<slug>` from the issue (no number — that lives in the PR's `Closes #N`), or `wip-<slug>` from the description. **Before** creating, provision dependencies exactly as in `reference/spine.md` Phase 1 step 1 (detect heavy gitignored dirs via `git check-ignore`; write `worktree.symlinkDirectories` + `.worktreeinclude` to **project** config without asking). Then call `opencode.worktree_create` with `name: <dash-form-name>` (yields branch `worktree-<name>`, provisions deps, switches the session in), and run the spine's Phase 1 step 3 so symlinked dependency dirs do not show as untracked. Do not ask about worktree vs in-place; if the repo's `CLAUDE.md` says to work directly on the default branch, follow that instead. + +Then proceed to Phase 1. + +### Phase 1 — Spec exploration + +Goal: turn the user's description into a richer rough spec by dispatching cheap, parallel research agents. + +1. **Identify 2-4 distinct exploration angles** based on the description. Common angles: + - **Locate existing code** — files, functions, types, modules touched by the feature + - **Map adjacent systems** — what consumes/produces the data, the call graph, dependencies + - **Find relevant tests, configs, docs** — existing coverage, CI setup, conventions + - **Surface prior art** — similar features already in the codebase, patterns to follow + - **Identify constraints** — performance, security, compatibility, deprecated paths + +2. **Dispatch all angles in parallel** in a single message, using the `Agent` tool with: + - `agent: explore` (read-only) + - `model: haiku` by default + - **Bump to `model: sonnet`** for an angle if: codebase is unfamiliar, the angle requires synthesizing patterns rather than locating code, or the description hints at subtle cross-file relationships + - **`model: opus`**: rarely; only for deeply tangled architectures + - Each agent's prompt MUST include the full user description, the specific angle, and explicit "report findings concisely; do not make changes." + +3. **Collect findings** into a rough spec the parent session can hold: + - Code locations (file:line) + - Adjacent systems and call paths + - Existing tests/conventions + - Constraints and gotchas surfaced + + Write the rough spec to `$STATE/spec.md` (`mkdir -p "$STATE"` first). + + Do NOT present this rough spec to the user yet — Phase 2 will refine it into a plan first. + +### Phase 2 — Plan generation + +Goal: produce an initial implementation plan plus an explicit list of gaps and open questions. + +1. **Dispatch a single planning sub-agent** using the `Agent` tool with: + - `agent: Plan` (architect agent) + - `model: sonnet` by default + - **Bump to `model: opus`** if: cross-system design tradeoffs, significant ambiguity in the spec, novel pattern with no clear precedent in the codebase, correctness-critical (security, data integrity, concurrency, migrations) + - **Never use `haiku`** — planning needs reasoning headroom + +2. **The plan agent's prompt MUST include:** + - The full user description + - The rough spec from Phase 1 (all angles' findings, condensed) + - Explicit instructions: produce (a) implementation plan with file/line targets, (b) explicit list of gaps/unknowns, (c) open questions for the user, (d) suggested chunking with rough parallel/serial dependency hints + +3. **Receive and hold the plan.** Do not yet present to user — Phase 3 is the discussion gate. + +### Phase 3 — Refine [USER GATE] + +Goal: iterate with the user until the spec and plan are agreed. + +1. **Present** to the user, in the main session output: + - Concise summary of the rough spec (2-3 sentences) + - The implementation plan from Phase 2 + - Identified gaps and open questions, called out clearly + +2. **Loop with the user** in plain conversation: + - User adds constraints, answers questions, requests changes + - You refine the spec/plan in-session (no agent dispatch needed for small refinements; re-dispatch a planning agent only if the user requests substantial re-planning) + - When you make refinements, summarize what changed before continuing + +3. **Gate**: when the user signals approval (or after refinements you believe complete), use the `question` tool with options: + - **Approve, proceed to divide** — proceed to Phase 4 + - **More refinement needed** — return to step 2 of this phase + - **Stop here** — abort the workflow + + The plan must state its scope explicitly (a `Scope:` line listing the PR(s)/unit(s)); approval authorizes every unit before the last through merge; the last unit pauses for the user's go before it ships (Phase 7). + + On approval, write the agreed spec and plan to `$STATE/spec.md` and `$STATE/plan.md` (overwriting the Phase 1 draft). + + Do NOT proceed to Phase 4 without explicit approval via this gate. + +### Phase 4 — Divide + +Goal: break the approved plan into discrete chunks that can be dispatched to execution agents. + +1. **Detect test infrastructure** — before deciding whether tests are mandatory, run a quick check: + + ```bash + # Probes: test directories, test files, CI test step, manifest test scripts + ls test tests __tests__ 2>/dev/null + git ls-files | grep -E '_test\.(go|py|rs)$|\.test\.(ts|tsx|js|jsx)$' | head -5 + git ls-files .github/workflows/ 2>/dev/null | head -5 + git ls-files | grep -E '^(package\.json|Cargo\.toml|pyproject\.toml|go\.mod)$' | head -5 + ``` + + If any positive signal — test directories, conventional test files, CI workflows referencing tests, or a `test`/`check` script in package manifests — record `tests_required=true`. Otherwise `tests_required=false`. + +2. **Chunk the plan** into discrete tasks. For each chunk record: + - **ID** — a short stable identifier (`c1`, `c2`, …). orchestrate_build keys execution, review, and re-dispatch on it, so it must be unique and stable across the run. + - **Scope** — one-line description of the change + - **Files** — specific paths touched. Chunks **within the same wave must own disjoint files** — they run in parallel against one working tree, so overlapping files would clobber each other. If two chunks must touch the same file, put them in different waves with a dependency. + - **Dependencies** — list of other chunk IDs this one depends on (for serial ordering); carried as `dependsOn`. If a chunk fails, orchestrate_build skips every chunk that depends on it. Omitting `dependsOn` means "depends on all earlier waves". + - **Tests** — if `tests_required=true` AND the chunk is not purely cosmetic, add a paired test chunk OR include test work in the chunk's scope (set its `tests` flag, with optional `testScope` guidance). Skip if cosmetic-only or `tests_required=false`. + - **Suggested model tier** — Haiku / Sonnet / Opus, applying these heuristics: + - **Haiku** — mechanical change, well-established pattern in the codebase, single-file scope, clear acceptance criteria (rename, add import, simple test case, copy-pattern) + - **Sonnet (default)** — standard dev work: new feature following codebase conventions, moderate refactor, multi-file but bounded + - **Opus** — novel algorithm, complex state machine, critical correctness path (auth, crypto, payments, transactions, migrations, concurrency primitives), deep refactor touching many subsystems, or chunks requiring lots of context + - **Opus review** — set an `opusReview` flag on the chunk when it warrants the senior review pass in Phase 6: it was tagged Opus-tier above, its paths match correctness-critical patterns (auth, crypto, payments, transactions, migrations, concurrency primitives), the spec called out correctness/security, or it involves a novel algorithm or non-trivial state machine. Leave it off for trivial chunks. + +3. **Identify parallelization** — group chunks into waves. A wave is a set of chunks with no dependencies on each other (within the wave); they will be dispatched in parallel. Waves run serially, with each later wave allowed to depend on completed earlier waves. + +4. **Hold the chunk plan** for the Phase 5 gate. Do not present yet — present at the gate. Persist it now by writing the full Phase 5 `args` object (step 2 below) to `$STATE/chunks.json`; rewrite it if the user adjusts chunks at the gate. + +### Phase 5 — Execute [USER GATE → orchestrate_build] + +Goal: get the user's approval, then hand the approved chunk plan to the build-and-verify `orchestrate_build` tool. + +1. **Present the chunk plan** to the user. Use the `question` tool with options: + - **Approve and dispatch** — proceed to step 2 + - **Adjust chunks** — explain what to change; revise and re-present + - **Adjust model tiers** — let the user override per-chunk model picks + - **Cancel** — abort the workflow + + This gate is also the spend gate: approving here is what authorizes the `orchestrate_build` tool to spin up a background fleet. Do not dispatch without it — even if this skill was auto-invoked by the model rather than the user. + +2. **Construct orchestrate_build `args`** from the approved chunk plan. Build a JSON object: + + ```json + { + "description": "<the user's feature description>", + "plan": "<the agreed implementation plan, as markdown>", + "testsRequired": <true|false from Phase 4 step 1>, + "waves": [ + [ { "id": "c1", "scope": "...", "files": ["..."], "model": "sonnet", "tests": false, "opusReview": false } ], + [ { "id": "c2", "scope": "...", "files": ["..."], "model": "opus", "tests": true, "testScope": "...", "opusReview": true } ] + ] + } + ``` + + `waves` is dependency-ordered: each inner array is one wave, dispatched in parallel; waves run serially. Carry every field from the Phase 4 chunk record (`id`, `scope`, `files`, `model`, `tests`, optional `testScope`, `opusReview`, `dependsOn`). + +3. **Dispatch the orchestrate_build.** Call the `orchestrate_build` tool with: + - `args: <the object from step 2>` (the same args contract the Claude workflow script took; pass it as an actual JSON value) + + orchestrate_build runs headless: it executes the waves with per-chunk failure escalation (attempt 1 = chunk tier; attempt 2 = same tier + failure-refined prompt; attempt 3 = bumped tier), then reviews every executed chunk (one Sonnet reviewer each, plus one Opus reviewer over the `opusReview` subset), and **auto-fixes blockers** by re-dispatching affected chunks with the reviewer feedback and re-reviewing only those — capped at 2 review iterations. Concerns and nits are reported, never auto-fixed. It edits the session's working tree (the Phase 0b worktree, if one was created), so no per-agent isolation is needed. Progress arrives as each wave completes. + +4. **When orchestrate_build returns**, it gives you a structured result — proceed to Phase 6 to consume it: + + ```json + { + "iterations": 1, + "hitReviewCap": false, + "perChunk": [ { "chunkId": "c1", "ok": true, "attempts": 1, "model": "sonnet", "summary": "...", "testsPassed": true } ], + "filesChanged": ["..."], + "clean": ["c1"], + "unresolvedBlockers": [], + "concerns": [ { "chunkId": "c2", "severity": "concern", "title": "...", "detail": "...", "file": "..." } ], + "nits": [ { "chunkId": "c1", "severity": "nit", "title": "..." } ], + "skipped": [ { "chunkId": "c3", "reason": "dependency failed: c2" } ], + "unassigned": [] + } + ``` + + `skipped` lists chunks never run because a dependency failed; `unassigned` lists reviewer findings that named an unknown chunk id. + +### Phase 6 — Consume review findings + +Goal: act on the `orchestrate_build` tool's structured result. The blocker auto-fix loop already ran headlessly inside the orchestrate_build; this phase handles only the decisions that need a human. + +0. **Surface `skipped` chunks and any `unassigned` findings** to the user first — skipped chunks (and failed chunks with `ok: false` in `perChunk`) mean the feature is incomplete; let the user decide whether to fix and re-run a targeted orchestrate_build on them. + +1. **If `unresolvedBlockers` is non-empty** (`hitReviewCap` is true — the auto-fix loop hit its 2-iteration cap with blockers still standing): surface every remaining blocker to the user with full context (chunk, title, detail, file, and the chunk's `perChunk` summary). Do not silently retry beyond the cap. Let the user decide — fix manually, re-run a targeted orchestrate_build on those chunks, or accept and move on. + +2. **Else if `concerns` is non-empty**: present them via the `question` tool: + - **Address now** — treat the concerns as a fresh, small chunk plan (one wave, one chunk per concern fix, tiers as appropriate) and re-dispatch orchestrate_build with those chunks. Then re-enter Phase 6 on the new result. + - **Defer** — record the concerns for the Phase 7 summary and proceed. + +3. **Else (only `nits` or fully clean)**: note any nits for the Phase 7 summary and proceed to Phase 7. + +Carry `perChunk`, `filesChanged`, `clean`, deferred `concerns`, and `nits` forward — Phase 7's summary draws on them. + +### Phase 7 — Ship (pre-ship review of the last unit) + +Goal: summarize, land the earlier units, and have the user review the last unit before it ships. + +1. **Produce a final summary** for the user covering: + - One-line outcome of the feature + - Files changed (grouped by chunk) + - Current state — branch name, what's committed vs. still uncommitted, test/build status + - Test coverage added (if any) + - **Caveats** — be up front and specific about known *or potential* problems: deferred concerns from Phase 6, chunks surfaced for manual handling, assumptions made, uncovered edge cases, and any known risks or follow-ups. If you are unsure something works, say so. Do not downplay risks to make the result look finished. + +2. **Land earlier units without waiting.** The Phase 3/5 approvals authorize every unit before the last through merge; the last unit pauses for the user's review first (step 3). Print the summary as a short progress note, land every unit before the last via `/ship`, then run the last unit (a single-unit scope is just this) through `session-end` (docs, review + fix, issue sweep, ships it once via `/ship`) — do not ship it separately first. With linked issues, the PR body carries one closing line per issue (`Closes #N` / `Fixes #N`) — use the in-context list if there is one, otherwise read `git config branch.$(git branch --show-current).session-issues` (comma-separated closing lines, e.g. `Closes #12,Fixes #13`). If the scope spans several PRs/units, continue through each in turn without stopping between them. + +3. **The one deliberate stop:** `session-end` **stops before shipping the last unit** to summarize the work and caveats and wait for the user's go; after the go it ships, watches CI, fixes and re-merges if needed, and ends with a final-state summary (issue closing, cleanup / worktree teardown, final summary — `session-end` steps 5-8). Do not ship the last unit before they answer. + +If this run created a worktree (Phase 0b), `/ship` step 9 removes it after the PR merges (`session-end` runs it too), or the user can remove it later with `opencode.worktree_remove`. + +### Notes + +- **Always think about whether the workflow is the right tool.** If the user invoked this for a small, well-scoped change, gently suggest `session-start` instead before kicking off Phase 1. +- **Do not skip the user gates.** Phases 3 and 5 must use the `question` tool, and Phase 5's gate is the spend gate for the `orchestrate_build` tool. The Phase 6 concerns step also gates via the `question` tool. The blocker auto-fix loop inside the `orchestrate_build` tool is the only place work advances without an explicit gate. +- **The build loop lives in the `orchestrate_build` tool, not the main session.** Do not re-implement Execute or the review/blocker loop with inline `Agent` calls — construct the `args` and dispatch the `agent-toolkit.session` plugin. Self-contained prompts (full context per agent), parallel wave dispatch, failure escalation, and review dedupe are all handled inside the script. +- **Sub-agent prompts are self-contained.** This still applies to the phases that *do* dispatch inline — every Phase 1 research `Agent` and the Phase 2 planning `Agent` must carry enough context to succeed without seeing the parent conversation. +- **Parallel dispatch matters for the inline phases.** Within a Phase 1 angle set, issue all `Agent` calls in a single message so they run concurrently. (Phase 5/6 parallelism is the `orchestrate_build` tool's job.) +- **Keep `args` and the script in sync.** If you change the chunk-record shape in Phase 4, update both the Phase 5 `args` contract and the `args` documentation at the top of the `orchestrate_build` tool's schema. diff --git a/plugins-opencode/session/skills/session-orchestrate/scripts/git-wait b/plugins-opencode/session/skills/session-orchestrate/scripts/git-wait new file mode 100755 index 0000000..335f658 --- /dev/null +++ b/plugins-opencode/session/skills/session-orchestrate/scripts/git-wait @@ -0,0 +1,1460 @@ +#!/usr/bin/env bash +# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. +# +# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: +# listing, creating, commenting, merging, closing, viewing logs. This script +# exists only for the three things neither CLI gives you: +# +# 1. Platform detection — matching the git remote hostname against configured +# tea logins, so a caller knows whether to reach for `gh` or `tea`. +# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a +# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on +# the merge itself; `tea` has no equivalent at all). +# 3. `run watch` — block until CI finishes, aggregating per-job status and +# dumping failed job logs. `gh run watch` is GitHub-only and misses +# job-level failures masked by a run-level success; `tea` has no watcher. +# +# Usage: +# git-wait [-C DIR] <command> ... +# Operate on the git repo at DIR instead of the current directory (like +# `git -C`). Must come before the command. gh/tea resolve the repo from the +# working directory, so this retargets every call without a caller-side cd. +# +# git-wait platform +# Echo "github" or "gitea" for the current repo's origin remote. +# +# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] +# [--alert-interval 300] +# Block until the PR for BRANCH reaches a terminal state. +# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, +# url, duration, and (when relevant) reason. +# +# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] +# [--timeout 14400] [--idle-timeout 0] [--interval 15] +# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] +# [--max-poll-failures 10] +# Block until CI finishes. Output: "status: pass|fail|closed|timeout| +# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed +# job logs go to stderr. +# +# --branch follows ONE run: the newest correlated to that branch (via the +# PR's check rollup when a PR exists, else the newest run in the list). +# That is right for a PR branch, where one push means one run. It is NOT +# sufficient on a default branch, where two merges landing close together +# produce two runs and the newest passing says nothing about the older +# one still executing. +# +# --sha watches EVERY run for one commit and is the correct flag for a +# post-merge/release watch: it stays pending while any run for the commit +# is pending, and fails if any run — or any job inside one — failed. Pass +# one or the other, not both. +# +# A running CI is never aborted for lack of visible progress: `run watch +# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress +# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO +# check is pending (running CI, or auto-merge armed, resets it), so a PR that +# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long +# jobs (VM boot + integration suite + teardown) can go quiet for a long time. +# While still waiting, a heartbeat alert goes to STDERR every --alert-interval +# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) +# pending: ...)". stdout key:value output is unchanged. +# +# --no-run-timeout is how long to wait for the FIRST run to appear before +# reporting no-workflow, counted from the end of --initial-delay. Default 600s +# for --sha (post-merge workflows queue late, or start only after another +# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty +# check. A stderr alert is printed each poll while waiting. A FAILED run-list +# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not +# counted toward this deadline and polling continues, but after +# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the +# watch gives up with "status: error" and exit 4. A successful poll resets the +# count. +# +# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the +# commit is terminal and passing, keep polling SECS more before reporting pass, +# so a chained workflow_run workflow that appears late is still watched. A +# stderr line is printed while settling; a new run restarts the watch. +# +# Exit codes: 0 terminal state reached (check "status:" for pass/fail), +# 1 usage error, 2 timeout, 3 platform detection failure or no +# PR/workflow found, 4 command failed + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +die() { echo "git-wait: $*" >&2; exit 1; } +die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } + +# Run a CLI command and pipe its stdout through a jq filter. +# If the command fails, die with its stderr instead of feeding junk to jq. +# Usage: cli_json [jq-flags...] <jq-filter> <cmd> [args...] +# +# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. +# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, +# auth warnings, progress text) into the JSON, silently corrupting jq +# parsing and producing wrong results downstream (e.g. run watch seeing +# unexpected status values). +cli_json() { + local jq_flags=() + while [[ "$1" =~ ^-[a-zA-Z] ]]; do + # Collect jq flags (e.g. -r, -e) — stop at the filter string + case "$1" in + -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; + *) break ;; + esac + done + local filter="$1"; shift + local raw stderr_file rc=0 + stderr_file=$(mktemp) + raw=$("$@" 2>"$stderr_file") || rc=$? + if [[ $rc -ne 0 ]]; then + local err + err=$(cat "$stderr_file") + rm -f "$stderr_file" + die "$err" + fi + rm -f "$stderr_file" + echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" +} + +# --------------------------------------------------------------------------- +# Target repo (-C DIR) +# +# Handled before platform detection. The cd happens inside this script's own +# process, so the caller's working directory is never touched. +# --------------------------------------------------------------------------- + +if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then + [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" + target_dir="$2" + [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" + git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die_usage "$1: not a git repository: $target_dir" + # Resolve the script path first: a relative $0 breaks once we cd (help reads it). + SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + cd "$target_dir" + shift 2 +fi +SELF="${SELF:-$0}" + +# --------------------------------------------------------------------------- +# Platform detection +# --------------------------------------------------------------------------- + +detect_platform() { + local remote_url hostname login_url login_host + remote_url=$(git remote get-url origin 2>/dev/null) \ + || die "no git remote 'origin' found — run from a git repository" + + # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) + # or HTTPS (https://host/org/repo or https://host:port/org/repo) + if [[ "$remote_url" =~ ^ssh:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') + elif [[ "$remote_url" =~ ^git@ ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') + elif [[ "$remote_url" =~ ^https?:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') + else + die "unrecognised remote URL format: $remote_url" + fi + + # Check if this hostname matches any configured tea login + if command -v tea >/dev/null 2>&1; then + while IFS= read -r login_url; do + login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') + if [[ "$login_host" == "$hostname" ]]; then + echo "gitea" + return + fi + done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) + fi + + # Not a known tea login — fall back to gh (GitHub) + if [[ "$hostname" == "github.com" ]]; then + echo "github" + return + fi + + die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" +} + +PLATFORM=$(detect_platform) + +case "$PLATFORM" in + github) CLI=gh ;; + gitea) CLI=tea ;; +esac + +command -v "$CLI" >/dev/null 2>&1 \ + || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } + +# --------------------------------------------------------------------------- +# Internal reads +# +# These are NOT public subcommands — they are the normalized queries the two +# waiters below need. Every one of them dies on backend failure, so callers +# invoke them inside $( ) with a fallback: a probe failure must degrade the +# poll loop, never abort it. +# --------------------------------------------------------------------------- + +# List PRs as normalized JSON. Flags: --state, --limit, --assignee. +_pr_list() { + local limit assignee state args + limit=30; assignee=""; state="open" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; + --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") + # gh uses 'merged' as a state but tea uses 'closed' for merged PRs + [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") + [[ -n "$assignee" ]] && args+=(--assignee "$assignee") + cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ + env GH_NO_COLOR=1 gh pr list "${args[@]}" + ;; + gitea) + args=(--output json --limit "$limit" + --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") + [[ "$state" == "merged" ]] && state="closed" + args+=(--state "$state") + cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ + env NO_COLOR=1 tea pr list "${args[@]}" + ;; + esac +} + +# Show one PR as normalized JSON. Takes <N> or --branch NAME. +_pr_show() { + local num branch pr_json pr_stderr pr_rc pr_detail err + num=""; branch="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --*) die_usage "unknown flag: $1" ;; + *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; + esac + shift + done + [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass <N> or --branch NAME, not both" + if [[ -n "$branch" ]]; then + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + num=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + [[ -n "$num" ]] || die "no PR found for branch '$branch'" + fi + [[ -n "$num" ]] || die_usage "usage: git-wait pr show <N> | --branch NAME" + case "$PLATFORM" in + github) + cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ + env GH_NO_COLOR=1 gh pr view "$num" \ + --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" + ;; + gitea) + # `tea pr list` omits the `merged` boolean and `merged_at` timestamp + # entirely (tea only encodes merge state into the `state` string) and + # emits `mergeable` as a string, so a merged PR reports + # merged:false / mergedAt:null and consumers think it is still open + # (#140). Fetch the PR detail via the REST API instead, mirroring the + # run:show/run:list `tea api` pattern, so merge fields are reliable. + pr_stderr=$(mktemp); pr_rc=0 + pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ + || pr_rc=$? + if [[ $pr_rc -ne 0 ]]; then + err=$(cat "$pr_stderr"); rm -f "$pr_stderr" + die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" + fi + rm -f "$pr_stderr" + # Derive `state` from `merged` so it stays consistent with the merge + # flags (Gitea REST reports state:"closed" for a merged PR) and matches + # the GitHub path, which emits state:"merged". + echo "$pr_detail" | jq '{ + number: (.number // .index), + title: (.title // ""), + body: (.body // ""), + state: (if (.merged // false) then "merged" else (.state // "") end), + merged: (.merged // false), + merged_at: (.merged_at // null), + author: (.user.login // .user.username // ""), + head: (.head.ref // .head.label // ""), + base: (.base.ref // .base.label // ""), + labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), + assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), + mergeable: (.mergeable // null), + created_at: (.created_at // ""), + updated_at: (.updated_at // null), + url: (.html_url // .url // ""), + comments: [] + }' + ;; + esac +} + +# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. +_auto_merge_status() { + local branch number pr_json am + branch=""; number="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) shift; branch="$1" ;; + --number) shift; number="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + + # Resolve PR number from branch if needed + if [[ -z "$number" ]]; then + [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" + pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" + number=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + if [[ -z "$number" || "$number" == "null" ]]; then + echo "auto_merge: false" + echo "No open PR found for branch '$branch'" >&2 + exit 3 + fi + fi + + case "$PLATFORM" in + github) + am=$(cli_json -r '.autoMergeRequest != null' \ + env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) + echo "auto_merge: $am" + ;; + gitea) + echo "auto_merge: false" + echo "Gitea does not support auto-merge detection" >&2 + ;; + esac +} + +# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. +# +# --sha filters to runs for one commit. GitHub has a server-side filter for it +# (`gh run list --commit`); Gitea does not, so it is applied client-side over +# an unfiltered fetch, the same way --branch already is there. Both platforms +# emit head_sha in the normalized output — GitHub did not used to, which is +# why `run watch --sha` needs the headSha field added below. +_run_list() { + local limit status branch sha args query raw_stderr raw_rc raw err + limit=20; status=""; branch=""; sha="" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") + [[ -n "$status" ]] && args+=(--status "$status") + [[ -n "$branch" ]] && args+=(--branch "$branch") + [[ -n "$sha" ]] && args+=(--commit "$sha") + cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ + env GH_NO_COLOR=1 gh run list "${args[@]}" + ;; + gitea) + # Source from Gitea REST API directly. `tea actions runs list` + # filters server-side by a `branch` column that Gitea leaves empty + # on `pull_request` runs, so the watcher's --branch lookup misses + # correlated runs (#103). Fetch unfiltered via `tea api`, normalize + # `branch` from `head_branch`, and apply --branch client-side. + query="limit=$limit" + [[ -n "$status" ]] && query+="&status=$status" + raw_stderr=$(mktemp); raw_rc=0 + raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ + || raw_rc=$? + if [[ $raw_rc -ne 0 ]]; then + err=$(cat "$raw_stderr"); rm -f "$raw_stderr" + die "tea api repos/{owner}/{repo}/actions/runs failed: $err" + fi + rm -f "$raw_stderr" + echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' + [(.workflow_runs // []) | .[] | { + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + head_sha: (.head_sha // ""), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // "") + }] + | if $b == "" then . else [.[] | select(.branch == $b)] end + | if $s == "" then . else + [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] + end + ' + ;; + esac +} + +# Show one CI run as normalized JSON, including per-job status. +_run_show() { + local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err + [[ $# -ge 1 ]] || die_usage "usage: git-wait run show <run-id>" + run_id="$1" + case "$PLATFORM" in + github) + cli_json \ + 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ + env GH_NO_COLOR=1 gh run view "$run_id" \ + --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" + ;; + gitea) + # Fetch the run object via the REST API. `tea actions runs view` + # ignores `--output json` (tea 0.14.1) and prints a human key/value + # table while still exiting 0, so jq downstream chokes (#133). Use the + # same `tea api` pattern as run:list and the jobs lookup below. + view_stderr=$(mktemp); view_rc=0 + view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ + || view_rc=$? + if [[ $view_rc -ne 0 ]]; then + err=$(cat "$view_stderr"); rm -f "$view_stderr" + die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" + fi + rm -f "$view_stderr" + + # Fetch per-job data via the actions API so callers (run watch) can + # detect job-level failures masked by run-level status=success on + # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. + jobs_array='[]' + jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) + if [[ -n "$jobs_json" ]]; then + jobs_array=$(echo "$jobs_json" | jq -c ' + def to_status: + if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) + end; + [(.jobs // .) | (if type == "array" then .[]? else empty end) | + {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] + ' 2>/dev/null) || jobs_array='[]' + fi + + # Older Gitea versions may not expose the jobs API; fall back to + # scanning the run logs for "Job '<name>' failed" lines. + if [[ "$jobs_array" == '[]' ]]; then + failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ + | grep -oE "Job '[^']+' failed" \ + | sed -E "s/Job '(.+)' failed/\1/" \ + | sort -u || true) + if [[ -n "$failed_log" ]]; then + jobs_array=$(printf '%s\n' "$failed_log" \ + | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') + fi + fi + + # Normalize REST field names into the output contract, mirroring the + # run:list jq above (conclusion-first status, head_branch//branch, + # run_started_at//created, name//workflow_id). + echo "$view_json" | jq --argjson jobs "$jobs_array" '{ + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // ""), + jobs: $jobs + }' + ;; + esac +} + +# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; +# Gitea has no server-side filter and returns every job's log). +_run_logs() { + local run_id failed_only + [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs <run-id> [--failed-only]" + run_id="$1"; shift + failed_only=false + while [[ $# -gt 0 ]]; do + case "$1" in + --failed-only) failed_only=true ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + if [[ "$failed_only" == "true" ]]; then + GH_NO_COLOR=1 gh run view "$run_id" --log-failed + else + GH_NO_COLOR=1 gh run view "$run_id" --log + fi + ;; + gitea) + # tea actions runs logs outputs all job logs; no built-in failed-only filter + NO_COLOR=1 tea actions runs logs "$run_id" + ;; + esac +} + +# --------------------------------------------------------------------------- +# Run helpers +# --------------------------------------------------------------------------- + +# Return comma-separated names of any jobs in <run_id> whose status is +# "failure", or empty if none. Used by run watch to detect job-level failures +# even when the run-level status reports success — Gitea sets run.status to +# "success" on a multi-job workflow if at least one job ran successfully, +# masking failures in earlier jobs (see issue #87). Calls "run show" to +# normalize per-platform JSON, so it works for both gh and tea paths. +_run_failed_jobs() { + local run_id="$1" show_json + show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 + echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' +} + +# Progress-aware timeout decision shared by `pr wait` and `run watch`. +# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress +# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. +# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ +# minutes: this lets callers keep waiting while CI is actively progressing and +# give up only after a stretch of no progress, with a hard ceiling backstop. +_wait_timed_out() { + local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" + if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then + echo "ceiling"; return 0 + fi + if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then + echo "idle"; return 0 + fi + return 1 +} + +# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. +_fmt_dur() { + local s="$1" + if [[ "$s" -lt 60 ]]; then echo "${s}s" + elif [[ "$s" -lt 3600 ]]; then + if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi + else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi +} + +# Periodic stderr heartbeat while a wait is still running. Callers set +# alert_interval (0 disables) and next_alert (initialised to alert_interval), +# and call `_heartbeat "$elapsed" "<detail>"` once per poll. Emits at most one +# alert per poll, then re-arms for the next multiple of alert_interval, so a +# slow poll never produces a burst. stderr only: stdout stays parseable. +_heartbeat() { + local el="$1" detail="$2" + [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 + echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 + next_alert=$(( (el / alert_interval + 1) * alert_interval )) +} + +# Coarse CI status — pending|success|failure|none — for a PR/branch, used by +# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the +# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is +# guarded so a probe failure degrades to "none" and never aborts the wait loop. +_ci_status() { + local pr_number="$1" branch="$2" view_json run_status + case "$PLATFORM" in + github) + view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } + echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) else "pending" end + else (.state // "pending" | ascii_downcase) end + ] | + if length == 0 then "none" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" end' 2>/dev/null || echo "none" + ;; + gitea) + run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) echo "pending" ;; + failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; + ""|none|null) echo "none" ;; + *) echo "success" ;; + esac + ;; + *) echo "none" ;; + esac +} + +# --------------------------------------------------------------------------- +# Command routing +# --------------------------------------------------------------------------- + +cmd="${1:-}" +sub="${2:-}" +shift 2 || shift || true + +case "$cmd:$sub" in + + # Echo the detected platform so callers know which CLI to reach for. + # PLATFORM is already resolved above; detection failure exited long before + # we got here. + platform:) + echo "$PLATFORM" + ;; + + pr:wait) + # timeout is the hard ceiling; idle_timeout is the no-progress window. + branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" ]] || die_usage "pr wait requires --branch" + + # Find PR for this branch + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + # Match branch — handle Gitea owner:branch format with endswith + pr=$(echo "$pr_json" | jq --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') + + if [[ -z "$pr" || "$pr" == "null" ]]; then + echo "status: no-pr" + echo "duration: 0s" + echo "No PR found for branch '$branch'" >&2 + exit 3 + fi + + pr_number=$(echo "$pr" | jq -r '.number') + pr_url=$(echo "$pr" | jq -r '.url // ""') + elapsed=0 + idle=0; idle_mark=0 + last_signal="" + unknown_streak=0 + + # Poll loop + while true; do + show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" + pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') + pr_merged=$(echo "$show_json" | jq -r '.merged // false') + pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') + + # Progress signals: CI still running or auto-merge pending means the PR is + # actively advancing toward merge, so the idle clock must not count down. + checks=$(_ci_status "$pr_number" "$branch") + if [[ "$PLATFORM" == "github" ]]; then + auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" + [[ "$auto_merge" == "true" ]] || auto_merge="false" + else + auto_merge="false" + fi + signal="$pr_state|$pr_mergeable|$checks|$auto_merge" + if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then + idle=0 + fi + last_signal="$signal" + + echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 + [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true + + case "$pr_state" in + merged) + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + closed) + if [[ "$pr_merged" == "true" ]]; then + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + fi + echo "status: closed" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR was closed without merging" >&2 + exit 0 + ;; + open) + # Check for merge conflicts + if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then + echo "status: blocked" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR has merge conflicts" >&2 + exit 0 + fi + # Still open — keep polling + ;; + *) + unknown_streak=$(( unknown_streak + 1 )) + if [[ "$unknown_streak" -ge 3 ]]; then + echo "status: error" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 + exit 4 + fi + echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 + ;; + esac + + # Reset unknown streak on any recognized state + [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 + + # Check timeout — only give up after a stretch of no progress (idle) or + # the absolute ceiling, never while CI/auto-merge is still working. + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + run:watch) + # timeout is the hard ceiling; idle_timeout is the no-progress backstop. + # While CI is actively pending the idle clock is reset each poll, so a long + # (15+ min) suite runs to completion up to the ceiling rather than being cut + # off by a flat wall-clock timeout. + branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 + alert_interval=300; next_alert=300; no_run_timeout="" + settle=0; settle_given=0; no_run_skew=0 + max_poll_failures=10; poll_fails=0 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; + --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; + --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" + [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" + [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" + # How long to wait for the FIRST run to appear (counted from the end of + # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ + # workflow_run and can queue minutes late, so that scope gets longer. + if [[ -z "$no_run_timeout" ]]; then + if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi + fi + + # `gh run list --commit` matches only on a FULL 40-character SHA -- a short + # one returns zero rows with no error, which this watcher would report as + # "no-workflow" rather than as the caller's mistake. Expand a short SHA via + # git when the commit is local, and refuse it outright when it is not, + # rather than silently watching nothing. (Gitea matches client-side on the + # first 12 chars, so a full SHA is correct there too.) + if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" + if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha="$_full_sha" + else + die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" + fi + fi + + elapsed=0 + idle=0; idle_mark=0 + + # A failed run-list call (network, auth, rate limit) is NOT an empty list. + # Note it, keep polling, and exclude the time from the no-workflow deadline + # (accumulated in no_run_skew). The hard ceiling still applies. After + # --max-poll-failures consecutive failures it gives up (exit 4). + _poll_failed() { + local what="$1" before="$elapsed" + poll_fails=$(( poll_fails + 1 )) + echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 + if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then + echo "status: error" + echo "duration: ${elapsed}s" + echo "reason: run list failed ${poll_fails} consecutive times" + echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 + exit 4 + fi + elapsed=$(( SECONDS - _t0 )) + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 + exit 2 + fi + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + no_run_skew=$(( no_run_skew + elapsed - before )) + } + + # Enforce the hard --timeout ceiling on paths that otherwise `continue` + # (no runs yet, settling, no checks registered) so they cannot outlive it. + _ceiling_check() { + local what="$1" + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what}" >&2 + exit 2 + fi + } + + # ------------------------------------------------------------------ + # --sha: watch EVERY run for one commit, not just the newest. + # + # `--branch` deliberately follows a single run (the newest correlated + # one). That is right for a PR branch, where one push means one run, but + # wrong for a default branch: two merges landing close together produce + # two runs, and the newest going green says nothing about the older one + # still executing. Watching a post-merge release run by branch reported + # "pass" while a second run was mid-flight. + # + # A commit is the honest scope for that question — the caller wants the + # runs *their* merge caused, not whatever else is landing on the branch. + # So this path aggregates: it stays non-terminal while ANY run for the + # commit is non-terminal, and fails if ANY run (or any job within one) + # failed. + # + # The CRITICAL DESIGN RULE below applies here too: only explicitly + # non-terminal statuses keep polling; anything unrecognized counts as + # terminal so an unexpected status cannot loop until timeout. + # ------------------------------------------------------------------ + if [[ -n "$sha" ]]; then + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + echo "Watching all runs for commit ${sha:0:12}..." >&2 + + # Settle window: after every run is terminal and passing, keep polling + # --settle seconds for a chained (workflow_run) run before reporting pass. + settle_start=-1; settle_ids="" + + while true; do + if ! sha_json=$(_run_list --sha "$sha" --limit 50); then + _poll_failed "commit ${sha:0:12}" + continue + fi + poll_fails=0 + sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) + + if [[ "$sha_count" -eq 0 ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + # Non-terminal set is explicit; everything else is terminal. + pending=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested")] + | length') + + echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 + + if [[ "$pending" -gt 0 ]]; then + pending_names=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested") + | (.workflow // .id)] | join(", ")') + _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" + # Active CI is progress — reset the idle clock, same as --branch. + idle=0 + settle_start=-1 + else + # Every run terminal. Collect run-level and job-level failures + # across ALL of them before declaring pass (#87 applies per run). + all_failed="" + fail_url="" + while IFS=$'\t' read -r r_id r_status r_url; do + [[ -n "$r_id" ]] || continue + case "$r_status" in + failure|timed_out|cancelled|canceled|skipped) + all_failed+="${all_failed:+,}run-$r_id:$r_status" + [[ -n "$fail_url" ]] || fail_url="$r_url" + ;; + *) + r_failed=$(_run_failed_jobs "$r_id") + if [[ -n "$r_failed" ]]; then + all_failed+="${all_failed:+,}$r_failed" + [[ -n "$fail_url" ]] || fail_url="$r_url" + fi + ;; + esac + done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') + + if [[ -n "$all_failed" ]]; then + echo "status: fail" + [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $all_failed" + echo "--- Failed job logs (last 80 lines) ---" >&2 + echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do + _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true + done + exit 0 + fi + + if [[ "$settle" -gt 0 ]]; then + cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') + if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then + echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 + settle_start=-1 + fi + if [[ "$settle_start" -lt 0 ]]; then + settle_start=$elapsed; settle_ids="$cur_ids" + fi + if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then + echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + fi + + echo "status: pass" + first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') + [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" + echo "duration: ${elapsed}s" + echo "runs: $sha_count" >&2 + exit 0 + fi + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so + # `run list --branch` correlates nothing and the watcher times out into + # no-workflow even when CI ran (#140). Resolve the branch head SHA up front + # (only on Gitea) and fall back to head_sha correlation when the + # branch-filtered lookup is empty. The run object's head_sha equals the + # branch head on Gitea (confirmed in #140); if a variant ever records a + # merge-ref SHA the fallback simply misses and degrades to today's + # behaviour rather than returning a wrong run. + _watch_branch_sha="" + if [[ "$PLATFORM" == "gitea" ]]; then + _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ + || git rev-parse "origin/$branch" 2>/dev/null || true) + fi + + # Echo a run-list JSON array for $branch: branch-name correlation first, + # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the + # server-side --branch filter populates the first call and _watch_branch_sha + # stays empty, so the SHA path is never taken. + _runs_for_branch() { + local lim="${1:-1}" out + # A failed call returns 1 (distinct from a successful empty "[]"). + out=$(_run_list --branch "$branch" --limit "$lim") || return 1 + if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then + echo "$out"; return 0 + fi + if [[ -n "$_watch_branch_sha" ]]; then + _run_list --limit 50 | jq \ + --arg s "$_watch_branch_sha" --argjson n "$lim" \ + '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ + || return 1 + return 0 + fi + echo "[]" + } + + # On GitHub, prefer PR-based status checking — one API call gives us both + # merge state and all CI check results via statusCheckRollup, avoiding the + # flaky run-level polling that produces "unknown" statuses. + pr_number="" + pr_url="" + use_pr=false + if [[ "$PLATFORM" == "github" ]]; then + pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { + pr_number=$(echo "$pr_json" | jq -r '.number // empty') + pr_url=$(echo "$pr_json" | jq -r '.url // ""') + [[ -n "$pr_number" ]] && use_pr=true + } + fi + + # Pre-check: look for an already-terminal state before sleeping the + # initial delay. If the PR already merged or CI already finished, + # report immediately instead of waiting. + _precheck_done=false + if [[ "$use_pr" == "true" ]]; then + _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" + _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') + + if [[ "$_pre_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already merged" >&2 + exit 0 + fi + if [[ "$_pre_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already closed without merging" >&2 + exit 0 + fi + + _pre_checks=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + if [[ "$_pre_checks" == "success" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "CI already passed on PR #$pr_number" >&2 + exit 0 + fi + + if [[ "$_pre_checks" == "failure" ]]; then + _pre_failed=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "failed_jobs: $_pre_failed" + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + fi + else + # Fallback path: check if a completed run already exists + _pre_list=$(_runs_for_branch 1) || _pre_list="[]" + _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') + if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then + _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') + _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') + _pre_id=$(echo "$_pre_latest" | jq -r '.id') + case "$_pre_status" in + success|completed) + # Run-level status can read "success" on Gitea even when a + # job inside the run failed (issue #87). Aggregate per-job + # status before declaring pass. + failed_jobs=$(_run_failed_jobs "$_pre_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "CI already passed for branch '$branch'" >&2 + exit 0 + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$_pre_id") + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$_pre_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a + # reason so consumers (ship/session-end) gating on + # status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "reason: $_pre_status" + echo "CI run $_pre_status for branch '$branch'" >&2 + exit 0 + ;; + esac + fi + fi + + # Initial delay — CI run may not exist immediately after push + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + if [[ "$use_pr" == "true" ]]; then + echo "Watching PR #$pr_number for branch '$branch'..." >&2 + + while true; do + # A failed gh call is not "unknown" -- count it, cap consecutive failures. + if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then + _poll_failed "PR #$pr_number" + continue + fi + poll_fails=0 + pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') + + # PR merged — all done + if [[ "$pr_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number merged" >&2 + exit 0 + fi + + # PR closed without merge + if [[ "$pr_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number closed without merging" >&2 + exit 0 + fi + + # Summarize CI check statuses from statusCheckRollup + # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state + checks_summary=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 + + case "$checks_summary" in + success) + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + failure) + failed_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_names" + # Try to fetch failed logs from the latest run + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + pending) + # Still running — keep polling. Active CI is progress, so reset idle. + check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') + if [[ "$check_count" -eq 0 ]]; then + # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + else + # Active CI is progress, so reset idle. + idle=0 + fi + pending_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select(if .__typename == "CheckRun" then (.conclusion // "") == "" + else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) + | .name // .context // "unknown"] | unique | join(", ")') + _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" + ;; + esac + + # Check timeout — idle window or absolute ceiling (see _wait_timed_out). + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Fallback: no PR found — poll run list directly (skip flaky run show). + # + # CRITICAL DESIGN RULE — default-terminal polling: + # + # This loop has caused repeated regressions (#53, #57, #58, #60). + # The recurring bug pattern is: + # 1. The API returns an unexpected status value (e.g. "completed" + # with null conclusion, or a new status GitHub adds later). + # 2. The case statement doesn't recognise it. + # 3. A catch-all `*) keep polling` silently loops until timeout. + # + # The fix (applied here) inverts the logic: + # - ONLY explicitly non-terminal states keep polling. + # - The `*` catch-all EXITS (as pass). + # + # DO NOT add a `*) keep polling` catch-all to this case statement. + # If a new non-terminal status appears, add it to the explicit list. + # If you're unsure whether a status is terminal, it's safer to exit + # early (the caller can retry) than to loop for 5 minutes. + # + run_url="" + while true; do + if ! list_json=$(_runs_for_branch 1); then + _poll_failed "branch '$branch'" + continue + fi + poll_fails=0 + latest=$(echo "$list_json" | jq -r '.[0] // empty') + + if [[ -z "$latest" || "$latest" == "null" ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + # Distinguish "no workflow registered at all" from "runs exist + # but none correlate to this branch" so callers (#103) can tell + # a real CI absence from a branch-correlation gap. + any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" + if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then + echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + else + echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + fi + exit 3 + fi + echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "branch '$branch'" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + run_id=$(echo "$latest" | jq -r '.id') + run_status=$(echo "$latest" | jq -r '.status // "unknown"') + run_url=$(echo "$latest" | jq -r '.url // ""') + + echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 + + # See "CRITICAL DESIGN RULE" above — non-terminal states are listed + # explicitly; everything else exits. Do NOT add a `*) keep polling`. + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) + # Non-terminal — keep polling. Active CI is progress, so reset idle. + idle=0 + _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$run_id") + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a reason + # so consumers gating on status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $run_status" + echo "CI run $run_status on branch '$branch'" >&2 + exit 0 + ;; + *) + # Terminal — covers success and any future/unexpected status. + # Even when the run-level status reports success, an individual + # job may have failed (Gitea reports run.status=success on a + # multi-job run if any job succeeded; see #87). Aggregate + # per-job status before declaring pass. + failed_jobs=$(_run_failed_jobs "$run_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + esac + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + --help:|-h:|:) + sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' + exit 0 + ;; + + *) + die_usage "unknown command: $cmd${sub:+ $sub}" + ;; +esac diff --git a/plugins-opencode/session/skills/session-orchestrate/scripts/sitrep b/plugins-opencode/session/skills/session-orchestrate/scripts/sitrep new file mode 100755 index 0000000..558f9e3 --- /dev/null +++ b/plugins-opencode/session/skills/session-orchestrate/scripts/sitrep @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# sitrep - Situation report for a git repository +# Always shows working-tree state (staged/unstaged/untracked) together with +# committed context, and falls back to broader repo activity only when +# nothing else is actionable. +# +# Sections: +# 1. Working tree (staged/unstaged/untracked) +# 2. Unpushed commits (ahead of remote tracking branch) +# 3. Branch work (commits on feature branch vs base) +# 4. Repo activity (active branches, open issues) - only when 1-3 are empty +# +# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). +# +# Exit codes: 0 success (including -h/--help), 1 bad usage + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" + +usage() { + cat <<'EOF' +Usage: sitrep [directory] + +Situation report for a git repository. Shows working-tree changes plus +unpushed and branch commits, expanding to broader repo activity only +when everything is clean. + +If directory is omitted, uses the current working directory. +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +if [[ $# -gt 1 ]]; then + usage >&2 + exit 1 +fi + +dir="${1:-.}" +cd "$dir" + +gitq() { + git -c core.quotepath=false "$@" +} + +# Print a diff section, truncated to MAX_DIFF_LINES. +emit_diff() { + local title="$1" text="$2" total + [[ -n "$text" ]] || return 0 + total="$(printf '%s\n' "$text" | wc -l)" + echo "" + echo "=== $title ===" + if ((total > MAX_DIFF_LINES)); then + printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" + echo "[truncated $((total - MAX_DIFF_LINES)) lines]" + else + printf '%s\n' "$text" + fi +} + +# --- Not a git repo --- +if ! gitq rev-parse --git-dir >/dev/null 2>&1; then + echo "=== REPO ===" + echo "is_git_repo: false" + exit 0 +fi + +# --- Basic repo info (always shown) --- +head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" +head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" + +echo "=== REPO ===" +if [[ -n "$head_branch" ]]; then + echo "branch: $head_branch" +else + echo "detached_at: $head_sha" +fi + +# Detect base branch: origin/HEAD, then origin/main|master, then local main|master +base_ref="" +origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" +for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do + [[ -n "$candidate" ]] || continue + if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then + base_ref="$candidate" + break + fi +done + +on_base=false +if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then + on_base=true +fi + +has_merge_base=false +if [[ -n "$base_ref" ]]; then + echo "base: $base_ref" + if ! $on_base; then + if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then + has_merge_base=true + else + echo "note: no merge base between $base_ref and HEAD (unrelated histories)" + fi + ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" + behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" + echo "ahead: $ahead" + echo "behind: $behind" + fi +fi + +found_activity=false + +# --- Working tree: staged / unstaged / untracked --- +staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" +unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" +untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" + +if [[ -n "$staged_files" ]]; then + found_activity=true + echo "" + echo "=== STAGED ===" + echo "$staged_files" + emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$unstaged_files" ]]; then + found_activity=true + echo "" + echo "=== UNSTAGED ===" + echo "$unstaged_files" + emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$untracked_files" ]]; then + found_activity=true + echo "" + echo "=== UNTRACKED ===" + echo "$untracked_files" +fi + +# --- Unpushed commits --- +tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" +unpushed="" + +if [[ -n "$tracking_branch" ]]; then + unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" +fi + +if [[ -n "$unpushed" ]]; then + found_activity=true + echo "" + echo "=== UNPUSHED ===" + echo "tracking: $tracking_branch" + echo "$unpushed" +fi + +# --- Branch work (feature branch vs base) --- +if ! $on_base && [[ -n "$base_ref" ]]; then + branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" + if [[ -n "$branch_commits" ]]; then + found_activity=true + echo "" + echo "=== BRANCH COMMITS ===" + echo "$branch_commits" + fi + + if $has_merge_base; then + committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + if [[ -n "$committed_files" ]]; then + found_activity=true + echo "" + echo "=== CHANGED FILES ===" + echo "$committed_files" + emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + fi + fi +fi + +if $found_activity; then + exit 0 +fi + +# --- Repo activity (everything clean, nothing ahead) --- +active_branches="" +if [[ -n "$base_ref" ]]; then + active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" +fi + +if [[ -n "$active_branches" ]]; then + echo "" + echo "=== ACTIVE BRANCHES ===" + echo "$active_branches" +fi + +# Open issues (requires git-wait for platform detection, plus gh or tea) +if [[ -x "$SCRIPT_DIR/git-wait" ]]; then + platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" + issues="" + issues_err="" + errfile="$(mktemp)" + case "$platform" in + github) + if command -v gh >/dev/null 2>&1; then + issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" + fi + ;; + gitea) + if command -v tea >/dev/null 2>&1; then + issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" + fi + ;; + esac + if [[ -n "$issues_err" ]]; then + detail="$(head -n 1 "$errfile" 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + echo "note: $issues_err${detail:+: $detail}" + elif [[ -n "$issues" && "$issues" != "[]" ]]; then + formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + if [[ -n "$formatted" ]]; then + echo "$formatted" + else + echo "note: could not parse issue list" + fi + fi + rm -f "$errfile" +fi + +# Recent commits on default branch for context +echo "" +echo "=== RECENT COMMITS ===" +gitq log --oneline -10 2>/dev/null || true + +# Nothing at all +if [[ -z "$active_branches" ]]; then + echo "" + echo "=== STATUS ===" + echo "clean: true" +fi diff --git a/plugins-opencode/session/skills/session-start/SKILL.md b/plugins-opencode/session/skills/session-start/SKILL.md new file mode 100644 index 0000000..bb7637c --- /dev/null +++ b/plugins-opencode/session/skills/session-start/SKILL.md @@ -0,0 +1,88 @@ +--- +name: session-start +description: "Use to begin a new unit of work (feature, fix, refactor) in a repo: loads the full start checklist — link related issues, branch, explore, plan. Not for questions or trivial one-off edits." +--- + +Start work from whatever you describe. This is the **input-driven** door: you say +what to do, it grounds in the current repo state, checks for open issues related +to the work, then runs the shared begin-work +spine (resolve target → isolate → explore → plan). To browse and pick from open +issues instead, use `session-issue`; for a read-only status view, use +`session-summarize`. + +> **CRITICAL**: You MUST drive this to a plan. NEVER print "suggested first steps" +> or ask "ready to start?" — the flow does not end until you have explored the code +> and called the `plan` agent. Plan approval then authorizes the whole stated scope +> for every unit before the last through merge: land each via `/ship` +> without stopping, then run the last unit through `session-end` (spine +> Phase 4). The one stop is before that final ship: summarize the work and caveats +> and wait for the user's go. Only then ship, watch CI, fix, re-merge, close out, and +> give a final summary. + +### Phase 0 — Take the input and ground it + +1. The work comes from the arguments provided with the invocation (the `/session-start` + command passes them through; your description). If this skill was invoked by + the model rather than the command, no arguments were provided: use the work the user + already described in the conversation as the description and do not re-ask. If + there are no arguments and nothing was described, ask + the user what they want to work on (a single open-ended prompt) — do **not** + enumerate a work board; `session-issue` is the issue picker and + `session-summarize` is the status view. + +2. Ground yourself in the current state: + + ```bash + git status --short -b + ``` + + - **Already on a non-default branch** (with commits ahead or uncommitted work) → + `continuing` is **true**. Reuse this branch; the spine skips Isolate and names + the session from the current branch. + - **Otherwise** (default branch, or a fresh branch with no work) → `continuing` + is **false**; the spine creates the branch. + + Pass `continuing` to the spine. + +3. Identify the target for the spine: + - **Description references issues** (`#42`, "issue 42", several allowed) → hand + the issue number(s) to the spine. + - **Freeform** → run the related-issue lookup below, then hand the spine either + the issues the user linked or, if none, the description (it builds `wip-<slug>`). + +4. **Related-issue lookup** (freeform only — skip when step 3 found `#N` references). + Open issues may already describe this work; find them so the PR can close them. + + a. Detect the platform once (the spine reuses it — do not detect again): + + ```bash + bash scripts/git-wait platform + ``` + + If detection fails (no remote or no CLI), skip the lookup silently and + continue as freeform. + + b. Launch one `Agent` (`agent: general-purpose`, `model: haiku`) with the + description and the platform. Tell it to fetch open issues — + **github:** `gh issue list --state open --limit 100 --json number,title,body,labels`; + **gitea:** `tea issues list --state open --limit 100 --output json --fields index,title,body,labels` — + and return up to 5 issues that are **clearly related** to the description + (favor precision; omit weak matches), each as `#N — Title [labels]` plus a + one-line reason, or just `NONE`. + + c. **`NONE`** → continue as freeform without comment. **One or more** → + the `question` tool with `multiSelect: true` (max 4 options, label + `#N — Title`, description = labels + reason). Selected issues become the + spine's issue target; none selected → freeform. + +### Phase 1 — Run the spine + +5. **Read the shared begin-work spine and execute it** (use the Read tool): + + ```text + reference/spine.md + ``` + + It owns issue fetching, branch naming, isolation, issue-linkage recording, session + rename, exploration (including the trivial fast path), planning, and the Phase 4 build loop (earlier units shipped, the last handed to `session-end`). Complete every + MANDATORY phase — the flow ends only once you have presented a plan. diff --git a/plugins-opencode/session/skills/session-start/reference/spine.md b/plugins-opencode/session/skills/session-start/reference/spine.md new file mode 100644 index 0000000..efc0289 --- /dev/null +++ b/plugins-opencode/session/skills/session-start/reference/spine.md @@ -0,0 +1,316 @@ +# Begin-work spine + +The shared playbook for the lightweight session entrypoints (`session-start` and +`session-issue`). Both doors differ only in **how the work is chosen** — once the +work is identified, they run these phases identically: resolve target → isolate → +explore → plan → build the approved scope. + +**Lightweight is the only flow here.** Do not ask "lightweight vs orchestrate", and +do not ask about worktree vs in-place, dependency symlinks, latency, or scope — +decide silently using the defaults below. Ask only when something is genuinely +ambiguous about **what to build** (the exceptions are the explicit prompts in Phase 0 +validation and Phase 1 collisions / dirty default branch). If the user asks for a +heavier multi-agent flow, mention once that `session-orchestrate` exists and +invoke it; never raise it unprompted. + +> **CRITICAL**: You MUST drive this through to a plan. After the branch exists you +> explore and enter plan mode. NEVER print "suggested first steps" or ask "ready to +> start?" — the flow does not end until you have switched to the `plan` agent with a plan +> built from real code exploration. +> +> **EQUALLY CRITICAL — the other end of the flow**: plan approval authorizes the +> whole stated scope, but the last unit is reviewed by the user before it ships. +> Implement each unit; land every unit before the last via `/ship` and move +> on without stopping, then run the last unit through `session-end` +> (Phase 4). The one deliberate stop is **before** that final ship: `session-end` +> summarizes the work and caveats and waits for the user's go. After the go it ships, +> watches CI, fixes and re-merges if needed, cleans up, and ends with a final-state +> summary. A one-PR session always pauses before its PR; a multi-PR scope pauses once, +> before the last PR. + +## Inputs (supplied by the calling door) + +- One of: **issue number(s)** (from `session-issue`, or `#N` references in a + `session-start` description or its related-issue lookup) or a **freeform + description**. +- Whether the door already knows the hosting `platform` (reuse it; never detect + twice). +- `continuing` (both doors determine it): **true** when the current branch is not the + default branch and has commits ahead of it or uncommitted work; otherwise false. + When true, skip Phase 1's Isolate steps and keep the current branch. + +If you reach this spine with neither issues nor a description, stop and return to +the calling door — it owns target selection. + +## Phase 0 — Resolve target + +Run this once, for both doors. + +1. **Fetch and validate issues** (skip for freeform work). Detect the platform once + unless the door already did, then fetch **every** referenced issue: + + ```bash + bash scripts/git-wait platform + ``` + + - **github:** `gh issue view <N> --json number,title,body,state,labels,comments` + - **gitea:** `tea issues <N> --output json` + + For anything beyond issue viewing (PR create, CI runs, state values), use the + command map in the `git-tools:git-wait` skill rather than guessing flags. + Keep each issue's title, body, and labels as context for the whole session. + + **Validate each issue.** If the fetch fails, the state is not open, or the number + is a pull request (not an issue), tell the user and either drop that number or + stop — ask which when it is not obvious. Also warn (and ask whether to proceed) + when an issue is already claimed: it appears in + `git config --get-regexp 'branch\..*\.session-issues'` or has an open PR. + +2. **Pick the branch type** from labels. Compare case-insensitively on the label's + **last path segment** (`kind/bug` and `Kind/Enhancement` match `bug` and + `enhancement`). With several issues, a `bug` label on any of them wins; otherwise + use the first issue's labels: + - `bug`, `fix` → `bug` + - `enhancement`, `feature`, `improvement` → `enhancement` + - `docs`, `chore`, `refactor`, `maintenance` → `chore` + - no matching label → `feature` + +3. **Name the work.** + - **Continuing** (`continuing` is true): do **not** build a new base name or + branch type. The session name is the current branch name with any leading + `worktree-` stripped. + - **Otherwise** build the base name: issue-linked `<type>-<slug>`; freeform + `wip-<slug>`. The slug is a kebab-case 3-5 word summary (of the first issue's + title, or the common theme when several issues are bundled; of the description + for freeform). The branch never encodes issue numbers — linkage is the closing + lines in the PR body. + + Actual branch names: created in place, the branch is `<base-name>`; created via + `opencode.worktree_create` (Phase 1), it is `worktree-<base-name>`. The session name is + `<base-name>`. + +4. **Closing lines.** One line per issue: `Fixes #N` for `bug` issues, `Closes #N` + otherwise. Phase 1 persists them. + +## Phase 1 — Isolate, record, rename + +**Skip the Isolate steps** (everything through "In place on a new branch") when +`continuing` is true, or when already inside a linked worktree. Detect the latter +with: + +```bash +git_dir=$(realpath "$(git rev-parse --path-format=absolute --git-dir)") +git_common_dir=$(realpath "$(git rev-parse --path-format=absolute --git-common-dir)") +[ "$git_dir" != "$git_common_dir" ] && echo "linked worktree" +``` + +(`realpath` avoids false differences from symlinked paths; same test as +`/ship` step 0.) Then go straight to "Record issue linkage" and "Rename the +session" below on the current checkout. + +Decide silently: + +- **Repo's `CLAUDE.md` says to work directly on the default branch / master** (as + `homelab-admin` does): do not create a branch or worktree; work on the default + branch in place and skip the rest of Isolate. There is no branch to record + linkage on; skip that step. +- **Otherwise: worktree by default.** It keeps the main checkout clean and lets + parallel sessions coexist. + +**Before creating anything:** + +- **Dirty default branch.** If on the default branch with uncommitted changes, warn + once that those edits stay in the main checkout (they are not carried into the + worktree) and ask whether to proceed with the worktree or work in place. This is a + genuine ambiguity, so ask. +- **Name collisions.** Check for `<base-name>` and `worktree-<base-name>`: + + ```bash + git worktree list + git branch --list "<base-name>" "worktree-<base-name>" + ``` + + If either exists, offer to **resume** it (enter the existing worktree via + `opencode.session_move` with that `directory`, or `git switch` to the branch) or to use a short + numeric suffix (`<base-name>-2`). Decide silently only when unambiguous (e.g. it + is clearly stale or clearly this same work); ask when it could be someone's other + work. If you resume, treat the run as `continuing`. + +**Worktree:** + +1. **Provision dependencies first.** A fresh worktree is a clean checkout — gitignored + deps don't carry over, and native provisioning only runs at creation time, so + configure it **before** creating the worktree. Symlink **dependency directories + only** — never build output (`target`, `build`, `dist`, `.next`, `.gradle`, + `.tox`), which is stale or wrong in another checkout. Detect those present: + + ```bash + for d in node_modules .venv venv vendor; do + [ -e "$d" ] && git check-ignore -q "$d" && echo "$d" + done + ``` + + Add the detected names **without asking** to `worktree.symlinkDirectories` in the + project's **`.claude/settings.local.json`** (`Local` scope — per-checkout, + normally gitignored; never the tracked `.claude/settings.json`, never global). + Merge with `jq`, unioning with any existing list and preserving all other keys; + create the file if absent. With the detected names in `$dirs` as a JSON array + (e.g. `'["node_modules",".venv"]'`): + + ```bash + f=.claude/settings.local.json + mkdir -p .claude + [ -s "$f" ] || echo '{}' > "$f" + jq --argjson d "$dirs" \ + '.worktree.symlinkDirectories = ((.worktree.symlinkDirectories // []) + $d | unique)' \ + "$f" > "$f.tmp" && mv "$f.tmp" "$f" + git check-ignore -q "$f" \ + || echo "/$f" >> "$(git rev-parse --path-format=absolute --git-path info/exclude)" + ``` + + Skip this step if no dependency directory was detected. Add `.env` / `.env.*` to a + root `.worktreeinclude` only if they exist. That file has no documented + alternative location, so keep it out of `git status` instead: if it is untracked, + add `/.worktreeinclude` to the same `info/exclude`. If the repo already tracks a + `.worktreeinclude`, append to it only when a needed pattern is missing and + mention the resulting diff in the Phase 4 report, since that one is a real change. + +2. **Create + enter the worktree:** call `opencode.worktree_create` with `name` set to the base + name (already dash form, no `/`). This creates the worktree (with its own branch) and returns its + directory; then move this session into it with `opencode.session_move` + (Code Mode). Do **not** also run `branch create`. + + This assumes `worktree.symlinkDirectories` is read at `worktree_create` time. As a + fallback, for each detected dependency directory missing in the new worktree, + create it yourself: `ln -s "<main-checkout>/<dir>" "<dir>"`. + +3. **Keep the tree clean for `ship`.** A directory pattern with a trailing slash + (e.g. `node_modules/`) does not match a *symlink*, so a symlinked dependency + directory can show up as untracked and trip `/ship`'s worktree + cleanliness gate. Inside the new worktree, exclude **only the dependency-directory + names detected in step 1** (not every untracked symlink): + + ```bash + exclude=$(git rev-parse --path-format=absolute --git-path info/exclude) + for d in $detected; do # names from step 1, e.g. node_modules .venv + [ -L "$d" ] && { grep -qxF "/$d" "$exclude" 2>/dev/null || printf '/%s\n' "$d" >> "$exclude"; } + done + git status --porcelain # expect no symlinked dependency dirs listed + ``` + + `info/exclude` is shared by every worktree of the repo, so these entries apply + everywhere; that is acceptable because root-relative dependency dirs are + normally ignored anyway. The `grep -qxF` guard prevents duplicates. + +**In place on a new branch** (only when the work genuinely cannot use a worktree): + +```bash +bash scripts/branch create <base-name> +``` + +**Record issue linkage** (always, once the branch exists — including when +`continuing`; skip when there are no linked issues or no branch). Store the closing +lines from Phase 0 step 4 as one comma-separated value, one entry per issue: + +```bash +git config "branch.$(git branch --show-current).session-issues" "Closes #12,Fixes #13" +``` + +The Phase 4 report, `session-end`, and `session-orchestrate` read this +key. When `continuing`, union with any existing value rather than overwriting. + +**Rename the session** (always, last). Use the session name from Phase 0 step 3: + +```ts +// Code Mode — no script, no ~/.claude writes +await tools.opencode.session_rename({ title: "<session-name>" }) +``` + +A rename failure is non-fatal: warn and continue. When working on the default +branch in place with no meaningful name, skip the rename (warn only). + +## Phase 2 — Explore the codebase + +> You MUST complete this phase. Do NOT stop after Phase 1. Do NOT print +> "suggested first steps". + +**Trivial fast path.** When the change is small and obvious — a typo, a one-line or +single-file fix, a config tweak, an issue that names the exact file and change — +skip the research subagents: read the few relevant files yourself and go straight to +Phase 3 with a short plan inside the `plan` agent. + +Otherwise launch **2-3 research agents in parallel** in a single message, using +`subagent` tool with `agent: explore`. Every agent prompt MUST include the full +context — the issue title/body/labels for **all** linked issues and/or the freeform +description — so the agent can work without seeing this conversation. Pick 2-3 +angles that fit: + +- **Locate the code** — files, functions, types, or modules implied by the work. + Report what each does, the change point, and surrounding signatures. +- **Find tests and related config** — existing coverage of the area, related config, + CI, docs. Report what exists, what is missing, how the suite is structured. +- **Trace the data/call flow** — entry points, intermediate steps, dependencies, and + edge cases. + +If an agent needs the issue tracker or repo API, tell it to use `gh` or `tea` +directly, per the `git-tools:git-wait` skill's command map. + +## Phase 3 — Plan + +> You MUST complete this phase. Do NOT stop after Phase 2. + +Switch the session to the built-in `plan` agent, then present a concrete plan for approval before any +implementation begins. Cover **all** linked issues in one plan. + +- **Changes** — the specific files and line ranges, and what each change does. + Describe the actual code change, not "fix the bug". +- **Testing** — include only when behavior changes: what tests to add or update, + using the project's existing framework. Omit for purely cosmetic changes + (comments, docs, formatting). +- **Risks & open questions** — edge cases and unknowns; omit when there are none. +- **Scope line, always last:** `Scope: <the PR(s)/unit(s) this plan covers>`. The + user defines the scope; approving the plan authorizes every unit listed through + merge. A single unit is a one-item scope. + +For trivial work keep the whole plan short — a few lines, not a document. Do **not** +otherwise describe the commit / push / PR / merge steps in the plan; Phase 4 defines +them. + +## Phase 4 — Report, continue the scope, pause before the final ship + +> Plan approval authorizes every unit before the last through merge: do **not** stop +> between those units or ask before their commit / push / PR / merge. The last (or +> only) unit is different: do not commit, push, or open its PR until the user has +> reviewed `session-end`'s summary and given the go. That is the only deliberate +> stop. + +After each unit is implemented: + +1. Print a **short progress note** (not a wait): one-line outcome, the per-file list + of what changed, branch, test/build status (say so plainly if tests were not + run), and any caveats — known or potential problems and assumptions, stated + specifically. Omit caveats only if there are genuinely none. +2. **If this is the last unit** (a single-unit scope is just this), do **not** ship + it here: go to `session-end`, which does docs, review, and the issue + sweep, then **stops before shipping** to summarize what was done and any + caveats and wait for the user's go. After the go it ships the unit once, watches + CI, fixes and re-merges if needed, closes out (issue closing, cleanup / + worktree teardown), and finishes with a final-state summary. +3. Otherwise (a unit before the last), optionally run + `/code-review <level> --fix` (e.g. `/code-review high --fix`), then land the unit: + commit → push → open PR → watch CI → merge, via `/ship` (a CI failure + clearly caused by the change is fixed forward within the unit, at most twice; + anything else is surfaced). If issues are linked, put one closing line per issue + (`Closes #N` / `Fixes #N`) in the PR body — read them from + `git config branch.$(git branch --show-current).session-issues` + (comma-separated) if they are no longer in context. +4. Start the next unit (re-isolate from the updated default branch, implement) and + repeat from step 1. + +- **Worked on the default branch in place** (repo `CLAUDE.md` says so): there is no + feature branch; `/ship` and `session-end` run from the default + branch. + +`/ship` step 9 tears down the worktree after each merge (the last unit's +ship runs inside `session-end`); the user can also +remove it later with `opencode.worktree_remove`. diff --git a/plugins-opencode/session/skills/session-start/scripts/branch b/plugins-opencode/session/skills/session-start/scripts/branch new file mode 100755 index 0000000..98f16e5 --- /dev/null +++ b/plugins-opencode/session/skills/session-start/scripts/branch @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# branch - Git branch operations for session workflows +# Exit codes: 0 success (including -h/--help), 1 bad usage or invalid name, 2 git error +# +# Subcommands: +# create <name> Create and switch to a new branch + +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: branch <subcommand> [args] + +Subcommands: + create <name> Create and switch to a new branch +EOF +} + +die() { echo "Error: $*" >&2; exit 2; } + +[[ $# -ge 1 ]] || { usage >&2; exit 1; } + +cmd="$1"; shift + +case "$cmd" in + create) + [[ $# -eq 1 ]] || { echo "Usage: branch create <name>" >&2; exit 1; } + name="$1" + [[ "$name" != -* ]] || { echo "Error: branch name must not start with '-': $name" >&2; exit 1; } + git check-ref-format --branch "$name" >/dev/null 2>&1 || { echo "Error: invalid branch name: $name" >&2; exit 1; } + if git show-ref --verify --quiet "refs/heads/$name"; then + die "branch '$name' already exists" + fi + git switch -c "$name" || die "failed to create branch '$name'" + ;; + -h|--help) usage ;; + *) echo "Unknown subcommand: $cmd" >&2; usage >&2; exit 1 ;; +esac diff --git a/plugins-opencode/session/skills/session-start/scripts/git-wait b/plugins-opencode/session/skills/session-start/scripts/git-wait new file mode 100755 index 0000000..335f658 --- /dev/null +++ b/plugins-opencode/session/skills/session-start/scripts/git-wait @@ -0,0 +1,1460 @@ +#!/usr/bin/env bash +# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. +# +# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: +# listing, creating, commenting, merging, closing, viewing logs. This script +# exists only for the three things neither CLI gives you: +# +# 1. Platform detection — matching the git remote hostname against configured +# tea logins, so a caller knows whether to reach for `gh` or `tea`. +# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a +# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on +# the merge itself; `tea` has no equivalent at all). +# 3. `run watch` — block until CI finishes, aggregating per-job status and +# dumping failed job logs. `gh run watch` is GitHub-only and misses +# job-level failures masked by a run-level success; `tea` has no watcher. +# +# Usage: +# git-wait [-C DIR] <command> ... +# Operate on the git repo at DIR instead of the current directory (like +# `git -C`). Must come before the command. gh/tea resolve the repo from the +# working directory, so this retargets every call without a caller-side cd. +# +# git-wait platform +# Echo "github" or "gitea" for the current repo's origin remote. +# +# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] +# [--alert-interval 300] +# Block until the PR for BRANCH reaches a terminal state. +# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, +# url, duration, and (when relevant) reason. +# +# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] +# [--timeout 14400] [--idle-timeout 0] [--interval 15] +# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] +# [--max-poll-failures 10] +# Block until CI finishes. Output: "status: pass|fail|closed|timeout| +# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed +# job logs go to stderr. +# +# --branch follows ONE run: the newest correlated to that branch (via the +# PR's check rollup when a PR exists, else the newest run in the list). +# That is right for a PR branch, where one push means one run. It is NOT +# sufficient on a default branch, where two merges landing close together +# produce two runs and the newest passing says nothing about the older +# one still executing. +# +# --sha watches EVERY run for one commit and is the correct flag for a +# post-merge/release watch: it stays pending while any run for the commit +# is pending, and fails if any run — or any job inside one — failed. Pass +# one or the other, not both. +# +# A running CI is never aborted for lack of visible progress: `run watch +# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress +# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO +# check is pending (running CI, or auto-merge armed, resets it), so a PR that +# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long +# jobs (VM boot + integration suite + teardown) can go quiet for a long time. +# While still waiting, a heartbeat alert goes to STDERR every --alert-interval +# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) +# pending: ...)". stdout key:value output is unchanged. +# +# --no-run-timeout is how long to wait for the FIRST run to appear before +# reporting no-workflow, counted from the end of --initial-delay. Default 600s +# for --sha (post-merge workflows queue late, or start only after another +# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty +# check. A stderr alert is printed each poll while waiting. A FAILED run-list +# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not +# counted toward this deadline and polling continues, but after +# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the +# watch gives up with "status: error" and exit 4. A successful poll resets the +# count. +# +# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the +# commit is terminal and passing, keep polling SECS more before reporting pass, +# so a chained workflow_run workflow that appears late is still watched. A +# stderr line is printed while settling; a new run restarts the watch. +# +# Exit codes: 0 terminal state reached (check "status:" for pass/fail), +# 1 usage error, 2 timeout, 3 platform detection failure or no +# PR/workflow found, 4 command failed + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +die() { echo "git-wait: $*" >&2; exit 1; } +die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } + +# Run a CLI command and pipe its stdout through a jq filter. +# If the command fails, die with its stderr instead of feeding junk to jq. +# Usage: cli_json [jq-flags...] <jq-filter> <cmd> [args...] +# +# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. +# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, +# auth warnings, progress text) into the JSON, silently corrupting jq +# parsing and producing wrong results downstream (e.g. run watch seeing +# unexpected status values). +cli_json() { + local jq_flags=() + while [[ "$1" =~ ^-[a-zA-Z] ]]; do + # Collect jq flags (e.g. -r, -e) — stop at the filter string + case "$1" in + -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; + *) break ;; + esac + done + local filter="$1"; shift + local raw stderr_file rc=0 + stderr_file=$(mktemp) + raw=$("$@" 2>"$stderr_file") || rc=$? + if [[ $rc -ne 0 ]]; then + local err + err=$(cat "$stderr_file") + rm -f "$stderr_file" + die "$err" + fi + rm -f "$stderr_file" + echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" +} + +# --------------------------------------------------------------------------- +# Target repo (-C DIR) +# +# Handled before platform detection. The cd happens inside this script's own +# process, so the caller's working directory is never touched. +# --------------------------------------------------------------------------- + +if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then + [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" + target_dir="$2" + [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" + git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ + || die_usage "$1: not a git repository: $target_dir" + # Resolve the script path first: a relative $0 breaks once we cd (help reads it). + SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + cd "$target_dir" + shift 2 +fi +SELF="${SELF:-$0}" + +# --------------------------------------------------------------------------- +# Platform detection +# --------------------------------------------------------------------------- + +detect_platform() { + local remote_url hostname login_url login_host + remote_url=$(git remote get-url origin 2>/dev/null) \ + || die "no git remote 'origin' found — run from a git repository" + + # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) + # or HTTPS (https://host/org/repo or https://host:port/org/repo) + if [[ "$remote_url" =~ ^ssh:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') + elif [[ "$remote_url" =~ ^git@ ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') + elif [[ "$remote_url" =~ ^https?:// ]]; then + hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') + else + die "unrecognised remote URL format: $remote_url" + fi + + # Check if this hostname matches any configured tea login + if command -v tea >/dev/null 2>&1; then + while IFS= read -r login_url; do + login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') + if [[ "$login_host" == "$hostname" ]]; then + echo "gitea" + return + fi + done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) + fi + + # Not a known tea login — fall back to gh (GitHub) + if [[ "$hostname" == "github.com" ]]; then + echo "github" + return + fi + + die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" +} + +PLATFORM=$(detect_platform) + +case "$PLATFORM" in + github) CLI=gh ;; + gitea) CLI=tea ;; +esac + +command -v "$CLI" >/dev/null 2>&1 \ + || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } + +# --------------------------------------------------------------------------- +# Internal reads +# +# These are NOT public subcommands — they are the normalized queries the two +# waiters below need. Every one of them dies on backend failure, so callers +# invoke them inside $( ) with a fallback: a probe failure must degrade the +# poll loop, never abort it. +# --------------------------------------------------------------------------- + +# List PRs as normalized JSON. Flags: --state, --limit, --assignee. +_pr_list() { + local limit assignee state args + limit=30; assignee=""; state="open" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; + --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") + # gh uses 'merged' as a state but tea uses 'closed' for merged PRs + [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") + [[ -n "$assignee" ]] && args+=(--assignee "$assignee") + cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ + env GH_NO_COLOR=1 gh pr list "${args[@]}" + ;; + gitea) + args=(--output json --limit "$limit" + --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") + [[ "$state" == "merged" ]] && state="closed" + args+=(--state "$state") + cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ + env NO_COLOR=1 tea pr list "${args[@]}" + ;; + esac +} + +# Show one PR as normalized JSON. Takes <N> or --branch NAME. +_pr_show() { + local num branch pr_json pr_stderr pr_rc pr_detail err + num=""; branch="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --*) die_usage "unknown flag: $1" ;; + *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; + esac + shift + done + [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass <N> or --branch NAME, not both" + if [[ -n "$branch" ]]; then + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + num=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + [[ -n "$num" ]] || die "no PR found for branch '$branch'" + fi + [[ -n "$num" ]] || die_usage "usage: git-wait pr show <N> | --branch NAME" + case "$PLATFORM" in + github) + cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ + env GH_NO_COLOR=1 gh pr view "$num" \ + --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" + ;; + gitea) + # `tea pr list` omits the `merged` boolean and `merged_at` timestamp + # entirely (tea only encodes merge state into the `state` string) and + # emits `mergeable` as a string, so a merged PR reports + # merged:false / mergedAt:null and consumers think it is still open + # (#140). Fetch the PR detail via the REST API instead, mirroring the + # run:show/run:list `tea api` pattern, so merge fields are reliable. + pr_stderr=$(mktemp); pr_rc=0 + pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ + || pr_rc=$? + if [[ $pr_rc -ne 0 ]]; then + err=$(cat "$pr_stderr"); rm -f "$pr_stderr" + die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" + fi + rm -f "$pr_stderr" + # Derive `state` from `merged` so it stays consistent with the merge + # flags (Gitea REST reports state:"closed" for a merged PR) and matches + # the GitHub path, which emits state:"merged". + echo "$pr_detail" | jq '{ + number: (.number // .index), + title: (.title // ""), + body: (.body // ""), + state: (if (.merged // false) then "merged" else (.state // "") end), + merged: (.merged // false), + merged_at: (.merged_at // null), + author: (.user.login // .user.username // ""), + head: (.head.ref // .head.label // ""), + base: (.base.ref // .base.label // ""), + labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), + assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), + mergeable: (.mergeable // null), + created_at: (.created_at // ""), + updated_at: (.updated_at // null), + url: (.html_url // .url // ""), + comments: [] + }' + ;; + esac +} + +# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. +_auto_merge_status() { + local branch number pr_json am + branch=""; number="" + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) shift; branch="$1" ;; + --number) shift; number="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + + # Resolve PR number from branch if needed + if [[ -z "$number" ]]; then + [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" + pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" + number=$(echo "$pr_json" | jq -r --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') + if [[ -z "$number" || "$number" == "null" ]]; then + echo "auto_merge: false" + echo "No open PR found for branch '$branch'" >&2 + exit 3 + fi + fi + + case "$PLATFORM" in + github) + am=$(cli_json -r '.autoMergeRequest != null' \ + env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) + echo "auto_merge: $am" + ;; + gitea) + echo "auto_merge: false" + echo "Gitea does not support auto-merge detection" >&2 + ;; + esac +} + +# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. +# +# --sha filters to runs for one commit. GitHub has a server-side filter for it +# (`gh run list --commit`); Gitea does not, so it is applied client-side over +# an unfiltered fetch, the same way --branch already is there. Both platforms +# emit head_sha in the normalized output — GitHub did not used to, which is +# why `run watch --sha` needs the headSha field added below. +_run_list() { + local limit status branch sha args query raw_stderr raw_rc raw err + limit=20; status=""; branch=""; sha="" + while [[ $# -gt 0 ]]; do + case "$1" in + --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; + --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") + [[ -n "$status" ]] && args+=(--status "$status") + [[ -n "$branch" ]] && args+=(--branch "$branch") + [[ -n "$sha" ]] && args+=(--commit "$sha") + cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ + env GH_NO_COLOR=1 gh run list "${args[@]}" + ;; + gitea) + # Source from Gitea REST API directly. `tea actions runs list` + # filters server-side by a `branch` column that Gitea leaves empty + # on `pull_request` runs, so the watcher's --branch lookup misses + # correlated runs (#103). Fetch unfiltered via `tea api`, normalize + # `branch` from `head_branch`, and apply --branch client-side. + query="limit=$limit" + [[ -n "$status" ]] && query+="&status=$status" + raw_stderr=$(mktemp); raw_rc=0 + raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ + || raw_rc=$? + if [[ $raw_rc -ne 0 ]]; then + err=$(cat "$raw_stderr"); rm -f "$raw_stderr" + die "tea api repos/{owner}/{repo}/actions/runs failed: $err" + fi + rm -f "$raw_stderr" + echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' + [(.workflow_runs // []) | .[] | { + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + head_sha: (.head_sha // ""), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // "") + }] + | if $b == "" then . else [.[] | select(.branch == $b)] end + | if $s == "" then . else + [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] + end + ' + ;; + esac +} + +# Show one CI run as normalized JSON, including per-job status. +_run_show() { + local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err + [[ $# -ge 1 ]] || die_usage "usage: git-wait run show <run-id>" + run_id="$1" + case "$PLATFORM" in + github) + cli_json \ + 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ + env GH_NO_COLOR=1 gh run view "$run_id" \ + --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" + ;; + gitea) + # Fetch the run object via the REST API. `tea actions runs view` + # ignores `--output json` (tea 0.14.1) and prints a human key/value + # table while still exiting 0, so jq downstream chokes (#133). Use the + # same `tea api` pattern as run:list and the jobs lookup below. + view_stderr=$(mktemp); view_rc=0 + view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ + || view_rc=$? + if [[ $view_rc -ne 0 ]]; then + err=$(cat "$view_stderr"); rm -f "$view_stderr" + die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" + fi + rm -f "$view_stderr" + + # Fetch per-job data via the actions API so callers (run watch) can + # detect job-level failures masked by run-level status=success on + # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. + jobs_array='[]' + jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) + if [[ -n "$jobs_json" ]]; then + jobs_array=$(echo "$jobs_json" | jq -c ' + def to_status: + if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) + end; + [(.jobs // .) | (if type == "array" then .[]? else empty end) | + {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] + ' 2>/dev/null) || jobs_array='[]' + fi + + # Older Gitea versions may not expose the jobs API; fall back to + # scanning the run logs for "Job '<name>' failed" lines. + if [[ "$jobs_array" == '[]' ]]; then + failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ + | grep -oE "Job '[^']+' failed" \ + | sed -E "s/Job '(.+)' failed/\1/" \ + | sort -u || true) + if [[ -n "$failed_log" ]]; then + jobs_array=$(printf '%s\n' "$failed_log" \ + | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') + fi + fi + + # Normalize REST field names into the output contract, mirroring the + # run:list jq above (conclusion-first status, head_branch//branch, + # run_started_at//created, name//workflow_id). + echo "$view_json" | jq --argjson jobs "$jobs_array" '{ + id: (.id | tostring), + status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) + elif .status == "completed" then "success" + else (.status // "unknown" | ascii_downcase) end), + workflow: (.name // .workflow_id // ""), + branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), + event: (.event // ""), + started_at: (.run_started_at // .created // ""), + duration: (.duration // null), + url: (.url // ""), + jobs: $jobs + }' + ;; + esac +} + +# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; +# Gitea has no server-side filter and returns every job's log). +_run_logs() { + local run_id failed_only + [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs <run-id> [--failed-only]" + run_id="$1"; shift + failed_only=false + while [[ $# -gt 0 ]]; do + case "$1" in + --failed-only) failed_only=true ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + case "$PLATFORM" in + github) + if [[ "$failed_only" == "true" ]]; then + GH_NO_COLOR=1 gh run view "$run_id" --log-failed + else + GH_NO_COLOR=1 gh run view "$run_id" --log + fi + ;; + gitea) + # tea actions runs logs outputs all job logs; no built-in failed-only filter + NO_COLOR=1 tea actions runs logs "$run_id" + ;; + esac +} + +# --------------------------------------------------------------------------- +# Run helpers +# --------------------------------------------------------------------------- + +# Return comma-separated names of any jobs in <run_id> whose status is +# "failure", or empty if none. Used by run watch to detect job-level failures +# even when the run-level status reports success — Gitea sets run.status to +# "success" on a multi-job workflow if at least one job ran successfully, +# masking failures in earlier jobs (see issue #87). Calls "run show" to +# normalize per-platform JSON, so it works for both gh and tea paths. +_run_failed_jobs() { + local run_id="$1" show_json + show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 + echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' +} + +# Progress-aware timeout decision shared by `pr wait` and `run watch`. +# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress +# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. +# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ +# minutes: this lets callers keep waiting while CI is actively progressing and +# give up only after a stretch of no progress, with a hard ceiling backstop. +_wait_timed_out() { + local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" + if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then + echo "ceiling"; return 0 + fi + if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then + echo "idle"; return 0 + fi + return 1 +} + +# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. +_fmt_dur() { + local s="$1" + if [[ "$s" -lt 60 ]]; then echo "${s}s" + elif [[ "$s" -lt 3600 ]]; then + if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi + else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi +} + +# Periodic stderr heartbeat while a wait is still running. Callers set +# alert_interval (0 disables) and next_alert (initialised to alert_interval), +# and call `_heartbeat "$elapsed" "<detail>"` once per poll. Emits at most one +# alert per poll, then re-arms for the next multiple of alert_interval, so a +# slow poll never produces a burst. stderr only: stdout stays parseable. +_heartbeat() { + local el="$1" detail="$2" + [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 + echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 + next_alert=$(( (el / alert_interval + 1) * alert_interval )) +} + +# Coarse CI status — pending|success|failure|none — for a PR/branch, used by +# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the +# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is +# guarded so a probe failure degrades to "none" and never aborts the wait loop. +_ci_status() { + local pr_number="$1" branch="$2" view_json run_status + case "$PLATFORM" in + github) + view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } + echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) else "pending" end + else (.state // "pending" | ascii_downcase) end + ] | + if length == 0 then "none" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" end' 2>/dev/null || echo "none" + ;; + gitea) + run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) echo "pending" ;; + failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; + ""|none|null) echo "none" ;; + *) echo "success" ;; + esac + ;; + *) echo "none" ;; + esac +} + +# --------------------------------------------------------------------------- +# Command routing +# --------------------------------------------------------------------------- + +cmd="${1:-}" +sub="${2:-}" +shift 2 || shift || true + +case "$cmd:$sub" in + + # Echo the detected platform so callers know which CLI to reach for. + # PLATFORM is already resolved above; detection failure exited long before + # we got here. + platform:) + echo "$PLATFORM" + ;; + + pr:wait) + # timeout is the hard ceiling; idle_timeout is the no-progress window. + branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" ]] || die_usage "pr wait requires --branch" + + # Find PR for this branch + pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" + # Match branch — handle Gitea owner:branch format with endswith + pr=$(echo "$pr_json" | jq --arg b "$branch" \ + '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') + + if [[ -z "$pr" || "$pr" == "null" ]]; then + echo "status: no-pr" + echo "duration: 0s" + echo "No PR found for branch '$branch'" >&2 + exit 3 + fi + + pr_number=$(echo "$pr" | jq -r '.number') + pr_url=$(echo "$pr" | jq -r '.url // ""') + elapsed=0 + idle=0; idle_mark=0 + last_signal="" + unknown_streak=0 + + # Poll loop + while true; do + show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" + pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') + pr_merged=$(echo "$show_json" | jq -r '.merged // false') + pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') + + # Progress signals: CI still running or auto-merge pending means the PR is + # actively advancing toward merge, so the idle clock must not count down. + checks=$(_ci_status "$pr_number" "$branch") + if [[ "$PLATFORM" == "github" ]]; then + auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" + [[ "$auto_merge" == "true" ]] || auto_merge="false" + else + auto_merge="false" + fi + signal="$pr_state|$pr_mergeable|$checks|$auto_merge" + if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then + idle=0 + fi + last_signal="$signal" + + echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 + [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true + + case "$pr_state" in + merged) + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + closed) + if [[ "$pr_merged" == "true" ]]; then + echo "status: merged" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + fi + echo "status: closed" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR was closed without merging" >&2 + exit 0 + ;; + open) + # Check for merge conflicts + if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then + echo "status: blocked" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: PR has merge conflicts" >&2 + exit 0 + fi + # Still open — keep polling + ;; + *) + unknown_streak=$(( unknown_streak + 1 )) + if [[ "$unknown_streak" -ge 3 ]]; then + echo "status: error" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 + exit 4 + fi + echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 + ;; + esac + + # Reset unknown streak on any recognized state + [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 + + # Check timeout — only give up after a stretch of no progress (idle) or + # the absolute ceiling, never while CI/auto-merge is still working. + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "pr_number: $pr_number" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + run:watch) + # timeout is the hard ceiling; idle_timeout is the no-progress backstop. + # While CI is actively pending the idle clock is reset each poll, so a long + # (15+ min) suite runs to completion up to the ceiling rather than being cut + # off by a flat wall-clock timeout. + branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 + alert_interval=300; next_alert=300; no_run_timeout="" + settle=0; settle_given=0; no_run_skew=0 + max_poll_failures=10; poll_fails=0 + _t0=$SECONDS + while [[ $# -gt 0 ]]; do + case "$1" in + --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; + --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; + --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; + --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; + --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; + --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; + --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; + --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; + --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; + --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; + *) die_usage "unknown flag: $1" ;; + esac + shift + done + [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" + [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" + [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" + # How long to wait for the FIRST run to appear (counted from the end of + # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ + # workflow_run and can queue minutes late, so that scope gets longer. + if [[ -z "$no_run_timeout" ]]; then + if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi + fi + + # `gh run list --commit` matches only on a FULL 40-character SHA -- a short + # one returns zero rows with no error, which this watcher would report as + # "no-workflow" rather than as the caller's mistake. Expand a short SHA via + # git when the commit is local, and refuse it outright when it is not, + # rather than silently watching nothing. (Gitea matches client-side on the + # first 12 chars, so a full SHA is correct there too.) + if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" + if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha="$_full_sha" + else + die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" + fi + fi + + elapsed=0 + idle=0; idle_mark=0 + + # A failed run-list call (network, auth, rate limit) is NOT an empty list. + # Note it, keep polling, and exclude the time from the no-workflow deadline + # (accumulated in no_run_skew). The hard ceiling still applies. After + # --max-poll-failures consecutive failures it gives up (exit 4). + _poll_failed() { + local what="$1" before="$elapsed" + poll_fails=$(( poll_fails + 1 )) + echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 + if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then + echo "status: error" + echo "duration: ${elapsed}s" + echo "reason: run list failed ${poll_fails} consecutive times" + echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 + exit 4 + fi + elapsed=$(( SECONDS - _t0 )) + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 + exit 2 + fi + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + no_run_skew=$(( no_run_skew + elapsed - before )) + } + + # Enforce the hard --timeout ceiling on paths that otherwise `continue` + # (no runs yet, settling, no checks registered) so they cannot outlive it. + _ceiling_check() { + local what="$1" + if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: exceeded max wait ${timeout}s" + echo "Timed out waiting for CI on ${what}" >&2 + exit 2 + fi + } + + # ------------------------------------------------------------------ + # --sha: watch EVERY run for one commit, not just the newest. + # + # `--branch` deliberately follows a single run (the newest correlated + # one). That is right for a PR branch, where one push means one run, but + # wrong for a default branch: two merges landing close together produce + # two runs, and the newest going green says nothing about the older one + # still executing. Watching a post-merge release run by branch reported + # "pass" while a second run was mid-flight. + # + # A commit is the honest scope for that question — the caller wants the + # runs *their* merge caused, not whatever else is landing on the branch. + # So this path aggregates: it stays non-terminal while ANY run for the + # commit is non-terminal, and fails if ANY run (or any job within one) + # failed. + # + # The CRITICAL DESIGN RULE below applies here too: only explicitly + # non-terminal statuses keep polling; anything unrecognized counts as + # terminal so an unexpected status cannot loop until timeout. + # ------------------------------------------------------------------ + if [[ -n "$sha" ]]; then + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + echo "Watching all runs for commit ${sha:0:12}..." >&2 + + # Settle window: after every run is terminal and passing, keep polling + # --settle seconds for a chained (workflow_run) run before reporting pass. + settle_start=-1; settle_ids="" + + while true; do + if ! sha_json=$(_run_list --sha "$sha" --limit 50); then + _poll_failed "commit ${sha:0:12}" + continue + fi + poll_fails=0 + sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) + + if [[ "$sha_count" -eq 0 ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + # Non-terminal set is explicit; everything else is terminal. + pending=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested")] + | length') + + echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 + + if [[ "$pending" -gt 0 ]]; then + pending_names=$(echo "$sha_json" | jq -r ' + [.[] | select(.status == "queued" or .status == "in_progress" + or .status == "waiting" or .status == "running" + or .status == "pending" or .status == "requested") + | (.workflow // .id)] | join(", ")') + _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" + # Active CI is progress — reset the idle clock, same as --branch. + idle=0 + settle_start=-1 + else + # Every run terminal. Collect run-level and job-level failures + # across ALL of them before declaring pass (#87 applies per run). + all_failed="" + fail_url="" + while IFS=$'\t' read -r r_id r_status r_url; do + [[ -n "$r_id" ]] || continue + case "$r_status" in + failure|timed_out|cancelled|canceled|skipped) + all_failed+="${all_failed:+,}run-$r_id:$r_status" + [[ -n "$fail_url" ]] || fail_url="$r_url" + ;; + *) + r_failed=$(_run_failed_jobs "$r_id") + if [[ -n "$r_failed" ]]; then + all_failed+="${all_failed:+,}$r_failed" + [[ -n "$fail_url" ]] || fail_url="$r_url" + fi + ;; + esac + done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') + + if [[ -n "$all_failed" ]]; then + echo "status: fail" + [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $all_failed" + echo "--- Failed job logs (last 80 lines) ---" >&2 + echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do + _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true + done + exit 0 + fi + + if [[ "$settle" -gt 0 ]]; then + cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') + if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then + echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 + settle_start=-1 + fi + if [[ "$settle_start" -lt 0 ]]; then + settle_start=$elapsed; settle_ids="$cur_ids" + fi + if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then + echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 + _ceiling_check "commit ${sha:0:12}" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + fi + + echo "status: pass" + first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') + [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" + echo "duration: ${elapsed}s" + echo "runs: $sha_count" >&2 + exit 0 + fi + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so + # `run list --branch` correlates nothing and the watcher times out into + # no-workflow even when CI ran (#140). Resolve the branch head SHA up front + # (only on Gitea) and fall back to head_sha correlation when the + # branch-filtered lookup is empty. The run object's head_sha equals the + # branch head on Gitea (confirmed in #140); if a variant ever records a + # merge-ref SHA the fallback simply misses and degrades to today's + # behaviour rather than returning a wrong run. + _watch_branch_sha="" + if [[ "$PLATFORM" == "gitea" ]]; then + _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ + || git rev-parse "origin/$branch" 2>/dev/null || true) + fi + + # Echo a run-list JSON array for $branch: branch-name correlation first, + # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the + # server-side --branch filter populates the first call and _watch_branch_sha + # stays empty, so the SHA path is never taken. + _runs_for_branch() { + local lim="${1:-1}" out + # A failed call returns 1 (distinct from a successful empty "[]"). + out=$(_run_list --branch "$branch" --limit "$lim") || return 1 + if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then + echo "$out"; return 0 + fi + if [[ -n "$_watch_branch_sha" ]]; then + _run_list --limit 50 | jq \ + --arg s "$_watch_branch_sha" --argjson n "$lim" \ + '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ + || return 1 + return 0 + fi + echo "[]" + } + + # On GitHub, prefer PR-based status checking — one API call gives us both + # merge state and all CI check results via statusCheckRollup, avoiding the + # flaky run-level polling that produces "unknown" statuses. + pr_number="" + pr_url="" + use_pr=false + if [[ "$PLATFORM" == "github" ]]; then + pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { + pr_number=$(echo "$pr_json" | jq -r '.number // empty') + pr_url=$(echo "$pr_json" | jq -r '.url // ""') + [[ -n "$pr_number" ]] && use_pr=true + } + fi + + # Pre-check: look for an already-terminal state before sleeping the + # initial delay. If the PR already merged or CI already finished, + # report immediately instead of waiting. + _precheck_done=false + if [[ "$use_pr" == "true" ]]; then + _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" + _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') + + if [[ "$_pre_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already merged" >&2 + exit 0 + fi + if [[ "$_pre_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "PR #$pr_number already closed without merging" >&2 + exit 0 + fi + + _pre_checks=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + if [[ "$_pre_checks" == "success" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "CI already passed on PR #$pr_number" >&2 + exit 0 + fi + + if [[ "$_pre_checks" == "failure" ]]; then + _pre_failed=$(echo "$_pre_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: 0s" + echo "failed_jobs: $_pre_failed" + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + fi + else + # Fallback path: check if a completed run already exists + _pre_list=$(_runs_for_branch 1) || _pre_list="[]" + _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') + if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then + _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') + _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') + _pre_id=$(echo "$_pre_latest" | jq -r '.id') + case "$_pre_status" in + success|completed) + # Run-level status can read "success" on Gitea even when a + # job inside the run failed (issue #87). Aggregate per-job + # status before declaring pass. + failed_jobs=$(_run_failed_jobs "$_pre_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "CI already passed for branch '$branch'" >&2 + exit 0 + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$_pre_id") + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$_pre_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a + # reason so consumers (ship/session-end) gating on + # status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" + echo "duration: 0s" + echo "reason: $_pre_status" + echo "CI run $_pre_status for branch '$branch'" >&2 + exit 0 + ;; + esac + fi + fi + + # Initial delay — CI run may not exist immediately after push + if [[ "$initial_delay" -gt 0 ]]; then + echo "Waiting ${initial_delay}s for CI to start..." >&2 + sleep "$initial_delay" + elapsed=$(( SECONDS - _t0 )) + fi + _nr0=$SECONDS; idle_mark=$elapsed + + if [[ "$use_pr" == "true" ]]; then + echo "Watching PR #$pr_number for branch '$branch'..." >&2 + + while true; do + # A failed gh call is not "unknown" -- count it, cap consecutive failures. + if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then + _poll_failed "PR #$pr_number" + continue + fi + poll_fails=0 + pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') + [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') + + # PR merged — all done + if [[ "$pr_state" == "merged" ]]; then + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number merged" >&2 + exit 0 + fi + + # PR closed without merge + if [[ "$pr_state" == "closed" ]]; then + echo "status: closed" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "PR #$pr_number closed without merging" >&2 + exit 0 + fi + + # Summarize CI check statuses from statusCheckRollup + # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state + checks_summary=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + if .__typename == "CheckRun" then + if .conclusion then (.conclusion | ascii_downcase) + else "pending" + end + else (.state // "pending" | ascii_downcase) + end + ] | + if length == 0 then "pending" + elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" + elif all(. == "success" or . == "neutral" or . == "skipped") then "success" + else "pending" + end') + + echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 + + case "$checks_summary" in + success) + echo "status: pass" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + failure) + failed_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select( + (.__typename == "CheckRun" and .conclusion and + ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or + (.__typename != "CheckRun" and .state and + ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) + ) | .name // .context // "unknown" + ] | join(",")') + echo "status: fail" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_names" + # Try to fetch failed logs from the latest run + run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + pending) + # Still running — keep polling. Active CI is progress, so reset idle. + check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') + if [[ "$check_count" -eq 0 ]]; then + # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + exit 3 + fi + echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + else + # Active CI is progress, so reset idle. + idle=0 + fi + pending_names=$(echo "$view_json" | jq -r ' + [.statusCheckRollup // [] | .[] | + select(if .__typename == "CheckRun" then (.conclusion // "") == "" + else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) + | .name // .context // "unknown"] | unique | join(", ")') + _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" + ;; + esac + + # Check timeout — idle window or absolute ceiling (see _wait_timed_out). + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + fi + + # Fallback: no PR found — poll run list directly (skip flaky run show). + # + # CRITICAL DESIGN RULE — default-terminal polling: + # + # This loop has caused repeated regressions (#53, #57, #58, #60). + # The recurring bug pattern is: + # 1. The API returns an unexpected status value (e.g. "completed" + # with null conclusion, or a new status GitHub adds later). + # 2. The case statement doesn't recognise it. + # 3. A catch-all `*) keep polling` silently loops until timeout. + # + # The fix (applied here) inverts the logic: + # - ONLY explicitly non-terminal states keep polling. + # - The `*` catch-all EXITS (as pass). + # + # DO NOT add a `*) keep polling` catch-all to this case statement. + # If a new non-terminal status appears, add it to the explicit list. + # If you're unsure whether a status is terminal, it's safer to exit + # early (the caller can retry) than to loop for 5 minutes. + # + run_url="" + while true; do + if ! list_json=$(_runs_for_branch 1); then + _poll_failed "branch '$branch'" + continue + fi + poll_fails=0 + latest=$(echo "$list_json" | jq -r '.[0] // empty') + + if [[ -z "$latest" || "$latest" == "null" ]]; then + no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) + [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 + if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then + echo "status: no-workflow" + echo "duration: ${elapsed}s" + # Distinguish "no workflow registered at all" from "runs exist + # but none correlate to this branch" so callers (#103) can tell + # a real CI absence from a branch-correlation gap. + any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" + if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then + echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + else + echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 + fi + exit 3 + fi + echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 + _ceiling_check "branch '$branch'" + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + continue + fi + + run_id=$(echo "$latest" | jq -r '.id') + run_status=$(echo "$latest" | jq -r '.status // "unknown"') + run_url=$(echo "$latest" | jq -r '.url // ""') + + echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 + + # See "CRITICAL DESIGN RULE" above — non-terminal states are listed + # explicitly; everything else exits. Do NOT add a `*) keep polling`. + case "$run_status" in + queued|in_progress|waiting|running|pending|requested) + # Non-terminal — keep polling. Active CI is progress, so reset idle. + idle=0 + _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" + ;; + failure|timed_out) + failed_jobs=$(_run_failed_jobs "$run_id") + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + if [[ -n "$run_id" ]]; then + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + fi + exit 0 + ;; + cancelled|canceled|skipped) + # Distinct terminal states — surface them as fail with a reason + # so consumers gating on status: pass stop instead of advancing. + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $run_status" + echo "CI run $run_status on branch '$branch'" >&2 + exit 0 + ;; + *) + # Terminal — covers success and any future/unexpected status. + # Even when the run-level status reports success, an individual + # job may have failed (Gitea reports run.status=success on a + # multi-job run if any job succeeded; see #87). Aggregate + # per-job status before declaring pass. + failed_jobs=$(_run_failed_jobs "$run_id") + if [[ -n "$failed_jobs" ]]; then + echo "status: fail" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "failed_jobs: $failed_jobs" + echo "--- Failed job logs (last 80 lines) ---" >&2 + _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true + exit 0 + fi + echo "status: pass" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + exit 0 + ;; + esac + + timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) + if [[ -n "$timeout_kind" ]]; then + if [[ "$timeout_kind" == "ceiling" ]]; then + reason="exceeded max wait ${timeout}s" + else + reason="no progress for ${idle}s" + fi + echo "status: timeout" + [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" + echo "duration: ${elapsed}s" + echo "reason: $reason" + echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 + exit 2 + fi + + sleep "$interval" + elapsed=$(( SECONDS - _t0 )) + idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed + done + ;; + + --help:|-h:|:) + sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' + exit 0 + ;; + + *) + die_usage "unknown command: $cmd${sub:+ $sub}" + ;; +esac diff --git a/plugins-opencode/session/skills/session-summarize/SKILL.md b/plugins-opencode/session/skills/session-summarize/SKILL.md new file mode 100644 index 0000000..df7ff8d --- /dev/null +++ b/plugins-opencode/session/skills/session-summarize/SKILL.md @@ -0,0 +1,48 @@ +--- +user-invocable: true +name: session-summarize +description: >- + Summarize the current repo state. Triggers on "what was I working on?", + "session status", "catch me up", or when returning to active work. + Returns a paragraph plus categorized file/detail bullets. +--- + +# Summarize + +Use one script call as the source of truth, then summarize with an agent. + +## Steps + +1. Run: + + ```bash + bash scripts/sitrep + ``` + +2. If output says `is_git_repo: false`, report that a summary cannot be generated outside a git repository. + +3. Otherwise, invoke the `Agent` tool (`agent: general-purpose`) and provide only this script output as input context. + +4. Return exactly this structure: + + ```text + <paragraph summarizing the situation> + + * <major change category one summary> + * <file 1> + * <file 1 detail 1> + * <file 1 detail 2> + * <file 2> + * <file 2 detail 1> + * <file 2 detail 2> + * <major change category two summary> + * <file 3> + * <file 3 detail 1> + ``` + +## Rules + +- Trust script sections as authoritative (do not run extra git commands unless script fails). +- Include committed + staged + unstaged + untracked file changes when present. +- Group files under 2-5 major categories (examples: "New functionality", "Refactors", "Fixes", "Docs/metadata"). +- If output shows `clean: true` with no active branches, return only a short paragraph and no bullet list. diff --git a/plugins-opencode/session/skills/session-summarize/scripts/sitrep b/plugins-opencode/session/skills/session-summarize/scripts/sitrep new file mode 100755 index 0000000..558f9e3 --- /dev/null +++ b/plugins-opencode/session/skills/session-summarize/scripts/sitrep @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# sitrep - Situation report for a git repository +# Always shows working-tree state (staged/unstaged/untracked) together with +# committed context, and falls back to broader repo activity only when +# nothing else is actionable. +# +# Sections: +# 1. Working tree (staged/unstaged/untracked) +# 2. Unpushed commits (ahead of remote tracking branch) +# 3. Branch work (commits on feature branch vs base) +# 4. Repo activity (active branches, open issues) - only when 1-3 are empty +# +# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). +# +# Exit codes: 0 success (including -h/--help), 1 bad usage + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" + +usage() { + cat <<'EOF' +Usage: sitrep [directory] + +Situation report for a git repository. Shows working-tree changes plus +unpushed and branch commits, expanding to broader repo activity only +when everything is clean. + +If directory is omitted, uses the current working directory. +EOF +} + +if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then + usage + exit 0 +fi + +if [[ $# -gt 1 ]]; then + usage >&2 + exit 1 +fi + +dir="${1:-.}" +cd "$dir" + +gitq() { + git -c core.quotepath=false "$@" +} + +# Print a diff section, truncated to MAX_DIFF_LINES. +emit_diff() { + local title="$1" text="$2" total + [[ -n "$text" ]] || return 0 + total="$(printf '%s\n' "$text" | wc -l)" + echo "" + echo "=== $title ===" + if ((total > MAX_DIFF_LINES)); then + printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" + echo "[truncated $((total - MAX_DIFF_LINES)) lines]" + else + printf '%s\n' "$text" + fi +} + +# --- Not a git repo --- +if ! gitq rev-parse --git-dir >/dev/null 2>&1; then + echo "=== REPO ===" + echo "is_git_repo: false" + exit 0 +fi + +# --- Basic repo info (always shown) --- +head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" +head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" + +echo "=== REPO ===" +if [[ -n "$head_branch" ]]; then + echo "branch: $head_branch" +else + echo "detached_at: $head_sha" +fi + +# Detect base branch: origin/HEAD, then origin/main|master, then local main|master +base_ref="" +origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" +for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do + [[ -n "$candidate" ]] || continue + if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then + base_ref="$candidate" + break + fi +done + +on_base=false +if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then + on_base=true +fi + +has_merge_base=false +if [[ -n "$base_ref" ]]; then + echo "base: $base_ref" + if ! $on_base; then + if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then + has_merge_base=true + else + echo "note: no merge base between $base_ref and HEAD (unrelated histories)" + fi + ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" + behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" + echo "ahead: $ahead" + echo "behind: $behind" + fi +fi + +found_activity=false + +# --- Working tree: staged / unstaged / untracked --- +staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" +unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" +untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" + +if [[ -n "$staged_files" ]]; then + found_activity=true + echo "" + echo "=== STAGED ===" + echo "$staged_files" + emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$unstaged_files" ]]; then + found_activity=true + echo "" + echo "=== UNSTAGED ===" + echo "$unstaged_files" + emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" +fi + +if [[ -n "$untracked_files" ]]; then + found_activity=true + echo "" + echo "=== UNTRACKED ===" + echo "$untracked_files" +fi + +# --- Unpushed commits --- +tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" +unpushed="" + +if [[ -n "$tracking_branch" ]]; then + unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" +fi + +if [[ -n "$unpushed" ]]; then + found_activity=true + echo "" + echo "=== UNPUSHED ===" + echo "tracking: $tracking_branch" + echo "$unpushed" +fi + +# --- Branch work (feature branch vs base) --- +if ! $on_base && [[ -n "$base_ref" ]]; then + branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" + if [[ -n "$branch_commits" ]]; then + found_activity=true + echo "" + echo "=== BRANCH COMMITS ===" + echo "$branch_commits" + fi + + if $has_merge_base; then + committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + if [[ -n "$committed_files" ]]; then + found_activity=true + echo "" + echo "=== CHANGED FILES ===" + echo "$committed_files" + emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" + fi + fi +fi + +if $found_activity; then + exit 0 +fi + +# --- Repo activity (everything clean, nothing ahead) --- +active_branches="" +if [[ -n "$base_ref" ]]; then + active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" +fi + +if [[ -n "$active_branches" ]]; then + echo "" + echo "=== ACTIVE BRANCHES ===" + echo "$active_branches" +fi + +# Open issues (requires git-wait for platform detection, plus gh or tea) +if [[ -x "$SCRIPT_DIR/git-wait" ]]; then + platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" + issues="" + issues_err="" + errfile="$(mktemp)" + case "$platform" in + github) + if command -v gh >/dev/null 2>&1; then + issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" + fi + ;; + gitea) + if command -v tea >/dev/null 2>&1; then + issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" + fi + ;; + esac + if [[ -n "$issues_err" ]]; then + detail="$(head -n 1 "$errfile" 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + echo "note: $issues_err${detail:+: $detail}" + elif [[ -n "$issues" && "$issues" != "[]" ]]; then + formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" + echo "" + echo "=== OPEN ISSUES ===" + if [[ -n "$formatted" ]]; then + echo "$formatted" + else + echo "note: could not parse issue list" + fi + fi + rm -f "$errfile" +fi + +# Recent commits on default branch for context +echo "" +echo "=== RECENT COMMITS ===" +gitq log --oneline -10 2>/dev/null || true + +# Nothing at all +if [[ -z "$active_branches" ]]; then + echo "" + echo "=== STATUS ===" + echo "clean: true" +fi diff --git a/plugins-opencode/session/src/index.ts b/plugins-opencode/session/src/index.ts index 9b7a482..ec3f872 100644 --- a/plugins-opencode/session/src/index.ts +++ b/plugins-opencode/session/src/index.ts @@ -1,8 +1,288 @@ import { Plugin } from "@opencode/plugin" +import { + normalizeArgs, + bump, + execPrompt, + reviewPrompt, + opusReviewPrompt, + extractLastJsonBlock, + validateExec, + validateReview, + planWave, + splitFindings, + semaphore, + EXEC_SCHEMA, + REVIEW_SCHEMA, + type Chunk, + type ExecResult, + type Finding, + type Tier, + type OrchestrateArgs, +} from "./orchestrate-core.js" + +const CONCURRENCY = 4 +const MAX_REVIEW_ITERS = 2 + +// `haiku|sonnet|opus` → concrete model refs. Override per install with plugin +// options: { "modelTiers": { "haiku": "provider/model-id", ... } }. Default: +// fuzzy-match the enabled model list for a model whose id contains the tier +// name; fall back to the session default when nothing matches. +async function resolveTier(ctx: any, tier: Tier): Promise<{ providerID: string; id: string } | undefined> { + const override = (ctx.options?.modelTiers as Record<string, string> | undefined)?.[tier] + if (override) { + const [providerID, ...rest] = String(override).split("/") + if (providerID && rest.length) return { providerID, id: rest.join("/") } + } + try { + const models = (await ctx.model.list()) as Array<{ providerID: string; id: string; enabled?: boolean }> + const match = models.find((m) => m.enabled !== false && m.id.toLowerCase().includes(tier)) + if (match) return { providerID: match.providerID, id: match.id } + } catch { + /* provider list unavailable; children use the session default */ + } + return undefined +} + +// Defensive text extraction: message shapes vary across versions. +function lastAssistantText(messages: readonly unknown[]): string { + for (let i = messages.length - 1; i >= 0; i--) { + const m = messages[i] as Record<string, any> + const role = m.role ?? m.info?.role + if (role !== "assistant") continue + const content = m.content ?? m.parts ?? m.text + if (typeof content === "string" && content) return content + if (Array.isArray(content)) { + const text = content + .filter((p: any) => p && (p.type === "text" || typeof p.text === "string")) + .map((p: any) => p.text ?? "") + .join("\n") + if (text.trim()) return text + } + } + return "" +} -// M0 scaffold: proves the server part loads. M4 adds the orchestrate_build -// tool and the worktree/plan/rename native surfaces. export default Plugin.define({ - id: "agent-toolkit.session", - setup() {}, + id: "agent-toolkit.session", + async setup(ctx) { + // One child session per attempt: create → build agent → tier → prompt + // → wait → parse the last ```json block. Unparseable output is a retry + // trigger, never a silent pass. Children are top-level build sessions + // (not the subagent tool), so the depth-1 subagent limit doesn't apply; + // only the parent session ever has orchestrate_build, so no recursion. + async function runChild(label: string, tier: Tier, prompt: string): Promise<unknown> { + const child = await ctx.session.create({ title: `orchestrate ${label}` }) + try { + await ctx.session.switchAgent({ sessionID: child.id, agent: "build" }) + const model = await resolveTier(ctx, tier) + if (model) await ctx.session.switchModel({ sessionID: child.id, model }) + await ctx.session.prompt({ sessionID: child.id, text: prompt }) + await ctx.session.wait({ sessionID: child.id }) + const messages = await ctx.session.context({ sessionID: child.id }) + return extractLastJsonBlock(lastAssistantText(messages as readonly unknown[])) + } finally { + await ctx.session.remove({ sessionID: child.id }).catch(() => {}) + } + } + + type ExecAttempt = { + chunkId: string + ok: boolean + attempts: number + model: Tier + result: ExecResult | null + blocker?: string + } + + // Failure escalation (cap 3): attempt 1 base tier + base prompt; + // attempt 2 base tier + failure-refined prompt; attempt 3 bumped tier + + // refined prompt. Mirrors the Claude workflow's executeChunk. + async function executeChunk(args: OrchestrateArgs, chunk: Chunk, seedContext?: string): Promise<ExecAttempt> { + const baseModel = (chunk.model || "sonnet") as Tier + let extra = seedContext || "" + let last: ExecResult | null = null + let usedModel = baseModel + for (let attempt = 1; attempt <= 3; attempt++) { + usedModel = attempt === 3 ? bump(baseModel) : baseModel + let parsed: ExecResult | null = null + try { + parsed = validateExec(await runChild(`exec:${chunk.id}#${attempt}`, usedModel, execPrompt(args, chunk, extra))) + } catch { + parsed = null + } + last = parsed + if (parsed && parsed.status === "done") { + return { chunkId: chunk.id, ok: true, attempts: attempt, model: usedModel, result: parsed } + } + const why = parsed ? parsed.blocker || parsed.summary : "no parsable result block (retrying)" + extra = `Attempt ${attempt} did not complete. Reported blocker: ${why}\nClarify the success criteria and address this blocker directly.` + } + return { + chunkId: chunk.id, + ok: false, + attempts: 3, + model: usedModel, + result: last, + blocker: last ? last.blocker || last.summary : "no result after 3 attempts", + } + } + + const toolReg = await ctx.tool.transform((editor) => { + editor.add({ + name: "orchestrate_build", + description: + "Execute an approved chunk plan in dependency waves with per-chunk failure escalation, then review executed chunks and auto-fix blockers (cap 2). Returns structured findings {perChunk, clean, concerns, unresolvedBlockers, nits, skipped, unassigned, filesChanged} for the calling skill to gate on.", + input: { + type: "object", + properties: { + description: { type: "string", description: "the user's feature description" }, + plan: { type: "string", description: "the agreed implementation plan (markdown)" }, + testsRequired: { type: "boolean", description: "whether the project requires tests to pass" }, + waves: { + type: "array", + description: "dependency-ordered waves; chunks within a wave run in parallel, waves run serially", + items: { type: "array", items: { type: "object" } }, + }, + }, + required: ["description", "plan", "testsRequired", "waves"], + additionalProperties: false, + }, + execute: async (input: unknown) => { + const args = normalizeArgs(input) + const allChunks = args.waves.flat() + const findChunk = (id: string) => allChunks.find((c) => c.id === id) + + // --- Execute: waves serially, chunks in parallel (capped) --- + const execByChunk = new Map<string, ExecAttempt>() + const skipped: { chunkId: string; reason: string }[] = [] + const notOk = new Set<string>() + const priorIds: string[] = [] + for (let w = 0; w < args.waves.length; w++) { + const wave = args.waves[w] + const plan = planWave(w, wave, priorIds, notOk) + for (const s of plan.skipped) notOk.add(s.chunkId) + skipped.push(...plan.skipped) + const results = await semaphore(CONCURRENCY, plan.runnable.map((chunk) => () => executeChunk(args, chunk))) + for (const r of results) { + execByChunk.set(r.chunkId, r) + if (!r.ok) notOk.add(r.chunkId) + } + for (const c of wave) priorIds.push(c.id) + } + + // --- Review + blocker auto-fix loop (cap 2) --- + const allUnassigned: Finding[] = [] + const reviewChunks = async (ids: string[]): Promise<Finding[]> => { + const warranted = ids.filter((id) => findChunk(id)?.opusReview) + const tasks: (() => Promise<Finding[]>)[] = ids.map((id) => async () => { + const exec = execByChunk.get(id) + const parsed = validateReview( + await runChild( + `review:${id}`, + "sonnet", + reviewPrompt(args, findChunk, (rid) => (rid === id ? { summary: exec?.result?.summary, ok: exec?.ok, attempts: exec?.attempts } : undefined), id), + ), + ) + return (parsed ?? []).map((f) => ({ ...f, chunkId: id })) // reviewer is scoped to one chunk + }) + if (warranted.length) { + tasks.push(async () => { + const parsed = validateReview(await runChild("review:opus", "opus", opusReviewPrompt(args, findChunk, warranted))) + return parsed ?? [] + }) + } + const merged = (await semaphore(CONCURRENCY, tasks)).flat() + // Findings naming an unknown chunk id cannot be re-dispatched; + // set them aside and surface them in the result (workflow parity). + const split = splitFindings(merged, ids) + allUnassigned.push(...split.unassigned) + return split.assigned + } + + let findings = await reviewChunks([...execByChunk.keys()]) + + let iteration = 0 + while (findings.some((f) => f.severity === "blocker") && iteration < MAX_REVIEW_ITERS) { + iteration++ + const blockerIds = [...new Set(findings.filter((f) => f.severity === "blocker").map((f) => f.chunkId))].filter((id) => findChunk(id)) + await semaphore( + CONCURRENCY, + blockerIds.map((id) => async () => { + const chunk = findChunk(id)! + const fb = findings + .filter((f) => f.chunkId === id && f.severity === "blocker") + .map((f) => `- ${f.title}${f.detail ? ": " + f.detail : ""}${f.file ? " (" + f.file + ")" : ""}`) + .join("\n") + const r = await executeChunk(args, chunk, `A reviewer flagged blocking issues with your earlier implementation:\n${fb}\nFix these specifically.`) + execByChunk.set(r.chunkId, r) + }), + ) + // Re-review ONLY the re-dispatched chunks; clean chunks' findings stand. + const reFindings = await reviewChunks(blockerIds) + findings = findings.filter((f) => !blockerIds.includes(f.chunkId)).concat(reFindings) + } + + const blockers = findings.filter((f) => f.severity === "blocker") + const concerns = findings.filter((f) => f.severity === "concern") + const nits = findings.filter((f) => f.severity === "nit") + const filesChanged = [...new Set([...execByChunk.values()].flatMap((r) => r.result?.filesChanged ?? []))] + const flaggedIds = new Set(findings.map((f) => f.chunkId)) + + return { + content: JSON.stringify( + { + iterations: iteration, + hitReviewCap: blockers.length > 0, + perChunk: [...execByChunk.values()].map((r) => ({ + chunkId: r.chunkId, + ok: r.ok, + attempts: r.attempts, + model: r.model, + summary: r.result?.summary ?? null, + testsPassed: r.result?.testsPassed, + blocker: r.ok ? undefined : r.blocker, + })), + skipped, + unassigned: allUnassigned, + filesChanged, + clean: [...execByChunk.keys()].filter((id) => !flaggedIds.has(id)), + unresolvedBlockers: blockers, + concerns, + nits, + }, + null, + 2, + ), + } + }, + }) + }) + + // Slash doors for the session skills (OpenCode skills take no slash + // arguments; the command forwards them through the prompt). + const doors = ["session-start", "session-issue", "session-end", "session-orchestrate", "session-summarize"] + const commandReg = await ctx.command.transform((editor) => { + for (const skill of doors) { + editor.add({ + name: skill, + description: `Run the ${skill} workflow`, + execute: async ({ sessionID, prompt, delivery }) => { + await ctx.session.prompt({ + ...prompt, + sessionID, + delivery, + text: + `Load the \`${skill}\` skill with the skill tool and follow it exactly.\n\n` + + `Invocation arguments (may be empty):\n${prompt.text || "(none)"}`, + }) + }, + }) + } + }) + + return () => { + void toolReg.dispose() + void commandReg.dispose() + } + }, }) diff --git a/plugins-opencode/session/src/orchestrate-core.ts b/plugins-opencode/session/src/orchestrate-core.ts new file mode 100644 index 0000000..2ee0bb5 --- /dev/null +++ b/plugins-opencode/session/src/orchestrate-core.ts @@ -0,0 +1,276 @@ +// orchestrate-core.ts — the deterministic logic of the Claude +// `orchestrate-build.workflow.js`, ported to run inside the OpenCode plugin +// tool. Pure functions only (no ctx, no I/O) so the wave/dependency/parse/ +// review semantics are unit-testable; the plugin part supplies the session +// mechanics (create/prompt/wait/context/remove). + +export type Tier = "haiku" | "sonnet" | "opus" +const TIERS: Tier[] = ["haiku", "sonnet", "opus"] +export const bump = (m: Tier): Tier => TIERS[Math.min(TIERS.indexOf(m) + 1, TIERS.length - 1)] + +export type Chunk = { + id: string + scope: string + files?: string[] + model?: Tier + tests?: boolean + testScope?: string + opusReview?: boolean + dependsOn?: string[] +} + +export type OrchestrateArgs = { + description: string + plan: string + testsRequired: boolean + waves: Chunk[][] +} + +export function normalizeArgs(raw: unknown): OrchestrateArgs { + const a = raw as OrchestrateArgs + if (!a || !Array.isArray(a.waves) || a.waves.length === 0) { + throw new Error("orchestrate_build: args.waves must be a non-empty array of chunk arrays") + } + for (const wave of a.waves) if (!Array.isArray(wave)) throw new Error("orchestrate_build: each wave must be an array of chunks") + // Unknown tiers would make bump() downgrade (indexOf -1 → haiku); default to sonnet. + for (const c of a.waves.flat()) if (!TIERS.includes(c.model as Tier)) c.model = "sonnet" + return a +} + +// --- exec/review result shapes (mirror the Claude workflow's schemas) -------- + +export type ExecResult = { + status: "done" | "blocked" + summary: string + filesChanged?: string[] + testsPassed?: boolean + blocker?: string +} + +export type Finding = { + chunkId: string + severity: "blocker" | "concern" | "nit" + title: string + detail?: string + file?: string + line?: number +} + +export function validateExec(obj: unknown): ExecResult | null { + if (typeof obj !== "object" || obj === null) return null + const o = obj as Record<string, unknown> + if (o.status !== "done" && o.status !== "blocked") return null + if (typeof o.summary !== "string") return null + const r: ExecResult = { status: o.status, summary: o.summary } + if (Array.isArray(o.filesChanged)) r.filesChanged = o.filesChanged.filter((f): f is string => typeof f === "string") + if (typeof o.testsPassed === "boolean") r.testsPassed = o.testsPassed + if (typeof o.blocker === "string") r.blocker = o.blocker + return r +} + +export function validateReview(obj: unknown): Finding[] | null { + if (typeof obj !== "object" || obj === null) return null + const o = obj as Record<string, unknown> + if (!Array.isArray(o.findings)) return null + const out: Finding[] = [] + for (const f of o.findings as unknown[]) { + if (typeof f !== "object" || f === null) return null + const x = f as Record<string, unknown> + if (typeof x.chunkId !== "string") return null + if (x.severity !== "blocker" && x.severity !== "concern" && x.severity !== "nit") return null + if (typeof x.title !== "string") return null + const finding: Finding = { chunkId: x.chunkId, severity: x.severity, title: x.title } + if (typeof x.detail === "string") finding.detail = x.detail + if (typeof x.file === "string") finding.file = x.file + if (typeof x.line === "number") finding.line = x.line + out.push(finding) + } + return out +} + +// --- output-block extraction -------------------------------------------------- +// Children are instructed to end with a fenced ```json block. Parsing free +// text is fragile: "no/invalid block" is a RETRY TRIGGER, never a silent pass. +export function extractLastJsonBlock(text: string): unknown { + const fence = /```json[ \t]*\r?\n([\s\S]*?)```/g + let last: string | null = null + for (let m = fence.exec(text); m !== null; m = fence.exec(text)) last = m[1] + if (last === null) return null + try { + return JSON.parse(last) + } catch { + return null + } +} + +// --- prompts (ported verbatim from the workflow script) ----------------------- + +export const OUTPUT_INSTRUCTION = (schema: object) => + `\n\nEnd your FINAL message with exactly one fenced \`\`\`json block containing the result object matching this JSON schema (no trailing prose after the block):\n${JSON.stringify(schema, null, 2)}` + +export const EXEC_SCHEMA = { + type: "object", + required: ["status", "summary"], + properties: { + status: { type: "string", enum: ["done", "blocked"] }, + summary: { type: "string", description: "Concise description of what was changed" }, + filesChanged: { type: "array", items: { type: "string" } }, + testsPassed: { type: "boolean", description: "true if tests were run and passed, false if run and failed; omit if not applicable" }, + blocker: { type: "string", description: "If status=blocked, describe the blocker precisely" }, + }, +} as const + +export const REVIEW_SCHEMA = { + type: "object", + required: ["findings"], + properties: { + findings: { + type: "array", + items: { + type: "object", + required: ["chunkId", "severity", "title"], + properties: { + chunkId: { type: "string" }, + severity: { type: "string", enum: ["blocker", "concern", "nit"] }, + title: { type: "string" }, + detail: { type: "string" }, + file: { type: "string" }, + line: { type: "integer" }, + }, + }, + }, + }, +} as const + +export function execPrompt(args: OrchestrateArgs, chunk: Chunk, extra?: string): string { + const lines = [ + `You are implementing ONE chunk of an approved feature plan. Stay strictly within this chunk's scope.`, + ``, + `## Feature`, + args.description, + ``, + `## Agreed plan (context — do not re-litigate)`, + args.plan, + ``, + `## Your chunk: ${chunk.id}`, + `Scope: ${chunk.scope}`, + `Files you own: ${(chunk.files || []).join(", ") || "(determine from scope; touch nothing owned by other chunks)"}`, + chunk.tests + ? `Tests: write/update tests for this chunk. ${chunk.testScope || ""}`.trim() + : args.testsRequired + ? `Tests: ensure existing tests still pass; you need not add new ones.` + : `Tests: this project has no test suite requirement.`, + ``, + `## Rules`, + `- Implement only this chunk. Do NOT modify files owned by other chunks.`, + `- Follow existing codebase conventions: naming, file layout, imports, idioms.`, + args.testsRequired ? `- Run the relevant tests/lint before reporting status="done".` : null, + `- If you cannot complete it, set status="blocked" and describe the blocker precisely — do not guess or fake completion.`, + extra ? `\n## Context for this attempt\n${extra}` : null, + ] + return lines.filter((l) => l !== null).join("\n") + OUTPUT_INSTRUCTION(EXEC_SCHEMA) +} + +export function reviewPrompt( + args: OrchestrateArgs, + findChunk: (id: string) => Chunk | undefined, + execSummary: (id: string) => { summary?: string; ok?: boolean; attempts?: number } | undefined, + id: string, +): string { + const chunk = findChunk(id) + const exec = execSummary(id) + const lines = [ + `Review the implementation of ONE chunk for correctness, convention compliance, and spec adherence. You may read files and run tests/lint. Do NOT modify code.`, + ``, + `## Feature`, + args.description, + ``, + `## Chunk under review: ${id}`, + `Scope: ${chunk?.scope ?? "(unknown chunk)"}`, + `Files: ${(chunk?.files || []).join(", ")}`, + `Implementer reported: ${exec?.summary ?? "(no summary)"}`, + exec && exec.ok === false ? `NOTE: the implementer reported this chunk as BLOCKED/incomplete after ${exec.attempts} attempts.` : null, + ``, + `## Check`, + `- Codebase conventions: naming, file layout, imports, idioms`, + args.testsRequired ? `- Tests pass; lint/type checks are clean` : `- (no test suite required for this project)`, + `- Spec compliance: does it implement what the chunk asked for?`, + `- Pitfalls: error paths, null/empty handling, dead code, stale TODOs, leftover debug output`, + `- No regressions in unrelated code`, + ``, + `Tag each finding's severity: "blocker" (broken/wrong/tests fail — must fix), "concern" (should consider), "nit" (trivial). Set chunkId="${id}" on every finding. Return an empty findings array if clean.`, + ] + return lines.filter((l) => l !== null).join("\n") + OUTPUT_INSTRUCTION(REVIEW_SCHEMA) +} + +export function opusReviewPrompt(args: OrchestrateArgs, findChunk: (id: string) => Chunk | undefined, ids: string[]): string { + const lines = [ + `Senior correctness/security review of the following chunks ONLY. Read the code and reason hard about edge cases, concurrency, data integrity, auth, and security. Do NOT modify code.`, + ``, + `## Feature`, + args.description, + ``, + `## Chunks in scope`, + ...ids.map((id) => { + const c = findChunk(id) + return `- ${id}: ${c?.scope ?? "?"} [${(c?.files || []).join(", ")}]` + }), + ``, + `Tag findings blocker/concern/nit and set chunkId to the relevant chunk. Empty findings array if clean.`, + ] + return lines.filter((l) => l !== null).join("\n") + OUTPUT_INSTRUCTION(REVIEW_SCHEMA) +} + +// --- wave/dependency planning (pure; the executor runs the plan) -------------- + +export type WavePlan = { wave: number; runnable: Chunk[]; skipped: { chunkId: string; reason: string }[] } + +// Mirror of the workflow's skip logic: a chunk is skipped when any dependency +// (explicit dependsOn, else all earlier-wave chunks) already failed/was +// skipped. `notOk` is the transitive poison set maintained by the executor. +export function planWave(waveIndex: number, wave: Chunk[], priorIds: string[], notOk: Set<string>): WavePlan { + const runnable: Chunk[] = [] + const skipped: { chunkId: string; reason: string }[] = [] + for (const chunk of wave) { + const deps = Array.isArray(chunk.dependsOn) ? chunk.dependsOn : priorIds + const bad = deps.filter((d) => notOk.has(d)) + if (bad.length) skipped.push({ chunkId: chunk.id, reason: `dependency failed: ${bad.join(", ")}` }) + else runnable.push(chunk) + } + return { wave: waveIndex, runnable, skipped } +} + +export function dedupeFindings(findings: Finding[]): Finding[] { + const seen = new Set<string>() + const out: Finding[] = [] + for (const f of findings) { + const key = `${f.chunkId}|${f.severity}|${f.file || ""}|${f.line ?? ""}|${(f.title || "").toLowerCase().slice(0, 60)}` + if (seen.has(key)) continue + seen.add(key) + out.push(f) + } + return out +} + +export function splitFindings(findings: Finding[], reviewedIds: string[]) { + const known = new Set(reviewedIds) + const assigned: Finding[] = [] + const unassigned: Finding[] = [] + for (const f of findings) (known.has(f.chunkId) ? assigned : unassigned).push(f) + return { assigned: dedupeFindings(assigned), unassigned } +} + +// --- small concurrency helper -------------------------------------------------- + +export async function semaphore<T>(limit: number, tasks: (() => Promise<T>)[]): Promise<T[]> { + const results: T[] = new Array(tasks.length) + let next = 0 + const workers = Array.from({ length: Math.min(limit, tasks.length) }, async () => { + for (let i = next++; i < tasks.length; i = next++) { + if (i >= tasks.length) break + results[i] = await tasks[i]() + } + }) + await Promise.all(workers) + return results +} diff --git a/tests/opencode/test-session-core.mjs b/tests/opencode/test-session-core.mjs new file mode 100644 index 0000000..8afd4bb --- /dev/null +++ b/tests/opencode/test-session-core.mjs @@ -0,0 +1,234 @@ +// test-session-core.mjs — unit tests for orchestrate-core.ts: the pure +// wave/dependency/parse/review logic of the ported build workflow. Run via +// test-session-core.sh (needs node >= 23 for TS type stripping). +import assert from "node:assert/strict" +import path from "node:path" + +const repo = path.resolve(import.meta.dirname, "../..") +const core = await import(path.join(repo, "plugins-opencode/session/src/orchestrate-core.ts")) + +let pass = 0 +let fail = 0 +const t = async (label, fn) => { + try { + await fn() + console.log(` \x1b[32m✓\x1b[0m ${label}`) + pass++ + } catch (err) { + console.log(` \x1b[31m✗\x1b[0m ${label} (${err.message})`) + fail++ + } +} + +// --- tier bump --------------------------------------------------------------- + +await t("bump walks up and clamps at opus", () => { + assert.equal(core.bump("haiku"), "sonnet") + assert.equal(core.bump("sonnet"), "opus") + assert.equal(core.bump("opus"), "opus") +}) + +// --- normalizeArgs ------------------------------------------------------------- + +await t("normalizeArgs rejects empty/missing waves", () => { + assert.throws(() => core.normalizeArgs({}), /non-empty/) + assert.throws(() => core.normalizeArgs({ waves: [] }), /non-empty/) + assert.throws(() => core.normalizeArgs({ waves: "x" }), /non-empty/) + assert.throws(() => core.normalizeArgs(null), /non-empty/) +}) + +await t("normalizeArgs rejects non-array waves", () => { + assert.throws(() => core.normalizeArgs({ waves: [{ id: "c1" }] }), /must be an array/) +}) + +await t("normalizeArgs defaults unknown tiers to sonnet", () => { + const args = core.normalizeArgs({ + description: "d", + plan: "p", + testsRequired: false, + waves: [[{ id: "c1", scope: "s", model: "gpt-999" }, { id: "c2", scope: "s", model: "haiku" }]], + }) + assert.equal(args.waves[0][0].model, "sonnet") + assert.equal(args.waves[0][1].model, "haiku") +}) + +// --- extractLastJsonBlock -------------------------------------------------------- + +await t("extractLastJsonBlock parses a trailing json fence", () => { + const out = core.extractLastJsonBlock('prose\n```json\n{"status":"done","summary":"ok"}\n```\n') + assert.deepEqual(out, { status: "done", summary: "ok" }) +}) + +await t("extractLastJsonBlock takes the LAST block when several exist", () => { + const out = core.extractLastJsonBlock('```json\n{"n":1}\n```\nmid\n```json\n{"n":2}\n```') + assert.deepEqual(out, { n: 2 }) +}) + +await t("extractLastJsonBlock returns null on missing or invalid block (retry trigger)", () => { + assert.equal(core.extractLastJsonBlock("no fence here"), null) + assert.equal(core.extractLastJsonBlock("```json\n{not json}\n```"), null) + assert.equal(core.extractLastJsonBlock(""), null) +}) + +await t("extractLastJsonBlock tolerates trailing spaces after the fence tag", () => { + const out = core.extractLastJsonBlock('```json \n{"a":1}\n```') + assert.deepEqual(out, { a: 1 }) +}) + +// --- validateExec / validateReview ------------------------------------------------- + +await t("validateExec accepts done and blocked, coerces junk fields away", () => { + assert.deepEqual(core.validateExec({ status: "done", summary: "s" }), { status: "done", summary: "s" }) + const r = core.validateExec({ status: "blocked", summary: "s", blocker: "b", filesChanged: ["a", 7], testsPassed: false }) + assert.deepEqual(r, { status: "blocked", summary: "s", filesChanged: ["a"], testsPassed: false, blocker: "b" }) +}) + +await t("validateExec rejects malformed objects", () => { + assert.equal(core.validateExec(null), null) + assert.equal(core.validateExec("str"), null) + assert.equal(core.validateExec({ status: "done" }), null) // no summary + assert.equal(core.validateExec({ status: "meh", summary: "s" }), null) + assert.equal(core.validateExec({ status: "done", summary: 42 }), null) +}) + +await t("validateReview accepts well-formed findings incl. empty list", () => { + assert.deepEqual(core.validateReview({ findings: [] }), []) + const fs = core.validateReview({ + findings: [{ chunkId: "c1", severity: "blocker", title: "t", detail: "d", file: "f.ts", line: 3 }], + }) + assert.deepEqual(fs, [{ chunkId: "c1", severity: "blocker", title: "t", detail: "d", file: "f.ts", line: 3 }]) +}) + +await t("validateReview rejects malformed findings", () => { + assert.equal(core.validateReview({}), null) + assert.equal(core.validateReview({ findings: "x" }), null) + assert.equal(core.validateReview({ findings: [{ chunkId: "c1", severity: "critical", title: "t" }] }), null) + assert.equal(core.validateReview({ findings: [{ severity: "nit", title: "t" }] }), null) +}) + +// --- planWave (dependency skip) ----------------------------------------------------- + +const chunk = (id, extra) => ({ id, scope: id, ...extra }) + +await t("planWave: implicit deps on all prior chunks; skips on any failure", () => { + const plan = core.planWave(1, [chunk("c3"), chunk("c4", { dependsOn: ["c2"] })], ["c1", "c2"], new Set(["c1"])) + assert.deepEqual( + plan.runnable.map((c) => c.id), + ["c4"], + ) + assert.deepEqual(plan.skipped, [{ chunkId: "c3", reason: "dependency failed: c1" }]) +}) + +await t("planWave: explicit dependsOn overrides implicit prior-wave deps", () => { + // c3 explicitly depends only on c2; c1's failure must not skip it + const plan = core.planWave(1, [chunk("c3", { dependsOn: ["c2"] })], ["c1", "c2"], new Set(["c1"])) + assert.deepEqual( + plan.runnable.map((c) => c.id), + ["c3"], + ) + assert.equal(plan.skipped.length, 0) +}) + +await t("planWave: all runnable when nothing failed", () => { + const plan = core.planWave(0, [chunk("c1"), chunk("c2")], [], new Set()) + assert.equal(plan.runnable.length, 2) + assert.equal(plan.skipped.length, 0) +}) + +await t("planWave: transitive poison via executor-set notOk", () => { + // wave2 c5 depends on c3 which was itself skipped (executor adds skips to notOk) + const plan = core.planWave(2, [chunk("c5", { dependsOn: ["c3"] })], ["c1", "c2", "c3"], new Set(["c3"])) + assert.equal(plan.runnable.length, 0) + assert.match(plan.skipped[0].reason, /dependency failed: c3/) +}) + +// --- findings --------------------------------------------------------------------- + +const finding = (chunkId, severity, title, extra) => ({ chunkId, severity, title, ...extra }) + +await t("dedupeFindings collapses identical (chunk,severity,file,line,title-prefix)", () => { + const out = core.dedupeFindings([ + finding("c1", "blocker", "Null deref", { file: "a.ts", line: 3 }), + finding("c1", "blocker", "NULL DEREF", { file: "a.ts", line: 3 }), // case-insensitive title + finding("c1", "blocker", "Null deref", { file: "a.ts", line: 4 }), // different line + ]) + assert.equal(out.length, 2) +}) + +await t("splitFindings separates known-chunk from unassigned and dedupes assigned", () => { + const { assigned, unassigned } = core.splitFindings( + [finding("c1", "nit", "a"), finding("c1", "nit", "a"), finding("cX", "concern", "b")], + ["c1", "c2"], + ) + assert.equal(assigned.length, 1) + assert.equal(unassigned.length, 1) + assert.equal(unassigned[0].chunkId, "cX") +}) + +// --- semaphore ---------------------------------------------------------------------- + +await t("semaphore runs all tasks and preserves result order", async () => { + const tasks = Array.from({ length: 9 }, (_, i) => async () => { + await Promise.resolve() + return i * 2 + }) + assert.deepEqual(await core.semaphore(4, tasks), [0, 2, 4, 6, 8, 10, 12, 14, 16]) +}) + +await t("semaphore caps concurrency at the limit", async () => { + let live = 0 + let max = 0 + const tasks = Array.from({ length: 12 }, () => async () => { + live++ + max = Math.max(max, live) + await new Promise((r) => setTimeout(r, 5)) + live-- + return true + }) + await core.semaphore(3, tasks) + assert.ok(max <= 3, `observed concurrency ${max} > 3`) +}) + +await t("semaphore with fewer tasks than slots still completes", async () => { + assert.deepEqual(await core.semaphore(8, [async () => 1, async () => 2]), [1, 2]) + assert.deepEqual(await core.semaphore(4, []), []) +}) + +// --- prompts --------------------------------------------------------------------------- + +const args = { description: "add widgets", plan: "# plan", testsRequired: true, waves: [[chunk("c1", { scope: "widget api", files: ["w.ts"], tests: true })]] } +const findChunk = (id) => args.waves.flat().find((c) => c.id === id) + +await t("execPrompt carries feature, plan, chunk scope, files, and the output contract", () => { + const p = core.execPrompt(args, findChunk("c1")) + assert.match(p, /add widgets/) + assert.match(p, /# plan/) + assert.match(p, /Your chunk: c1/) + assert.match(p, /widget api/) + assert.match(p, /w\.ts/) + assert.match(p, /```json block/) + assert.match(p, /status.*done.*blocked/s) +}) + +await t("execPrompt appends attempt context when retrying", () => { + const p = core.execPrompt(args, findChunk("c1"), "Attempt 1 failed: build broke") + assert.match(p, /Context for this attempt/) + assert.match(p, /build broke/) +}) + +await t("reviewPrompt notes blocked implementations", () => { + const p = core.reviewPrompt(args, findChunk, () => ({ summary: "stuck", ok: false, attempts: 3 }), "c1") + assert.match(p, /Chunk under review: c1/) + assert.match(p, /reported this chunk as BLOCKED/) + assert.match(p, /stuck/) +}) + +await t("opusReviewPrompt lists all in-scope chunks", () => { + const p = core.opusReviewPrompt(args, findChunk, ["c1", "c9"]) + assert.match(p, /c1: widget api/) + assert.match(p, /c9: \?/) +}) + +console.log("") +console.log(`Total: ${pass + fail} PASS: ${pass} FAIL: ${fail}`) +process.exit(fail === 0 ? 0 : 1) diff --git a/tests/opencode/test-session-core.sh b/tests/opencode/test-session-core.sh new file mode 100644 index 0000000..c41bb5f --- /dev/null +++ b/tests/opencode/test-session-core.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# test-session-core.sh — run the session orchestrate-core node unit tests. +# Requires a node that can import .ts directly (node >= 23 with type +# stripping). Skips with a note on older runtimes, mirroring +# test-inbox-core.sh. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" + +if ! node --version | grep -qE 'v(2[3-9]|[3-9][0-9])'; then + if [[ -n "${CI:-}" ]]; then + echo "node >= 23 required for TS type stripping and CI is set — refusing to skip" >&2 + exit 1 + fi + echo "node >= 23 required — skipping session core tests" >&2 + exit 0 +fi + +exec node "$SCRIPT_DIR/test-session-core.mjs" "$@" diff --git a/tests/opencode/test-session-port.sh b/tests/opencode/test-session-port.sh new file mode 100644 index 0000000..710703e --- /dev/null +++ b/tests/opencode/test-session-port.sh @@ -0,0 +1,146 @@ +#!/usr/bin/env bash +# test-session-port.sh — the OpenCode session port stays faithful to the +# Claude original. The ported SKILL.md files must equal +# utils/opencode-port.py(Claude original) — so any upstream edit to a Claude +# skill that isn't re-ported (or a mapping bug) fails here. Vendored scripts +# must be byte-identical to utils/; the rendered spine must match what +# sync.sh produces; no Claude-harness leakage anywhere. +# +# Usage: bash tests/opencode/test-session-port.sh [filter] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)" +REPO="$SCRIPT_DIR/.." +CLAUDE="$REPO/plugins-claude/session" +OC="$REPO/plugins-opencode/session" +PORTER="$REPO/utils/opencode-port.py" + +PASS=0 +FAIL=0 +FILTER="${1:-}" + +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +pass() { + printf " \033[32m✓\x1b[0m %s\n" "$1" + ((PASS++)) || true +} +fail() { + printf " \033[31m✗\x1b[0m %s (%s)\n" "$1" "$2" + ((FAIL++)) || true +} +t2() { + local label="$1" + shift + if [[ -n "$FILTER" ]] && ! echo "$label" | grep -qi "$FILTER"; then return; fi + if "$@" >/dev/null 2>&1; then pass "$label"; else fail "$label" "assertion failed: $*"; fi +} + +SKILLS="session-start session-issue session-end session-orchestrate session-summarize" + +# --- no Claude harness leakage in the whole opencode session tree ------------ +for pat in CLAUDE_PLUGIN_ROOT EnterWorktree ExitWorktree EnterPlanMode AskUserQuestion subagent_type '\$ARGUMENTS' '/session:' '/git-tools:' 'allowed-tools:' Workflow; do + t2 "no leakage: $pat" sh -c "! grep -rq -- '$pat' '$OC/skills' '$OC/src'" +done + +# --- ported skills == porter(Claude original) --------------------------------- +# The porter strips `allowed-tools:` frontmatter lines, applies the harness +# mapping, then applies its $ARGUMENTS rewrites. Reproduce that pipeline here +# from the CURRENT Claude originals: if someone edits a Claude skill and +# forgets to re-run utils/port-session-skills.py, this comparison breaks. +for skill in $SKILLS; do + src="$CLAUDE/skills/$skill/SKILL.md" + dst="$OC/skills/$skill/SKILL.md" + t2 "$skill exists in port" test -s "$dst" + # frontmatter: name + description present, no allowed-tools + awk '/^---$/{n++; next} n==1' "$dst" >"$TMP/fm" + t2 "$skill frontmatter has name" grep -q '^name: ' "$TMP/fm" + t2 "$skill frontmatter has description" grep -q '^description: ' "$TMP/fm" + t2 "$skill frontmatter drops allowed-tools" sh -c "! grep -q 'allowed-tools' '$TMP/fm'" +done + +# full-file fidelity: run the porter's own pipeline via port-session-skills.py +# in a sandbox (it writes to the real tree; we diff against the committed tree +# instead by rendering each original through the same functions). +python3 - "$REPO" "$TMP" <<'PYEOF' +import re, sys +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path + +repo, tmp = Path(sys.argv[1]), Path(sys.argv[2]) +spec = spec_from_file_location("psp", repo / "utils" / "port-session-skills.py") +# exec-ing the module would rewrite the tree; instead import its tables only. +src = (repo / "utils" / "port-session-skills.py").read_text() +ns = {} +# grab ARG_REWRITES + strip_frontmatter_line without running the port loop +head = src.split("for skill in SKILLS:")[0] +ns = {"__file__": str(repo / "utils" / "port-session-skills.py")} +exec(compile(head, "port-session-skills.py", "exec"), ns) +render, ARG_REWRITES, strip = ns["render"], ns["ARG_REWRITES"], ns["strip_frontmatter_line"] + +for skill in ns["SKILLS"]: + text = strip((repo / "plugins-claude/session/skills" / skill / "SKILL.md").read_text(), "allowed-tools") + text = render(text) + for old, new in ARG_REWRITES.get(skill, []): + text = text.replace(old, new) + (tmp / f"{skill}.expected").write_text(text) +PYEOF +for skill in $SKILLS; do + if diff -q "$TMP/$skill.expected" "$OC/skills/$skill/SKILL.md" >/dev/null 2>&1; then + pass "$skill matches porter output (up to date)" + else + fail "$skill matches porter output (up to date)" "re-run utils/port-session-skills.py — diff: $(diff "$TMP/$skill.expected" "$OC/skills/$skill/SKILL.md" | head -4)" + fi +done + +# --- vendored scripts byte-identical to canonical utils/ ---------------------- +declare -A VENDORS=( + ["session-start"]="git-wait branch" + ["session-issue"]="git-wait branch" + ["session-end"]="git-wait sitrep" + ["session-summarize"]="sitrep" + ["session-orchestrate"]="git-wait sitrep" +) +for skill in $SKILLS; do + for util in ${VENDORS[$skill]}; do + t2 "$skill vendors $util byte-identical" cmp -s "$REPO/utils/$util" "$OC/skills/$skill/scripts/$util" + done +done + +# --- rendered spine matches sync.sh's rendering of utils/spine.md -------------- +for skill in session-start session-issue; do + python3 "$PORTER" <"$REPO/utils/spine.md" >"$TMP/spine.rendered" + t2 "$skill spine.md matches opencode-port rendering" cmp -s "$TMP/spine.rendered" "$OC/skills/$skill/reference/spine.md" +done +# and the Claude copy stays byte-identical to the canonical +t2 "claude spine.md byte-identical to utils/spine.md" cmp -s "$REPO/utils/spine.md" "$CLAUDE/reference/spine.md" + +# --- harness mapping actually landed in the rendered spine ---------------------- +t2 "spine maps EnterWorktree → worktree_create" grep -q "opencode.worktree_create" "$OC/skills/session-start/reference/spine.md" +t2 "spine maps EnterPlanMode → plan agent" sh -c "! grep -q 'EnterPlanMode' '$OC/skills/session-start/reference/spine.md'" +t2 "spine maps rename-session → session_rename" grep -q "session_rename" "$OC/skills/session-start/reference/spine.md" +t2 "spine keeps git-wait usage (skill-relative)" grep -q "bash scripts/git-wait" "$OC/skills/session-start/reference/spine.md" + +# --- orchestrate skill points at the tool, not the Workflow script -------------- +t2 "orchestrate dispatches orchestrate_build" grep -q "orchestrate_build" "$OC/skills/session-orchestrate/SKILL.md" +t2 "orchestrate has no workflow-script path" sh -c "! grep -q 'orchestrate-build.workflow.js' '$OC/skills/session-orchestrate/SKILL.md'" +# all seven phases survived the port +for phase in "Phase 1" "Phase 2" "Phase 3" "Phase 4" "Phase 5" "Phase 6" "Phase 7"; do + t2 "orchestrate has $phase" grep -q "$phase" "$OC/skills/session-orchestrate/SKILL.md" +done + +# --- plugin package + sources ------------------------------------------------------ +t2 "package.json exports src/index.ts" sh -c "node -e ' + const p = require(\"$OC/package.json\"); + if (p.type !== \"module\") process.exit(1); + if (!p.exports || !p.exports[\".\"] || !p.exports[\".\"].includes(\"src/index.ts\")) process.exit(1); +'" +t2 "orchestrate-core.ts exists" test -s "$OC/src/orchestrate-core.ts" +t2 "index.ts registers orchestrate_build" grep -q '"orchestrate_build"' "$OC/src/index.ts" +t2 "index.ts registers the five door commands" sh -c "grep -q 'session-start.*session-issue.*session-end.*session-orchestrate.*session-summarize' '$OC/src/index.ts'" + +echo "" +echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" +[[ $FAIL -eq 0 ]] diff --git a/tests/opencode/test-sync.sh b/tests/opencode/test-sync.sh index d003bc3..00eea30 100644 --- a/tests/opencode/test-sync.sh +++ b/tests/opencode/test-sync.sh @@ -54,13 +54,16 @@ run() { S="$TMP/repo" mkdir -p "$S/utils" cp "$REPO/utils/sync.sh" "$S/utils/" -for util in inbox git-wait branch sitrep hook-compat.sh detect-schema.sh validate-frontmatter.sh; do +cp "$REPO/utils/opencode-port.py" "$S/utils/" +for util in inbox git-wait branch sitrep spine.md hook-compat.sh detect-schema.sh validate-frontmatter.sh; do cp "$REPO/utils/$util" "$S/utils/" done for p in format-on-save git-tools kb-capture inbox notify-on-stop session; do mkdir -p "$S/plugins-claude/$p" done -for p in git-tools/skills/git-wait git-tools/skills/ship inbox session; do +for p in git-tools/skills/git-wait git-tools/skills/ship inbox \ + session/skills/session-start session/skills/session-issue session/skills/session-end \ + session/skills/session-summarize session/skills/session-orchestrate; do mkdir -p "$S/plugins-opencode/$p" done @@ -87,6 +90,24 @@ check "claude session vendored branch" 0 "$RC" run cmp -s "$S/utils/sitrep" "$S/plugins-claude/session/scripts/sitrep" check "claude session vendored sitrep" 0 "$RC" +# util:dir syntax — spine.md lands in reference/, byte-identical for claude +run cmp -s "$S/utils/spine.md" "$S/plugins-claude/session/reference/spine.md" +check "claude session vendored spine.md into reference/ (util:dir)" 0 "$RC" + +# markdown for the opencode target is rendered through opencode-port.py: +# harness mapping applied, no Claude leakage, and NOT byte-identical +run cmp -s "$S/utils/spine.md" "$S/plugins-opencode/session/skills/session-start/reference/spine.md" +check "opencode spine.md is rendered (differs from canonical)" nonzero "$RC" +run grep -q "CLAUDE_PLUGIN_ROOT" "$S/plugins-opencode/session/skills/session-start/reference/spine.md" +check "rendered opencode spine.md has no CLAUDE_PLUGIN_ROOT" nonzero "$RC" +run grep -q "opencode.worktree_create" "$S/plugins-opencode/session/skills/session-start/reference/spine.md" +check "rendered opencode spine.md carries the harness mapping" 0 "$RC" +# nested manifest keys vendor into each skill's own dir +run cmp -s "$S/utils/git-wait" "$S/plugins-opencode/session/skills/session-start/scripts/git-wait" +check "session-start skill vendored git-wait (nested key)" 0 "$RC" +run test ! -e "$S/plugins-opencode/session/scripts/git-wait" +check "session plugin root no longer receives scripts (moved to skills)" 0 "$RC" + # --- --check clean after sync ------------------------------------------------ run sync --check check "--check clean after sync" 0 "$RC" "$OUT$ERR" @@ -111,10 +132,16 @@ fi # --- missing vendored file is drift -------------------------------------------- run sync -rm "$S/plugins-opencode/session/scripts/git-wait" +rm "$S/plugins-opencode/session/skills/session-start/scripts/git-wait" run sync --check check "--check fails on missing vendored file" nonzero "$RC" +# --- rendered markdown drift is detected too ------------------------------------- +run sync +echo "# tampered" >>"$S/plugins-opencode/session/skills/session-issue/reference/spine.md" +run sync --check +check "--check fails on rendered markdown drift" nonzero "$RC" + # --- missing canonical source is a hard error ----------------------------------- run sync rm "$S/utils/branch" diff --git a/utils/opencode-port.py b/utils/opencode-port.py new file mode 100644 index 0000000..901157e --- /dev/null +++ b/utils/opencode-port.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""opencode-port.py — render Claude-harness prose for the OpenCode harness. + +Single source of truth for the harness mapping, used by: + - utils/sync.sh, to render vendored markdown (spine.md) for the + plugins-opencode target, and + - the one-time skill port (tests/opencode/test-session-port.sh re-checks + the ported skills against `sync.sh`-style rendering of the originals). + +Ordered exact-string substitutions; longest/most specific first. Anything +not listed passes through unchanged — the port must be minimal and auditable. +The Claude target renders identity (sync.sh only calls this for opencode). +""" + +import sys + +SUBST = [ + # --- script paths: skill-relative (skill base dir is provided at load) --- + ( + '**Rename the session** (always, last — `rename-session` keys off the current\ndirectory, which `EnterWorktree` changes). Use the session name from Phase 0 step 3:\n\n```bash\nbash ${CLAUDE_PLUGIN_ROOT}/scripts/rename-session "<session-name>"\n```', + '**Rename the session** (always, last). Use the session name from Phase 0 step 3:\n\n```ts\n// Code Mode — no script, no ~/.claude writes\nawait tools.opencode.session_rename({ title: "<session-name>" })\n```', + ), + ("bash ${CLAUDE_PLUGIN_ROOT}/scripts/", "bash scripts/"), + ("${CLAUDE_PLUGIN_ROOT}/scripts/", "scripts/"), + ("${CLAUDE_PLUGIN_ROOT}/reference/", "reference/"), + # --- worktrees: EnterWorktree → opencode.worktree_* + session_move ------- + # ExitWorktree entries first: one block below contains `EnterWorktree`, + # which the generic mappings would rewrite before a later match could fire. + ( + 'call `ExitWorktree` with\n`action: "keep"` (see step 8), or switch to a valid directory such as the main\ncheckout.', + "move this session out with `opencode.session_move` (see step 8), or switch to a valid directory such as the main\ncheckout.", + ), + ( + 'If this session was entered with `EnterWorktree` and the worktree directory no\nlonger exists after `ship` (ship removes it with plain git), call `ExitWorktree`\nwith `action: "keep"` to reset the harness\'s session state (do this at the start\nof step 7 when that step has work to do). Never use `remove`\nor `discard` here; `ship` already removed the directory.', + "If this session was moved into a worktree with `opencode.worktree_create` and that\ndirectory no longer exists after `ship` (ship removes it with plain git), call\n`opencode.session_move` back to the main checkout to reset the session's working\ndirectory (do this at the start of step 7 when that step has work to do). Do not\nre-create or delete anything here; `ship` already removed the directory.", + ), + ("leave with `ExitWorktree`.", "remove it later with `opencode.worktree_remove`."), + ( + "or the user can leave it and exit later with `ExitWorktree`.", + "or the user can remove it later with `opencode.worktree_remove`.", + ), + ("`ExitWorktree`", "`opencode.worktree_remove`"), + ("ExitWorktree", "opencode.worktree_remove"), + ( + "This creates branch `worktree-<base-name>`, runs\n native provisioning, and switches the session into the worktree. Do **not** also\n run `branch create`.", + "This creates the worktree (with its own branch) and returns its\n directory; then move this session into it with `opencode.session_move`\n (Code Mode). Do **not** also run `branch create`.", + ), + ("`EnterWorktree` with `path`", "`opencode.session_move` with that `directory`"), + ( + "call `EnterWorktree` with `name` set to the base", + "call `opencode.worktree_create` with `name` set to the base", + ), + ("read at `EnterWorktree` time", "read at `worktree_create` time"), + ("`EnterWorktree` (Phase 1)", "`opencode.worktree_create` (Phase 1)"), + ("EnterWorktree", "opencode.worktree_create"), + # --- plan mode: EnterPlanMode → the built-in plan agent ------------------- + ( + "until you have called `EnterPlanMode` with a plan", + "until you have switched to the `plan` agent with a plan", + ), + ("short plan inside `EnterPlanMode`", "short plan inside the `plan` agent"), + ( + "Call `EnterPlanMode`, then present", + "Switch the session to the built-in `plan` agent, then present", + ), + ("`EnterPlanMode`", "the `plan` agent"), + # --- subagents: Agent + subagent_type → subagent tool + agent ------------- + ("`Agent` with `subagent_type: research`", "`subagent` tool with `agent: explore`"), + ("subagent_type: research", "agent: explore"), + ("subagent_type", "agent"), + # --- user gates: AskUserQuestion → the question tool ----------------------- + ("`AskUserQuestion`", "the `question` tool"), + ("AskUserQuestion", "the `question` tool"), + # --- orchestration: Claude Workflow primitive → session.orchestrate_build -- + # Order matters: the multi-line dispatch block must match the ORIGINAL + # text, so it precedes the generic ${CLAUDE_PLUGIN_ROOT} rewrites would + # have touched it — but those run earlier in this list, so match the + # already-path-rewritten form here. Phrase forms, then catch-all. + ( + "Call the `Workflow` tool with:\n - `scriptPath: scripts/orchestrate-build.workflow.js`\n - `args: <the object from step 2>` (pass it as an actual JSON value, not a stringified blob)", + "Call the `orchestrate_build` tool with:\n - `args: <the object from step 2>` (the same args contract the Claude workflow script took; pass it as an actual JSON value)", + ), + ( + "(`scripts/orchestrate-build.workflow.js`)", + "(implemented by the `agent-toolkit.session` plugin)", + ), + ("`scripts/orchestrate-build.workflow.js`", "the `agent-toolkit.session` plugin"), + ("`orchestrate-build.workflow.js`", "the `orchestrate_build` tool's schema"), + ("`Workflow` call", "`orchestrate_build` tool call"), + ("in a `Workflow`", "in the `orchestrate_build` tool"), + ("`Workflow` tool", "`orchestrate_build` tool"), + ( + "the build-and-verify `Workflow`", + "the build-and-verify `orchestrate_build` tool", + ), + ("the `Workflow`", "the `orchestrate_build` tool"), + ("The Workflow ", "orchestrate_build "), + ("the Workflow ", "orchestrate_build "), + ("a targeted Workflow", "a targeted orchestrate_build"), + ( + "You can watch progress via `/workflows`.", + "Progress arrives as each wave completes.", + ), + ("Workflow", "orchestrate_build"), + # --- slash-command doors: /plugin:name → skill id / command ----------------- + ("/session:session-", "session-"), + ("/git-tools:ship", "/ship"), +] + + +def render(text: str) -> str: + for old, new in SUBST: + text = text.replace(old, new) + return text + + +if __name__ == "__main__": + data = sys.stdin.read() + sys.stdout.write(render(data)) diff --git a/utils/port-session-skills.py b/utils/port-session-skills.py new file mode 100644 index 0000000..87b3f6e --- /dev/null +++ b/utils/port-session-skills.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""One-time port of the Claude session skills to plugins-opencode. + +Applies utils/opencode-port.py (the shared harness mapping), drops Claude-only +frontmatter, and rewrites the $ARGUMENTS sentences (OpenCode skills receive no +slash arguments; the registered command doors pass invocation text through +the prompt instead). Re-run after editing a Claude original, then review the +diff — tests/opencode/test-session-port.sh guards the result. +""" + +import re +import sys +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path + +_here = Path(__file__).parent +_spec = spec_from_file_location("opencode_port", _here / "opencode-port.py") +_mod = module_from_spec(_spec) +_spec.loader.exec_module(_mod) +render = _mod.render + +SRC = Path(__file__).parent.parent / "plugins-claude/session/skills" +DST = Path(__file__).parent.parent / "plugins-opencode/session/skills" + +SKILLS = [ + "session-start", + "session-issue", + "session-end", + "session-orchestrate", + "session-summarize", +] + +# $ARGUMENTS rewrites per skill (exact strings; OpenCode doors pass arguments +# through the invoking prompt, so skills speak of "the invocation arguments"). +ARG_REWRITES = { + "session-start": [ + ( + "1. The work comes from `$ARGUMENTS` (your description). If this skill was invoked by\n the model rather than a slash command, `$ARGUMENTS` is empty: use the work the user\n already described in the conversation as the description and do not re-ask. If\n `$ARGUMENTS` is empty and nothing was described, ask", + "1. The work comes from the arguments provided with the invocation (the `/session-start`\n command passes them through; your description). If this skill was invoked by\n the model rather than the command, no arguments were provided: use the work the user\n already described in the conversation as the description and do not re-ask. If\n there are no arguments and nothing was described, ask", + ), + ], + "session-issue": [ + ( + "2. **Issue numbers in `$ARGUMENTS`** (`#127 #125 #115`, `127 and 125`, `127,125`):", + "2. **Issue numbers in the invocation arguments** (`#127 #125 #115`, `127 and 125`, `127,125`):", + ), + ], + "session-orchestrate": [ + ( + "- `$ARGUMENTS` — optional initial description. If empty and no context inherited from `session-start`, ask the user to describe the feature before starting Phase 1.", + "- The invocation arguments — optional initial description. If absent and no context inherited from `session-start`, ask the user to describe the feature before starting Phase 1.", + ), + ( + "- Issue refs (`#N`) in `$ARGUMENTS` with no prior spine run in this session", + "- Issue refs (`#N`) in the invocation arguments with no prior spine run in this session", + ), + ], +} + + +def strip_frontmatter_line(text: str, key: str) -> str: + m = re.match(r"^(---\n.*?\n---\n)", text, re.S) + if not m: + return text + fm, rest = m.group(1), text[m.end() :] + fm = "\n".join(l for l in fm.splitlines() if not l.startswith(f"{key}:")) + "\n" + return fm + rest + + +for skill in SKILLS: + src = SRC / skill / "SKILL.md" + dst = DST / skill / "SKILL.md" + text = src.read_text() + text = strip_frontmatter_line(text, "allowed-tools") + text = render(text) + for old, new in ARG_REWRITES.get(skill, []): + if old not in text: + print( + f"WARN: {skill}: $ARGUMENTS rewrite not applied (text changed upstream?):\n {old[:80]}..." + ) + text = text.replace(old, new) + if "ARGUMENTS" in text: + print(f"WARN: {skill}: leftover $ARGUMENTS") + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(text) + print(f"ported: {dst.relative_to(DST.parent.parent)}") diff --git a/utils/spine.md b/utils/spine.md new file mode 100644 index 0000000..e26dce8 --- /dev/null +++ b/utils/spine.md @@ -0,0 +1,316 @@ +# Begin-work spine + +The shared playbook for the lightweight session entrypoints (`session-start` and +`session-issue`). Both doors differ only in **how the work is chosen** — once the +work is identified, they run these phases identically: resolve target → isolate → +explore → plan → build the approved scope. + +**Lightweight is the only flow here.** Do not ask "lightweight vs orchestrate", and +do not ask about worktree vs in-place, dependency symlinks, latency, or scope — +decide silently using the defaults below. Ask only when something is genuinely +ambiguous about **what to build** (the exceptions are the explicit prompts in Phase 0 +validation and Phase 1 collisions / dirty default branch). If the user asks for a +heavier multi-agent flow, mention once that `/session:session-orchestrate` exists and +invoke it; never raise it unprompted. + +> **CRITICAL**: You MUST drive this through to a plan. After the branch exists you +> explore and enter plan mode. NEVER print "suggested first steps" or ask "ready to +> start?" — the flow does not end until you have called `EnterPlanMode` with a plan +> built from real code exploration. +> +> **EQUALLY CRITICAL — the other end of the flow**: plan approval authorizes the +> whole stated scope, but the last unit is reviewed by the user before it ships. +> Implement each unit; land every unit before the last via `/git-tools:ship` and move +> on without stopping, then run the last unit through `/session:session-end` +> (Phase 4). The one deliberate stop is **before** that final ship: `session-end` +> summarizes the work and caveats and waits for the user's go. After the go it ships, +> watches CI, fixes and re-merges if needed, cleans up, and ends with a final-state +> summary. A one-PR session always pauses before its PR; a multi-PR scope pauses once, +> before the last PR. + +## Inputs (supplied by the calling door) + +- One of: **issue number(s)** (from `session-issue`, or `#N` references in a + `session-start` description or its related-issue lookup) or a **freeform + description**. +- Whether the door already knows the hosting `platform` (reuse it; never detect + twice). +- `continuing` (both doors determine it): **true** when the current branch is not the + default branch and has commits ahead of it or uncommitted work; otherwise false. + When true, skip Phase 1's Isolate steps and keep the current branch. + +If you reach this spine with neither issues nor a description, stop and return to +the calling door — it owns target selection. + +## Phase 0 — Resolve target + +Run this once, for both doors. + +1. **Fetch and validate issues** (skip for freeform work). Detect the platform once + unless the door already did, then fetch **every** referenced issue: + + ```bash + bash ${CLAUDE_PLUGIN_ROOT}/scripts/git-wait platform + ``` + + - **github:** `gh issue view <N> --json number,title,body,state,labels,comments` + - **gitea:** `tea issues <N> --output json` + + For anything beyond issue viewing (PR create, CI runs, state values), use the + command map in the `git-tools:git-wait` skill rather than guessing flags. + Keep each issue's title, body, and labels as context for the whole session. + + **Validate each issue.** If the fetch fails, the state is not open, or the number + is a pull request (not an issue), tell the user and either drop that number or + stop — ask which when it is not obvious. Also warn (and ask whether to proceed) + when an issue is already claimed: it appears in + `git config --get-regexp 'branch\..*\.session-issues'` or has an open PR. + +2. **Pick the branch type** from labels. Compare case-insensitively on the label's + **last path segment** (`kind/bug` and `Kind/Enhancement` match `bug` and + `enhancement`). With several issues, a `bug` label on any of them wins; otherwise + use the first issue's labels: + - `bug`, `fix` → `bug` + - `enhancement`, `feature`, `improvement` → `enhancement` + - `docs`, `chore`, `refactor`, `maintenance` → `chore` + - no matching label → `feature` + +3. **Name the work.** + - **Continuing** (`continuing` is true): do **not** build a new base name or + branch type. The session name is the current branch name with any leading + `worktree-` stripped. + - **Otherwise** build the base name: issue-linked `<type>-<slug>`; freeform + `wip-<slug>`. The slug is a kebab-case 3-5 word summary (of the first issue's + title, or the common theme when several issues are bundled; of the description + for freeform). The branch never encodes issue numbers — linkage is the closing + lines in the PR body. + + Actual branch names: created in place, the branch is `<base-name>`; created via + `EnterWorktree` (Phase 1), it is `worktree-<base-name>`. The session name is + `<base-name>`. + +4. **Closing lines.** One line per issue: `Fixes #N` for `bug` issues, `Closes #N` + otherwise. Phase 1 persists them. + +## Phase 1 — Isolate, record, rename + +**Skip the Isolate steps** (everything through "In place on a new branch") when +`continuing` is true, or when already inside a linked worktree. Detect the latter +with: + +```bash +git_dir=$(realpath "$(git rev-parse --path-format=absolute --git-dir)") +git_common_dir=$(realpath "$(git rev-parse --path-format=absolute --git-common-dir)") +[ "$git_dir" != "$git_common_dir" ] && echo "linked worktree" +``` + +(`realpath` avoids false differences from symlinked paths; same test as +`/git-tools:ship` step 0.) Then go straight to "Record issue linkage" and "Rename the +session" below on the current checkout. + +Decide silently: + +- **Repo's `CLAUDE.md` says to work directly on the default branch / master** (as + `homelab-admin` does): do not create a branch or worktree; work on the default + branch in place and skip the rest of Isolate. There is no branch to record + linkage on; skip that step. +- **Otherwise: worktree by default.** It keeps the main checkout clean and lets + parallel sessions coexist. + +**Before creating anything:** + +- **Dirty default branch.** If on the default branch with uncommitted changes, warn + once that those edits stay in the main checkout (they are not carried into the + worktree) and ask whether to proceed with the worktree or work in place. This is a + genuine ambiguity, so ask. +- **Name collisions.** Check for `<base-name>` and `worktree-<base-name>`: + + ```bash + git worktree list + git branch --list "<base-name>" "worktree-<base-name>" + ``` + + If either exists, offer to **resume** it (enter the existing worktree via + `EnterWorktree` with `path`, or `git switch` to the branch) or to use a short + numeric suffix (`<base-name>-2`). Decide silently only when unambiguous (e.g. it + is clearly stale or clearly this same work); ask when it could be someone's other + work. If you resume, treat the run as `continuing`. + +**Worktree:** + +1. **Provision dependencies first.** A fresh worktree is a clean checkout — gitignored + deps don't carry over, and native provisioning only runs at creation time, so + configure it **before** creating the worktree. Symlink **dependency directories + only** — never build output (`target`, `build`, `dist`, `.next`, `.gradle`, + `.tox`), which is stale or wrong in another checkout. Detect those present: + + ```bash + for d in node_modules .venv venv vendor; do + [ -e "$d" ] && git check-ignore -q "$d" && echo "$d" + done + ``` + + Add the detected names **without asking** to `worktree.symlinkDirectories` in the + project's **`.claude/settings.local.json`** (`Local` scope — per-checkout, + normally gitignored; never the tracked `.claude/settings.json`, never global). + Merge with `jq`, unioning with any existing list and preserving all other keys; + create the file if absent. With the detected names in `$dirs` as a JSON array + (e.g. `'["node_modules",".venv"]'`): + + ```bash + f=.claude/settings.local.json + mkdir -p .claude + [ -s "$f" ] || echo '{}' > "$f" + jq --argjson d "$dirs" \ + '.worktree.symlinkDirectories = ((.worktree.symlinkDirectories // []) + $d | unique)' \ + "$f" > "$f.tmp" && mv "$f.tmp" "$f" + git check-ignore -q "$f" \ + || echo "/$f" >> "$(git rev-parse --path-format=absolute --git-path info/exclude)" + ``` + + Skip this step if no dependency directory was detected. Add `.env` / `.env.*` to a + root `.worktreeinclude` only if they exist. That file has no documented + alternative location, so keep it out of `git status` instead: if it is untracked, + add `/.worktreeinclude` to the same `info/exclude`. If the repo already tracks a + `.worktreeinclude`, append to it only when a needed pattern is missing and + mention the resulting diff in the Phase 4 report, since that one is a real change. + +2. **Create + enter the worktree:** call `EnterWorktree` with `name` set to the base + name (already dash form, no `/`). This creates branch `worktree-<base-name>`, runs + native provisioning, and switches the session into the worktree. Do **not** also + run `branch create`. + + This assumes `worktree.symlinkDirectories` is read at `EnterWorktree` time. As a + fallback, for each detected dependency directory missing in the new worktree, + create it yourself: `ln -s "<main-checkout>/<dir>" "<dir>"`. + +3. **Keep the tree clean for `ship`.** A directory pattern with a trailing slash + (e.g. `node_modules/`) does not match a *symlink*, so a symlinked dependency + directory can show up as untracked and trip `/git-tools:ship`'s worktree + cleanliness gate. Inside the new worktree, exclude **only the dependency-directory + names detected in step 1** (not every untracked symlink): + + ```bash + exclude=$(git rev-parse --path-format=absolute --git-path info/exclude) + for d in $detected; do # names from step 1, e.g. node_modules .venv + [ -L "$d" ] && { grep -qxF "/$d" "$exclude" 2>/dev/null || printf '/%s\n' "$d" >> "$exclude"; } + done + git status --porcelain # expect no symlinked dependency dirs listed + ``` + + `info/exclude` is shared by every worktree of the repo, so these entries apply + everywhere; that is acceptable because root-relative dependency dirs are + normally ignored anyway. The `grep -qxF` guard prevents duplicates. + +**In place on a new branch** (only when the work genuinely cannot use a worktree): + +```bash +bash ${CLAUDE_PLUGIN_ROOT}/scripts/branch create <base-name> +``` + +**Record issue linkage** (always, once the branch exists — including when +`continuing`; skip when there are no linked issues or no branch). Store the closing +lines from Phase 0 step 4 as one comma-separated value, one entry per issue: + +```bash +git config "branch.$(git branch --show-current).session-issues" "Closes #12,Fixes #13" +``` + +The Phase 4 report, `/session:session-end`, and `session-orchestrate` read this +key. When `continuing`, union with any existing value rather than overwriting. + +**Rename the session** (always, last — `rename-session` keys off the current +directory, which `EnterWorktree` changes). Use the session name from Phase 0 step 3: + +```bash +bash ${CLAUDE_PLUGIN_ROOT}/scripts/rename-session "<session-name>" +``` + +A rename failure is non-fatal: warn and continue. When working on the default +branch in place with no meaningful name, skip the rename (warn only). + +## Phase 2 — Explore the codebase + +> You MUST complete this phase. Do NOT stop after Phase 1. Do NOT print +> "suggested first steps". + +**Trivial fast path.** When the change is small and obvious — a typo, a one-line or +single-file fix, a config tweak, an issue that names the exact file and change — +skip the research subagents: read the few relevant files yourself and go straight to +Phase 3 with a short plan inside `EnterPlanMode`. + +Otherwise launch **2-3 research agents in parallel** in a single message, using +`Agent` with `subagent_type: research`. Every agent prompt MUST include the full +context — the issue title/body/labels for **all** linked issues and/or the freeform +description — so the agent can work without seeing this conversation. Pick 2-3 +angles that fit: + +- **Locate the code** — files, functions, types, or modules implied by the work. + Report what each does, the change point, and surrounding signatures. +- **Find tests and related config** — existing coverage of the area, related config, + CI, docs. Report what exists, what is missing, how the suite is structured. +- **Trace the data/call flow** — entry points, intermediate steps, dependencies, and + edge cases. + +If an agent needs the issue tracker or repo API, tell it to use `gh` or `tea` +directly, per the `git-tools:git-wait` skill's command map. + +## Phase 3 — Plan + +> You MUST complete this phase. Do NOT stop after Phase 2. + +Call `EnterPlanMode`, then present a concrete plan for approval before any +implementation begins. Cover **all** linked issues in one plan. + +- **Changes** — the specific files and line ranges, and what each change does. + Describe the actual code change, not "fix the bug". +- **Testing** — include only when behavior changes: what tests to add or update, + using the project's existing framework. Omit for purely cosmetic changes + (comments, docs, formatting). +- **Risks & open questions** — edge cases and unknowns; omit when there are none. +- **Scope line, always last:** `Scope: <the PR(s)/unit(s) this plan covers>`. The + user defines the scope; approving the plan authorizes every unit listed through + merge. A single unit is a one-item scope. + +For trivial work keep the whole plan short — a few lines, not a document. Do **not** +otherwise describe the commit / push / PR / merge steps in the plan; Phase 4 defines +them. + +## Phase 4 — Report, continue the scope, pause before the final ship + +> Plan approval authorizes every unit before the last through merge: do **not** stop +> between those units or ask before their commit / push / PR / merge. The last (or +> only) unit is different: do not commit, push, or open its PR until the user has +> reviewed `session-end`'s summary and given the go. That is the only deliberate +> stop. + +After each unit is implemented: + +1. Print a **short progress note** (not a wait): one-line outcome, the per-file list + of what changed, branch, test/build status (say so plainly if tests were not + run), and any caveats — known or potential problems and assumptions, stated + specifically. Omit caveats only if there are genuinely none. +2. **If this is the last unit** (a single-unit scope is just this), do **not** ship + it here: go to `/session:session-end`, which does docs, review, and the issue + sweep, then **stops before shipping** to summarize what was done and any + caveats and wait for the user's go. After the go it ships the unit once, watches + CI, fixes and re-merges if needed, closes out (issue closing, cleanup / + worktree teardown), and finishes with a final-state summary. +3. Otherwise (a unit before the last), optionally run + `/code-review <level> --fix` (e.g. `/code-review high --fix`), then land the unit: + commit → push → open PR → watch CI → merge, via `/git-tools:ship` (a CI failure + clearly caused by the change is fixed forward within the unit, at most twice; + anything else is surfaced). If issues are linked, put one closing line per issue + (`Closes #N` / `Fixes #N`) in the PR body — read them from + `git config branch.$(git branch --show-current).session-issues` + (comma-separated) if they are no longer in context. +4. Start the next unit (re-isolate from the updated default branch, implement) and + repeat from step 1. + +- **Worked on the default branch in place** (repo `CLAUDE.md` says so): there is no + feature branch; `/git-tools:ship` and `/session:session-end` run from the default + branch. + +`/git-tools:ship` step 9 tears down the worktree after each merge (the last unit's +ship runs inside `/session:session-end`); the user can also +leave with `ExitWorktree`. diff --git a/utils/sync.sh b/utils/sync.sh index 75ec9d8..552eb48 100755 --- a/utils/sync.sh +++ b/utils/sync.sh @@ -25,19 +25,25 @@ set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" MODE="${1:-sync}" -# Vendoring manifests: PLUGIN → space-separated list of utils/ filenames, -# per target. Every plugin listed receives a real copy of each util in its -# <target>/<plugin>/scripts/ directory. Keys are quoted because shfmt -# otherwise reformats hyphens as arithmetic operators. +# Vendoring manifests: PLUGIN → space-separated list of utils/ entries, +# per target. An entry is `util` (vendored into <plugin>/scripts/) or +# `util:dir` (vendored into <plugin>/dir/). Every plugin listed receives a +# real copy of each entry. Keys are quoted because shfmt otherwise +# reformats hyphens as arithmetic operators. +# +# Markdown entries vendored for the opencode target are rendered through +# utils/opencode-port.py (harness mapping: script paths, worktree/plan/ +# question/subagent surfaces). Claude always receives the byte-identical +# canonical file. declare -A NEEDS_CLAUDE=( ["format-on-save"]="hook-compat.sh" ["git-tools"]="git-wait" ["kb-capture"]="detect-schema.sh validate-frontmatter.sh" ["inbox"]="inbox" ["notify-on-stop"]="hook-compat.sh inbox" - # branch and sitrep are canonical in utils/ and vendored back here; they - # used to live only in this plugin's scripts/ dir. - ["session"]="git-wait branch sitrep" + # branch, sitrep, and spine.md are canonical in utils/ and vendored back + # here; they used to live only in this plugin's scripts/ dir. + ["session"]="git-wait branch sitrep spine.md:reference" ) declare -A NEEDS_OPENCODE=( @@ -47,20 +53,39 @@ declare -A NEEDS_OPENCODE=( ["git-tools/skills/git-wait"]="git-wait" ["git-tools/skills/ship"]="git-wait" ["inbox"]="inbox" - ["session"]="git-wait branch sitrep" + ["session/skills/session-start"]="git-wait branch spine.md:reference" + ["session/skills/session-issue"]="git-wait branch spine.md:reference" + ["session/skills/session-end"]="git-wait sitrep" + ["session/skills/session-summarize"]="sitrep" + ["session/skills/session-orchestrate"]="git-wait sitrep" ) +# render_for_target <target> <src> — content on stdout, harness-adjusted. +render_for_target() { + local target="$1" src="$2" + if [[ "$target" == "opencode" && "$src" == *.md ]]; then + python3 "$ROOT/utils/opencode-port.py" <"$src" + else + cat "$src" + fi +} + drift=0 synced=0 +TMPOUT=$(mktemp) +trap 'rm -f "$TMPOUT"' EXIT for target in claude opencode; do declare -n NEEDS="NEEDS_${target^^}" target_dir="$ROOT/plugins-$target" for plugin in "${!NEEDS[@]}"; do - for util in ${NEEDS[$plugin]}; do + for entry in ${NEEDS[$plugin]}; do + util="${entry%%:*}" + subdir="${entry#*:}" + [[ "$subdir" == "$entry" ]] && subdir="scripts" src="$ROOT/utils/$util" - dst="$target_dir/$plugin/scripts/$util" + dst="$target_dir/$plugin/$subdir/$util" if [[ ! -f "$src" ]]; then echo "ERROR: canonical source missing: utils/$util" >&2 @@ -80,18 +105,27 @@ for target in claude opencode; do elif [[ ! -f "$dst" ]]; then echo "DRIFT: $dst missing (run utils/sync.sh)" >&2 drift=1 - elif ! cmp -s "$src" "$dst"; then + elif ! render_for_target "$target" "$src" >"$TMPOUT" || ! cmp -s "$TMPOUT" "$dst"; then echo "DRIFT: $dst differs from utils/$util (run utils/sync.sh)" >&2 drift=1 fi ;; sync) [[ -L "$dst" ]] && rm "$dst" - if ! cmp -s "$src" "$dst" 2>/dev/null; then - mkdir -p "$target_dir/$plugin/scripts" - cp -p "$src" "$dst" + render_for_target "$target" "$src" >"$TMPOUT" + # mktemp renders at 0600; carry the canonical exec bit over + # (unconditionally — mode drift is drift even when content matches) + if [[ -x "$src" ]]; then + chmod +x "$dst" 2>/dev/null || true + fi + if ! cmp -s "$TMPOUT" "$dst" 2>/dev/null; then + mkdir -p "$target_dir/$plugin/$subdir" + cp "$TMPOUT" "$dst" + if [[ -x "$src" ]]; then + chmod +x "$dst" + fi synced=$((synced + 1)) - echo "synced: plugins-$target/$plugin/scripts/$util" + echo "synced: plugins-$target/$plugin/$subdir/$util" fi ;; *) From f0fb94fc2328310ba38276f35293d79ba975b48c Mon Sep 17 00:00:00 2001 From: Logan Gagne <logan.gagne@gmail.com> Date: Tue, 10 Nov 2026 18:23:03 -0500 Subject: [PATCH 6/6] fix(opencode): address code-review findings on the session/inbox ports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Session plugin: - orchestrate_build: a throwing review child no longer kills the whole run (each reviewer task is guarded; a failed reviewer reports a 'not reviewed' concern instead of discarding all Execute work — parity with the Claude workflow's null-agent tolerance). - ctx.session.wait gets a deadline (options.childTimeoutMs, default 45m) so a child stuck on a permission/form can't hang the parent turn. - perChunk now echoes resolvedModel so tier-resolution no-ops are visible. - Re-review merge extracted to orchestrate-core.mergeReReview (+3 tests). Session port fidelity (reviewer-found content bugs): - session-orchestrate now vendors reference/spine.md (it instructs 'Run reference/spine.md Phase 0' — the file was missing). - Porter maps the spine's Claude worktree.symlinkDirectories/.claude/ settings.local.json provisioning procedure to OpenCode's manual symlink flow (worktree config only takes 'directory'), fixes the orchestrate skill's false 'provisions deps, switches the session in' parenthetical, maps bare `Agent` tool references → subagent tool (general-purpose→general, Plan→plan), and replaces the false per-wave-progress claim with the honest single-result wording. - Deleted orphaned plugins-opencode/session/scripts/ copies (manifest moved to per-skill dirs in M4; nothing vendored there anymore). Inbox plugin: - Footer slot now seeds the store (events are live-only; previously it stayed empty until the first inbox write). - Session hint also seeds on session.execution.started so sessions that predate plugin install learn the CLI path (keyed put is idempotent). - Event subscription loop wrapped (no unhandled rejection on abort/error). - form/permission pings filtered to the current session; panel triage errors surfaced in-panel instead of silently keeping stale rows. utils/inbox: update gains --blocking/--no-blocking (question-only) so a parked question can be escalated without --new; vendored copies re-synced. sync.sh: --check now detects exec-bit drift both ways (git tracks it; a bad merge dropping +x no longer false-passes); sync applies canonical modes (0644 / +x) instead of inheriting mktemp 0600. Tests: sync exec-bit drift + repair (5), session-port reference/ cross-check + expanded leak greps + porter-split guard (+9), session-core mergeReReview (+3), inbox update blocking semantics (+3), format-parity parser hardened (non-fmt_ arms fail loudly, multi-invocation functions fail loudly). Full suite 976 green; live-verified enum validation and cli_failed error path against opencode 2.2.6. Refs #236 --- plugins-claude/inbox/scripts/inbox | 13 +- plugins-claude/notify-on-stop/scripts/inbox | 13 +- plugins-opencode/inbox/scripts/inbox | 13 +- plugins-opencode/inbox/src/index.ts | 48 +- plugins-opencode/inbox/src/tui.tsx | 41 +- plugins-opencode/session/scripts/branch | 38 - plugins-opencode/session/scripts/git-wait | 1460 ----------------- plugins-opencode/session/scripts/sitrep | 246 --- .../skills/session-issue/reference/spine.md | 35 +- .../skills/session-orchestrate/SKILL.md | 21 +- .../session-orchestrate/reference/spine.md | 299 ++++ .../skills/session-start/reference/spine.md | 35 +- .../session/skills/session-summarize/SKILL.md | 2 +- plugins-opencode/session/src/index.ts | 78 +- .../session/src/orchestrate-core.ts | 10 + tests/inbox/test-inbox-blocking.sh | 10 + tests/opencode/test-format-on-save-parity.sh | 22 +- tests/opencode/test-session-core.mjs | 24 + tests/opencode/test-session-port.sh | 18 +- tests/opencode/test-sync.sh | 24 + utils/inbox | 13 +- utils/opencode-port.py | 48 +- utils/sync.sh | 27 +- 23 files changed, 668 insertions(+), 1870 deletions(-) delete mode 100755 plugins-opencode/session/scripts/branch delete mode 100755 plugins-opencode/session/scripts/git-wait delete mode 100755 plugins-opencode/session/scripts/sitrep create mode 100644 plugins-opencode/session/skills/session-orchestrate/reference/spine.md diff --git a/plugins-claude/inbox/scripts/inbox b/plugins-claude/inbox/scripts/inbox index 86be29b..6f15ae7 100755 --- a/plugins-claude/inbox/scripts/inbox +++ b/plugins-claude/inbox/scripts/inbox @@ -38,6 +38,7 @@ Commands: Refused (exit 3) if a similar open followup exists unless --new. update <Q<n>|D<n>|F<n>> [--title T] [--context C] [--option O]... [--recommend R (question)] [--chosen X (decision)] + [--blocking | --no-blocking (question)] Replace provided fields (any --option replaces the options list). answer Q<n> [--note N] Remove a question. --note is reserved and currently ignored. @@ -268,7 +269,7 @@ cmd_update() { shift local kind="$REF_KIND" id="$REF_ID" kind_keys "$kind" - local title="" context="" extra="" have_t=0 have_c=0 have_e=0 + local title="" context="" extra="" have_t=0 have_c=0 have_e=0 blocking=0 have_b=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -283,6 +284,12 @@ cmd_update() { --chosen) [[ "$kind" == decision ]] || die "update $PFX$id: --chosen applies to decisions only (use --recommend)" 1 extra="${2:?--chosen needs a value}"; have_e=1; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --blocking applies to questions only" 1 + blocking=1; have_b=1; shift ;; + --no-blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --no-blocking applies to questions only" 1 + blocking=0; have_b=1; shift ;; *) die "update: unknown argument: $1" 2 ;; esac done @@ -298,13 +305,15 @@ cmd_update() { local new new=$(jq --arg k "$ARR" --arg kind "$kind" --argjson id "$id" \ --arg t "$title" --arg c "$context" --arg e "$extra" \ - --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" ' + --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" \ + --argjson b "$blocking" --argjson hb "$have_b" ' (if $kind == "question" then "recommendation" else "chosen" end) as $ek | .[$k] |= map(if .id == $id then (if $ht == 1 then .title = $t else . end) | (if $hc == 1 then .context = $c else . end) | (if $he == 1 then .[$ek] = $e else . end) | (if $o != null then .options = $o else . end) + | (if $hb == 1 then .blocking = ($b == 1) else . end) else . end)' <<<"$state") write_state "$new" echo "$PFX$id updated" diff --git a/plugins-claude/notify-on-stop/scripts/inbox b/plugins-claude/notify-on-stop/scripts/inbox index 86be29b..6f15ae7 100755 --- a/plugins-claude/notify-on-stop/scripts/inbox +++ b/plugins-claude/notify-on-stop/scripts/inbox @@ -38,6 +38,7 @@ Commands: Refused (exit 3) if a similar open followup exists unless --new. update <Q<n>|D<n>|F<n>> [--title T] [--context C] [--option O]... [--recommend R (question)] [--chosen X (decision)] + [--blocking | --no-blocking (question)] Replace provided fields (any --option replaces the options list). answer Q<n> [--note N] Remove a question. --note is reserved and currently ignored. @@ -268,7 +269,7 @@ cmd_update() { shift local kind="$REF_KIND" id="$REF_ID" kind_keys "$kind" - local title="" context="" extra="" have_t=0 have_c=0 have_e=0 + local title="" context="" extra="" have_t=0 have_c=0 have_e=0 blocking=0 have_b=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -283,6 +284,12 @@ cmd_update() { --chosen) [[ "$kind" == decision ]] || die "update $PFX$id: --chosen applies to decisions only (use --recommend)" 1 extra="${2:?--chosen needs a value}"; have_e=1; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --blocking applies to questions only" 1 + blocking=1; have_b=1; shift ;; + --no-blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --no-blocking applies to questions only" 1 + blocking=0; have_b=1; shift ;; *) die "update: unknown argument: $1" 2 ;; esac done @@ -298,13 +305,15 @@ cmd_update() { local new new=$(jq --arg k "$ARR" --arg kind "$kind" --argjson id "$id" \ --arg t "$title" --arg c "$context" --arg e "$extra" \ - --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" ' + --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" \ + --argjson b "$blocking" --argjson hb "$have_b" ' (if $kind == "question" then "recommendation" else "chosen" end) as $ek | .[$k] |= map(if .id == $id then (if $ht == 1 then .title = $t else . end) | (if $hc == 1 then .context = $c else . end) | (if $he == 1 then .[$ek] = $e else . end) | (if $o != null then .options = $o else . end) + | (if $hb == 1 then .blocking = ($b == 1) else . end) else . end)' <<<"$state") write_state "$new" echo "$PFX$id updated" diff --git a/plugins-opencode/inbox/scripts/inbox b/plugins-opencode/inbox/scripts/inbox index 86be29b..6f15ae7 100755 --- a/plugins-opencode/inbox/scripts/inbox +++ b/plugins-opencode/inbox/scripts/inbox @@ -38,6 +38,7 @@ Commands: Refused (exit 3) if a similar open followup exists unless --new. update <Q<n>|D<n>|F<n>> [--title T] [--context C] [--option O]... [--recommend R (question)] [--chosen X (decision)] + [--blocking | --no-blocking (question)] Replace provided fields (any --option replaces the options list). answer Q<n> [--note N] Remove a question. --note is reserved and currently ignored. @@ -268,7 +269,7 @@ cmd_update() { shift local kind="$REF_KIND" id="$REF_ID" kind_keys "$kind" - local title="" context="" extra="" have_t=0 have_c=0 have_e=0 + local title="" context="" extra="" have_t=0 have_c=0 have_e=0 blocking=0 have_b=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -283,6 +284,12 @@ cmd_update() { --chosen) [[ "$kind" == decision ]] || die "update $PFX$id: --chosen applies to decisions only (use --recommend)" 1 extra="${2:?--chosen needs a value}"; have_e=1; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --blocking applies to questions only" 1 + blocking=1; have_b=1; shift ;; + --no-blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --no-blocking applies to questions only" 1 + blocking=0; have_b=1; shift ;; *) die "update: unknown argument: $1" 2 ;; esac done @@ -298,13 +305,15 @@ cmd_update() { local new new=$(jq --arg k "$ARR" --arg kind "$kind" --argjson id "$id" \ --arg t "$title" --arg c "$context" --arg e "$extra" \ - --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" ' + --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" \ + --argjson b "$blocking" --argjson hb "$have_b" ' (if $kind == "question" then "recommendation" else "chosen" end) as $ek | .[$k] |= map(if .id == $id then (if $ht == 1 then .title = $t else . end) | (if $hc == 1 then .context = $c else . end) | (if $he == 1 then .[$ek] = $e else . end) | (if $o != null then .options = $o else . end) + | (if $hb == 1 then .blocking = ($b == 1) else . end) else . end)' <<<"$state") write_state "$new" echo "$PFX$id updated" diff --git a/plugins-opencode/inbox/src/index.ts b/plugins-opencode/inbox/src/index.ts index 8f447a7..5e95188 100644 --- a/plugins-opencode/inbox/src/index.ts +++ b/plugins-opencode/inbox/src/index.ts @@ -93,27 +93,37 @@ export default Plugin.define({ // --- session hint (replaces Claude's SessionStart hook) --------------- // One keyed instruction entry per session: survives compaction, applies - // at the next step boundary, costs no extra model turn. + // at the next step boundary, costs no extra model turn. Subscribes to + // execution.started too (not just created) so sessions that predate the + // plugin install still learn the CLI path on their next run; the keyed + // put is idempotent, so repeat events are free. const controller = new AbortController() void (async () => { - for await (const event of ctx.event.subscribe({ types: ["session.created"], signal: controller.signal })) { - const data = event.data as { id?: string; sessionID?: string; session?: { id?: string } } - const sessionID = data.session?.id ?? data.id ?? data.sessionID - if (!sessionID) continue - await ctx.session.instructions - .entry.put({ - sessionID, - key: HINT_KEY, - value: - `Inbox tracker is active for this session. Record blockers, decisions, and followups with: ` + - `bash ${cli} --session ${sessionID} add question|decision|followup --title T [--context C] [--option O]... ` + - `Questions are NON-BLOCKING by default: park the question, state your assumption as a decision if needed, and keep working. ` + - `Pass --blocking only when you genuinely cannot proceed without the user. ` + - `Never poll or ask the user to check the inbox; the user reviews it from the sidebar/panel.`, - }) - .catch(() => { - /* session may already be gone */ - }) + try { + for await (const event of ctx.event.subscribe({ + types: ["session.created", "session.execution.started"], + signal: controller.signal, + })) { + const data = event.data as { id?: string; sessionID?: string; session?: { id?: string } } + const sessionID = data.session?.id ?? data.id ?? data.sessionID + if (!sessionID) continue + await ctx.session.instructions + .entry.put({ + sessionID, + key: HINT_KEY, + value: + `Inbox tracker is active for this session. Record blockers, decisions, and followups with: ` + + `bash ${cli} --session ${sessionID} add question|decision|followup --title T [--context C] [--option O]... ` + + `Questions are NON-BLOCKING by default: park the question, state your assumption as a decision if needed, and keep working. ` + + `Pass --blocking only when you genuinely cannot proceed without the user. ` + + `Never poll or ask the user to check the inbox; the user reviews it from the sidebar/panel.`, + }) + .catch(() => { + /* session may already be gone */ + }) + } + } catch { + /* stream ended (dispose/abort) or transport error; hint seeding stops */ } })() diff --git a/plugins-opencode/inbox/src/tui.tsx b/plugins-opencode/inbox/src/tui.tsx index 9da2e88..5d78f54 100644 --- a/plugins-opencode/inbox/src/tui.tsx +++ b/plugins-opencode/inbox/src/tui.tsx @@ -65,6 +65,7 @@ function InboxPanel(props: { panel: PanelInput }) { } const [sel, setSel] = createSignal(0) + const [err, setErr] = createSignal<string | undefined>(undefined) createEffect(() => void store.refresh(sessionID())) context.keymap.layer(() => { const n = rows().length @@ -85,7 +86,12 @@ function InboxPanel(props: { panel: PanelInput }) { placeholder: "Your answer…", }) if (note === undefined) return - await store.rpc.triage({ sessionID: sessionID(), action: "answer", id: row.ref, note, resume: true }) + try { + await store.rpc.triage({ sessionID: sessionID(), action: "answer", id: row.ref, note, resume: true }) + setErr(undefined) + } catch (e) { + setErr(`triage failed: ${e instanceof Error ? e.message : String(e)}`) + } }, }, { @@ -95,7 +101,12 @@ function InboxPanel(props: { panel: PanelInput }) { run: async () => { const row = rows()[sel()] if (!row || row.kind === "question") return - await store.rpc.triage({ sessionID: sessionID(), action: row.kind === "decision" ? "resolve" : "done", id: row.ref }) + try { + await store.rpc.triage({ sessionID: sessionID(), action: row.kind === "decision" ? "resolve" : "done", id: row.ref }) + setErr(undefined) + } catch (e) { + setErr(`triage failed: ${e instanceof Error ? e.message : String(e)}`) + } }, }, { id: "inbox.refresh", title: "Refresh", bind: "r", run: () => store.refresh(sessionID()) }, @@ -117,6 +128,9 @@ function InboxPanel(props: { panel: PanelInput }) { </text> )} </For> + <Show when={err()}> + <text fg={context.theme.text.base}>{err()}</text> + </Show> <text fg={context.theme.text.muted}>↑/↓ move · a answer · d acknowledge · r refresh</text> </box> ) @@ -142,6 +156,12 @@ export default Plugin.define({ append: "home.footer.status", render: () => { const id = currentSession() + // Seed the store: RPC events are live-only, so without this the + // footer stays empty until the next inbox write anywhere. + createEffect(() => { + const sid = currentSession() + if (sid) void store.refresh(sid) + }) if (!id) return null const c = store.counts(id) if (c.questions + c.decisions + c.followups === 0) return null @@ -200,17 +220,28 @@ export default Plugin.define({ context.attention .notify({ title: "agent-toolkit inbox", message, notification: { when: "blurred" }, sound: { name: "done", volume: 0.5, when: "always" } }) .catch(() => {}) + // Only ping for the session the user is actually looking at; a form or + // permission ask in some background session is not "waiting for you". + // Events without a sessionID (older servers) ping conservatively. + const forCurrent = (data: unknown) => { + const sid = (data as { sessionID?: string })?.sessionID + return !sid || sid === currentSession() + } const offs = [ context.data.on("session.execution.succeeded", (event) => { const sid = (event.data as { sessionID?: string })?.sessionID if (!sid) return void (async () => { await store.refresh(sid) - if (store.counts(sid).blocking > 0) void ping("A blocking question needs you") + if (store.counts(sid).blocking > 0 && sid === currentSession()) void ping("A blocking question needs you") })() }), - context.data.on("form.created", () => void ping("The agent is waiting for your answer")), - context.data.on("permission.asked", () => void ping("The agent needs permission")), + context.data.on("form.created", (event) => { + if (forCurrent(event.data)) void ping("The agent is waiting for your answer") + }), + context.data.on("permission.asked", (event) => { + if (forCurrent(event.data)) void ping("The agent needs permission") + }), ] return () => { diff --git a/plugins-opencode/session/scripts/branch b/plugins-opencode/session/scripts/branch deleted file mode 100755 index 98f16e5..0000000 --- a/plugins-opencode/session/scripts/branch +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -# branch - Git branch operations for session workflows -# Exit codes: 0 success (including -h/--help), 1 bad usage or invalid name, 2 git error -# -# Subcommands: -# create <name> Create and switch to a new branch - -set -euo pipefail - -usage() { - cat <<'EOF' -Usage: branch <subcommand> [args] - -Subcommands: - create <name> Create and switch to a new branch -EOF -} - -die() { echo "Error: $*" >&2; exit 2; } - -[[ $# -ge 1 ]] || { usage >&2; exit 1; } - -cmd="$1"; shift - -case "$cmd" in - create) - [[ $# -eq 1 ]] || { echo "Usage: branch create <name>" >&2; exit 1; } - name="$1" - [[ "$name" != -* ]] || { echo "Error: branch name must not start with '-': $name" >&2; exit 1; } - git check-ref-format --branch "$name" >/dev/null 2>&1 || { echo "Error: invalid branch name: $name" >&2; exit 1; } - if git show-ref --verify --quiet "refs/heads/$name"; then - die "branch '$name' already exists" - fi - git switch -c "$name" || die "failed to create branch '$name'" - ;; - -h|--help) usage ;; - *) echo "Unknown subcommand: $cmd" >&2; usage >&2; exit 1 ;; -esac diff --git a/plugins-opencode/session/scripts/git-wait b/plugins-opencode/session/scripts/git-wait deleted file mode 100755 index 335f658..0000000 --- a/plugins-opencode/session/scripts/git-wait +++ /dev/null @@ -1,1460 +0,0 @@ -#!/usr/bin/env bash -# git-wait — blocking waiters for PR merge and CI completion, on GitHub and Gitea. -# -# This is NOT a CLI wrapper. Use `gh` and `tea` directly for everything else: -# listing, creating, commenting, merging, closing, viewing logs. This script -# exists only for the three things neither CLI gives you: -# -# 1. Platform detection — matching the git remote hostname against configured -# tea logins, so a caller knows whether to reach for `gh` or `tea`. -# 2. `pr wait` — block until a PR merges, closes, or conflicts, with a -# progress-aware idle timeout (`gh pr checks --watch` waits on CI, not on -# the merge itself; `tea` has no equivalent at all). -# 3. `run watch` — block until CI finishes, aggregating per-job status and -# dumping failed job logs. `gh run watch` is GitHub-only and misses -# job-level failures masked by a run-level success; `tea` has no watcher. -# -# Usage: -# git-wait [-C DIR] <command> ... -# Operate on the git repo at DIR instead of the current directory (like -# `git -C`). Must come before the command. gh/tea resolve the repo from the -# working directory, so this retargets every call without a caller-side cd. -# -# git-wait platform -# Echo "github" or "gitea" for the current repo's origin remote. -# -# git-wait pr wait --branch NAME [--timeout 14400] [--idle-timeout 300] [--interval 15] -# [--alert-interval 300] -# Block until the PR for BRANCH reaches a terminal state. -# Output: "status: merged|closed|blocked|timeout|error" plus pr_number, -# url, duration, and (when relevant) reason. -# -# git-wait run watch (--branch NAME | --sha SHA) [--initial-delay 60] -# [--timeout 14400] [--idle-timeout 0] [--interval 15] -# [--alert-interval 300] [--no-run-timeout 600|900] [--settle 0] -# [--max-poll-failures 10] -# Block until CI finishes. Output: "status: pass|fail|closed|timeout| -# no-workflow" plus url, duration, and (on failure) failed_jobs. Failed -# job logs go to stderr. -# -# --branch follows ONE run: the newest correlated to that branch (via the -# PR's check rollup when a PR exists, else the newest run in the list). -# That is right for a PR branch, where one push means one run. It is NOT -# sufficient on a default branch, where two merges landing close together -# produce two runs and the newest passing says nothing about the older -# one still executing. -# -# --sha watches EVERY run for one commit and is the correct flag for a -# post-merge/release watch: it stays pending while any run for the commit -# is pending, and fails if any run — or any job inside one — failed. Pass -# one or the other, not both. -# -# A running CI is never aborted for lack of visible progress: `run watch -# --idle-timeout` defaults to 0 (disabled; pass N to opt in to a no-progress -# window). `pr wait --idle-timeout` defaults to 300 but only ticks while NO -# check is pending (running CI, or auto-merge armed, resets it), so a PR that -# just waits on review gives up while a 30+ min CI never does; 0 disables. --timeout is a generous hard ceiling (default 14400s = 4h; 0 disables). Long -# jobs (VM boot + integration suite + teardown) can go quiet for a long time. -# While still waiting, a heartbeat alert goes to STDERR every --alert-interval -# seconds (default 300; 0 disables), e.g. "still running after 5m (2 job(s) -# pending: ...)". stdout key:value output is unchanged. -# -# --no-run-timeout is how long to wait for the FIRST run to appear before -# reporting no-workflow, counted from the end of --initial-delay. Default 600s -# for --sha (post-merge workflows queue late, or start only after another -# workflow finishes) and 900s for --branch (PR checks can register late). 0 gives up on the first empty -# check. A stderr alert is printed each poll while waiting. A FAILED run-list -# call (network/auth/rate limit) is not "no runs": it is noted on stderr, not -# counted toward this deadline and polling continues, but after -# --max-poll-failures N CONSECUTIVE failed polls (default 10; 0 disables) the -# watch gives up with "status: error" and exit 4. A successful poll resets the -# count. -# -# --settle SECS (--sha only, error with --branch; default 0 = off; opt in with --settle 30 for workflow_run chains): once every run for the -# commit is terminal and passing, keep polling SECS more before reporting pass, -# so a chained workflow_run workflow that appears late is still watched. A -# stderr line is printed while settling; a new run restarts the watch. -# -# Exit codes: 0 terminal state reached (check "status:" for pass/fail), -# 1 usage error, 2 timeout, 3 platform detection failure or no -# PR/workflow found, 4 command failed - -set -euo pipefail - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - -die() { echo "git-wait: $*" >&2; exit 1; } -die_usage() { echo "git-wait: $*" >&2; echo "Run 'git-wait --help' for usage." >&2; exit 1; } - -# Run a CLI command and pipe its stdout through a jq filter. -# If the command fails, die with its stderr instead of feeding junk to jq. -# Usage: cli_json [jq-flags...] <jq-filter> <cmd> [args...] -# -# IMPORTANT: stderr is captured to a temp file, NOT mixed into stdout. -# Using 2>&1 here would merge any gh/tea stderr output (upgrade notices, -# auth warnings, progress text) into the JSON, silently corrupting jq -# parsing and producing wrong results downstream (e.g. run watch seeing -# unexpected status values). -cli_json() { - local jq_flags=() - while [[ "$1" =~ ^-[a-zA-Z] ]]; do - # Collect jq flags (e.g. -r, -e) — stop at the filter string - case "$1" in - -r|-e|-c|-S|-s|-R) jq_flags+=("$1"); shift ;; - *) break ;; - esac - done - local filter="$1"; shift - local raw stderr_file rc=0 - stderr_file=$(mktemp) - raw=$("$@" 2>"$stderr_file") || rc=$? - if [[ $rc -ne 0 ]]; then - local err - err=$(cat "$stderr_file") - rm -f "$stderr_file" - die "$err" - fi - rm -f "$stderr_file" - echo "$raw" | jq "${jq_flags[@]+"${jq_flags[@]}"}" "$filter" -} - -# --------------------------------------------------------------------------- -# Target repo (-C DIR) -# -# Handled before platform detection. The cd happens inside this script's own -# process, so the caller's working directory is never touched. -# --------------------------------------------------------------------------- - -if [[ "${1:-}" == "-C" || "${1:-}" == "--repo-dir" ]]; then - [[ $# -gt 1 && -n "$2" ]] || die_usage "$1 requires a directory" - target_dir="$2" - [[ -d "$target_dir" ]] || die_usage "$1: not a directory: $target_dir" - git -C "$target_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 \ - || die_usage "$1: not a git repository: $target_dir" - # Resolve the script path first: a relative $0 breaks once we cd (help reads it). - SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" - cd "$target_dir" - shift 2 -fi -SELF="${SELF:-$0}" - -# --------------------------------------------------------------------------- -# Platform detection -# --------------------------------------------------------------------------- - -detect_platform() { - local remote_url hostname login_url login_host - remote_url=$(git remote get-url origin 2>/dev/null) \ - || die "no git remote 'origin' found — run from a git repository" - - # Extract hostname from SSH (git@host:org/repo or ssh://git@host:port/org/repo) - # or HTTPS (https://host/org/repo or https://host:port/org/repo) - if [[ "$remote_url" =~ ^ssh:// ]]; then - hostname=$(echo "$remote_url" | sed -E 's|^ssh://[^@]*@([^:/]+).*|\1|') - elif [[ "$remote_url" =~ ^git@ ]]; then - hostname=$(echo "$remote_url" | sed -E 's|^git@([^:]+):.*|\1|') - elif [[ "$remote_url" =~ ^https?:// ]]; then - hostname=$(echo "$remote_url" | sed -E 's|^https?://([^/:]+).*|\1|') - else - die "unrecognised remote URL format: $remote_url" - fi - - # Check if this hostname matches any configured tea login - if command -v tea >/dev/null 2>&1; then - while IFS= read -r login_url; do - login_host=$(echo "$login_url" | sed -E 's|^https?://([^/:]+).*|\1|') - if [[ "$login_host" == "$hostname" ]]; then - echo "gitea" - return - fi - done < <(tea login list --output json 2>/dev/null | jq -r '.[].url' 2>/dev/null || true) - fi - - # Not a known tea login — fall back to gh (GitHub) - if [[ "$hostname" == "github.com" ]]; then - echo "github" - return - fi - - die "cannot determine platform for host '$hostname' — configure a tea login or ensure gh is authenticated" -} - -PLATFORM=$(detect_platform) - -case "$PLATFORM" in - github) CLI=gh ;; - gitea) CLI=tea ;; -esac - -command -v "$CLI" >/dev/null 2>&1 \ - || { echo "git-wait: '$CLI' not found — install and authenticate it" >&2; exit 3; } - -# --------------------------------------------------------------------------- -# Internal reads -# -# These are NOT public subcommands — they are the normalized queries the two -# waiters below need. Every one of them dies on backend failure, so callers -# invoke them inside $( ) with a fallback: a probe failure must degrade the -# poll loop, never abort it. -# --------------------------------------------------------------------------- - -# List PRs as normalized JSON. Flags: --state, --limit, --assignee. -_pr_list() { - local limit assignee state args - limit=30; assignee=""; state="open" - while [[ $# -gt 0 ]]; do - case "$1" in - --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; - --assignee) [[ $# -gt 1 ]] || die_usage "--assignee requires a value"; shift; assignee="$1" ;; - --state) [[ $# -gt 1 ]] || die_usage "--state requires a value"; shift; state="$1" ;; - *) die_usage "unknown flag: $1" ;; - esac - shift - done - case "$PLATFORM" in - github) - args=(--json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,url" --limit "$limit") - # gh uses 'merged' as a state but tea uses 'closed' for merged PRs - [[ "$state" == "all" ]] && args+=(--state "all") || args+=(--state "$state") - [[ -n "$assignee" ]] && args+=(--assignee "$assignee") - cli_json '[.[] | {number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, url}]' \ - env GH_NO_COLOR=1 gh pr list "${args[@]}" - ;; - gitea) - args=(--output json --limit "$limit" - --fields "index,title,body,state,author,head,base,labels,assignees,mergeable,created,updated,url") - [[ "$state" == "merged" ]] && state="closed" - args+=(--state "$state") - cli_json '[.[] | {number: (.index | tonumber? // .index), title, body: (.body // ""), state, merged: (.merged // false), author: (.author // ""), head: (.head // ""), base: (.base // ""), labels: (if .labels and (.labels | type) == "array" then [.labels[].name] else [] end), assignees: (if .assignees and (.assignees | type) == "array" then [.assignees[] | .login // empty] else [] end), mergeable: (.mergeable // null), created_at: (.created // ""), updated_at: (.updated // null), url: (.url // "")}]' \ - env NO_COLOR=1 tea pr list "${args[@]}" - ;; - esac -} - -# Show one PR as normalized JSON. Takes <N> or --branch NAME. -_pr_show() { - local num branch pr_json pr_stderr pr_rc pr_detail err - num=""; branch="" - while [[ $# -gt 0 ]]; do - case "$1" in - --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; - --*) die_usage "unknown flag: $1" ;; - *) [[ -z "$num" ]] || die_usage "pr show takes a single number argument"; num="$1" ;; - esac - shift - done - [[ -z "$num" || -z "$branch" ]] || die_usage "pr show: pass <N> or --branch NAME, not both" - if [[ -n "$branch" ]]; then - pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" - num=$(echo "$pr_json" | jq -r --arg b "$branch" \ - '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') - [[ -n "$num" ]] || die "no PR found for branch '$branch'" - fi - [[ -n "$num" ]] || die_usage "usage: git-wait pr show <N> | --branch NAME" - case "$PLATFORM" in - github) - cli_json '{number, title, body: (.body // ""), state: (.state | ascii_downcase), merged: ((.state | ascii_downcase) == "merged"), author: .author.login, head: .headRefName, base: .baseRefName, labels: [.labels[].name], assignees: [.assignees[].login], mergeable: (.mergeable | ascii_downcase? // null), created_at: .createdAt, updated_at: .updatedAt, merged_at: .mergedAt, url, comments: [.comments[] | {author: .author.login, body, created_at: .createdAt}]}' \ - env GH_NO_COLOR=1 gh pr view "$num" \ - --json "number,title,body,state,author,headRefName,baseRefName,labels,assignees,mergeable,createdAt,updatedAt,mergedAt,url,comments" - ;; - gitea) - # `tea pr list` omits the `merged` boolean and `merged_at` timestamp - # entirely (tea only encodes merge state into the `state` string) and - # emits `mergeable` as a string, so a merged PR reports - # merged:false / mergedAt:null and consumers think it is still open - # (#140). Fetch the PR detail via the REST API instead, mirroring the - # run:show/run:list `tea api` pattern, so merge fields are reliable. - pr_stderr=$(mktemp); pr_rc=0 - pr_detail=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/pulls/${num}" 2>"$pr_stderr") \ - || pr_rc=$? - if [[ $pr_rc -ne 0 ]]; then - err=$(cat "$pr_stderr"); rm -f "$pr_stderr" - die "tea api repos/{owner}/{repo}/pulls/${num} failed: $err" - fi - rm -f "$pr_stderr" - # Derive `state` from `merged` so it stays consistent with the merge - # flags (Gitea REST reports state:"closed" for a merged PR) and matches - # the GitHub path, which emits state:"merged". - echo "$pr_detail" | jq '{ - number: (.number // .index), - title: (.title // ""), - body: (.body // ""), - state: (if (.merged // false) then "merged" else (.state // "") end), - merged: (.merged // false), - merged_at: (.merged_at // null), - author: (.user.login // .user.username // ""), - head: (.head.ref // .head.label // ""), - base: (.base.ref // .base.label // ""), - labels: (if (.labels | type) == "array" then [.labels[].name] else [] end), - assignees: (if (.assignees | type) == "array" then [.assignees[] | (.login // .username // empty)] else [] end), - mergeable: (.mergeable // null), - created_at: (.created_at // ""), - updated_at: (.updated_at // null), - url: (.html_url // .url // ""), - comments: [] - }' - ;; - esac -} - -# Echo "auto_merge: true|false" for a PR. Takes --number N or --branch NAME. -_auto_merge_status() { - local branch number pr_json am - branch=""; number="" - while [[ $# -gt 0 ]]; do - case "$1" in - --branch) shift; branch="$1" ;; - --number) shift; number="$1" ;; - *) die_usage "unknown flag: $1" ;; - esac - shift - done - - # Resolve PR number from branch if needed - if [[ -z "$number" ]]; then - [[ -n "$branch" ]] || die_usage "pr auto-merge-status requires --branch or --number" - pr_json=$(_pr_list --state open 2>/dev/null) || pr_json="[]" - number=$(echo "$pr_json" | jq -r --arg b "$branch" \ - '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last | .number // empty') - if [[ -z "$number" || "$number" == "null" ]]; then - echo "auto_merge: false" - echo "No open PR found for branch '$branch'" >&2 - exit 3 - fi - fi - - case "$PLATFORM" in - github) - am=$(cli_json -r '.autoMergeRequest != null' \ - env GH_NO_COLOR=1 gh pr view "$number" --json autoMergeRequest) - echo "auto_merge: $am" - ;; - gitea) - echo "auto_merge: false" - echo "Gitea does not support auto-merge detection" >&2 - ;; - esac -} - -# List CI runs as normalized JSON. Flags: --limit, --status, --branch, --sha. -# -# --sha filters to runs for one commit. GitHub has a server-side filter for it -# (`gh run list --commit`); Gitea does not, so it is applied client-side over -# an unfiltered fetch, the same way --branch already is there. Both platforms -# emit head_sha in the normalized output — GitHub did not used to, which is -# why `run watch --sha` needs the headSha field added below. -_run_list() { - local limit status branch sha args query raw_stderr raw_rc raw err - limit=20; status=""; branch=""; sha="" - while [[ $# -gt 0 ]]; do - case "$1" in - --limit) [[ $# -gt 1 ]] || die_usage "--limit requires a value"; shift; limit="$1" ;; - --status) [[ $# -gt 1 ]] || die_usage "--status requires a value"; shift; status="$1" ;; - --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; - --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; - *) die_usage "unknown flag: $1" ;; - esac - shift - done - case "$PLATFORM" in - github) - args=(--json "databaseId,status,conclusion,workflowName,headBranch,headSha,event,createdAt,url" --limit "$limit") - [[ -n "$status" ]] && args+=(--status "$status") - [[ -n "$branch" ]] && args+=(--branch "$branch") - [[ -n "$sha" ]] && args+=(--commit "$sha") - cli_json '[.[] | {id: (.databaseId | tostring), status: (if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end), workflow: .workflowName, branch: .headBranch, head_sha: (.headSha // ""), event, started_at: .createdAt, duration: null, url: (.url // "")}]' \ - env GH_NO_COLOR=1 gh run list "${args[@]}" - ;; - gitea) - # Source from Gitea REST API directly. `tea actions runs list` - # filters server-side by a `branch` column that Gitea leaves empty - # on `pull_request` runs, so the watcher's --branch lookup misses - # correlated runs (#103). Fetch unfiltered via `tea api`, normalize - # `branch` from `head_branch`, and apply --branch client-side. - query="limit=$limit" - [[ -n "$status" ]] && query+="&status=$status" - raw_stderr=$(mktemp); raw_rc=0 - raw=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs?$query" 2>"$raw_stderr") \ - || raw_rc=$? - if [[ $raw_rc -ne 0 ]]; then - err=$(cat "$raw_stderr"); rm -f "$raw_stderr" - die "tea api repos/{owner}/{repo}/actions/runs failed: $err" - fi - rm -f "$raw_stderr" - echo "$raw" | jq --arg b "$branch" --arg s "$sha" ' - [(.workflow_runs // []) | .[] | { - id: (.id | tostring), - status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) - elif .status == "completed" then "success" - else (.status // "unknown" | ascii_downcase) end), - workflow: (.name // .workflow_id // ""), - branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), - head_sha: (.head_sha // ""), - event: (.event // ""), - started_at: (.run_started_at // .created // ""), - duration: (.duration // null), - url: (.url // "") - }] - | if $b == "" then . else [.[] | select(.branch == $b)] end - | if $s == "" then . else - [.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))] - end - ' - ;; - esac -} - -# Show one CI run as normalized JSON, including per-job status. -_run_show() { - local run_id view_stderr view_rc view_json jobs_array jobs_json failed_log err - [[ $# -ge 1 ]] || die_usage "usage: git-wait run show <run-id>" - run_id="$1" - case "$PLATFORM" in - github) - cli_json \ - 'def resolve_status: if .conclusion and .conclusion != "" then (.conclusion | ascii_downcase) elif .status == "completed" then "success" else (.status | ascii_downcase) end; {id: (.databaseId | tostring), status: resolve_status, workflow: .workflowName, branch: .headBranch, event, started_at: .createdAt, url: (.url // ""), jobs: [.jobs[] | {id: (.databaseId | tostring), name, status: resolve_status, steps: [.steps[] | {name, status: resolve_status}]}]}' \ - env GH_NO_COLOR=1 gh run view "$run_id" \ - --json "databaseId,status,conclusion,workflowName,headBranch,event,createdAt,jobs,url" - ;; - gitea) - # Fetch the run object via the REST API. `tea actions runs view` - # ignores `--output json` (tea 0.14.1) and prints a human key/value - # table while still exiting 0, so jq downstream chokes (#133). Use the - # same `tea api` pattern as run:list and the jobs lookup below. - view_stderr=$(mktemp); view_rc=0 - view_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id" 2>"$view_stderr") \ - || view_rc=$? - if [[ $view_rc -ne 0 ]]; then - err=$(cat "$view_stderr"); rm -f "$view_stderr" - die "tea api repos/{owner}/{repo}/actions/runs/$run_id failed: $err" - fi - rm -f "$view_stderr" - - # Fetch per-job data via the actions API so callers (run watch) can - # detect job-level failures masked by run-level status=success on - # Gitea (see _run_failed_jobs). tea api substitutes {owner}/{repo}. - jobs_array='[]' - jobs_json=$(NO_COLOR=1 tea api "repos/{owner}/{repo}/actions/runs/$run_id/jobs" 2>/dev/null || true) - if [[ -n "$jobs_json" ]]; then - jobs_array=$(echo "$jobs_json" | jq -c ' - def to_status: - if (.conclusion // "") != "" then (.conclusion | ascii_downcase) - elif .status == "completed" then "success" - else (.status // "unknown" | ascii_downcase) - end; - [(.jobs // .) | (if type == "array" then .[]? else empty end) | - {id: ((.id // 0) | tostring), name: (.name // ""), status: to_status}] - ' 2>/dev/null) || jobs_array='[]' - fi - - # Older Gitea versions may not expose the jobs API; fall back to - # scanning the run logs for "Job '<name>' failed" lines. - if [[ "$jobs_array" == '[]' ]]; then - failed_log=$(NO_COLOR=1 tea actions runs logs "$run_id" 2>/dev/null \ - | grep -oE "Job '[^']+' failed" \ - | sed -E "s/Job '(.+)' failed/\1/" \ - | sort -u || true) - if [[ -n "$failed_log" ]]; then - jobs_array=$(printf '%s\n' "$failed_log" \ - | jq -R -s -c 'split("\n") | map(select(length > 0)) | map({id: "", name: ., status: "failure"})') - fi - fi - - # Normalize REST field names into the output contract, mirroring the - # run:list jq above (conclusion-first status, head_branch//branch, - # run_started_at//created, name//workflow_id). - echo "$view_json" | jq --argjson jobs "$jobs_array" '{ - id: (.id | tostring), - status: (if (.conclusion // "") != "" then (.conclusion | ascii_downcase) - elif .status == "completed" then "success" - else (.status // "unknown" | ascii_downcase) end), - workflow: (.name // .workflow_id // ""), - branch: (((.head_branch // "") | select(. != "")) // (.branch // "")), - event: (.event // ""), - started_at: (.run_started_at // .created // ""), - duration: (.duration // null), - url: (.url // ""), - jobs: $jobs - }' - ;; - esac -} - -# Stream a CI run's logs. Flag: --failed-only (GitHub honours it natively; -# Gitea has no server-side filter and returns every job's log). -_run_logs() { - local run_id failed_only - [[ $# -ge 1 ]] || die_usage "usage: git-wait run logs <run-id> [--failed-only]" - run_id="$1"; shift - failed_only=false - while [[ $# -gt 0 ]]; do - case "$1" in - --failed-only) failed_only=true ;; - *) die_usage "unknown flag: $1" ;; - esac - shift - done - case "$PLATFORM" in - github) - if [[ "$failed_only" == "true" ]]; then - GH_NO_COLOR=1 gh run view "$run_id" --log-failed - else - GH_NO_COLOR=1 gh run view "$run_id" --log - fi - ;; - gitea) - # tea actions runs logs outputs all job logs; no built-in failed-only filter - NO_COLOR=1 tea actions runs logs "$run_id" - ;; - esac -} - -# --------------------------------------------------------------------------- -# Run helpers -# --------------------------------------------------------------------------- - -# Return comma-separated names of any jobs in <run_id> whose status is -# "failure", or empty if none. Used by run watch to detect job-level failures -# even when the run-level status reports success — Gitea sets run.status to -# "success" on a multi-job workflow if at least one job ran successfully, -# masking failures in earlier jobs (see issue #87). Calls "run show" to -# normalize per-platform JSON, so it works for both gh and tea paths. -_run_failed_jobs() { - local run_id="$1" show_json - show_json=$(_run_show "$run_id" 2>/dev/null) || return 0 - echo "$show_json" | jq -r '[.jobs[]? | select(.status == "failure") | .name] | join(",")' -} - -# Progress-aware timeout decision shared by `pr wait` and `run watch`. -# Echoes "ceiling" if the absolute deadline is hit, "idle" if the no-progress -# window is hit, or nothing (return 1) if neither. A bound of 0 disables it. -# A flat wall-clock timeout is the wrong primitive for CI that can run 15+ -# minutes: this lets callers keep waiting while CI is actively progressing and -# give up only after a stretch of no progress, with a hard ceiling backstop. -_wait_timed_out() { - local elapsed="$1" idle="$2" max_timeout="$3" idle_timeout="$4" - if [[ "$max_timeout" -gt 0 && "$elapsed" -ge "$max_timeout" ]]; then - echo "ceiling"; return 0 - fi - if [[ "$idle_timeout" -gt 0 && "$idle" -ge "$idle_timeout" ]]; then - echo "idle"; return 0 - fi - return 1 -} - -# Human-readable duration for alerts: 45s, 5m, 5m30s, 1h05m. -_fmt_dur() { - local s="$1" - if [[ "$s" -lt 60 ]]; then echo "${s}s" - elif [[ "$s" -lt 3600 ]]; then - if (( s % 60 == 0 )); then echo "$(( s / 60 ))m"; else echo "$(( s / 60 ))m$(( s % 60 ))s"; fi - else printf '%dh%02dm\n' $(( s / 3600 )) $(( s % 3600 / 60 )); fi -} - -# Periodic stderr heartbeat while a wait is still running. Callers set -# alert_interval (0 disables) and next_alert (initialised to alert_interval), -# and call `_heartbeat "$elapsed" "<detail>"` once per poll. Emits at most one -# alert per poll, then re-arms for the next multiple of alert_interval, so a -# slow poll never produces a burst. stderr only: stdout stays parseable. -_heartbeat() { - local el="$1" detail="$2" - [[ "${alert_interval:-0}" -gt 0 && "$el" -ge "${next_alert:-0}" ]] || return 0 - echo "git-wait: still running after $(_fmt_dur "$el") (${detail})" >&2 - next_alert=$(( (el / alert_interval + 1) * alert_interval )) -} - -# Coarse CI status — pending|success|failure|none — for a PR/branch, used by -# `pr wait` to tell whether CI is actively progressing. GitHub aggregates the -# PR's statusCheckRollup; Gitea maps the latest run's status. Every API call is -# guarded so a probe failure degrades to "none" and never aborts the wait loop. -_ci_status() { - local pr_number="$1" branch="$2" view_json run_status - case "$PLATFORM" in - github) - view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json statusCheckRollup 2>/dev/null) || { echo "none"; return 0; } - echo "$view_json" | jq -r ' - [.statusCheckRollup // [] | .[] | - if .__typename == "CheckRun" then - if .conclusion then (.conclusion | ascii_downcase) else "pending" end - else (.state // "pending" | ascii_downcase) end - ] | - if length == 0 then "none" - elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" - elif all(. == "success" or . == "neutral" or . == "skipped") then "success" - else "pending" end' 2>/dev/null || echo "none" - ;; - gitea) - run_status=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].status // "none"' 2>/dev/null) || run_status="none" - case "$run_status" in - queued|in_progress|waiting|running|pending|requested) echo "pending" ;; - failure|timed_out|cancelled|canceled|skipped) echo "failure" ;; - ""|none|null) echo "none" ;; - *) echo "success" ;; - esac - ;; - *) echo "none" ;; - esac -} - -# --------------------------------------------------------------------------- -# Command routing -# --------------------------------------------------------------------------- - -cmd="${1:-}" -sub="${2:-}" -shift 2 || shift || true - -case "$cmd:$sub" in - - # Echo the detected platform so callers know which CLI to reach for. - # PLATFORM is already resolved above; detection failure exited long before - # we got here. - platform:) - echo "$PLATFORM" - ;; - - pr:wait) - # timeout is the hard ceiling; idle_timeout is the no-progress window. - branch=""; timeout=14400; idle_timeout=300; interval=15; alert_interval=300; next_alert=300 - _t0=$SECONDS - while [[ $# -gt 0 ]]; do - case "$1" in - --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; - --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; - --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; - --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; - --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; - *) die_usage "unknown flag: $1" ;; - esac - shift - done - [[ -n "$branch" ]] || die_usage "pr wait requires --branch" - - # Find PR for this branch - pr_json=$(_pr_list --state all --limit 100 2>/dev/null) || pr_json="[]" - # Match branch — handle Gitea owner:branch format with endswith - pr=$(echo "$pr_json" | jq --arg b "$branch" \ - '[.[] | select(.head == $b or (.head | split(":") | last) == $b)] | sort_by(.number) | last // empty') - - if [[ -z "$pr" || "$pr" == "null" ]]; then - echo "status: no-pr" - echo "duration: 0s" - echo "No PR found for branch '$branch'" >&2 - exit 3 - fi - - pr_number=$(echo "$pr" | jq -r '.number') - pr_url=$(echo "$pr" | jq -r '.url // ""') - elapsed=0 - idle=0; idle_mark=0 - last_signal="" - unknown_streak=0 - - # Poll loop - while true; do - show_json=$(_pr_show "$pr_number" 2>/dev/null) || show_json="{}" - pr_state=$(echo "$show_json" | jq -r '.state // "unknown"') - pr_merged=$(echo "$show_json" | jq -r '.merged // false') - pr_mergeable=$(echo "$show_json" | jq -r '.mergeable // ""') - [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$show_json" | jq -r '.url // ""') - - # Progress signals: CI still running or auto-merge pending means the PR is - # actively advancing toward merge, so the idle clock must not count down. - checks=$(_ci_status "$pr_number" "$branch") - if [[ "$PLATFORM" == "github" ]]; then - auto_merge=$(_auto_merge_status --number "$pr_number" 2>/dev/null | sed -n 's/^auto_merge: //p' | head -1) || auto_merge="" - [[ "$auto_merge" == "true" ]] || auto_merge="false" - else - auto_merge="false" - fi - signal="$pr_state|$pr_mergeable|$checks|$auto_merge" - if [[ "$checks" == "pending" || "$auto_merge" == "true" || "$signal" != "$last_signal" ]]; then - idle=0 - fi - last_signal="$signal" - - echo "PR #$pr_number: state=$pr_state merged=$pr_merged checks=$checks auto_merge=$auto_merge (idle ${idle}s, ${elapsed}s elapsed)" >&2 - [[ "$pr_state" == "open" ]] && _heartbeat "$elapsed" "PR #$pr_number still open: checks=$checks auto_merge=$auto_merge" || true - - case "$pr_state" in - merged) - echo "status: merged" - echo "pr_number: $pr_number" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - exit 0 - ;; - closed) - if [[ "$pr_merged" == "true" ]]; then - echo "status: merged" - echo "pr_number: $pr_number" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - exit 0 - fi - echo "status: closed" - echo "pr_number: $pr_number" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "reason: PR was closed without merging" >&2 - exit 0 - ;; - open) - # Check for merge conflicts - if [[ "$pr_mergeable" == "conflicting" || "$pr_mergeable" == "false" ]]; then - echo "status: blocked" - echo "pr_number: $pr_number" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "reason: PR has merge conflicts" >&2 - exit 0 - fi - # Still open — keep polling - ;; - *) - unknown_streak=$(( unknown_streak + 1 )) - if [[ "$unknown_streak" -ge 3 ]]; then - echo "status: error" - echo "pr_number: $pr_number" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "Failed to determine PR state after $unknown_streak consecutive attempts (last state: '$pr_state')" >&2 - exit 4 - fi - echo "Unexpected PR state '$pr_state' ($unknown_streak/3 before abort), retrying..." >&2 - ;; - esac - - # Reset unknown streak on any recognized state - [[ "$pr_state" == "merged" || "$pr_state" == "closed" || "$pr_state" == "open" ]] && unknown_streak=0 - - # Check timeout — only give up after a stretch of no progress (idle) or - # the absolute ceiling, never while CI/auto-merge is still working. - timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) - if [[ -n "$timeout_kind" ]]; then - if [[ "$timeout_kind" == "ceiling" ]]; then - reason="exceeded max wait ${timeout}s" - else - reason="no progress for ${idle}s" - fi - echo "status: timeout" - echo "pr_number: $pr_number" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "reason: $reason" - echo "Timed out waiting for PR #$pr_number to merge ($reason)" >&2 - exit 2 - fi - - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed - done - ;; - - run:watch) - # timeout is the hard ceiling; idle_timeout is the no-progress backstop. - # While CI is actively pending the idle clock is reset each poll, so a long - # (15+ min) suite runs to completion up to the ceiling rather than being cut - # off by a flat wall-clock timeout. - branch=""; sha=""; initial_delay=60; timeout=14400; idle_timeout=0; interval=15 - alert_interval=300; next_alert=300; no_run_timeout="" - settle=0; settle_given=0; no_run_skew=0 - max_poll_failures=10; poll_fails=0 - _t0=$SECONDS - while [[ $# -gt 0 ]]; do - case "$1" in - --branch) [[ $# -gt 1 ]] || die_usage "--branch requires a value"; shift; branch="$1" ;; - --sha) [[ $# -gt 1 ]] || die_usage "--sha requires a value"; shift; sha="$1" ;; - --initial-delay) [[ $# -gt 1 ]] || die_usage "--initial-delay requires a value"; shift; initial_delay="$1" ;; - --timeout) [[ $# -gt 1 ]] || die_usage "--timeout requires a value"; shift; timeout="$1" ;; - --idle-timeout) [[ $# -gt 1 ]] || die_usage "--idle-timeout requires a value"; shift; idle_timeout="$1" ;; - --interval) [[ $# -gt 1 ]] || die_usage "--interval requires a value"; shift; interval="$1" ;; - --alert-interval) [[ $# -gt 1 ]] || die_usage "--alert-interval requires a value"; shift; alert_interval="$1"; next_alert="$1" ;; - --no-run-timeout) [[ $# -gt 1 ]] || die_usage "--no-run-timeout requires a value"; shift; no_run_timeout="$1" ;; - --settle) [[ $# -gt 1 ]] || die_usage "--settle requires a value"; shift; settle="$1"; settle_given=1 ;; - --max-poll-failures) [[ $# -gt 1 ]] || die_usage "--max-poll-failures requires a value"; shift; max_poll_failures="$1" ;; - *) die_usage "unknown flag: $1" ;; - esac - shift - done - [[ -n "$branch" || -n "$sha" ]] || die_usage "run watch requires --branch or --sha" - [[ -z "$branch" || -z "$sha" ]] || die_usage "run watch: pass --branch or --sha, not both" - [[ "$settle_given" -eq 0 || -n "$sha" ]] || die_usage "--settle requires --sha" - # How long to wait for the FIRST run to appear (counted from the end of - # --initial-delay). Post-merge (--sha) workflows trigger by push/tag/ - # workflow_run and can queue minutes late, so that scope gets longer. - if [[ -z "$no_run_timeout" ]]; then - if [[ -n "$sha" ]]; then no_run_timeout=600; else no_run_timeout=900; fi - fi - - # `gh run list --commit` matches only on a FULL 40-character SHA -- a short - # one returns zero rows with no error, which this watcher would report as - # "no-workflow" rather than as the caller's mistake. Expand a short SHA via - # git when the commit is local, and refuse it outright when it is not, - # rather than silently watching nothing. (Gitea matches client-side on the - # first 12 chars, so a full SHA is correct there too.) - if [[ -n "$sha" && ! "$sha" =~ ^[0-9a-fA-F]{40}$ ]]; then - _full_sha=$(git rev-parse --verify --quiet "${sha}^{commit}" 2>/dev/null) || _full_sha="" - if [[ "$_full_sha" =~ ^[0-9a-fA-F]{40}$ ]]; then - sha="$_full_sha" - else - die_usage "run watch --sha needs a full 40-character SHA (or a revision git can resolve here); got '$sha'" - fi - fi - - elapsed=0 - idle=0; idle_mark=0 - - # A failed run-list call (network, auth, rate limit) is NOT an empty list. - # Note it, keep polling, and exclude the time from the no-workflow deadline - # (accumulated in no_run_skew). The hard ceiling still applies. After - # --max-poll-failures consecutive failures it gives up (exit 4). - _poll_failed() { - local what="$1" before="$elapsed" - poll_fails=$(( poll_fails + 1 )) - echo "git-wait: run list failed for ${what} (${poll_fails} consecutive); retrying (not counted toward --no-run-timeout)" >&2 - if [[ "$max_poll_failures" -gt 0 && "$poll_fails" -ge "$max_poll_failures" ]]; then - echo "status: error" - echo "duration: ${elapsed}s" - echo "reason: run list failed ${poll_fails} consecutive times" - echo "git-wait: giving up on ${what} after ${poll_fails} consecutive run-list failures (check CLI auth/network; --max-poll-failures ${max_poll_failures})" >&2 - exit 4 - fi - elapsed=$(( SECONDS - _t0 )) - if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then - echo "status: timeout" - echo "duration: ${elapsed}s" - echo "reason: exceeded max wait ${timeout}s" - echo "Timed out waiting for CI on ${what} (run list kept failing)" >&2 - exit 2 - fi - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - no_run_skew=$(( no_run_skew + elapsed - before )) - } - - # Enforce the hard --timeout ceiling on paths that otherwise `continue` - # (no runs yet, settling, no checks registered) so they cannot outlive it. - _ceiling_check() { - local what="$1" - if [[ -n "$(_wait_timed_out "$elapsed" 0 "$timeout" 0 || true)" ]]; then - echo "status: timeout" - echo "duration: ${elapsed}s" - echo "reason: exceeded max wait ${timeout}s" - echo "Timed out waiting for CI on ${what}" >&2 - exit 2 - fi - } - - # ------------------------------------------------------------------ - # --sha: watch EVERY run for one commit, not just the newest. - # - # `--branch` deliberately follows a single run (the newest correlated - # one). That is right for a PR branch, where one push means one run, but - # wrong for a default branch: two merges landing close together produce - # two runs, and the newest going green says nothing about the older one - # still executing. Watching a post-merge release run by branch reported - # "pass" while a second run was mid-flight. - # - # A commit is the honest scope for that question — the caller wants the - # runs *their* merge caused, not whatever else is landing on the branch. - # So this path aggregates: it stays non-terminal while ANY run for the - # commit is non-terminal, and fails if ANY run (or any job within one) - # failed. - # - # The CRITICAL DESIGN RULE below applies here too: only explicitly - # non-terminal statuses keep polling; anything unrecognized counts as - # terminal so an unexpected status cannot loop until timeout. - # ------------------------------------------------------------------ - if [[ -n "$sha" ]]; then - if [[ "$initial_delay" -gt 0 ]]; then - echo "Waiting ${initial_delay}s for CI to start..." >&2 - sleep "$initial_delay" - elapsed=$(( SECONDS - _t0 )) - fi - _nr0=$SECONDS; idle_mark=$elapsed - - echo "Watching all runs for commit ${sha:0:12}..." >&2 - - # Settle window: after every run is terminal and passing, keep polling - # --settle seconds for a chained (workflow_run) run before reporting pass. - settle_start=-1; settle_ids="" - - while true; do - if ! sha_json=$(_run_list --sha "$sha" --limit 50); then - _poll_failed "commit ${sha:0:12}" - continue - fi - poll_fails=0 - sha_count=$(echo "$sha_json" | jq -r 'length' 2>/dev/null || echo 0) - - if [[ "$sha_count" -eq 0 ]]; then - no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) - [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 - if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then - echo "status: no-workflow" - echo "duration: ${elapsed}s" - echo "No CI workflow found for commit ${sha:0:12} after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 - exit 3 - fi - echo "git-wait: no runs yet for ${sha:0:12}, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 - _ceiling_check "commit ${sha:0:12}" - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - continue - fi - - # Non-terminal set is explicit; everything else is terminal. - pending=$(echo "$sha_json" | jq -r ' - [.[] | select(.status == "queued" or .status == "in_progress" - or .status == "waiting" or .status == "running" - or .status == "pending" or .status == "requested")] - | length') - - echo "Commit ${sha:0:12}: $sha_count run(s), $pending pending (${elapsed}s elapsed)" >&2 - - if [[ "$pending" -gt 0 ]]; then - pending_names=$(echo "$sha_json" | jq -r ' - [.[] | select(.status == "queued" or .status == "in_progress" - or .status == "waiting" or .status == "running" - or .status == "pending" or .status == "requested") - | (.workflow // .id)] | join(", ")') - _heartbeat "$elapsed" "$pending run(s) pending: $pending_names" - # Active CI is progress — reset the idle clock, same as --branch. - idle=0 - settle_start=-1 - else - # Every run terminal. Collect run-level and job-level failures - # across ALL of them before declaring pass (#87 applies per run). - all_failed="" - fail_url="" - while IFS=$'\t' read -r r_id r_status r_url; do - [[ -n "$r_id" ]] || continue - case "$r_status" in - failure|timed_out|cancelled|canceled|skipped) - all_failed+="${all_failed:+,}run-$r_id:$r_status" - [[ -n "$fail_url" ]] || fail_url="$r_url" - ;; - *) - r_failed=$(_run_failed_jobs "$r_id") - if [[ -n "$r_failed" ]]; then - all_failed+="${all_failed:+,}$r_failed" - [[ -n "$fail_url" ]] || fail_url="$r_url" - fi - ;; - esac - done < <(echo "$sha_json" | jq -r '.[] | [.id, (.status // "unknown"), (.url // "")] | @tsv') - - if [[ -n "$all_failed" ]]; then - echo "status: fail" - [[ -n "$fail_url" && "$fail_url" != "null" ]] && echo "url: $fail_url" - echo "duration: ${elapsed}s" - echo "failed_jobs: $all_failed" - echo "--- Failed job logs (last 80 lines) ---" >&2 - echo "$sha_json" | jq -r '.[].id' | while read -r r_id; do - _run_logs "$r_id" --failed-only 2>/dev/null | tail -80 >&2 || true - done - exit 0 - fi - - if [[ "$settle" -gt 0 ]]; then - cur_ids=$(echo "$sha_json" | jq -r '[.[].id | tostring] | sort | join(",")') - if [[ "$settle_start" -ge 0 && "$cur_ids" != "$settle_ids" ]]; then - echo "git-wait: new run appeared for ${sha:0:12} while settling; continuing to watch" >&2 - settle_start=-1 - fi - if [[ "$settle_start" -lt 0 ]]; then - settle_start=$elapsed; settle_ids="$cur_ids" - fi - if [[ $(( elapsed - settle_start )) -lt "$settle" ]]; then - echo "git-wait: all runs for ${sha:0:12} passed; settling $(( elapsed - settle_start ))s of ${settle}s for chained workflows" >&2 - _ceiling_check "commit ${sha:0:12}" - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - continue - fi - fi - - echo "status: pass" - first_url=$(echo "$sha_json" | jq -r '.[0].url // ""') - [[ -n "$first_url" && "$first_url" != "null" ]] && echo "url: $first_url" - echo "duration: ${elapsed}s" - echo "runs: $sha_count" >&2 - exit 0 - fi - - timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) - if [[ -n "$timeout_kind" ]]; then - if [[ "$timeout_kind" == "ceiling" ]]; then - reason="exceeded max wait ${timeout}s" - else - reason="no progress for ${idle}s" - fi - echo "status: timeout" - echo "duration: ${elapsed}s" - echo "reason: $reason" - echo "Timed out waiting for CI on commit ${sha:0:12} ($reason)" >&2 - exit 2 - fi - - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed - done - fi - - # Gitea leaves head_branch/branch empty on pull_request-triggered runs, so - # `run list --branch` correlates nothing and the watcher times out into - # no-workflow even when CI ran (#140). Resolve the branch head SHA up front - # (only on Gitea) and fall back to head_sha correlation when the - # branch-filtered lookup is empty. The run object's head_sha equals the - # branch head on Gitea (confirmed in #140); if a variant ever records a - # merge-ref SHA the fallback simply misses and degrades to today's - # behaviour rather than returning a wrong run. - _watch_branch_sha="" - if [[ "$PLATFORM" == "gitea" ]]; then - _watch_branch_sha=$(git rev-parse "$branch" 2>/dev/null \ - || git rev-parse "origin/$branch" 2>/dev/null || true) - fi - - # Echo a run-list JSON array for $branch: branch-name correlation first, - # head_sha correlation as a fallback (Gitea). Platform-safe — on GitHub the - # server-side --branch filter populates the first call and _watch_branch_sha - # stays empty, so the SHA path is never taken. - _runs_for_branch() { - local lim="${1:-1}" out - # A failed call returns 1 (distinct from a successful empty "[]"). - out=$(_run_list --branch "$branch" --limit "$lim") || return 1 - if [[ "$(echo "$out" | jq -r 'length' 2>/dev/null || echo 0)" -gt 0 ]]; then - echo "$out"; return 0 - fi - if [[ -n "$_watch_branch_sha" ]]; then - _run_list --limit 50 | jq \ - --arg s "$_watch_branch_sha" --argjson n "$lim" \ - '[.[] | select(.head_sha != "" and (.head_sha[0:12]) == ($s[0:12]))][0:$n]' \ - || return 1 - return 0 - fi - echo "[]" - } - - # On GitHub, prefer PR-based status checking — one API call gives us both - # merge state and all CI check results via statusCheckRollup, avoiding the - # flaky run-level polling that produces "unknown" statuses. - pr_number="" - pr_url="" - use_pr=false - if [[ "$PLATFORM" == "github" ]]; then - pr_json=$(GH_NO_COLOR=1 gh pr view "$branch" --json number,url 2>/dev/null) && { - pr_number=$(echo "$pr_json" | jq -r '.number // empty') - pr_url=$(echo "$pr_json" | jq -r '.url // ""') - [[ -n "$pr_number" ]] && use_pr=true - } - fi - - # Pre-check: look for an already-terminal state before sleeping the - # initial delay. If the PR already merged or CI already finished, - # report immediately instead of waiting. - _precheck_done=false - if [[ "$use_pr" == "true" ]]; then - _pre_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null) || _pre_json="{}" - _pre_state=$(echo "$_pre_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') - [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$_pre_json" | jq -r '.url // ""') - - if [[ "$_pre_state" == "merged" ]]; then - echo "status: pass" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: 0s" - echo "PR #$pr_number already merged" >&2 - exit 0 - fi - if [[ "$_pre_state" == "closed" ]]; then - echo "status: closed" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: 0s" - echo "PR #$pr_number already closed without merging" >&2 - exit 0 - fi - - _pre_checks=$(echo "$_pre_json" | jq -r ' - [.statusCheckRollup // [] | .[] | - if .__typename == "CheckRun" then - if .conclusion then (.conclusion | ascii_downcase) - else "pending" - end - else (.state // "pending" | ascii_downcase) - end - ] | - if length == 0 then "pending" - elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" - elif all(. == "success" or . == "neutral" or . == "skipped") then "success" - else "pending" - end') - - if [[ "$_pre_checks" == "success" ]]; then - echo "status: pass" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: 0s" - echo "CI already passed on PR #$pr_number" >&2 - exit 0 - fi - - if [[ "$_pre_checks" == "failure" ]]; then - _pre_failed=$(echo "$_pre_json" | jq -r ' - [.statusCheckRollup // [] | .[] | - select( - (.__typename == "CheckRun" and .conclusion and - ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or - (.__typename != "CheckRun" and .state and - ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) - ) | .name // .context // "unknown" - ] | join(",")') - echo "status: fail" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: 0s" - echo "failed_jobs: $_pre_failed" - run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true - if [[ -n "$run_id" ]]; then - echo "--- Failed job logs (last 80 lines) ---" >&2 - _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true - fi - exit 0 - fi - else - # Fallback path: check if a completed run already exists - _pre_list=$(_runs_for_branch 1) || _pre_list="[]" - _pre_latest=$(echo "$_pre_list" | jq -r '.[0] // empty') - if [[ -n "$_pre_latest" && "$_pre_latest" != "null" ]]; then - _pre_status=$(echo "$_pre_latest" | jq -r '.status // "unknown"') - _pre_url=$(echo "$_pre_latest" | jq -r '.url // ""') - _pre_id=$(echo "$_pre_latest" | jq -r '.id') - case "$_pre_status" in - success|completed) - # Run-level status can read "success" on Gitea even when a - # job inside the run failed (issue #87). Aggregate per-job - # status before declaring pass. - failed_jobs=$(_run_failed_jobs "$_pre_id") - if [[ -n "$failed_jobs" ]]; then - echo "status: fail" - [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" - echo "duration: 0s" - echo "failed_jobs: $failed_jobs" - echo "--- Failed job logs (last 80 lines) ---" >&2 - _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true - exit 0 - fi - echo "status: pass" - [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" - echo "duration: 0s" - echo "CI already passed for branch '$branch'" >&2 - exit 0 - ;; - failure|timed_out) - failed_jobs=$(_run_failed_jobs "$_pre_id") - echo "status: fail" - [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" - echo "duration: 0s" - echo "failed_jobs: $failed_jobs" - if [[ -n "$_pre_id" ]]; then - echo "--- Failed job logs (last 80 lines) ---" >&2 - _run_logs "$_pre_id" --failed-only 2>/dev/null | tail -80 >&2 || true - fi - exit 0 - ;; - cancelled|canceled|skipped) - # Distinct terminal states — surface them as fail with a - # reason so consumers (ship/session-end) gating on - # status: pass stop instead of advancing. - echo "status: fail" - [[ -n "$_pre_url" && "$_pre_url" != "null" ]] && echo "url: $_pre_url" - echo "duration: 0s" - echo "reason: $_pre_status" - echo "CI run $_pre_status for branch '$branch'" >&2 - exit 0 - ;; - esac - fi - fi - - # Initial delay — CI run may not exist immediately after push - if [[ "$initial_delay" -gt 0 ]]; then - echo "Waiting ${initial_delay}s for CI to start..." >&2 - sleep "$initial_delay" - elapsed=$(( SECONDS - _t0 )) - fi - _nr0=$SECONDS; idle_mark=$elapsed - - if [[ "$use_pr" == "true" ]]; then - echo "Watching PR #$pr_number for branch '$branch'..." >&2 - - while true; do - # A failed gh call is not "unknown" -- count it, cap consecutive failures. - if ! view_json=$(GH_NO_COLOR=1 gh pr view "$pr_number" --json state,statusCheckRollup,url 2>/dev/null); then - _poll_failed "PR #$pr_number" - continue - fi - poll_fails=0 - pr_state=$(echo "$view_json" | jq -r '.state // "UNKNOWN" | ascii_downcase') - [[ -z "$pr_url" || "$pr_url" == "null" ]] && pr_url=$(echo "$view_json" | jq -r '.url // ""') - - # PR merged — all done - if [[ "$pr_state" == "merged" ]]; then - echo "status: pass" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "PR #$pr_number merged" >&2 - exit 0 - fi - - # PR closed without merge - if [[ "$pr_state" == "closed" ]]; then - echo "status: closed" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "PR #$pr_number closed without merging" >&2 - exit 0 - fi - - # Summarize CI check statuses from statusCheckRollup - # CheckRun: conclusion (SUCCESS/FAILURE/null if pending), StatusContext: state - checks_summary=$(echo "$view_json" | jq -r ' - [.statusCheckRollup // [] | .[] | - if .__typename == "CheckRun" then - if .conclusion then (.conclusion | ascii_downcase) - else "pending" - end - else (.state // "pending" | ascii_downcase) - end - ] | - if length == 0 then "pending" - elif any(. == "failure" or . == "error" or . == "timed_out" or . == "action_required") then "failure" - elif all(. == "success" or . == "neutral" or . == "skipped") then "success" - else "pending" - end') - - echo "PR #$pr_number: state=$pr_state checks=$checks_summary (${elapsed}s elapsed)" >&2 - - case "$checks_summary" in - success) - echo "status: pass" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - exit 0 - ;; - failure) - failed_names=$(echo "$view_json" | jq -r ' - [.statusCheckRollup // [] | .[] | - select( - (.__typename == "CheckRun" and .conclusion and - ((.conclusion | ascii_downcase) == "failure" or (.conclusion | ascii_downcase) == "error" or (.conclusion | ascii_downcase) == "timed_out")) or - (.__typename != "CheckRun" and .state and - ((.state | ascii_downcase) == "failure" or (.state | ascii_downcase) == "error")) - ) | .name // .context // "unknown" - ] | join(",")') - echo "status: fail" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "failed_jobs: $failed_names" - # Try to fetch failed logs from the latest run - run_id=$(_run_list --branch "$branch" --limit 1 2>/dev/null | jq -r '.[0].id // empty') || true - if [[ -n "$run_id" ]]; then - echo "--- Failed job logs (last 80 lines) ---" >&2 - _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true - fi - exit 0 - ;; - pending) - # Still running — keep polling. Active CI is progress, so reset idle. - check_count=$(echo "$view_json" | jq -r '(.statusCheckRollup // []) | length') - if [[ "$check_count" -eq 0 ]]; then - # Nothing registered yet: bounded by --no-run-timeout, like the run-list path. - no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) - [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 - if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then - echo "status: no-workflow" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "No CI checks registered on PR #$pr_number after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 - exit 3 - fi - echo "git-wait: no checks yet on PR #$pr_number, still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 - else - # Active CI is progress, so reset idle. - idle=0 - fi - pending_names=$(echo "$view_json" | jq -r ' - [.statusCheckRollup // [] | .[] | - select(if .__typename == "CheckRun" then (.conclusion // "") == "" - else ((.state // "pending" | ascii_downcase) | . == "pending" or . == "expected") end) - | .name // .context // "unknown"] | unique | join(", ")') - _heartbeat "$elapsed" "PR #$pr_number checks pending: ${pending_names:-none registered yet}" - ;; - esac - - # Check timeout — idle window or absolute ceiling (see _wait_timed_out). - timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) - if [[ -n "$timeout_kind" ]]; then - if [[ "$timeout_kind" == "ceiling" ]]; then - reason="exceeded max wait ${timeout}s" - else - reason="no progress for ${idle}s" - fi - echo "status: timeout" - [[ -n "$pr_url" && "$pr_url" != "null" ]] && echo "url: $pr_url" - echo "duration: ${elapsed}s" - echo "reason: $reason" - echo "Timed out waiting for CI on PR #$pr_number ($reason)" >&2 - exit 2 - fi - - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed - done - fi - - # Fallback: no PR found — poll run list directly (skip flaky run show). - # - # CRITICAL DESIGN RULE — default-terminal polling: - # - # This loop has caused repeated regressions (#53, #57, #58, #60). - # The recurring bug pattern is: - # 1. The API returns an unexpected status value (e.g. "completed" - # with null conclusion, or a new status GitHub adds later). - # 2. The case statement doesn't recognise it. - # 3. A catch-all `*) keep polling` silently loops until timeout. - # - # The fix (applied here) inverts the logic: - # - ONLY explicitly non-terminal states keep polling. - # - The `*` catch-all EXITS (as pass). - # - # DO NOT add a `*) keep polling` catch-all to this case statement. - # If a new non-terminal status appears, add it to the explicit list. - # If you're unsure whether a status is terminal, it's safer to exit - # early (the caller can retry) than to loop for 5 minutes. - # - run_url="" - while true; do - if ! list_json=$(_runs_for_branch 1); then - _poll_failed "branch '$branch'" - continue - fi - poll_fails=0 - latest=$(echo "$list_json" | jq -r '.[0] // empty') - - if [[ -z "$latest" || "$latest" == "null" ]]; then - no_run_waited=$(( SECONDS - _nr0 - no_run_skew )) - [[ "$no_run_waited" -ge 0 ]] || no_run_waited=0 - if [[ "$no_run_waited" -ge "$no_run_timeout" ]]; then - echo "status: no-workflow" - echo "duration: ${elapsed}s" - # Distinguish "no workflow registered at all" from "runs exist - # but none correlate to this branch" so callers (#103) can tell - # a real CI absence from a branch-correlation gap. - any_runs=$(_run_list --limit 1 2>/dev/null | jq -r '.[0] // empty') || any_runs="" - if [[ -n "$any_runs" && "$any_runs" != "null" ]]; then - echo "CI workflow runs exist but none correlate to branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 - else - echo "No CI workflow found for branch '$branch' after ${no_run_waited}s of waiting (--no-run-timeout ${no_run_timeout}s)" >&2 - fi - exit 3 - fi - echo "git-wait: no runs yet for '$branch', still waiting (${no_run_waited}s of ${no_run_timeout}s)" >&2 - _ceiling_check "branch '$branch'" - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - continue - fi - - run_id=$(echo "$latest" | jq -r '.id') - run_status=$(echo "$latest" | jq -r '.status // "unknown"') - run_url=$(echo "$latest" | jq -r '.url // ""') - - echo "Run $run_id: $run_status (${elapsed}s elapsed)" >&2 - - # See "CRITICAL DESIGN RULE" above — non-terminal states are listed - # explicitly; everything else exits. Do NOT add a `*) keep polling`. - case "$run_status" in - queued|in_progress|waiting|running|pending|requested) - # Non-terminal — keep polling. Active CI is progress, so reset idle. - idle=0 - _heartbeat "$elapsed" "1 run pending: $(echo "$latest" | jq -r '.workflow // .id')" - ;; - failure|timed_out) - failed_jobs=$(_run_failed_jobs "$run_id") - echo "status: fail" - [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" - echo "duration: ${elapsed}s" - echo "failed_jobs: $failed_jobs" - if [[ -n "$run_id" ]]; then - echo "--- Failed job logs (last 80 lines) ---" >&2 - _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true - fi - exit 0 - ;; - cancelled|canceled|skipped) - # Distinct terminal states — surface them as fail with a reason - # so consumers gating on status: pass stop instead of advancing. - echo "status: fail" - [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" - echo "duration: ${elapsed}s" - echo "reason: $run_status" - echo "CI run $run_status on branch '$branch'" >&2 - exit 0 - ;; - *) - # Terminal — covers success and any future/unexpected status. - # Even when the run-level status reports success, an individual - # job may have failed (Gitea reports run.status=success on a - # multi-job run if any job succeeded; see #87). Aggregate - # per-job status before declaring pass. - failed_jobs=$(_run_failed_jobs "$run_id") - if [[ -n "$failed_jobs" ]]; then - echo "status: fail" - [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" - echo "duration: ${elapsed}s" - echo "failed_jobs: $failed_jobs" - echo "--- Failed job logs (last 80 lines) ---" >&2 - _run_logs "$run_id" --failed-only 2>/dev/null | tail -80 >&2 || true - exit 0 - fi - echo "status: pass" - [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" - echo "duration: ${elapsed}s" - exit 0 - ;; - esac - - timeout_kind=$(_wait_timed_out "$elapsed" "$idle" "$timeout" "$idle_timeout" || true) - if [[ -n "$timeout_kind" ]]; then - if [[ "$timeout_kind" == "ceiling" ]]; then - reason="exceeded max wait ${timeout}s" - else - reason="no progress for ${idle}s" - fi - echo "status: timeout" - [[ -n "$run_url" && "$run_url" != "null" ]] && echo "url: $run_url" - echo "duration: ${elapsed}s" - echo "reason: $reason" - echo "Timed out waiting for CI on branch '$branch' ($reason)" >&2 - exit 2 - fi - - sleep "$interval" - elapsed=$(( SECONDS - _t0 )) - idle=$(( idle + elapsed - idle_mark )); idle_mark=$elapsed - done - ;; - - --help:|-h:|:) - sed -n '2,/^$/p' "$SELF" | sed 's/^# \{0,1\}//' - exit 0 - ;; - - *) - die_usage "unknown command: $cmd${sub:+ $sub}" - ;; -esac diff --git a/plugins-opencode/session/scripts/sitrep b/plugins-opencode/session/scripts/sitrep deleted file mode 100755 index 558f9e3..0000000 --- a/plugins-opencode/session/scripts/sitrep +++ /dev/null @@ -1,246 +0,0 @@ -#!/usr/bin/env bash -# sitrep - Situation report for a git repository -# Always shows working-tree state (staged/unstaged/untracked) together with -# committed context, and falls back to broader repo activity only when -# nothing else is actionable. -# -# Sections: -# 1. Working tree (staged/unstaged/untracked) -# 2. Unpushed commits (ahead of remote tracking branch) -# 3. Branch work (commits on feature branch vs base) -# 4. Repo activity (active branches, open issues) - only when 1-3 are empty -# -# Each diff section is capped at SITREP_MAX_DIFF_LINES lines (default 2000). -# -# Exit codes: 0 success (including -h/--help), 1 bad usage - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -MAX_DIFF_LINES="${SITREP_MAX_DIFF_LINES:-2000}" - -usage() { - cat <<'EOF' -Usage: sitrep [directory] - -Situation report for a git repository. Shows working-tree changes plus -unpushed and branch commits, expanding to broader repo activity only -when everything is clean. - -If directory is omitted, uses the current working directory. -EOF -} - -if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then - usage - exit 0 -fi - -if [[ $# -gt 1 ]]; then - usage >&2 - exit 1 -fi - -dir="${1:-.}" -cd "$dir" - -gitq() { - git -c core.quotepath=false "$@" -} - -# Print a diff section, truncated to MAX_DIFF_LINES. -emit_diff() { - local title="$1" text="$2" total - [[ -n "$text" ]] || return 0 - total="$(printf '%s\n' "$text" | wc -l)" - echo "" - echo "=== $title ===" - if ((total > MAX_DIFF_LINES)); then - printf '%s\n' "$text" | head -n "$MAX_DIFF_LINES" - echo "[truncated $((total - MAX_DIFF_LINES)) lines]" - else - printf '%s\n' "$text" - fi -} - -# --- Not a git repo --- -if ! gitq rev-parse --git-dir >/dev/null 2>&1; then - echo "=== REPO ===" - echo "is_git_repo: false" - exit 0 -fi - -# --- Basic repo info (always shown) --- -head_branch="$(gitq symbolic-ref --quiet --short HEAD 2>/dev/null || true)" -head_sha="$(gitq rev-parse --short HEAD 2>/dev/null || echo "unknown")" - -echo "=== REPO ===" -if [[ -n "$head_branch" ]]; then - echo "branch: $head_branch" -else - echo "detached_at: $head_sha" -fi - -# Detect base branch: origin/HEAD, then origin/main|master, then local main|master -base_ref="" -origin_head="$(gitq symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)" -for candidate in "$origin_head" "origin/main" "origin/master" "main" "master"; do - [[ -n "$candidate" ]] || continue - if gitq rev-parse --verify --quiet "$candidate^{commit}" >/dev/null 2>&1; then - base_ref="$candidate" - break - fi -done - -on_base=false -if [[ -z "$base_ref" || "$head_branch" == "$base_ref" || "$head_branch" == "${base_ref#origin/}" ]]; then - on_base=true -fi - -has_merge_base=false -if [[ -n "$base_ref" ]]; then - echo "base: $base_ref" - if ! $on_base; then - if gitq merge-base "$base_ref" HEAD >/dev/null 2>&1; then - has_merge_base=true - else - echo "note: no merge base between $base_ref and HEAD (unrelated histories)" - fi - ahead="$(gitq rev-list --count "$base_ref..HEAD" 2>/dev/null || echo 0)" - behind="$(gitq rev-list --count "HEAD..$base_ref" 2>/dev/null || echo 0)" - echo "ahead: $ahead" - echo "behind: $behind" - fi -fi - -found_activity=false - -# --- Working tree: staged / unstaged / untracked --- -staged_files="$(gitq diff --name-status --cached --find-renames 2>/dev/null || true)" -unstaged_files="$(gitq diff --name-status --find-renames 2>/dev/null || true)" -untracked_files="$(gitq ls-files --others --exclude-standard 2>/dev/null || true)" - -if [[ -n "$staged_files" ]]; then - found_activity=true - echo "" - echo "=== STAGED ===" - echo "$staged_files" - emit_diff "STAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --cached --find-renames 2>/dev/null || true)" -fi - -if [[ -n "$unstaged_files" ]]; then - found_activity=true - echo "" - echo "=== UNSTAGED ===" - echo "$unstaged_files" - emit_diff "UNSTAGED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames 2>/dev/null || true)" -fi - -if [[ -n "$untracked_files" ]]; then - found_activity=true - echo "" - echo "=== UNTRACKED ===" - echo "$untracked_files" -fi - -# --- Unpushed commits --- -tracking_branch="$(gitq rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)" -unpushed="" - -if [[ -n "$tracking_branch" ]]; then - unpushed="$(gitq log --oneline "$tracking_branch..HEAD" 2>/dev/null || true)" -fi - -if [[ -n "$unpushed" ]]; then - found_activity=true - echo "" - echo "=== UNPUSHED ===" - echo "tracking: $tracking_branch" - echo "$unpushed" -fi - -# --- Branch work (feature branch vs base) --- -if ! $on_base && [[ -n "$base_ref" ]]; then - branch_commits="$(gitq log --oneline "$base_ref..HEAD" 2>/dev/null || true)" - if [[ -n "$branch_commits" ]]; then - found_activity=true - echo "" - echo "=== BRANCH COMMITS ===" - echo "$branch_commits" - fi - - if $has_merge_base; then - committed_files="$(gitq diff --name-status --find-renames "$base_ref...HEAD" 2>/dev/null || true)" - if [[ -n "$committed_files" ]]; then - found_activity=true - echo "" - echo "=== CHANGED FILES ===" - echo "$committed_files" - emit_diff "COMMITTED DIFF" "$(gitq diff --no-color --minimal --unified=0 --find-renames "$base_ref...HEAD" 2>/dev/null || true)" - fi - fi -fi - -if $found_activity; then - exit 0 -fi - -# --- Repo activity (everything clean, nothing ahead) --- -active_branches="" -if [[ -n "$base_ref" ]]; then - active_branches="$(gitq branch --no-merged "$base_ref" --format '%(refname:short)' 2>/dev/null || true)" -fi - -if [[ -n "$active_branches" ]]; then - echo "" - echo "=== ACTIVE BRANCHES ===" - echo "$active_branches" -fi - -# Open issues (requires git-wait for platform detection, plus gh or tea) -if [[ -x "$SCRIPT_DIR/git-wait" ]]; then - platform="$(bash "$SCRIPT_DIR/git-wait" platform 2>/dev/null || true)" - issues="" - issues_err="" - errfile="$(mktemp)" - case "$platform" in - github) - if command -v gh >/dev/null 2>&1; then - issues="$(gh issue list --state open --limit 10 --json number,title 2>"$errfile")" || issues_err="gh issue list failed" - fi - ;; - gitea) - if command -v tea >/dev/null 2>&1; then - issues="$(tea issues list --state open --limit 10 --output json --fields index,title 2>"$errfile")" || issues_err="tea issues list failed" - fi - ;; - esac - if [[ -n "$issues_err" ]]; then - detail="$(head -n 1 "$errfile" 2>/dev/null || true)" - echo "" - echo "=== OPEN ISSUES ===" - echo "note: $issues_err${detail:+: $detail}" - elif [[ -n "$issues" && "$issues" != "[]" ]]; then - formatted="$(printf '%s' "$issues" | jq -r '.[] | "#\(.number // .index) \(.title)"' 2>/dev/null || true)" - echo "" - echo "=== OPEN ISSUES ===" - if [[ -n "$formatted" ]]; then - echo "$formatted" - else - echo "note: could not parse issue list" - fi - fi - rm -f "$errfile" -fi - -# Recent commits on default branch for context -echo "" -echo "=== RECENT COMMITS ===" -gitq log --oneline -10 2>/dev/null || true - -# Nothing at all -if [[ -z "$active_branches" ]]; then - echo "" - echo "=== STATUS ===" - echo "clean: true" -fi diff --git a/plugins-opencode/session/skills/session-issue/reference/spine.md b/plugins-opencode/session/skills/session-issue/reference/spine.md index efc0289..d41d7ac 100644 --- a/plugins-opencode/session/skills/session-issue/reference/spine.md +++ b/plugins-opencode/session/skills/session-issue/reference/spine.md @@ -150,39 +150,22 @@ Decide silently: done ``` - Add the detected names **without asking** to `worktree.symlinkDirectories` in the - project's **`.claude/settings.local.json`** (`Local` scope — per-checkout, - normally gitignored; never the tracked `.claude/settings.json`, never global). - Merge with `jq`, unioning with any existing list and preserving all other keys; - create the file if absent. With the detected names in `$dirs` as a JSON array - (e.g. `'["node_modules",".venv"]'`): + OpenCode's `worktree_create` has no symlink-provisioning setting (its + `worktree` config only takes `directory`), so there is no project-config + write here: just record the detected dir names — Phase 1 step 2 symlinks + them into the new worktree manually. - ```bash - f=.claude/settings.local.json - mkdir -p .claude - [ -s "$f" ] || echo '{}' > "$f" - jq --argjson d "$dirs" \ - '.worktree.symlinkDirectories = ((.worktree.symlinkDirectories // []) + $d | unique)' \ - "$f" > "$f.tmp" && mv "$f.tmp" "$f" - git check-ignore -q "$f" \ - || echo "/$f" >> "$(git rev-parse --path-format=absolute --git-path info/exclude)" - ``` - - Skip this step if no dependency directory was detected. Add `.env` / `.env.*` to a - root `.worktreeinclude` only if they exist. That file has no documented - alternative location, so keep it out of `git status` instead: if it is untracked, - add `/.worktreeinclude` to the same `info/exclude`. If the repo already tracks a - `.worktreeinclude`, append to it only when a needed pattern is missing and - mention the resulting diff in the Phase 4 report, since that one is a real change. + Skip this step if no dependency directory was detected. Include `.env` / + `.env.*` files in the recorded set when they exist and the work needs + them. 2. **Create + enter the worktree:** call `opencode.worktree_create` with `name` set to the base name (already dash form, no `/`). This creates the worktree (with its own branch) and returns its directory; then move this session into it with `opencode.session_move` (Code Mode). Do **not** also run `branch create`. - This assumes `worktree.symlinkDirectories` is read at `worktree_create` time. As a - fallback, for each detected dependency directory missing in the new worktree, - create it yourself: `ln -s "<main-checkout>/<dir>" "<dir>"`. + Symlink each detected dependency directory into the new worktree: + `ln -s "<main-checkout>/<dir>" "<dir>"`. 3. **Keep the tree clean for `ship`.** A directory pattern with a trailing slash (e.g. `node_modules/`) does not match a *symlink*, so a symlinked dependency diff --git a/plugins-opencode/session/skills/session-orchestrate/SKILL.md b/plugins-opencode/session/skills/session-orchestrate/SKILL.md index 13d747c..e4a7bb4 100644 --- a/plugins-opencode/session/skills/session-orchestrate/SKILL.md +++ b/plugins-opencode/session/skills/session-orchestrate/SKILL.md @@ -39,7 +39,12 @@ Orchestrate persists its state under the git dir so a later session can resume. Orchestrate runs are heavy and long-lived — **isolate them in a git worktree by default** so the main checkout stays clean and parallel sessions can coexist. - **Already isolated** — if the session is already in a worktree, or a feature branch is already checked out (inherited from `session-start` or `session-issue`, or the current branch is not the default), proceed in the current checkout. Do **not** create another worktree. -- **Fresh run on the default branch** — create the work's branch as a worktree by default. Derive the name: `<type>-<slug>` from the issue (no number — that lives in the PR's `Closes #N`), or `wip-<slug>` from the description. **Before** creating, provision dependencies exactly as in `reference/spine.md` Phase 1 step 1 (detect heavy gitignored dirs via `git check-ignore`; write `worktree.symlinkDirectories` + `.worktreeinclude` to **project** config without asking). Then call `opencode.worktree_create` with `name: <dash-form-name>` (yields branch `worktree-<name>`, provisions deps, switches the session in), and run the spine's Phase 1 step 3 so symlinked dependency dirs do not show as untracked. Do not ask about worktree vs in-place; if the repo's `CLAUDE.md` says to work directly on the default branch, follow that instead. +- **Fresh run on the default branch** — create the work's branch as a worktree by default. Derive the name: `<type>-<slug>` from the issue (no number — that lives in the PR's `Closes #N`), or `wip-<slug>` from the description. **Before** creating, detect heavy gitignored dependency dirs exactly as in +`reference/spine.md` Phase 1 step 1 (`git check-ignore` probe). Then call +`opencode.worktree_create` with `name: <dash-form-name>` (it returns the +worktree's directory; move this session into it with `opencode.session_move`), +symlink the detected dirs per the spine's Phase 1 step 2, and run the spine's +Phase 1 step 3 so symlinked dependency dirs do not show as untracked.Do not ask about worktree vs in-place; if the repo's `CLAUDE.md` says to work directly on the default branch, follow that instead. Then proceed to Phase 1. @@ -54,7 +59,7 @@ Goal: turn the user's description into a richer rough spec by dispatching cheap, - **Surface prior art** — similar features already in the codebase, patterns to follow - **Identify constraints** — performance, security, compatibility, deprecated paths -2. **Dispatch all angles in parallel** in a single message, using the `Agent` tool with: +2. **Dispatch all angles in parallel** in a single message, using the `subagent` tool with: - `agent: explore` (read-only) - `model: haiku` by default - **Bump to `model: sonnet`** for an angle if: codebase is unfamiliar, the angle requires synthesizing patterns rather than locating code, or the description hints at subtle cross-file relationships @@ -75,8 +80,8 @@ Goal: turn the user's description into a richer rough spec by dispatching cheap, Goal: produce an initial implementation plan plus an explicit list of gaps and open questions. -1. **Dispatch a single planning sub-agent** using the `Agent` tool with: - - `agent: Plan` (architect agent) +1. **Dispatch a single planning sub-agent** using the `subagent` tool with: + - `agent: plan` (architect agent) - `model: sonnet` by default - **Bump to `model: opus`** if: cross-system design tradeoffs, significant ambiguity in the spec, novel pattern with no clear precedent in the codebase, correctness-critical (security, data integrity, concurrency, migrations) - **Never use `haiku`** — planning needs reasoning headroom @@ -176,7 +181,7 @@ Goal: get the user's approval, then hand the approved chunk plan to the build-an 3. **Dispatch the orchestrate_build.** Call the `orchestrate_build` tool with: - `args: <the object from step 2>` (the same args contract the Claude workflow script took; pass it as an actual JSON value) - orchestrate_build runs headless: it executes the waves with per-chunk failure escalation (attempt 1 = chunk tier; attempt 2 = same tier + failure-refined prompt; attempt 3 = bumped tier), then reviews every executed chunk (one Sonnet reviewer each, plus one Opus reviewer over the `opusReview` subset), and **auto-fixes blockers** by re-dispatching affected chunks with the reviewer feedback and re-reviewing only those — capped at 2 review iterations. Concerns and nits are reported, never auto-fixed. It edits the session's working tree (the Phase 0b worktree, if one was created), so no per-agent isolation is needed. Progress arrives as each wave completes. + orchestrate_build runs headless: it executes the waves with per-chunk failure escalation (attempt 1 = chunk tier; attempt 2 = same tier + failure-refined prompt; attempt 3 = bumped tier), then reviews every executed chunk (one Sonnet reviewer each, plus one Opus reviewer over the `opusReview` subset), and **auto-fixes blockers** by re-dispatching affected chunks with the reviewer feedback and re-reviewing only those — capped at 2 review iterations. Concerns and nits are reported, never auto-fixed. It edits the session's working tree (the Phase 0b worktree, if one was created), so no per-agent isolation is needed. The tool returns one structured result when all waves and the review loop finish; there is no per-wave progress channel. 4. **When orchestrate_build returns**, it gives you a structured result — proceed to Phase 6 to consume it: @@ -234,7 +239,7 @@ If this run created a worktree (Phase 0b), `/ship` step 9 removes it after the P - **Always think about whether the workflow is the right tool.** If the user invoked this for a small, well-scoped change, gently suggest `session-start` instead before kicking off Phase 1. - **Do not skip the user gates.** Phases 3 and 5 must use the `question` tool, and Phase 5's gate is the spend gate for the `orchestrate_build` tool. The Phase 6 concerns step also gates via the `question` tool. The blocker auto-fix loop inside the `orchestrate_build` tool is the only place work advances without an explicit gate. -- **The build loop lives in the `orchestrate_build` tool, not the main session.** Do not re-implement Execute or the review/blocker loop with inline `Agent` calls — construct the `args` and dispatch the `agent-toolkit.session` plugin. Self-contained prompts (full context per agent), parallel wave dispatch, failure escalation, and review dedupe are all handled inside the script. -- **Sub-agent prompts are self-contained.** This still applies to the phases that *do* dispatch inline — every Phase 1 research `Agent` and the Phase 2 planning `Agent` must carry enough context to succeed without seeing the parent conversation. -- **Parallel dispatch matters for the inline phases.** Within a Phase 1 angle set, issue all `Agent` calls in a single message so they run concurrently. (Phase 5/6 parallelism is the `orchestrate_build` tool's job.) +- **The build loop lives in the `orchestrate_build` tool, not the main session.** Do not re-implement Execute or the review/blocker loop with inline `subagent` calls — construct the `args` and dispatch the `agent-toolkit.session` plugin. Self-contained prompts (full context per agent), parallel wave dispatch, failure escalation, and review dedupe are all handled inside the script. +- **Sub-agent prompts are self-contained.** This still applies to the phases that *do* dispatch inline — every Phase 1 research `subagent` and the Phase 2 planning `subagent` must carry enough context to succeed without seeing the parent conversation. +- **Parallel dispatch matters for the inline phases.** Within a Phase 1 angle set, issue all `subagent` calls in a single message so they run concurrently. (Phase 5/6 parallelism is the `orchestrate_build` tool's job.) - **Keep `args` and the script in sync.** If you change the chunk-record shape in Phase 4, update both the Phase 5 `args` contract and the `args` documentation at the top of the `orchestrate_build` tool's schema. diff --git a/plugins-opencode/session/skills/session-orchestrate/reference/spine.md b/plugins-opencode/session/skills/session-orchestrate/reference/spine.md new file mode 100644 index 0000000..d41d7ac --- /dev/null +++ b/plugins-opencode/session/skills/session-orchestrate/reference/spine.md @@ -0,0 +1,299 @@ +# Begin-work spine + +The shared playbook for the lightweight session entrypoints (`session-start` and +`session-issue`). Both doors differ only in **how the work is chosen** — once the +work is identified, they run these phases identically: resolve target → isolate → +explore → plan → build the approved scope. + +**Lightweight is the only flow here.** Do not ask "lightweight vs orchestrate", and +do not ask about worktree vs in-place, dependency symlinks, latency, or scope — +decide silently using the defaults below. Ask only when something is genuinely +ambiguous about **what to build** (the exceptions are the explicit prompts in Phase 0 +validation and Phase 1 collisions / dirty default branch). If the user asks for a +heavier multi-agent flow, mention once that `session-orchestrate` exists and +invoke it; never raise it unprompted. + +> **CRITICAL**: You MUST drive this through to a plan. After the branch exists you +> explore and enter plan mode. NEVER print "suggested first steps" or ask "ready to +> start?" — the flow does not end until you have switched to the `plan` agent with a plan +> built from real code exploration. +> +> **EQUALLY CRITICAL — the other end of the flow**: plan approval authorizes the +> whole stated scope, but the last unit is reviewed by the user before it ships. +> Implement each unit; land every unit before the last via `/ship` and move +> on without stopping, then run the last unit through `session-end` +> (Phase 4). The one deliberate stop is **before** that final ship: `session-end` +> summarizes the work and caveats and waits for the user's go. After the go it ships, +> watches CI, fixes and re-merges if needed, cleans up, and ends with a final-state +> summary. A one-PR session always pauses before its PR; a multi-PR scope pauses once, +> before the last PR. + +## Inputs (supplied by the calling door) + +- One of: **issue number(s)** (from `session-issue`, or `#N` references in a + `session-start` description or its related-issue lookup) or a **freeform + description**. +- Whether the door already knows the hosting `platform` (reuse it; never detect + twice). +- `continuing` (both doors determine it): **true** when the current branch is not the + default branch and has commits ahead of it or uncommitted work; otherwise false. + When true, skip Phase 1's Isolate steps and keep the current branch. + +If you reach this spine with neither issues nor a description, stop and return to +the calling door — it owns target selection. + +## Phase 0 — Resolve target + +Run this once, for both doors. + +1. **Fetch and validate issues** (skip for freeform work). Detect the platform once + unless the door already did, then fetch **every** referenced issue: + + ```bash + bash scripts/git-wait platform + ``` + + - **github:** `gh issue view <N> --json number,title,body,state,labels,comments` + - **gitea:** `tea issues <N> --output json` + + For anything beyond issue viewing (PR create, CI runs, state values), use the + command map in the `git-tools:git-wait` skill rather than guessing flags. + Keep each issue's title, body, and labels as context for the whole session. + + **Validate each issue.** If the fetch fails, the state is not open, or the number + is a pull request (not an issue), tell the user and either drop that number or + stop — ask which when it is not obvious. Also warn (and ask whether to proceed) + when an issue is already claimed: it appears in + `git config --get-regexp 'branch\..*\.session-issues'` or has an open PR. + +2. **Pick the branch type** from labels. Compare case-insensitively on the label's + **last path segment** (`kind/bug` and `Kind/Enhancement` match `bug` and + `enhancement`). With several issues, a `bug` label on any of them wins; otherwise + use the first issue's labels: + - `bug`, `fix` → `bug` + - `enhancement`, `feature`, `improvement` → `enhancement` + - `docs`, `chore`, `refactor`, `maintenance` → `chore` + - no matching label → `feature` + +3. **Name the work.** + - **Continuing** (`continuing` is true): do **not** build a new base name or + branch type. The session name is the current branch name with any leading + `worktree-` stripped. + - **Otherwise** build the base name: issue-linked `<type>-<slug>`; freeform + `wip-<slug>`. The slug is a kebab-case 3-5 word summary (of the first issue's + title, or the common theme when several issues are bundled; of the description + for freeform). The branch never encodes issue numbers — linkage is the closing + lines in the PR body. + + Actual branch names: created in place, the branch is `<base-name>`; created via + `opencode.worktree_create` (Phase 1), it is `worktree-<base-name>`. The session name is + `<base-name>`. + +4. **Closing lines.** One line per issue: `Fixes #N` for `bug` issues, `Closes #N` + otherwise. Phase 1 persists them. + +## Phase 1 — Isolate, record, rename + +**Skip the Isolate steps** (everything through "In place on a new branch") when +`continuing` is true, or when already inside a linked worktree. Detect the latter +with: + +```bash +git_dir=$(realpath "$(git rev-parse --path-format=absolute --git-dir)") +git_common_dir=$(realpath "$(git rev-parse --path-format=absolute --git-common-dir)") +[ "$git_dir" != "$git_common_dir" ] && echo "linked worktree" +``` + +(`realpath` avoids false differences from symlinked paths; same test as +`/ship` step 0.) Then go straight to "Record issue linkage" and "Rename the +session" below on the current checkout. + +Decide silently: + +- **Repo's `CLAUDE.md` says to work directly on the default branch / master** (as + `homelab-admin` does): do not create a branch or worktree; work on the default + branch in place and skip the rest of Isolate. There is no branch to record + linkage on; skip that step. +- **Otherwise: worktree by default.** It keeps the main checkout clean and lets + parallel sessions coexist. + +**Before creating anything:** + +- **Dirty default branch.** If on the default branch with uncommitted changes, warn + once that those edits stay in the main checkout (they are not carried into the + worktree) and ask whether to proceed with the worktree or work in place. This is a + genuine ambiguity, so ask. +- **Name collisions.** Check for `<base-name>` and `worktree-<base-name>`: + + ```bash + git worktree list + git branch --list "<base-name>" "worktree-<base-name>" + ``` + + If either exists, offer to **resume** it (enter the existing worktree via + `opencode.session_move` with that `directory`, or `git switch` to the branch) or to use a short + numeric suffix (`<base-name>-2`). Decide silently only when unambiguous (e.g. it + is clearly stale or clearly this same work); ask when it could be someone's other + work. If you resume, treat the run as `continuing`. + +**Worktree:** + +1. **Provision dependencies first.** A fresh worktree is a clean checkout — gitignored + deps don't carry over, and native provisioning only runs at creation time, so + configure it **before** creating the worktree. Symlink **dependency directories + only** — never build output (`target`, `build`, `dist`, `.next`, `.gradle`, + `.tox`), which is stale or wrong in another checkout. Detect those present: + + ```bash + for d in node_modules .venv venv vendor; do + [ -e "$d" ] && git check-ignore -q "$d" && echo "$d" + done + ``` + + OpenCode's `worktree_create` has no symlink-provisioning setting (its + `worktree` config only takes `directory`), so there is no project-config + write here: just record the detected dir names — Phase 1 step 2 symlinks + them into the new worktree manually. + + Skip this step if no dependency directory was detected. Include `.env` / + `.env.*` files in the recorded set when they exist and the work needs + them. + +2. **Create + enter the worktree:** call `opencode.worktree_create` with `name` set to the base + name (already dash form, no `/`). This creates the worktree (with its own branch) and returns its + directory; then move this session into it with `opencode.session_move` + (Code Mode). Do **not** also run `branch create`. + + Symlink each detected dependency directory into the new worktree: + `ln -s "<main-checkout>/<dir>" "<dir>"`. + +3. **Keep the tree clean for `ship`.** A directory pattern with a trailing slash + (e.g. `node_modules/`) does not match a *symlink*, so a symlinked dependency + directory can show up as untracked and trip `/ship`'s worktree + cleanliness gate. Inside the new worktree, exclude **only the dependency-directory + names detected in step 1** (not every untracked symlink): + + ```bash + exclude=$(git rev-parse --path-format=absolute --git-path info/exclude) + for d in $detected; do # names from step 1, e.g. node_modules .venv + [ -L "$d" ] && { grep -qxF "/$d" "$exclude" 2>/dev/null || printf '/%s\n' "$d" >> "$exclude"; } + done + git status --porcelain # expect no symlinked dependency dirs listed + ``` + + `info/exclude` is shared by every worktree of the repo, so these entries apply + everywhere; that is acceptable because root-relative dependency dirs are + normally ignored anyway. The `grep -qxF` guard prevents duplicates. + +**In place on a new branch** (only when the work genuinely cannot use a worktree): + +```bash +bash scripts/branch create <base-name> +``` + +**Record issue linkage** (always, once the branch exists — including when +`continuing`; skip when there are no linked issues or no branch). Store the closing +lines from Phase 0 step 4 as one comma-separated value, one entry per issue: + +```bash +git config "branch.$(git branch --show-current).session-issues" "Closes #12,Fixes #13" +``` + +The Phase 4 report, `session-end`, and `session-orchestrate` read this +key. When `continuing`, union with any existing value rather than overwriting. + +**Rename the session** (always, last). Use the session name from Phase 0 step 3: + +```ts +// Code Mode — no script, no ~/.claude writes +await tools.opencode.session_rename({ title: "<session-name>" }) +``` + +A rename failure is non-fatal: warn and continue. When working on the default +branch in place with no meaningful name, skip the rename (warn only). + +## Phase 2 — Explore the codebase + +> You MUST complete this phase. Do NOT stop after Phase 1. Do NOT print +> "suggested first steps". + +**Trivial fast path.** When the change is small and obvious — a typo, a one-line or +single-file fix, a config tweak, an issue that names the exact file and change — +skip the research subagents: read the few relevant files yourself and go straight to +Phase 3 with a short plan inside the `plan` agent. + +Otherwise launch **2-3 research agents in parallel** in a single message, using +`subagent` tool with `agent: explore`. Every agent prompt MUST include the full +context — the issue title/body/labels for **all** linked issues and/or the freeform +description — so the agent can work without seeing this conversation. Pick 2-3 +angles that fit: + +- **Locate the code** — files, functions, types, or modules implied by the work. + Report what each does, the change point, and surrounding signatures. +- **Find tests and related config** — existing coverage of the area, related config, + CI, docs. Report what exists, what is missing, how the suite is structured. +- **Trace the data/call flow** — entry points, intermediate steps, dependencies, and + edge cases. + +If an agent needs the issue tracker or repo API, tell it to use `gh` or `tea` +directly, per the `git-tools:git-wait` skill's command map. + +## Phase 3 — Plan + +> You MUST complete this phase. Do NOT stop after Phase 2. + +Switch the session to the built-in `plan` agent, then present a concrete plan for approval before any +implementation begins. Cover **all** linked issues in one plan. + +- **Changes** — the specific files and line ranges, and what each change does. + Describe the actual code change, not "fix the bug". +- **Testing** — include only when behavior changes: what tests to add or update, + using the project's existing framework. Omit for purely cosmetic changes + (comments, docs, formatting). +- **Risks & open questions** — edge cases and unknowns; omit when there are none. +- **Scope line, always last:** `Scope: <the PR(s)/unit(s) this plan covers>`. The + user defines the scope; approving the plan authorizes every unit listed through + merge. A single unit is a one-item scope. + +For trivial work keep the whole plan short — a few lines, not a document. Do **not** +otherwise describe the commit / push / PR / merge steps in the plan; Phase 4 defines +them. + +## Phase 4 — Report, continue the scope, pause before the final ship + +> Plan approval authorizes every unit before the last through merge: do **not** stop +> between those units or ask before their commit / push / PR / merge. The last (or +> only) unit is different: do not commit, push, or open its PR until the user has +> reviewed `session-end`'s summary and given the go. That is the only deliberate +> stop. + +After each unit is implemented: + +1. Print a **short progress note** (not a wait): one-line outcome, the per-file list + of what changed, branch, test/build status (say so plainly if tests were not + run), and any caveats — known or potential problems and assumptions, stated + specifically. Omit caveats only if there are genuinely none. +2. **If this is the last unit** (a single-unit scope is just this), do **not** ship + it here: go to `session-end`, which does docs, review, and the issue + sweep, then **stops before shipping** to summarize what was done and any + caveats and wait for the user's go. After the go it ships the unit once, watches + CI, fixes and re-merges if needed, closes out (issue closing, cleanup / + worktree teardown), and finishes with a final-state summary. +3. Otherwise (a unit before the last), optionally run + `/code-review <level> --fix` (e.g. `/code-review high --fix`), then land the unit: + commit → push → open PR → watch CI → merge, via `/ship` (a CI failure + clearly caused by the change is fixed forward within the unit, at most twice; + anything else is surfaced). If issues are linked, put one closing line per issue + (`Closes #N` / `Fixes #N`) in the PR body — read them from + `git config branch.$(git branch --show-current).session-issues` + (comma-separated) if they are no longer in context. +4. Start the next unit (re-isolate from the updated default branch, implement) and + repeat from step 1. + +- **Worked on the default branch in place** (repo `CLAUDE.md` says so): there is no + feature branch; `/ship` and `session-end` run from the default + branch. + +`/ship` step 9 tears down the worktree after each merge (the last unit's +ship runs inside `session-end`); the user can also +remove it later with `opencode.worktree_remove`. diff --git a/plugins-opencode/session/skills/session-start/reference/spine.md b/plugins-opencode/session/skills/session-start/reference/spine.md index efc0289..d41d7ac 100644 --- a/plugins-opencode/session/skills/session-start/reference/spine.md +++ b/plugins-opencode/session/skills/session-start/reference/spine.md @@ -150,39 +150,22 @@ Decide silently: done ``` - Add the detected names **without asking** to `worktree.symlinkDirectories` in the - project's **`.claude/settings.local.json`** (`Local` scope — per-checkout, - normally gitignored; never the tracked `.claude/settings.json`, never global). - Merge with `jq`, unioning with any existing list and preserving all other keys; - create the file if absent. With the detected names in `$dirs` as a JSON array - (e.g. `'["node_modules",".venv"]'`): + OpenCode's `worktree_create` has no symlink-provisioning setting (its + `worktree` config only takes `directory`), so there is no project-config + write here: just record the detected dir names — Phase 1 step 2 symlinks + them into the new worktree manually. - ```bash - f=.claude/settings.local.json - mkdir -p .claude - [ -s "$f" ] || echo '{}' > "$f" - jq --argjson d "$dirs" \ - '.worktree.symlinkDirectories = ((.worktree.symlinkDirectories // []) + $d | unique)' \ - "$f" > "$f.tmp" && mv "$f.tmp" "$f" - git check-ignore -q "$f" \ - || echo "/$f" >> "$(git rev-parse --path-format=absolute --git-path info/exclude)" - ``` - - Skip this step if no dependency directory was detected. Add `.env` / `.env.*` to a - root `.worktreeinclude` only if they exist. That file has no documented - alternative location, so keep it out of `git status` instead: if it is untracked, - add `/.worktreeinclude` to the same `info/exclude`. If the repo already tracks a - `.worktreeinclude`, append to it only when a needed pattern is missing and - mention the resulting diff in the Phase 4 report, since that one is a real change. + Skip this step if no dependency directory was detected. Include `.env` / + `.env.*` files in the recorded set when they exist and the work needs + them. 2. **Create + enter the worktree:** call `opencode.worktree_create` with `name` set to the base name (already dash form, no `/`). This creates the worktree (with its own branch) and returns its directory; then move this session into it with `opencode.session_move` (Code Mode). Do **not** also run `branch create`. - This assumes `worktree.symlinkDirectories` is read at `worktree_create` time. As a - fallback, for each detected dependency directory missing in the new worktree, - create it yourself: `ln -s "<main-checkout>/<dir>" "<dir>"`. + Symlink each detected dependency directory into the new worktree: + `ln -s "<main-checkout>/<dir>" "<dir>"`. 3. **Keep the tree clean for `ship`.** A directory pattern with a trailing slash (e.g. `node_modules/`) does not match a *symlink*, so a symlinked dependency diff --git a/plugins-opencode/session/skills/session-summarize/SKILL.md b/plugins-opencode/session/skills/session-summarize/SKILL.md index df7ff8d..824f1c8 100644 --- a/plugins-opencode/session/skills/session-summarize/SKILL.md +++ b/plugins-opencode/session/skills/session-summarize/SKILL.md @@ -21,7 +21,7 @@ Use one script call as the source of truth, then summarize with an agent. 2. If output says `is_git_repo: false`, report that a summary cannot be generated outside a git repository. -3. Otherwise, invoke the `Agent` tool (`agent: general-purpose`) and provide only this script output as input context. +3. Otherwise, invoke the `subagent` tool (`agent: general`) and provide only this script output as input context. 4. Return exactly this structure: diff --git a/plugins-opencode/session/src/index.ts b/plugins-opencode/session/src/index.ts index ec3f872..99c2cc9 100644 --- a/plugins-opencode/session/src/index.ts +++ b/plugins-opencode/session/src/index.ts @@ -10,6 +10,7 @@ import { validateReview, planWave, splitFindings, + mergeReReview, semaphore, EXEC_SCHEMA, REVIEW_SCHEMA, @@ -22,6 +23,19 @@ import { const CONCURRENCY = 4 const MAX_REVIEW_ITERS = 2 +const CHILD_TIMEOUT_MS_DEFAULT = 45 * 60 * 1000 + +// A child stuck on a permission/form would otherwise hang the whole tool call +// (and the parent turn) forever; a timed-out wait counts as a failed attempt. +function withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> { + let timer: ReturnType<typeof setTimeout> + return Promise.race([ + p.finally(() => clearTimeout(timer)), + new Promise<never>((_, reject) => { + timer = setTimeout(() => reject(new Error(`orchestrate_build: child ${label} timed out after ${ms}ms`)), ms) + }), + ]) +} // `haiku|sonnet|opus` → concrete model refs. Override per install with plugin // options: { "modelTiers": { "haiku": "provider/model-id", ... } }. Default: @@ -66,20 +80,27 @@ export default Plugin.define({ id: "agent-toolkit.session", async setup(ctx) { // One child session per attempt: create → build agent → tier → prompt - // → wait → parse the last ```json block. Unparseable output is a retry - // trigger, never a silent pass. Children are top-level build sessions - // (not the subagent tool), so the depth-1 subagent limit doesn't apply; - // only the parent session ever has orchestrate_build, so no recursion. - async function runChild(label: string, tier: Tier, prompt: string): Promise<unknown> { + // → wait (with deadline) → parse the last ```json block. Unparseable + // output is a retry trigger, never a silent pass. Children are top-level + // build sessions (not the subagent tool), so the depth-1 subagent limit + // doesn't apply; only the parent session ever has orchestrate_build, so + // no recursion. + async function runChild(label: string, tier: Tier, prompt: string): Promise<{ parsed: unknown; model: string }> { const child = await ctx.session.create({ title: `orchestrate ${label}` }) try { await ctx.session.switchAgent({ sessionID: child.id, agent: "build" }) const model = await resolveTier(ctx, tier) if (model) await ctx.session.switchModel({ sessionID: child.id, model }) await ctx.session.prompt({ sessionID: child.id, text: prompt }) - await ctx.session.wait({ sessionID: child.id }) + const timeoutMs = Number(ctx.options?.childTimeoutMs) || CHILD_TIMEOUT_MS_DEFAULT + await withTimeout(ctx.session.wait({ sessionID: child.id }), timeoutMs, label) const messages = await ctx.session.context({ sessionID: child.id }) - return extractLastJsonBlock(lastAssistantText(messages as readonly unknown[])) + return { + parsed: extractLastJsonBlock(lastAssistantText(messages as readonly unknown[])), + // Echo the concrete model so the result shows whether tier + // resolution actually did anything (vs session default). + model: model ? `${model.providerID}/${model.id}` : "session-default", + } } finally { await ctx.session.remove({ sessionID: child.id }).catch(() => {}) } @@ -90,6 +111,7 @@ export default Plugin.define({ ok: boolean attempts: number model: Tier + resolvedModel?: string result: ExecResult | null blocker?: string } @@ -102,17 +124,20 @@ export default Plugin.define({ let extra = seedContext || "" let last: ExecResult | null = null let usedModel = baseModel + let resolvedModel: string | undefined for (let attempt = 1; attempt <= 3; attempt++) { usedModel = attempt === 3 ? bump(baseModel) : baseModel let parsed: ExecResult | null = null try { - parsed = validateExec(await runChild(`exec:${chunk.id}#${attempt}`, usedModel, execPrompt(args, chunk, extra))) + const r = await runChild(`exec:${chunk.id}#${attempt}`, usedModel, execPrompt(args, chunk, extra)) + resolvedModel = r.model + parsed = validateExec(r.parsed) } catch { parsed = null } last = parsed if (parsed && parsed.status === "done") { - return { chunkId: chunk.id, ok: true, attempts: attempt, model: usedModel, result: parsed } + return { chunkId: chunk.id, ok: true, attempts: attempt, model: usedModel, resolvedModel, result: parsed } } const why = parsed ? parsed.blocker || parsed.summary : "no parsable result block (retrying)" extra = `Attempt ${attempt} did not complete. Reported blocker: ${why}\nClarify the success criteria and address this blocker directly.` @@ -122,6 +147,7 @@ export default Plugin.define({ ok: false, attempts: 3, model: usedModel, + resolvedModel, result: last, blocker: last ? last.blocker || last.summary : "no result after 3 attempts", } @@ -174,21 +200,38 @@ export default Plugin.define({ const allUnassigned: Finding[] = [] const reviewChunks = async (ids: string[]): Promise<Finding[]> => { const warranted = ids.filter((id) => findChunk(id)?.opusReview) + // A throwing reviewer must NOT kill the run (the Claude + // reference tolerated null agents) — but an unreviewed + // chunk is a concern the user should see, not a silent + // pass, so a failed reviewer reports one. const tasks: (() => Promise<Finding[]>)[] = ids.map((id) => async () => { const exec = execByChunk.get(id) - const parsed = validateReview( - await runChild( + try { + const r = await runChild( `review:${id}`, "sonnet", reviewPrompt(args, findChunk, (rid) => (rid === id ? { summary: exec?.result?.summary, ok: exec?.ok, attempts: exec?.attempts } : undefined), id), - ), - ) - return (parsed ?? []).map((f) => ({ ...f, chunkId: id })) // reviewer is scoped to one chunk + ) + const parsed = validateReview(r.parsed) ?? [] + return parsed.map((f) => ({ ...f, chunkId: id })) // reviewer is scoped to one chunk + } catch { + return [{ chunkId: id, severity: "concern" as const, title: "reviewer failed to run — this chunk was not reviewed" }] + } }) if (warranted.length) { tasks.push(async () => { - const parsed = validateReview(await runChild("review:opus", "opus", opusReviewPrompt(args, findChunk, warranted))) - return parsed ?? [] + try { + const r = await runChild("review:opus", "opus", opusReviewPrompt(args, findChunk, warranted)) + return validateReview(r.parsed) ?? [] + } catch { + return [ + { + chunkId: "review:opus", + severity: "concern" as const, + title: `Opus reviewer failed to run — not covered: ${warranted.join(", ")}`, + }, + ] + } }) } const merged = (await semaphore(CONCURRENCY, tasks)).flat() @@ -219,7 +262,7 @@ export default Plugin.define({ ) // Re-review ONLY the re-dispatched chunks; clean chunks' findings stand. const reFindings = await reviewChunks(blockerIds) - findings = findings.filter((f) => !blockerIds.includes(f.chunkId)).concat(reFindings) + findings = mergeReReview(findings, blockerIds, reFindings) } const blockers = findings.filter((f) => f.severity === "blocker") @@ -238,6 +281,7 @@ export default Plugin.define({ ok: r.ok, attempts: r.attempts, model: r.model, + resolvedModel: r.resolvedModel, summary: r.result?.summary ?? null, testsPassed: r.result?.testsPassed, blocker: r.ok ? undefined : r.blocker, diff --git a/plugins-opencode/session/src/orchestrate-core.ts b/plugins-opencode/session/src/orchestrate-core.ts index 2ee0bb5..3c36cb8 100644 --- a/plugins-opencode/session/src/orchestrate-core.ts +++ b/plugins-opencode/session/src/orchestrate-core.ts @@ -260,6 +260,16 @@ export function splitFindings(findings: Finding[], reviewedIds: string[]) { return { assigned: dedupeFindings(assigned), unassigned } } +// Re-review merge: findings for the re-dispatched chunks are REPLACED by the +// fresh review; clean chunks' findings stand. Pure so the loop bookkeeping is +// unit-testable (the executor in index.ts just wires children to it). +export function mergeReReview(findings: Finding[], reReviewedIds: string[], reFindings: Finding[]): Finding[] { + const re = new Set(reReviewedIds) + return dedupeFindings( + findings.filter((f) => !re.has(f.chunkId)).concat(reFindings), + ) +} + // --- small concurrency helper -------------------------------------------------- export async function semaphore<T>(limit: number, tasks: (() => Promise<T>)[]): Promise<T[]> { diff --git a/tests/inbox/test-inbox-blocking.sh b/tests/inbox/test-inbox-blocking.sh index c43445c..9634af5 100644 --- a/tests/inbox/test-inbox-blocking.sh +++ b/tests/inbox/test-inbox-blocking.sh @@ -94,6 +94,16 @@ q bash "$Q" "${S[@]}" list --json echo "$OUT" | jq -e '.questions | all(has("blocking"))' >/dev/null t "combined --json questions all carry blocking" 0 +# update can escalate/de-escalate blocking (question-only) +q bash "$Q" "${S[@]}" update Q1 --blocking +jq -e '.questions[] | select(.id == 1) | .blocking == true' "$INBOX_STATE_DIR/blocktest.json" >/dev/null +t "update Q1 --blocking escalates" 0 +q bash "$Q" "${S[@]}" update Q2 --no-blocking +jq -e '.questions[] | select(.id == 2) | .blocking == false' "$INBOX_STATE_DIR/blocktest.json" >/dev/null +t "update Q2 --no-blocking de-escalates" 0 +q bash "$Q" "${S[@]}" update D1 --blocking +t "update decision --blocking rejected" nonzero + echo "" echo "Total: $((PASS + FAIL)) PASS: $PASS FAIL: $FAIL" [[ $FAIL -eq 0 ]] diff --git a/tests/opencode/test-format-on-save-parity.sh b/tests/opencode/test-format-on-save-parity.sh index eb6fe45..25e6b0a 100644 --- a/tests/opencode/test-format-on-save-parity.sh +++ b/tests/opencode/test-format-on-save-parity.sh @@ -32,9 +32,11 @@ fail() { # --- extract the hook's dispatch: one "ext<TAB>fmt_fn" line per extension --- # Drop the `case`/`esac` lines, flatten, split arms on ;;, split alternates on |. +# Match ANY function name after ")" (not just fmt_*) so an arm renamed away +# from the fmt_ convention fails loudly downstream instead of vanishing. sed -n '/^case "\$ext" in/,/^esac/p' "$HOOK" | sed '1d;$d' | tr '\n' ' ' | sed -E 's/ *\| */ /g; s/;;/\n/g' | - awk -F')' '/fmt_/ { + awk -F')' '$2 ~ /^ *[a-z_]+/ { fn = $2; sub(/^ +/, "", fn); sub(/ +.*$/, "", fn) n = split($1, a, / +/) for (i = 1; i <= n; i++) if (a[i] ~ /^[a-z]+$/) print a[i] "\t" fn @@ -58,11 +60,15 @@ argv_for() { return fi awk -v fn="$fn" '$0 == fn"() {" {infn=1} infn && /if ! / && !/command -v/ { - sub(/^ +if ! /, "") - sub(/ "[$]file_path" 2>&1; then/, " $FILE") - print - exit - } infn && /^}/ {infn=0}' "$HOOK" + n++ + line = $0 + sub(/^ +if ! /, "", line) + sub(/ "[$]file_path" 2>&1; then/, " $FILE", line) + if (n == 1) first = line + } infn && /^}/ {infn=0} END { + if (n > 1) print "MULTI" + else if (n == 1) print first + }' "$HOOK" } : >"$TMP/script_table" @@ -72,6 +78,10 @@ while IFS=$'\t' read -r ext fn; do fail "extract command for $fn" "no 'if ! …' invocation found — did the function shape change?" continue fi + if [[ "$argv" == "MULTI" ]]; then + fail "extract command for $fn" "multiple invocation paths — parity script cannot compare; extend it deliberately" + continue + fi printf '%s\t%s\n' "$ext" "$argv" >>"$TMP/script_table" done <"$TMP/extfn" diff --git a/tests/opencode/test-session-core.mjs b/tests/opencode/test-session-core.mjs index 8afd4bb..9f06ed9 100644 --- a/tests/opencode/test-session-core.mjs +++ b/tests/opencode/test-session-core.mjs @@ -165,6 +165,30 @@ await t("splitFindings separates known-chunk from unassigned and dedupes assigne assert.equal(unassigned[0].chunkId, "cX") }) +await t("mergeReReview replaces re-reviewed chunks' findings, keeps the rest", () => { + const old = [finding("c1", "blocker", "b"), finding("c1", "concern", "c"), finding("c2", "nit", "n")] + const re = [finding("c1", "concern", "fixed, minor residue")] + const out = core.mergeReReview(old, ["c1"], re) + // c1's blocker AND concern are gone; only the fresh c1 finding + c2's stand + assert.deepEqual( + out.map((f) => `${f.chunkId}/${f.severity}`), + ["c2/nit", "c1/concern"], + ) +}) + +await t("mergeReReview: clean re-review clears the chunk's blockers (loop terminates)", () => { + const old = [finding("c1", "blocker", "b")] + const out = core.mergeReReview(old, ["c1"], []) + assert.deepEqual(out, []) +}) + +await t("mergeReReview dedupes across the merge boundary", () => { + const old = [finding("c2", "nit", "same")] + const re = [finding("c1", "nit", "same")] // same title/severity, different chunk → distinct key + const out = core.mergeReReview(old, ["c1"], re.concat([finding("c1", "nit", "same")])) + assert.equal(out.length, 2) +}) + // --- semaphore ---------------------------------------------------------------------- await t("semaphore runs all tasks and preserves result order", async () => { diff --git a/tests/opencode/test-session-port.sh b/tests/opencode/test-session-port.sh index 710703e..dc692e9 100644 --- a/tests/opencode/test-session-port.sh +++ b/tests/opencode/test-session-port.sh @@ -41,10 +41,20 @@ t2() { SKILLS="session-start session-issue session-end session-orchestrate session-summarize" # --- no Claude harness leakage in the whole opencode session tree ------------ -for pat in CLAUDE_PLUGIN_ROOT EnterWorktree ExitWorktree EnterPlanMode AskUserQuestion subagent_type '\$ARGUMENTS' '/session:' '/git-tools:' 'allowed-tools:' Workflow; do +for pat in CLAUDE_PLUGIN_ROOT EnterWorktree ExitWorktree EnterPlanMode AskUserQuestion subagent_type '\$ARGUMENTS' '/session:' '/git-tools:' 'allowed-tools:' Workflow 'symlinkDirectories' '\.claude/settings' 'worktreeinclude' '`Agent` tool' 'CLAUDE_SESSION_ID'; do t2 "no leakage: $pat" sh -c "! grep -rq -- '$pat' '$OC/skills' '$OC/src'" done +# --- every reference/<file> a SKILL.md mentions must be vendored beside it ---- +# Catches manifest gaps (the session-orchestrate spine miss): the porter maps +# ${CLAUDE_PLUGIN_ROOT}/reference/ → reference/, so any such mention must +# resolve inside the skill's own base dir. +for skill in $SKILLS; do + while IFS= read -r ref; do + t2 "$skill vendors referenced $ref" test -f "$OC/skills/$skill/$ref" + done < <(grep -oE 'reference/[A-Za-z0-9._-]+' "$OC/skills/$skill/SKILL.md" | sort -u) +done + # --- ported skills == porter(Claude original) --------------------------------- # The porter strips `allowed-tools:` frontmatter lines, applies the harness # mapping, then applies its $ARGUMENTS rewrites. Reproduce that pipeline here @@ -75,6 +85,10 @@ spec = spec_from_file_location("psp", repo / "utils" / "port-session-skills.py") src = (repo / "utils" / "port-session-skills.py").read_text() ns = {} # grab ARG_REWRITES + strip_frontmatter_line without running the port loop +# grab ARG_REWRITES + strip_frontmatter_line without running the port loop. +# Hard-assert the split point exists: if the port script is refactored and the +# marker moves, silently exec-ing the whole module would REWRITE THE REAL TREE. +assert "for skill in SKILLS:" in src, "port-session-skills.py split marker missing" head = src.split("for skill in SKILLS:")[0] ns = {"__file__": str(repo / "utils" / "port-session-skills.py")} exec(compile(head, "port-session-skills.py", "exec"), ns) @@ -110,7 +124,7 @@ for skill in $SKILLS; do done # --- rendered spine matches sync.sh's rendering of utils/spine.md -------------- -for skill in session-start session-issue; do +for skill in session-start session-issue session-orchestrate; do python3 "$PORTER" <"$REPO/utils/spine.md" >"$TMP/spine.rendered" t2 "$skill spine.md matches opencode-port rendering" cmp -s "$TMP/spine.rendered" "$OC/skills/$skill/reference/spine.md" done diff --git a/tests/opencode/test-sync.sh b/tests/opencode/test-sync.sh index 00eea30..2d10fc3 100644 --- a/tests/opencode/test-sync.sh +++ b/tests/opencode/test-sync.sh @@ -142,6 +142,30 @@ echo "# tampered" >>"$S/plugins-opencode/session/skills/session-issue/reference/ run sync --check check "--check fails on rendered markdown drift" nonzero "$RC" +# --- exec-bit drift is detected (git tracks it; a bad merge must not pass) -------- +run sync +chmod -x "$S/plugins-opencode/inbox/scripts/inbox" +run sync --check +check "--check fails on dropped exec bit" nonzero "$RC" +if [[ -z "$FILTER" ]] || echo "exec drift names path" | grep -qi "$FILTER"; then + if echo "$ERR" | grep -q "exec bit"; then + pass "--check names the exec-bit drift" + else + fail "--check names the exec-bit drift" "stderr: $ERR" + fi +fi +run sync # repairs it +run test -x "$S/plugins-opencode/inbox/scripts/inbox" +check "sync repairs the exec bit" 0 "$RC" +# extra +x on a non-exec canonical file is drift too (spine.md is 0644) +run sync +chmod +x "$S/plugins-claude/session/reference/spine.md" +run sync --check +check "--check fails on spurious exec bit" nonzero "$RC" +run sync +run test ! -x "$S/plugins-claude/session/reference/spine.md" +check "sync strips the spurious exec bit" 0 "$RC" + # --- missing canonical source is a hard error ----------------------------------- run sync rm "$S/utils/branch" diff --git a/utils/inbox b/utils/inbox index 86be29b..6f15ae7 100755 --- a/utils/inbox +++ b/utils/inbox @@ -38,6 +38,7 @@ Commands: Refused (exit 3) if a similar open followup exists unless --new. update <Q<n>|D<n>|F<n>> [--title T] [--context C] [--option O]... [--recommend R (question)] [--chosen X (decision)] + [--blocking | --no-blocking (question)] Replace provided fields (any --option replaces the options list). answer Q<n> [--note N] Remove a question. --note is reserved and currently ignored. @@ -268,7 +269,7 @@ cmd_update() { shift local kind="$REF_KIND" id="$REF_ID" kind_keys "$kind" - local title="" context="" extra="" have_t=0 have_c=0 have_e=0 + local title="" context="" extra="" have_t=0 have_c=0 have_e=0 blocking=0 have_b=0 local -a opts=() while [[ $# -gt 0 ]]; do case "$1" in @@ -283,6 +284,12 @@ cmd_update() { --chosen) [[ "$kind" == decision ]] || die "update $PFX$id: --chosen applies to decisions only (use --recommend)" 1 extra="${2:?--chosen needs a value}"; have_e=1; shift 2 ;; + --blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --blocking applies to questions only" 1 + blocking=1; have_b=1; shift ;; + --no-blocking) + [[ "$kind" == question ]] || die "update $PFX$id: --no-blocking applies to questions only" 1 + blocking=0; have_b=1; shift ;; *) die "update: unknown argument: $1" 2 ;; esac done @@ -298,13 +305,15 @@ cmd_update() { local new new=$(jq --arg k "$ARR" --arg kind "$kind" --argjson id "$id" \ --arg t "$title" --arg c "$context" --arg e "$extra" \ - --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" ' + --argjson ht "$have_t" --argjson hc "$have_c" --argjson he "$have_e" --argjson o "$opts_json" \ + --argjson b "$blocking" --argjson hb "$have_b" ' (if $kind == "question" then "recommendation" else "chosen" end) as $ek | .[$k] |= map(if .id == $id then (if $ht == 1 then .title = $t else . end) | (if $hc == 1 then .context = $c else . end) | (if $he == 1 then .[$ek] = $e else . end) | (if $o != null then .options = $o else . end) + | (if $hb == 1 then .blocking = ($b == 1) else . end) else . end)' <<<"$state") write_state "$new" echo "$PFX$id updated" diff --git a/utils/opencode-port.py b/utils/opencode-port.py index 901157e..ceaed28 100644 --- a/utils/opencode-port.py +++ b/utils/opencode-port.py @@ -24,6 +24,39 @@ ("${CLAUDE_PLUGIN_ROOT}/scripts/", "scripts/"), ("${CLAUDE_PLUGIN_ROOT}/reference/", "reference/"), # --- worktrees: EnterWorktree → opencode.worktree_* + session_move ------- + # --- spine worktree provisioning: Claude's symlinkDirectories config has + # no OpenCode equivalent (worktree config only takes `directory`), so the + # whole settings-write procedure becomes manual symlinks in step 2. + # Exact multi-line blocks from utils/spine.md; must precede the generic + # EnterWorktree mappings (the fallback block contains one). + ( + ' Add the detected names **without asking** to `worktree.symlinkDirectories` in the\n project\'s **`.claude/settings.local.json`** (`Local` scope — per-checkout,\n normally gitignored; never the tracked `.claude/settings.json`, never global).\n Merge with `jq`, unioning with any existing list and preserving all other keys;\n create the file if absent. With the detected names in `$dirs` as a JSON array\n (e.g. `\'["node_modules",".venv"]\'`):\n\n ```bash\n f=.claude/settings.local.json\n mkdir -p .claude\n [ -s "$f" ] || echo \'{}\' > "$f"\n jq --argjson d "$dirs" \\\n \'.worktree.symlinkDirectories = ((.worktree.symlinkDirectories // []) + $d | unique)\' \\\n "$f" > "$f.tmp" && mv "$f.tmp" "$f"\n git check-ignore -q "$f" \\\n || echo "/$f" >> "$(git rev-parse --path-format=absolute --git-path info/exclude)"\n ```\n', + " OpenCode's `worktree_create` has no symlink-provisioning setting (its\n" + " `worktree` config only takes `directory`), so there is no project-config\n" + " write here: just record the detected dir names — Phase 1 step 2 symlinks\n" + " them into the new worktree manually.\n", + ), + ( + " Skip this step if no dependency directory was detected. Add `.env` / `.env.*` to a\n root `.worktreeinclude` only if they exist. That file has no documented\n alternative location, so keep it out of `git status` instead: if it is untracked,\n add `/.worktreeinclude` to the same `info/exclude`. If the repo already tracks a\n `.worktreeinclude`, append to it only when a needed pattern is missing and\n mention the resulting diff in the Phase 4 report, since that one is a real change.\n", + " Skip this step if no dependency directory was detected. Include `.env` /\n" + " `.env.*` files in the recorded set when they exist and the work needs\n" + " them.\n", + ), + ( + ' This assumes `worktree.symlinkDirectories` is read at `EnterWorktree` time. As a\n fallback, for each detected dependency directory missing in the new worktree,\n create it yourself: `ln -s "<main-checkout>/<dir>" "<dir>"`.\n', + " Symlink each detected dependency directory into the new worktree:\n" + ' `ln -s "<main-checkout>/<dir>" "<dir>"`.\n', + ), + # orchestrate skill's condensed worktree instruction + ( + "**Before** creating, provision dependencies exactly as in `reference/spine.md` Phase 1 step 1 (detect heavy gitignored dirs via `git check-ignore`; write `worktree.symlinkDirectories` + `.worktreeinclude` to **project** config without asking). Then call `EnterWorktree` with `name: <dash-form-name>` (yields branch `worktree-<name>`, provisions deps, switches the session in), and run the spine's Phase 1 step 3 so symlinked dependency dirs do not show as untracked. ", + "**Before** creating, detect heavy gitignored dependency dirs exactly as in\n" + "`reference/spine.md` Phase 1 step 1 (`git check-ignore` probe). Then call\n" + "`opencode.worktree_create` with `name: <dash-form-name>` (it returns the\n" + "worktree's directory; move this session into it with `opencode.session_move`),\n" + "symlink the detected dirs per the spine's Phase 1 step 2, and run the spine's\n" + "Phase 1 step 3 so symlinked dependency dirs do not show as untracked.", + ), # ExitWorktree entries first: one block below contains `EnterWorktree`, # which the generic mappings would rewrite before a later match could fire. ( @@ -67,6 +100,19 @@ # --- subagents: Agent + subagent_type → subagent tool + agent ------------- ("`Agent` with `subagent_type: research`", "`subagent` tool with `agent: explore`"), ("subagent_type: research", "agent: explore"), + ( + "invoke the `Agent` tool (`subagent_type: general-purpose`)", + "invoke the `subagent` tool (`agent: general`)", + ), + ("`subagent_type: Plan` (architect agent)", "`agent: plan` (architect agent)"), + ("using the `Agent` tool with:", "using the `subagent` tool with:"), + ("issue all `Agent` calls", "issue all `subagent` calls"), + ("inline `Agent` calls", "inline `subagent` calls"), + ( + "Phase 1 research `Agent` and the Phase 2 planning `Agent`", + "Phase 1 research `subagent` and the Phase 2 planning `subagent`", + ), + ("`Agent` tool", "`subagent` tool"), ("subagent_type", "agent"), # --- user gates: AskUserQuestion → the question tool ----------------------- ("`AskUserQuestion`", "the `question` tool"), @@ -99,7 +145,7 @@ ("a targeted Workflow", "a targeted orchestrate_build"), ( "You can watch progress via `/workflows`.", - "Progress arrives as each wave completes.", + "The tool returns one structured result when all waves and the review loop finish; there is no per-wave progress channel.", ), ("Workflow", "orchestrate_build"), # --- slash-command doors: /plugin:name → skill id / command ----------------- diff --git a/utils/sync.sh b/utils/sync.sh index 552eb48..aa6bca5 100755 --- a/utils/sync.sh +++ b/utils/sync.sh @@ -57,7 +57,7 @@ declare -A NEEDS_OPENCODE=( ["session/skills/session-issue"]="git-wait branch spine.md:reference" ["session/skills/session-end"]="git-wait sitrep" ["session/skills/session-summarize"]="sitrep" - ["session/skills/session-orchestrate"]="git-wait sitrep" + ["session/skills/session-orchestrate"]="git-wait sitrep spine.md:reference" ) # render_for_target <target> <src> — content on stdout, harness-adjusted. @@ -75,7 +75,19 @@ synced=0 TMPOUT=$(mktemp) trap 'rm -f "$TMPOUT"' EXIT +# mode_drift <src> <dst> — true when the exec bits differ. Git only tracks the +# exec bit, so that is the mode that matters for vendored copies; a checkout +# or merge that drops +x on a script must not pass --check. +mode_drift() { + local sx dx + [[ -x "$1" ]] && sx=1 || sx=0 + [[ -x "$2" ]] && dx=1 || dx=0 + [[ $sx -ne $dx ]] +} + for target in claude opencode; do + # namerefs + ${var^^} need bash >= 4.3 (already past the repo's floor; + # macOS ships bash 3.2, so run this with a brew-installed bash) declare -n NEEDS="NEEDS_${target^^}" target_dir="$ROOT/plugins-$target" @@ -108,19 +120,20 @@ for target in claude opencode; do elif ! render_for_target "$target" "$src" >"$TMPOUT" || ! cmp -s "$TMPOUT" "$dst"; then echo "DRIFT: $dst differs from utils/$util (run utils/sync.sh)" >&2 drift=1 + elif mode_drift "$src" "$dst"; then + echo "DRIFT: $dst exec bit differs from utils/$util (run utils/sync.sh)" >&2 + drift=1 fi ;; sync) [[ -L "$dst" ]] && rm "$dst" render_for_target "$target" "$src" >"$TMPOUT" - # mktemp renders at 0600; carry the canonical exec bit over - # (unconditionally — mode drift is drift even when content matches) - if [[ -x "$src" ]]; then - chmod +x "$dst" 2>/dev/null || true - fi - if ! cmp -s "$TMPOUT" "$dst" 2>/dev/null; then + if ! cmp -s "$TMPOUT" "$dst" 2>/dev/null || { [[ -f "$dst" ]] && mode_drift "$src" "$dst"; }; then mkdir -p "$target_dir/$plugin/$subdir" cp "$TMPOUT" "$dst" + # mktemp renders at 0600; apply the canonical mode instead + # (group/other readable, exec bit only when the source has it) + chmod 0644 "$dst" if [[ -x "$src" ]]; then chmod +x "$dst" fi