SLOPSHOPPER

Alvearium

Alvearium: one ticket board for all your coding-agent sessions (Claude Code in the terminal and on claude.ai/code, and OpenAI Codex CLI) and their agents: what…

commandstatusnetworktimer
v0.9.24MITupdated 2026-10-26Iskandeur/alvearium
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · alvearium
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ 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 › /board ⎿ alvearium: ⎿ alvearium: No tickets yet on this machine. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Alvearium

You run five coding agents. One board tells you which one is waiting on you.

A live ticket board for Claude Code (terminal and claude.ai/code) and OpenAI Codex CLI. Zero dependencies. Two commands to install. Nothing leaves your machine unless you host a server.

claude plugin marketplace add Iskandeur/alvearium
claude plugin install alvearium@session-board

The board: what waits on you, what is in progress, what is next

Why you want it

Agents stop and ask: approve a command, add a secret, pick between two options, review a PR. The question scrolls away in a terminal you are not looking at, and the agent sits idle for hours.

  • Nothing waits unseen. Every session becomes a ticket. When one needs you, it jumps to the Waiting on you lane, with the exact question and the buttons to answer it.
  • One place for every agent. Many sessions, many repos, many machines, Claude and Codex, one board. Filter by repo, session, agent or person.
  • Agents plan with you. They file tickets for what only you can do, split long work into steps with priorities and dependencies, and pick the next unblocked one themselves.
  • Your queue, ordered. Next says what to do now, and the Matrix sorts your open tickets on the important × urgent grid.
  • Live, on your phone too. The page updates as things happen, in light and dark, desktop and phone, in English and French.
  • Yours. Local mode keeps a SQLite file under ~/.claude/. A self-hosted server (one Node process, one Docker image) adds sharing, members and invitations.

See it

| Answer in one tap | Do the important thing first | | :-: | :-: | | <img src="docs/screenshots/waiting-lane-mobile-light.png" alt="The Waiting on you lane on a phone: questions with Yes / No and A / B / C buttons" width="260"> | <img src="docs/screenshots/matrix-desktop-light.png" alt="The matrix: Do now, Schedule, Clear fast, Later" width="520"> | | Agents ask a question with its options and a default; you answer from the lane. | Urgent × important, computed from deadlines, waiting time and your priorities. |

| What is next | Tickets that wait for the world | | :-: | :-: | | <img src="docs/screenshots/next-desktop-light.png" alt="The Next view" width="400"> | <img src="docs/screenshots/on-hold-panel-desktop-light.png" alt="A ticket on hold until a pull request is merged" width="400"> | | Open, unblocked tickets by priority and by what they unblock. | A ticket can sleep until a PR is merged, a date comes, or you reply, then wake an agent. |

| Dependencies and history | Replies and hand-overs | | :-: | :-: | | <img src="docs/screenshots/detail-deps-desktop-light.png" alt="A ticket with its dependencies and its who-to-whom history" width="400"> | <img src="docs/screenshots/replies-board-desktop-light.png" alt="Two unread replies on the board" width="400"> | | Blocked tickets say by what; every change says who made it. | Unread replies surface on the board, filtered by the actor they are for. |

More in docs/screenshots: the feedback inbox, members and invitations, dark mode, the phone layouts, and a change made in one tab showing up in another without a reload.

Quick start

  1. Install (Node.js 22.13 or later on your PATH): ``bash claude plugin marketplace add Iskandeur/alvearium claude plugin install alvearium@session-board ``
  2. Restart your open Claude Code sessions: a plugin loads when a session starts.
  3. Look: type /board in a session. Tickets for your sessions are already there.
  4. Ask for work to be tracked: "Split this migration into steps and file a ticket for anything I have to do." The agent files them; /ticket next shows what is left.
  5. Want the web page, sharing or a phone view? Host the server (one Docker image): see *The web page* and *Pointing a machine at a server*. Codex CLI? One script: *Use with OpenAI Codex CLI*.

Everything below is the reference: what runs, what it reads and sends, every view, every setting.

What it looks like in a terminal

WAITING ON YOU (3)
  ⌨ SB-5 Approve Bash: npm run db:migrate -- --env staging · 6m · api@fix/token-refresh
  ⌨ SB-6 Add REFRESH_LOCK_TTL to the staging secrets · 38m · api@fix/token-refresh
  ☁ SB-7 Add a sliding-window rate limiter to the public API [review] · 22m · api@claude/rate-limit
      PR: https://github.com/acme/api/pull/412
      open: https://claude.ai/code/session_01…

IN PROGRESS (2)
  ⌨ SB-1 Fix the token refresh race in the auth middleware · 2h · api@fix/token-refresh
  ⌨ SB-17 Accessibility pass on the product page (WCAG AA) · 25m · web

TO DO (4)
  ⌨ SB-4 Add a regression test · 2h · api@fix/token-refresh
  …

What Alvearium runs, reads and sends

Alvearium is a Claude Code plugin, also usable from OpenAI Codex CLI, plus an optional self-hosted server.

What runs

  • Hooks (hooks/hooks.json → hooks/report.mjs): one zero-dependency Node script run by Claude Code on hook events (SessionStart, PreToolUse, Stop…). It turns the session state into tickets.
  • MCP server (mcp/server.mjs, stdio): lets Claude create/update/list tickets through MCP tools (ticket_create, ticket_next, …).
  • Mod (hooks/hooks.json → modules: ["./mod.mjs"]): draws the status line and implements an instant /board in the terminal (Claude Code v2.1.287+).
  • Slash commands (commands/*.md): /board, /ticket, /install-cloud just run the Node scripts in scripts/.
  • Under Codex: the same hook script and MCP server, started by Codex with --codex (see Use with OpenAI Codex CLI). No mod, no slash commands.

What it reads

  • From the environment: SESSION_BOARD_URL, SESSION_BOARD_TOKEN, and optional knobs like SESSION_BOARD_SEND_TEXT, SESSION_BOARD_MIRROR_TASKS.
  • From disk (local mode): ~/.claude/session-board/board.db and small helper files under the same directory.
  • From the session transcript (the transcript_path Claude Code hands the hook; skipped when SESSION_BOARD_SEND_TEXT=0): the last reply when a Stop or a waiting notification carries none, and the first prompt of a session the board has no title for (its first 256 KB only).
  • From plugin config: server_url and token (stored by Claude Code; token is sensitive).

What it sends

  • Nothing leaves the machine in local mode.
  • In server mode, it sends HTTPS requests only to the host of SESSION_BOARD_URL (or the server_url option). It never follows redirects (a redirect is treated as a gateway/login page, and is reported as an error).
  • Authentication is a Bearer token (SESSION_BOARD_TOKEN or the token option). In claude.ai/code, SESSION_BOARD_TOKEN=proxy means: do not send an Authorization header; the cloud agent proxy injects the configured API credential.
  • Credentials in a command or a prompt are replaced by [redacted] before they leave (header values, Bearer …, ?token=/?key= query values, *_TOKEN=/*_KEY= assignments, --token/--password flags, URL passwords, and well-known token shapes). The server applies the same filter to what older clients send (0.4.2).

Tickets, sessions, and where tickets come from

A ticket is the unit of the board: key (SB-12), title, markdown body, status, kind, assignee (user, claude, or any agent id), priority P0–P3, labels, sub-tickets, dependencies, links (PR, cloud session, file, URL), and a history of every change and comment, with who made it and for whom. A session is a context: a session has zero, one or many tickets, and you filter on it.

Statuses: todo, in_progress, waiting_on_user, review, done, cancelled, failed. The board's columns are derived: Waiting on you = waiting on you, in review or failed, assigned to you, plus the to do assigned to you whose kind asks a gesture of you (decision, action, question; never a session, a hook ticket or a trace such as a note); In progress; To do; Done folded away. Done tickets older than 30 days leave the default views (they are never deleted; Show archived brings them back).

Tickets come from three places:

  1. Hooks, automatically. Each session gets one ticket that follows it (in progress while Claude works, review when the turn ends, failed on an API error, done when the session ends). A permission prompt or a question opens a waiting on you sub-ticket that closes by itself when the session moves on. One review ticket per session, not one per turn.

| Hook event | Ticket | | :- | :- | | UserPromptSubmit, PreToolUse, PostToolUse | session ticket in progress; open questions close (tool calls throttled to one report per 20 s) | | UserPromptSubmit carrying a background task's report (<task-notification>, a Monitor's progress) | nothing: the session ticket keeps its status, and so does the turn the report starts, unless that turn needs you (0.5.4) | | PermissionRequest, Elicitation, Notification (permission_prompt, elicitation_dialog, agent_needs_input) | a waiting on you ticket (Approve Bash: …, or the question). Its body carries the question Claude's last reply ended on, the session's folder and the claude --resume <id> line to get back into it (0.5.4) | | Stop, Notification (agent_completed) | session ticket review, with the end of Claude's last message and the PR link | | StopFailure | session ticket failed, with the error | | SessionEnd | session ticket done; unanswered questions cancelled | | TaskCreated, TaskCompleted | Claude's own task list mirrored as claude tickets (SESSION_BOARD_MIRROR_TASKS=0 to turn off) | | SubagentStart, SubagentStop | a line in the session ticket's history: Claude → Explore: started it, Explore → Claude: finished: … |

  1. Claude, through MCP tools. The plugin ships a small MCP server (ticket_create, ticket_update, ticket_next, ticket_list, ticket_comment, ticket_get, ticket_attachment, board_feedback) and a skill telling Claude when to use them: an action item only you can do ("add the STRIPE_KEY secret", "review PR #412"), a long task split into prioritized sub-tickets with their dependencies, what to pick next, what is left at the end, and what wasted its time. Tickets attach to the current session and repo by themselves.
  2. You, from the web page (create, edit title / status / labels / priority, comment, close, sub-tickets) or the terminal (/ticket).

The hook is one zero-dependency Node script. It never blocks or fails your session: network calls time out after 2 s, every error is swallowed, it always exits 0, and hot-path events run async.

Waiting for the world (0.8.0)

A ticket on hold (ticket_hold, 0.6.0) leaves every lane and comes back by itself when what it waits for happens: its blockers closed (blocked_by), a pull request merged (pr_merged), a time (time), a reply (reply). 0.8.0 adds external: a state of the world the board cannot see itself.

A pr_merged hold on a private repository needs BOARD_GITHUB_TOKEN (read access) on the server. When GitHub refuses to show the pull request (401, 404, or a 403 that is not a rate limit), the board says so once in a comment on the waiting ticket instead of leaving a hold that never lifts. If a relay of yours already reports those merges through POST /api/holds/pr (a script with its own GitHub access), set BOARD_PR_RELAY to its name: the comment then says that relay watches the pull request, and no token is needed on the board.

The ticket's panel says what it waits for and what happens then, with a button to lift the hold by hand; a ticket that waits for nothing yet has a Put on hold… form.

The panel of a ticket on hold: it waits for a pull request to be merged, then wakes an agent (dark, the form at 390 px, the form at 390 px, dark.)

The tickets on hold sit in the On hold drawer under the lanes, each with what it waits for; a long wait ends in "…" inside its card, and its tooltip keeps the full text.

The On hold drawer: three tickets on hold, the longest wait ends in an ellipsis inside its card (dark, at 390 px, at 390 px, dark.)

A ticket woken 5 times (BOARD_HOLD_MAX_BOUNCES) refuses a new hold: a loop goes to someone who decides. Since 0.9.3 only the wakes of the last 7 days count, and a person (not an agent) lifting a hold by hand starts the count again.

{ "condition": { "type": "external", "what": "the hall motion sensor sees someone come in",
                 "deadline": "2026-11-02T22:00:00Z",
                 "otherwise": { "type": "assign", "to": "user", "text": "Nothing was seen: check the sensor." } },
  "then": { "type": "wake", "actor": "builder" } }
  • what says the state in words; it is what the ticket shows as waits for.
  • Whoever sees it (a polling script, a home-automation hook, an agent) lifts the hold with a proof: POST /api/tickets/ALV-12/hold/fire { "proof": "on at 19:42, entity history" }, or ticket_hold with fire_proof. The ticket comes back through then (or the default step), and the proof stays in its history: Back with @builder: seen: … (on at 19:42 …).
  • deadline is optional. When it passes unmet, the ticket comes back on its own through otherwise (absent: the same step as then), and the history says not met: … was not seen by ….
  • The board never polls anything for an external hold: the watcher lives where the state can be read, and needs only a token that may write tickets.

Ticket keys (0.5.3)

Tickets are numbered ALV-1, ALV-2… A board created before 0.5.3 keeps its SB- keys (they are in notes, links and commit messages) until you choose: set BOARD_KEY_PREFIX=ALV (2 to 8 letters) on the server and restart it. The choice is kept in the database. Only the number identifies a ticket: SB-523, ALV-523 and 523 open the same one everywhere (API, MCP tools, /ticket, search, and page links like ?ticket=SB-523), so switching renumbers nothing and breaks no old link.

A key typed in the search (0.9.12) puts that ticket first in its lane, closed or archived, and opens the Done drawer when it is closed; the other matches are the tickets that cite that exact key. The page also works under a sub-path of a reverse proxy opened without its trailing slash (/alvearium).

Searching with a query (0.10.0)

Words in the search box find the tickets that contain every one of them, in the title, the description, the comments or the labels, as before. Nothing else to learn. When you want more, the same box reads a small query language, close to GitHub's and Gmail's. The ? at the end of the box opens the syntax, with examples you can tap.

| You type | You get | | :- | :- | | login crash | every word, anywhere in the ticket | | "login page" | these words side by side | | status:todo | a filter: field, colon, value | | -label:noise or NOT label:noise | leave these out | | status:todo,review | any of these values | | p:P0 OR label:urgent | either side (\| works too) | | (p:P0 OR p:P1) is:blocked | parentheses group |

Spaces mean AND. OR joins the two terms beside it, before the spaces: status:todo label:a OR label:b is status:todo AND (label:a OR label:b). Field names and values ignore case and accents (Priorité:p1 reads as priority:P1).

| Field (aliases) | Values | | :- | :- | | is | open, closed, blocked, unblocked, archived (closed for more than 30 days), or a status | | status (s, statut) | todo, in_progress, waiting_on_user, review, failed, on_hold, done, cancelled, open, closed | | priority (p, prio) | P0…P3 or none; p:<=P1 is P0 and P1 (P0 comes first, as on the board), p:P1..P2 a range | | assignee (to), author (by), actor (either) | an actor id, me (you, or the invited member reading), or a prefix: assignee:lupi/* | | label (#) | label:vigie or #vigie; label:ci-* for a prefix | | type (kind), subtype, importance, origin, source | the ticket's value (type:decision, importance:high, origin:cloud) | | repo, branch, machine, session | a value, a prefix with *, or none; repo:api is the repo name under any owner | | created, updated, closed | a day (2026-10-01), today, yesterday, a range (2026-10-01..2026-10-15), > / < a day, or an age: updated:7d and updated:<7d are less than 7 days ago, updated:>7d more (30m, 12h, 7d, 2w, 3mo, 1y) | | has, no | priority, label, repo, branch, parent, session, importance, pr, blocker, children | | key, parent | a key or its number; key:>100, key:ALV-10..ALV-20 | | title, body | the text contains these characters |

A query the board cannot read never empties the board in silence: a line under the box says what it did instead, and offers the corrected query when it can guess it. An unknown field is searched as text (stauts:todo: "Did you mean status?"); a value it cannot read leaves that filter out (status:tdo: "Did you mean todo?"); an unknown type still filters, since a client may invent its own. OR must be in capitals: a lower-case or is a word. A URL or a time (10:30) stays text, and so does a minus before a digit (-5). Days (2026-10-01, today) are UTC days; an age (7d) counts back from now. -type:x leaves that type out without bringing the feedback inbox in; a positive type: or is:archived reaches the tickets the views leave out by default.

The language lives in the server (lib/query.mjs, no dependency): the API reads it in q on GET /api/tickets, /api/tickets/board and /api/tickets/next, alongside the other filters, and returns query: { errors, fix } when it found a problem.

Realtime

The page keeps one connection open to GET /api/stream (Server-Sent Events) and redraws only the cards that changed, with a short flash, the moment a hook, an agent or another tab changes a ticket: no reload, no flicker. The dot in the header says Live; if the stream cannot be opened (a proxy that buffers, a network change) it reconnects by itself with backoff and polls every 10 s meanwhile (Polling). An open ticket refreshes too, unless you are editing it.

The stream sends one change event per committed change, with a minimal payload ({ type, op, key, fields, version }: type is ticket, comment, dependency, reorder or session), and a : heartbeat comment every 15 s. Its headers (Cache-Control: no-cache, X-Accel-Buffering: no) keep nginx and similar proxies from buffering it. If you put the server behind your own reverse proxy, make sure it streams responses (for nginx, proxy_buffering off is implied by the header; for a Node relay, pipe the body instead of reading it whole).

Dependencies and priority

  • Priority P0 (drop everything) to P3 (some day); 0.2 values are migrated (urgent→P0, high→P1, medium→P2, low→P3), and the API still accepts those names.
  • "A blocks B": blocked_by on create, blocked_by_add / blocked_by_remove on update (API, MCP, /ticket block SB-5 --by SB-3, or the Dependencies section of the ticket panel). Many to many; a dependency that would close a cycle is refused. Each ticket carries blocked (an open blocker remains), blocked_by and blocking. A blocked card is hatched with a ⛔ badge. When its last blocker is done (or cancelled), the ticket is unblocked by itself and its history says so; reopening the blocker blocks it again.
  • Who set it (0.9.5): each priority remembers who set it (priority_by). On a ticket assigned to you, or on a project, a priority an agent set is a proposal: the card reads P1?, its tooltip and the ticket panel say who proposed it, and the panel offers Confirm P1. Setting a priority yourself, or the same value again, makes it yours; an agent changing it makes it a proposal again. Until you confirm it, a proposal above P2 counts as P2 in your lane and in the matrix, unless the ticket has a deadline (due: label, or a date in the Without an answer line). An agent's priority on its own work is just its priority. Ticket payloads carry priority_by, priority_by_name and priority_proposed; an existing board reads who set each priority back from the history once.
  • Important for you (0.9.18): an assistant's daily reading of your queue, apart from priority. ticket_update (and PATCH /api/tickets/:key) take importance (high, medium, low, or empty to clear), importance_reason (one concrete reason, 160 characters) and importance_rank (position in your whole queue, 1 = first). The card shows a ↑ for you chip; the panel has High / Medium / Low / Clear. Your word wins: once a human set the level, an agent's write of importance or importance_reason is ignored (the rank may still move), and the history keeps each change (importance high → low). "Waiting on you" orders your own P0/P1 first, then importance_rank, then the level, then as before. In the matrix high counts as important; a low you set removes it, unless your priority is P0/P1. Payloads carry importance, importance_reason, importance_rank, importance_by, importance_by_name and importance_yours.
  • Your projects lend their priority (0.9.5): a ticket under a project (a sub-ticket, at any depth, or one carrying <label>-id:<name> like the project) counts at the priority you gave the project when it has no priority of yours and the project's is higher. A project priority an agent proposed lends nothing. Payloads carry it as project_priority: { key, title, priority }.
  • Manual order: drag a card in the To do column or a row in Next (POST /api/tickets/SB-5/move { before | after }). Dropped among tickets of another priority, it takes that priority.
  • Next (page view, GET /api/tickets/next, MCP ticket_next, /ticket next): open tickets that nothing blocks (to do and in progress), most important first, then your manual order, then the oldest. Session, question and feedback tickets are not work and stay out. Same filters as the list (repo, session, actor, assignee, label…), plus the number of blocked tickets left aside.
  • Related (0.9.13): the ticket panel lists, under Related, its sub-tickets, the tickets blocking it, the tickets it blocks, and the tickets of the same front: when the ticket carries <label>-id:<name> (front-id:<name> by default), every ticket with a label ending in :<name> (the same id, or a label such as card-of:<name> that points at it). Closed ones are greyed, each opens on a click; the section is open up to 5 entries, collapsed above, absent when empty. The server computes it: GET /api/tickets/SB-12 carries related: [{ key, title, status, rel }] (rel is child, blocked_by, blocks or front), 50 entries at most.

Reading and writing long tickets (0.5.10)

  • A wider ticket. Drag the left edge of the open ticket to resize it (between 380 px and the width of the window minus 96 px, so there is always some board left to click). The width is kept in this browser; double-click the edge to go back to 560 px. The edge is also a focusable separator: arrows
Source 1 files
hooks/mod.mjs 210 lines
1// Alvearium mod (Claude Code v2.1.287+): draws the board inside the terminal.
2//  · a status line under the prompt — "2 for you · 3 in progress · 5 to do", refreshed every 20 s
3//  · /board — prints the whole ticket board at once, with no Claude turn (runs even while Claude works)
4// Older Claude Code versions ignore this file; the settings hooks in hooks.json still report.
5// Mods cannot open SQLite: in local mode the hooks keep ~/.claude/session-board/summary.json fresh.
6//
7// Self-contained on purpose (no imports): the directory reviewer wants to know exactly what runs.
8// Rendering logic is a subset of lib/core.mjs, duplicated here.
9
10const REFRESH_MS = 20_000
11let lastStatus
12
13export function register(on, options) {
14  on('session.start', async ($, e, next) => {
15    // Cloud session with the agent proxy's credential: this mod's fetch would not carry it (see
16    // notJson). Stay out of the way, so /board is the plugin's Node command, which goes through the proxy.
17    if ((await remote($, options).catch(() => ({}))).token === 'proxy') return next(e)
18    $.clock.every(REFRESH_MS, async () => {
19      await refreshStatus($, options)
20    })
21    refreshStatus($, options).catch(() => {})
22    try {
23      await $.command.register({
24        name: 'board',
25        description: 'Show the ticket board of every Claude Code session: waiting on you, in progress, to do',
26        immediate: true,
27      })
28    } catch {}
29    return next(e)
30  })
31
32  on('command.run', { command: 'board' }, async ($, e) => {
33    try {
34      return { text: '\n' + (await boardText($, options)) }
35    } catch (err) {
36      return { text: 'board unavailable: ' + (err && err.message ? err.message : String(err)) }
37    }
38  })
39}
40
41async function refreshStatus($, options) {
42  let text
43  try {
44    text = await statusFor($, options)
45  } catch {
46    text = 'board offline'
47  }
48  if (text === lastStatus) return
49  lastStatus = text
50  $.ui.status(text)
51}
52
53async function readJson($, path) {
54  try {
55    return JSON.parse(await $.fs.read(path))
56  } catch {
57    return null
58  }
59}
60
61async function localDir($) {
62  const custom = await $.env.get('SESSION_BOARD_DIR')
63  if (custom) return custom
64  const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
65  return home + '/.claude/session-board'
66}
67
68async function remote($, options) {
69  const dir = await localDir($)
70  const file = (await readJson($, dir + '/config.json')) || {}
71  const opts = options || {}
72  const url = (opts.server_url || (await $.env.get('SESSION_BOARD_URL')) || file.url || '').trim().replace(/\/+$/, '')
73  const token = (opts.token || (await $.env.get('SESSION_BOARD_TOKEN')) || file.token || '').trim()
74  return { dir, url, token, on: Boolean(url && token) }
75}
76
77async function get($, cfg, path) {
78  const headers = cfg.token === 'proxy' ? {} : { authorization: 'Bearer ' + cfg.token }
79  const res = await $.http.fetch(cfg.url + path, { headers })
80  if (!res.ok) throw new Error('HTTP ' + res.status)
81  try {
82    return JSON.parse(res.text)
83  } catch {
84    throw new Error(notJson(cfg, res.text))
85  }
86}
87
88// A login gateway in front of the board answers with its login page. In a claude.ai/code cloud
89// session (token "proxy"), this fetch is Claude Code's own and does not carry the API credential
90// that the agent proxy adds; the /alvearium:board command runs in Node and goes through the proxy.
91function notJson(cfg, text) {
92  const page = /^\s*</.test(text || '') ? 'the server answered with a login page instead of the board' : 'the server did not answer with the board'
93  return cfg.token === 'proxy'
94    ? page + ' (this request does not carry the cloud API credential). The plugin\'s board command goes through the proxy: /alvearium:board.'
95    : page + ' (is the token right?). /alvearium:board doctor says more.'
96}
97
98/** Status line: tickets waiting on you first. Old servers (no ticket counts) fall back to sessions. */
99async function statusFor($, options) {
100  const cfg = await remote($, options)
101  if (cfg.on) {
102    const b = await get($, cfg, '/api/board')
103    return (b.tickets ? ticketStatusText(b.tickets.counts) : statusText(b.counts)) || undefined
104  }
105  const s = await readJson($, cfg.dir + '/summary.json')
106  return s ? ticketStatusText(s.counts) || undefined : undefined
107}
108
109async function boardText($, options) {
110  const cfg = await remote($, options)
111  if (cfg.on) {
112    try {
113      return renderTicketsText(await get($, cfg, '/api/tickets/board?limit=50'))
114    } catch {
115      return renderText(await get($, cfg, '/api/board'))
116    }
117  }
118  const s = await readJson($, cfg.dir + '/summary.json')
119  return s ? s.text : 'No tickets yet on this machine.'
120}
121
122// ---- rendering helpers (subset of lib/core.mjs)
123
124function truncate(text, max) {
125  if (typeof text !== 'string') return ''
126  const flat = text.replace(/\s+/g, ' ').trim()
127  return flat.length > max ? flat.slice(0, max - 1) + '…' : flat
128}
129
130function ago(ms, now = Date.now()) {
131  const s = Math.max(0, Math.round((now - ms) / 1000))
132  if (s < 60) return `${s}s`
133  if (s < 3600) return `${Math.round(s / 60)}m`
134  if (s < 86400) return `${Math.round(s / 3600)}h`
135  return `${Math.round(s / 86400)}d`
136}
137
138function statusText(counts) {
139  const parts = []
140  if (counts.waiting) parts.push(`${counts.waiting} waiting`)
141  if (counts.working) parts.push(`${counts.working} working`)
142  if (counts.review) parts.push(`${counts.review} review`)
143  return parts.join(' · ')
144}
145
146function ticketStatusText(counts) {
147  const parts = []
148  if (counts.waiting) parts.push(`${counts.waiting} for you`)
149  if (counts.inProgress) parts.push(`${counts.inProgress} in progress`)
150  if (counts.todo) parts.push(`${counts.todo} to do`)
151  return parts.join(' · ')
152}
153
154function renderText(board) {
155  const lines = []
156  const now = board.now
157  const label = (rec) => {
158    const where = rec.repo || (rec.cwd ? rec.cwd.split(/[\\/]/).filter(Boolean).pop() : '') || 'session'
159    const branch = rec.branch && rec.branch !== 'HEAD' ? `@${rec.branch}` : ''
160    return rec.name ? `${rec.name} (${where}${branch})` : `${where}${branch}`
161  }
162  const line = (r) => {
163    const where = r.surface === 'cloud' ? '☁' : '⌨'
164    const badge = r.display === 'failed' ? ' [FAILED]' : r.display === 'stale' ? ' [stale]' : ''
165    const out = [`  ${where} ${label(r)}${badge} · ${ago(r.since ?? r.lastSeen, now)}`]
166    if (r.title) out.push(`      task: ${truncate(r.title, 100)}`)
167    if (r.detail) out.push(`      ${truncate(r.detail, 160)}`)
168    if (r.pr) out.push(`      PR: ${r.pr}`)
169    if (r.url) out.push(`      open: ${r.url}`)
170    return out.join('\n')
171  }
172  const section = (title, list) => {
173    lines.push(`${title} (${list.length})`)
174    lines.push(list.length ? list.map(line).join('\n') : '  —')
175    lines.push('')
176  }
177  section('WAITING ON YOU', board.waiting || [])
178  section('IN PROGRESS', board.inProgress || [])
179  section('READY FOR REVIEW', board.review || [])
180  if (board.idle?.length) lines.push(`(${board.idle.length} idle session${board.idle.length > 1 ? 's' : ''} not shown)`)
181  return lines.join('\n').trimEnd()
182}
183
184function renderTicketsText(board, { now = board.now ?? Date.now() } = {}) {
185  const out = []
186  const line = (t) => {
187    const where = [t.repo ? t.repo.split('/').pop() : '', t.branch && t.branch !== 'HEAD' ? t.branch : ''].filter(Boolean).join('@')
188    const flag = (t.status === 'failed' ? ' [FAILED]' : t.status === 'review' ? ' [review]' : t.stale ? ' [stale]' : '') + (t.blocked ? ' [blocked]' : '')
189    const rows = [`  ${t.origin === 'cloud' ? '☁' : '⌨'} ${t.key}${t.priority ? ' ' + t.priority : ''} ${truncate(t.title, 90)}${flag} · ${ago(t.status_at ?? t.updated_at, now)}${where ? ' · ' + where : ''}`]
190    const pr = (t.links || []).find((l) => l.type === 'pr')
191    if (pr) rows.push(`      PR: ${pr.url}`)
192    const sess = (t.links || []).find((l) => l.type === 'session')
193    if (sess) rows.push(`      open: ${sess.url}`)
194    return rows.join('\n')
195  }
196  const section = (title, col) => {
197    const list = board.columns?.[col] || []
198    const total = board.counts?.[col] ?? list.length
199    out.push(`${title} (${total})`)
200    out.push(list.length ? list.map(line).join('\n') : '  —')
201    if (total > list.length) out.push(`  … ${total - list.length} more`)
202    out.push('')
203  }
204  section('WAITING ON YOU', 'waiting')
205  section('IN PROGRESS', 'inProgress')
206  section('TO DO', 'todo')
207  if (board.counts?.done) out.push(`(${board.counts.done} done, not shown)`)
208  return out.join('\n').trimEnd()
209}
210