SLOPSHOPPER

huddle

Huddle: when two or more Claude Code sessions work in the same repo, see it before they collide, and get them to split the work with one button.

bandguardcommandtoaststatusprompt
v0.3.5MITupdated 2026-10-23Br4inergy/claude-huddle
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · huddle
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ huddle │ ⏺ Read(src/auth.ts) │ No other agents are active in this repo │ ⎿ Read 6 lines │ anymore. │ ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /huddle ⎿ huddle: No other agents are active in this repo anymore. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Huddle

Two Claude Code sessions in the same repo, about to edit the same file? Huddle sees it first, and gets them to split the work with one button.

The problem

You run several Claude Code sessions at once. One is fixing auth, another is adding a feature, a third is "just cleaning up". They don't know about each other:

  • Two agents edit the same file and one silently overwrites the other.
  • Both bump package.json or the lockfile, or both write a migration, and the merge is a mess.
  • Two sessions share one working copy and one runs git stash or checkout under the other's feet.
  • You only find out at merge time, when it's expensive.

Huddle watches for that, tells you how bad it is, and when you press Coordinate the agents agree on who owns what before they collide.

What it looks like

A band above the prompt, colored by how serious the overlap is:

■ Clash in acme-api · both edited 2 files (src/auth.ts, src/session.ts) · «SSO login» · feature/sso
▲ Another agent in acme-web · same working copy (no worktree of its own) · «Dependency bumps» · main
Coordinating is recommended.  [ Coordinate ]  [ Snooze 30 min ]

Each other session is shown by the name you see in your sidebar (or, until it has one, by the start of what it was asked), next to the repo the alert is about. In the Claude desktop app, click that name to jump to the session.

Press Coordinate (or run /huddle) and:

  1. Every other live session in the shared repos receives a short coordination protocol: who's asking, what they're doing, which files clash, and who leads.
  2. Your own session leads: it waits for their replies, then records one owner per disputed file and a 3-line summary with the agree tool, which reaches everyone. It gives you the summary.
  3. The other sessions answer the leader and keep working on what doesn't clash.

Once a huddle is going, the band changes with it:

  • Everyone who shares a repo with you is in it: one calm line instead of alerts, ✓ Huddle with 6 sessions · led by «Billing refactor» · 5/6 confirmed. A session confirms the first time it sends a message after joining. If a member edits a file the agreement gave to another member, a second soft line says so: ▲ «Auth» edited src/auth.ts (owner «SSO login»).
  • A new session shows up, or one that isn't in it: the usual alert rows for those sessions only, and the button reads Add to huddle. It sends the protocol only to them (a member that adds tells the leader, who takes the replies).

Owner warnings reach the agent while it works, not at the end of its turn: when a session edits (with a file tool or from the shell) a file another live member owns, that tool's result carries a note ("this file belongs to «B» in the agreement") and you get a toast, once per file. A huddle message that arrives while an agent is mid-turn is also copied into its next tool result, so a long run sees it within the turn.

Install

/plugin install huddle --marketplace Br4inergy/claude-huddle

Install it in every Claude Code where you run sessions. Huddle sees the sessions that have it. (A session still on 0.2.x shows up for 0.3.0 sessions, but doesn't see them.)

Levels

Judged per repo, over every repo two sessions share. A session works in its home repo (where it started) and in any other repo it edits a file in or enters from the shell (cd, git -C, pushd), for the next 4 hours. Each peer raises one alert, for the strongest repo it shares with you.

LevelWhenWhat you see
1 · infoAnother session in the same repo, in another worktree or clone, on different filesGrey line, status bar count
2 · attentionAnother session in the same working copy (shared index, stash, installs)Yellow line
3 · clashBoth sessions edited the same file in the last 4 hours, or both touched single-owner files (lockfile, package.json, migrations, schema, generated code)Red line, a toast, "Coordinating is recommended"

So a session that starts in one repo and goes on to edit ~/code/api clashes with the session that lives there. The same repo is recognized across clones and worktrees by its origin remote (or, with no remote, its git directory).

Sessions of one family

In the Claude desktop app a session can start another one. Those two already coordinate through the app, so Huddle keeps out of it: a session and the one that started it (its mother) never alert each other and never get the protocol. Two sessions started by the same mother (sisters) alert only on level 3, and that alert also reaches the mother with one short note, so she can settle who owns the files. A dim line closes the band: ◦ started by «Mother» · 2 daughters. The link comes from the app (get_session), so this works in the desktop app only; a session you move to top level is no longer a daughter. Sessions outside the family are unchanged.

Idle sessions don't alert. A session nobody has typed to and whose agent has made no tool call in the last 2 hours is left out of the band and out of the huddle's count, unless its files clash with yours.

Shell edits count. Around every Bash command Huddle compares git status (plus the size and modification time of up to 300 dirty files) in your home repo, the repos you entered recently and the directories the command names, at most 3 repos, and attributes what changed to this session. Entering a repo (cd ~/code/api && git push) is enough to show up in it. Files that merely leave the status (a commit, a revert) are not edits.

The protocol the agents follow

  • Reply to the leader (the protocol names its session id) with the send tool or SendMessage: their task, the files they edited and the files they plan to touch.
  • One owner per disputed file. Whoever goes first finishes and commits first; the other updates before touching those files. Lockfiles, package.json, migrations, schema and generated files get a single owner.
  • In a shared working copy, nobody runs checkout, stash, reset or installs dependencies without telling the other, and each commits only its own files with a pathspec (git commit -- <files>).
  • Each agent keeps to its original instruction. If committing, pushing or publishing was already part of its task, it still does it, in the agreed order and carefully. If it wasn't, coordinating is no reason to start. Coordinating is never a reason to stop doing what it was asked.
  • The leader closes with the agree tool, once: one owner per disputed file and a short summary, sent to every member.

Tools the agents get

  • peers: the other live sessions that share a repo with this one, with repo, level, task, branch and the files in conflict.
  • send: a message to one of them by session id.
  • agree: for the huddle leader only. { summary, owners: [{ repo?, path, sessionId }] } records who owns which file (repo is a repo name or key, the leader's own repo by default) and sends the summary to every member.

What it doesn't do (yet)

  • It only sees Claude Code sessions with Huddle installed. Codex, other tools or a human editing by hand are invisible to it.
  • Shell edits are inferred from git status around each command: a change that never shows as dirty (a git pull, a checkout, a file git ignores) isn't seen, and in a working copy shared by two sessions, a file the other one changes while your command runs is attributed to you unless the other session had already recorded it.
  • It doesn't lock files or block edits. It warns and gets the agents talking.
  • Sessions on different machines don't see each other. The registry is local to your computer.
  • An agent that is busy and makes no tool call gets a huddle message at the end of its turn, like any other message: the mid-turn copy and the owner warnings ride on tool calls.
  • Jumping to a session by clicking its name works in the Claude desktop app, also for a session that is not open in the window right now. In a terminal, and for a headless claude -p run started from a desktop session, the name is shown, not linked.
  • A session reads its own title from the desktop app's sidebar, or from claude.ai for a Remote Control session, only where that read needs no permission prompt; otherwise the title arrives with your next prompt.

Files

Each session keeps one small JSON file under ~/.claude/huddle/sessions/ (a headless run, one with no terminal, phone, IDE or desktop window behind it, such as a claude -p that a status line, a mod, a script or an SDK app starts, writes none until it edits something in a repo: until then it is no risk to anyone, and it doesn't show up as a nameless peer): its id, the desktop app's id for it, its sidebar title, the first 140 characters of the first prompt you typed, its language, when it was last active, the huddle it is in, and for each repo it works in the name, working-copy path, branch and the repo-relative files it edited in the last 4 hours. A huddle leader's file also holds the members, the owners and the summary. It is refreshed every 15 seconds; each session writes only its own file and reads the others'. A session gone for a day is emptied on the next check. Nothing leaves your machine except the messages Claude Code itself delivers between your own sessions.

Language

English or Spanish, following Claude Code's language setting; with none, the language of the first thing you type (Spanish when it has more Spanish than English markers), then your locale. Messages to other agents go out in the sender's language.

Development

claude plugin validate .
claude plugin test .

hooks/logic.ts holds the pure parts (levels, huddle state, the band, command parsing, messages) and is what the tests cover. hooks/register.tsx wires them into Claude Code.

License

MIT © Br4inergy

Source 4 files
hooks/register.tsx 951 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Api, Register, ToolCallResult } from 'claude-code'
3
4import type { Alert, BandState, CoordResult, Family } from '../types'
5import { type Lang, type Words, inferLang, pickLang, words } from './i18n'
6import {
7  type Presence,
8  type RepoEntry,
9  type Snapshot,
10  activeRepos,
11  addMarker,
12  compactForMidTurn,
13  assessAll,
14  bandState,
15  diffSnapshots,
16  dirsInCommand,
17  huddleMarker,
18  huddleMembers,
19  isHostId,
20  isLive,
21  isSeenSession,
22  leadPrompt,
23  leaderOf,
24  liveHuddle,
25  motherOf,
26  nameOf,
27  newHuddleId,
28  normalizeRemote,
29  parentFromSession,
30  ownerKey,
31  ownerOf,
32  parseAddMarker,
33  parseHuddleMarker,
34  parsePorcelain,
35  peerMessage,
36  reasonOf,
37  repoNameOf,
38  repoRelative,
39  resolvePath,
40  sameJson,
41  sessionLink,
42  shouldPublish,
43  sisterNotice,
44  shouldRefreshTitle,
45  slashes,
46  stripMarkers,
47  taskFromPrompt,
48  titleFromSessionAnswer,
49  upgradePresence,
50  FILE_WINDOW_MS,
51} from './logic'
52
53const alerts = atom({ plugin: 'huddle', key: 'alerts' } as const, [] as Alert[])
54const band = atom({ plugin: 'huddle', key: 'band' } as const, { kind: 'none' } as BandState)
55const snoozeUntil = atom({ plugin: 'huddle', key: 'snoozeUntil' } as const, 0)
56const lastCoord = atom({ plugin: 'huddle', key: 'lastCoord' } as const, null as CoordResult | null)
57
58const TICK_MS = 15_000
59const SNOOZE_MS = 30 * 60_000
60const STALE_MS = 24 * 60 * 60_000
61const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
62const HUMAN_ORIGINS = new Set<string>(['composer', 'bridge', 'sdk'])
63// The desktop app's own read of a session: its sidebar title. Asked only when it runs without a permission prompt.
64const GET_SESSION = 'mcp__ccd_session_mgmt__get_session'
65// A Remote Control session's title lives in claude.ai: read there when the desktop app has none to give.
66const GET_REMOTE_SESSION = 'mcp__claude-code-remote__get_session'
67const LEVEL_MARK = { 1: '◦', 2: '▲', 3: '■' } as const
68const LEVEL_COLOR = { 1: 'subtle', 2: 'warning', 3: 'error' } as const
69// A shell command is watched in at most this many repos; git gets this long to list a repo's dirty files.
70const SNAPSHOT_REPOS = 3
71const SNAPSHOT_MS = 3000
72const STAT_CAP = 300
73const NEGATIVE_MS = 60_000
74const PENDING_MAX = 5
75const LIST_TIMEOUT_MS = 5000
76const TOOL_LOOKS_MAX = 12
77const ID_RE = /^[A-Za-z0-9_-]{1,80}$/
78
79// The module's own variables: a reload starts them over and session.start fills them again.
80let me: Presence | null = null
81let dir = ''
82let homeDir = ''
83let w: Words = words('en')
84// What the person's own first prompt read as (Spanish or English), for when no setting says.
85let inferred: Lang | null = null
86// Peer+repo+level triples already toasted, so an alert is raised once per escalation.
87const toasted = new Set<string>()
88// Files already toasted as taken by another member of the huddle.
89const warned = new Set<string>()
90let ticks = 0
91// The desktop app's id from the environment. A `claude -p` started from a desktop session inherits it, so it is
92// taken as this session's own only once someone sees the session (isSeenSession): a headless run never is.
93let envHostId = ''
94// Whether someone sees this session (isSeenSession). Until then it takes no desktop id and, until it edits something,
95// writes no presence (shouldPublish).
96let seen = false
97let toolLooks = 0
98// A turn is running between prompt.submit and turn.complete: huddle messages are also copied into its next tool result.
99let busy = false
100let pending: string[] = []
101// The peers as the last tick read them, for names and liveness between ticks.
102let peersSeen: Presence[] = []
103// directory -> its git top level ('' when it is not in a repo, remembered for a minute); top level -> repo identity.
104const topCache = new Map<string, { top: string; at: number }>()
105const identityCache = new Map<string, { repoKey: string; repoName: string }>()
106
107/** Claude Code's `language` setting, then what the person writes, then LC_ALL/LANG; English by default. */
108async function detectLang($: Api): Promise<Lang> {
109  const settings = (await $.settings.read().catch(() => ({}))) as { language?: unknown }
110  const locale = (await $.env.get('LC_ALL').catch(() => null)) || (await $.env.get('LANG').catch(() => null)) || null
111  return pickLang(undefined, settings.language, locale, inferred)
112}
113
114/** `p`, or undefined when it fails or takes longer than `ms`. */
115function withTimeout<T>($: Api, p: Promise<T>, ms: number): Promise<T | undefined> {
116  return new Promise(resolve => {
117    const t = $.clock.after(ms, () => resolve(undefined))
118    p.then(
119      v => {
120        t.cancel()
121        resolve(v)
122      },
123      () => {
124        t.cancel()
125        resolve(undefined)
126      },
127    )
128  })
129}
130
131async function git($: Api, cwd: string, args: string[]) {
132  const r = await $.process.run(['git', ...args], { cwd, timeoutMs: 5000 })
133  return r.exitCode === 0 ? r.stdout.trim() : ''
134}
135
136/** `git -C <dir> ...`, '' on any failure (no such directory, not a repo, timeout). */
137async function gitC($: Api, where: string, args: string[]) {
138  const r = await $.process.run(['git', '-C', where, ...args], { timeoutMs: 5000 }).catch(() => null)
139  return r && r.exitCode === 0 ? r.stdout.trim() : ''
140}
141
142async function save($: Api) {
143  if (!me || !shouldPublish(seen, me)) return
144  const now = await $.clock.now()
145  me.lastSeen = now
146  me.repos[me.home]!.seenAt = now
147  // Only what still counts is kept: files edited in the last 4 hours, repos seen in the last 4 hours.
148  for (const [key, repo] of Object.entries(me.repos)) {
149    for (const [file, at] of Object.entries(repo.files)) if (now - at >= FILE_WINDOW_MS) delete repo.files[file]
150    if (key !== me.home && now - (repo.seenAt ?? 0) >= FILE_WINDOW_MS) delete me.repos[key]
151  }
152  await $.fs.write(`${dir}/${me.sessionId}.json`, JSON.stringify(me))
153}
154
155async function readPeers($: Api, now: number): Promise<Presence[]> {
156  const peers: Presence[] = []
157  for (const entry of await $.fs.list(dir)) {
158    if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
159    const path = `${dir}/${entry.name}`
160    try {
161      const text = await $.fs.read(path)
162      if (!text) continue
163      const p = upgradePresence(JSON.parse(text))
164      if (!p) continue
165      if (now - p.lastSeen > STALE_MS) {
166        // No delete in $.fs: a session gone for a day is emptied, and an empty file is skipped.
167        await $.fs.write(path, '').catch(() => null)
168        continue
169      }
170      peers.push(p)
171    } catch {
172      // half-written by a peer this instant, or emptied when stale; the next tick reads it
173    }
174  }
175  peersSeen = peers
176  return peers
177}
178
179/** Asks one `get_session` tool, if it is there and runs without a permission prompt; its parsed answer, or undefined. */
180async function askSession($: Api, tools: readonly { name: string }[], input: { tool: string } & Record<string, unknown>) {
181  if (!tools.some(t => t.name === input.tool)) return undefined
182  const { tool, ...args } = input
183  const { decision } = await $.tool.check({ tool, input: args } as never)
184  if (decision !== 'allow') return undefined
185  const { text } = (await $.tool.call(input as never)) as { text?: string }
186  return text ? (JSON.parse(text) as unknown) : undefined
187}
188
189/** This session's title: the desktop app's sidebar, else claude.ai's for a Remote Control session. */
190async function refreshTitle($: Api) {
191  if (!me) return
192  const tools = await $.tool.list()
193  if (me.hostId) {
194    const answer = await askSession($, tools, { tool: GET_SESSION, session_id: 'self' }).catch(() => undefined)
195    const title = titleFromSessionAnswer(answer)
196    if (title) me.title = title
197    // The session that started this one, while the person has not moved it to top level.
198    if (answer) me.parentHostId = parentFromSession(answer)
199    if (title) return
200  }
201  const remote = titleFromSessionAnswer(await askSession($, tools, { tool: GET_REMOTE_SESSION }).catch(() => undefined))
202  if (remote) me.title = remote
203}
204
205/** Tells the mother, once, that two of her daughters edit the same files. Best effort; only when she is live. */
206async function tellMother($: Api, peers: Presence[], sisters: Alert[], now: number) {
207  const mother = me && motherOf(me, peers, now)
208  if (!me || !mother || sisters.length === 0) return
209  await $.session.send({ to: { sessionId: mother.sessionId }, text: sisterNotice(w, me, sisters) }).catch(() => null)
210}
211
212/** Opens a session of the desktop app by its own link, through the OS: the band may be drawn where links can't. */
213async function openSession($: Api, hostId: string) {
214  // `start` goes through cmd on Windows: only an id the app could have written reaches it.
215  if (!isHostId(hostId)) return
216  const url = sessionLink(hostId)
217  const isWindows = (await $.env.get('OS')) === 'Windows_NT'
218  const tries = isWindows ? [['cmd', '/c', 'start', '', url]] : [['open', url], ['xdg-open', url]]
219  for (const argv of tries) {
220    const r = await $.process.run(argv, { timeoutMs: 5000 }).catch(() => null)
221    if (r?.exitCode === 0) return
222  }
223  $.ui.toast(w.openFailed)
224}
225
226// ---- Repos: which one a file or a directory belongs to ----
227
228/** The git top level of a directory (or of the nearest parent that is a repo, for a folder a Write is about to
229 * create); '' when it is in none. Remembered per directory. */
230async function toplevelOf($: Api, start: string): Promise<string> {
231  const now = await $.clock.now()
232  let d = slashes(start)
233  const tried: string[] = []
234  for (let i = 0; i < 5 && d; i++) {
235    const hit = topCache.get(d)
236    let top = ''
237    if (hit && (hit.top || now - hit.at < NEGATIVE_MS)) top = hit.top
238    else {
239      top = slashes(await gitC($, d, ['rev-parse', '--show-toplevel']))
240      topCache.set(d, { top, at: now })
241    }
242    if (top) {
243      for (const t of tried) topCache.set(t, { top, at: now })
244      return top
245    }
246    tried.push(d)
247    const parent = d.replace(/\/[^/]*$/, '')
248    if (!parent || parent === d) break
249    d = parent
250  }
251  return ''
252}
253
254/** A repo's key and name: its normalized origin, else its absolute git directory (as session.start does). */
255async function identityOf($: Api, toplevel: string): Promise<{ repoKey: string; repoName: string }> {
256  const cached = identityCache.get(toplevel)
257  if (cached) return cached
258  const remote = await gitC($, toplevel, ['config', '--get', 'remote.origin.url'])
259  const commonDir = remote ? '' : await gitC($, toplevel, ['rev-parse', '--path-format=absolute', '--git-common-dir'])
260  const repoKey = remote ? normalizeRemote(remote) : slashes(commonDir || toplevel)
261  const id = { repoKey, repoName: repoNameOf(repoKey, toplevel) }
262  if (identityCache.size > 200) identityCache.clear()
263  identityCache.set(toplevel, id)
264  return id
265}
266
267/** The session's entry for the repo at `toplevel`, made when it is the first time it is edited or entered. */
268async function noteRepo($: Api, toplevel: string, now: number): Promise<RepoEntry | null> {
269  if (!me || !toplevel) return null
270  const byTop = Object.values(me.repos).find(r => r.toplevel === toplevel)
271  const known = byTop ?? me.repos[(await identityOf($, toplevel)).repoKey]
272  if (known) {
273    known.seenAt = now
274    return known
275  }
276  const id = await identityOf($, toplevel)
277  const entry: RepoEntry = {
278    ...id,
279    toplevel,
280    branch: await gitC($, toplevel, ['rev-parse', '--abbrev-ref', 'HEAD']),
281    files: {},
282    seenAt: now,
283  }
284  me.repos[id.repoKey] = entry
285  return entry
286}
287
288// ---- Edits: through the file tools, and through the shell (what a command changed in the repos it works in) ----
289
290type Hit = { repoKey: string; repoName: string; rel: string }
291type Watched = { top: string; entry: RepoEntry; snap: Snapshot | null; startedAt: number }
292
293/** One repo's dirty files and, for at most 300 of them, a signature of mtime and size. Null when git can't say. */
294async function snapshot($: Api, top: string, prefer?: Snapshot | null): Promise<Snapshot | null> {
295  const r = await $.process
296    .run(['git', '-C', top, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], { timeoutMs: SNAPSHOT_MS })
297    .catch(() => null)
298  if (!r || r.exitCode !== 0) return null
299  const status = parsePorcelain(r.stdout)
300  const snap: Snapshot = {}
301  for (const [path, st] of Object.entries(status)) snap[path] = { status: st }
302  // The files the first snapshot signed come first, so the two can be compared.
303  const paths = Object.keys(snap).sort((a, b) => Number(prefer?.[b]?.sig !== undefined) - Number(prefer?.[a]?.sig !== undefined))
304  await Promise.all(
305    paths.slice(0, STAT_CAP).map(async path => {
306      const st = await $.fs.stat(`${top}/${path}`).catch(() => null)
307      if (st) snap[path]!.sig = `${st.mtimeMs}:${st.size}`
308    }),
309  )
310  return snap
311}
312
313/** Before a shell command: the repos to watch (home, the directories it names, those visited in the last 4 h),
314 * each with its dirty files. A command that enters a repo makes this session visit it. */
315async function beforeBash($: Api, command: string): Promise<Watched[]> {
316  if (!me) return []
317  const now = await $.clock.now()
318  const cwd = slashes(await $.session.cwd().catch(() => me!.cwd))
319  const named = new Set<string>()
320  for (const d of dirsInCommand(command, cwd, homeDir).slice(0, 6)) {
321    const top = await toplevelOf($, d)
322    if (top) named.add(top)
323  }
324  const tops = [me.repos[me.home]!.toplevel]
325  for (const top of named) tops.push(top)
326  const recent = Object.values(me.repos)
327    .filter(r => r.repoKey !== me!.home && now - (r.seenAt ?? 0) < FILE_WINDOW_MS)
328    .sort((a, b) => (b.seenAt ?? 0) - (a.seenAt ?? 0))
329  for (const r of recent) tops.push(r.toplevel)
330
331  const watched: Watched[] = []
332  let entered = false
333  for (const top of named) {
334    const before = Object.keys(me.repos).length
335    await noteRepo($, top, now)
336    if (Object.keys(me.repos).length !== before) entered = true
337  }
338  for (const top of [...new Set(tops)].slice(0, SNAPSHOT_REPOS)) {
339    const entry = Object.values(me.repos).find(r => r.toplevel === top) ?? (await noteRepo($, top, now))
340    if (entry) watched.push({ top, entry, snap: null, startedAt: now })
341  }
342  await Promise.all(watched.map(async t => (t.snap = await snapshot($, t.top))))
343  if (entered) save($).catch(() => {})
344  return watched
345}
346
347/** After it: what changed in those repos is this session's edit. */
348async function afterBash($: Api, watched: Watched[]): Promise<Hit[]> {
349  const now = await $.clock.now()
350  const hits: Hit[] = []
351  if (!watched.some(t => t.snap)) return hits
352  const peers = (await readPeers($, now).catch(() => peersSeen)).filter(p => p.sessionId !== me?.sessionId && isLive(p, now))
353  await Promise.all(
354    watched.map(async t => {
355      if (!t.snap) return
356      const after = await snapshot($, t.top, t.snap)
357      if (!after) return
358      for (const rel of diffSnapshots(t.snap, after)) {
359        // In a shared working copy another session may have written meanwhile: what it recorded is not ours.
360        if (peers.some(p => (p.repos[t.entry.repoKey]?.files[rel] ?? 0) >= t.startedAt)) continue
361        t.entry.files[rel] = now
362        t.entry.seenAt = now
363        hits.push({ repoKey: t.entry.repoKey, repoName: t.entry.repoName, rel })
364      }
365    }),
366  )
367  return hits
368}
369
370/** A write through Edit/Write/MultiEdit/NotebookEdit: the file's own repo, wherever it is. */
371async function afterEdit($: Api, input: { file_path?: string; notebook_path?: string }): Promise<Hit[]> {
372  if (!me) return []
373  const given = input.file_path ?? input.notebook_path
374  if (!given) return []
375  const path = resolvePath(slashes(await $.session.cwd().catch(() => me!.cwd)), given)
376  const top = await toplevelOf($, path.replace(/\/[^/]*$/, '') || '/')
377  const now = await $.clock.now()
378  const entry = await noteRepo($, top, now)
379  if (!entry) return []
380  let rel = repoRelative(top, path)
381  if (!rel) {
382    // git spells the top level with symbolic links resolved; the tool may not have.
383    const real = (await $.fs.stat(path, { resolve: true }).catch(() => null))?.realPath
384    rel = real ? repoRelative(top, real) : null
385  }
386  if (!rel) return []
387  entry.files[rel] = now
388  return [{ repoKey: entry.repoKey, repoName: entry.repoName, rel }]
389}
390
391// ---- Huddle ----
392
393/** The leader's lead as it is now on disk (a member reads it fresh: the agreement may be seconds old). */
394async function currentLead($: Api) {
395  if (!me?.huddle) return undefined
396  if (me.huddle.leaderId === me.sessionId) return me.huddle.lead
397  try {
398    return upgradePresence(JSON.parse(await $.fs.read(`${dir}/${me.huddle.leaderId}.json`)))?.huddle?.lead
399  } catch {
400    return leaderOf(me, peersSeen)?.huddle?.lead
401  }
402}
403
404/** Notes for edits that fall on a file the agreement gave to another live member; a toast the first time per file. */
405async function ownerNotes($: Api, hits: Hit[]): Promise<string[]> {
406  if (!me || hits.length === 0 || !me.huddle) return []
407  const lead = await currentLead($)
408  if (!lead) return []
409  const now = await $.clock.now()
410  const notes: string[] = []
411  for (const hit of hits) {
412    const ownerId = ownerOf(lead, hit.repoKey, hit.rel)
413    if (!ownerId || ownerId === me.sessionId) continue
414    const owner = peersSeen.find(p => p.sessionId === ownerId)
415    if (!owner || !isLive(owner, now)) continue
416    const name = nameOf(w, owner)
417    notes.push(w.ownerConflict(hit.rel, name))
418    const key = ownerKey(hit.repoKey, hit.rel)
419    if (!warned.has(key)) {
420      warned.add(key)
421      $.ui.toast(w.toastOwner(hit.rel, name))
422    }
423  }
424  return notes
425}
426
427/** A member's first message to anyone after joining confirms the huddle. */
428async function markAck($: Api) {
429  const h = me?.huddle
430  if (!me || !h || h.leaderId === me.sessionId || h.ackAt) return
431  h.ackAt = await $.clock.now()
432  await save($)
433}
434
435async function onReceive($: Api, e: { text: string }) {
436  if (!me) return
437  const now = await $.clock.now()
438  const add = parseAddMarker(e.text)
439  const lead = me.huddle?.leaderId === me.sessionId ? me.huddle.lead : undefined
440  if (add && lead && me.huddle?.id === add.id) {
441    lead.members = [...new Set([...lead.members, ...add.sessionIds.filter(id => id !== me!.sessionId)])]
442    await save($)
443  }
444  const marker = parseHuddleMarker(e.text)
445  if (marker && marker.leaderId !== me.sessionId) {
446    // A leader keeps its own huddle; anyone else follows the latest one that reached it.
447    const mine = me.huddle
448    if (!mine || (mine.id !== marker.id && mine.leaderId !== me.sessionId)) {
449      me.huddle = { id: marker.id, leaderId: marker.leaderId, joinedAt: now }
450      await save($)
451    }
452  }
453  if (busy && (marker || add)) {
454    const leader = marker && peersSeen.find(p => p.sessionId === marker.leaderId)
455    const from = leader ? nameOf(w, leader) : w.aMember
456    pending = [...pending, w.midTurnNote(from, compactForMidTurn(e.text))].slice(-PENDING_MAX)
457  }
458}
459
460async function onPrompt($: Api, e: { text: string; origin: { kind: string } }) {
461  busy = true
462  if (!me || !HUMAN_ORIGINS.has(e.origin.kind)) return
463  me.lastActiveAt = await $.clock.now()
464  const task = taskFromPrompt(e.text)
465  if (task && !me.task) {
466    me.task = task
467    // The first thing the person types says which language they work in.
468    inferred = inferLang(e.text.slice(0, 2000)) ?? inferred
469    const lang = await detectLang($)
470    w = words(lang)
471    me.lang = lang
472  }
473  save($).catch(() => {})
474}
475
476/** What a tool call adds after it ran: ownership notes for what it edited, and huddle messages that arrived mid-turn. */
477async function afterTool(
478  $: Api,
479  e: { tool: string; agentId?: string; file_path?: string; notebook_path?: string },
480  ran: ToolCallResult,
481  watched: Watched[],
482): Promise<ToolCallResult> {
483  if (ran.deny !== undefined) return ran
484  const notes: string[] = []
485  let hits: Hit[] = []
486  if (e.tool === 'Bash') hits = await afterBash($, watched)
487  else if (EDIT_TOOLS.has(e.tool) && !ran.isError) hits = await afterEdit($, e)
488  if (hits.length) {
489    notes.push(...(await ownerNotes($, hits)))
490    save($).catch(() => {})
491    refresh($).catch(() => {})
492  }
493  if (!e.agentId && pending.length) {
494    notes.push(...pending)
495    pending = []
496  }
497  return notes.length ? { ...ran, context: [...(ran.context ?? []), ...notes] } : ran
498}
499
500/** One look at the peers. `timer` marks the clock's own tick: only those count toward re-reading the title. */
501async function refresh($: Api, timer = false) {
502  if (!me) return
503  if (!seen) {
504    const surfaces = await $.session.surfaces().catch(() => [])
505    // The desktop's tools are there from the start (or within its first minutes): a run without them by then is headless,
506    // and only a surface can still make it seen. That spares a long SDK run a tool list every tick.
507    const look = surfaces.length === 0 && toolLooks < TOOL_LOOKS_MAX
508    if (look) toolLooks++
509    const tools = look ? ((await withTimeout($, $.tool.list(), LIST_TIMEOUT_MS)) ?? []).map(t => t.name) : []
510    seen = isSeenSession(seen, surfaces, tools)
511  }
512  if (!me.hostId && seen && isHostId(envHostId)) me.hostId = envHostId
513  if (timer && shouldRefreshTitle(ticks++)) await refreshTitle($).catch(() => {})
514  const now = await $.clock.now()
515  await Promise.all(
516    activeRepos(me, now)
517      .slice(0, 5)
518      .map(async r => (r.branch = (await gitC($, r.toplevel, ['rev-parse', '--abbrev-ref', 'HEAD'])) || r.branch)),
519  )
520  await save($)
521  const peers = await readPeers($, now)
522  // A huddle nobody in it keeps alive is over (unless this session only just joined and the leader's file is not in yet).
523  if (me.huddle && now - me.huddle.joinedAt > 2 * 60_000 && !liveHuddle(me, peers, now)) me.huddle = undefined
524
525  const all = assessAll(me, peers, now)
526  const state = bandState(me, peers, now)
527  if (!sameJson(await read($, alerts), all)) await update($, alerts, () => all)
528  if (!sameJson(await read($, band), state)) await update($, band, () => state)
529
530  if (state.kind === 'alert') {
531    const snoozed = (await read($, snoozeUntil)) > now
532    for (const a of state.alerts) {
533      const key = `${a.sessionId}:${a.repoKey}:${a.level}`
534      if (a.level < 3 || toasted.has(key) || snoozed) continue
535      toasted.add(key)
536      $.ui.toast(w.toastClash(a.repoName, reasonOf(w, a)))
537      if (a.family === 'sister') void tellMother($, peers, [a], now)
538    }
539    $.ui.status(w.status(state.alerts.length + 1, state.alerts[0]!.repoName))
540  } else {
541    $.ui.status(state.kind === 'huddle' ? w.statusHuddle(state.size) : undefined)
542  }
543}
544
545/** Starts a huddle with every live peer in the shared repos, or adds those who are not yet in the one that is live.
546 * Answers what the toast says. */
547async function coordinate($: Api): Promise<string> {
548  if (!me) return w.commandNotRepo
549  // Titles are what the person sees in the messages: take this session's and the peers' as they are now.
550  await refreshTitle($).catch(() => {})
551  const now = await $.clock.now()
552  const peers = await readPeers($, now)
553  const current = assessAll(me, peers, now)
554  const members = huddleMembers(me, peers, now)
555  const targets = current.filter(a => !members?.has(a.sessionId))
556  if (targets.length === 0) {
557    const told = current.length ? w.toastAllIn : w.toastNoPeers
558    $.ui.toast(told)
559    return told
560  }
561  if (!members) {
562    me.huddle = {
563      id: newHuddleId(me.sessionId, now),
564      leaderId: me.sessionId,
565      joinedAt: now,
566      lead: { members: [], owners: {}, createdAt: now },
567    }
568  }
569  const h = me.huddle!
570  const isLeader = h.leaderId === me.sessionId
571  if (isLeader && !h.lead) h.lead = { members: [], owners: {}, createdAt: now }
572
573  const sent: string[] = []
574  const failed: string[] = []
575  for (const a of targets) {
576    const r = await $.session
577      .send({ to: { sessionId: a.sessionId }, text: peerMessage(w, me, a, now, { id: h.id, leaderId: h.leaderId }) })
578      .catch(err => ({ isDelivered: false as const, reason: String(err) }))
579    if (r.isDelivered) sent.push(a.sessionId)
580    else failed.push(`${a.sessionId.slice(0, 8)}: ${r.reason}`)
581  }
582  // Sisters clash on the same files: their mother hears of it once, and the alert loop doesn't repeat it.
583  const sisters = targets.filter(a => a.family === 'sister')
584  if (sisters.length) {
585    for (const a of sisters) toasted.add(`${a.sessionId}:${a.repoKey}:${a.level}`)
586    await tellMother($, peers, sisters, now)
587  }
588  const names = targets.filter(a => sent.includes(a.sessionId)).map(a => nameOf(w, a)).join(', ')
589  if (sent.length) {
590    if (isLeader) h.lead!.members = [...new Set([...h.lead!.members, ...sent])]
591    // A member that adds tells the leader, who keeps the list and takes the replies.
592    else void $.session.send({ to: { sessionId: h.leaderId }, text: w.addedNotice(names, addMarker(h.id, sent)) }).catch(() => null)
593  }
594  await save($)
595  await update($, lastCoord, () => ({ at: now, sent: sent.length, failed }))
596  const told = failed.length ? w.toastPartial(sent.length, failed.length) : members ? w.toastAdded(sent.length) : w.toastSent(sent.length)
597  $.ui.toast(told)
598  if (!members) void $.prompt.submit({ text: leadPrompt(w, me, targets, sent) })
599  else if (isLeader && sent.length) void $.prompt.submit({ text: w.leadAdded(names) })
600  refresh($).catch(() => {})
601  return told
602}
603
604type AgreeInput = { summary?: unknown; owners?: unknown }
605
606/** The `agree` tool: the leader records who owns which file and tells every member. */
607async function agree($: Api, input: AgreeInput): Promise<{ result: string } | { deny: string }> {
608  const h = me?.huddle
609  if (!me || !h) return { deny: w.agreeNoHuddle }
610  if (h.leaderId !== me.sessionId || !h.lead) return { deny: w.agreeNotLeader }
611  const summary = typeof input.summary === 'string' ? input.summary.trim() : ''
612  const given = Array.isArray(input.owners) ? (input.owners as { repo?: unknown; path?: unknown; sessionId?: unknown }[]) : []
613  if (!summary || given.length === 0) return { deny: w.agreeBadInput }
614
615  const now = await $.clock.now()
616  const peers = await readPeers($, now)
617  const everyone = [me, ...peers]
618  const repos = everyone.flatMap(p => Object.values(p.repos))
619  const owners: Record<string, string> = {}
620  const lines: string[] = []
621  for (const o of given) {
622    const sessionId = typeof o.sessionId === 'string' ? o.sessionId : ''
623    let path = typeof o.path === 'string' ? slashes(o.path).replace(/^\.\//, '') : ''
624    if (!ID_RE.test(sessionId) || !path) return { deny: w.agreeBadInput }
625    const asked = typeof o.repo === 'string' ? o.repo.trim() : ''
626    let repo = asked
627      ? repos.find(r => r.repoKey === asked) ?? repos.find(r => r.repoName.toLowerCase() === asked.toLowerCase())
628      : me.repos[me.home]
629    if (!repo) return { deny: w.agreeBadRepo(asked) }
630    if (!asked) {
631      // An absolute path names its own repo.
632      const inside = repos.find(r => repoRelative(r.toplevel, path) !== null)
633      if (inside && path.startsWith('/')) repo = inside
634    }
635    path = repoRelative(repo.toplevel, path) ?? path
636    owners[ownerKey(repo.repoKey, path)] = sessionId
637    const owner = everyone.find(p => p.sessionId === sessionId)
638    lines.push(`- ${repo.repoName}/${path} → ${owner ? nameOf(w, owner) : sessionId.slice(0, 8)} (${sessionId})`)
639  }
640
641  h.lead.owners = owners
642  h.lead.summary = summary
643  h.lead.agreedAt = now
644  const text = w.agreeMessage({ summary, owners: lines, marker: huddleMarker(h.id, me.sessionId) })
645  const memberIds = new Set([...h.lead.members, ...peers.filter(p => p.huddle?.id === h.id).map(p => p.sessionId)])
646  memberIds.delete(me.sessionId)
647  let sent = 0
648  let failed = 0
649  for (const id of memberIds) {
650    if (!peers.some(p => p.sessionId === id && isLive(p, now))) continue
651    const r = await $.session.send({ to: { sessionId: id }, text }).catch(() => ({ isDelivered: false as const }))
652    if (r.isDelivered) sent++
653    else failed++
654  }
655  await save($)
656  refresh($).catch(() => {})
657  return { result: w.agreeDone(sent, failed) }
658}
659
660export const register: Register = on => {
661  on('session.start', async ($, e, next) => {
662    const started = await next(e)
663    const cwd = await $.session.cwd()
664    const toplevel = await git($, cwd, ['rev-parse', '--show-toplevel'])
665    if (!toplevel) {
666      w = words(await detectLang($))
667      return started
668    }
669
670    const commonDir = await git($, cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir'])
671    const remote = await git($, cwd, ['config', '--get', 'remote.origin.url'])
672    const repoKey = remote ? normalizeRemote(remote) : slashes(commonDir)
673    const now = await $.clock.now()
674    homeDir = slashes((await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || '')
675    dir = `${homeDir}/.claude/huddle/sessions`
676
677    const home: RepoEntry = {
678      repoKey,
679      repoName: repoNameOf(repoKey, slashes(toplevel)),
680      toplevel: slashes(toplevel),
681      branch: await git($, cwd, ['rev-parse', '--abbrev-ref', 'HEAD']),
682      files: {},
683      seenAt: now,
684    }
685    me = {
686      v: 2,
687      sessionId: await $.session.id(),
688      cwd,
689      home: repoKey,
690      repos: { [repoKey]: home },
691      task: '',
692      hostId: undefined,
693      startedAt: now,
694      lastSeen: now,
695      lastActiveAt: now,
696    }
697    // A reload keeps the session: pick up what this session already recorded.
698    try {
699      const saved = upgradePresence(JSON.parse(await $.fs.read(`${dir}/${me.sessionId}.json`)))
700      if (saved) {
701        me.task = saved.task
702        me.title = saved.title
703        me.parentHostId = saved.parentHostId
704        me.huddle = saved.huddle
705        me.startedAt = saved.startedAt
706        me.lastActiveAt = saved.lastActiveAt
707        me.repos = { ...saved.repos, [repoKey]: { ...home, files: saved.repos[repoKey]?.files ?? {} } }
708        if (saved.task) inferred = inferLang(saved.task)
709      }
710    } catch {
711      // first start
712    }
713    // Read here too: after a reload the task is already known and the first prompt never comes again.
714    envHostId = (await $.env.get('CLAUDE_CODE_HOST_SESSION_ID').catch(() => undefined)) || ''
715    const lang = await detectLang($)
716    w = words(lang)
717    me.lang = lang
718
719    await $.command.register({ name: 'huddle', description: w.commandDescription })
720    await $.tool.register({ name: 'peers', description: w.toolPeers })
721    await $.tool.register({
722      name: 'send',
723      description: w.toolSend,
724      inputSchema: {
725        type: 'object',
726        properties: { sessionId: { type: 'string' }, text: { type: 'string' } },
727        required: ['sessionId', 'text'],
728      },
729    })
730    await $.tool.register({
731      name: 'agree',
732      description: w.toolAgree,
733      inputSchema: {
734        type: 'object',
735        properties: {
736          summary: { type: 'string' },
737          owners: {
738            type: 'array',
739            items: {
740              type: 'object',
741              properties: { repo: { type: 'string' }, path: { type: 'string' }, sessionId: { type: 'string' } },
742              required: ['path', 'sessionId'],
743            },
744          },
745        },
746        required: ['summary', 'owners'],
747      },
748    })
749
750    await refresh($, true)
751    $.clock.every(TICK_MS, () => void refresh($, true).catch(() => {}))
752    return started
753  })
754
755  on('command.run', { command: 'huddle' }, async $ => ({ text: await coordinate($) }))
756
757  on('prompt.submit', async ($, e, next) => {
758    // The task is what a person asked: typed, sent from a phone or an SDK host; never a peer's or a plugin's text.
759    await onPrompt($, e).catch(() => {})
760    return next(e)
761  })
762
763  on('turn.complete', async ($, e, next) => {
764    if (!e.agentId) busy = false
765    return next(e)
766  })
767
768  // Outside the desktop app the title comes with the prompt (a /rename in the terminal, say).
769  on('classic.UserPromptSubmit', async ($, e, next) => {
770    if (me && e.session_title && e.session_title !== me.title) {
771      me.title = e.session_title.slice(0, 120)
772      save($).catch(() => {})
773    }
774    return next(e)
775  })
776
777  on('tool.call', async ($, e, next) => {
778    // A shell command is looked at before and after: what changed in between is this session's edit.
779    let watched: Watched[] = []
780    try {
781      if (me) {
782        me.lastActiveAt = await $.clock.now()
783        if (e.tool === 'Bash') watched = await beforeBash($, e.command)
784      }
785    } catch {
786      // watching is best effort; the command still runs
787    }
788    const ran = await next(e)
789    if (!me) return ran
790    // Recording never changes the tool's result: the edit already happened.
791    return afterTool($, e as never, ran, watched).catch(() => ran)
792  })
793
794  // The engine's tool names don't list a mod's own tools: the exact name is cast, so matching stays a plain string match.
795  on('tool.call', { tool: 'mcp__huddle__peers' as never }, async $ => {
796    try {
797      const list = await read($, alerts)
798      return { result: list.length ? JSON.stringify(list, null, 2) : w.peersNone }
799    } catch (err) {
800      return { deny: `huddle: ${String(err)}` }
801    }
802  })
803
804  on('tool.call', { tool: 'mcp__huddle__send' as never }, async ($, e) => {
805    const { sessionId, text } = e as unknown as { sessionId: string; text: string }
806    try {
807      const r = await $.session.send({ to: { sessionId }, text })
808      if (r.isDelivered) await markAck($).catch(() => {})
809      return r.isDelivered ? { result: w.delivered } : { deny: w.notDelivered(r.reason) }
810    } catch (err) {
811      return { deny: w.notDelivered(String(err)) }
812    }
813  })
814
815  on('tool.call', { tool: 'mcp__huddle__agree' as never }, async ($, e) => {
816    try {
817      return await agree($, e as unknown as AgreeInput)
818    } catch (err) {
819      return { deny: `huddle: ${String(err)}` }
820    }
821  })
822
823  // Joining a huddle is a matter of reading its marker; the message itself is always delivered.
824  on('session.receive', async ($, e, next) => {
825    await onReceive($, e).catch(() => {})
826    return next(e)
827  })
828
829  on('session.send', async ($, e, next) => {
830    const r = await next(e)
831    if (r.isDelivered) await markAck($).catch(() => {})
832    return r
833  })
834
835  on('session.end', async ($, e, next) => {
836    if (me) {
837      me.ended = true
838      await save($).catch(() => {})
839    }
840    return next(e)
841  })
842
843  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
844    const state = await read($, band)
845    const now = await $.clock.now()
846    if (!me || e.props.hasSurvey || state.kind === 'none') return next(e)
847    const { Box, Button, Text } = $.ui.resolve(e)
848
849    // The dim family line closes every band: who started this session, how many it started.
850    const fam: Family | undefined = state.family
851    const mother = fam?.mother
852    const familyRow = fam && (
853      <Box flexDirection="row" gap={1}>
854        {mother?.hostId ? (
855          <Button key="open-mother" plain onPress={() => openSession($, mother.hostId)}>
856            <Text dimColor underline>
857              ◦ {w.familyBy} {nameOf(w, mother)}
858            </Text>
859          </Button>
860        ) : (
861          <Text dimColor>◦ {mother ? w.familyMother(nameOf(w, mother)) : ''}</Text>
862        )}
863        {fam.daughters > 0 && <Text dimColor>{mother ? '· ' : ''}{w.familyDaughters(fam.daughters)}</Text>}
864      </Box>
865    )
866
867    if (state.kind === 'family') {
868      return (
869        <Box flexDirection="column" marginTop={1}>
870          {familyRow}
871        </Box>
872      )
873    }
874
875    if (state.kind === 'huddle') {
876      const led = state.leader
877      return (
878        <Box flexDirection="column" marginTop={1}>
879          <Box flexDirection="row" gap={1}>
880            <Text color="success">
881              ✓ {w.huddleWith(state.size)} · {state.leaderIsMe ? w.ledByYou : w.ledBy}
882            </Text>
883            {!state.leaderIsMe &&
884              (led.hostId ? (
885                <Button key="open-leader" plain onPress={() => openSession($, led.hostId)}>
886                  <Text color="success" underline>
887                    {nameOf(w, led)}
888                  </Text>
889                </Button>
890              ) : (
891                <Text color="success">{nameOf(w, led)}</Text>
892              ))}
893            <Text dimColor>· {w.confirmed(state.confirmed, state.size)}</Text>
894          </Box>
895          {state.conflicts.slice(0, 2).map(c => (
896            <Text color="warning" dimColor>
897              ▲ {w.editedOwned(nameOf(w, c.editor), c.file, nameOf(w, c.owner))}
898            </Text>
899          ))}
900          {familyRow}
901        </Box>
902      )
903    }
904
905    if ((await read($, snoozeUntil)) > now) return next(e)
906    const list = state.alerts
907    const top = list[0]!.level
908    const done = await read($, lastCoord)
909
910    return (
911      <Box flexDirection="column" marginTop={1}>
912        {list.slice(0, 3).map(a => (
913          <Box flexDirection="row" gap={1}>
914            <Text color={LEVEL_COLOR[a.level]}>
915              {LEVEL_MARK[a.level]} {a.level === 3 ? w.clash : w.otherAgent} {w.in} {a.repoName} · {reasonOf(w, a)}
916              {a.overlap.length ? ` (${a.overlap.slice(0, 3).join(', ')}${a.overlap.length > 3 ? '…' : ''})` : ''} ·
917            </Text>
918            {a.hostId ? (
919              <Button key={`open-${a.sessionId}`} plain onPress={() => openSession($, a.hostId)}>
920                <Text color={LEVEL_COLOR[a.level]} underline>
921                  {nameOf(w, { title: a.title, task: a.task.slice(0, 60) })}
922                </Text>
923              </Button>
924            ) : (
925              <Text color={LEVEL_COLOR[a.level]}>{nameOf(w, { title: a.title, task: a.task.slice(0, 60) })}</Text>
926            )}
927            <Text dimColor>· {a.branch}</Text>
928          </Box>
929        ))}
930        {list.length > 3 && <Text dimColor>  {w.more(list.length - 3)}</Text>}
931        <Box flexDirection="row" gap={1}>
932          {top === 3 && <Text color="error" bold>{w.recommend}</Text>}
933          <Button key="coord" variant={top === 3 ? 'primary' : undefined} onPress={() => coordinate($)}>
934            {state.hasHuddle ? w.addToHuddle : w.coordinate}
935          </Button>
936          <Button key="snooze" onPress={() => update($, snoozeUntil, () => now + SNOOZE_MS)}>
937            {w.snooze}
938          </Button>
939          {done && now - done.at < 10 * 60_000 && (
940            <Text dimColor>
941              {w.sentTo(done.sent)}
942              {done.failed.length ? w.failedN(done.failed.length) : ''}
943            </Text>
944          )}
945        </Box>
946        {familyRow}
947      </Box>
948    )
949  })
950}
951
hooks/i18n.ts 248 lines
1/**
2 * Huddle's words in English and Spanish, picked by Claude Code's `language` setting, then by what the person types,
3 * then the locale (nothing to configure). Messages to other agents go out in the sender's language.
4 */
5import type { AlertKind } from '../types'
6
7export type Lang = 'en' | 'es'
8
9const EN = {
10  reason: (kind: AlertKind, n: number): string =>
11    kind === 'overlap'
12      ? `both edited ${n} file${n === 1 ? '' : 's'}`
13      : kind === 'hot'
14        ? 'both touch single-owner files (lockfile, package.json, migrations, schema)'
15        : kind === 'checkout'
16          ? 'same working copy (no worktree of its own)'
17          : 'same repo, another copy or worktree',
18  none: 'none yet',
19  noTask: '(no task stated)',
20  clash: 'Clash',
21  otherAgent: 'Another agent',
22  in: 'in',
23  recommend: 'Coordinating is recommended.',
24  coordinate: 'Coordinate',
25  addToHuddle: 'Add to huddle',
26  snooze: 'Snooze 30 min',
27  more: (n: number) => `+${n} more`,
28  sentTo: (n: number) => `Sent to ${n}`,
29  failedN: (n: number) => ` · ${n} failed`,
30  status: (n: number, repo: string) => `👥 ${n} agents in ${repo}`,
31  statusHuddle: (n: number) => `👥 Huddle · ${n} agents`,
32  huddleWith: (n: number) => `Huddle with ${n} sessions`,
33  aMember: 'a huddle member',
34  ledBy: 'led by',
35  ledByYou: 'led by you',
36  confirmed: (c: number, n: number) => `${c}/${n} confirmed`,
37  editedOwned: (editor: string, file: string, owner: string) => `${editor} edited ${file} (owner ${owner})`,
38  toastOwner: (file: string, owner: string) => `You edited ${file}, which the huddle gave to ${owner}.`,
39  toastAllIn: 'Everyone active here is already in the huddle.',
40  toastAdded: (n: number) => `Added ${n} session${n === 1 ? '' : 's'} to the huddle.`,
41  toastClash: (repo: string, reason: string) => `Clash with another agent in ${repo}: ${reason}. Coordinate from the band.`,
42  toastNoPeers: 'No other agents are active in this repo anymore.',
43  openFailed: "Couldn't open that session. Find it by name in the sidebar.",
44  toastSent: (n: number) => `Huddle sent to ${n} session${n === 1 ? '' : 's'}.`,
45  toastPartial: (sent: number, failed: number) => `Huddle sent to ${sent}; ${failed} failed.`,
46  commandDescription: 'Coordinate with the other Claude sessions working in this repo',
47  commandNotRepo: 'Huddle only works inside a git repository.',
48  toolPeers:
49    'Lists the other Claude sessions active in this same repo: id, task, branch, clash level (1 same repo, 2 same working copy, 3 same files) and the files in conflict.',
50  toolSend:
51    'Sends a message to another Claude session in this repo to coordinate work (use the sessionId the peers tool gives).',
52  toolAgree:
53    "Huddle leader only: records the agreement (one owner per disputed file, plus a short summary) and sends it to every member. Call it once, when the members' replies are in.",
54  agreeNoHuddle: 'There is no huddle led by this session.',
55  agreeNotLeader: 'Only the huddle leader can call agree.',
56  agreeBadInput: 'agree needs a summary and at least one owner with a path and a sessionId.',
57  agreeBadRepo: (repo: string) => `Unknown repo «${repo}». Use a repo name or key from the peers tool.`,
58  agreeDone: (sent: number, failed: number) =>
59    `Agreement recorded and sent to ${sent} session${sent === 1 ? '' : 's'}${failed ? `; ${failed} failed` : ''}.`,
60  peersNone: 'No other sessions are active in this repo.',
61  delivered: 'Delivered.',
62  notDelivered: (why: string) => `Not delivered: ${why}`,
63  peerMessage: (p: {
64    repo: string; level: number; reason: string; id: string; task: string; branch: string; path: string
65    files: string; clash: string | null; leader: string; marker: string
66  }) =>
67    [
68      `[huddle] The user asked to coordinate the sessions working in the repo ${p.repo} (level ${p.level}: ${p.reason}).`,
69      `Initiating session (id ${p.id}): ${p.task} · branch ${p.branch} · ${p.path}`,
70      `Files it has edited: ${p.files}.`,
71      p.clash ? `Files in conflict: ${p.clash}.` : '',
72      'Protocol:',
73      `1. Reply to the leader (sessionId ${p.leader}) with the huddle send tool or with SendMessage: your task, the files you edited and the ones you plan to touch.`,
74      '2. Agree on one owner for each disputed file and on the order of work: whoever goes first finishes and commits first; the other updates (pull/rebase) before touching those files. Lockfile, package.json, migrations, schema and generated files have a single owner.',
75      '3. If you share the same working copy: nobody runs checkout, stash, reset or installs dependencies without telling the other, and you commit only your own files with a pathspec (git commit -- <files>), never everything that is dirty.',
76      "4. Don't edit the other session's files without agreement. While the agreement lands, keep working on what doesn't clash.",
77      '5. Respect your original instruction. If your task already includes committing, pushing or publishing, still do it, but in the agreed order and carefully (update first, verify after). If it was not asked of you, coordinating is not a reason to do it. Coordinating is never a reason to stop doing what you were asked.',
78      'The leader closes with the agreement (the huddle agree tool), which reaches everyone.',
79      p.marker,
80    ]
81      .filter(Boolean)
82      .join('\n'),
83  addedNotice: (names: string, marker: string) =>
84    `[huddle] I added these sessions to the huddle: ${names}. They received the protocol and will reply to you, the leader.\n${marker}`,
85  agreeMessage: (p: { summary: string; owners: string[]; marker: string }) =>
86    [
87      '[huddle] The leader recorded the agreement. Follow it and keep doing your original task.',
88      p.summary,
89      p.owners.length ? `Owners:\n${p.owners.join('\n')}` : '',
90      p.marker,
91    ]
92      .filter(Boolean)
93      .join('\n'),
94  ownerConflict: (file: string, owner: string) =>
95    `[huddle] Heads-up: in the huddle agreement ${file} belongs to ${owner}, and you just edited it. Stop editing it; tell the owner with the huddle send tool, or hand them the change.`,
96  midTurnNote: (from: string, text: string) =>
97    `[huddle] A message from ${from} arrived while you were working:\n${text}`,
98  leadIntro: (repo: string) =>
99    `[huddle] The user asked to coordinate this session with the others working in ${repo}. I already sent them the coordination protocol.`,
100  leadRow: (p: { id: string; level: number; reason: string; task: string; branch: string; clash: string | null; failed: boolean }) =>
101    `- ${p.id} · level ${p.level} (${p.reason}) · ${p.task} · branch ${p.branch}` +
102    (p.clash ? ` · conflict in: ${p.clash}` : '') +
103    (p.failed ? ' · ⚠ the message could not be delivered' : ''),
104  leadClose:
105    'You lead. The protocol already went out: do not message them until they reply. When the replies are in, call the huddle agree tool once with one owner per disputed file and a 3-line summary; it reaches everyone. Then keep doing your task and give the user the summary. Keep to your original instruction: commit or publish only if that was already part of your task, and then in the agreed order.',
106  familyBy: 'started by',
107  familyMother: (name: string) => `started by ${name}`,
108  familyDaughters: (n: number) => `${n} daughter${n === 1 ? '' : 's'}`,
109  sisterSuffix: ' · sister session',
110  sisterClashToMother: (me: string, sister: string, files: string) =>
111    `[huddle] Two of the sessions you started, ${me} and ${sister}, are editing the same files (${files}). You split the work between them, so settle which of them owns those files and tell them.`,
112  leadAdded: (names: string) =>
113    `[huddle] I added these sessions to the huddle: ${names}. The protocol already went out: do not message them until they reply. When their replies are in, call the huddle agree tool again with the updated owners and summary.`,
114}
115
116export type Words = typeof EN
117
118const ES: Words = {
119  reason: (kind, n) =>
120    kind === 'overlap'
121      ? `ambos editaron ${n} archivo${n === 1 ? '' : 's'}`
122      : kind === 'hot'
123        ? 'ambos tocan archivos de dueño único (lockfile, package.json, migraciones, schema)'
124        : kind === 'checkout'
125          ? 'misma copia de trabajo (sin worktree propio)'
126          : 'mismo repo, otra copia o worktree',
127  none: 'ninguno aún',
128  noTask: '(sin tarea declarada)',
129  clash: 'Choque',
130  otherAgent: 'Otro agente',
131  in: 'en',
132  recommend: 'Se recomienda coordinar.',
133  coordinate: 'Coordinar',
134  addToHuddle: 'Añadir al huddle',
135  snooze: 'Silenciar 30 min',
136  more: n => `+${n} más`,
137  sentTo: n => `Enviado a ${n}`,
138  failedN: n => ` · falló ${n}`,
139  status: (n, repo) => `👥 ${n} agentes en ${repo}`,
140  statusHuddle: n => `👥 Huddle · ${n} agentes`,
141  huddleWith: n => `En huddle con ${n} sesiones`,
142  aMember: 'un miembro del huddle',
143  ledBy: 'lidera',
144  ledByYou: 'lo lideras tú',
145  confirmed: (c, n) => `${c}/${n} confirmaron`,
146  editedOwned: (editor, file, owner) => `${editor} editó ${file} (dueño ${owner})`,
147  toastOwner: (file, owner) => `Editaste ${file}, que el huddle asignó a ${owner}.`,
148  toastAllIn: 'Todos los activos aquí ya están en el huddle.',
149  toastAdded: n => `Se añadió ${n} sesi${n === 1 ? 'ón' : 'ones'} al huddle.`,
150  toastClash: (repo, reason) => `Choque con otro agente en ${repo}: ${reason}. Coordina desde la banda.`,
151  toastNoPeers: 'Ya no hay otros agentes activos en este repo.',
152  openFailed: 'No pude abrir esa sesión. Búscala por nombre en el sidebar.',
153  toastSent: n => `Huddle enviado a ${n} sesi${n === 1 ? 'ón' : 'ones'}.`,
154  toastPartial: (sent, failed) => `Huddle enviado a ${sent}; falló con ${failed}.`,
155  commandDescription: 'Coordina con las otras sesiones de Claude que trabajan en este repo',
156  commandNotRepo: 'Huddle solo funciona dentro de un repositorio git.',
157  toolPeers:
158    'Lista las otras sesiones de Claude activas en este mismo repo: id, tarea, rama, nivel de choque (1 mismo repo, 2 misma copia, 3 mismos archivos) y archivos en choque.',
159  toolSend:
160    'Envía un mensaje a otra sesión de Claude del mismo repo para coordinar trabajo (usa el sessionId que da la herramienta peers).',
161  toolAgree:
162    'Solo el líder del huddle: registra el acuerdo (un dueño por archivo en disputa y un resumen corto) y lo envía a todos los miembros. Llámala una vez, cuando ya llegaron las respuestas.',
163  agreeNoHuddle: 'Esta sesión no lidera ningún huddle.',
164  agreeNotLeader: 'Solo el líder del huddle puede llamar a agree.',
165  agreeBadInput: 'agree necesita un resumen y al menos un dueño con path y sessionId.',
166  agreeBadRepo: repo => `Repo desconocido «${repo}». Usa un nombre o clave de repo de la herramienta peers.`,
167  agreeDone: (sent, failed) =>
168    `Acuerdo registrado y enviado a ${sent} sesi${sent === 1 ? 'ón' : 'ones'}${failed ? `; falló con ${failed}` : ''}.`,
169  peersNone: 'No hay otras sesiones activas en este repo.',
170  delivered: 'Entregado.',
171  notDelivered: why => `No se entregó: ${why}`,
172  peerMessage: p =>
173    [
174      `[huddle] El usuario pidió coordinar las sesiones que trabajan en el repo ${p.repo} (nivel ${p.level}: ${p.reason}).`,
175      `Sesión que inicia (id ${p.id}): ${p.task} · rama ${p.branch} · ${p.path}`,
176      `Archivos que ha editado: ${p.files}.`,
177      p.clash ? `Archivos en choque: ${p.clash}.` : '',
178      'Protocolo:',
179      `1. Contesta al líder (sessionId ${p.leader}) con la herramienta send de huddle o con SendMessage: tu tarea, los archivos que editaste y los que planeas tocar.`,
180      '2. Acuerden un dueño por cada archivo en disputa y el orden de trabajo: quien va primero termina y commitea primero; el otro actualiza (pull/rebase) antes de tocar esos archivos. Lockfile, package.json, migraciones, schema y generados tienen un solo dueño.',
181      '3. Si comparten la misma copia de trabajo: nadie hace checkout, stash, reset ni instala dependencias sin avisar al otro, y tú commiteas solo tus archivos con pathspec (git commit -- <archivos>), nunca todo lo que esté sucio.',
182      '4. No edites archivos del otro sin acuerdo. Mientras llega el acuerdo, sigue con lo que no choca.',
183      '5. Respeta tu instrucción original. Si tu tarea ya incluye commitear, hacer push o publicar, hazlo igual, pero en el orden acordado y con cuidado (actualiza antes, verifica después). Si no te lo pidieron, coordinarte no es razón para hacerlo. Coordinarte nunca es razón para dejar de hacer lo que te pidieron.',
184      'El líder cierra con el acuerdo (la herramienta agree de huddle), que le llega a todos.',
185      p.marker,
186    ]
187      .filter(Boolean)
188      .join('\n'),
189  addedNotice: (names, marker) =>
190    `[huddle] Añadí estas sesiones al huddle: ${names}. Recibieron el protocolo y te contestarán a ti, el líder.\n${marker}`,
191  agreeMessage: p =>
192    [
193      '[huddle] El líder registró el acuerdo. Síguelo y continúa con tu tarea original.',
194      p.summary,
195      p.owners.length ? `Dueños:\n${p.owners.join('\n')}` : '',
196      p.marker,
197    ]
198      .filter(Boolean)
199      .join('\n'),
200  ownerConflict: (file, owner) =>
201    `[huddle] Ojo: en el acuerdo del huddle ${file} es de ${owner}, y acabas de editarlo. Deja de editarlo; avísale al dueño con la herramienta send de huddle o entrégale el cambio.`,
202  midTurnNote: (from, text) => `[huddle] Llegó un mensaje de ${from} mientras trabajabas:\n${text}`,
203  leadIntro: repo =>
204    `[huddle] El usuario pidió coordinar esta sesión con las otras que trabajan en ${repo}. Ya les envié el protocolo de coordinación.`,
205  leadRow: p =>
206    `- ${p.id} · nivel ${p.level} (${p.reason}) · ${p.task} · rama ${p.branch}` +
207    (p.clash ? ` · choque en: ${p.clash}` : '') +
208    (p.failed ? ' · ⚠ no se le pudo entregar el mensaje' : ''),
209  leadClose:
210    'Lidera tú. El protocolo ya salió: no les escribas hasta que contesten. Cuando lleguen las respuestas, llama una sola vez a la herramienta agree de huddle con un dueño por archivo en disputa y un resumen de 3 líneas; le llega a todos. Luego sigue con tu tarea y dale el resumen al usuario. Respeta tu instrucción original: commitea o publica solo si eso ya era parte de tu tarea, y entonces en el orden acordado.',
211  familyBy: 'la inició',
212  familyMother: name => `la inició ${name}`,
213  familyDaughters: n => `${n} hija${n === 1 ? '' : 's'}`,
214  sisterSuffix: ' · sesión hermana',
215  sisterClashToMother: (me, sister, files) =>
216    `[huddle] Dos de las sesiones que iniciaste, ${me} y ${sister}, están editando los mismos archivos (${files}). Tú repartiste el trabajo entre ellas, así que define cuál es dueña de esos archivos y avísales.`,
217  leadAdded: names =>
218    `[huddle] Añadí estas sesiones al huddle: ${names}. El protocolo ya salió: no les escribas hasta que contesten. Cuando lleguen sus respuestas, llama otra vez a la herramienta agree de huddle con los dueños y el resumen actualizados.`,
219}
220
221export const words = (lang: Lang): Words => (lang === 'es' ? ES : EN)
222
223/**
224 * Spanish when Spanish markers outnumber English ones in what the person typed, English when the reverse, null on a
225 * tie (a prompt like "ok" says nothing).
226 */
227export function inferLang(text: string): Lang | null {
228  const t = text.toLowerCase()
229  const es = (t.match(/[¿¡áéíóúñ]/g) ?? []).length + (t.match(ES_WORDS) ?? []).length
230  const en = (t.match(EN_WORDS) ?? []).length
231  return es > en ? 'es' : en > es ? 'en' : null
232}
233
234const ES_WORDS = /(?<![\p{L}\p{N}])(?:que|de|la|el|los|las|para|por|una|con|está|ya|sí|también|pero|como|esto|esta|cómo)(?![\p{L}\p{N}])/gu
235const EN_WORDS = /(?<![\p{L}\p{N}])(?:the|and|to|is|of|for|with|this|that|please|it|in|on|are|you)(?![\p{L}\p{N}])/gu
236
237/**
238 * Claude Code's `language` setting, then what the person's own prompts read as, then LC_ALL/LANG; English otherwise.
239 * An explicit 'en' or 'es' first wins (tests).
240 */
241export function pickLang(option: unknown, settingsLanguage: unknown, locale: string | null, inferred?: Lang | null): Lang {
242  if (option === 'en' || option === 'es') return option
243  const s = typeof settingsLanguage === 'string' ? settingsLanguage.toLowerCase() : ''
244  if (s) return s.startsWith('es') || s.startsWith('span') || s.startsWith('espa') ? 'es' : 'en'
245  if (inferred) return inferred
246  return (locale ?? '').toLowerCase().startsWith('es') ? 'es' : 'en'
247}
248
hooks/logic.ts 646 lines
1import type { Alert, AlertKind, BandState, Family, Level, OwnerConflict, Who } from '../types'
2import type { Lang, Words } from './i18n'
3
4/** What a session knows of one repo it works in: its working copy there, its branch, the files it edited. */
5export type RepoEntry = {
6  repoKey: string
7  repoName: string
8  toplevel: string
9  branch: string
10  files: Record<string, number>
11  /** When the session last edited or entered this repo. A repo not seen for the file window stops counting. */
12  seenAt?: number
13}
14
15/** What the leader decided: who owns which disputed file. `owners` keys are `repoKey::relPath`. */
16export type HuddleLead = {
17  members: string[]
18  owners: Record<string, string>
19  summary?: string
20  createdAt: number
21  /** When `agree` last recorded the owners: only edits after it can break the agreement. */
22  agreedAt?: number
23}
24
25export type HuddleInfo = {
26  id: string
27  leaderId: string
28  joinedAt: number
29  ackAt?: number
30  lead?: HuddleLead
31}
32
33// One file per live session under ~/.claude/huddle/sessions/<sessionId>.json.
34export type Presence = {
35  v: 2
36  sessionId: string
37  cwd: string
38  /** The repo of the session's working directory; always in `repos`. */
39  home: string
40  repos: Record<string, RepoEntry>
41  task: string
42  title?: string
43  hostId?: string
44  /** The desktop id of the session that started this one (start_session), while it is not detached. */
45  parentHostId?: string
46  lang?: Lang
47  huddle?: HuddleInfo
48  startedAt: number
49  lastSeen: number
50  /** Last human prompt or tool call: a session open but untouched for hours is idle. */
51  lastActiveAt: number
52  ended?: boolean
53}
54
55export const LIVE_MS = 60_000
56export const FILE_WINDOW_MS = 4 * 60 * 60_000
57export const IDLE_MS = 2 * 60 * 60_000
58
59// Files only one session should touch at a time (single-owner).
60const HOT = [
61  /(^|\/)package\.json$/,
62  /(^|\/)(pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lockb?)$/,
63  /(^|\/)migrations?\//,
64  /(^|\/)(schema\.prisma|drizzle\.config\.\w+)$/,
65  /(^|\/)(schema|db\/schema)\.\w+$/,
66  /(^|\/)generated\//,
67]
68
69export const isHot = (path: string) => HOT.some(re => re.test(path))
70
71// git remote spellings collapse to one key: git@github.com:o/r.git == https://github.com/o/r
72export function normalizeRemote(url: string): string {
73  return url
74    .trim()
75    .replace(/^[a-z+]+:\/\//, '')
76    .replace(/^[^@/]+@/, '')
77    .replace(':', '/')
78    .replace(/\/+$/, '')
79    .replace(/\.git$/, '')
80    .toLowerCase()
81}
82
83const recent = (files: Record<string, number>, now: number) =>
84  Object.keys(files).filter(f => now - (files[f] ?? 0) < FILE_WINDOW_MS)
85
86export function isLive(p: Presence, now: number): boolean {
87  return !p.ended && now - p.lastSeen < LIVE_MS
88}
89
90export const isIdle = (p: Presence, now: number): boolean => now - p.lastActiveAt > IDLE_MS
91
92/**
93 * A presence file as this version reads it. A session still on 0.2.x writes `v: 1` (one repo, flat); it is read as
94 * a session whose only repo is its home. Anything else is skipped.
95 */
96export function upgradePresence(raw: unknown): Presence | null {
97  const p = raw as Record<string, any> | null
98  if (!p || typeof p !== 'object' || typeof p.sessionId !== 'string') return null
99  if (p.v === 2) {
100    if (!p.repos || typeof p.repos !== 'object' || typeof p.home !== 'string') return null
101    return { ...p, lastActiveAt: typeof p.lastActiveAt === 'number' ? p.lastActiveAt : p.lastSeen } as Presence
102  }
103  if (p.v !== 1 || typeof p.repoKey !== 'string') return null
104  const { files, toplevel, repoName, branch, repoKey, ...rest } = p
105  return {
106    ...rest,
107    v: 2,
108    home: repoKey,
109    repos: { [repoKey]: { repoKey, repoName, toplevel, branch, files: files ?? {}, seenAt: p.lastSeen } },
110    lastActiveAt: p.lastSeen,
111  } as Presence
112}
113
114/** The repos that count right now: the home one always, the others while they were seen within the file window. */
115export function activeRepos(p: Presence, now: number): RepoEntry[] {
116  return Object.values(p.repos).filter(r => r.repoKey === p.home || now - (r.seenAt ?? p.lastSeen) < FILE_WINDOW_MS)
117}
118
119function assessRepo(mine: RepoEntry, theirs: RepoEntry, now: number): Pick<Alert, 'level' | 'kind' | 'overlap'> {
120  const theirFiles = new Set(recent(theirs.files, now))
121  const mineFiles = recent(mine.files, now)
122  const overlap = mineFiles.filter(f => theirFiles.has(f)).sort()
123  const bothHot = mineFiles.some(isHot) && [...theirFiles].some(isHot)
124  const sameCheckout = mine.toplevel === theirs.toplevel
125  const [level, kind]: [Level, AlertKind] =
126    overlap.length > 0 ? [3, 'overlap'] : bothHot ? [3, 'hot'] : sameCheckout ? [2, 'checkout'] : [1, 'repo']
127  return { level, kind, overlap }
128}
129
130/**
131 * How two sessions clash. Every repo they both work in is judged on its own (same files 3, both on single-owner
132 * files 3, same working copy 2, else 1) and the peer raises one alert, for its strongest repo.
133 */
134export function assess(me: Presence, peer: Presence, now: number): Alert | null {
135  if (peer.sessionId === me.sessionId || !isLive(peer, now)) return null
136  // A session and the one that started it (or one it started) already coordinate through the app.
137  const family = familyOf(me, peer)
138  if (family === 'mother' || family === 'daughter') return null
139
140  const theirs = new Map(activeRepos(peer, now).map(r => [r.repoKey, r]))
141  let best: { repo: RepoEntry; found: Pick<Alert, 'level' | 'kind' | 'overlap'> } | null = null
142  for (const repo of activeRepos(me, now)) {
143    const other = theirs.get(repo.repoKey)
144    if (!other) continue
145    const found = assessRepo(repo, other, now)
146    const wins =
147      !best ||
148      found.level > best.found.level ||
149      (found.level === best.found.level && found.overlap.length > best.found.overlap.length) ||
150      (found.level === best.found.level && found.overlap.length === best.found.overlap.length && repo.repoKey === me.home)
151    if (wins) best = { repo, found }
152  }
153  if (!best) return null
154  // A session nobody has touched for hours only speaks up when the files already clash.
155  if (isIdle(peer, now) && best.found.level < 3) return null
156  // Sisters only speak up when their files clash.
157  if (family === 'sister' && best.found.level < 3) return null
158
159  const peerRepo = theirs.get(best.repo.repoKey)!
160  return {
161    sessionId: peer.sessionId,
162    ...best.found,
163    repoKey: best.repo.repoKey,
164    repoName: best.repo.repoName,
165    title: peer.title ?? '',
166    hostId: isHostId(peer.hostId) ? peer.hostId : '',
167    task: peer.task,
168    branch: peerRepo.branch,
169    ...(family === 'sister' ? { family } : {}),
170  }
171}
172
173/**
174 * The session's own title out of a `get_session` answer: the desktop app's (`{ title }`) or claude.ai's for a Remote
175 * Control session (`{ ccr: { title } }`), at most 120 characters. '' when there is none.
176 */
177export function titleFromSessionAnswer(answer: unknown): string {
178  const a = (answer ?? {}) as { title?: unknown; ccr?: { title?: unknown } }
179  if (typeof a !== 'object') return ''
180  const title = typeof a.title === 'string' ? a.title : typeof a.ccr?.title === 'string' ? a.ccr.title : ''
181  return title.replace(/\s+/g, ' ').trim().slice(0, 120)
182}
183
184/** The session that started the one whose get_session answer this is; none once the person detached it. */
185export function parentFromSession(answer: unknown): string | undefined {
186  const a = answer as { parentSessionId?: unknown; detached?: unknown } | null
187  if (!a || typeof a !== 'object' || a.detached === true) return undefined
188  return isHostId(a.parentSessionId) ? a.parentSessionId : undefined
189}
190
191/** What `peer` is to `me` among sessions started from one another, by the desktop ids; null when unrelated or unknown. */
192export function familyOf(me: Presence, peer: Presence): 'mother' | 'daughter' | 'sister' | null {
193  if (me.parentHostId && me.parentHostId === peer.hostId) return 'mother'
194  if (peer.parentHostId && peer.parentHostId === me.hostId) return 'daughter'
195  if (me.parentHostId && me.parentHostId === peer.parentHostId) return 'sister'
196  return null
197}
198
199/** The live session that started this one. */
200export const motherOf = (me: Presence, peers: Presence[], now: number): Presence | undefined =>
201  peers.find(p => p.sessionId !== me.sessionId && isLive(p, now) && familyOf(me, p) === 'mother')
202
203export function assessAll(me: Presence, peers: Presence[], now: number): Alert[] {
204  return peers
205    .map(p => assess(me, p, now))
206    .filter((a): a is Alert => a !== null)
207    .sort((a, b) => b.level - a.level)
208}
209
210// Paths as git spells them: forward slashes, so Windows tool paths compare with `git rev-parse` output.
211export const slashes = (path: string) => path.replace(/\\/g, '/')
212
213/** The file relative to the repo's top level, or null when it lies outside it. */
214export function repoRelative(toplevel: string, path: string): string | null {
215  const root = slashes(toplevel).replace(/\/+$/, '') + '/'
216  const file = slashes(path)
217  return file.startsWith(root) ? file.slice(root.length) : null
218}
219
220export const reasonOf = (w: Words, a: Alert) =>
221  w.reason(a.kind, a.overlap.length) + (a.family === 'sister' ? w.sisterSuffix : '')
222
223const list = (w: Words, xs: string[], max = 8) =>
224  xs.length === 0 ? w.none : xs.slice(0, max).join(', ') + (xs.length > max ? ` (+${xs.length - max})` : '')
225
226const quote = (w: Words, s: string) => (s ? `«${s}»` : w.noTask)
227
228/** How a session is named to the person: its sidebar title, else the start of what it was asked. */
229export const nameOf = (w: Words, p: { title?: string; task: string }) => (p.title ? `«${p.title}»` : quote(w, p.task))
230
231/** A desktop session id as the app spells it; anything else (from a peer's file) is never opened. */
232export const isHostId = (id: unknown): id is string => typeof id === 'string' && /^[A-Za-z0-9_-]{1,80}$/.test(id)
233
234/** The prefix of the tools the Claude desktop app gives the sessions it hosts (`mcp__ccd_session__...`, `mcp__ccd_turn__...`). */
235export const DESKTOP_TOOL_PREFIX = 'mcp__ccd_'
236
237/**
238 * Whether this process is a session someone sees, and so may take the desktop app's id from CLAUDE_CODE_HOST_SESSION_ID
239 * as its own: it draws on a surface (terminal, phone, IDE, desktop) or the desktop app hosts it (its `mcp__ccd_*` tools
240 * are there even while the session is not open in the window, when `surfaces()` is empty for hours). A `claude -p` run
241 * started from a desktop session inherits the variable but neither of these, so it never passes for its parent. Once
242 * true it stays true. If a desktop release ever hands its `ccd` servers to child processes, this needs another signal.
243 */
244export function isSeenSession(before: boolean, surfaces: readonly unknown[], toolNames: readonly string[]): boolean {
245  return before || surfaces.length > 0 || toolNames.some(n => n.startsWith(DESKTOP_TOOL_PREFIX))
246}
247
248/**
249 * Whether this session writes its presence file for the others to read. One someone sees always does. A run no one sees
250 * (a `claude -p` helper that a status line, a mod or a script starts) only once it has edited something in a repo: until
251 * then it is no risk to anyone, and showing it would put a nameless peer in every band of that repo.
252 */
253export function shouldPublish(seen: boolean, me: Pick<Presence, 'repos'>): boolean {
254  return seen || Object.values(me.repos).some(r => Object.keys(r.files).length > 0)
255}
256
257/** The desktop app's own link to a session, as its get_session answers it. */
258export const sessionLink = (hostId: string) => `claude://claude.ai/epitaxy/${hostId}`
259
260/** The repo entry a message speaks about: the alert's repo, else the session's home. */
261const entryFor = (p: Presence, repoKey: string): RepoEntry => p.repos[repoKey] ?? p.repos[p.home]!
262
263// What each peer session receives. `huddle` is the huddle it joins: with none, this session leads a new one.
264export function peerMessage(
265  w: Words,
266  me: Presence,
267  alert: Alert,
268  now: number,
269  huddle?: { id: string; leaderId: string },
270): string {
271  const repo = entryFor(me, alert.repoKey)
272  return w.peerMessage({
273    repo: alert.repoName,
274    level: alert.level,
275    reason: reasonOf(w, alert),
276    id: me.sessionId,
277    task: nameOf(w, me),
278    branch: repo.branch,
279    path: repo.toplevel,
280    files: list(w, recent(repo.files, now)),
281    clash: alert.overlap.length ? list(w, alert.overlap) : null,
282    leader: huddle?.leaderId ?? me.sessionId,
283    marker: huddle ? huddleMarker(huddle.id, huddle.leaderId) : '',
284  })
285}
286
287/** The one short notice a mother gets when two of her daughters edit the same files. */
288export function sisterNotice(w: Words, me: Presence, sisters: Alert[]): string {
289  const files = [...new Set(sisters.flatMap(a => a.overlap))].sort()
290  return w.sisterClashToMother(
291    nameOf(w, me),
292    sisters.map(a => nameOf(w, a)).join(', '),
293    files.length ? list(w, files) : w.none,
294  )
295}
296
297// What the initiating session's own model is asked to do.
298export function leadPrompt(w: Words, me: Presence, alerts: Alert[], sent: string[]): string {
299  const repos = [...new Set(alerts.map(a => a.repoName))].join(', ')
300  return [
301    w.leadIntro(repos),
302    ...alerts.map(a =>
303      w.leadRow({
304        id: a.sessionId,
305        level: a.level,
306        reason: reasonOf(w, a),
307        task: nameOf(w, a),
308        branch: a.branch,
309        clash: a.overlap.length ? list(w, a.overlap) : null,
310        failed: !sent.includes(a.sessionId),
311      }),
312    ),
313    w.leadClose,
314  ].join('\n')
315}
316
317export function sameJson(a: unknown, b: unknown): boolean {
318  return JSON.stringify(a) === JSON.stringify(b)
319}
320
321export const sameAlerts = (a: Alert[], b: Alert[]): boolean => sameJson(a, b)
322
323// ---- Huddle: the marker line every protocol message carries, so the receiving side knows it joined. ----
324
325const ID = '[A-Za-z0-9_-]{1,80}'
326const MARKER = new RegExp(`\\[huddle:(${ID}) leader:(${ID})\\]`)
327const ADD_MARKER = new RegExp(`\\[huddle-add:(${ID}) ((?:${ID})(?:,${ID})*)\\]`)
328
329export const huddleMarker = (id: string, leaderId: string) => `[huddle:${id} leader:${leaderId}]`
330export const addMarker = (id: string, sessionIds: string[]) => `[huddle-add:${id} ${sessionIds.join(',')}]`
331
332export function parseHuddleMarker(text: string): { id: string; leaderId: string } | null {
333  const m = MARKER.exec(text)
334  return m ? { id: m[1]!, leaderId: m[2]! } : null
335}
336
337export function parseAddMarker(text: string): { id: string; sessionIds: string[] } | null {
338  const m = ADD_MARKER.exec(text)
339  return m ? { id: m[1]!, sessionIds: m[2]!.split(',') } : null
340}
341
342/** The message without its machine lines, for the short copy a busy agent reads mid-turn. */
343export const stripMarkers = (text: string): string =>
344  text
345    .split('\n')
346    .filter(line => !MARKER.test(line) && !ADD_MARKER.test(line))
347    .join('\n')
348    .trim()
349
350export const newHuddleId = (sessionId: string, now: number) => `${sessionId.slice(0, 8)}-${now}`
351
352export const BACKGROUND_PREFIX = 'Background (from the session that started this one)'
353
354/** What the session is "about": the start of what the person asked, never the text a parent session wrote to it. */
355export function taskFromPrompt(text: string): string {
356  const t = text.replace(/\s+/g, ' ').trim()
357  return t.startsWith(BACKGROUND_PREFIX) ? '' : t.slice(0, 140)
358}
359
360/** The sidebar title is read on every tick for the first 8, then every 4th. */
361export const shouldRefreshTitle = (tick: number): boolean => tick < 8 || tick % 4 === 0
362
363// ---- Shell edits: which directories a command enters, and what changed in a repo while it ran. ----
364
365type Word = { text: string; dynamic: boolean }
366
367/** A shell line as lists of words, one list per simple command. Quotes and `~`/`$HOME` are resolved; a word that
368 * needs the shell to expand (`$X`, backticks, globs) is flagged dynamic. */
369function splitCommand(command: string, home: string): Word[][] {
370  const cmds: Word[][] = [[]]
371  let cur = ''
372  let has = false
373  let dynamic = false
374  let quote = ''
375  const push = () => {
376    if (has) cmds[cmds.length - 1]!.push({ text: cur, dynamic })
377    cur = ''
378    has = false
379    dynamic = false
380  }
381  const cut = () => {
382    push()
383    if (cmds[cmds.length - 1]!.length) cmds.push([])
384  }
385  const homeAt = (i: number): number => {
386    for (const name of ['HOME', '{HOME}']) {
387      const end = i + 1 + name.length
388      if (command.startsWith(name, i + 1) && (name.startsWith('{') || !/[A-Za-z0-9_]/.test(command[end] ?? ''))) return end
389    }
390    return -1
391  }
392  for (let i = 0; i < command.length; i++) {
393    const c = command[i]!
394    if (quote === "'") {
395      if (c === "'") quote = ''
396      else cur += c
397      continue
398    }
399    if (c === '$') {
400      const end = home ? homeAt(i) : -1
401      if (end > 0) {
402        cur += home
403        has = true
404        i = end - 1
405      } else {
406        dynamic = true
407        has = true
408        cur += c
409      }
410      continue
411    }
412    if (quote === '"') {
413      if (c === '"') quote = ''
414      else if (c === '`') dynamic = true
415      else if (c === '\\' && '"\\$`'.includes(command[i + 1] ?? ' ')) cur += command[++i]
416      else cur += c
417      continue
418    }
419    if (c === "'" || c === '"') {
420      quote = c
421      has = true
422    } else if (c === '\\') {
423      if (command[i + 1] === '\n') i++
424      else if (i + 1 < command.length) {
425        cur += command[++i]
426        has = true
427      }
428    } else if (c === '#' && !has) {
429      while (i + 1 < command.length && command[i + 1] !== '\n') i++
430    } else if (c === '~' && !has && home && (i + 1 >= command.length || /[/\s;&|)]/.test(command[i + 1]!))) {
431      cur += home
432      has = true
433    } else if (c === '\n' || c === ';' || c === '|' || c === '&' || c === '(' || c === ')') cut()
434    else if (c === ' ' || c === '\t' || c === '\r') push()
435    else {
436      if (c === '*' || c === '?' || c === '[' || c === '`') dynamic = true
437      cur += c
438      has = true
439    }
440  }
441  push()
442  return cmds.filter(c => c.length)
443}
444
445/** `p` against `base`, `.` and `..` folded, forward slashes: no file system involved. */
446export function resolvePath(base: string, p: string): string {
447  const abs = p.startsWith('/') || /^[A-Za-z]:[\\/]/.test(p)
448  const full = slashes(abs || !base ? p : `${base}/${p}`)
449  const prefix = /^([A-Za-z]:)?\//.exec(full)?.[0] ?? ''
450  const stack: string[] = []
451  for (const part of full.slice(prefix.length).split('/')) {
452    if (part === '' || part === '.') continue
453    if (part === '..') stack.pop()
454    else stack.push(part)
455  }
456  return prefix + stack.join('/')
457}
458
459/** The directories a command names with `cd`, `pushd` and `git -C`, as absolute paths, in order. A `cd` moves
460 * the directory the later parts of the line are read against. */
461export function dirsInCommand(command: string, cwd: string, home = ''): string[] {
462  const out: string[] = []
463  const add = (d: string) => {
464    if (d && !out.includes(d)) out.push(d)
465  }
466  let running = slashes(cwd)
467  for (const words of splitCommand(command, slashes(home))) {
468    let i = 0
469    while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]!.text)) i++
470    const head = words[i]?.text
471    if (head === 'cd' || head === 'pushd') {
472      const arg = words.slice(i + 1).find(x => !x.text.startsWith('-'))
473      if (arg && !arg.dynamic) {
474        running = resolvePath(running, arg.text)
475        add(running)
476      }
477    } else if (head === 'git') {
478      let base = running
479      for (let j = i + 1; j < words.length; j++) {
480        const t = words[j]!
481        if (t.text === '-C') {
482          const dir = words[++j]
483          if (dir && !dir.dynamic) {
484            base = resolvePath(base, dir.text)
485            add(base)
486          }
487        } else if (t.text === '-c') j++
488        else if (!t.text.startsWith('-')) break
489      }
490    }
491  }
492  return out
493}
494
495/** `git status --porcelain=v1 -z` as path -> two-letter status. A rename lists its old path after the new one. */
496export function parsePorcelain(out: string, cap = 2000): Record<string, string> {
497  const map: Record<string, string> = {}
498  const parts = out.split('\0')
499  let count = 0
500  for (let i = 0; i < parts.length && count < cap; i++) {
501    const entry = parts[i]!
502    if (entry.length < 4) continue
503    const xy = entry.slice(0, 2)
504    if (xy.includes('R') || xy.includes('C')) i++
505    map[entry.slice(3)] = xy
506    count++
507  }
508  return map
509}
510
511/** One repo's dirty files: git's status, and for some of them a signature of mtime and size. */
512export type Snapshot = Record<string, { status: string; sig?: string }>
513
514/** The paths that changed between two snapshots: a new status, a new signature, or not there before. A path that
515 * left the list (committed, reverted) is not an edit. */
516export function diffSnapshots(before: Snapshot, after: Snapshot): string[] {
517  const changed: string[] = []
518  for (const [path, a] of Object.entries(after)) {
519    const b = before[path]
520    if (!b || b.status !== a.status || (b.sig !== undefined && a.sig !== undefined && b.sig !== a.sig)) changed.push(path)
521  }
522  return changed.sort()
523}
524
525// ---- Huddle: who is in it, how the band reads it, who owns what. ----
526
527export const ownerKey = (repoKey: string, rel: string) => `${repoKey}::${rel}`
528
529/** The session the agreement gave this file to, if any. */
530export const ownerOf = (lead: HuddleLead | undefined, repoKey: string, rel: string): string | undefined =>
531  lead?.owners[ownerKey(repoKey, rel)]
532
533/** The leader's presence: this session's own when it leads, else the peer's file. */
534export function leaderOf(me: Presence, peers: Presence[]): Presence | null {
535  const h = me.huddle
536  if (!h) return null
537  return h.leaderId === me.sessionId ? me : (peers.find(p => p.sessionId === h.leaderId) ?? null)
538}
539
540/** My huddle while it is live: its leader's presence is live, or another member was active in the last 4 h. */
541export function liveHuddle(me: Presence, peers: Presence[], now: number): HuddleInfo | null {
542  const h = me.huddle
543  if (!h) return null
544  if (h.leaderId === me.sessionId) return h
545  const leader = peers.find(p => p.sessionId === h.leaderId)
546  if (leader && isLive(leader, now)) return h
547  const another = peers.some(
548    p => p.sessionId !== me.sessionId && p.huddle?.id === h.id && !p.ended && now - p.lastActiveAt < FILE_WINDOW_MS,
549  )
550  return another ? h : null
551}
552
553/** Every session id in my live huddle (mine and the leader's included): who joined, plus whom the leader invited. */
554export function huddleMembers(me: Presence, peers: Presence[], now: number): Set<string> | null {
555  const h = liveHuddle(me, peers, now)
556  if (!h) return null
557  const ids = new Set<string>([me.sessionId, h.leaderId])
558  for (const id of leaderOf(me, peers)?.huddle?.lead?.members ?? []) ids.add(id)
559  for (const p of peers) if (p.huddle?.id === h.id) ids.add(p.sessionId)
560  return ids
561}
562
563const who = (p: Presence): Who => ({
564  title: p.title ?? '',
565  task: p.task.slice(0, 60),
566  hostId: isHostId(p.hostId) ? p.hostId : '',
567})
568
569/** Files a member edited after the agreement that the agreement gave to another member. */
570export function ownerConflicts(lead: HuddleLead | undefined, members: Presence[], now: number): OwnerConflict[] {
571  if (!lead?.agreedAt) return []
572  const byId = new Map(members.map(m => [m.sessionId, m]))
573  const found: { at: number; c: OwnerConflict }[] = []
574  for (const editor of members) {
575    for (const repo of Object.values(editor.repos)) {
576      for (const [file, at] of Object.entries(repo.files)) {
577        if (at <= lead.agreedAt! || now - at >= FILE_WINDOW_MS) continue
578        const owner = byId.get(ownerOf(lead, repo.repoKey, file) ?? '')
579        if (owner && owner.sessionId !== editor.sessionId) {
580          found.push({ at, c: { editor: who(editor), owner: who(owner), repoName: repo.repoName, file } })
581        }
582      }
583    }
584  }
585  return found.sort((a, b) => b.at - a.at).map(f => f.c)
586}
587
588/**
589 * What the band shows. Peers that are live, not idle (unless their files clash) and share a repo are the ones to
590 * speak of: if all of them are in my huddle it is one calm line, else the alert rows for those who are not.
591 */
592export function bandState(me: Presence, peers: Presence[], now: number): BandState {
593  const alerts = assessAll(me, peers, now)
594  const family = familyLine(me, peers, now)
595  if (alerts.length === 0) return family ? { kind: 'family', family } : { kind: 'none' }
596  const members = huddleMembers(me, peers, now)
597  const outsiders = alerts.filter(a => !members?.has(a.sessionId))
598  if (outsiders.length > 0) return { kind: 'alert', alerts: outsiders, hasHuddle: members !== null, ...(family ? { family } : {}) }
599
600  const inAlert = new Set(alerts.map(a => a.sessionId))
601  // A mother or a daughter takes no part in the huddle, even if a marker reached it.
602  const others = peers.filter(
603    p =>
604      members!.has(p.sessionId) &&
605      isLive(p, now) &&
606      (!isIdle(p, now) || inAlert.has(p.sessionId)) &&
607      !['mother', 'daughter'].includes(familyOf(me, p) ?? ''),
608  )
609  const h = me.huddle!
610  const leader = leaderOf(me, peers)
611  const confirmed =
612    (h.leaderId === me.sessionId || h.ackAt ? 1 : 0) + others.filter(p => p.sessionId === h.leaderId || p.huddle?.ackAt).length
613  return {
614    kind: 'huddle',
615    size: others.length + 1,
616    confirmed,
617    leader: leader ? who(leader) : { title: '', task: '', hostId: '' },
618    leaderIsMe: h.leaderId === me.sessionId,
619    conflicts: ownerConflicts(leader?.huddle?.lead, [me, ...others], now),
620    ...(family ? { family } : {}),
621  }
622}
623
624/** The live sessions of my family, for the dim line of the band; undefined when there are none. */
625export function familyLine(me: Presence, peers: Presence[], now: number): Family | undefined {
626  const mother = motherOf(me, peers, now)
627  const daughters = peers.filter(p => p.sessionId !== me.sessionId && isLive(p, now) && familyOf(me, p) === 'daughter').length
628  return mother || daughters ? { ...(mother ? { mother: who(mother) } : {}), daughters } : undefined
629}
630
631/** A repo's short name: the last part of its remote, or, with no remote (the key is its git directory), its folder. */
632export function repoNameOf(repoKey: string, toplevel: string): string {
633  const fromKey = repoKey.split('/').filter(Boolean).at(-1)?.replace(/\.git$/, '') ?? ''
634  return fromKey || slashes(toplevel).split('/').filter(Boolean).at(-1) || toplevel
635}
636
637/** A huddle message cut to what a busy agent needs now: who, what clashes and how to answer. The protocol's later
638 * points and the machine lines are left for the full message, which still arrives when the turn ends. */
639export function compactForMidTurn(text: string, max = 1500): string {
640  const lines = stripMarkers(text)
641    .split('\n')
642    .filter(line => !/^\s*[2-9]\.\s/.test(line))
643  const out = lines.join('\n').trim()
644  return out.length > max ? `${out.slice(0, max - 1)}…` : out
645}
646
types/index.d.ts 60 lines
1export type Level = 1 | 2 | 3
2
3/** Why a peer raised its level: same files, both on single-owner files, same working copy, or just the same repo. */
4export type AlertKind = 'overlap' | 'hot' | 'checkout' | 'repo'
5
6export type Alert = {
7  sessionId: string
8  level: Level
9  kind: AlertKind
10  /** The repo the alert is about: the strongest one the two sessions share. */
11  repoKey: string
12  repoName: string
13  /** The name the person sees for that session (its sidebar title), when it has one. */
14  title: string
15  /** The desktop app's id for that session, so the band can open it; empty outside the app. */
16  hostId: string
17  task: string
18  branch: string
19  overlap: string[]
20  /** Set when the peer was started by the same session that started this one (a sister): it alerts only on level 3. */
21  family?: 'sister'
22}
23
24/** How a session is named to the person, and how the band opens it. */
25export type Who = { title: string; task: string; hostId: string }
26
27/** A member of the huddle edited a file the agreement gave to another member. */
28export type OwnerConflict = { editor: Who; owner: Who; repoName: string; file: string }
29
30/** The live sessions of this one's family in the desktop app: the one that started it and the ones it started. */
31export type Family = { mother?: Who; daughters: number }
32
33/** What the band shows: nothing, the peers that are not in the huddle, a calm line when everyone is, or only the family. */
34export type BandState =
35  | { kind: 'none' }
36  | { kind: 'family'; family: Family }
37  | { kind: 'alert'; alerts: Alert[]; hasHuddle: boolean; family?: Family }
38  | {
39      kind: 'huddle'
40      size: number
41      confirmed: number
42      leader: Who
43      leaderIsMe: boolean
44      conflicts: OwnerConflict[]
45      family?: Family
46    }
47
48export type CoordResult = { at: number; sent: number; failed: string[] }
49
50declare module 'claude-code' {
51  interface PluginState {
52    huddle: {
53      alerts: Alert[]
54      band: BandState
55      snoozeUntil: number
56      lastCoord: CoordResult | null
57    }
58  }
59}
60