SLOPSHOPPER

verification-ledger

Tracks local verification commands and GitHub Actions for the current commit

newpaneguardcommandtoastprocess
★ 2v0.1.0MITupdated 2026-10-15bradtraversy/claude-mods/verification-ledger
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · verification-ledger
│ ┃ Checks ✕ › fix the failing auth test and add an audit ╭─────────────────────╮ │ ┃ Verification Ledger [ Refresh ] │ verification-ledger │ │ ┃ ⏺ Read(src/auth.ts) │ Tests failed. │ │ ┃ feat/auth-refresh @ ⎿ Read 6 lines ╰─────────────────────╯ │ ┃ a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0 ⏺ Update(src/auth.ts) │ ┃ 2 changed · no upstream ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ Local checks ⎿ 3 pass, 1 fail │ ┃ FAIL Tests 08:53 AM │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ GitHub CI │ ┃ GitHub returned CI data that the ledger ✻ Worked for 42s · done 4:20 PM │ ┃ could not read. │ ┃ Updated 08:53 AM › /checks │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Checks
Verification Ledger [ Refresh ] feat/auth-refresh @ a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0 2 changed · no upstream Local checks FAIL Tests 08:53 AM GitHub CI GitHub returned CI data that the ledger could not read. Updated 08:53 AM
README

Claude Code Mods

A collection of personal Claude Code mods by Brad Traversy. These mods add useful session information, interface customizations, safety demonstrations, and verification tools to Claude Code.

Every mod is a small, independent Claude Code plugin written in TypeScript. Install only the ones you want, or run all eight together.

[!IMPORTANT] Mods run inside Claude Code with your user permissions. They can see session events, start processes, access files, and make network requests. Read the source before installing any mod, including these.

What is a mod?

A mod is a Claude Code plugin with JavaScript or TypeScript event handlers. Claude Code calls those handlers when something happens, such as:

  • A session starts
  • Claude calls a tool
  • A command is submitted
  • Part of the interface is rendered
  • Context usage changes

A handler can observe the event, change it, or handle it completely. That makes mods different from normal settings hooks. A mod can draw interface elements, replace existing tool rows, register slash commands, share state between handlers, and intercept a tool call before it runs.

These mods work in:

  • Claude Code in a terminal
  • Local sessions in the Code tab of the Claude Desktop app
  • SSH sessions in the Code tab when plugins are available on the remote host

Visual elements do not appear in the VS Code chat panel, claude -p, Agent SDK sessions, or cloud sessions. Plugins are not available in WSL sessions opened through the desktop app.

Requirements

  • Claude Code 2.1.287 or newer for terminal use
  • A desktop app version that includes Claude Code 2.1.286 or newer for the Code tab
  • Git, so Claude Code can clone this marketplace
  • GitHub CLI, authenticated with gh auth login, only if you want Verification Ledger to display remote GitHub Actions runs

Check your terminal version:

claude --version

In the desktop Code tab, enter /status and check the Claude Code version.

Quick start

1. Add the marketplace

Run this in your shell:

claude plugin marketplace add bradtraversy/claude-mods

You can also enter this in a Claude Code session:

/plugin marketplace add bradtraversy/claude-mods

2. Install the mods you want

Install one mod:

claude plugin install session-hud@traversy-mods

Install all eight:

claude plugin install session-hud@traversy-mods
claude plugin install impact-map@traversy-mods
claude plugin install tool-cards@traversy-mods
claude plugin install safe-shell@traversy-mods
claude plugin install quality-console@traversy-mods
claude plugin install verification-ledger@traversy-mods
claude plugin install agent-pulse@traversy-mods
claude plugin install work-queue@traversy-mods

Inside an interactive session, the same commands start with /plugin install instead of claude plugin install.

3. Load the mods

Start a new Claude Code session. If a session was already open when you installed or updated a mod, enter:

/reload-plugins

Run /plugin and open the Installed tab to confirm that the mods are enabled.

Use the same mods in terminal and desktop

Claude Code in the terminal and local sessions in the desktop Code tab share user-scoped plugin settings. Install a mod once at user scope and it is available in both places.

For the desktop app:

  1. Open the Code tab.
  2. Start a local session.
  3. Enter /reload-plugins, or start a new session after installation.
  4. Enter /plugin and confirm the mod is listed as active.

You can also use the desktop plugin manager. Click the plus button beside the prompt, choose Plugins, and use Manage plugins to enable or disable an installed mod.

Included mods

ModWhat it doesHow to open or test it
Session HUDShows the current Git branch, context, and weekly usage with detailed session informationSwitch branches or click Details beside the context meter
Impact MapTracks touched files and opens current Git diffsSelect an edited or created file in the Impact Map
Tool CardsReplaces normal tool-use rows with compact status cardsAsk Claude to read a file or run a command
Safe ShellDemonstrates a confirmation gate for a marked Bash commandAsk Claude to run echo __SAFE_SHELL_DEMO__
Quality ConsoleValidates a local mod from inside Claude CodeEnter /mod-check <path>
Verification LedgerTracks local checks, Git state, and GitHub ActionsEnter /checks
Agent PulseShows live subagent status, activity, elapsed time, and recent transcriptsAsk Claude to use a subagent or enter /agents
Work QueueGroups session tasks by working, blocked, ready, and doneAsk Claude to create tasks or enter /work-queue

Session HUD

Session HUD draws a compact band above the prompt with:

  • The current Git branch
  • Current context usage
  • A visual progress bar
  • Overall weekly account usage

Working branches appear in green. main and master appear in yellow as a reminder that you are on the default branch. Detached HEAD states are also yellow, and folders outside a Git repository say so directly. Session HUD checks every five seconds, so it also catches branch changes made in the built-in terminal or another terminal. Branches changed by a Claude Bash tool refresh immediately.

The compact Week label shows overall seven-day account usage. Click Details beside it to open Session Details. The pane shows:

  • Five-hour account usage with its reset time
  • Weekly account usage with its reset time
  • Session cost when Claude Code reports one
  • A color-coded meter for your personal context target

Claude Code also counts the current context and shows:

  • Clean progress bars for messages, system content, tool schemas, memory, skills, and agents
  • Messages as one conversation total
  • Loaded MCP tokens grouped by server, with tool details available from a server picker
  • Free space and the automatic compaction buffer

The full breakdown runs only when you click Details or press Refresh. It does not poll in the background. Claude Code provides a reliable total for Messages, but it does not provide a reliable token count for every individual message.

The context percentage uses a configurable personal target. It does not change Claude's actual context window or automatic compaction behavior.

Change the context target

Open Session Details and select Change beside the current target. Enter a value such as 200k, 300k, 750k, or 1m, then press Enter to save it. You can also open Claude Code's /config menu and change Context target there.

The setting is saved with the plugin and applies to future sessions. The default is 300k, and accepted values range from 10k through 10m.

The meter is green below 70 percent, yellow from 70 through 89 percent, and red at 90 percent or higher. Its visual fill stops at 100 percent, but the numeric percentage can go higher.

Test Session HUD

  1. Install and load session-hud.
  2. Send a prompt so Claude Code records session usage.
  3. Look directly above the prompt box.
  4. Confirm that the current branch, context, and weekly usage appear.
  5. Switch branches in the built-in terminal and confirm that the label updates within five seconds.
  6. Confirm that the Week label shows your weekly percentage.
  7. Click Details beside the progress bar.
  8. Confirm that Session Details shows five-hour usage, weekly usage, session cost, context categories, and any connected MCP tool schemas.
  9. Select Change, enter another context target, and confirm that the percentage updates after the mod reloads.

Source: session-hud/hooks/register.tsx

Impact Map

Impact Map opens a pane that records the most recent files Claude touched during the current session.

It labels each file as:

  • READ when Claude uses the Read tool
  • EDITED when Claude uses the Edit tool
  • CREATED when Claude uses the Write tool

The pane keeps the 14 most recent unique file paths. Reading or changing the same file again moves it to the newest position.

Edited and created files are clickable. Selecting one opens a Diff pane with Claude Code's native unified-diff highlighting. Tracked files use the current working-tree diff against HEAD. Untracked files are shown as newly added files.

The Diff pane reflects the file's current Git state, not a private history of only Claude's edits. If you or another tool changed the same file, those changes appear too. Read-only files are not clickable because they have no change to display.

Test Impact Map

  1. Install and load impact-map.
  2. Ask Claude to read two files and edit one of them.
  3. Watch the Impact Map pane update.
  4. Select the edited file and confirm that its highlighted diff opens in a new pane tab.
  5. If the Impact Map pane is closed, enter /impact-map to reopen it.

Claude Code has one docked pane area. If Verification Ledger is also open, the two panes appear as tabs in that area rather than side by side.

Source: impact-map/hooks/register.tsx

Tool Cards

Tool Cards replaces Claude Code's standard tool-use row with a bordered card that emphasizes the current state, tool name, and target.

Possible states are:

  • RUNNING
  • DONE
  • FAILED
  • STOPPED

For file tools, the card displays the file path. For Bash, it displays the command. It also handles tools that expose a path or pattern field.

Test Tool Cards

  1. Install and load tool-cards.
  2. Ask Claude to read a file.
  3. Watch the card change from RUNNING to DONE.
  4. Ask Claude to run a command that fails if you want to see the FAILED state.

The green DONE label is part of this mod. Disable Tool Cards from /plugin to return to Claude Code's normal tool rows.

Source: tool-cards/hooks/register.tsx

Safe Shell

Safe Shell is a harmless demonstration of a tool.check handler. It shows how a mod can stop before a Bash command runs and ask the user to approve or cancel it.

This version looks only for the marker:

__SAFE_SHELL_DEMO__

It does not attempt to identify real dangerous commands. That limited behavior is intentional, so the demo cannot accidentally become a false promise of shell security.

Test Safe Shell

  1. Install and load safe-shell.
  2. Ask Claude to run this exact command:
   echo __SAFE_SHELL_DEMO__
  1. Claude Code should show a confirmation prompt from Safe Shell before the command runs.
  2. Choose whether to continue or cancel.
  3. Run a normal command such as git status and confirm that Safe Shell does not interfere.

Source: safe-shell/hooks/register.ts

Quality Console

Quality Console adds a /mod-check command that runs Claude Code's official static validator against a local mod directory.

Use it from a Claude Code session:

/mod-check /absolute/path/to/a-mod

If you omit the path, it validates the current working directory:

/mod-check

The command displays PASS, FAIL, or ERROR followed by the validator output. Validation checks the manifest, hook events, matchers, API calls, imports, and statically detectable capabilities. It does not execute the mod.

Test Quality Console

  1. Install and load quality-console.
  2. Clone this repository if you do not already have a local mod to check.
  3. Enter /mod-check with the absolute path to one of the mod directories.
  4. Confirm that the result starts with PASS.

Example:

/mod-check /path/to/claude-mods/session-hud

Source: quality-console/hooks/register.ts

Verification Ledger

Verification Ledger opens a Checks pane that combines three kinds of evidence:

  • Local verification commands run by Claude through the Bash tool
  • Current Git branch, commit, working-tree state, and upstream state
  • GitHub Actions runs for the current commit

Open it with:

/checks

The pane does not open automatically, so it does not compete with Impact Map until you ask for it. When both panes are open, Claude Code places them in tabs within the same docked pane area.

Recognized local commands

The ledger recognizes common commands in these categories:

  • Verify: npm run verify, pnpm verify, yarn verify, bun verify, and ./scripts/verify
  • Tests: package test scripts, Vitest, Jest, Pytest, cargo test, and go test
  • Lint: package lint scripts, ESLint, Biome, Ruff, golangci-lint, and Cargo Clippy
  • Typecheck: package typecheck scripts, tsc --noEmit, Mypy, and Pyright
  • Build: package build scripts, cargo build, and go build

The command must be run by Claude through its Bash tool. A command run manually in a separate terminal is not a Claude Code event, so the mod cannot observe it.

Pass, fail, and stale results

Verification Ledger stores the latest result in each category for the current session.

  • PASS means the recognized command completed successfully.
  • FAIL means it returned an error.
  • STALE means files, the current commit, or the recorded session revision changed after the check ran.

Local results reset when the mod reloads or a new session starts. The ledger is a live session display, not a permanent audit database.

GitHub Actions support

Remote checks require the GitHub CLI:

gh --version
gh auth status

If needed, authenticate it:

gh auth login

While the Checks pane is open, the mod runs this read-only query for the current commit every 15 seconds:

gh run list --commit <commit-sha> --limit 8 --json name,status,conclusion,url,headSha,workflowName

The pane displays workflow links and the states RUNNING, PASS, FAIL, or SKIPPED. It also shows a toast when a previously running workflow passes or fails.

If gh is missing, not authenticated, or the repository is not hosted on GitHub, the remote section reports that GitHub CI is unavailable. Local checks and Git state still work.

Change the polling interval

Open verification-ledger/hooks/config.ts:

export const CI_POLL_INTERVAL_MS = 15_000
export const MAX_CI_RUNS = 8

Change the values to control how often the open pane refreshes and how many workflow runs it displays.

Test Verification Ledger

  1. Install and load verification-ledger in a Git repository.
  2. Enter /checks.
  3. Ask Claude to run the project's test command.
  4. Confirm that Tests appears with PASS or FAIL.
  5. Ask Claude to edit a file.
  6. Reopen or refresh /checks and confirm that the earlier result is STALE.
  7. Push a commit with GitHub Actions configured.
  8. Leave the pane open and watch the workflow move from RUNNING to its final state.

Source: verification-ledger/hooks/register.tsx

Agent Pulse

Agent Pulse opens an Agents pane when the first subagent starts in the current session. It gives each agent a compact card with:

  • Current status
  • Agent name or task description
  • Elapsed time since the mod first observed it
  • Current tool while one is running
  • Most recent tool after it finishes

The pane does not open when a session has no subagents. It also does not take keyboard focus when it opens automatically. Enter /agents whenever you want to open it manually or bring it back after closing it.

Select View on an agent card to replace the list with a compact detail view. The detail view shows the agent type, status, elapsed time, parent agent when present, and up to eight recent transcript messages. Select Back to return to the full list.

Agent Pulse keeps finished agents in the pane for the rest of the current session, even when Claude Code no longer includes them in its live agent list. The history resets when the mod reloads or a new session starts.

Possible states are:

  • PENDING before work begins
  • RUNNING while the agent is working
  • WAITING when it is waiting on another action
  • IDLE when a teammate is available for more work
  • COMPLETED after a successful result
  • FAILED after an error or refusal
  • KILLED after an interrupted run

Agent Pulse uses only Claude Code's agent, session, clock, command, and interface APIs. It does not call a model, start a process, read project files, make a network request, or save agent transcripts outside the current session.

Claude Code may deny transcript access for an agent running in another process, a remote workflow agent, or an agent whose saved transcript is no longer available. The card still shows any status and activity that Claude Code reports, and the detail view explains when its transcript cannot be read.

Test Agent Pulse

  1. Install and load agent-pulse.
  2. Enter /agents and confirm that the empty state says there are no subagents in the session.
  3. Ask Claude to use an Explore subagent to inspect a small part of the current project.
  4. Confirm that the Agents pane opens without taking focus.
  5. Watch the card update with the agent status, elapsed time, and current or last tool.
  6. Select View and confirm that the recent prompt, response, and tool names appear.
  7. Select Back to return to the agent list.
  8. Repeat the same check in a terminal session and a local session in the desktop Code tab.

Source: agent-pulse/hooks/register.tsx

Work Queue

Work Queue opens a Tasks pane when Claude creates the first task in the current session. It turns Claude's task state into four focused groups:

  • Working for tasks in progress
  • Blocked for pending tasks with unfinished dependencies
  • Ready for pending tasks that can start
  • Done for completed tasks

Each row shows the task subject, owner when one is assigned, and how long it has been in its current state. Select View to see the full description, owner, creation and update times, tasks that block it, and tasks that depend on it. Dependencies are clickable, so you can move through the work graph without leaving the pane.

The pane does not open in an empty session and does not take keyboard focus when it opens automatically. Enter /work-queue to open it manually or bring it back after closing it.

Work Queue observes TaskCreate, TaskUpdate, TaskList, and TaskGet tool calls. It also observes Claude Code's task-created and task-completed lifecycle events, which catches task activity that did not pass through those tools. It never creates, updates, completes, or deletes a task itself.

Task history lives only in memory for the current session. Reloading the mod or starting a new session clears the pane. The mod does not call a model, start a process, read project files, make a network request, or persist task data.

Claude Code does not deliver classic task lifecycle events to user-installed plugins when an organization manages the installation. Normal task tool calls still appear, but a task created in another process may be missing if it produces only a lifecycle event.

Test Work Queue

  1. Install and load work-queue.
  2. Enter /work-queue and confirm that the empty state says there are no tasks in the session.
  3. Ask Claude to create a three-step task plan where the interface task depends on the API task.
  4. Ask Claude to start the API task.
  5. Confirm that the pane shows one task under Working, the dependent task under Blocked, and the remaining task under Ready.
  6. Select View on the blocked task and confirm that the API task appears under Blocked by.
  7. Complete the API task and confirm that it moves to Done while the dependent task moves to Ready.
  8. Repeat the check in a terminal session and a local session in the desktop Code tab.

Source: work-queue/hooks/register.tsx

How the mods work together

The mods have separate responsibilities, so their interface elements do not duplicate each other:

  • Session HUD owns the band above the prompt.
  • Tool Cards owns tool-use rows in the transcript.
  • Impact Map owns a file-activity pane.
  • Verification Ledger owns a checks pane.
  • Agent Pulse owns a live subagent pane.
  • Work Queue owns a task-state pane.
  • Quality Console owns /mod-check.
  • Safe Shell owns only its marked-command confirmation.

Impact Map, Verification Ledger, Agent Pulse, and Work Queue share Claude Code's single docked pane area as separate tabs. Agent Pulse shows who is working, while Work Queue shows what work exists and what is blocked. All other mods use different interface regions or event types.

Develop locally from scratch

You do not need Node.js, a bundler, or a dependency installation. Claude Code loads TypeScript mod files directly and supplies the test runner.

1. Clone the repository

git clone https://github.com/bradtraversy/claude-mods.git
cd claude-mods

2. Validate the marketplace and every mod

claude plugin validate .
claude plugin validate ./session-hud
claude plugin validate ./impact-map
claude plugin validate ./tool-cards
claude plugin validate ./safe-shell
claude plugin validate ./quality-console
claude plugin validate ./verification-ledger
claude plugin validate ./agent-pulse
claude plugin validate ./work-queue

Validation reads the mod without executing it. Review the reported hooks: and calls: lines to see what it handles and which Claude Code APIs it uses.

3. Run the automated tests

claude plugin test ./session-hud
claude plugin test ./impact-map
claude plugin test ./tool-cards
claude plugin test ./safe-shell
claude plugin test ./quality-console
claude plugin test ./verification-ledger
claude plugin test ./agent-pulse
claude plugin test ./work-queue

The interface tests mount each visual mod on simulated terminal and desktop surfaces.

4. Load one mod for a development session

claude --plugin-dir ./session-hud

Claude Code watches a directory loaded with --plugin-dir and reloads the hooks module after changes. Run /plugin to confirm that the mod loaded.

You can load multiple development directories by repeating the flag:

claude \
  --plugin-dir ./session-hud \
  --plugin-dir ./impact-map \
  --plugin-dir ./tool-cards

5. Use the local checkout in terminal and desktop

Register the clone itself as a local marketplace:

claude plugin marketplace add /absolute/path/to/claude-mods

Then install any mod from traversy-mods. A marketplace added from a local directory reads these relative plugin directories in place, so edits appear after a new session starts or after /reload-plugins.

This is the easiest development setup for sharing the exact same working directory between terminal sessions and local desktop Code sessions.

Anatomy of each mod

Every directory follows the same basic structure:

mod-name/
├── .claude-plugin/
│   ├── plugin.json
│   └── types/
│       ├── .gitignore
│       └── tsconfig.json
├── hooks/
│   ├── hooks.json
│   ├── config.ts       # only when the mod has user-editable settings
│   └── register.tsx    # register.ts when JSX is not needed
├── tests/
│   └── mod-name.test.ts
└── tsconfig.json

plugin.json

The plugin manifest provides the mod name, version, description, and author.

hooks.json

This file points Claude Code to the TypeScript module that registers the event handlers.

register.ts or register.tsx

The module imports the Register type from claude-code and exports a register function:

import type { Register } from 'claude-code'

export const register: Register = on => {
  on('session.start', ($, event, next) => {
    return next(event)
  })
}

The Register type comes from declarations generated by Claude Code in .claude-plugin/types/. Those declarations also provide types for $, event, and next, which removes the red lines a

Source 2 files
hooks/register.tsx 443 lines
1import type { EngineInterface, Register } from 'claude-code'
2import { CI_POLL_INTERVAL_MS, MAX_CI_RUNS } from './config.ts'
3
4const PANE = 'verification-ledger'
5
6type CheckKind = 'verify' | 'test' | 'lint' | 'typecheck' | 'build'
7type ResultStatus = 'pass' | 'fail'
8type DisplayStatus = ResultStatus | 'stale' | 'running' | 'skipped'
9
10type LocalCheck = {
11  kind: CheckKind
12  label: string
13  command: string
14  status: ResultStatus
15  completedAt: number
16  fingerprint: string
17  revision: number
18}
19
20type GitSnapshot = {
21  root: string | null
22  branch: string
23  head: string
24  shortHead: string
25  fingerprint: string
26  dirtyFiles: number
27  ahead: number | null
28  behind: number | null
29}
30
31type CiRun = {
32  name: string
33  status: string
34  conclusion: string
35  url: string
36  headSha: string
37}
38
39type CommandResult = {
40  exitCode: number
41  stdout: string
42}
43
44const checks = new Map<CheckKind, LocalCheck>()
45let git: GitSnapshot = emptyGitSnapshot()
46let ciRuns: CiRun[] = []
47let ciMessage = 'Open this pane to load GitHub CI.'
48let ciRefreshedAt: number | null = null
49let revision = 0
50let refreshTask: Promise<void> | null = null
51let pollStarted = false
52
53function emptyGitSnapshot(): GitSnapshot {
54  return {
55    root: null,
56    branch: '',
57    head: '',
58    shortHead: '',
59    fingerprint: '',
60    dirtyFiles: 0,
61    ahead: null,
62    behind: null,
63  }
64}
65
66function classifyCheck(command: string): { kind: CheckKind; label: string } | null {
67  const value = command.toLowerCase()
68
69  if (/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?verify\b|(?:^|\s)\.\/scripts\/verify\b/.test(value)) {
70    return { kind: 'verify', label: 'Verify' }
71  }
72
73  if (/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test(?:\s|:|$)|\b(?:vitest|jest|pytest|cargo\s+test|go\s+test)\b/.test(value)) {
74    return { kind: 'test', label: 'Tests' }
75  }
76
77  if (/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint(?:\s|:|$)|\b(?:eslint|biome\s+check|ruff\s+check|golangci-lint|cargo\s+clippy)\b/.test(value)) {
78    return { kind: 'lint', label: 'Lint' }
79  }
80
81  if (/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?typecheck\b|\b(?:tsc\s+--noemit|mypy|pyright)\b/.test(value)) {
82    return { kind: 'typecheck', label: 'Typecheck' }
83  }
84
85  if (/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build(?:\s|:|$)|\b(?:cargo|go)\s+build\b/.test(value)) {
86    return { kind: 'build', label: 'Build' }
87  }
88
89  return null
90}
91
92async function run(
93  $: EngineInterface,
94  argv: readonly string[],
95  cwd: string,
96): Promise<CommandResult> {
97  try {
98    const result = await $.process.run(argv, { cwd, timeoutMs: 10_000 })
99    return { exitCode: result.exitCode, stdout: result.stdout.trim() }
100  } catch {
101    return { exitCode: 1, stdout: '' }
102  }
103}
104
105async function readGitSnapshot($: EngineInterface): Promise<GitSnapshot> {
106  const cwd = await $.session.cwd()
107  const rootResult = await run($, ['git', 'rev-parse', '--show-toplevel'], cwd)
108  if (rootResult.exitCode !== 0 || !rootResult.stdout) return emptyGitSnapshot()
109
110  const root = rootResult.stdout
111  const [branchResult, headResult, shortHeadResult, statusResult, upstreamResult] = await Promise.all([
112    run($, ['git', 'branch', '--show-current'], root),
113    run($, ['git', 'rev-parse', 'HEAD'], root),
114    run($, ['git', 'rev-parse', '--short', 'HEAD'], root),
115    run($, ['git', 'status', '--porcelain=v1'], root),
116    run($, ['git', 'rev-parse', '--verify', '@{upstream}'], root),
117  ])
118
119  const status = statusResult.stdout
120  let ahead: number | null = null
121  let behind: number | null = null
122
123  if (upstreamResult.exitCode === 0) {
124    const counts = await run($, ['git', 'rev-list', '--left-right', '--count', 'HEAD...@{upstream}'], root)
125    if (counts.exitCode === 0) {
126      const values = counts.stdout.split(/\s+/)
127      const left = Number(values[0])
128      const right = Number(values[1])
129      if (Number.isFinite(left) && Number.isFinite(right)) {
130        ahead = left
131        behind = right
132      }
133    }
134  }
135
136  return {
137    root,
138    branch: branchResult.stdout || '(detached)',
139    head: headResult.stdout,
140    shortHead: shortHeadResult.stdout,
141    fingerprint: `${headResult.stdout}\n${status}`,
142    dirtyFiles: status ? status.split('\n').filter(Boolean).length : 0,
143    ahead,
144    behind,
145  }
146}
147
148async function refreshLocal($: EngineInterface): Promise<void> {
149  git = await readGitSnapshot($)
150  $.ui.invalidate('ui.render')
151}
152
153function ciStatus(run: CiRun): DisplayStatus {
154  if (run.status !== 'completed') return 'running'
155  if (run.conclusion === 'success') return 'pass'
156  if (run.conclusion === 'neutral' || run.conclusion === 'skipped') return 'skipped'
157  return 'fail'
158}
159
160function ciOverall(runs: readonly CiRun[]): 'none' | 'running' | 'pass' | 'fail' {
161  if (runs.length === 0) return 'none'
162  if (runs.some(run => ciStatus(run) === 'fail')) return 'fail'
163  if (runs.some(run => ciStatus(run) === 'running')) return 'running'
164  return 'pass'
165}
166
167async function refreshCi($: EngineInterface): Promise<void> {
168  if (!git.root || !git.head) {
169    ciRuns = []
170    ciMessage = 'GitHub CI requires a Git repository with a commit.'
171    ciRefreshedAt = await $.clock.now()
172    return
173  }
174
175  const previous = ciOverall(ciRuns)
176  const result = await run(
177    $,
178    [
179      'gh',
180      'run',
181      'list',
182      '--commit',
183      git.head,
184      '--limit',
185      String(MAX_CI_RUNS),
186      '--json',
187      'name,status,conclusion,url,headSha,workflowName',
188    ],
189    git.root,
190  )
191
192  ciRefreshedAt = await $.clock.now()
193
194  if (result.exitCode !== 0) {
195    ciRuns = []
196    ciMessage = 'GitHub CI is unavailable. Check the remote and gh authentication.'
197    return
198  }
199
200  try {
201    const parsed = JSON.parse(result.stdout) as Array<{
202      name?: unknown
203      workflowName?: unknown
204      status?: unknown
205      conclusion?: unknown
206      url?: unknown
207      headSha?: unknown
208    }>
209
210    ciRuns = parsed
211      .filter(item => item && typeof item === 'object')
212      .map(item => ({
213        name: typeof item.workflowName === 'string' && item.workflowName
214          ? item.workflowName
215          : typeof item.name === 'string' && item.name
216            ? item.name
217            : 'Workflow',
218        status: typeof item.status === 'string' ? item.status : 'unknown',
219        conclusion: typeof item.conclusion === 'string' ? item.conclusion : '',
220        url: typeof item.url === 'string' ? item.url : '',
221        headSha: typeof item.headSha === 'string' ? item.headSha : '',
222      }))
223      .filter(run => !run.headSha || run.headSha === git.head)
224      .slice(0, MAX_CI_RUNS)
225
226    ciMessage = ciRuns.length === 0
227      ? `No GitHub Actions runs found for ${git.shortHead}.`
228      : ''
229  } catch {
230    ciRuns = []
231    ciMessage = 'GitHub returned CI data that the ledger could not read.'
232  }
233
234  const current = ciOverall(ciRuns)
235  if (previous === 'running' && current === 'pass') {
236    $.ui.toast(`GitHub CI passed for ${git.shortHead}.`)
237  } else if (previous === 'running' && current === 'fail') {
238    $.ui.toast(`GitHub CI failed for ${git.shortHead}.`)
239  }
240}
241
242function refreshAll($: EngineInterface): Promise<void> {
243  if (refreshTask) return refreshTask
244
245  refreshTask = (async () => {
246    await refreshLocal($)
247    await refreshCi($)
248  })().finally(() => {
249    refreshTask = null
250    $.ui.invalidate('ui.render')
251  })
252
253  $.ui.invalidate('ui.render')
254  return refreshTask
255}
256
257async function pollIfOpen($: EngineInterface): Promise<void> {
258  const panes = await $.ui.panes()
259  if (panes.some(pane => pane.id === PANE)) await refreshAll($)
260}
261
262function localStatus(check: LocalCheck): DisplayStatus {
263  if (check.revision !== revision) return 'stale'
264  if (git.fingerprint && check.fingerprint !== git.fingerprint) return 'stale'
265  return check.status
266}
267
268function statusColor(status: DisplayStatus): 'success' | 'error' | 'warning' | 'inactive' {
269  if (status === 'pass') return 'success'
270  if (status === 'fail') return 'error'
271  if (status === 'stale' || status === 'running') return 'warning'
272  return 'inactive'
273}
274
275function statusLabel(status: DisplayStatus): string {
276  return status.toUpperCase().padEnd(7)
277}
278
279function timeLabel(value: number | null): string {
280  if (value === null) return ''
281  return new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
282}
283
284function branchState(): string {
285  const parts = [git.dirtyFiles === 0 ? 'clean' : `${git.dirtyFiles} changed`]
286  if (git.ahead !== null && git.ahead > 0) parts.push(`${git.ahead} ahead`)
287  if (git.behind !== null && git.behind > 0) parts.push(`${git.behind} behind`)
288  if (git.ahead === null) parts.push('no upstream')
289  return parts.join(' · ')
290}
291
292export const register: Register = on => {
293  on('session.start', async ($, event, next) => {
294    await $.command.register({
295      name: 'checks',
296      description: 'Open and refresh the Verification Ledger',
297    })
298
299    await refreshLocal($)
300
301    if (!pollStarted) {
302      pollStarted = true
303      $.clock.every(CI_POLL_INTERVAL_MS, () => {
304        void pollIfOpen($)
305      })
306    }
307
308    return next(event)
309  })
310
311  on('command.run', { command: 'checks' }, async $ => {
312    await $.ui.open({
313      id: PANE,
314      title: 'Checks',
315      focus: true,
316      closeOnEscape: true,
317      columns: 56,
318    })
319    await refreshAll($)
320    return {}
321  })
322
323  on('tool.call', { tool: 'Bash' }, async ($, event, next) => {
324    const recognized = classifyCheck(event.command)
325    const result = await next(event)
326    if ('deny' in result) return result
327
328    try {
329      const completed = !result.isError ? result.result : null
330      const backgrounded = completed?.backgroundTaskId !== undefined
331      const changed = completed?.bashEditDiff !== undefined
332
333      if (changed) revision += 1
334      if (changed || recognized) await refreshLocal($)
335
336      if (recognized && !event.run_in_background && !backgrounded) {
337        checks.set(recognized.kind, {
338          ...recognized,
339          command: event.command,
340          status: result.isError ? 'fail' : 'pass',
341          completedAt: await $.clock.now(),
342          fingerprint: git.fingerprint,
343          revision,
344        })
345
346        if (result.isError) $.ui.toast(`${recognized.label} failed.`)
347        $.ui.invalidate('ui.render')
348      }
349
350      if (completed?.gitOperation?.push) {
351        $.ui.toast('Push detected. Watching GitHub CI.')
352        $.clock.after(1_000, () => {
353          void refreshAll($)
354        })
355      }
356    } catch (error) {
357      $.ui.log(`Verification Ledger could not record a Bash result: ${String(error)}`, { to: 'debug' })
358    }
359
360    return result
361  }).catch(($, event, next) => next(event))
362
363  on('tool.call', { tool: ['Edit', 'Write', 'NotebookEdit'] }, async ($, event, next) => {
364    const result = await next(event)
365    if ('deny' in result || result.isError) return result
366
367    try {
368      revision += 1
369      await refreshLocal($)
370    } catch (error) {
371      $.ui.log(`Verification Ledger could not refresh after an edit: ${String(error)}`, { to: 'debug' })
372    }
373
374    return result
375  }).catch(($, event, next) => next(event))
376
377  on('ui.render', { component: 'Pane', requestId: PANE }, ($, event) => {
378    const { Box, Button, Link, Text } = $.ui.resolve(event)
379    const localChecks = [...checks.values()]
380
381    return (
382      <Box flexDirection="column" gap={1}>
383        <Box gap={2}>
384          <Text bold>Verification Ledger</Text>
385          <Button
386            key="refresh"
387            label={refreshTask ? 'Refreshing' : 'Refresh'}
388            hotkey="r"
389            onPress={() => {
390              void refreshAll($)
391            }}
392          />
393        </Box>
394
395        {git.root ? (
396          <Box flexDirection="column">
397            <Text bold>{git.branch} @ {git.shortHead}</Text>
398            <Text dimColor>{branchState()}</Text>
399          </Box>
400        ) : (
401          <Text color="warning">Not inside a Git repository.</Text>
402        )}
403
404        <Box flexDirection="column">
405          <Text bold>Local checks</Text>
406          {localChecks.length === 0 ? (
407            <Text dimColor>No verification commands recorded this session.</Text>
408          ) : (
409            localChecks.map(check => {
410              const status = localStatus(check)
411              return (
412                <Box key={check.kind} gap={1}>
413                  <Text color={statusColor(status)} bold>{statusLabel(status)}</Text>
414                  <Text bold>{check.label}</Text>
415                  <Text dimColor>{timeLabel(check.completedAt)}</Text>
416                </Box>
417              )
418            })
419          )}
420        </Box>
421
422        <Box flexDirection="column">
423          <Text bold>GitHub CI</Text>
424          {ciRuns.length === 0 ? (
425            <Text dimColor>{ciMessage}</Text>
426          ) : (
427            ciRuns.map((run, index) => {
428              const status = ciStatus(run)
429              return (
430                <Box key={`${run.url}:${index}`} gap={1}>
431                  <Text color={statusColor(status)} bold>{statusLabel(status)}</Text>
432                  {run.url ? <Link href={run.url} label={run.name} /> : <Text>{run.name}</Text>}
433                </Box>
434              )
435            })
436          )}
437          {ciRefreshedAt !== null && <Text dimColor>Updated {timeLabel(ciRefreshedAt)}</Text>}
438        </Box>
439      </Box>
440    )
441  })
442}
443
hooks/config.ts 3 lines
1export const CI_POLL_INTERVAL_MS = 15_000
2export const MAX_CI_RUNS = 8
3