SLOPSHOPPER

dev-hooks

Polyglot dev-workflow hooks for Claude Code: auto-lint on edit, verify tests/linters before stopping, a PreToolUse dangerous-command guard (catastrophic…

panebandrowsguardcommandtoast
v2.65.25MITupdated 2026-10-25mickzijdel/dev-hooks/plugins/dev-hooks
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · dev-hooks
│ ┃ Session status ✕ › fix the failing auth test and add an audit log call │ ┃ updated 08:53 │ ┃ ● Turn ended, no end report · since 08:53 (j ⏺ Read(src/auth.ts) │ ┃ last said: "Done. I made `refresh` reject ⎿ Read 6 lines │ ┃ expired clai…" ⏺ Update(src/auth.ts) │ ┃ [ Summarize this turn ] ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ Your move ⎿ 3 pass, 1 fail │ ┃ nothing │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ 1 turn · session since 08:53 (just now) │ ✻ Worked for 42s · done 4:20 PM │ │ › /context-bar │ ⎿ dev-hooks: Context bar on. │ │ Context bar: waiting for the first measurement… ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Context bar: waiting for the first measurement… ⟨Claude Code's own drawing⟩
Pane · Session status
updated 08:53 ● Turn ended, no end report · since 08:53 (just now) last said: "Done. I made `refresh` reject expired clai…" [ Summarize this turn ] Your move nothing 1 turn · session since 08:53 (just now)
README

dev-hooks

A Claude Code plugin bundling polyglot, project-agnostic dev-workflow hooks plus the companion skills the hooks point at. Each hook script detects the project's own toolchain (Ruby/Rails, JavaScript/TypeScript, Python) — there is nothing to configure.

Part of the dev-hooks marketplace, alongside coding-onboarding, thinking-tools, and writing.

Contents

Hooks

EventScriptPurpose
UserPromptSubmitprompt-log.shAppend one JSON line per user prompt (timestamp, repo cwd, session id, prompt length, first 500 chars) to ~/.claude/automation-review/prompts.jsonl (created 0600) — the cross-repo data source the thinking-tools weekly-automation-review skill clusters to spot repetitive requests worth automating. Credential-shaped values (vendor token prefixes, JWTs, private-key blocks, SECRET=-style assignments) are redacted to [REDACTED] before the line is written. Local-only, silent, never blocks the prompt. Opt out with DEV_HOOKS_PROMPT_LOG=false.
UserPromptSubmitintent-check-reminder.shWhen a prompt is a task (an imperative change, research or writing request — "add…", "refactor…", "research…", "look into…", "draft…") but states neither a why (intent) nor non-goals (what's out of scope), inject one advisory nudging Claude to play the brief back before substantial work (outcome, out of scope, depth and check-in point, done when, what it needs — thinking-tools' brief-back contract), and to ask the blocking questions when the task is ambiguous or high-stakes. Deliberately conservative — skips questions, follow-ups, one-liners, and prompts that already carry intent or scope markers, so it fires only on a genuinely thin brief. Advisory, never blocks; pairs with the agent-brief skill. Opt out with DEV_HOOKS_INTENT_CHECK=false.
UserPromptSubmitdata-before-design-reminder.shWhen a prompt asks to build a surface that displays stored data (a build verb followed closely by a display surface — card, panel, dashboard, table, report, profile, badge, tile, widget, …), inject one advisory pointing at the data-before-design skill: profile every field the view will show (non-null count, distinct values, length min/mean/max, coverage, cardinality per parent, date presence) and state the numbers before writing markup, then mock several options from the busiest, the typical and the empty record and let the user pick. Conservative — stays silent for pure restyling (colour/padding/font/spacing/alignment), reads only what you typed (a subagent's report, a task notification, IDE context, a pasted block or a forwarded side-agent note's quoted lines never trip it), and fires once per session. Advisory, never blocks. Opt out with DEV_HOOKS_DATA_BEFORE_DESIGN=false.
PreToolUse (Bash)dangerous-command-guard.shBlock the catastrophic, irreversible few before they run: wipe the disk/home (rm -rf /), fork bomb, format a filesystem (mkfs), overwrite a raw block device (dd of=/dev/…), chmod -R 777 /. Flags and targets are judged per simple command, split the way the shell would (quotes honoured; $(…), backticks, bash -c '…', eval, a heredoc fed to a shell, and what ssh, docker/kubectl/incus exec, watch and script -c run split out), so cd ~ && rm -rf build/ isn't read as rm -rf ~ and `rg "fnox getbws secret get" isn't read as a secret read. Risky-but-legitimate commands (rm -rf a path, git reset --hard, force-push, curl … \bash, sudo) are not gated — the normal permission flow already prompts on them, and Claude Code's auto-mode classifier catches them besides. Aimed at beginners not running auto mode, whose agents shouldn't be able to run a machine-wiping command on their say-so. The deny is configurable with DEV_HOOKS_GUARD_DENY (deny default / ask / allow) for advanced users. Opt-in extra (DEV_HOOKS_GUARD_MAIN=1, seeded by the coding-onboarding plugin's getting-started skill): ask before committing/pushing straight to main/master. Separately, it blocks a command that would print a secret value into the transcript — cat .env, cat config/master.key, bws secret get, op read, echo $GITHUB_TOKEN, and credential probes such as git credential fill, a helper's get, gh auth token, gh auth status -t, secret-tool lookup and cat ~/.git-credentials — since a leaked value can only really be fixed by rotating it; template files (.env.example), *.pub halves, inject-only wrappers (fnox run), source .env, counting greps, stdout sent to /dev/null or a file, and a value captured into a variable (v=$(fnox get X)) stay silent (2>/dev/null hides only stderr, so it doesn't). Configurable with DEV_HOOKS_GUARD_SECRETS (deny default / ask / allow) — it asked until 2.40.0, until an auto-mode classifier approved a ${VAR:-UNSET} presence check and leaked a live token. Opt out of the whole hook with DEV_HOOKS_BASH_GUARD=false`.
PreToolUse (Agent, Task, SendMessage)comment-brief-guard.shDenies a subagent brief that asks for a comment pass ("do a comment pass", "trim the comments") without naming the compress-comments skill, so Claude re-sends it telling the subagent to load the skill instead of restating its rules, which skips the skill's code-unchanged check. Only imperative phrasings match; a brief that mentions an earlier comment pass passes. Opt out with DEV_HOOKS_COMMENT_BRIEF_GUARD=false.
PostToolUse (Bash)ci-watch-reminder.shAfter a git push in a repo with GitHub Actions workflows, remind Claude to watch the CI run so a red pipeline comes back to it instead of going unnoticed — watch to completion when idle, or background the watch (or hand it to a sub-agent) when there's more work, rather than pushing and forgetting. Reminder-only: the hook never runs gh; Claude does. Fires on real git push invocations (git push, git -C dir push, … && git push), not git config …pushurl/switch/pushall, and only when .github/workflows/ exists. Advisory, never blocks. Stands down where the mod's CI watch (below) watches the run itself (it sets DEV_HOOKS_CI_WATCH_SESSION to the session id). Opt out of both with DEV_HOOKS_CI_WATCH=false.
PostToolUse (Bash)worktree-provision-reminder.shAfter git worktree add, check whether the new worktree is missing gitignored state the main checkout has (Rails storage/ blobs, config/credentials/master.key, .env, service-account JSON, uploads) and point at [[worktree-setup]]'s setup-worktree.sh. Compares exact ignored paths, not top-level dirs — storage/ exists in a fresh worktree because storage/.keep is tracked, while every blob is absent, so the app boots and then 500s on each image as if the view were broken. Load-bearing entries lead the report; editor/tool caches are excluded. Silent when the worktree is correctly provisioned. Advisory, never blocks. Opt out with DEV_HOOKS_WORKTREE_PROVISION=false.
PostToolUse (Write\Edit\MultiEdit)lint-on-edit.shAuto-fix/format the file Claude just wrote using the linter this project configures (RuboCop/Standard, herb/erb_lint for ERB, Biome/Prettier/ESLint, Ruff/Black). Safe fixes only, never blocks. For Python it marks the code-deleting rules unfixable (F401 unused import, F841 unused variable) so a beat-early import/binding isn't stripped before the line that uses it lands — verify-work.sh/CI still flag them; override with DEV_HOOKS_RUFF_KEEP (set empty to restore full autofix).
PostToolUse (Write\Edit\MultiEdit)latest-deps-reminder.shWhen Claude writes a dependency manifest (requirements.txt, package.json, Gemfile, pyproject.toml, …) or hand-writes a lockfile, remind it to verify the versions are current (training data goes stale) with the right lookup command per ecosystem, or to regenerate lockfiles via the package manager. On manifest edits it also nudges Claude to keep the README/CLAUDE.md key-package versions in sync (creating those docs if missing). Advisory only, never blocks; fires once per session per ecosystem.
PostToolUse (Write\Edit\MultiEdit)scaffold-reminder.shWhen Claude creates a new project manifest or framework entrypoint by hand (Gemfile, package.json, pyproject.toml, Cargo.toml, go.mod, mix.exs, composer.json, build.gradle/pom.xml, manage.py, config/application.rb, …), remind it to run the framework's official generator (rails new, npm create vite@latest, django-admin startproject, cargo new, …) instead of scaffolding from memory — and to check the framework's current stable release and the generator's current flags first, unless the user pinned a version. Write-tool only; files git already tracks are skipped. Advisory only, never blocks; fires once per session. Opt out with DEV_HOOKS_SCAFFOLD=false.
PostToolUse (Write\Edit\MultiEdit)dockerfile-reminder.shWhen Claude writes a Dockerfile/Containerfile, run hadolint on it and feed the findings (or a clean pass) back to Claude, plus a layer-ordering nudge that points at the dockerfile skill. If hadolint isn't installed, falls back to a once-per-session ordering/gotchas reminder. Advisory only — reports every time, never blocks.
PostToolUse (Write\Edit\MultiEdit)secret-plaintext-reminder.shWhen Claude writes what looks like a plaintext secret value (a named API_KEY/SECRET/TOKEN/PASSWORD assignment to a real literal, a private-key block, or an AWS key id), nudge it to migrate to fnox via the env-to-fnox skill instead of committing the value. Fires at write time (before gitleaks would at commit). Env-var refs and obvious placeholders are ignored. Advisory only, never blocks; fires once per session.
PostToolUse (Write\Edit\MultiEdit)popover-reminder.shWhen Claude writes popover/tooltip/dropdown/menu UI (a frontend file — the shared extension list, see inline-svg-reminder.sh notes — that has a popover/tooltip/dropdown controller filename, role="tooltip"/the popover attribute, an @floating-ui/popper/tippy import, a data-controller naming one, or a tooltip/popover/dropdown class/data-attribute), nudge it to use a collision-aware positioner (flip + shift) rendered in the top layer/a portal instead of hand-rolled top/left math, and point at the popovers-tooltips skill. Advisory only, never blocks; fires once per session. Opt out with DEV_HOOKS_POPOVER=false.
PostToolUse (Write\Edit\MultiEdit)ci-action-ref-reminder.shWhen Claude writes/edits a GitHub Actions workflow (a *.yml/*.yaml pinning uses: owner/repo@ref), point it at the github-actions skill's supply-chain checklist (SHA-pin every action, read-only GITHUB_TOKEN, no untrusted input in run:) and have it verify the pins with the bundled check_action_refs.sh (which resolves each pin's # vX.Y.Z comment via git ls-remote and fails on a missing/mismatched tag); the hook itself never hits the network. Advisory only, never blocks; fires once per session per file.
PostToolUse (Write\Edit\MultiEdit)inline-svg-reminder.shWhen Claude hand-writes inline SVG into a frontend file (an <svg> blob with real drawing content — <path>/<circle>/<rect>/… or long d="M…" path data — or a data:image/svg+xml URI), feed a correction back (exit 2, every occurrence): use the project's icon library (named from package.json/Gemfile when found), else extract to a dedicated .svg file/sprite and reference it. Good patterns stay silent: <use href> sprite refs, writing .svg files, , markdown, test files, data-driven chart markup (<rect x={…}>), and pre-existing SVG (Writes deduped against HEAD, Edits against old_string). Opt out with DEV_HOOKS_SVG_INLINE=false.
PostToolUse (Write\Edit\MultiEdit)migration-safety-reminder.shWhen Claude writes a database migration (Rails db/migrate/*.rb, Django <app>/migrations/*.py, Alembic …/versions/*.py), nudge it to check safe-migration practice — reversibility (change/up+down/downgrade), no data backfill inside a schema migration, lock-safe column adds (nullable → batched backfill → constraint), and concurrent index creation (algorithm: :concurrently + disable_ddl_transaction!, CREATE INDEX CONCURRENTLY, AddIndexConcurrently). Advisory only, never blocks; fires once per session. Opt out with DEV_HOOKS_MIGRATION=false.
PostToolUse (Write\Edit\MultiEdit)a11y-reminder.shWhen Claude writes frontend markup with common accessibility gaps — an <img> with no alt, an icon-only <button>/<a> with no accessible name, a click handler on a non-interactive <div>/<span>, or an unlabeled form <input> — flag them and point at the accessibility skill. Scans only what the call adds; heuristic. Advisory only, never blocks; fires once per session. Opt out with DEV_HOOKS_A11Y=false.
PostToolUse (Write\Edit\MultiEdit)sql-injection-reminder.shWhen Claude writes SQL with a value interpolated straight into the query string (a Python f-string, Ruby #{}, or string concatenation around SQL keywords), nudge it toward parameterized queries / ORM bind variables. The safe %s/:name/? placeholder styles are not flagged. Advisory only, never blocks; fires once per session. Opt out with DEV_HOOKS_SQL_INJECTION=false.
PostToolUse (Write\Edit\MultiEdit)error-swallow-reminder.shWhen Claude writes a handler that silently swallows the error (a Python bare except: or except …: pass, an empty JS/TS catch {}, or an empty Ruby rescue … end), nudge it to catch the specific exception and handle/log/re-raise instead. Scans only what the call adds. Advisory only, never blocks; fires once per session. Opt out with DEV_HOOKS_ERROR_SWALLOW=false.
Stopverify-work.shOn stop, detect changed code files and run the project's linters/tests (RuboCop, herb + brakeman for Rails, Minitest/RSpec, Ruff/pytest — through uv run in a uv project, ESLint/JS tests). Blocks the stop with real failures so Claude fixes them before finishing — these re-block on every stop until fixed, including the continuation another Stop hook forced (capped at 3 blocks in a row there; when the mod runs it, DEV_HOOKS_ORCHESTRATED, it says on stderr that the cap silenced a standing failure, so the nudge isn't scored as a pass). When code changed but no tooling is recognised, it nudges Claude to check manually at most once per session, then lets it finish (no Stop loop). Turn the whole hook off with DEV_HOOKS_VERIFY=false (per-repo/user).
Stopdebug-leftover-reminder.shOn stop, flag debug statements Claude newly introduced this session (console.log/debugger, binding.pry/byebug/Ruby p, breakpoint()/pdb) — diffed against HEAD so pre-existing lines are ignored — and feed them back (blocks the stop) to strip before finishing. Test files excluded. Fires at most once per session.
Stopmissing-test-reminder.shOn stop, if Claude added a new source file this session with no matching test (*_spec.rb/*_test.rb, test_*.py/*_test.py, *.test.*/*.spec.*), nudge it (blocks the stop) to add one. Counts files added by commits made during the session as well as uncommitted ones, so committing as you go doesn't hide them. Skips test files, low-value targets (barrels, type defs, config, migrations, __init__/conftest), and vendored/generated code (dirs from the repo's .jscpd.json, plus minified *.min.*). Fires at most once per session.
SessionStartdev-env-reminder.shIf the repo is yours and the dev-env standard applies but isn't met (missing mise/hk/CI/gitleaks, or behind the version stamp), nudge Claude to flag it and offer the dev-env-setup skill. Advisory only — never edits. Owner-gated (see env vars below); opt out per repo.
SessionStartdocs-context.shIf the project has a docs/ or doc/ directory containing Markdown files, emit a brief index (titles + optional descriptions from YAML frontmatter) so Claude knows where documentation lives and can consult the right files when working on related features. Docs whose frontmatter carries an opt-in stale_after: YYYY-MM-DD (past) or status: stale/deprecated/draft get their line flagged with ⚠ so Claude doesn't blindly trust an out-of-date doc; docs without the fields are unaffected. Advisory only — never blocks. Opt out with DEV_HOOKS_DOCS_CONTEXT=false.
SessionStartscript-index.shList the custom CLI tools in your saved script library — each executable shebang script's path + its # short-description: line — so Claude knows what already exists and reaches for it instead of re-solving the problem, like a lightweight skill index. The library is DEV_HOOKS_SCRIPT_DIR, a colon-separated list of roots like PATH (default ~/.local/bin), each scanned recursively so a cloned scripts repo with subdirectories works. Scripts with no # short-description: are listed under a placeholder telling Claude to run <path> --help and ask you to add one. Hide scripts that aren't your own tools (installed/third-party CLIs, app launchers) with DEV_HOOKS_SCRIPT_IGNORE — a colon-separated list of globs matched against each script's basename or full path (e.g. *vocalinux*:gext). Never executes a script (so no --help side effects at startup). Paired with the script-library skill. Advisory only — never blocks. Opt out with DEV_HOOKS_SCRIPT_INDEX=false.
Stopplan-reminder.shIf .claude/current_plan.md exists and is stale, remind Claude to update the multi-session plan before ending. Nudges once per version of the plan, not once per stop.
Stopreview-reminder.shOn stop, if this session touched code files but no code review ran since, remind Claude (blocks the stop) to run a review and keep iterating until it comes back clean. "This session's work" counts uncommitted changes and commits made since the session started, so the commit-as-you-go workflow's clean tree no longer silences it. "Already reviewed" is a tool-use scan for /code-review, a code-reviewer agent, requesting-code-review, or a dispatched agent whose description says "review" (how a subagent-driven session reviews) — not a bare name grep, which would match the transcript's skill listing in every session. Re-arms rather than firing once: while no review has run it asks at every stop (once only for a change under 10 added lines, up to 3 times above that, so a Claude that cannot review still terminates); once one has run, the session's added-code-line total becomes a baseline and the hook speaks again when it grows by ≥ 20 — code written after a review makes that review stale. Opt out with DEV_HOOKS_REVIEW=false.
Stopcompress-comments-reminder.shOn stop, if the session's work added a noticeable number of comment lines to code files (≥ 3, counting added lines in one diff from the last commit before the session started — the transcript's first timestamp — to the working tree, plus untracked code files, so commit-as-you-go sessions still trigger and rewriting this session's own comments is not growth; shebangs and directive comments like shellcheck/noqa/eslint don't count), remind Claude (blocks the stop) to run the compress-comments skill — delete comments that restate the code, compress the rest. Re-arms rather than firing once: the comment total at each reminder is stored per session, and the hook fires again whenever the total grows by ≥ 10 — one large commit or purely uncommitted edits alike. A skill run after a reminder (in the session or, via the mod's facts, in a subagent) absorbs the growth since, so comments merged in from already-compressed work don't re-fire. An unchanged total stays silent (no Stop loop), a dropped total (cleanup) rebases the baseline, and a skill run before any reminder seeds it (detected by tool-use scan, not a bare name grep — the transcript's skill listing names every installed skill). Opt out with DEV_HOOKS_COMPRESS_COMMENTS=false.
Stopmemory-reminder.shOn stop of a substantial session (≥ 6 human turns), remind Claude (blocks the stop) to capture durable, non-obvious learnings into its file-based memory — memory dir only, never CLAUDE.md, with an explicit "nothing worth saving" escape hatch. Fires at most once per session, and not at all once a memory file was written this session (including by a subagent, when the mod runs the Stop hooks). Opt-in via DEV_HOOKS_MEMORY=1, or auto-enabled once you use Claude's memory feature anywhere.
Stopbig-change-reminder.shOn stop, if the working tree holds a very large uncommitted change (default: ≥ 25 files or ≥ 800 added lines), nudge Claude (blocks the stop) to slow down — commit the working pieces in small, focused commits, run tests, get a review, and consider plan mode for the next chunk. Stays silent when a multi-session plan is already in progress (.claude/current_plan.md). Aimed at beginners, for whom a giant uncommitted diff is hard to review and easy to lose. Fires once per session. Thresholds tunable via DEV_HOOKS_BIG_CHANGE_FILES/DEV_HOOKS_BIG_CHANGE_LINES; opt out with DEV_HOOKS_BIG_CHANGE=false.
Stopsave-script-reminder.shOn stop, if Claude wrote a script this session (a Write of shebang-prefixed content, wherever it landed — scratchpad, /tmp, or inside a project repo; only scripts already in a library root are excluded), nudge it (blocks the stop) to decide per script: a broadly useful tool gets genericized to the saved-script standard (PEP 723 + uv run shebang + # short-description: + chmod +x) and added to a library root (or a subdirectory) so the script-index hook surfaces it next session — even one already committed to a repo can be worth promoting — while a genuinely task-specific or throwaway script is left where it is. Points at the script-library skill. Fires at most once per session. Library roots come from DEV_HOOKS_SCRIPT_DIR; opt out with DEV_HOOKS_SAVE_SCRIPT=false.
Stopend-report-reminder.shOn stop of a turn that did work (a file edit, or ≥ 10 tool calls), block once if Claude's last message has no Changed or Your move line. That last message is what you read when you come back to a session you left running, so it has to stand alone: what is different now, and every action you still have to take, including asks buried in earlier messages. It also checks the reply another Stop hook forced (still at most one block per stop), since that reply is the one you see last. Every dev-hooks and writing Stop message ends with the same footer asking for the full end report again (REMINDER_END_REPORT_FOOTER; the mod adds it once to its merged message), with the hook's own work reported only as what it changed, found or left undone: never a clean result or the hook's name. Both stand down in a headless run (claude -p, the Agent SDK), whose end report nobody reads. Threshold tunable via DEV_HOOKS_END_REPORT_TOOLS; opt out with DEV_HOOKS_END_REPORT=false.

Skills

The companion skills the hooks point at:

SkillUse when

| dev-env-setup | Auditing/setting up a repo against an opinionated dev-env standard, version-tracked via DEV_ENV_VERSION: mise pinning the toolchain, an hk pre-commit hook running linters/tests + gitleaks + zizmor & actionlint (GitHub Actions security + correctness checks, v18) (Rails gets the v17 ERB + security + correctness suite —

Source 5 files
hooks/register.tsx 1202 lines
1// dev-hooks' function-hook module (Claude Code mods, 2.1.287+). Command hooks stay in
2// hooks.json; this file holds what only a mod can do, such as drawing UI.
3//
4// /context-bar: the context window as a stacked bar above the prompt, one color per
5// /context category, refreshed after every turn from the local (API-free) estimate.
6//
7// Session facts: what this session did, recorded as it happens rather than rebuilt
8// from git and the transcript at Stop — skills expanded (main loop and subagents),
9// subagents dispatched, files edited per repo with net growth, and the Stop verdict
10// the command hooks returned. The Stop orchestration below hands it to the Stop hooks.
11//
12// Stop orchestration: the module runs dev-hooks' own Stop command hooks itself and
13// returns their reasons as one block. It marks the session with DEV_HOOKS_MOD_SESSION,
14// which makes the copies Claude Code runs directly stand down (reminder_stop_init), and
15// runs its own copies with DEV_HOOKS_ORCHESTRATED set. Without this module (an older
16// Claude Code, mods off) nothing is marked and the command hooks run as before.
17//
18// Stop-nudge outcomes: each reason the orchestration returns is resolved at the next
19// Stop as acted on or not (nudge-outcomes.ts), shown by /session-facts nudges.
20//
21// CI watch: after a git push the module follows that push's GitHub Actions runs and
22// tells the person and Claude how they ended (the block marked below).
23import type { EngineInterface, Register } from 'claude-code'
24
25import type { BackgroundItem, Facts, Nudge, NudgeRecord, Segment, Snapshot, StatusPaneState, TurnRecord } from '../types'
26import {
27  ciNote,
28  ciStatusLine,
29  ciToast,
30  ciVerdict,
31  gitDir,
32  githubRepo,
33  isDryRun,
34  isGitPush,
35  isQuietPush,
36  parsePushOutput,
37  parseRuns,
38  pushDir,
39  pushRepositories,
40  RUN_FIELDS,
41  watchingNote,
42} from './ci-watch'
43import type { PushSection, Run, Watch } from './ci-watch'
44import {
45  formatNudgeStats,
46  hookName,
47  isProbeSession,
48  mergeNudgeLog,
49  newNudge,
50  NUDGE_LOG_KEY,
51  nudgeExport,
52  nudgeExportFile,
53  resolvePending,
54  toRecord,
55} from './nudge-outcomes'
56import {
57  answerFacts,
58  clockTime,
59  EMPTY_PANE_STATE,
60  findBrief,
61  keepTurns,
62  noReportTurn,
63  paneView,
64  parseCommits,
65  parseEndReport,
66  sinceLabel,
67  typedFrom,
68} from './status-pane'
69
70const isShown = { plugin: 'dev-hooks', key: 'contextBarShown' } as const
71const snapshot = { plugin: 'dev-hooks', key: 'contextBarSnapshot' } as const
72
73const formatTokens = (n: number) =>
74  n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : `${n}`
75
76// Largest-remainder split, so the cells always add up to the bar's width
77// and any category with tokens gets at least the cell its share earns.
78export const allocate = (segments: Segment[], width: number): number[] => {
79  const total = segments.reduce((sum, s) => sum + s.tokens, 0)
80  if (total === 0 || width <= 0) return segments.map(() => 0)
81  const exact = segments.map(s => (s.tokens / total) * width)
82  const cells = exact.map(Math.floor)
83  let left = width - cells.reduce((sum, c) => sum + c, 0)
84  const byRemainder = exact
85    .map((x, i) => ({ i, rest: x - Math.floor(x) }))
86    .sort((a, b) => b.rest - a.rest)
87  for (const { i } of byRemainder) {
88    if (left-- <= 0) break
89    cells[i] = (cells[i] ?? 0) + 1
90  }
91  return cells
92}
93
94async function refresh($: EngineInterface) {
95  const { context } = await $.session.usage({ breakdown: 'summary' })
96  const b = context.breakdown
97  if (!b) return
98  const next: Snapshot = {
99    segments: b.categories
100      .filter(c => c.kind !== 'deferred' && c.tokens > 0)
101      .map(c => ({ name: c.name, tokens: c.tokens, color: c.color, kind: c.kind as Segment['kind'] })),
102    totalTokens: b.totalTokens,
103    maxTokens: b.rawMaxTokens,
104    percentage: b.percentage,
105  }
106  await $.state.set(snapshot, next)
107}
108
109type Patch = { lines: string[] }[]
110
111// Net growth: a replaced line is a -/+ pair, not growth. A created file's
112// patch is empty, so count its content instead.
113export const netAdded = (patch: Patch | undefined, created: string | undefined): number => {
114  const lines = (patch ?? []).flatMap(hunk => hunk.lines)
115  if (lines.length === 0 && created !== undefined) {
116    return created === '' ? 0 : created.replace(/\n$/, '').split('\n').length
117  }
118  return lines.filter(l => l.startsWith('+')).length - lines.filter(l => l.startsWith('-')).length
119}
120
121const FACTS_TTL_MS = 30 * 86_400_000
122const emptyFacts = (): Facts => ({ updatedAt: 0, skills: [], agents: [], repos: [], stops: [] })
123
124// $.store, not $.state: facts must survive a reboot or a resumed session.
125async function loadFacts($: EngineInterface, sessionId?: string): Promise<Facts> {
126  const id = sessionId ?? (await $.session.id())
127  return ((await $.store.get(`facts:${id}`)) as Facts | undefined) ?? emptyFacts()
128}
129
130// The store has no compare-and-set and tool calls run in parallel, so every
131// read-modify-write goes through one queue.
132let factsQueue: Promise<unknown> = Promise.resolve()
133
134function changeFacts($: EngineInterface, fn: (f: Facts) => Facts, sessionId?: string): Promise<Facts> {
135  const run = factsQueue.then(async () => {
136    const id = sessionId ?? (await $.session.id())
137    const next = { ...fn(await loadFacts($, id)), updatedAt: Date.now() }
138    await $.store.set(`facts:${id}`, next)
139    return next
140  })
141  factsQueue = run.catch(() => undefined)
142  return run
143}
144
145// Returns the facts kept, by session id.
146async function pruneFacts($: EngineInterface): Promise<Map<string, Facts>> {
147  const cutoff = Date.now() - FACTS_TTL_MS
148  const kept = new Map<string, Facts>()
149  for (const key of await $.store.keys()) {
150    if (!key.startsWith('facts:')) continue
151    const f = (await $.store.get(key)) as Facts | undefined
152    if (!f || f.updatedAt < cutoff) await $.store.delete(key)
153    else kept.set(key.slice('facts:'.length), f)
154  }
155  return kept
156}
157
158export const ago = (at: number, now: number): string => {
159  const mins = Math.floor((now - at) / 60_000)
160  if (mins < 1) return 'just now'
161  if (mins < 60) return `${mins}m ago`
162  if (mins < 24 * 60) return `${Math.floor(mins / 60)}h${mins % 60 ? `${mins % 60}m` : ''} ago`
163  return `${Math.floor(mins / (24 * 60))}d ago`
164}
165
166const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
167
168// This session's Stop nudges, shown only once one fired.
169const nudgeSection = (nudges: Nudge[], when: (at: number) => string): string[] =>
170  nudges.length === 0
171    ? []
172    : [
173        '',
174        `Stop nudges (${nudges.length})`,
175        ...nudges.map(n => `  ${when(n.at)} ${n.hook} · ${n.outcome ? `${n.outcome} (${n.evidence})` : 'pending'}`),
176      ]
177
178// Plain text: command output is shown as-is, not rendered as markdown.
179export const formatFacts = (f: Facts, now: number, home: string): string => {
180  const tilde = (path: string) => (home && path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path)
181  const when = (at: number) => ago(at, now).padEnd(8)
182  // "Title: none" when empty; otherwise the heading (with its count) and the rows.
183  const section = (title: string, count: string, rows: string[]) =>
184    rows.length === 0 ? [`${title}: none`] : [`${title}${count}`, ...rows, '']
185
186  const repos = [...f.repos].sort((a, b) => Number(a.root === null) - Number(b.root === null))
187  const edits = repos.flatMap(r => {
188    const where = r.root === null ? 'outside any repo' : tilde(r.root)
189    const inRepo = (file: string) => r.root !== null && file.startsWith(`${r.root}/`)
190    const bySub = r.bySubagent > 0 ? ` · ${plural(r.bySubagent, 'edit')} by subagents` : ''
191    return [
192      `  ${where} · ${r.added >= 0 ? '+' : ''}${r.added} lines · ${plural(r.files.length, 'file')}${bySub}`,
193      ...r.files.map(file => `    ${inRepo(file) ? file.slice((r.root ?? '').length + 1) : tilde(file)}`),
194    ]
195  })
196  const blocked = f.stops.filter(s => s.block !== null)
197  // A merged block is its reasons joined by blank lines, then the footer: one line for each.
198  const reasons = (block: string) =>
199    block
200      .replace(END_REPORT_FOOTER, '')
201      .split(/\n\s*\n/)
202      .map(part => part.trim().split('\n')[0] ?? '')
203      .filter(Boolean)
204
205  const lines = [
206    f.updatedAt ? `Session facts · updated ${ago(f.updatedAt, now)}` : 'Session facts · nothing recorded yet',
207    '',
208    ...section('Skills', ` (${f.skills.length})`, f.skills.map(s => `  ${when(s.at)} ${s.skill}`)),
209    ...section(
210      'Subagents',
211      ` (${f.agents.length})`,
212      f.agents.map(a => `  ${when(a.at)} ${a.subagentType} · ${a.description}`),
213    ),
214    ...section('Edits via Edit/Write (Bash-made edits are not tracked)', '', edits),
215    ...(f.stops.length === 0
216      ? ['Stops: none']
217      : [
218          `Stops (${f.stops.length}, ${blocked.length || 'none'} blocked)`,
219          ...blocked.flatMap(s =>
220            reasons(s.block ?? '').map((r, i) => `  ${i === 0 ? when(s.at) : ' '.repeat(8)} ${r}`),
221          ),
222        ]),
223    ...nudgeSection(f.nudges ?? [], when),
224  ]
225  if (lines[lines.length - 1] !== '') lines.push('')
226  return [
227    ...lines,
228    '/session-facts json prints the raw record; /session-facts nudges, Stop-nudge outcomes across sessions.',
229  ].join('\n')
230}
231
232const repoRoots = new Map<string, string | null>()
233
234async function repoRoot($: EngineInterface, file: string): Promise<string | null> {
235  const dir = file.slice(0, file.lastIndexOf('/')) || '/'
236  const known = repoRoots.get(dir)
237  if (known !== undefined) return known
238  const run = await $.process.run(['git', '-C', dir, 'rev-parse', '--show-toplevel'])
239  const root = run.exitCode === 0 ? run.stdout.trim() : null
240  repoRoots.set(dir, root)
241  return root
242}
243
244export type StopHook = { command: string; timeoutMs: number }
245
246// Claude Code's default for a command hook with no `timeout`, in seconds.
247const DEFAULT_HOOK_TIMEOUT_S = 600
248
249type HookEntry = { type?: string; command?: string; timeout?: number }
250
251export const stopHooks = (config: unknown): StopHook[] => {
252  const groups = (config as { hooks?: { Stop?: { hooks?: HookEntry[] }[] } } | null)?.hooks?.Stop ?? []
253  return groups
254    .flatMap(group => group.hooks ?? [])
255    .filter((h): h is HookEntry & { command: string } => h.type === 'command' && typeof h.command === 'string')
256    .map(h => ({ command: h.command, timeoutMs: (h.timeout ?? DEFAULT_HOOK_TIMEOUT_S) * 1000 }))
257}
258
259// A command hook's Stop answer, read as Claude Code reads it: exit 2 blocks with
260// stderr as the reason; exit 0 blocks only with a decision:block JSON answer.
261// verify-work.sh's stderr (exit 0, which Claude Code ignores) when it stood down at its
262// block cap with the failure still standing.
263export const STOP_CAPPED_MARK = 'dev-hooks: block cap reached'
264
265type StopRun = { exitCode: number; stdout: string; stderr: string }
266
267export const stopCapped = (run: StopRun): boolean => run.exitCode === 0 && run.stderr.includes(STOP_CAPPED_MARK)
268
269export const stopReason = (run: StopRun): string | null => {
270  if (run.exitCode === 2) return run.stderr.trim() || null
271  if (run.exitCode !== 0) return null
272  try {
273    const out = JSON.parse(run.stdout) as { decision?: unknown; reason?: unknown }
274    return out.decision === 'block' && typeof out.reason === 'string' && out.reason.trim() ? out.reason : null
275  } catch {
276    return null
277  }
278}
279
280// reminder-common.sh's REMINDER_END_REPORT_FOOTER, which the orchestrated hooks leave to the
281// merged block; pinned by test_end_report_footers_match.
282export const END_REPORT_FOOTER =
283  'Whatever the above asks, do it without narrating it, then end with your full end report again, written for someone who reads only that message: Status (say what is still running and what happens when it lands), Done when, Changed (what is different now: files linked, commits, settings, anything sent), Assumed, Not checked, and Your move (every action the person must take, including asks from earlier in this turn, or "nothing"); drop any other line that would be empty. Report that work only as what it changed, what it found that needs the person, or what it left undone, one line each in that report: never a clean result, an ask that did not apply, a hook name, why a hook fired, or that it misfired.'
284
285// A footer the writing plugin's Stop hook gave `below` moves to the end, once.
286export const mergeBlocks = (below: string | undefined, reasons: string[], footer = true): string | undefined => {
287  if (reasons.length === 0) return below
288  const parts = [...(below ? [below.replace(END_REPORT_FOOTER, '').trim()] : []), ...reasons].filter(Boolean)
289  return [...parts, ...(footer ? [END_REPORT_FOOTER] : [])].join('\n\n')
290}
291
292// A `claude -p` or Agent SDK run: nobody reads its end report (reminder_is_headless).
293const isHeadless = async ($: EngineInterface) => ((await $.env.get('CLAUDE_CODE_ENTRYPOINT')) ?? '').startsWith('sdk-')
294
295async function ownStopHooks($: EngineInterface): Promise<StopHook[]> {
296  return stopHooks(JSON.parse(await $.fs.read(`${$.plugin.root}/hooks/hooks.json`)))
297}
298
299// A failed orchestration is remembered against this plugin version, so a broken
300// release doesn't cost every new session its first Stop; a new version tries again.
301const ORCHESTRATION_FAILED = 'stopOrchestrationFailed'
302
303async function pluginVersion($: EngineInterface): Promise<string> {
304  const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: string }
305  return manifest.version ?? 'unknown'
306}
307
308// Runs dev-hooks' Stop commands as Claude Code would and merges their reasons after
309// `below` (any block from hooks beneath the module).
310async function orchestrateStop(
311  $: EngineInterface,
312  e: StopInput,
313  below: string | undefined,
314): Promise<string | undefined> {
315  const stdin = JSON.stringify(e)
316  // The facts reach the shell hooks as a file (reminder_transcript_invoked reads it):
317  // they see skills and agents run inside subagents, which the transcript doesn't.
318  // Optional — without them the hooks fall back to the transcript.
319  const factsFile = `${(await $.env.get('TMPDIR')) || '/tmp'}/dev-hooks-facts-${e.session_id}.json`
320  const hasFacts = await $.fs
321    .write(factsFile, JSON.stringify(await loadFacts($)))
322    .then(() => true, () => false)
323  const env = {
324    CLAUDE_PLUGIN_ROOT: $.plugin.root,
325    DEV_HOOKS_ORCHESTRATED: '1',
326    ...(hasFacts ? { DEV_HOOKS_FACTS_FILE: factsFile } : {}),
327  }
328  const hooks = await ownStopHooks($)
329  const runs = await Promise.all(
330    hooks.map(hook =>
331      $.process
332        .run(['bash', '-c', hook.command], { cwd: e.cwd, stdin, env, timeoutMs: hook.timeoutMs })
333        .then(
334          run => ({ reason: stopReason(run), capped: stopCapped(run) }),
335          () => ({ reason: null, capped: false }),
336        ),
337    ),
338  )
339  const block = mergeBlocks(
340    below,
341    runs.flatMap(r => (r.reason !== null ? [r.reason] : [])),
342    !(await isHeadless($)),
343  )
344  const stop = { at: Date.now(), block: block ?? null }
345  await changeFacts($, f => ({ ...f, stops: [...f.stops, stop].slice(-20) })).catch(() => undefined)
346  const fired = hooks.flatMap((hook, i) => {
347    const reason = runs[i]?.reason
348    return reason ? [{ hook: hookName(hook.command), reason }] : []
349  })
350  const capped = hooks.flatMap((hook, i) => (runs[i]?.capped ? [hookName(hook.command)] : []))
351  await trackNudges($, e, fired, capped).catch(() => undefined)
352  return block
353}
354
355// ── Guard dialog ─────────────────────────────────────────────────────────────────
356// When dangerous-command-guard.sh asks (its `ask` modes), the mod puts the question to
357// the person in Claude Code's own dialog: a PreToolUse `ask` is answered by the
358// auto-mode classifier, the dialog is not. Allow only withdraws the guard's question —
359// the normal permission flow still runs — and Deny refuses; a hard deny is never asked.
360export const GUARD_PREFIX = 'dev-hooks guard — '
361
362export const isGuardAsk = (ask: string | undefined): ask is string => !!ask && ask.startsWith(GUARD_PREFIX)
363
364const COMMAND_SHOWN = 300
365
366const waitLabel = (seconds: number) => (seconds % 60 === 0 ? `${seconds / 60} min` : `${seconds}s`)
367
368export const guardQuestion = (ask: string, command: string, seconds = 0): string => {
369  const reason = ask.slice(GUARD_PREFIX.length).replace(/^please confirm:\s*/i, '')
370  const shown = command.length > COMMAND_SHOWN ? `${command.slice(0, COMMAND_SHOWN)}…` : command
371  const wait = seconds > 0 ? `\n\n(No answer within ${waitLabel(seconds)} refuses it.)` : ''
372  return `${reason}\n\nCommand: ${shown}${wait}\n\nLet it run?`
373}
374
375// An unanswered dialog refuses after this long, and tells Claude the safer route instead of
376// leaving it stuck. DEV_HOOKS_GUARD_DIALOG_TIMEOUT (seconds; 0 waits forever) set in front of
377// the command itself wins — Claude may pick a longer wait, since a timeout only ever refuses —
378// then the session's setting, then this default.
379const DEFAULT_GUARD_TIMEOUT_S = 120
380
381const COMMAND_TIMEOUT_RE =
382  /(?:^|[;&|]\s*)(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*DEV_HOOKS_GUARD_DIALOG_TIMEOUT=(['"]?)(\d+)\1(?=\s)/
383
384export const commandTimeout = (command: string): number | undefined => {
385  const match = COMMAND_TIMEOUT_RE.exec(command)
386  return match ? Number(match[2]) : undefined
387}
388
389export const guardTimeoutReason = (ask: string, seconds: number): string => {
390  const base =
391    `No answer in the dev-hooks guard dialog within ${seconds}s, so this command did not run.` +
392    ' (If the person may need longer, put DEV_HOOKS_GUARD_DIALOG_TIMEOUT=<seconds> in front of the command; 0 waits indefinitely.)'
393  return /the `[^`]+` branch directly/.test(ask)
394    ? `${base} Make this change on a separate branch in a git worktree instead (branch off the current HEAD), not directly on the main branch.`
395    : `${base} Ask the person in the chat before trying again, or find a route that doesn't need this command.`
396}
397
398// A dialog can't be closed from the mod, so one that timed out stays on screen. The mod
399// remembers it (question text -> note) and its render hook redraws it as a note: what was
400// asked, what Claude was told instead, and options that just close it.
401const GUARD_TIMED_OUT = { plugin: 'dev-hooks', key: 'guardTimedOut' } as const
402const TIMED_OUT_KEPT = 20
403
404export const timedOutNote = (command: string, seconds: number, toldClaude: string): string => {
405  const shown = command.length > COMMAND_SHOWN ? `${command.slice(0, COMMAND_SHOWN)}…` : command
406  return (
407    `⏱ This guard question timed out after ${waitLabel(seconds)} and no longer does anything.` +
408    `\n\nIt asked about: ${shown}\n\nClaude was told: ${toldClaude}\n\nEither option just closes this.`
409  )
410}
411
412// The dialog outlives its timeout (VS Code doesn't draw it through the render hook above), and
413// the person may still answer it. That late answer reaches Claude as a prompt; a late Allow
414// also lets that exact command through once, for a while, without asking again.
415const LATE_ALLOW_MS = 10 * 60_000
416const lateAllowed = new Map<string, number>()
417
418export const lateAnswerNote = (command: string, answer: string): string => {
419  const head = `[dev-hooks guard] The person answered the guard question about \`${command}\` after it had timed out:`
420  if (answer === 'Allow')
421    return `${head} Allow. If you still want it, run that exact command again — it will go through once without asking (for the next 10 minutes).`
422  if (answer === 'Deny') return `${head} Deny. Don't run it.`
423  return `${head} "${answer}"`
424}
425
426// From session.start: whether a person is there to answer the dialog.
427let isInteractive = false
428
429async function guardTimeoutSeconds($: EngineInterface, command: string): Promise<number> {
430  const own = commandTimeout(command)
431  if (own !== undefined) return own
432  const raw = await $.env.get('DEV_HOOKS_GUARD_DIALOG_TIMEOUT').catch(() => undefined)
433  const seconds = Number(raw)
434  return raw !== undefined && raw.trim() !== '' && Number.isFinite(seconds) && seconds >= 0
435    ? seconds
436    : DEFAULT_GUARD_TIMEOUT_S
437}
438
439// ── Stop-nudge outcomes ─────────────────────────────────────────────────────────
440// Each reason the orchestration returns is a nudge in this session's facts; the next
441// Stop resolves the pending ones as acted/ignored/declined/unknown (nudge-outcomes.ts
442// holds the remedy per hook), and the resolved ones go to a cross-session log in the
443// store (`nudgeOutcomes`), exported for the weekly automation review.
444
445type StopInput = { session_id: string; cwd: string; last_assistant_message?: string }
446
447// A session idle this long with a nudge still pending never reached another Stop or a
448// clean session end (killed, crashed): resolve it from its facts at the next start.
449const NUDGE_SWEEP_IDLE_MS = 6 * 3_600_000
450
451async function trackNudges(
452  $: EngineInterface,
453  e: StopInput,
454  fired: { hook: string; reason: string }[],
455  capped: string[],
456) {
457  // A probe never adds a nudge, so session end and the sweep have none to log either.
458  const home = (await $.env.get('HOME')) ?? ''
459  const probe = await $.env.get('DEV_HOOKS_PROBE')
460  if (isProbeSession({ session: e.session_id, cwd: e.cwd, home, probe })) return
461  const now = Date.now()
462  let resolved: Nudge[] = []
463  await changeFacts($, f => {
464    const ev = { facts: f, refired: fired.map(x => x.hook), capped, lastMessage: e.last_assistant_message, atStop: true }
465    const r = resolvePending(f, ev, now)
466    resolved = r.resolved
467    if (fired.length === 0) return r.facts
468    const added = fired.map(x => newNudge(x.hook, x.reason, now))
469    return { ...r.facts, nudges: [...(r.facts.nudges ?? []), ...added].slice(-100) }
470  })
471  await logNudges($, resolved.map(n => toRecord(e.session_id, n)))
472}
473
474// The session is ending: whatever is still pending gets no further Stop.
475async function closeNudges($: EngineInterface, sessionId: string) {
476  if (!((await loadFacts($, sessionId)).nudges ?? []).some(n => n.outcome === undefined)) return
477  let resolved: Nudge[] = []
478  await changeFacts(
479    $,
480    f => {
481      const r = resolvePending(f, { facts: f, refired: [], atStop: false }, Date.now())
482      resolved = r.resolved
483      return r.facts
484    },
485    sessionId,
486  )
487  await logNudges($, resolved.map(n => toRecord(sessionId, n)))
488}
489
490// At session start: resolve abandoned sessions' pending nudges, and re-add every resolved
491// nudge the kept facts hold, repairing a log write another process raced.
492async function sweepNudges($: EngineInterface, kept: Map<string, Facts>, current: string) {
493  const now = Date.now()
494  const records: NudgeRecord[] = []
495  for (const [id, f] of kept) {
496    let facts = f
497    const pending = (f.nudges ?? []).some(n => n.outcome === undefined)
498    if (id !== current && pending && f.updatedAt < now - NUDGE_SWEEP_IDLE_MS) {
499      facts = resolvePending(f, { facts: f, refired: [], atStop: false }, now).facts
500      await $.store.set(`facts:${id}`, facts)
501    }
502    for (const n of facts.nudges ?? []) if (n.outcome !== undefined) records.push(toRecord(id, n))
503  }
504  await logNudges($, records)
505}
506
507async function loadNudgeLog($: EngineInterface): Promise<NudgeRecord[]> {
508  return ((await $.store.get(NUDGE_LOG_KEY)) as NudgeRecord[] | undefined) ?? []
509}
510
511async function logNudges($: EngineInterface, records: NudgeRecord[]) {
512  if (records.length === 0) return
513  const now = Date.now()
514  const log = mergeNudgeLog(await loadNudgeLog($), records, now)
515  await $.store.set(NUDGE_LOG_KEY, log)
516  // Beside the prompt log and hook-fires.jsonl; only where that directory already exists.
517  const dir = `${(await $.env.get('HOME')) ?? ''}/.claude/automation-review`
518  if (await $.fs.exists(dir)) {
519    await $.fs.write(`${dir}/${nudgeExportFile($.plugin.root)}`, `${JSON.stringify(nudgeExport(log, now))}\n`)
520  }
521}
522
523// ── CI watch ────────────────────────────────────────────────────────────────────────
524// After a successful `git push` the module watches that push's GitHub Actions runs:
525// progress in the status line, a toast when they end, and the outcome handed to Claude
526// (a pass as a conversation note, a failure as a prompt that wakes the session). It
527// marks the session with DEV_HOOKS_CI_WATCH_SESSION so ci-watch-reminder.sh stands down;
528// DEV_HOOKS_CI_WATCH=false turns both off. Watches live in module variables: a reload
529// of the module drops them.
530const CI_FIRST_POLL_MS = 3_000
531const CI_APPEAR_MS = 120_000
532const CI_RETRY_MS = 5_000
533const CI_POLL_MS = 15_000
534const CI_GIVE_UP_MS = 90 * 60_000
535
536const ciWatches = new Map<string, Watch & { startedAt: number }>()
537
538async function ciOptedOut($: EngineInterface): Promise<boolean> {
539  return (await $.env.get('DEV_HOOKS_CI_WATCH')) === 'false'
540}
541
542async function claimCiWatch($: EngineInterface) {
543  if (!(await ciOptedOut($))) await $.env.set('DEV_HOOKS_CI_WATCH_SESSION', await $.session.id())
544}
545
546function showCiStatus($: EngineInterface) {
547  $.ui.status(ciStatusLine([...ciWatches.values()]))
548}
549
550async function git($: EngineInterface, cwd: string, ...args: string[]): Promise<string | null> {
551  const run = await $.process.run(['git', '-C', cwd, ...args]).catch(() => null)
552  return run?.exitCode === 0 ? run.stdout.trim() : null
553}
554
555// Where a bare `git push` goes, as git picks it: branch.<name>.pushRemote, then
556// remote.pushDefault, then the branch's upstream remote. Null when none is set (git
557// then pushes to origin).
558async function branchPushRemote($: EngineInterface, root: string): Promise<string | null> {
559  const branches = await git($, root, 'for-each-ref', '--format=%(HEAD)%(push:remotename)', 'refs/heads')
560  return branches?.split('\n').find(line => line.startsWith('*'))?.slice(1) || null
561}
562
563// The URLs the command pushed to: each remote a push names, or the branch's push remote
564// for a bare push. Never just the fetch remote, which in a fork checkout is the fork.
565async function commandRemotes($: EngineInterface, root: string, command: string): Promise<string[]> {
566  const urls = await Promise.all(
567    pushRepositories(command).map(async named => {
568      const remote = named ?? (await branchPushRemote($, root))
569      return remote ? git($, root, 'ls-remote', '--get-url', remote) : git($, root, 'ls-remote', '--get-url')
570    }),
571  )
572  return [...new Set(urls.filter((u): u is string => u !== null))]
573}
574
575// The commits a push sent to GitHub and where it sent them, from its output. Refs whose
576// `To` line was cut (`| tail -1`) go to the remotes the command names; a quiet push (`-q`)
577// prints no ref lines, so it falls back to HEAD.
578async function pushTargets($: EngineInterface, command: string, output: string): Promise<{ repo: string; sha: string }[]> {
579  const root = await git($, pushDir(command, await $.session.cwd()), 'rev-parse', '--show-toplevel')
580  if (root === null) return []
581  const workflows = await $.fs.list(`${root}/.github/workflows`).catch(() => [])
582  if (!workflows.some(w => /\.ya?ml$/.test(w.name))) return []
583
584  const sections = parsePushOutput(output)
585  // No ref lines: up to date, or no push ran at all (the command only mentioned one), unless
586  // a quiet push hid them.
587  if (sections.length === 0 && (/Everything up-to-date/.test(output) || !isQuietPush(command))) return []
588  const parts: PushSection[] = sections.length > 0 ? sections : [{ refs: [] }]
589  const targets = new Map<string, { repo: string; sha: string }>()
590  for (const section of parts) {
591    const urls = section.remote ? [section.remote] : await commandRemotes($, root, command)
592    const repos = urls.map(githubRepo).filter((r): r is string => r !== null)
593    const refs = section.refs.length > 0 ? section.refs.map(r => r.sha ?? r.src) : ['HEAD']
594    const shas = await Promise.all(refs.map(ref => git($, root, 'rev-parse', `${ref}^{commit}`)))
595    for (const repo of repos) for (const sha of shas) if (sha !== null) targets.set(`${repo}@${sha}`, { repo, sha })
596  }
597  return [...targets.values()]
598}
599
600async function startCiWatch($: EngineInterface, target: { repo: string; sha: string }) {
601  const key = `${target.repo}@${target.sha}`
602  if (ciWatches.has(key)) return
603  ciWatches.set(key, { ...target, done: 0, total: 0, startedAt: await $.clock.now() })
604  showCiStatus($)
605  $.clock.after(CI_FIRST_POLL_MS, () => void pollCi($, key))
606}
607
608async function pollCi($: EngineInterface, key: string) {
609  const w = ciWatches.get(key)
610  if (!w) return
611  try {
612    let runs: Run[] = []
613    let error: string | undefined
614    try {
615      const argv = ['gh', 'run', 'list', '--repo', w.repo, '--commit', w.sha, '--json', RUN_FIELDS, '--limit', '50']
616      const run = await $.process.run(argv, { timeoutMs: 30_000 })
617      if (run.exitCode === 0) runs = parseRuns(run.stdout)
618      else error = run.stderr.trim().split('\n')[0] || `gh exited ${run.exitCode}`
619    } catch (err) {
620      error = String(err)
621    }
622    const { verdict, runs: mine } = ciVerdict(runs, w.sha)
623    const elapsed = (await $.clock.now()) - w.startedAt
624    if (verdict === 'pending' ? elapsed < CI_GIVE_UP_MS : verdict === 'none' && elapsed < CI_APPEAR_MS) {
625      w.done = mine.filter(r => r.status === 'completed').length
626      w.total = mine.length
627      showCiStatus($)
628      $.clock.after(verdict === 'none' ? CI_RETRY_MS : CI_POLL_MS, () => void pollCi($, key))
629      return
630    }
631
632    ciWatches.delete(key)
633    showCiStatus($)
634    $.ui.toast(ciToast(w.repo, w.sha, verdict, mine), { timeoutMs: verdict === 'success' ? 8_000 : 20_000 })
635    const note = ciNote(w.repo, w.sha, verdict, mine, error)
636    // A failure needs Claude to act, so it starts a turn (once the session is idle);
637    // anything else is read with Claude's next request without waking it.
638    if (verdict === 'failure') await $.prompt.submit({ text: note })
639    else await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: note }] } })
640  } catch (err) {
641    ciWatches.delete(key)
642    showCiStatus($)
643    $.ui.log(`dev-hooks: CI watch for ${key} failed: ${String(err)}`)
644  }
645}
646// ── end CI watch ────────────────────────────────────────────────────────────────────
647
648// ── Session-status pane ───────────────────────────────────────────────────────────
649// Records the session's turns, tool counts, commits and background work for the pane;
650// what it shows is derived in status-pane.ts.
651const PANE_STATE = { plugin: 'dev-hooks', key: 'statusPane' } as const
652// Change the tag when StatusPaneState changes: a value stored under another is declined.
653const PANE_SHAPE = 'status-pane-2'
654const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
655
656async function loadPane($: EngineInterface): Promise<StatusPaneState> {
657  const stored = (await $.state.get(PANE_STATE)).value
658  return stored?.shape === PANE_SHAPE ? stored.value : EMPTY_PANE_STATE(await $.clock.now())
659}
660
661// Tool calls run in parallel and $.state has no compare-and-set: one queue, as for facts.
662let paneQueue: Promise<unknown> = Promise.resolve()
663
664function changePane($: EngineInterface, fn: (s: StatusPaneState, now: number) => StatusPaneState): Promise<void> {
665  const run = paneQueue.then(async () => {
666    const now = await $.clock.now()
667    const next = { ...fn(await loadPane($), now), updatedAt: now }
668    await $.state.set(PANE_STATE, { shape: PANE_SHAPE, value: next })
669  })
670  paneQueue = run.catch(() => undefined)
671  return run
672}
673
674const changeOpenTurn = (s: StatusPaneState, fn: (t: TurnRecord) => TurnRecord): StatusPaneState => {
675  const open = s.turns.findLast(t => t.endedAt === undefined)
676  return open ? { ...s, turns: s.turns.map(t => (t === open ? fn(t) : t)) } : s
677}
678
679// The open turn is waiting on the person: an AskUserQuestion, or the guard's dialog.
680const setAsking = ($: EngineInterface, asking: boolean) =>
681  changePane($, s => changeOpenTurn(s, t => ({ ...t, asking }))).catch(() => undefined)
682
683// prompt.submit names the next turn's origin before turn.start; a Stop hook's continuation
684// has none, and reads as not typed.
685let nextOrigin: string | undefined
686
687// A repo by its main checkout's name, so a worktree's commits count for their repo.
688const repoNames = new Map<string, string | null>()
689
690async function repoName($: EngineInterface, dir: string): Promise<string | null> {
691  if (!repoNames.has(dir)) {
692    const common = await git($, dir, 'rev-parse', '--path-format=absolute', '--git-common-dir')
693    repoNames.set(dir, common?.replace(/\/\.git\/?$/, '').split('/').at(-1) || null)
694  }
695  return repoNames.get(dir) ?? null
696}
697
698async function recordGit($: EngineInterface, command: string, output: string) {
699  const commits = parseCommits(output)
700  const pushed = isGitPush(command) && !isDryRun(command) && parsePushOutput(output).some(p => p.refs.length > 0)
701  if (commits.length === 0 && !pushed) return
702  const cwd = await $.session.cwd()
703  const repo = await repoName($, gitDir(command, cwd, pushed && commits.length === 0 ? 'push' : 'commit'))
704  if (repo === null) return
705  await changePane($, (s, now) => {
706    const prev = s.repos.find(r => r.repo === repo) ?? { repo, commits: 0, lastCommitAt: 0 }
707    const next = {
708      ...prev,
709      commits: prev.commits + commits.length,
710      ...(commits.length > 0 ? { lastCommitAt: now } : {}),
711      ...(pushed ? { lastPushAt: now } : {}),
712    }
713    return { ...s, repos: [...s.repos.filter(r => r.repo !== repo), next] }
714  })
715}
716
717type StopBackground = {
718  background_tasks?: { id: string; type: string; status: string; description: string }[]
719  session_crons?: { id: string; prompt: string }[]
720}
721
722// What still runs when a turn stops: a task keeps the time it was first seen.
723async function recordBackground($: EngineInterface, e: StopBackground) {
724  const tasks = (e.background_tasks ?? []).filter(t => t.status === 'running' || t.status === 'pending')
725  const crons = e.session_crons ?? []
726  await changePane($, (s, now) => {
727    const seen = new Map(s.background.map(b => [b.id, b.since]))
728    const items: BackgroundItem[] = [
729      ...tasks.map(t => ({ id: t.id, label: t.description || t.type, since: seen.get(t.id) ?? now })),
730      ...crons.map(c => ({ id: c.id, label: `wakes up: ${c.prompt}`, since: seen.get(c.id) ?? now })),
731    ]
732    return { ...s, background: items }
733  })
734}
735const STATUS_PANE = 'session-status'
736const PANE_TITLE = 'Session status'
737// shortcut: a fullscreen terminal docks a pane too, but can't be told apart here; it
738// gets /session-status.
739const DOCKING_SURFACES = new Set(['vscode', 'desktop'])
740
741async function openPaneUnasked($: EngineInterface, surface: string | null) {
742  if (surface === null || !DOCKING_SURFACES.has(surface)) return
743  if ((await $.env.get('DEV_HOOKS_STATUS_PANE')) === 'false') return
744  void $.ui.open({ id: STATUS_PANE, title: PANE_TITLE }).catch(() => undefined)
745}
746
747const ciBackground = (): BackgroundItem[] =>
748  [...ciWatches.values()].map(w => ({ label: `CI ${w.repo.split('/').at(-1)}@${w.sha.slice(0, 7)}`, since: w.startedAt }))
749
750const SUMMARY_PROMPT =
751  'Write the end report for the turn that just ended, as plain lines and nothing else: a "Status:" line, then "Your move:" with each action for the person as a "- " bullet, or "Your move: nothing".'
752
753// The turn a Summarize press is answering, if any: module memory, so a reload mid-fork
754// clears it instead of leaving the button gone for good.
755let summarizing: string | undefined
756
757// The pane's one model call, made only when the person presses Summarize.
758async function summarizeTurn($: EngineInterface) {
759  const target = noReportTurn(await loadPane($))?.id
760  if (target === undefined || summarizing !== undefined) return
761  const mark = (fn: (t: TurnRecord) => TurnRecord) =>
762    changePane($, s => ({ ...s, turns: s.turns.map(t => (t.id === target ? fn(t) : t)) }))
763  summarizing = target
764  await mark(t => ({ ...t, summaryError: undefined }))
765  const answer = await $.model.fork({ prompt: SUMMARY_PROMPT }).catch(() => null)
766  summarizing = undefined
767  const summary = answer?.isAnswered ? parseEndReport(answer.text) : null
768  const failed = answer === null ? 'the call failed' : answer.isAnswered ? 'the answer held no end report' : answer.reason
769  await mark(t => ({ ...t, ...(summary ? { summary } : { summaryError: failed }) }))
770}
771
772// The pane's ages ("12 min") move on their own: redraw once a minute while it is open.
773let paneTicking = false
774
775function tickPane($: EngineInterface) {
776  if (paneTicking) return
777  paneTicking = true
778  const tick = async () => {
779    const panes = await $.ui.panes().catch(() => [])
780    if (!panes.some(p => p.id === STATUS_PANE)) {
781      paneTicking = false
782      return
783    }
784    $.ui.invalidate('ui.render')
785    $.clock.after(60_000, () => void tick())
786  }
787  $.clock.after(60_000, () => void tick())
788}
789
790const clamp = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text)
791// ── end session-status pane ─────────────────────────────────────────────────────────
792
793async function guardNow($: EngineInterface): Promise<number> {
794  return $.clock.now().catch(() => Date.now())
795}
796
797async function lateGuardAnswer($: EngineInterface, command: string, answer: string) {
798  if (answer === 'Allow') lateAllowed.set(command, (await guardNow($)) + LATE_ALLOW_MS)
799  await $.prompt.submit({ text: lateAnswerNote(command, answer) }).catch(() => undefined)
800}
801
802export const register: Register = on => {
803  on('session.start', async ($, e, next) => {
804    isInteractive = e.isInteractive
805    await $.command.register({
806      name: 'context-bar',
807      description: 'Toggle a stacked context-usage bar above the prompt',
808    })
809    await $.command.register({
810      name: 'session-facts',
811      description: 'Show what dev-hooks recorded about this session (nudges: Stop-nudge outcomes)',
812    })
813    await $.command.register({
814      name: STATUS_PANE,
815      description: 'Show where this session stands: what it needs from you, what runs, what changed',
816    })
817    const kept = await pruneFacts($)
818    await sweepNudges($, kept, await $.session.id()).catch(() => undefined)
819    if ((await $.state.get(isShown)).value) await refresh($)
820    // Only take the Stop hooks over once their config reads cleanly, and not on a
821    // version whose orchestration already failed; otherwise leave the session unmarked
822    // so the command hooks keep running directly.
823    const failedOn = await $.store.get(ORCHESTRATION_FAILED)
824    if ((await ownStopHooks($)).length > 0 && failedOn !== (await pluginVersion($))) {
825      await $.env.set('DEV_HOOKS_MOD_SESSION', await $.session.id())
826    }
827    await claimCiWatch($)
828    await openPaneUnasked($, e.surface).catch(() => undefined)
829
830    return next(e)
831  })
832
833  on('command.run', { command: 'context-bar' }, async $ => {
834    const shown = !(await $.state.get(isShown)).value
835    await $.state.set(isShown, shown)
836    if (shown) await refresh($)
837
838    return { text: shown ? 'Context bar on.' : 'Context bar off.' }
839  })
840
841  on('session.measure', async ($, e, next) => {
842    if ((await $.state.get(isShown)).value) await refresh($)
843
844    return next(e)
845  })
846
847  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
848    if (e.props.hasSurvey || !(await $.state.get(isShown)).value) return next(e)
849    const snap = (await $.state.get(snapshot)).value
850    const { Box, Text } = $.ui.resolve(e)
851    // Stack above whatever the plugins beneath draw (another plugin's band), never replace it.
852    const below = await next(e).catch(() => undefined)
853    const stacked = (mine: JSX.Element) =>
854      below ? (
855        <Box flexDirection="column">
856          {mine}
857          {below}
858        </Box>
859      ) : (
860        mine
861      )
862
863    if (!snap) {
864      return stacked(
865        <Box>
866          <Text dimColor>Context bar: waiting for the first measurement…</Text>
867        </Box>,
868      )
869    }
870
871    const summary = ` ${snap.percentage}% · ${formatTokens(snap.totalTokens)}/${formatTokens(snap.maxTokens)}`
872    const width = Math.max(10, e.props.bodyColumns - summary.length - 1)
873    const cells = allocate(snap.segments, width)
874    const glyph = (s: Segment) => (s.kind === 'free' ? '░' : s.kind === 'buffer' ? '▒' : '█')
875
876    return stacked(
877      <Box flexDirection="column">
878        <Box>
879          <Text>
880            {snap.segments.map((s, i) => (
881              <Text color={s.color} dimColor={s.kind === 'free'}>
882                {glyph(s).repeat(cells[i] ?? 0)}
883              </Text>
884            ))}
885          </Text>
886          <Text dimColor>{summary}</Text>
887        </Box>
888        <Box flexWrap="wrap">
889          {snap.segments.map(s => (
890            <Text>
891              <Text color={s.color}>{glyph(s)} </Text>
892              <Text dimColor>
893                {s.name} {formatTokens(s.tokens)}
894                {'  '}
895              </Text>
896            </Text>
897          ))}
898        </Box>
899      </Box>
900    )
901  })
902
903  on('command.run', { command: 'session-facts' }, async ($, e) => {
904    const [sub, arg] = e.args.trim().split(/\s+/)
905    if (sub === 'nudges') {
906      const days = Number(arg) > 0 ? Number(arg) : 7
907      return { text: formatNudgeStats(await loadNudgeLog($), Date.now(), days) }
908    }
909    const f = await loadFacts($)
910    if (sub === 'json') return { text: JSON.stringify(f, null, 2) }
911
912    return { text: formatFacts(f, Date.now(), (await $.env.get('HOME')) ?? '') }
913  })
914
915  on('skill.prompt', async ($, e, next) => {
916    const at = Date.now()
917    await changeFacts($, f => ({ ...f, skills: [...f.skills, { skill: e.skill, at }].slice(-200) }))
918
919    return next(e)
920  })
921
922  on('agent.spawn', async ($, e, next) => {
923    const agent = { description: e.description, subagentType: e.subagentType, at: Date.now() }
924    await changeFacts($, f => ({ ...f, agents: [...f.agents, agent].slice(-200) }))
925
926    return next(e)
927  })
928
929  on('tool.call', async ($, e, next) => {
930    const asks = e.agentId === undefined && e.tool === 'AskUserQuestion'
931    if (asks) await setAsking($, true)
932    const ran = await next(e)
933    if (asks) await setAsking($, false)
934    if (e.agentId === undefined) {
935      const edited = EDIT_TOOLS.has(e.tool) && ran.deny === undefined && !ran.isError
936      await changePane($, s =>
937        changeOpenTurn(s, t => ({ ...t, calls: t.calls + 1, edits: t.edits + (edited ? 1 : 0) })),
938      ).catch(() => undefined)
939    }
940    if (ran.deny !== undefined || ran.isError || (e.tool !== 'Edit' && e.tool !== 'Write')) return ran
941
942    const result = ran.result as { structuredPatch?: Patch; type?: string } | undefined
943    const created = e.tool === 'Write' && result?.type === 'create' ? e.content : undefined
944    const added = netAdded(result?.structuredPatch, created)
945    const root = await repoRoot($, e.file_path)
946    const bySubagent = e.agentId === undefined ? 0 : 1
947
948    await changeFacts($, f => {
949      const prev = f.repos.find(r => r.root === root) ?? { root, files: [], added: 0, bySubagent: 0 }
950      const repo = {
951        root,
952        files: prev.files.includes(e.file_path) ? prev.files : [...prev.files, e.file_path],
953        added: prev.added + added,
954        bySubagent: prev.bySubagent + bySubagent,
955      }
956      const lastEdit = { ...f.lastEdit, [e.file_path]: Date.now() }
957      return { ...f, repos: [...f.repos.filter(r => r.root !== root), repo], lastEdit }
958    })
959
960    return ran
961  })
962
963  on('session.attach', async ($, e, next) => {
964    await openPaneUnasked($, e.surface).catch(() => undefined)
965
966    return next(e)
967  })
968
969  on('command.run', { command: STATUS_PANE }, async $ => {
970    await $.ui.open({ id: STATUS_PANE, title: PANE_TITLE })
971
972    return { text: 'Session status pane opened.' }
973  })
974
975  on('ui.render', { component: 'Pane', requestId: STATUS_PANE }, async ($, e) => {
976    const { Box, Text, Button } = $.ui.resolve(e)
977    tickPane($)
978    const s = await loadPane($)
979    const now = await $.clock.now()
980    const v = paneView(s, ciBackground(), now, summarizing)
981    const width = Math.max(20, e.props.bodyColumns)
982    const section = (title: string, rows: string[], dim = false) => (
983      <Box flexDirection="column" marginTop={1}>
984        <Text dimColor>{title}</Text>
985        {rows.map(row => (
986          <Text dimColor={dim}>{clamp(row, 2 * width)}</Text>
987        ))}
988      </Box>
989    )
990    // Number the actions, not the "+N more" row after them.
991    const moves =
992      v.yourMove.length === 0
993        ? ['nothing']
994        : v.yourMove.length === 1
995          ? v.yourMove
996          : v.yourMove.map((m, i) => (/^\+\d+ more$/.test(m) ? m : `${i + 1}. ${m}`))
997    const parts = [
998      <Text dimColor>{`updated ${clockTime(s.updatedAt ?? s.startedAt)}`}</Text>,
999      <Box>
1000        {v.tone === 'dim' ? <Text dimColor>{`● ${v.label}`}</Text> : <Text color={v.tone} bold>{`● ${v.label}`}</Text>}
1001        <Text dimColor>{` · ${sinceLabel(v.since, now)}`}</Text>
1002      </Box>,
1003      ...(v.lastSaid ? [<Text dimColor>{`last said: "${clamp(v.lastSaid, width - 13)}"`}</Text>] : []),
1004      ...(v.canSummarize ? [<Button key="summarize" label="Summarize this turn" onPress={() => summarizeTurn($)} />] : []),
1005      ...(v.summarizing ? [<Text dimColor>Summarizing…</Text>] : []),
1006      ...(v.summaryError ? [<Text color="red">{`summary failed: ${v.summaryError}`}</Text>] : []),
1007      section('Your move', moves, v.yourMove.length === 0),
1008      ...(v.doing ? [section('Doing', [clamp(v.doing, 2 * width)])] : []),
1009      ...(v.doneWhen.length > 0
1010        ? [
1011            <Box flexDirection="column" marginTop={1}>
1012              <Text dimColor>Done when</Text>
1013              {v.doneWhen.map(d =>
1014                d.met === null ? (
1015                  <Text dimColor>{`○ ${clamp(d.text, 2 * width)}`}</Text>
1016                ) : (
1017                  <Text color={d.met ? 'green' : 'red'}>{`${d.met ? '✓' : '✗'} ${clamp(d.text, 2 * width)}`}</Text>
1018                ),
1019              )}
1020              {v.doneWhenNote ? <Text dimColor>{`report: ${clamp(v.doneWhenNote, 2 * width)}`}</Text> : <Text> </Text>}
1021            </Box>,
1022          ]
1023        : []),
1024      ...(v.running.length > 0 ? [section('Running', v.running)] : []),
1025      ...(v.changed.length + v.repoLines.length > 0
1026        ? [
1027            <Box flexDirection="column" marginTop={1}>
1028              <Text dimColor>Changed</Text>
1029              {v.changed.map(row => (
1030                <Text>{clamp(row, 2 * width)}</Text>
1031              ))}
1032              {v.repoLines.map(row => (
1033                <Text dimColor>{clamp(row, width)}</Text>
1034              ))}
1035            </Box>,
1036          ]
1037        : []),
1038      ...(v.notChecked.length > 0 ? [section('Not checked', v.notChecked, true)] : []),
1039      <Box marginTop={1}>
1040        <Text dimColor>{`${v.turnCount} turn${v.turnCount === 1 ? '' : 's'} · session ${sinceLabel(s.startedAt, now)}`}</Text>
1041      </Box>,
1042    ]
1043
1044    return <Box flexDirection="column">{parts}</Box>
1045  })
1046
1047  on('prompt.submit', async ($, e, next) => {
1048    if (e.turnId === undefined) nextOrigin = e.origin.kind
1049
1050    return next(e)
1051  })
1052
1053  on('turn.start', async ($, e, next) => {
1054    if (e.agentId === undefined) {
1055      const turn: TurnRecord = { id: e.turnId, startedAt: 0, typed: typedFrom(nextOrigin, e.text), calls: 0, edits: 0 }
1056      nextOrigin = undefined
1057      await changePane($, (s, now) => ({
1058        ...s,
1059        turns: keepTurns([
1060          // Main-loop turns don't overlap: one still open never got its end.
1061          ...s.turns.map(t => (t.endedAt === undefined ? { ...t, endedAt: now, end: 'aborted' as const } : t)),
1062          { ...turn, startedAt: now },
1063        ]),
1064        turnsTotal: s.turnsTotal + 1,
1065      })).catch(() => undefined)
1066    }
1067
1068    return next(e)
1069  })
1070
1071  on('turn.complete', async ($, e, next) => {
1072    if (e.agentId === undefined) {
1073      // A brief comes with a task the person typed; other turns don't read the transcript.
1074      const typed = (await loadPane($)).turns.find(t => t.id === e.turnId)?.typed === true
1075      const messages = typed ? await $.session.messages().catch(() => []) : []
1076      const texts = Array.isArray(messages) ? messages.filter(m => m.role === 'assistant').map(m => m.text) : []
1077      const brief = findBrief(texts)
1078      await changePane($, (s, now) => ({
1079        ...s,
1080        turns: s.turns.map(t => (t.id !== e.turnId ? t : {
1081          ...t,
1082          endedAt: now,
1083          end: e.reason,
1084          ...answerFacts(e.answer),
1085          report: parseEndReport(e.answer),
1086        })),
1087        brief: brief ?? s.brief,
1088      })).catch(() => undefined)
1089    }
1090
1091    return next(e)
1092  })
1093
1094  on('session.end', async ($, e, next) => {
1095    await closeNudges($, e.sessionId).catch(() => undefined)
1096
1097    return next(e)
1098  })
1099
1100  // CI watch: a push that went through starts a watch on its runs.
1101  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
1102    const ran = await next(e)
1103    if (ran.deny !== undefined || ran.isError || e.tool !== 'Bash') return ran
1104    await recordGit($, e.command, ran.text ?? '').catch(() => undefined)
1105    if (!isGitPush(e.command) || isDryRun(e.command) || (await ciOptedOut($))) return ran
1106
1107    const targets = await pushTargets($, e.command, ran.text ?? '')
1108    if (targets.length === 0) return ran
1109    for (const target of targets) await startCiWatch($, target)
1110
1111    return { ...ran, context: [...(ran.context ?? []), watchingNote(targets)] }
1112  })
1113
1114  // Sees the command hooks' Stop verdict folded last-write-wins: with several
1115  // blocking, only the last reason arrives here (Claude still gets them all).
1116  on('classic.Stop', async ($, e, next) => {
1117    const below = await next(e)
1118    await recordBackground($, e).catch(() => undefined)
1119    if ((await $.env.get('DEV_HOOKS_MOD_SESSION')) !== e.session_id) return below
1120
1121    try {
1122      const block = await orchestrateStop($, e, below.block)
1123      return block === undefined ? below : { ...below, block }
1124    } catch (error) {
1125      // The command hooks stood down for this session, so a failure here would
1126      // silence every later Stop too: hand Stop back to them from the next turn.
1127      await $.env.set('DEV_HOOKS_MOD_SESSION', undefined)
1128      await $.store.set(ORCHESTRATION_FAILED, await pluginVersion($).catch(() => 'unknown')).catch(() => undefined)
1129      $.ui.log(`dev-hooks: Stop orchestration failed, the Stop hooks run directly from now on: ${String(error)}`)
1130      return below
1131    }
1132  })
1133
1134  on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
1135    const first = e.props.questions[0] as { question?: unknown } | undefined
1136    if (!first || typeof first.question !== 'string') return next(e)
1137    // Read while drawing, so a timeout recorded later redraws this dialog.
1138    const note = ((await $.state.get(GUARD_TIMED_OUT)).value ?? {})[first.question]
1139    if (!note) return next(e)
1140    const closes = { description: 'Closes this note; it changes nothing.' }
1141    return next({
1142      ...e,
1143      props: {
1144        ...e.props,
1145        questions: [{ ...first, question: note, multiSelect: false, options: [{ label: 'Close', ...closes }, { label: 'OK', ...closes }] }],
1146      },
1147    })
1148  })
1149
1150  on('classic.PreToolUse', async ($, e, next) => {
1151    const decided = await next(e)
1152    if (e.tool !== 'Bash' || !isGuardAsk(decided.ask)) return decided
1153    const allowedUntil = lateAllowed.get(e.command)
1154    if (allowedUntil !== undefined) {
1155      lateAllowed.delete(e.command)
1156      if (allowedUntil > (await guardNow($))) {
1157        const { ask: _answeredLate, ...rest } = decided
1158        return rest
1159      }
1160    }
1161    const seconds = await guardTimeoutSeconds($, e.command)
1162    const question = guardQuestion(decided.ask, e.command, seconds)
1163    await setAsking($, true)
1164    const asked = $.ui.ask(question, {
1165      header: 'dev-hooks',
1166      options: ['Allow', 'Deny'],
1167    })
1168    let answer: string
1169    try {
1170      const never = new Promise<never>(() => {})
1171      // A timer that can't run means no timeout, never a decision.
1172      const timedOut = seconds > 0 ? $.clock.sleep(seconds * 1000).then(() => undefined, () => never) : never
1173      const first = await Promise.race([asked, timedOut])
1174      if (first === undefined) {
1175        asked.then(
1176          answer => lateGuardAnswer($, e.command, answer),
1177          () => undefined,
1178        )
1179        const reason = guardTimeoutReason(decided.ask, seconds)
1180        const notes = (await $.state.get(GUARD_TIMED_OUT)).value ?? {}
1181        const kept = Object.entries(notes).slice(-(TIMED_OUT_KEPT - 1))
1182        await $.state.set(GUARD_TIMED_OUT, { ...Object.fromEntries(kept), [question]: timedOutNote(e.command, seconds, reason) })
1183        return { deny: reason }
1184      }
1185      answer = first
1186    } catch {
1187      // Dismissed: refuse, since handing the question back would let auto mode answer
1188      // it. With no one to ask at all (claude -p) the guard's question stands as it was.
1189      return isInteractive
1190        ? { deny: 'The dev-hooks guard dialog was dismissed, so this command did not run.' }
1191        : decided
1192    } finally {
1193      await setAsking($, false)
1194    }
1195    if (answer === 'Allow') {
1196      const { ask: _withdrawn, ...rest } = decided
1197      return rest
1198    }
1199    return { deny: `The person declined this command in the dev-hooks guard dialog (answer: ${answer}).` }
1200  })
hooks/ci-watch.ts 210 lines
1// CI watch: the pure half. register.tsx detects a push, resolves what was pushed and
2// polls GitHub with these; nothing here touches `$`, so tests import it directly.
3
4// ci-watch-reminder.sh's rule, kept line-local: `git` (env-prefixed or flagged) walking
5// tokens to a `push` subcommand. `git push`, `git -C dir push`, `… && git push`; not
6// `git config …pushurl`, `git switch`, `git pushall`.
7const GIT_PUSH = /(^|[^A-Za-z0-9_])git([ \t]+\S+)*[ \t]+push([^A-Za-z0-9_]|$)/m
8
9export const isGitPush = (command: string): boolean => GIT_PUSH.test(command)
10
11// A dry run prints the same ref lines but triggers no run, so a watch would only
12// find the last real push's run.
13export const isDryRun = (command: string): boolean =>
14  /(^|[^A-Za-z0-9_])git([ \t]+\S+)*[ \t]+push([ \t]+[^\s;&|]+)*[ \t]+(--dry-run|-n)([ \t;&|]|$)/m.test(command)
15
16// A quiet push prints no ref lines, so it is the one push watched without them.
17export const isQuietPush = (command: string): boolean =>
18  /(^|[^A-Za-z0-9_])git([ \t]+\S+)*[ \t]+push([ \t]+[^\s;&|]+)*[ \t]+(-q|--quiet)([ \t;&|]|$)/m.test(command)
19
20const unquote = (s: string) => s.replace(/^(['"])(.*)\1$/, '$2')
21
22const resolveDir = (dir: string, cwd: string) => {
23  const d = unquote(dir)
24  return d.startsWith('/') ? d : `${cwd.replace(/\/$/, '')}/${d}`
25}
26
27// The directory a git subcommand ran in: `git -C <dir> <sub>`, a `cd <dir> &&` before it,
28// or cwd.
29export const gitDir = (command: string, cwd: string, sub: string): string => {
30  const flag = new RegExp(
31    String.raw`(^|[^A-Za-z0-9_])git[ \t]+(?:\S+[ \t]+)*?-C[ \t]+("[^"]*"|'[^']*'|\S+)(?:[ \t]+\S+)*?[ \t]+${sub}`,
32    'm',
33  ).exec(command)
34  if (flag?.[2]) return resolveDir(flag[2], cwd)
35  const cd = new RegExp(
36    String.raw`(^|[;&|][ \t]*)cd[ \t]+("[^"]*"|'[^']*'|\S+)[ \t]*(&&|;)[^\n]*git([ \t]+\S+)*[ \t]+${sub}`,
37    'm',
38  ).exec(command)
39  if (cd?.[2]) return resolveDir(cd[2], cwd)
40  return cwd
41}
42
43export const pushDir = (command: string, cwd: string): string => gitDir(command, cwd, 'push')
44
45// Options of `git push` that take the next word as their value.
46const VALUE_OPTIONS = new Set(['-o', '--push-option', '--receive-pack', '--exec'])
47
48// The words after each `push` subcommand, up to the end of that shell command.
49const PUSH_ARGS = /(?:^|[^A-Za-z0-9_])git(?:[ \t]+\S+)*?[ \t]+push(?=$|[\s;&|()])((?:[ \t]+[^\s;&|()]+)*)/gm
50
51// The repository each `git push` in the command names (its first word that is not an
52// option or a redirect), or null for a bare push, which goes to the branch's push remote.
53export const pushRepositories = (command: string): (string | null)[] => {
54  const repos = [...command.matchAll(PUSH_ARGS)].map(m => {
55    const words = (m[1] ?? '').split(/[ \t]+/).filter(w => w && !/^\d*[<>]/.test(w)).map(unquote)
56    for (let i = 0; i < words.length; i++) {
57      const word = words[i] ?? ''
58      if (word === '--') return words[i + 1] ?? null
59      if (VALUE_OPTIONS.has(word)) i++
60      else if (!word.startsWith('-')) return word
61    }
62    return null
63  })
64  return repos.length > 0 ? repos : [null]
65}
66
67export type PushedRef = { src: string; dst: string; sha?: string }
68// One per `To` line. Refs printed before any `To` line (cut off, as by `| tail -1`)
69// come without a remote.
70export type PushSection = { remote?: string; refs: PushedRef[] }
71
72// git push's human output (stderr, which the Bash tool's result carries):
73//   To github.com:owner/repo.git
74//      762caa3..abc1234  main -> main
75//    + 1111111...2222222 main -> main (forced update)
76//    * [new branch]      feat -> feat
77// A deletion (` - [deleted]`) and a rejection (` ! [rejected]`) start no run.
78export const parsePushOutput = (text: string): PushSection[] => {
79  const sections: PushSection[] = []
80  let section: PushSection | undefined
81  const add = (ref: PushedRef) => {
82    if (!section) sections.push((section = { refs: [] }))
83    section.refs.push(ref)
84  }
85  for (const line of text.split('\n')) {
86    const to = /^To (\S+)/.exec(line)
87    if (to?.[1]) {
88      sections.push((section = { remote: to[1], refs: [] }))
89      continue
90    }
91    const updated = /^\s*[+ ]?\s*[0-9a-f]{7,40}\.\.\.?([0-9a-f]{7,40})\s+(\S+)\s+->\s+(\S+)/.exec(line)
92    if (updated?.[1] && updated[2] && updated[3]) {
93      add({ sha: updated[1], src: updated[2], dst: updated[3] })
94      continue
95    }
96    const created = /^\s*\*\s+\[new (?:branch|tag|reference)\]\s+(\S+)\s+->\s+(\S+)/.exec(line)
97    if (created?.[1] && created[2]) add({ src: created[1], dst: created[2] })
98  }
99  return sections
100}
101
102// owner/repo of a GitHub remote URL in any spelling git accepts (scp-like, ssh://,
103// https:// with or without credentials); null for any other host.
104export const githubRepo = (url: string): string | null => {
105  const m = /(?:^|[@/])github\.com[:/]+([^/\s:]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(url.trim())
106  return m?.[1] && m[2] ? `${m[1]}/${m[2]}` : null
107}
108
109export type Run = {
110  databaseId: number
111  workflowName: string
112  status: string
113  conclusion: string
114  headSha: string
115  url: string
116  event: string
117}
118
119export const RUN_FIELDS = 'databaseId,workflowName,status,conclusion,headSha,url,event'
120
121export const parseRuns = (stdout: string): Run[] => {
122  try {
123    const rows = JSON.parse(stdout) as unknown
124    return Array.isArray(rows) ? (rows as Run[]) : []
125  } catch {
126    return []
127  }
128}
129
130export type Verdict = 'none' | 'pending' | 'success' | 'failure' | 'cancelled'
131
132const FAILED = new Set(['failure', 'timed_out', 'startup_failure', 'action_required'])
133
134// Runs are selected by head sha, never by recency: the newest run in the list can
135// belong to an older push still running.
136export const ciVerdict = (runs: Run[], sha: string): { verdict: Verdict; runs: Run[] } => {
137  const mine = runs.filter(r => r.headSha === sha)
138  if (mine.length === 0) return { verdict: 'none', runs: mine }
139  if (mine.some(r => r.status !== 'completed')) return { verdict: 'pending', runs: mine }
140  if (mine.some(r => FAILED.has(r.conclusion))) return { verdict: 'failure', runs: mine }
141  if (mine.some(r => r.conclusion === 'cancelled')) return { verdict: 'cancelled', runs: mine }
142  return { verdict: 'success', runs: mine }
143}
144
145export type Watch = { repo: string; sha: string; done: number; total: number }
146
147const short = (sha: string) => sha.slice(0, 7)
148const name = (repo: string) => repo.slice(repo.indexOf('/') + 1)
149
150export const ciStatusLine = (watches: Watch[]): string | undefined => {
151  if (watches.length === 0) return undefined
152  const parts = watches.map(w =>
153    w.total === 0
154      ? `${name(w.repo)}@${short(w.sha)} waiting for its run`
155      : `${name(w.repo)}@${short(w.sha)} ${w.done}/${w.total} runs done`,
156  )
157  return `CI: ${parts.join(' · ')}`
158}
159
160const runLine = (r: Run) => `- ${r.workflowName}: ${r.conclusion || r.status} (${r.event}) ${r.url}`
161
162export const ciToast = (repo: string, sha: string, verdict: Verdict, runs: Run[]): string => {
163  const where = `${name(repo)}@${short(sha)}`
164  const bad = runs.filter(r => FAILED.has(r.conclusion)).map(r => r.workflowName)
165  switch (verdict) {
166    case 'success':
167      return `✓ CI passed · ${where}`
168    case 'failure':
169      return `✗ CI failed · ${where}: ${bad.join(', ')}`
170    case 'cancelled':
171      return `◌ CI cancelled · ${where}`
172    case 'none':
173      return `? No CI run appeared · ${where}`
174    default:
175      return `… CI still running · ${where}`
176  }
177}
178
179// What the model reads. A failure arrives as a prompt of its own, so it says what to do.
180export const ciNote = (repo: string, sha: string, verdict: Verdict, runs: Run[], error?: string): string => {
181  const head = `[dev-hooks CI watch] ${repo}@${short(sha)}`
182  const lines = runs.map(runLine)
183  switch (verdict) {
184    case 'success':
185      return [`${head}: CI passed.`, ...lines].join('\n')
186    case 'failure': {
187      const failed = runs.find(r => FAILED.has(r.conclusion))
188      return [
189        `${head}: CI FAILED on the commit you pushed.`,
190        ...lines,
191        `Find the cause (\`gh run view ${failed?.databaseId ?? '<id>'} --repo ${repo} --log-failed\`), fix it, and push the fix.`,
192      ].join('\n')
193    }
194    case 'cancelled':
195      return [`${head}: CI was cancelled (often a newer push superseded it).`, ...lines].join('\n')
196    case 'none':
197      return error
198        ? `${head}: couldn't read its GitHub Actions runs (${error}). Watch it yourself: \`gh run list --repo ${repo} --commit ${sha}\`.`
199        : `${head}: no GitHub Actions run appeared for this commit; its workflows may not trigger on this ref. Check \`gh run list --repo ${repo}\` if you expected one.`
200    default:
201      return [`${head}: CI is still running; the watch gave up waiting.`, ...lines].join('\n')
202  }
203}
204
205// Read with the push's own tool result, so Claude doesn't start a watch of its own.
206export const watchingNote = (targets: { repo: string; sha: string }[]): string =>
207  `[dev-hooks CI watch] Watching the GitHub Actions run(s) for ${targets
208    .map(t => `${t.repo}@${short(t.sha)}`)
209    .join(', ')} in the background. Don't run \`gh run watch\` or poll for it: a failure comes back to you as a new message, and a pass is noted in the conversation.`
210
hooks/nudge-outcomes.ts 251 lines
1// Stop-nudge outcomes: did Claude act on a Stop hook's reason? Pure functions only —
2// register.tsx owns every `$` call and passes the facts in.
3//
4// A nudge fires when the Stop orchestration returns a hook's reason, and is resolved at
5// the next Stop (the forced continuation the block caused, normally) or at session end,
6// from what the session facts show happened after it fired.
7import type { Facts, Nudge, NudgeCounts, NudgeOutcome, NudgeRecord } from '../types'
8
9import { endReportMissing } from './status-pane'
10
11// The hook a Stop command runs, by its script name: `bash ".../review-reminder.sh"` →
12// `review-reminder`. Names hooks without relying on each reason's tag.
13export const hookName = (command: string): string =>
14  command.match(/([\w.-]+)\.sh\b/g)?.at(-1)?.replace(/\.sh$/, '') ?? command
15
16// The files a reason lists, one per "  path" or "  path:line: text" line.
17const reasonFiles = (reason: string): string[] =>
18  reason
19    .split('\n')
20    .filter(l => /^ {2}\S/.test(l) && !l.startsWith('  ... and'))
21    .map(l => l.trim().replace(/:\d+:.*$/, ''))
22
23const LISTS_FILES = new Set(['debug-leftover-reminder', 'missing-test-reminder'])
24
25export const newNudge = (hook: string, reason: string, at: number): Nudge => {
26  const files = LISTS_FILES.has(hook) ? reasonFiles(reason) : []
27  return {
28    hook,
29    at,
30    summary: (reason.split('\n')[0] ?? '').slice(0, 120),
31    ...(files.length > 0 ? { files } : {}),
32  }
33}
34
35// Mirrors review-reminder.sh's reminder_transcript_invoked needles (tests/test_nudge_parity.py).
36export const REVIEW_NEEDLES = ['code-review', 'code_review', 'requesting-code-review', 'code-reviewer']
37// Mirrors hook_helpers.MEMORY_DIR_RE.
38export const MEMORY_DIR_RE = /\/\.claude\/(?:projects\/[^/]+\/)?memory\//
39
40// Mirrors hook_helpers._AGENT_DOER_RE and _agent_job_re: "Review task 8" is a review,
41// "Add product review form" is not.
42const AGENT_DOER_RE = /^\s*(?:fix|fixes|implement|build|add|create|write|update|refactor|address|apply|predict|simulate)\b/i
43const agentJobRe = (w: string) =>
44  new RegExp(
45    `^\\s*(?:re-?)?${w}(?:ing)?\\b` +
46      `|\\bre-?${w}\\b` +
47      `|^\\s*(?:code|final|whole-branch|final whole-branch)[- ]${w}\\b(?!\\s+fix)` +
48      `|\\bwhole-branch ${w}\\b` +
49      `|\\b${w}(?:ing)?(?=\\s*(?:$|[:,;(—–-]|\\s+(?:of|for|round|pass|loop)\\b))`,
50    'i',
51  )
52
53// A skill or subagent run after `at` that names one of `names`, or a subagent described
54// as doing `job`; its description for the evidence, or undefined.
55const invokedSince = (f: Facts, at: number, names: string[], job?: string): string | undefined => {
56  const named = (s: string) => names.some(n => s.includes(n))
57  const skill = f.skills.find(s => s.at > at && named(s.skill))
58  if (skill) return `skill ${skill.skill}`
59  const jobRe = job ? agentJobRe(job) : undefined
60  const agent = f.agents.find(
61    a =>
62      a.at > at &&
63      (named(a.subagentType) || (jobRe !== undefined && !AGENT_DOER_RE.test(a.description) && jobRe.test(a.description))),
64  )
65  return agent ? `agent ${agent.subagentType}: ${agent.description}`.slice(0, 100) : undefined
66}
67
68const editedSince = (f: Facts, at: number, match: (file: string) => boolean): string | undefined =>
69  Object.entries(f.lastEdit ?? {}).find(([file, t]) => t > at && match(file))?.[0]
70
71const base = (path: string) => path.slice(path.lastIndexOf('/') + 1)
72const stem = (path: string) => base(path).replace(/\.[^.]*$/, '')
73const isTestPath = (path: string) =>
74  /(^|\/)(tests?|spec|__tests__)\//.test(path) || /(^test_|_test\.|\.test\.|_spec\.|\.spec\.)/.test(base(path))
75
76export type NudgeEvidence = {
77  facts: Facts
78  // Hooks whose reason the resolving Stop returned again.
79  refired: string[]
80  // Hooks that stood down at their block cap at the resolving Stop, failure still standing.
81  capped?: string[]
82  // The resolving Stop's last assistant message; undefined when resolved at session end.
83  lastMessage?: string
84  // false when resolved at session end or a later sweep: no Stop ran after the nudge.
85  atStop: boolean
86}
87
88type Resolution = { outcome: NudgeOutcome; evidence: string }
89
90// What counts as acting on each hook's reason. A hook without a remedy the facts can show
91// is "unknown", never guessed. The facts see Edit/Write only, so a remedy done through
92// Bash (a test file made by a generator, a memory file written with cat) reads as ignored.
93export const resolveNudge = (n: Nudge, ev: NudgeEvidence): Resolution => {
94  const acted = (evidence: string): Resolution => ({ outcome: 'acted', evidence })
95  const missed = (what: string): Resolution =>
96    ev.atStop
97      ? { outcome: 'ignored', evidence: `no ${what} before the next Stop` }
98      : { outcome: 'unknown', evidence: `session ended before the next Stop; no ${what}` }
99
100  switch (n.hook) {
101    case 'review-reminder': {
102      const hit = invokedSince(ev.facts, n.at, REVIEW_NEEDLES, 'review')
103      return hit ? acted(hit) : missed('review skill or review agent')
104    }
105    case 'compress-comments-reminder': {
106      const hit = invokedSince(ev.facts, n.at, ['compress-comments'])
107      return hit ? acted(hit) : missed('compress-comments run')
108    }
109    case 'memory-reminder': {
110      const file = editedSince(ev.facts, n.at, f => MEMORY_DIR_RE.test(f))
111      if (file) return acted(`wrote memory ${base(file)}`)
112      // The reason's own escape hatch: "Say 'nothing worth saving' in one line and stop."
113      if (/nothing worth saving/i.test(ev.lastMessage ?? '')) {
114        return { outcome: 'declined', evidence: "said 'nothing worth saving'" }
115      }
116      return missed('memory write')
117    }
118    case 'missing-test-reminder': {
119      const stems = (n.files ?? []).map(stem)
120      const file = editedSince(ev.facts, n.at, f => isTestPath(f) && stems.some(s => base(f).includes(s)))
121      return file ? acted(`wrote test ${base(file)}`) : missed('test written for a listed file')
122    }
123    case 'debug-leftover-reminder': {
124      const files = n.files ?? []
125      const file = editedSince(ev.facts, n.at, f => files.some(l => f === l || f.endsWith(`/${l}`)))
126      return file ? acted(`edited ${base(file)}`) : missed('edit to a listed file')
127    }
128    case 'verify-work': {
129      // Only a failure can be re-checked: verify-work runs again at the continuation's
130      // Stop and blocks again while the failure stands.
131      if (!n.summary.startsWith('Verification failed')) return { outcome: 'unknown', evidence: 'advisory, nothing to re-check' }
132      if (!ev.atStop) return { outcome: 'unknown', evidence: 'session ended before verify-work ran again' }
133      if (ev.refired.includes('verify-work')) return { outcome: 'ignored', evidence: 'still failing at the next Stop' }
134      if (ev.capped?.includes('verify-work'))
135        return { outcome: 'ignored', evidence: 'still failing at the next Stop; block cap reached' }
136      return acted('passed at the next Stop')
137    }
138    case 'end-report-reminder': {
139      if (!ev.atStop || ev.lastMessage === undefined) return missed('reply to read')
140      const lacking = endReportMissing(ev.lastMessage)
141      return lacking.length === 0
142        ? acted('the next reply carried Changed and Your move')
143        : { outcome: 'ignored', evidence: `the next reply still has no ${lacking.join(' or ')} line` }
144    }
145    default:
146      return { outcome: 'unknown', evidence: 'no remedy the session facts can show' }
147  }
148}
149
150// Resolves every nudge fired before `now` that is still pending.
151export const resolvePending = (f: Facts, ev: NudgeEvidence, now: number): { facts: Facts; resolved: Nudge[] } => {
152  const resolved: Nudge[] = []
153  const nudges = (f.nudges ?? []).map(n => {
154    if (n.outcome !== undefined || n.at >= now) return n
155    const r = { ...n, ...resolveNudge(n, ev), resolvedAt: now }
156    resolved.push(r)
157    return r
158  })
159  return { facts: resolved.length > 0 ? { ...f, nudges } : f, resolved }
160}
161
162// A throwaway session whose nudges would skew the weekly review: the mirror of
163// reminder_is_probe_session in reminder-common.sh, pinned by test_nudge_parity.py.
164export const PROBE_ON = ['1', 'true', 'yes', 'on']
165export const PROBE_CWDS = ['/tmp/claude-', '/private/tmp/claude-', '~/.cache/']
166export const isProbeSession = (p: { session: string; cwd: string; home: string; probe?: string }): boolean =>
167  !/^[0-9a-f]{8}-[0-9a-f]{4}-/.test(p.session) ||
168  PROBE_ON.includes(p.probe ?? '') ||
169  PROBE_CWDS.some(prefix => p.cwd.startsWith(prefix.replace(/^~/, p.home)))
170
171export const NUDGE_LOG_KEY = 'nudgeOutcomes'
172const LOG_DAYS = 90
173const LOG_MAX = 3000
174const DAY_MS = 86_400_000
175
176export const toRecord = (session: string, n: Nudge): NudgeRecord => ({
177  hook: n.hook,
178  session,
179  at: n.at,
180  resolvedAt: n.resolvedAt ?? n.at,
181  outcome: n.outcome ?? 'unknown',
182  evidence: n.evidence ?? '',
183})
184
185// Union by (session, hook, at), so re-adding a record is harmless; keeps the last
186// LOG_DAYS days and at most LOG_MAX records, which bounds the store key.
187export const mergeNudgeLog = (log: NudgeRecord[] | undefined, add: NudgeRecord[], now: number): NudgeRecord[] => {
188  const byId = new Map<string, NudgeRecord>()
189  for (const r of [...(log ?? []), ...add]) byId.set(`${r.session}|${r.hook}|${r.at}`, r)
190  return [...byId.values()]
191    .filter(r => r.at >= now - LOG_DAYS * DAY_MS)
192    .sort((a, b) => a.at - b.at)
193    .slice(-LOG_MAX)
194}
195
196export type NudgeSummary = { hook: string } & NudgeCounts
197
198// Per hook, the outcomes of nudges fired since `since`, most-fired first.
199export const summarizeNudges = (log: NudgeRecord[], since: number): NudgeSummary[] => {
200  const byHook = new Map<string, NudgeSummary>()
201  for (const r of log) {
202    if (r.at < since) continue
203    const s = byHook.get(r.hook) ?? { hook: r.hook, fired: 0, acted: 0, ignored: 0, declined: 0, unknown: 0 }
204    s.fired++
205    s[r.outcome]++
206    byHook.set(r.hook, s)
207  }
208  return [...byHook.values()].sort((a, b) => b.fired - a.fired || a.hook.localeCompare(b.hook))
209}
210
211// Acted-on rate over the nudges whose outcome is known; null when none is.
212export const actedRate = (s: NudgeCounts): number | null => {
213  const known = s.acted + s.ignored + s.declined
214  return known === 0 ? null : s.acted / known
215}
216
217export const formatNudgeStats = (log: NudgeRecord[], now: number, days = 7): string => {
218  const rows = summarizeNudges(log, now - days * DAY_MS)
219  if (rows.length === 0) return `Stop nudges · none resolved in the last ${days} days`
220  const width = Math.max(4, ...rows.map(r => r.hook.length))
221  const pct = (s: NudgeCounts) => {
222    const r = actedRate(s)
223    return r === null ? '   -' : `${Math.round(r * 100)}%`.padStart(4)
224  }
225  const cell = (n: number | string) => String(n).padStart(8)
226  return [
227    `Stop nudges · last ${days} days · acted = acted / (acted + ignored + declined)`,
228    '',
229    `${'hook'.padEnd(width)} ${cell('fired')} ${cell('acted')} ${cell('ignored')} ${cell('declined')} ${cell('unknown')}  rate`,
230    ...rows.map(
231      r => `${r.hook.padEnd(width)} ${cell(r.fired)} ${cell(r.acted)} ${cell(r.ignored)} ${cell(r.declined)} ${cell(r.unknown)}  ${pct(r)}`,
232    ),
233    '',
234    '/session-facts nudges 30 widens the window; the weekly review reads ~/.claude/automation-review/stop-nudges.json.',
235  ].join('\n')
236}
237
238// The export the weekly automation review reads.
239export const nudgeExport = (log: NudgeRecord[], now: number) => ({
240  generatedAt: new Date(now).toISOString(),
241  retentionDays: LOG_DAYS,
242  last7Days: summarizeNudges(log, now - 7 * DAY_MS),
243  last30Days: summarizeNudges(log, now - 30 * DAY_MS),
244  records: log,
245})
246
247// A --plugin-dir dev copy has a store of its own; exporting it would replace the installed
248// plugin's stop-nudges.json until the next real nudge, so it writes beside it instead.
249export const nudgeExportFile = (pluginRoot: string): string =>
250  pluginRoot.includes('/.claude/plugins/') ? 'stop-nudges.json' : 'stop-nudges.inline.json'
251
hooks/status-pane.ts 373 lines
1// The session-status pane's pure half: it reads end reports, briefs and git output, and
2// derives what the pane shows. register.tsx records the session and draws the result.
3import type { BackgroundItem, Brief, EndReport, StatusPaneState, TurnRecord } from '../types'
4
5export type { BackgroundItem, Brief, EndReport, RepoCommits, StatusPaneState, TurnEnd, TurnRecord } from '../types'
6
7
8// hook_helpers._END_REPORT_LINES' patterns, pinned by test_status_pane_parity.py.
9export const END_REPORT_LABELS = {
10  changed: String.raw`(?:what\s+(?:i\s+)?)?changed`,
11  yourMove: String.raw`your\s+move`,
12}
13
14const REPORT_LABELS = {
15  status: 'status',
16  doneWhen: String.raw`done\s+when`,
17  changed: END_REPORT_LABELS.changed,
18  assumed: 'assumed',
19  notChecked: String.raw`not\s+checked`,
20  yourMove: END_REPORT_LABELS.yourMove,
21}
22
23const BRIEF_LABELS = {
24  doing: 'doing',
25  notDoing: String.raw`not\s+doing`,
26  depth: 'depth',
27  doneWhen: String.raw`done\s+when`,
28  needFromYou: String.raw`need\s+from\s+you`,
29  assuming: 'assuming',
30}
31
32const TAIL = String.raw`(?:\s+this\s+(?:turn|session))?`
33const BULLET = /^\s*(?:[-*+]|\d+[.)])\s+(.*)$/
34const NOTHING = /^(?:nothing(?: yet)?|none)\.?$/i
35
36// Emphasis markers around words go; an underscore inside a name (snake_case, a_b.py) stays.
37const unmark = (text: string) =>
38  text
39    .replace(/\*\*|__/g, '')
40    .replace(/(^|\s)[*_](?=\S)/g, '$1')
41    .replace(/(\S)[*_](?=\s|[.,;:!?)]|$)/g, '$1')
42    .trim()
43
44type Labels = Record<string, string>
45type Sections<L extends Labels> = { [K in keyof L]?: string[] }
46
47// A label line as hook_helpers.end_report_missing reads one: "**Changed:**", "Your move:",
48// "What I changed this session:", or a heading holding only the label.
49const parseSections = <L extends Labels>(text: string, labels: L): Sections<L> => {
50  const matchers = Object.entries(labels).map(([key, word]) => ({
51    key: key as keyof L,
52    inline: new RegExp(String.raw`^[\s>*_|-]*(?:${word})${TAIL}[*_\s]*:(.*)$`, 'i'),
53    heading: new RegExp(String.raw`^\s*#+\s*(?:${word})${TAIL}\s*$`, 'i'),
54  }))
55  const found: Sections<L> = {}
56  let current: keyof L | null = null
57  let gap = false
58  let fenced = false
59  for (const line of text.split('\n')) {
60    // A fenced block holds a template or code, and a quote holds someone else's words.
61    if (/^\s*```/.test(line)) fenced = !fenced
62    if (fenced || /^\s*```/.test(line)) continue
63    const label = /^\s*>/.test(line) ? undefined : matchers.flatMap(m => {
64      const inline = m.inline.exec(line)
65      if (inline) return [{ key: m.key, rest: unmark(inline[1] ?? '') }]
66      return m.heading.test(line) ? [{ key: m.key, rest: '' }] : []
67    })[0]
68    if (label) {
69      current = label.key
70      found[current] = label.rest ? [label.rest] : []
71      gap = false
72      continue
73    }
74    if (current === null) continue
75    const items = found[current] ?? []
76    if (!line.trim()) {
77      gap = true
78      continue
79    }
80    const bullet = BULLET.exec(line)
81    if (bullet) items.push(unmark(bullet[1] ?? ''))
82    else if (gap && items.length > 0) current = null
83    else if (items.length > 0) items[items.length - 1] = `${items[items.length - 1]} ${line.trim()}`
84    else items.push(unmark(line))
85    gap = false
86  }
87  return found
88}
89
90const list = (items: string[] | undefined) => (items ?? []).filter(item => item && !NOTHING.test(item))
91
92export const parseEndReport = (text: string): EndReport | null => {
93  const s = parseSections(text, REPORT_LABELS)
94  if (!s.status && !s.changed && !s.yourMove) return null
95  const status = s.status?.join(' ')
96  return {
97    ...(status ? { status } : {}),
98    doneWhen: list(s.doneWhen),
99    changed: list(s.changed),
100    notChecked: list(s.notChecked),
101    ...(s.yourMove ? { yourMove: list(s.yourMove) } : {}),
102  }
103}
104
105// end-report-reminder's check: the Changed / Your move lines `text` lacks.
106export const endReportMissing = (text: string): string[] => {
107  const s = parseSections(text, REPORT_LABELS)
108  return [...(s.changed ? [] : ['Changed']), ...(s.yourMove ? [] : ['Your move'])]
109}
110
111export const findBrief = (texts: string[]): Brief | null => {
112  for (const text of [...texts].reverse()) {
113    const s = parseSections(text, BRIEF_LABELS)
114    if (s.doing && s.doneWhen) return { doing: s.doing.join(' '), doneWhen: list(s.doneWhen) }
115  }
116  return null
117}
118
119const COMMIT = /^\[([^\s\]]+)(?: \([^)]*\))? ([0-9a-f]{7,40})\]/gm
120
121export const parseCommits = (text: string): { branch: string; sha: string }[] =>
122  [...text.matchAll(COMMIT)].map(m => ({ branch: m[1] ?? '', sha: m[2] ?? '' }))
123
124export const endsOnQuestion = (text: string): boolean => {
125  const last = text.trim().split('\n').at(-1) ?? ''
126  return last.replace(/[*_`>\s]+$/, '').endsWith('?')
127}
128
129// ── The view ─────────────────────────────────────────────────────────────────────────
130
131export const EMPTY_PANE_STATE = (now: number): StatusPaneState => ({
132  turns: [],
133  turnsTotal: 0,
134  brief: null,
135  repos: [],
136  background: [],
137  startedAt: now,
138})
139
140export type PaneStateName =
141  | 'stopped'
142  | 'waiting'
143  | 'no-report'
144  | 'working'
145  | 'running'
146  | 'done'
147  | 'replied'
148  | 'interrupted'
149  | 'no-turns'
150export type PaneTone = 'red' | 'yellow' | 'blue' | 'green' | 'dim'
151export type PaneView = {
152  state: PaneStateName
153  tone: PaneTone
154  label: string
155  since: number
156  yourMove: string[]
157  doing?: string
158  doneWhen: { text: string; met: boolean | null }[]
159  doneWhenNote?: string
160  running: string[]
161  changed: string[]
162  repoLines: string[]
163  notChecked: string[]
164  lastSaid?: string
165  canSummarize: boolean
166  summarizing: boolean
167  summaryError?: string
168  turnCount: number
169}
170
171// Highest first: the pane shows the worst state any turn since the last typed prompt is in.
172const ORDER: PaneStateName[] = [
173  'stopped',
174  'waiting',
175  'no-report',
176  'working',
177  'running',
178  'done',
179  'replied',
180  'interrupted',
181  'no-turns',
182]
183const TONE: Record<PaneStateName, PaneTone> = {
184  stopped: 'red',
185  waiting: 'yellow',
186  'no-report': 'yellow',
187  working: 'blue',
188  running: 'blue',
189  done: 'green',
190  replied: 'dim',
191  interrupted: 'dim',
192  'no-turns': 'dim',
193}
194const LABEL: Record<PaneStateName, string> = {
195  stopped: 'Stopped',
196  waiting: 'Waiting on you',
197  'no-report': 'Turn ended, no end report',
198  working: 'Working',
199  running: 'Running',
200  done: 'Done',
201  replied: 'Replied',
202  interrupted: 'Interrupted',
203  'no-turns': 'No turns yet',
204}
205const CAPS = { yourMove: 5, changed: 4, running: 4, notChecked: 2 }
206const QUESTION_MOVE = 'answer the question in the chat'
207const NOT_TYPED = /^\s*(?:<task-notification>|<agent-message|<system-reminder>|\[dev-hooks CI watch\])/
208
209export const isTypedPrompt = (text: string): boolean => text.trim() !== '' && !NOT_TYPED.test(text)
210
211// The person's own message: Enter at the prompt, the Remote Control bridge, or an SDK host's
212// turn (how VS Code and claude -p send what was typed). The text is only the fallback, for a
213// turn whose prompt.submit never arrived.
214const TYPED_ORIGINS = new Set(['composer', 'bridge', 'sdk'])
215
216export const typedFrom = (origin: string | undefined, text: string): boolean =>
217  origin !== undefined ? TYPED_ORIGINS.has(origin) : isTypedPrompt(text)
218
219const LAST_SAID_CAP = 300
220
221export const answerFacts = (answer: string): { lastSaid?: string; asksQuestion: boolean } => {
222  const first = answer.trim().split('\n')[0]?.trim() ?? ''
223  return { ...(first ? { lastSaid: first.slice(0, LAST_SAID_CAP) } : {}), asksQuestion: endsOnQuestion(answer) }
224}
225
226// end-report-reminder's rule for a turn that owes a report.
227export const isWorkTurn = (t: TurnRecord): boolean => t.edits > 0 || t.calls >= 10
228
229// The last `cap` turns, and every turn from the last typed one on (so an ask survives any
230// number of notification turns), up to `hardCap`.
231export const keepTurns = (turns: TurnRecord[], cap = 20, hardCap = 200): TurnRecord[] => {
232  const lastTyped = turns.map(t => t.typed).lastIndexOf(true)
233  const from = Math.min(Math.max(turns.length - cap, 0), lastTyped < 0 ? turns.length : lastTyped)
234  return turns.slice(Math.max(from, turns.length - hardCap))
235}
236
237export const capped = (items: string[], cap: number): string[] =>
238  items.length <= cap ? items : [...items.slice(0, cap - 1), `+${items.length - cap + 1} more`]
239
240const age = (ms: number): string => {
241  const minutes = Math.floor(ms / 60_000)
242  if (minutes < 1) return 'just now'
243  if (minutes < 60) return `${minutes} min`
244  return `${Math.floor(minutes / 60)} h ${minutes % 60} min`
245}
246
247export const clockTime = (at: number, tz?: string): string =>
248  new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: tz }).format(at)
249
250export const sinceLabel = (at: number, now: number, tz?: string): string => `since ${clockTime(at, tz)} (${age(now - at)})`
251
252const reportOf = (t: TurnRecord) => t.summary ?? t.report ?? null
253const isBlocked = (r: EndReport | null) => /^blocked/i.test(r?.status ?? '')
254// A report whose Your move line was there, even as "nothing".
255const hasMove = (r: EndReport | null): r is EndReport & { yourMove: string[] } => r?.yourMove !== undefined
256
257// null: a later turn's report covers this one, as when a Stop hook's continuation writes it.
258const classify = (t: TurnRecord, later: TurnRecord[]): PaneStateName | null => {
259  if (t.endedAt === undefined) return t.asking ? 'waiting' : 'working'
260  if (t.end === 'error' || t.end === 'refusal') return 'stopped'
261  if (t.end === 'aborted') return 'interrupted'
262  const r = reportOf(t)
263  if (isBlocked(r)) return 'waiting'
264  if (hasMove(r)) return r.yourMove.length > 0 || t.asksQuestion ? 'waiting' : 'done'
265  if (later.some(l => hasMove(reportOf(l)))) return null
266  if (t.asksQuestion) return 'waiting'
267  return isWorkTurn(t) ? 'no-report' : 'replied'
268}
269
270const movesOf = (t: TurnRecord, cls: PaneStateName | null): string[] => {
271  if (cls === null) return []
272  const r = reportOf(t)
273  const own = hasMove(r) ? r.yourMove : []
274  if (own.length > 0) return own
275  if (t.asking || (t.asksQuestion && cls === 'waiting')) return [QUESTION_MOVE]
276  return isBlocked(r) && r?.status ? [r.status] : []
277}
278
279// The verdict word leads the item ("met: …") or follows its criterion ("tests green: met");
280// anything else ("partly met") ticks nothing.
281const SAYS_NOT_MET = /^(?:(?:not met|unmet|no)\b|✗)/i
282const SAYS_MET = /^(?:(?:met|done|yes)\b|✓)/i
283const leadingVerdict = (text: string): boolean | null =>
284  SAYS_NOT_MET.test(text) ? false : SAYS_MET.test(text) ? true : null
285const verdict = (item: string): boolean | null => {
286  const whole = leadingVerdict(item.trim())
287  const colon = item.indexOf(':')
288  return whole ?? (colon < 0 ? null : leadingVerdict(item.slice(colon + 1).trim()))
289}
290
291// The turns since the person last typed a prompt: what the pane reads.
292const windowOf = (s: StatusPaneState) => s.turns.slice(Math.max(s.turns.map(t => t.typed).lastIndexOf(true), 0))
293
294// The turn the Summarize button answers for: the latest that did work and left no report.
295export const noReportTurn = (s: StatusPaneState): TurnRecord | undefined => {
296  const window = windowOf(s)
297  return window.findLast((t, i) => classify(t, window.slice(i + 1)) === 'no-report')
298}
299
300// When the shown state began: an ask since the turn that made it, not the latest turn.
301const sinceOf = (
302  state: PaneStateName,
303  window: TurnRecord[],
304  perTurn: (PaneStateName | null)[],
305  background: BackgroundItem[],
306  startedAt: number,
307): number => {
308  if (state === 'running' && background.length > 0) return Math.min(...background.map(b => b.since))
309  const first = window.find((_t, i) => perTurn[i] === state)
310  return first ? (first.endedAt ?? first.startedAt) : (window.at(-1)?.endedAt ?? startedAt)
311}
312
313// summarizing: the turn a Summarize press is answering now (module memory, so a reload
314// mid-fork never leaves the button stuck).
315export const paneView = (
316  s: StatusPaneState,
317  extraRunning: BackgroundItem[],
318  now: number,
319  summarizing?: string,
320): PaneView => {
321  const window = windowOf(s)
322  const background = [...s.background, ...extraRunning]
323  const perTurn = window.map((t, i) => classify(t, window.slice(i + 1)))
324  const classes = perTurn.filter((c): c is PaneStateName => c !== null)
325  if (background.length > 0) classes.push('running')
326  const state = ORDER.find(name => classes.includes(name)) ?? 'no-turns'
327  const reports = window.map(reportOf).filter((r): r is EndReport => r !== null)
328  const latest = reports.at(-1)
329  const lastTurn = window.at(-1)
330  const open = window.find(t => t.endedAt === undefined)
331
332  const moves = window.flatMap((t, i) => movesOf(t, perTurn[i] ?? null))
333  const criteria = s.brief?.doneWhen ?? []
334  const verdicts = !open && latest && latest.doneWhen.length === criteria.length ? latest.doneWhen.map(verdict) : []
335  const ticked = verdicts.length > 0 && verdicts.every(v => v !== null)
336  const noReport = noReportTurn(s)
337
338  return {
339    state,
340    tone: TONE[state],
341    label:
342      state !== 'stopped'
343        ? LABEL[state]
344        : window.findLast((_t, i) => perTurn[i] === 'stopped')?.end === 'refusal'
345          ? 'Stopped: refused'
346          : 'Stopped: API error',
347    since: sinceOf(state, window, perTurn, background, s.startedAt),
348    yourMove: capped([...new Set(moves)], CAPS.yourMove),
349    ...(s.brief ? { doing: s.brief.doing } : {}),
350    doneWhen: criteria.map((text, i) => ({ text, met: ticked ? (verdicts[i] ?? null) : null })),
351    ...(!open && !ticked && latest && latest.doneWhen.length > 0 && criteria.length > 0
352      ? { doneWhenNote: latest.doneWhen.join('; ') }
353      : {}),
354    running: capped(
355      background.map(b => `${b.label} (${age(now - b.since)})`),
356      CAPS.running,
357    ),
358    changed: capped(latest?.changed ?? [], CAPS.changed),
359    repoLines: s.repos.map(
360      r =>
361        `${r.repo}: ${r.commits} commit${r.commits === 1 ? '' : 's'}, ${
362          (r.lastPushAt ?? 0) >= r.lastCommitAt ? 'pushed' : 'not pushed'
363        }`,
364    ),
365    notChecked: capped(latest?.notChecked ?? [], CAPS.notChecked),
366    ...(lastTurn?.lastSaid && !hasMove(reportOf(lastTurn)) ? { lastSaid: lastTurn.lastSaid } : {}),
367    canSummarize: noReport !== undefined && noReport.id !== summarizing,
368    summarizing: noReport !== undefined && noReport.id === summarizing,
369    ...(noReport?.summaryError ? { summaryError: noReport.summaryError } : {}),
370    turnCount: s.turnsTotal,
371  }
372}
373
types/index.d.ts 92 lines
1export type Segment = { name: string; tokens: number; color: string; kind: 'used' | 'free' | 'buffer' }
2export type Snapshot = { segments: Segment[]; totalTokens: number; maxTokens: number; percentage: number }
3
4// Session facts, kept in $.store under `facts:<session id>`.
5export type RepoEdits = { root: string | null; files: string[]; added: number; bySubagent: number }
6export type Facts = {
7  updatedAt: number
8  skills: { skill: string; at: number }[]
9  agents: { description: string; subagentType: string; at: number }[]
10  // root null: edited outside any git repo (scratchpad, memory dir, ~/.claude).
11  repos: RepoEdits[]
12  stops: { at: number; block: string | null }[]
13  // Per file, when an Edit/Write last touched it: the evidence window for Stop nudges.
14  lastEdit?: Record<string, number>
15  // Stop nudges this session: one per hook reason the Stop orchestration returned.
16  nudges?: Nudge[]
17}
18
19// Stop-nudge outcomes. A nudge is pending until a later Stop (or the session's end)
20// resolves it from what the session did after it fired.
21export type NudgeOutcome = 'acted' | 'ignored' | 'declined' | 'unknown'
22export type Nudge = {
23  hook: string
24  at: number
25  // The reason's first line, cut short.
26  summary: string
27  // Files the reason named (debug-leftover, missing-test).
28  files?: string[]
29  outcome?: NudgeOutcome
30  resolvedAt?: number
31  evidence?: string
32}
33// One resolved nudge, as kept across sessions in $.store under `nudgeOutcomes`.
34export type NudgeRecord = {
35  hook: string
36  session: string
37  at: number
38  resolvedAt: number
39  outcome: NudgeOutcome
40  evidence: string
41}
42export type NudgeCounts = { fired: number } & Record<NudgeOutcome, number>
43
44// The session-status pane's record of the session, kept in $.state under `statusPane`.
45// yourMove: undefined when the report has no Your move line, which is not the same as "nothing".
46export type EndReport = { status?: string; doneWhen: string[]; changed: string[]; notChecked: string[]; yourMove?: string[] }
47export type Brief = { doing: string; doneWhen: string[] }
48export type TurnEnd = 'answer' | 'aborted' | 'refusal' | 'error'
49export type TurnRecord = {
50  id: string
51  startedAt: number
52  // Started by a prompt the person typed: it opens the window of turns the pane reads.
53  typed: boolean
54  endedAt?: number
55  end?: TurnEnd
56  calls: number
57  edits: number
58  // What the pane keeps of the final message: its first line, and whether it ends on a question.
59  lastSaid?: string
60  asksQuestion?: boolean
61  // An open turn waiting on a question in the chat (AskUserQuestion, the guard dialog).
62  asking?: boolean
63  report?: EndReport | null
64  summary?: EndReport
65  summaryError?: string
66}
67export type RepoCommits = { repo: string; commits: number; lastCommitAt: number; lastPushAt?: number }
68// id: a background task's, so its age survives the next Stop's list.
69export type BackgroundItem = { label: string; since: number; id?: string }
70export type StatusPaneState = {
71  turns: TurnRecord[]
72  turnsTotal: number
73  brief: Brief | null
74  repos: RepoCommits[]
75  background: BackgroundItem[]
76  startedAt: number
77  // When the record last changed: the pane shows it, so a stale pane is visible.
78  updatedAt?: number
79}
80
81
82declare module 'claude-code' {
83  interface PluginState {
84    'dev-hooks': {
85      contextBarShown: boolean
86      contextBarSnapshot: Snapshot | null
87      guardTimedOut: Record<string, string>
88      statusPane: Shaped<StatusPaneState>
89    }
90  }
91}
92