SLOPSHOPPER

guildhall-tavern

A live pane of the Guildhall during a /quest: who is working, what they are up to in character, and who answers to whom; a recap of phase times and reviewer…

panebandguardcommandstatusprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · guildhall-tavern
│ ┃ The Tavern ✕ › fix the failing auth test and add an audit log call │ ┃ 🧙 The tavern is quiet. │ ┃ Mordain waits by the hearth. Issue /quest to ⏺ Read(src/auth.ts) │ ┃ call the guild. ⎿ Read 6 lines │ ⏺ 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 │ │ › /guildhall-tavern │ ⎿ guildhall-tavern: The tavern door swings open. (Surfaces attache │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · The Tavern
🧙 The tavern is quiet. Mordain waits by the hearth. Issue /quest to call the guild.
README

guildhall-tavern

A Claude Code mod that draws the Guildhall tavern as a live pane while a /quest runs: Mordain at the top, every adventurer he summons grouped by phase (Build chain, Review fan-out, Closer, Field work, Hirelings), each with an icon, a spinner while at work, the model the spawn resolved to, elapsed time, a deed count, and one in-character line for what they are doing right now ("Bruga forges rate_limit.ts", "Oriana searches for unwatched gates: password"). A short chronicle under the tree records summons and returns.

When Mordain's turn ends with nobody left in the field, a recap appears: who answered and who fell, the wall-clock time each phase held the road, and the gating verdicts from the plan scroll's ## Reviewers selected (the scroll is the docs/guildhall/plans/*.md file Mordain himself wrote this quest). A reviewer the scroll planned but nobody summoned, or skipped yet summoned, is flagged with ⚠. A fast-lane quest has no scroll and says so.

With the pane closed (or behind another tab), a one-line band above the prompt keeps the quest in sight: ⚔ Review fan-out · 🦉📖 at work, Mordain's own line between dispatches, then recap ready once the hall is quiet, with a Tavern button that opens the pane. It steps aside for surveys and goes quiet when you send your next prompt after the quest settles. The band draws on the terminal and desktop surfaces.

It is a spectator. It reads agent.spawn, tool.call, turn.complete, command.run, prompt.submit and ui.close (and the quest's plan scroll), never changes them, and every hook falls through to the engine if its own bookkeeping fails. It does not touch the guildhall plugin, its agents or /quest.

Install

From the GrillerGeek plugin marketplace, alongside Guildhall:

claude plugin marketplace add https://github.com/GrillerGeek/skills.git
claude plugin install guildhall-tavern@grillergeek-plugins

Or in a Claude Code session: /plugin install guildhall-tavern --marketplace GrillerGeek/skills.

Already have the marketplace from installing Guildhall? A copy added before the tavern was listed does not show it until refreshed:

claude plugin marketplace update grillergeek-plugins

It is a function-hook mod, written and tested against Claude Code 2.1.295. For local development, load the folder directly:

claude --plugin-dir <repo>/plugin --plugin-dir <repo>/mods/guildhall-tavern

The pane opens itself when a /quest starts, or when a guild agent is dispatched outside one. /guildhall-tavern opens it any time.

The pane needs a surface that draws mod UI: the Claude Code terminal (a pane you did not ask for waits for 144 columns; asked for, it opens at any width) or a local session in the desktop app. A cloud session viewed from the Claude app attaches no such surface, so there /guildhall-tavern prints the tavern as text instead; run it again for a fresh look.

Where things live

  • hooks/roster.ts: one entry per agent in plugin/agents/, voiced from plugin/CHARACTERS.md. A new adventurer needs a row here or it shows as a hireling; tests/test_tavern_roster.py fails CI until it has one, and when a roster name drifts from its character sheet.
  • hooks/register.tsx: the hooks and the pane.
  • types/index.d.ts: the session state the pane draws from.

Check it

claude plugin validate mods/guildhall-tavern
claude plugin test mods/guildhall-tavern
Source 4 files
hooks/register.tsx 531 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { ChronicleEntry, GuildMember, GuildQuest, Recap } from '../types'
5import { isPlanScroll, phaseSpans, planStatus, reviewerVerdicts, rootPhase } from './recap'
6import { KEEPER, PHASES, characterOf, classify, flavor, guildRole, shorten } from './roster'
7import type { Character } from './roster'
8
9const PANE = 'guildhall'
10const TITLE = 'The Tavern'
11const SPINNER = ['◐', '◓', '◑', '◒']
12const CHRONICLE_LENGTH = 8
13const MEMBER_LIMIT = 40
14const EARLIER_LIMIT = 5
15
16const quest = atom({ plugin: 'guildhall-tavern', key: 'quest' } as const, null as GuildQuest | null)
17const members = atom({ plugin: 'guildhall-tavern', key: 'members' } as const, [] as GuildMember[])
18const chronicle = atom({ plugin: 'guildhall-tavern', key: 'chronicle' } as const, [] as ChronicleEntry[])
19// One collapsed line per finished quest, oldest first.
20const earlier = atom({ plugin: 'guildhall-tavern', key: 'earlier' } as const, [] as string[])
21const tick = atom({ plugin: 'guildhall-tavern', key: 'tick' } as const, 0)
22const recap = atom({ plugin: 'guildhall-tavern', key: 'recap' } as const, null as Recap | null)
23// Set once the person moves on from a settled quest: the band has said its piece.
24const bandQuiet = atom({ plugin: 'guildhall-tavern', key: 'bandQuiet' } as const, false)
25
26// Which surfaces have asked this module to draw the pane since it loaded: diagnostics only.
27const drawnOn = new Set<string>()
28
29async function whereText($: EngineInterface): Promise<string> {
30  const surfaces = await $.session.surfaces()
31  const pane = (await $.ui.panes()).find(p => p.id === PANE)
32  const state = pane ? `placed ${pane.isPlaced}, shown ${pane.isShown}` : 'not open'
33  const drawn = drawnOn.size > 0 ? [...drawnOn].join(', ') : 'none yet'
34  return `Surfaces attached: ${surfaces.join(', ') || 'none'} · pane: ${state} · drawn on: ${drawn}`
35}
36
37const isQuestCommand = (command: string) => command === 'quest' || command === 'guildhall:quest'
38
39const elapsed = (ms: number) => {
40  const s = Math.max(0, Math.floor(ms / 1000))
41  return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
42}
43
44const memberCharacter = (m: GuildMember): Character => characterOf(m.role)
45
46async function record($: EngineInterface, icon: string, text: string) {
47  await update($, chronicle, list => [...(list ?? []), { at: Date.now(), icon, text }].slice(-CHRONICLE_LENGTH))
48}
49
50async function beginQuest($: EngineInterface, title: string, planPath?: string) {
51  const previous = await read($, quest)
52  const band = (await read($, members)) ?? []
53  if (previous !== null && band.length > 0) {
54    const line = `${shorten(previous.title, 60)} · ${band.length} summoned`
55    await update($, earlier, list => [...(list ?? []), line].slice(-EARLIER_LIMIT))
56  }
57  await update($, quest, () => ({
58    title,
59    ...(planPath !== undefined ? { planPath } : {}),
60    startedAt: Date.now(),
61    keeperLine: `${KEEPER.name} reads the whole scroll before speaking`,
62    isKeeperBusy: true,
63  }))
64  await update($, members, () => [])
65  await update($, chronicle, () => [])
66  await update($, recap, () => null)
67  await update($, bandQuiet, () => false)
68  await record($, KEEPER.icon, `${KEEPER.name}: “${KEEPER.catchphrase}”`)
69  // A surface that cannot seat the pane leaves the ledger kept; /guildhall-tavern opens it later.
70  await $.ui.open({ id: PANE, title: TITLE }).catch(() => undefined)
71  await refreshStatus($)
72}
73
74/**
75 * A guild agent dispatched outside /quest still gets a hall to work in. Created only
76 * when none exists, in one write, so agents dispatched together share one quest.
77 */
78async function ensureQuest($: EngineInterface, title: string) {
79  await update($, quest, current =>
80    current ?? {
81      title,
82      startedAt: Date.now(),
83      keeperLine: `${KEEPER.name} sends adventurers out on an errand`,
84      isKeeperBusy: true,
85    },
86  )
87  await $.ui.open({ id: PANE, title: TITLE }).catch(() => undefined)
88}
89
90async function setKeeper($: EngineInterface, line: string, isKeeperBusy = true) {
91  await update($, quest, q => (q ? { ...q, keeperLine: line, isKeeperBusy } : q))
92  await refreshStatus($)
93}
94
95type RecapRow = { text: string; tone: 'head' | 'ok' | 'skip' | 'warn' | 'dim' }
96
97const fileName = (path: string) => shorten(path.split('/').pop() ?? path, 60)
98
99/** The recap as rows both the pane and the text fallback draw; none while anyone works. */
100function recapRows(r: Recap | null, list: GuildMember[], now: number): RecapRow[] {
101  if (r === null || list.some(m => m.status === 'working')) return []
102  const fallen = list.filter(m => m.status === 'fallen').length
103  const icons = list.map(m => memberCharacter(m).icon).join('')
104  const rows: RecapRow[] = [
105    { text: `Recap · ${r.status ?? 'the hall is quiet'}`, tone: 'head' },
106    { text: `  Summoned ${icons || 'nobody'} · ${list.length - fallen} returned, ${fallen} fallen`, tone: 'dim' },
107  ]
108  const spans = phaseSpans(list, now)
109  if (spans.length > 0) {
110    rows.push({ text: `  Time     ${spans.map(s => `${s.label} ${elapsed(s.ms)}`).join(' · ')}`, tone: 'dim' })
111  }
112  const summoned = new Set(list.map(m => m.role))
113  for (const v of r.reviewers) {
114    const who = characterOf(v.role)
115    const label = `${who.icon} ${who.name}`
116    const why = v.reason ? ` — ${v.reason}` : ''
117    if (v.fired && summoned.has(v.role)) rows.push({ text: `  ✓ ${label}${why}`, tone: 'ok' })
118    else if (!v.fired && !summoned.has(v.role)) rows.push({ text: `  · ${label} skipped${why}`, tone: 'skip' })
119    else if (v.fired) rows.push({ text: `  ⚠ ${label} planned, never summoned${why}`, tone: 'warn' })
120    else rows.push({ text: `  ⚠ ${label} skipped in the scroll, yet summoned${why}`, tone: 'warn' })
121  }
122  const scroll =
123    r.planPath === undefined
124      ? 'no plan scroll (fast lane or prototype)'
125      : r.problem !== undefined
126        ? `could not read ${fileName(r.planPath)}: ${r.problem}`
127        : `Scroll ${fileName(r.planPath)}`
128  rows.push({ text: `  ${scroll}`, tone: 'dim' })
129  return rows
130}
131
132/** Mordain's turn ended with nobody in the field: read the scroll and settle the recap. */
133async function settle($: EngineInterface) {
134  const q = await read($, quest)
135  const list = (await read($, members)) ?? []
136  if (q === null || list.some(m => m.status === 'working')) return
137  const planPath = q.planPath
138  let next: Recap = { at: Date.now(), planPath, reviewers: [] }
139  if (planPath !== undefined) {
140    try {
141      const text = await $.fs.read(planPath)
142      next = { ...next, status: planStatus(text), reviewers: reviewerVerdicts(text) }
143    } catch (error) {
144      next = { ...next, problem: shorten(error instanceof Error ? error.message : String(error), 60) }
145    }
146  }
147  await update($, recap, () => next)
148}
149
150/**
151 * The band's one line, for when the pane is out of view: the phases at work and
152 * who is in them, else Mordain's own line, else a pointer to the recap.
153 */
154function bandText(q: GuildQuest | null, list: GuildMember[], r: Recap | null, isQuiet: boolean): string | undefined {
155  if (q === null || isQuiet) return undefined
156  const working = list.filter(m => m.status === 'working')
157  if (working.length > 0) {
158    const phases = PHASES.flatMap(p => {
159      const here = working.filter(m => rootPhase(list, m) === p.phase)
160      return here.length > 0 ? [`${p.label} · ${here.map(m => memberCharacter(m).icon).join('')} at work`] : []
161    })
162    return `⚔ ${phases.join(' · ')}`
163  }
164  if (r !== null) return `⚔ ${shorten(q.title, 40)} · recap ready${r.status ? ` (${r.status})` : ''}`
165  return `⚔ ${shorten(q.title, 40)} · ${KEEPER.icon} ${q.keeperLine}`
166}
167
168/** The pane is in view somewhere: the band would only repeat it. */
169async function isPaneInView($: EngineInterface): Promise<boolean> {
170  const pane = (await $.ui.panes()).find(p => p.id === PANE)
171  return pane !== undefined && pane.isShown && pane.isPlaced
172}
173
174/** The tavern as plain text: the command's answer where no surface draws the pane. */
175function tavernText(
176  q: GuildQuest | null,
177  list: GuildMember[],
178  log: ChronicleEntry[],
179  r: Recap | null,
180  now: number,
181  past: string[] = [],
182): string {
183  if (q === null) return `${KEEPER.icon} The tavern is quiet. ${KEEPER.name} waits by the hearth.`
184  const mark = (m: GuildMember) => (m.status === 'working' ? '▶' : m.status === 'done' ? '✓' : '✗')
185  const lines = [
186    `⚔ ${q.title} (${elapsed(now - q.startedAt)} on the road)`,
187    `${q.isKeeperBusy ? '▶' : '·'} ${KEEPER.icon} ${KEEPER.name} ${KEEPER.title}: ${q.keeperLine}`,
188  ]
189  for (const p of PHASES) {
190    const group = list.filter(m => memberCharacter(m).phase === p.phase)
191    if (group.length === 0) continue
192    lines.push(`  ${p.label}`)
193    for (const m of group) {
194      const who = memberCharacter(m)
195      lines.push(`    ${mark(m)} ${who.icon} ${who.name} ${who.title} (${m.role}, ${elapsed((m.endedAt ?? now) - m.startedAt)}, ${m.deeds} deeds): ${m.task ? `${m.task} — ` : ''}${m.line}`)
196    }
197  }
198  if (past.length > 0) lines.push(`  Earlier: ${past.join(' · ')}`)
199  lines.push(...recapRows(r, list, now).map(row => `  ${row.text}`))
200  if (log.length > 0) lines.push('  Chronicle', ...log.map(entry => `    ${entry.icon} ${entry.text}`))
201  return lines.join('\n')
202}
203
204/** One status-line entry that follows the quest on every surface, pane or no pane. */
205async function refreshStatus($: EngineInterface) {
206  const q = await read($, quest)
207  if (q === null) return $.ui.status(undefined)
208  const list = (await read($, members)) ?? []
209  const working = list.filter(m => m.status === 'working')
210  if (working.length > 0) {
211    return $.ui.status(`⚔ ${working.map(m => `${memberCharacter(m).icon} ${m.line}`).join(' · ')}`)
212  }
213  $.ui.status(`⚔ ${KEEPER.icon} ${q.keeperLine}${list.length > 0 ? ` · ${list.length} summoned, all returned` : ''}`)
214}
215
216export const register: Register = on => {
217  on('session.start', async ($, e, next) => {
218    await $.command.register({
219      name: 'guildhall-tavern',
220      description: 'Open the Guildhall tavern: who is on the quest and what they are doing',
221    })
222    // Spinners and running clocks advance only while someone is at work.
223    $.clock.every(500, () => {
224      void (async () => {
225        const list = (await read($, members)) ?? []
226        const q = await read($, quest)
227        if (list.some(m => m.status === 'working') || q?.isKeeperBusy) {
228          await update($, tick, n => (n ?? 0) + 1)
229        }
230      })()
231    })
232    return next(e)
233  })
234
235  on('command.run', { command: 'guildhall-tavern' }, async $ => {
236    const opened = await $.ui.open({ id: PANE, title: TITLE })
237    await update($, tick, n => (n ?? 0) + 1) // the band redraws: the pane may now be in view
238    // With no surface attached (a cloud session viewed from an app) every pane reads
239    // as placed, yet nothing draws it: only this command's text reaches the person.
240    const surfaces = await $.session.surfaces()
241    if (opened.isPlaced && surfaces.length > 0) {
242      return { text: `The tavern door swings open. (${await whereText($)})` }
243    }
244    const why = opened.isPlaced ? 'no surface that draws panes is attached to this session' : opened.reason
245    const snapshot = tavernText(
246      await read($, quest),
247      (await read($, members)) ?? [],
248      (await read($, chronicle)) ?? [],
249      await read($, recap),
250      Date.now(),
251      (await read($, earlier)) ?? [],
252    )
253    return { text: `The pane cannot be drawn here (${why}). Run /guildhall-tavern again for a fresh look.\n\n${snapshot}` }
254  })
255
256  // A /quest begins a fresh ledger. The hook only watches; the command runs as typed.
257  on('command.run', async ($, e, next) => {
258    if (isQuestCommand(e.command)) {
259      await beginQuest($, shorten(e.args ?? '', 80) || 'An unnamed quest')
260    }
261    return next(e)
262  }).catch(($, e, next) => next(e))
263
264  on('agent.spawn', async ($, e, next) => {
265    const role = guildRole(e.subagentType)
266    if (role === undefined && (await read($, quest)) === null) return next(e)
267
268    const spawned = await next(e)
269    if (spawned.deny !== undefined || spawned.agentId === undefined) return spawned
270    if (role !== undefined) await ensureQuest($, shorten(e.description ?? '', 80) || 'An impromptu errand')
271
272    const who = role ? characterOf(role) : characterOf(e.subagentType)
273    const member: GuildMember = {
274      id: spawned.agentId,
275      role: role ?? e.subagentType,
276      parentId: e.parentAgentId,
277      status: 'working',
278      task: shorten(e.description ?? '', 80),
279      line: `${who.name} answers the summons`,
280      deeds: 0,
281      model: spawned.model,
282      startedAt: Date.now(),
283    }
284    await update($, members, list => [...(list ?? []), member].slice(-MEMBER_LIMIT))
285    await update($, bandQuiet, () => false)
286    await refreshStatus($)
287    if (e.parentAgentId === undefined) {
288      await setKeeper($, `${KEEPER.name} summons ${who.name}`)
289    }
290    await record($, who.icon, `${who.name} ${who.title} takes up: ${member.task}`)
291    return spawned
292  }).catch(($, e, next) => next(e)) // the pane is a spectator: a bookkeeping failure never blocks a dispatch
293
294  on('tool.call', async ($, e, next) => {
295    const q = await read($, quest)
296    if (q === null) return next(e)
297    const { deed, target } = classify(String(e.tool), e as unknown as Record<string, unknown>)
298
299    if (e.agentId === undefined) {
300      // The main loop is Mordain; his summons are drawn by agent.spawn.
301      if (e.tool !== 'Agent') await setKeeper($, flavor(KEEPER, deed, target))
302      if (e.tool === 'Skill') {
303        const skill = (e as { skill?: unknown }).skill
304        if (typeof skill === 'string' && isQuestCommand(skill)) {
305          const args = (e as { args?: unknown }).args
306          await beginQuest($, shorten(typeof args === 'string' ? args : '', 80) || 'An unnamed quest')
307        }
308        return next(e)
309      }
310      const path = (e as { file_path?: unknown }).file_path
311      if (deed !== 'write' || typeof path !== 'string' || !isPlanScroll(path)) return next(e)
312      // Only a scroll that was actually written is the one the recap reads.
313      const wrote = await next(e)
314      if (wrote.deny === undefined && wrote.isError !== true) {
315        if (q.planPath !== undefined && q.planPath !== path) {
316          await beginQuest($, q.title, path)
317          return wrote
318        }
319        await update($, quest, current => (current ? { ...current, planPath: path } : current))
320      }
321      return wrote
322    }
323
324    const agentId = e.agentId
325    const list = (await read($, members)) ?? []
326    const member = list.find(m => m.id === agentId)
327    if (member === undefined) return next(e)
328    const line = flavor(memberCharacter(member), deed, target)
329    await update($, members, all =>
330      (all ?? []).map(m => (m.id === agentId ? { ...m, line, deeds: m.deeds + 1 } : m)),
331    )
332    await refreshStatus($)
333    return next(e)
334  }).catch(($, e, next) => next(e))
335
336  on('turn.complete', async ($, e, next) => {
337    const done = await next(e)
338    const q = await read($, quest)
339    if (q === null) return done
340
341    if (e.agentId === undefined) {
342      await setKeeper($, flavor(KEEPER, 'idle', ''), false)
343      await settle($)
344      return done
345    }
346
347    const agentId = e.agentId
348    const list = (await read($, members)) ?? []
349    const member = list.find(m => m.id === agentId)
350    if (member === undefined || member.status !== 'working') return done
351    const who = memberCharacter(member)
352    const fell = e.isAborted || e.reason === 'error' || e.reason === 'refusal'
353    await update($, members, all =>
354      (all ?? []).map(m =>
355        m.id === agentId
356          ? {
357              ...m,
358              status: fell ? 'fallen' : 'done',
359              line: fell ? `${who.name} was called back from the field` : `“${who.catchphrase}”`,
360              endedAt: Date.now(),
361            }
362          : m,
363      ),
364    )
365    await record(
366      $,
367      who.icon,
368      fell ? `${who.name} returns empty-handed` : `${who.name} returns to the hall (${elapsed(Date.now() - member.startedAt)})`,
369    )
370    await refreshStatus($)
371    // The last of a background fan-out may return after Mordain's turn has ended.
372    if ((await read($, quest))?.isKeeperBusy === false) await settle($)
373    return done
374  }).catch(($, e, next) => next(e)) // replays the turn's own answer; nothing runs twice
375
376  // A settled quest's band stands down once the person moves on.
377  on('prompt.submit', async ($, e, next) => {
378    const list = (await read($, members)) ?? []
379    if ((await read($, recap)) !== null && !list.some(m => m.status === 'working')) {
380      await update($, bandQuiet, () => true)
381    }
382    return next(e)
383  }).catch(($, e, next) => next(e))
384
385  // Closing the pane brings the band back: redraw it.
386  on('ui.close', async ($, e, next) => {
387    const closed = await next(e)
388    if (e.id === PANE) await update($, tick, n => (n ?? 0) + 1)
389    return closed
390  }).catch(($, e, next) => next(e))
391
392  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
393    if (e.props.hasSurvey) return next(e)
394    await read($, tick) // redraw with the pane's comings and goings
395    const line = bandText(
396      await read($, quest),
397      (await read($, members)) ?? [],
398      await read($, recap),
399      (await read($, bandQuiet)) ?? false,
400    )
401    if (line === undefined || (await isPaneInView($))) return next(e)
402    const { Box, Text, Button } = $.ui.resolve(e)
403    return (
404      <Box>
405        <Text wrap="truncate-end">{line} </Text>
406        <Button key="open-tavern" label="Tavern" onPress={() => $.ui.open({ id: PANE, title: TITLE })} />
407      </Box>
408    )
409  })
410
411  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
412    const { Box, Text } = $.ui.resolve(e)
413    drawnOn.add(e.surface)
414    const q = await read($, quest)
415    const list = (await read($, members)) ?? []
416    const log = (await read($, chronicle)) ?? []
417    const past = (await read($, earlier)) ?? []
418    const settled = recapRows(await read($, recap), list, Date.now())
419    const frame = SPINNER[((await read($, tick)) ?? 0) % SPINNER.length]
420    const now = Date.now()
421
422    if (q === null) {
423      return (
424        <Box flexDirection="column">
425          <Text bold>{KEEPER.icon} The tavern is quiet.</Text>
426          <Text dimColor>{KEEPER.name} waits by the hearth. Issue /quest to call the guild.</Text>
427        </Box>
428      )
429    }
430
431    const statusMark = (m: GuildMember) =>
432      m.status === 'working' ? frame : m.status === 'done' ? '✓' : '✗'
433    const statusColor = (m: GuildMember) =>
434      m.status === 'working' ? 'claude' : m.status === 'done' ? 'success' : 'error'
435
436    const rows: RenderChildren[] = []
437    const drawMember = (m: GuildMember, indent: string) => {
438      const who = memberCharacter(m)
439      const clock = elapsed((m.endedAt ?? now) - m.startedAt)
440      rows.push(
441        <Text wrap="truncate-end">
442          {indent}
443          <Text color={statusColor(m)}>{statusMark(m)}</Text> {who.icon} <Text bold>{who.name}</Text>
444          <Text dimColor> {who.title} · {m.role}{m.model ? ` · ${m.model}` : ''} · {clock} · {m.deeds} deeds</Text>
445        </Text>,
446      )
447      if (m.task) {
448        rows.push(
449          <Text wrap="truncate-end">
450            {indent}     {m.task}
451          </Text>,
452        )
453      }
454      rows.push(
455        <Text wrap="truncate-end" dimColor={m.status !== 'working'} italic>
456          {indent}     {m.line}
457        </Text>,
458      )
459      for (const child of list.filter(c => c.parentId === m.id)) drawMember(child, indent + '   ')
460    }
461
462    const withDescendants = (m: GuildMember): GuildMember[] => [
463      m,
464      ...list.filter(c => c.parentId === m.id).flatMap(withDescendants),
465    ]
466    const ids = new Set(list.map(m => m.id))
467    const roots = list.filter(m => m.parentId === undefined || !ids.has(m.parentId))
468    const groups = PHASES.map(p => ({
469      ...p,
470      list: roots.filter(m => memberCharacter(m).phase === p.phase),
471    })).filter(g => g.list.length > 0)
472
473    groups.forEach((g, i) => {
474      const last = i === groups.length - 1
475      const working = g.list.flatMap(withDescendants).filter(m => m.status === 'working').length
476      rows.push(
477        <Text>
478          <Text dimColor>{last ? '└─ ' : '├─ '}</Text>
479          <Text bold>{g.label}</Text>
480          <Text dimColor>{working > 0 ? `  ${working} at work` : '  done'}</Text>
481        </Text>,
482      )
483      for (const m of g.list) drawMember(m, last ? '   ' : '│  ')
484    })
485
486    const atWork = list.filter(m => m.status === 'working').length
487    return (
488      <Box flexDirection="column">
489        <Text bold wrap="truncate-end">⚔ {q.title}</Text>
490        <Text dimColor>
491          {elapsed(now - q.startedAt)} on the road · {atWork} at work · {list.length} summoned
492        </Text>
493        <Text> </Text>
494        <Text wrap="truncate-end">
495          <Text color={q.isKeeperBusy ? 'claude' : 'subtle'}>{q.isKeeperBusy ? frame : '·'}</Text> {KEEPER.icon}{' '}
496          <Text bold>{KEEPER.name}</Text>
497          <Text dimColor> {KEEPER.title} · Guildmaster</Text>
498        </Text>
499        <Text wrap="truncate-end" italic dimColor={!q.isKeeperBusy}>
500          {'     '}{q.keeperLine}
501        </Text>
502        {rows}
503        {past.length > 0 && <Text> </Text>}
504        {past.length > 0 && (
505          <Text wrap="truncate-end" dimColor>
506            Earlier: {past.join(' · ')}
507          </Text>
508        )}
509        {settled.length > 0 && <Text> </Text>}
510        {settled.map(row => (
511          <Text
512            wrap="truncate-end"
513            bold={row.tone === 'head'}
514            dimColor={row.tone === 'dim' || row.tone === 'skip'}
515            color={row.tone === 'ok' ? 'success' : row.tone === 'warn' ? 'warning' : undefined}
516          >
517            {row.text}
518          </Text>
519        ))}
520        {log.length > 0 && <Text> </Text>}
521        {log.length > 0 && <Text bold dimColor>Chronicle</Text>}
522        {log.map(entry => (
523          <Text wrap="truncate-end" dimColor>
524            {entry.icon} {entry.text}
525          </Text>
526        ))}
527      </Box>
528    )
529  })
530}
531
hooks/recap.ts 107 lines
1// The end-of-quest recap: who answered, how long each phase held the road, and the
2// gating verdicts Mordain recorded in the plan scroll's `## Reviewers selected`.
3
4import type { GuildMember, ReviewerVerdict } from '../types'
5import { PHASES, ROSTER, characterOf, shorten } from './roster'
6import type { Phase } from './roster'
7
8/** Where Mordain keeps plan scrolls; the folder's README is not one. */
9export const isPlanScroll = (path: string) =>
10  /(^|\/)docs\/guildhall\/plans\/[^/]+\.md$/.test(path) && !/\/README\.md$/i.test(path)
11
12/** `Oriana`, `oriana`, `security-reviewer` → `security-reviewer`; undefined for anyone else. */
13export function roleByName(name: string): string | undefined {
14  const wanted = name.trim().replace(/^`|`$/g, '').toLowerCase()
15  if (Object.hasOwn(ROSTER, wanted)) return wanted
16  return Object.keys(ROSTER).find(role => ROSTER[role]?.name.toLowerCase() === wanted)
17}
18
19/** The bullets under `## Reviewers selected`, up to the next `## ` heading. */
20export function reviewerBullets(markdown: string): string[] {
21  const lines = markdown.split(/\r?\n/)
22  const start = lines.findIndex(l => /^##\s+Reviewers selected\s*$/i.test(l))
23  if (start < 0) return []
24  const bullets: string[] = []
25  for (const line of lines.slice(start + 1)) {
26    if (/^##\s/.test(line)) break
27    const bullet = /^\s*[-*]\s+(.*)$/.exec(line)
28    if (bullet?.[1]) bullets.push(bullet[1])
29  }
30  return bullets
31}
32
33/**
34 * One bullet → the verdicts it records. Plan scrolls come in two dialects:
35 *
36 *   template:  Vance (`observability-reviewer`) — skipped — docs-only change
37 *              Oriana (`security-reviewer`) — fires
38 *   freeform:  Oriana security: API credential handling, untrusted input
39 *              Skip Vera/Lior: no visual UI changes.
40 *
41 * A bullet naming nobody on the roster (`Always-on:` stray text) yields [].
42 */
43export function parseReviewerLine(line: string): ReviewerVerdict[] {
44  // "Skip Ysolde: no migration. Skip Vera/Lior: no UI." is one bullet holding two clauses.
45  const clauses = line.split(/(?<=[.;])\s+(?=skip\b)/i)
46  return clauses.flatMap(parseClause)
47}
48
49function parseClause(line: string): ReviewerVerdict[] {
50  // Names are read from the head only, so a reviewer mentioned in a reason is not a verdict.
51  // A bullet with no separator ("Tink only if a refactor is needed") records no verdict.
52  const dashed = line.split(/\s+[—–]\s+/)
53  const colon = line.indexOf(':')
54  const [head, verdict, reason] =
55    dashed.length > 1
56      ? [dashed[0] ?? '', dashed[1] ?? '', dashed.slice(2).join(' — ')]
57      : colon > 0
58        ? [line.slice(0, colon), '', line.slice(colon + 1)]
59        : ['', '', '']
60  const fired = !/^\s*skip\b/i.test(head) && !/^skip(ped|s)?\b/i.test(verdict.trim())
61  const roles = new Set(head.split(/[\s/,()`]+/).flatMap(word => roleByName(word) ?? []))
62  return [...roles].map(role => ({ role, fired, reason: reason.trim() }))
63}
64
65/** Every verdict in the section; a later bullet about the same role wins. */
66export function reviewerVerdicts(markdown: string): ReviewerVerdict[] {
67  const byRole = new Map<string, ReviewerVerdict>()
68  for (const bullet of reviewerBullets(markdown)) {
69    for (const v of parseReviewerLine(bullet)) {
70      byRole.set(v.role, { ...v, reason: shorten(v.reason, 60) })
71    }
72  }
73  return [...byRole.values()]
74}
75
76/** The frontmatter's `status:` (in_progress, completed, abandoned), if the scroll has one. */
77export function planStatus(markdown: string): string | undefined {
78  const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)?.[1]
79  const status = front && /^status:\s*([\w-]+)/m.exec(front)?.[1]
80  return status || undefined
81}
82
83/** The phase a member works in: its root's, so a hireling counts with whoever hired it. */
84export function rootPhase(list: GuildMember[], m: GuildMember): Phase {
85  let at = m
86  for (let hops = 0; at.parentId !== undefined && hops < list.length; hops++) {
87    const parent = list.find(p => p.id === at.parentId)
88    if (parent === undefined) break
89    at = parent
90  }
91  return characterOf(at.role).phase
92}
93
94/**
95 * Wall-clock time each phase held the road: first summons to last return, so a
96 * parallel fan-out counts once, not once per reviewer. A child counts with its root.
97 */
98export function phaseSpans(list: GuildMember[], now: number): { phase: Phase; label: string; ms: number }[] {
99  return PHASES.flatMap(p => {
100    const group = list.filter(m => rootPhase(list, m) === p.phase)
101    if (group.length === 0) return []
102    const start = Math.min(...group.map(m => m.startedAt))
103    const end = Math.max(...group.map(m => m.endedAt ?? now))
104    return [{ phase: p.phase, label: p.label, ms: Math.max(0, end - start) }]
105  })
106}
107
hooks/roster.ts 299 lines
1// The guild as the pane draws it: one entry per agent in plugin/agents/,
2// voiced from plugin/CHARACTERS.md. `{x}` in a line is the deed's target.
3
4export type Phase = 'build' | 'review' | 'closer' | 'standalone' | 'hireling'
5
6export type Deed = 'read' | 'search' | 'write' | 'run' | 'ask' | 'ledger' | 'idle'
7
8export type Character = {
9  name: string
10  title: string
11  icon: string
12  phase: Phase
13  catchphrase: string
14  lines: Partial<Record<Deed, string>>
15}
16
17export const PHASES: { phase: Phase; label: string }[] = [
18  { phase: 'build', label: 'Build chain' },
19  { phase: 'review', label: 'Review fan-out' },
20  { phase: 'closer', label: 'Closer' },
21  { phase: 'standalone', label: 'Field work' },
22  { phase: 'hireling', label: 'Hirelings' },
23]
24
25export const KEEPER: Character = {
26  name: 'Mordain',
27  title: 'the Keeper',
28  icon: '🧙',
29  phase: 'standalone',
30  catchphrase: 'First, the plan. Then, the adventurers.',
31  lines: {
32    read: 'reads the whole scroll before speaking: {x}',
33    search: 'consults the archives for {x}',
34    write: 'inks the plan: {x}',
35    run: 'sends a runner on an errand: {x}',
36    ask: 'awaits the patron’s word',
37    ledger: 'updates the ledger',
38    idle: 'rests in the high chair by the hearth',
39  },
40}
41
42export const ROSTER: Record<string, Character> = {
43  'prototype-builder': {
44    name: 'Pip', title: 'the Scout', icon: '🎒', phase: 'standalone',
45    catchphrase: 'Here, it runs! Don’t ask what happens on Tuesday.',
46    lines: {
47      read: 'peeks at {x} between bites', search: 'rummages around for {x}',
48      write: 'lashes together {x}', run: 'pokes it to see if it runs: {x}',
49      idle: 'chews thoughtfully',
50    },
51  },
52  'test-author': {
53    name: 'Seraphine', title: 'the Oracle', icon: '🔮', phase: 'build',
54    catchphrase: 'The spec is written. The test is its shadow.',
55    lines: {
56      read: 'reads the spec as scripture: {x}', search: 'seeks the Expectation of {x}',
57      write: 'inscribes a prophecy: {x}', run: 'watches the prophecy fail, as foretold: {x}',
58      idle: 'meditates on the spec, eyes averted from the code',
59    },
60  },
61  'feature-implementer': {
62    name: 'Bruga', title: 'the Smith', icon: '🔨', phase: 'build',
63    catchphrase: 'Show me the blueprint.',
64    lines: {
65      read: 'studies the blueprint: {x}', search: 'sorts the scrap pile for {x}',
66      write: 'forges {x}', run: 'quenches the blade: {x}',
67      idle: 'stokes the forge',
68    },
69  },
70  refactorer: {
71    name: 'Tink', title: 'the Enchanter', icon: '✨', phase: 'build',
72    catchphrase: 'Same stone. Better setting.',
73    lines: {
74      read: 'turns {x} in the light', search: 'hunts loose settings in {x}',
75      write: 'resets the stone: {x}', run: 'checks the shine holds: {x}',
76      idle: 'polishes quietly',
77    },
78  },
79  'architecture-reviewer': {
80    name: 'Aldric', title: 'the Cartographer', icon: '📐', phase: 'build',
81    catchphrase: 'Three paths lie open. Only one leads forward without debt.',
82    lines: {
83      read: 'surveys the terrain of {x}', search: 'traces the roads to {x}',
84      run: 'paces the distance: {x}', idle: 'weighs three paths',
85    },
86  },
87  'debug-investigator': {
88    name: 'Kael', title: 'the Tracker', icon: '🏹', phase: 'standalone',
89    catchphrase: 'I know WHY. What you do next is not my tale to tell.',
90    lines: {
91      read: 'reads the tracks in {x}', search: 'follows the trail of {x}',
92      write: 'marks the trail: {x}', run: 'sets a snare: {x}',
93      idle: 'kneels to study the ground',
94    },
95  },
96  'ui-test-author': {
97    name: 'Vera', title: 'the Playwright', icon: '🎭', phase: 'review',
98    catchphrase: 'The curtain has risen. Let us see if the play matches the script.',
99    lines: {
100      read: 'reads the script: {x}', search: 'scouts the stage for {x}',
101      write: 'writes the scene: {x}', run: 'raises the curtain: {x}',
102      idle: 'rehearses the blocking',
103    },
104  },
105  'security-reviewer': {
106    name: 'Oriana', title: 'the Watcher', icon: '🦉', phase: 'review',
107    catchphrase: 'Trust no path you have not walked.',
108    lines: {
109      read: 'walks the wall past {x}', search: 'searches for unwatched gates: {x}',
110      run: 'tests the lock: {x}', idle: 'keeps the watch',
111    },
112  },
113  'docs-writer': {
114    name: 'Cassian', title: 'the Scribe', icon: '📖', phase: 'review',
115    catchphrase: 'A song is only as true as the singer who remembers it.',
116    lines: {
117      read: 'reads the old songs: {x}', search: 'seeks the verse about {x}',
118      write: 'sets down the verse: {x}', run: 'checks the tune: {x}',
119      idle: 'sharpens the quill',
120    },
121  },
122  'observability-reviewer': {
123    name: 'Vance', title: 'the Chronicler', icon: '📜', phase: 'review',
124    catchphrase: 'What happened, and would we know if it happened again?',
125    lines: {
126      read: 'reads the chronicle of {x}', search: 'searches for unrecorded deeds: {x}',
127      run: 'listens for echoes: {x}', idle: 'asks: would we know?',
128    },
129  },
130  'reliability-reviewer': {
131    name: 'Thalia', title: 'the Stormwarden', icon: '⚡', phase: 'review',
132    catchphrase: 'The wind will come. The wall must hold.',
133    lines: {
134      read: 'tests the walls of {x}', search: 'searches for cracks: {x}',
135      run: 'summons a squall: {x}', idle: 'reads the sky',
136    },
137  },
138  'performance-reviewer': {
139    name: 'Cassia', title: 'the Smith of Cycles', icon: '⏳', phase: 'review',
140    catchphrase: 'Every cycle costs something. Pay it knowingly.',
141    lines: {
142      read: 'counts the cycles in {x}', search: 'hunts hot loops: {x}',
143      run: 'times the forge: {x}', idle: 'weighs the cost',
144    },
145  },
146  'ops-readiness-reviewer': {
147    name: 'Garran', title: 'the Quartermaster', icon: '📦', phase: 'review',
148    catchphrase: 'No army marches without a wagon train.',
149    lines: {
150      read: 'inspects the supply lines in {x}', search: 'inventories {x}',
151      run: 'loads the wagon: {x}', idle: 'drafts the marching orders',
152    },
153  },
154  'migration-safety-reviewer': {
155    name: 'Ysolde', title: 'the Gravedigger', icon: '🪦', phase: 'review',
156    catchphrase: 'Some doors close behind you. Be sure before you walk through.',
157    lines: {
158      read: 'reads the gravestones of {x}', search: 'searches for one-way doors: {x}',
159      run: 'tests the ground: {x}', idle: 'weighs what cannot be undone',
160    },
161  },
162  'accessibility-reviewer': {
163    name: 'Lior', title: 'the Lampbearer', icon: '🏮', phase: 'review',
164    catchphrase: 'A door without a handle is a wall.',
165    lines: {
166      read: 'carries the lamp through {x}', search: 'looks for doors without handles: {x}',
167      run: 'walks the path in the dark: {x}', idle: 'trims the wick',
168    },
169  },
170  'pr-author': {
171    name: 'Rook', title: 'the Herald', icon: '📯', phase: 'closer',
172    catchphrase: 'The deed is done. Now let the tale be told precisely.',
173    lines: {
174      read: 'reviews the deeds in {x}', search: 'gathers witnesses: {x}',
175      write: 'drafts the proclamation: {x}', run: 'consults the ledger: {x}',
176      idle: 'clears the throat',
177    },
178  },
179  'fog-cartographer': {
180    name: 'Wren', title: 'the Wayfinder', icon: '🧭', phase: 'closer',
181    catchphrase: 'I mark what the scouts saw. I do not redraw coastlines I haven’t walked.',
182    lines: {
183      read: 'reads the scouts’ notes: {x}', search: 'seeks the fog line near {x}',
184      write: 'marks the map: {x}', run: 'checks the bearings: {x}',
185      idle: 'watches the fog',
186    },
187  },
188  'plugin-validator': {
189    name: 'Tabs', title: 'the Apprentice', icon: '🔩', phase: 'standalone',
190    catchphrase: 'Small checks, small surprises.',
191    lines: {
192      read: 'checks {x}, line by line', search: 'counts the rivets: {x}',
193      write: 'notes it down: {x}', run: 'runs the checks: {x}',
194      idle: 'ticks the checklist',
195    },
196  },
197  'model-echo': {
198    name: 'Echo', title: 'the Diagnostic', icon: '🔔', phase: 'standalone',
199    catchphrase: 'An echo is a hint, never proof.',
200    lines: { idle: 'rings once and listens' },
201  },
202}
203
204const GENERIC: Record<Deed, string> = {
205  read: 'reads {x}',
206  search: 'searches for {x}',
207  write: 'scribbles notes: {x}',
208  run: 'runs a command: {x}',
209  ask: 'asks the patron a question',
210  ledger: 'updates the ledger',
211  idle: 'is at work',
212}
213
214/** A subagent type the guild does not employ: `Explore`, `general-purpose`. */
215export function hireling(subagentType: string): Character {
216  return {
217    name: shorten(subagentType, 40),
218    title: 'hireling',
219    icon: '🧳',
220    phase: 'hireling',
221    catchphrase: 'Paid in full.',
222    lines: {},
223  }
224}
225
226/** `guildhall:test-author` → `test-author`; undefined for a non-guild agent. */
227export function guildRole(subagentType: string): string | undefined {
228  const role = subagentType.startsWith('guildhall:')
229    ? subagentType.slice('guildhall:'.length)
230    : subagentType
231  return Object.hasOwn(ROSTER, role) ? role : undefined
232}
233
234export function characterOf(role: string): Character {
235  return Object.hasOwn(ROSTER, role) ? (ROSTER[role] as Character) : hireling(role)
236}
237
238/** One line of plain text: control characters (terminal escapes) dropped, cut to `max`. */
239export const shorten = (text: string, max = 48) => {
240  const one = text.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]+/g, ' ').replace(/\s+/g, ' ').trim()
241  return one.length > max ? one.slice(0, max - 1) + '…' : one
242}
243
244// A URL's query and fragment can carry tokens: only its host and path are shown.
245const withoutQuery = (url: string) => {
246  try {
247    const parsed = new URL(url)
248    return parsed.origin + parsed.pathname // drops user:pass@ too
249  } catch {
250    return url.split(/[?#]/)[0]?.replace(/\/\/[^/@]*@/, '//') ?? ''
251  }
252}
253
254const basename = (path: string) => shorten(path.split('/').filter(Boolean).pop() ?? path)
255
256/** Which kind of deed a tool call is, and what it is done to. */
257export function classify(
258  tool: string,
259  input: Record<string, unknown>,
260): { deed: Deed; target: string } {
261  const str = (key: string) => (typeof input[key] === 'string' ? (input[key] as string) : '')
262  switch (tool) {
263    case 'Read':
264    case 'NotebookRead':
265      return { deed: 'read', target: basename(str('file_path') || str('notebook_path')) }
266    case 'Write':
267    case 'Edit':
268    case 'MultiEdit':
269    case 'NotebookEdit':
270      return { deed: 'write', target: basename(str('file_path') || str('notebook_path')) }
271    case 'Grep':
272    case 'Glob':
273      return { deed: 'search', target: shorten(str('pattern'), 32) }
274    case 'WebFetch':
275      return { deed: 'search', target: shorten(withoutQuery(str('url')), 40) }
276    case 'WebSearch':
277      return { deed: 'search', target: shorten(str('query'), 40) }
278    case 'Bash':
279      // A bare command can hold a credential; only the call's own description is shown.
280      return { deed: 'run', target: shorten(str('description'), 40) }
281    case 'AskUserQuestion':
282      return { deed: 'ask', target: '' }
283    case 'TodoWrite':
284    case 'TaskCreate':
285    case 'TaskUpdate':
286      return { deed: 'ledger', target: '' }
287    default:
288      return { deed: 'idle', target: shorten(tool, 40) }
289  }
290}
291
292/** The in-character line for a character doing one deed. */
293export function flavor(who: Character, deed: Deed, target: string): string {
294  const template = who.lines[deed] ?? GENERIC[deed]
295  // A deed with no target to show drops its trailing `: {x}`.
296  const line = target ? template.replace('{x}', target) : template.replace(/:\s*\{x\}$/, '').replace('{x}', 'something')
297  return `${who.name} ${line}`
298}
299
types/index.d.ts 52 lines
1export type MemberStatus = 'working' | 'done' | 'fallen'
2
3export type GuildMember = {
4  id: string
5  role: string
6  parentId?: string
7  status: MemberStatus
8  task: string
9  line: string
10  deeds: number
11  model?: string
12  startedAt: number
13  endedAt?: number
14}
15
16export type GuildQuest = {
17  title: string
18  startedAt: number
19  keeperLine: string
20  isKeeperBusy: boolean
21  /** The plan scroll Mordain last wrote this quest, as the Write named it. */
22  planPath?: string
23}
24
25/** One gating verdict from the plan's `## Reviewers selected`. */
26export type ReviewerVerdict = { role: string; fired: boolean; reason: string }
27
28/** What the plan scroll said when the hall last fell quiet. */
29export type Recap = {
30  at: number
31  planPath?: string
32  status?: string
33  reviewers: ReviewerVerdict[]
34  /** Why the scroll could not be read, when it could not. */
35  problem?: string
36}
37
38export type ChronicleEntry = { at: number; icon: string; text: string }
39
40declare module 'claude-code' {
41  interface PluginState {
42    'guildhall-tavern': {
43      quest: GuildQuest | null
44      members: GuildMember[]
45      chronicle: ChronicleEntry[]
46      tick: number
47      recap: Recap | null
48      bandQuiet: boolean
49    }
50  }
51}
52