SLOPSHOPPER

git-status

Git snapshot, per-prompt GIT_STATE context and a fallback git status line that gives way to ccstatusline or band-line

guardstatuspromptprocesstimer
A shopper browsing a rack in a slop shop
README

git-status

A git status line and a per-prompt GIT_STATE context line, written as a CLI plugin of function hooks. Cross-platform: it runs git through the engine, with no shell script.

What it shows

Status line (at most 80 characters):

⎇ feature/x ↑2 ↓1 · +3 ~3 ?2 -- commits(R,L):1,2

The branch (clipped to 32 characters), ahead/behind its upstream or no upstream, then staged (+), unstaged and unmerged (~) and untracked (?) counts, or clean. The commits(R,L) tail is always present: R counts commits only the remote has (behind), L commits only the local branch has (ahead); both are 0 when the branch has no upstream. When the line runs over 80 characters, the part before the tail is clipped and the tail stays whole.

Prompt context, attached only when it changed since the line last attached:

GIT_STATE BRANCH=feature/x UPSTREAM=origin/feature/x AHEAD=2 BEHIND=1 STAGED=3 UNSTAGED=3 UNTRACKED=2 DIRTY=true

After /clear, a resume or a compaction of the main conversation, the next prompt gets the line again even when unchanged.

When another banner draws the git state

The status line is the fallback banner (the engine draws it as ⚠ git-status: <line>, in its own color). It gives way to the other banner options (plugins/banner-status/README.md):

  • ccstatusline: an optional dependency that no plugin installs on its own (Node.js and npm, then npm install -g ccstatusline@~2.2.32; /banner-status:setup-statusline offers to run it and writes the statusLine setting). Once the merged statusLine setting's command runs ccstatusline (ccstatusline ..., or through npx / bunx) and its executable is found (as given, or under a PATH folder, with .cmd and .exe tried), the mod clears its line on every refresh. The lookup is kept per executable and PATH for the life of the module, so an install made mid-session shows after a restart. Without the executable the mod keeps drawing, so a checkout without the install still has a banner.
  • band-line: that mod clears this line while it is loaded.

The snapshot and the GIT_STATE context are kept in every case.

Project root

git -C <start> rev-parse --show-toplevel, asked first from the session cwd (a linked worktree resolves to itself) and then from CLAUDE_PROJECT_DIR. The first top level git answers is the root; each start folder's answer is kept for the life of the module. No repository anywhere clears the status line and attaches nothing.

Hooks

HookDoes
session.startStarts a 60 s background refresh and refreshes once. Each refresh reads the statusLine setting to decide whether the line gives way to ccstatusline.
tool.call on Bash, PowerShell, Edit, Write, MultiEdit, NotebookEditRefreshes after the call returns, without delaying it.
turn.completeRefreshes.
prompt.submitRuns its own git status (after a background run in flight, waiting at most 2 s) and attaches the GIT_STATE line when it changed.
session.end, session.compactForce the next prompt's line after /clear, a resume or a main compaction.

Background runs coalesce: one git status in flight, at least 2 s between background starts, and a request made while one runs is owed a single run after it. git status runs with GIT_OPTIONAL_LOCKS=0, so it never takes the index lock. Every failure (git missing, not a repository, a timeout, a refused status line) clears the status and never blocks a prompt or a tool call.

State

$.state['git-status'] (contract: types/index.d.ts):

KeyMeaning
gitThe latest snapshot (branch, upstream, ahead, behind, staged, unstaged, untracked); null after a failed run.
lastContextThe GIT_STATE line last attached to a prompt.

Checks

claude plugin validate <mod folder>
claude plugin test <mod folder>

Loading

Install from the operator-straps marketplace:

claude plugin marketplace add t968rs/operator-straps
claude plugin install git-status@operator-straps

For development, add the folder to CLAUDE_CODE_PLUGIN_DIRS in the user-level ~/.claude/settings.json env block (;-separated on Windows), or start one session with claude --plugin-dir <folder>.

.claude-plugin/types/ is generated by the engine on load and git-ignored; tsconfig.json extends it.

Source 3 files
hooks/register.ts 8 lines
1import type { Register } from 'claude-code'
2
3import { registerStatus } from './status'
4
5export const register: Register = on => {
6  registerStatus(on)
7}
8
hooks/status.ts 448 lines
1import type {
2  EngineInterface,
3  PromptSubmitResult,
4  Register,
5  SessionCompactInput,
6  SessionCompactResult,
7} from 'claude-code'
8import { atom, read, update } from 'claude-code'
9
10import type { GitSnapshot } from '../types'
11
12/**
13 * Cross-platform git status line and per-prompt git context.
14 *
15 * The project root is `git rev-parse --show-toplevel` from the session cwd (else CLAUDE_PROJECT_DIR);
16 * the per-prompt line is attached only when it changed since the last one attached. Every failure path
17 * (no root, no git, not a repo) clears the status and never throws.
18 */
19
20type Dollar = EngineInterface
21
22const gitState = atom({ plugin: 'git-status', key: 'git' } as const, null)
23const lastContext = atom({ plugin: 'git-status', key: 'lastContext' } as const, '')
24
25/** Minimum gap between two background git runs, in milliseconds. */
26export const MIN_GAP_MS = 2000
27/** Background refresh period while the session is open, in milliseconds. */
28export const TICK_MS = 60_000
29const MAX_STATUS = 80
30const MAX_BRANCH = 32
31const GIT_TIMEOUT_MS = 10_000
32/**
33 * Longest wait, in milliseconds, a prompt gives a background git run in flight before it runs its own:
34 * that wait is no `$` call of the hook's, so it counts against the hook's 10 s budget.
35 */
36export const TAIL_WAIT_MS = 2000
37const REFRESH_TOOLS = /^(Bash|PowerShell|Edit|Write|MultiEdit|NotebookEdit)$/
38
39// ---------------------------------------------------------------------------
40// Pure parsing and formatting
41
42/** Parses `git status --porcelain=v2 --branch` output; unknown lines are ignored. */
43export const parsePorcelain = (stdout: string): GitSnapshot => {
44  const out: GitSnapshot = {
45    branch: '', upstream: null, ahead: 0, behind: 0, staged: 0, unstaged: 0, untracked: 0,
46  }
47  for (const raw of stdout.split(/\r?\n/)) parseLine(raw, out)
48  return out
49}
50
51/** Folds one porcelain line into `out`. */
52const parseLine = (line: string, out: GitSnapshot): void => {
53  let m: RegExpMatchArray | null
54  if ((m = line.match(/^# branch\.head (.+)$/))) out.branch = m[1] ?? ''
55  else if ((m = line.match(/^# branch\.upstream (.+)$/))) out.upstream = m[1] ?? null
56  else if ((m = line.match(/^# branch\.ab \+(\d+) -(\d+)$/))) {
57    out.ahead = Number(m[1])
58    out.behind = Number(m[2])
59  } else if ((m = line.match(/^[12] (.)(.) /))) {
60    if (m[1] !== '.') out.staged++
61    if (m[2] !== '.') out.unstaged++
62  } else if (/^u /.test(line)) out.unstaged++
63  else if (/^\? /.test(line)) out.untracked++
64}
65
66/** Whole-string truncation with an ellipsis. */
67const clip = (text: string, max: number): string => (text.length <= max ? text : `${text.slice(0, max - 1)}…`)
68
69/** The branch segment: name, then ahead/behind or "no upstream". */
70const branchSegment = (g: GitSnapshot): string => {
71  const head = `⎇ ${clip(g.branch || '?', MAX_BRANCH)}`
72  if (g.upstream === null) return `${head} no upstream`
73  return g.ahead > 0 || g.behind > 0 ? `${head} ↑${g.ahead} ↓${g.behind}` : head
74}
75
76/** The working-tree segment: non-zero counts, or "clean". */
77const treeSegment = (g: GitSnapshot): string => {
78  const parts: string[] = []
79  if (g.staged > 0) parts.push(`+${g.staged}`)
80  if (g.unstaged > 0) parts.push(`~${g.unstaged}`)
81  if (g.untracked > 0) parts.push(`?${g.untracked}`)
82  return parts.length === 0 ? 'clean' : parts.join(' ')
83}
84
85/** The commit-count segment: commits only the remote has (behind), then commits only the local branch has (ahead). */
86const commitsSegment = (g: GitSnapshot): string => ` -- commits(R,L):${g.behind},${g.ahead}`
87
88/** The status line, at most 80 characters; the commit counts are kept whole and the rest is clipped to fit. */
89export const formatStatus = (g: GitSnapshot): string => {
90  const commits = commitsSegment(g)
91  return clip(`${branchSegment(g)} · ${treeSegment(g)}`, MAX_STATUS - commits.length) + commits
92}
93
94/** The prompt context line under a GIT_STATE tag. */
95export const formatContext = (g: GitSnapshot): string => {
96  const dirty = g.staged > 0 || g.unstaged > 0 || g.untracked > 0
97  return (
98    `GIT_STATE BRANCH=${g.branch} UPSTREAM=${g.upstream ?? 'none'} AHEAD=${g.ahead} BEHIND=${g.behind}` +
99    ` STAGED=${g.staged} UNSTAGED=${g.unstaged} UNTRACKED=${g.untracked} DIRTY=${dirty}`
100  )
101}
102
103/** A path with forward slashes and no trailing slash; undefined when blank. */
104export const cleanPath = (p: string | undefined): string | undefined => {
105  const out = (p ?? '').trim().replace(/\\/g, '/').replace(/\/+$/, '')
106  return out === '' ? undefined : out
107}
108
109/**
110 * The executable a `statusLine` setting starts when its command runs ccstatusline (a quoted first word
111 * unquoted); undefined for any other setting.
112 */
113export const delegateExecutable = (statusLine: unknown): string | undefined => {
114  if (typeof statusLine !== 'object' || statusLine === null) return undefined
115  const command = (statusLine as { command?: unknown }).command
116  if (typeof command !== 'string' || !/(^|[\s/\\"'])ccstatusline(@|\.|\s|"|'|$)/.test(command)) return undefined
117  const first = command.trim().match(/^"([^"]+)"|^'([^']+)'|^(\S+)/)
118  return first?.[1] ?? first?.[2] ?? first?.[3]
119}
120
121/** The PATH separator: `;` when the value holds one or starts with a drive letter, else `:`. */
122const pathSeparator = (rawPath: string): string => (rawPath.includes(';') || /^[A-Za-z]:[\\/]/.test(rawPath) ? ';' : ':')
123
124/**
125 * Files that would be `exe`, each with the Windows launcher suffixes: `exe` itself when it names a folder,
126 * else `exe` under every PATH folder.
127 */
128export const executableCandidates = (exe: string, rawPath: string | undefined): string[] => {
129  const names = [exe, `${exe}.cmd`, `${exe}.exe`]
130  if (/[\\/]/.test(exe)) return names
131  const dirs = (rawPath ?? '').split(pathSeparator(rawPath ?? '')).map(d => cleanPath(d))
132  return dirs.filter((d): d is string => d !== undefined).flatMap(d => names.map(n => `${d}/${n}`))
133}
134
135/** Where to ask git for the top level, in order: the session cwd, then CLAUDE_PROJECT_DIR (no repeats). */
136export const rootStarts = (rawEnv: string | undefined, rawCwd: string | undefined): string[] => {
137  const out: string[] = []
138  for (const c of [cleanPath(rawCwd), cleanPath(rawEnv)]) {
139    if (c !== undefined && !out.some(o => o.toLowerCase() === c.toLowerCase())) out.push(c)
140  }
141  return out
142}
143
144// ---------------------------------------------------------------------------
145// Host access (kept in this file: the engine follows `$` past an import only into function declarations)
146
147/** Top levels already answered, by start folder (a reload starts afresh). */
148const toplevels = new Map<string, string>()
149
150/** `git rev-parse --show-toplevel` from `start`; undefined on any failure. */
151const toplevelOf = async ($: Dollar, start: string): Promise<string | undefined> => {
152  const known = toplevels.get(start)
153  if (known !== undefined) return known
154  const argv = ['git', '-C', start, 'rev-parse', '--show-toplevel']
155  const ran = await $.process.run(argv, { timeoutMs: GIT_TIMEOUT_MS }).catch(() => undefined)
156  const top = ran === undefined || ran.exitCode !== 0 ? undefined : cleanPath(ran.stdout)
157  if (top !== undefined) toplevels.set(start, top)
158  return top
159}
160
161/** The project root: the first start folder git answers for; undefined when none does. Never throws. */
162const resolveRoot = async ($: Dollar): Promise<string | undefined> => {
163  const env = await $.env.get('CLAUDE_PROJECT_DIR').catch(() => undefined)
164  const cwd = await $.session.cwd().catch(() => undefined)
165  for (const start of rootStarts(env, cwd)) {
166    const top = await toplevelOf($, start)
167    if (top !== undefined) return top
168  }
169  return undefined
170}
171
172/** Runs git status; undefined on any failure (git missing, not a repo, timeout). */
173const runGitStatus = async ($: Dollar, root: string): Promise<GitSnapshot | undefined> => {
174  const argv = ['git', '-C', root, 'status', '--porcelain=v2', '--branch']
175  const ran = await $.process
176    .run(argv, { timeoutMs: GIT_TIMEOUT_MS, env: { GIT_OPTIONAL_LOCKS: '0' } })
177    .catch(() => undefined)
178  if (ran === undefined || ran.exitCode !== 0) return undefined
179  const snap = parsePorcelain(ran.stdout)
180  return snap.branch === '' ? undefined : snap
181}
182
183/** A full snapshot, or undefined when the root or git is unavailable. */
184const takeSnapshot = async ($: Dollar): Promise<GitSnapshot | undefined> => {
185  const root = await resolveRoot($)
186  return root === undefined ? undefined : runGitStatus($, root)
187}
188
189/** Sets or clears the status line, swallowing a refusal. */
190const showStatus = async ($: Dollar, text: string | undefined): Promise<void> => {
191  try {
192    await $.ui.status(text)
193  } catch {
194    // a surface that draws no status line
195  }
196}
197
198/** Executable lookups already answered, by executable and PATH (a reload starts afresh). */
199const lookups = new Map<string, boolean>()
200
201/** The PATH value: `PATH`, else `Path` (its Windows spelling); undefined when neither is set. */
202const readPath = async ($: Dollar): Promise<string | undefined> =>
203  (await $.env.get('PATH').catch(() => undefined)) ?? $.env.get('Path').catch(() => undefined)
204
205/** Whether `exe` is a file, as given or under a PATH folder; the answer is kept per PATH. */
206const isInstalled = async ($: Dollar, exe: string): Promise<boolean> => {
207  const rawPath = await readPath($)
208  const key = `${exe}\n${rawPath ?? ''}`
209  const known = lookups.get(key)
210  if (known !== undefined) return known
211  let found = false
212  for (const candidate of executableCandidates(exe, rawPath)) {
213    if (await $.fs.exists(candidate).catch(() => false)) {
214      found = true
215      break
216    }
217  }
218  lookups.set(key, found)
219  return found
220}
221
222/**
223 * Whether ccstatusline draws the status line: the merged `statusLine` setting runs it and its executable is
224 * installed. The mod's own line then stays clear. Never throws.
225 */
226const isDelegated = async ($: Dollar): Promise<boolean> => {
227  const statusLine = await $.settings.read({ key: 'statusLine' }).catch(() => undefined)
228  const exe = delegateExecutable(statusLine)
229  return exe === undefined ? false : isInstalled($, exe)
230}
231
232/** Stores the snapshot and draws (or clears) the status line; never throws. */
233const publish = async ($: Dollar, snap: GitSnapshot | undefined): Promise<void> => {
234  await update($, gitState, () => snap ?? null).catch(() => undefined)
235  if (snap === undefined) return showStatus($, undefined)
236  const isClear = await isDelegated($).catch(() => false)
237  return showStatus($, isClear ? undefined : formatStatus(snap))
238}
239
240/** Snapshot then publish; swallows every error. */
241const refreshNow = async ($: Dollar): Promise<GitSnapshot | undefined> => {
242  const snap = await takeSnapshot($).catch(() => undefined)
243  await publish($, snap).catch(() => undefined)
244  return snap
245}
246
247// ---------------------------------------------------------------------------
248// Coalescing: one git run in flight, at least MIN_GAP_MS between background starts
249
250/** Per-load refresh bookkeeping (a reload starts afresh). */
251const pacing = {
252  /** A background run is scheduled or in flight. */
253  isBusy: false,
254  /** Background git is running now (past the pacing wait): a request then is owed a run after it. */
255  isRunning: false,
256  isOwed: false,
257  lastStart: Number.NEGATIVE_INFINITY,
258  /** The next prompt gets the context line even when unchanged: a new conversation, or a compacted one. */
259  isContextForced: true,
260  /** Tail of the git runs, background and foreground: each starts after the one before settled. */
261  gitTail: Promise.resolve() as Promise<unknown>,
262  /** Git runs chained on `gitTail` that have not settled. */
263  inFlight: 0,
264  tick: undefined as { cancel: () => void } | undefined,
265}
266
267/**
268 * Snapshot and publish after any run in flight settles, so git never runs twice at once and the
269 * last run started is the last one published.
270 */
271const serialRefresh = ($: Dollar): Promise<GitSnapshot | undefined> => {
272  const run = pacing.gitTail.then(() => refreshNow($))
273  track(run)
274  return run
275}
276
277/** Chains `run` onto the tail and counts it in flight until it settles. */
278const track = (run: Promise<unknown>): void => {
279  pacing.inFlight += 1
280  const settled = run.catch(() => undefined).finally(() => {
281    pacing.inFlight -= 1
282  })
283  pacing.gitTail = Promise.all([pacing.gitTail, settled]).catch(() => undefined)
284}
285
286/** Waits for the runs in flight, at most TAIL_WAIT_MS; returns at once when none is. Never throws. */
287const awaitTail = async ($: Dollar, signal: AbortSignal): Promise<void> => {
288  if (pacing.inFlight === 0) return
289  const stop = new AbortController()
290  const timer = $.clock.sleep(TAIL_WAIT_MS, { signal: AbortSignal.any([signal, stop.signal]) })
291  try {
292    await Promise.race([pacing.gitTail, timer.catch(() => undefined)])
293  } finally {
294    stop.abort()
295  }
296}
297
298/**
299 * The prompt's own snapshot: after the runs in flight when they settle within TAIL_WAIT_MS, else at
300 * once beside them (git status takes no lock: GIT_OPTIONAL_LOCKS=0).
301 */
302const promptRefresh = async ($: Dollar, signal: AbortSignal): Promise<GitSnapshot | undefined> => {
303  await awaitTail($, signal)
304  const run = refreshNow($)
305  track(run)
306  return run
307}
308
309/** Milliseconds left before a background run may start. */
310const gapLeft = async ($: Dollar): Promise<number> => pacing.lastStart + MIN_GAP_MS - (await $.clock.now())
311
312/** One paced background run; a refused wait rejects, which ends the cycle rather than hanging it. */
313const cycle = async ($: Dollar): Promise<void> => {
314  for (let wait = await gapLeft($); wait > 0; wait = await gapLeft($)) await $.clock.sleep(wait)
315  pacing.lastStart = await $.clock.now()
316  pacing.isRunning = true
317  await serialRefresh($)
318}
319
320/** Asks for a background refresh and returns at once; folds into a run already in flight. */
321const requestRefresh = ($: Dollar): void => {
322  if (pacing.isBusy) {
323    // a run still waiting out its gap will read the newer state anyway
324    if (pacing.isRunning) pacing.isOwed = true
325    return
326  }
327  pacing.isBusy = true
328  void cycle($)
329    .catch(() => undefined)
330    .finally(() => finishCycle($))
331}
332
333/** Ends a run and starts the one owed, if any. */
334const finishCycle = ($: Dollar): void => {
335  pacing.isBusy = false
336  pacing.isRunning = false
337  if (!pacing.isOwed) return
338  pacing.isOwed = false
339  requestRefresh($)
340}
341
342/** Records a foreground run, so the next background one keeps its distance. */
343const noteForegroundRun = async ($: Dollar): Promise<void> => {
344  const now = await $.clock.now().catch(() => undefined)
345  if (now !== undefined) pacing.lastStart = Math.max(pacing.lastStart, now)
346}
347
348/** Schedules a refresh after the current dispatch, so the caller's result is not delayed. */
349const refreshLater = ($: Dollar): void => {
350  try {
351    $.clock.after(0, () => requestRefresh($))
352  } catch {
353    // no timer: this refresh is skipped
354  }
355}
356
357/** (Re)starts the periodic refresh; a timer costs no model tokens. */
358const startTicking = ($: Dollar): void => {
359  try {
360    pacing.tick?.cancel()
361    pacing.tick = $.clock.every(TICK_MS, () => requestRefresh($))
362  } catch {
363    pacing.tick = undefined
364  }
365}
366
367// ---------------------------------------------------------------------------
368// Prompt context
369
370/** A fresh snapshot's context line when it should be attached to this prompt; records nothing. */
371const promptContext = async ($: Dollar, signal: AbortSignal): Promise<string | undefined> => {
372  await noteForegroundRun($)
373  const snap = await promptRefresh($, signal)
374  if (snap === undefined) return undefined
375  const line = formatContext(snap)
376  if (pacing.isContextForced) return line
377  const previous = await read($, lastContext).catch(() => '')
378  return previous === line ? undefined : line
379}
380
381/** Records `line` as attached, once the prompt entered with it and the dispatch did not move on. */
382const recordAttached = async (
383  $: Dollar,
384  line: string,
385  result: PromptSubmitResult,
386  signal: AbortSignal,
387): Promise<void> => {
388  if (signal.aborted || result.drop !== undefined || !(result.context ?? []).includes(line)) return
389  pacing.isContextForced = false
390  await update($, lastContext, () => line).catch(() => undefined)
391}
392
393/** Session-end reasons after which the same process goes on with a fresh conversation. */
394const FRESH_CONVERSATION = new Set<string>(['clear', 'resume'])
395
396/** Whether a compaction result replaced the main conversation (its GIT_STATE line may be gone). */
397const isMainCompaction = (e: SessionCompactInput, result: SessionCompactResult): boolean =>
398  result.skip === undefined && e.agentId === undefined && e.trigger !== 'precompute'
399
400/** Forces the context line on the next prompt after `/clear`, a resume, or a main compaction. */
401const registerContextResets = (on: Parameters<Register>[0]): void => {
402  on('session.end', async ($, e, next) => {
403    if (FRESH_CONVERSATION.has(e.reason)) pacing.isContextForced = true
404    return next(e)
405  }).catch((_$, e, next) => next(e))
406
407  on('session.compact', async ($, e, next) => {
408    const result = await next(e)
409    if (isMainCompaction(e, result)) pacing.isContextForced = true
410    return result
411  }).catch((_$, e, next) => next(e))
412}
413
414// ---------------------------------------------------------------------------
415// Registration
416
417/** Registers the status line, its refresh triggers and the per-prompt git context. */
418export const registerStatus = (on: Parameters<Register>[0]): void => {
419  on('session.start', async ($, e, next) => {
420    const started = await next(e)
421    startTicking($)
422    refreshLater($)
423    return started
424  })
425
426  on('tool.call', { tool: REFRESH_TOOLS }, async ($, e, next) => {
427    const result = await next(e)
428    refreshLater($)
429    return result
430  }).catch((_$, e, next) => next(e))
431
432  on('turn.complete', async ($, e, next) => {
433    const result = await next(e)
434    refreshLater($)
435    return result
436  })
437
438  on('prompt.submit', async ($, e, next) => {
439    const line = await promptContext($, next.signal).catch(() => undefined)
440    if (line === undefined || next.signal.aborted) return next(e)
441    const result = await next({ ...e, context: [...(e.context ?? []), line] })
442    await recordAttached($, line, result, next.signal)
443    return result
444  }).catch((_$, e, next) => next(e))
445
446  registerContextResets(on)
447}
448
types/index.d.ts 26 lines
1/** One `git status --porcelain=v2 --branch` reading of the project root. */
2export type GitSnapshot = {
3  /** `# branch.head`: the branch name, or `(detached)`. */
4  branch: string
5  /** `# branch.upstream`; null when the branch tracks none. */
6  upstream: string | null
7  ahead: number
8  behind: number
9  /** Entries with an index (X) change. */
10  staged: number
11  /** Entries with a worktree (Y) change, plus unmerged entries. */
12  unstaged: number
13  untracked: number
14}
15
16declare module 'claude-code' {
17  interface PluginState {
18    'git-status': {
19      /** The latest snapshot; null before the first or after a failed run. */
20      git: GitSnapshot | null
21      /** The GIT_STATE line last attached to a prompt. */
22      lastContext: string
23    }
24  }
25}
26