Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugins/agentic-advisor/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "agentic-advisor",
"version": "1.5.2",
"version": "1.5.3",
"description": "Before writing code, grades how fragile the target is from LinearB health signals + local git history (rework, incidents, fix/revert density, code ownership) and reports whether it Reduced, Kept or Raised effort against the model's current level — lean on calm repos, defensive on fragile ones. Auto-triggers via a bundled hook and can report each effort decision to your LinearB org as usage telemetry.",
"author": {
"name": "LinearB",
Expand Down
9 changes: 9 additions & 0 deletions plugins/agentic-advisor/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Changelog

## [1.5.3] - 2026-11-24

### Fixed

- With Claude Code's sandbox on, the 24-hour repo-health cache couldn't be written to `~/.cache` ("operation not permitted"), so every task re-ran the LinearB calls. The skill now falls back to `$TMPDIR`, which the sandbox allows (or a per-user folder under `/tmp` when `$TMPDIR` is unset).
- A verdict now holds or releases edits only in the repo it names, so grading one repo no longer blocks or unblocks edits in another in the same session. A "skipped (not a code task)" line releases edits in its own repo only.
- On a medium or higher grade with no target file named, edits wait for the file-level (phase 2) line, held at most twice per repo and session.
- A verdict containing an apostrophe is shown in full: the hook reads the printed line, not the shell source.

## [1.5.2] - 2026-11-10

### Fixed
Expand Down
74 changes: 63 additions & 11 deletions plugins/agentic-advisor/hooks/agentic-advisor-trigger.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
# session. Catches tasks that slipped past the prompt gate.
#
# PostToolUse (matcher Bash)
# SHOW - a `printf` verdict line ran: echo it as a systemMessage so the user sees it
# SHOW - a `printf` verdict (or stage 2) line ran: echo it as a systemMessage so the user sees it
# even when the Bash call is collapsed.
#
# This NEVER does LinearB work itself and NEVER blocks. It only injects an
Expand Down Expand Up @@ -80,6 +80,40 @@ verdict_state() { # $1 = the verdict regex required (default: a grade or a skip)
then "ok" else "pending" end' "$transcript" 2>/dev/null
}

# One pass over the assistant's lines (text, and `printf` Bash calls) for the latest verdict naming this repo
# ($1 = its names, one per line; none = any repo). Prints pending|skipped|graded, or stage2 when that verdict
# is medium+ with no target file, followed by the "LinearB phase 2 —" lines printed after it. Nothing on parse failure.
repo_state() {
jq -rs --arg any "$VERDICT_RE" --arg re "$GRADED_RE" --arg names "${1:-}" '
[.[] | select(.message.role? == "assistant") | .message.content? // [] | .[]?
| if .type? == "text" then (.text? // "") | split("\n")[]
elif (.type? == "tool_use" and .name? == "Bash") then (.input.command? // "") | split("\n")[]
| select(test("(^|;|&&)\\s*printf\\s")) else empty end] as $t
| [$names | split("\n")[] | select(length > 0)] as $ns
| [$t | to_entries[] | select((.value | test($any)) and (.value as $l | ($ns | length) == 0 or any($ns[];
. as $n | $l | contains("LinearB: " + $n + " ") or (test("LinearB: [^ ]+/") and contains("/" + $n + " ")))))] as $v
Comment on lines +87 to +94
| if ($v | length) == 0 then "pending"
else $v[-1] as $l
| if ($l.value | test($re) | not) then "skipped"
elif ($l.value | test("target [^ ;)]+: ")) or ($l.value | test("(→|->) low[;)]|Kept effort \\(low[;)]| LOW effort")) then "graded"
else "stage2", ($t[($l.key + 1):][] | select(test("LinearB phase 2 — ")))
end
end' "$transcript" 2>/dev/null
}

# Does a phase-2 line ($1) name the edited file, this repo, or a file in it? Uses $file_path, $names and $root.
p2_here() {
local toks t n
t="${1#*LinearB phase 2 — }"
read -ra toks <<<"$(printf '%s' "${t%%: *}" | tr ',+&`' ' ')"
for t in ${toks[@]+"${toks[@]}"}; do
[ "$t" = "$(basename "$file_path")" ] || [ -e "$root/$t" ] && return 0
while IFS= read -r n; do [ -n "$n" ] && case "$t" in "$n"|"$n"/*) return 0 ;; esac; done <<<"$names"
[ -n "$(git -C "$root" ls-files -- ":(glob)**/$t" 2>/dev/null | head -n 1)" ] && return 0
Comment on lines +110 to +112
done
return 1
}

note() { # $1 = context for the model; the tool call still runs (no red error in the UI)
printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":%s}}\n' "$(printf '%s' "$1" | jq -Rs .)"
exit 0
Expand Down Expand Up @@ -139,8 +173,10 @@ fi
case "$event" in
PostToolUse)
cmd="$(jq -r '.tool_input.command // empty' <<<"$input" 2>/dev/null || true)"
case "$cmd" in *printf*"LinearB: "*) ;; *) exit 0 ;; esac
line="$(printf '%s\n' "$cmd" | grep -oE "> ${GRADED_RE}[^']*" | head -n 1)"
case "$cmd" in *printf*"LinearB"*) ;; *) exit 0 ;; esac
# Read the printed line, not the shell source, so quoting (e.g. an apostrophe) can't cut it short.
out="$(jq -r '.tool_response.stdout // empty' <<<"$input" 2>/dev/null || true)"
line="$(printf '%s\n' "$out" | grep -m 1 -E "^> (${GRADED_RE}|LinearB phase 2 — .+)" || true)"
[ -n "$line" ] || exit 0
jq -cn --arg m "$line" '{systemMessage: $m}'
dbg "PostToolUse: showed the verdict line to the user"
Expand Down Expand Up @@ -220,16 +256,32 @@ case "$event" in
# setup never walls. Scoped to a git repo; fails OPEN on any uncertainty.
git -C "$dir" rev-parse --is-inside-work-tree >/dev/null 2>&1 || exit 0

# Skill already graded this session -> allow the edit. A "skipped (not a code task)" line alone doesn't count: editing now is code work.
# If a verdict names this repo, mark it handled so later prompts here aren't nudged.
# Graded only by a verdict or "skipped (not a code task)" line naming THIS repo (the remote's or the folder's
# name: clones and worktrees can differ), so one repo's run can't hold or release another.
# "pending" only when parsed and no grade yet; a parse failure prints nothing and fails open.
if skill_ran && [ "$(verdict_state "$GRADED_RE")" != "pending" ]; then
root="$(git -C "$dir" rev-parse --show-toplevel 2>/dev/null)"
url="$(git -C "$dir" config --get remote.origin.url 2>/dev/null)"; url="${url%.git}"
names="$(printf '%s\n' "${url##*[/:]}" "${root:+$(basename "$root")}" | grep -v '^$')"
gate="pending"
if skill_ran; then
rs="$(repo_state "$names")"; gate="${rs%%$'\n'*}"
# No name to match: the latest skill run must also be graded, as before.
[ -n "$names" ] || [ "$(verdict_state "$GRADED_RE")" != "pending" ] || gate="pending"
fi
if [ "$gate" != "pending" ]; then
set_marker "$dir"
# The verdict uses the repo's name: check the remote's name and the folder's (clones and worktrees can differ).
url="$(git -C "$dir" config --get remote.origin.url 2>/dev/null)"; url="${url%.git}"
for name in "${url##*[/:]}" "$(basename "$(git -C "$dir" rev-parse --show-toplevel 2>/dev/null)")"; do
[ -n "$name" ] && grep -qF "LinearB: $name " "$transcript" 2>/dev/null && { : > "$marker" 2>/dev/null || true; break; }
done
# A grade naming this repo marks it handled so later prompts here aren't nudged.
case "$gate" in graded|stage2) [ -n "$names" ] && { : > "$marker" 2>/dev/null || true; } ;; esac
# Stage 2 counts only a phase-2 line printed after this repo's verdict that names its file(s).
if [ "$gate" = "stage2" ] && [ "$what" = "this edit" ]; then
while IFS= read -r p2; do [ -n "$p2" ] && p2_here "$p2" && { gate="graded"; break; }; done <<<"$(printf '%s\n' "$rs" | tail -n +2)"
fi
# Stage 2: on a medium+ grade, edits wait for the file-level line, held at most twice per repo/session (never a wall).
s2="${marker%.done}.s2"; k="$(cat "$s2" 2>/dev/null)"; case "$k" in ''|*[!0-9]*) k=0 ;; esac
if [ "$what" = "this edit" ] && [ "$k" -lt 2 ] && [ "$gate" = "stage2" ] && printf '%s' "$((k + 1))" > "$s2" 2>/dev/null; then
dbg "PreToolUse: held $tool for the stage 2 (change-area) line"
deny "Stage 2 first: before editing $(basename "$file_path"), run the change-area probe on the file(s) you'll change and print the result with one Bash call: printf '%s\\n' '> LinearB phase 2 — <file>: ~N lines rewritten/90d over M commits — <concentrate guards + tests here | clean, standard care>'. If it changes the effort, print the full verdict line again instead. Then make the same call again."
fi
exit 0
fi
# Can't read the transcript -> can't confirm skill status -> fail open (allow).
Expand Down
25 changes: 14 additions & 11 deletions plugins/agentic-advisor/skills/agentic-advisor/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ set -o pipefail # with curl -f, a failed request fails the whole pipeline inst

Two checks that prevent wasted work — do them before any LinearB call:

- **Not a code task → no grade at all.** If the task will not modify any file (reading or explaining code, answering a question, reviewing a doc, ticket or screenshot, drafting a reply or message in chat), don't grade it: print `> LinearB: <repo> — skipped (not a code task)`, call nothing, and work with your normal care. A grade measures the risk of a code change; a LOW here would wrongly tell you to go light on accuracy. If the task later turns into a file edit, run the sweep then, before the first edit (a hook holds that edit until a real grade exists).
- **Not a code task → no grade at all.** If the task will not modify any file (reading or explaining code, answering a question, reviewing a doc, ticket or screenshot, drafting a reply or message in chat), don't grade it: print `> LinearB: <repo> — skipped (not a code task)`, call nothing, and work with your normal care. A grade measures the risk of a code change; a LOW here would wrongly tell you to go light on accuracy. If the task later turns into a file edit, run the sweep then, before the first edit.
- **Trivial code edit → LOW, skip everything.** If the task edits any file but changes **no code behavior** (code comments, doc files, formatting/whitespace, a pure rename), skip signal gathering entirely: effort is **LOW**, add no defensive guards (there's no logic to protect), and don't call LinearB at all — this holds **even on a fragile repo**. Anything that changes behavior is **not** trivial and warrants the sweep below — note that a **constant-value change counts as behavioral** (e.g. a timeout, retry count, or feature-flag default), as does any conditional or logic edit.
- **Already graded recently → reuse (persistent 24h cache).** The repo-level verdict is daily-stable, so compute it at most **once per repo per ~24h**, not once per task/session — this is the main token/time saver. Cache file, keyed by repo root:

Expand All @@ -63,14 +63,17 @@ Two checks that prevent wasted work — do them before any LinearB call:
root="$(git -C "<cwd>" rev-parse --show-toplevel)"; api="${LINEARB_API_URL:-https://public-api.linearb.io}"; api="${api%/}"
key="$root"; [ "$api" = "https://public-api.linearb.io" ] || key="$root|$api"
h="$(printf '%s' "$key" | { if command -v shasum >/dev/null 2>&1; then shasum; else sha1sum; fi; } | cut -c1-12)"
f="${XDG_CACHE_HOME:-$HOME/.cache}/agentic-advisor/verdicts/$h.json" # private per-user dir, not shared /tmp
d="${XDG_CACHE_HOME:-$HOME/.cache}/agentic-advisor/verdicts" # private per-user dir
# Claude Code's sandbox blocks writes to ~/.cache ("operation not permitted"); its $TMPDIR is per user and writable
(umask 077; mkdir -p "$d") 2>/dev/null && ( : > "$d/.w.$$" ) 2>/dev/null && rm -f "$d/.w.$$" || d="${TMPDIR:-/tmp}/agentic-advisor-verdicts-$(id -u)"
(umask 077; mkdir -p "$d") 2>/dev/null; [ -O "$d" ] || d="" # a folder someone else made is not safe to write in
f="${d:+$d/$h.json}" # empty: no safe cache folder, so skip the cache this time
cat "$f" 2>/dev/null # read BEFORE any LinearB call
```
- **On a hit** (file exists, **is owned by you** — check `[ -O "$f" ]` and ignore it otherwise, since a cache file someone else wrote could fake a LOW grade — AND `computed_at` is within the last 24h — or the file's mtime is <24h old): **skip the repo-health LinearB calls** (repo list, measurements, incidents/search) and reuse `repo_effort`/`repo_evidence` **as the repo-health axis only**. You MUST still grade **task-complexity and change-area (files) fresh for the current task**, then combine — the cache replaces the phase-1 *data*, NOT the final verdict. Note it — **keep the standard verdict shape** so the reporter still captures the decision: `LinearB: <repo> — <Raised|Reduced|Kept> effort (<levels>; repo-health cached <N>h ago; task + files fresh)`. (The ticket lookup under Task Complexity is per task, not repo health, so it still runs on a hit.)
- **On a miss/stale:** compute the repo-health verdict fresh, then **write the cache atomically** (a per-process temp file then `mv` — atomic on the same filesystem, and the `$$` suffix means two concurrent sessions never share a temp file):
```text
(umask 077; mkdir -p "${XDG_CACHE_HOME:-$HOME/.cache}/agentic-advisor/verdicts")
printf '%s' '{"repo":"<name>","repo_id":<id>,"repo_effort":"<LOW|MEDIUM|HIGH>","repo_evidence":"<real figures>","computed_at":"<ISO-8601 UTC>"}' > "$f.$$.tmp" && mv -f "$f.$$.tmp" "$f"
[ -n "$f" ] && printf '%s' '{"repo":"<name>","repo_id":<id>,"repo_effort":"<LOW|MEDIUM|HIGH>","repo_evidence":"<real figures>","computed_at":"<ISO-8601 UTC>"}' > "$f.$$.tmp" && mv -f "$f.$$.tmp" "$f"
```
- **Recompute (ignore cache) if:** it's older than 24h, you just merged/deployed to this repo, or a serious incident may have landed.
- **⚠️ The cache stores ONLY the repo-health verdict (phase 1: rework / incidents / unreviewed merges) — daily-stable and task-independent. It does NOT store the final combined effort.** Both **change-area (file fix/revert + ownership)** and **task-complexity** are per-task and are **NEVER cached** — recompute them every task and combine `max(cached repo-health, fresh task-complexity, fresh change-area)`. So a **different task on the same repo within 24h** reuses only the cheap repo-health part and still re-grades the task-specific axes → correct effort for the new task. A cached-calm repo can still surface a HIGH task or file finding.
Expand Down Expand Up @@ -268,16 +271,16 @@ Phase 2 was only ever deferred because it needs the target file paths. So:
```
This is the reliable path: it's part of the same up-front measurement, not a "remember later" step.
- **Only if the file cannot be known without exploring** (vague prompt) — emit the repo verdict first, explore to find the files, then before your first `Edit`/`Write` report phase 2. **Which line you print depends on whether phase 2 changes the effort** (recall `effort = max(repo-health, change-area, task)`, so a fix/revert hotspot can raise it above the repo level):
- **If phase 2 CHANGES the combined effort** — re-emit the **full verdict line** with the new level, so it stands as the corrected decision (this is the line that gets recorded; without it, telemetry keeps the stale phase-1 level):
```text
> LinearB: <repo> — <Raised|Reduced|Kept> effort (<levels>; repo rework X% — but target <file>: ~N lines rewritten/90d) — <what you'll do>.
- **If phase 2 CHANGES the combined effort** — re-emit the **full verdict line** with the new level, with the same one `printf` Bash call, so it stands as the corrected decision (this is the line that gets recorded; without it, telemetry keeps the stale phase-1 level):
```bash
printf '%s\n' '> LinearB: <repo> — <Raised|Reduced|Kept> effort (<levels>; repo rework X% — but target <file>: ~N lines rewritten/90d) — <what you will do>.'
```
- **If phase 2 does NOT change the level** — it's pure targeting context; print the short follow-up:
```text
> LinearB phase 2 — <file>: ~N lines rewritten/90d — <concentrate guards + tests here | clean, standard care>.
- **If phase 2 does NOT change the level** — it's pure targeting context; print the short follow-up with one `printf` Bash call (a hook shows it to the user):
```bash
printf '%s\n' '> LinearB phase 2 — <file>: ~N lines rewritten/90d over M commits — <concentrate guards + tests here | clean, standard care>.'
```

**HARD RULE either way:** on a phase-2-gated task, the file-level finding must be printed **before the first `Edit`/`Write` to a target file** — combined into the phase-1 verdict when the file is known, or as the follow-up line when it isn't. Measure and report first, edit second. Skip only for trivial edits.
**HARD RULE either way:** on a phase-2-gated task, the file-level finding must be printed **before the first `Edit`/`Write` to a target file** — combined into the phase-1 verdict when the file is known, or as the follow-up line when it isn't. Measure and report first, edit second. Skip only for trivial edits. When the grade is medium or above and no file was named, a hook holds your edit until the phase-2 line is printed (at most twice per repo and session).

## Coding Posture

Expand Down
Loading
Loading