SLOPSHOPPER

factory-board

A pane tracking every app the software factory built: live health, deploy status, product stage and open tickets

panecommandstatusprocessnetworktimer
★ 2v0.1.0AGPL-3.0updated 2026-10-26never2average/software-factory/plugins/factory-board
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · factory-board
│ ┃ Factory board ✕ › fix the failing auth test and add an audit log call │ ┃ [ Products & apps ] [ Molds ] [ Tickets ] [ │ ┃ ⏺ Read(src/auth.ts) │ ┃ Could not read /root/software-factory/state: ⎿ Read 6 lines │ ┃ ENOENT: no such file ⏺ Update(src/auth.ts) │ ┃ /root/software-factory/state/factory.json ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ No apps in state/application. ⎿ 3 pass, 1 fail │ ┃ │ ┃ built: the AI the factory spent making it, ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ at list prices. (shared): split from │ ┃ sessions that also built other apps; ~ est.: ✻ Worked for 42s · done 4:20 PM │ ┃ work not yet counted, estimated. │ ┃ › /factory │ ┃ ⎿ factory-board: factory: 0/0 apps healthy · 0 open tickets │ ┃ │ ┃ │ ┃ │ ┃ [ Refreshing… ] [ Recompute build costs ] he │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ factory-board: factory: could not read state

Draws

Pane · Factory board
[ Products & apps ] [ Molds ] [ Tickets ] [ Analytics ] Could not read /root/software-factory/state: ENOENT: no such file /root/software-factory/state/factory.json No apps in state/application. built: the AI the factory spent making it, at list prices. (shared): split from sessions that also built other apps; ~ est.: work not yet counted, estimated. [ Refreshing… ] [ Recompute build costs ] health checked pen
README

factory-board

A Claude Code plugin that ships with the software factory. One pane, four tabs, covering every app the factory has built:

  • Products & apps: where each product stands, with its apps underneath: whether each is up right now, and where and when it was deployed.
  • Molds: the base codebases and their tickets.
  • Tickets: every open ticket, filterable, each one clickable.
  • Analytics: each app's rough usage, and the tickets people raised inside it.

Type /factory in a Claude Code session started in the factory.

The factory board open beside a Claude Code session

Tabs

The tab buttons sit at the top of the pane. You can also jump straight to a tab:

TypeOpens
/factory productsProducts & apps (the board opens here)
/factory moldsMolds
/factory ticketsTickets
/factory analytics onfinance_hfc_vmAnalytics, with that app picked
/factory mold_v1-215that ticket's details
/factory refreshthe board, after a fresh health check

Products & apps

Products & apps tab

Each product in state/products.json gets:

  • Its stage path: defined → built → tested → deployed → released. Done stages are ticked and the current one is green. A product of a coming-soon mold shows coming soon instead.
  • Each of its apps:
  • Health: live health (healthy, down, pending, or n/a for a retired app), shown only when it isn't plain stamped. Its record status shows beside it, as reverted or retired. Where it runs: vercel, or own server.
  • Checks: the answer from each health page the board loads itself (web, api, and on Vercel the workflow service). Also the workspace-isolation proof from the last deploy: RLS 62/62 means all 62 workspace tables are locked to their workspace. And what the last deploy found about "Continue with Google": Google sign-in ok, via hub, or in red Google sign-in NOT working (python3 .claude/scripts/provision.py <app> --google-signin gives the steps).
  • Deploy: when it was last deployed, and the base-code (mold) version it runs. current is the factory's latest snapshot; behind means a redeploy would update it.
  • Why, when it is down: a red why: line names each failing page and, when the app's health page says which part failed, that part and its cause in plain words, for example why: web 503: database: the request was refused (usage limit?). The app's own error text is never shown (it can name a host or a database role). The status line names the down app with its first cause too.
  • Database: its database plan and how much of each limit the provider says is used, and when that was measured, for example database: Neon Free · compute time 85.25/100 CU-hours (85%) · not measured: Storage · measured 5m ago. Amber at 80% of a limit, red when it is reached. On a paid plan with no fixed limit it shows the usage this billing period. A figure no source reports says not measured, never 0. A report more than an hour old says not measured since 3d ago (stale) and is never shown as a calm line. See Database plan usage.
  • Address: its web address.
  • Built: what it took to make the app, for example built: $1,299 (shared) + ~$37.62 est. · agent 16h 55m · active 12h 39m · first message → live 21h 33m · 70 deploys:
  • built: the AI (Claude) the factory spent making it, at list prices, read from the agent sessions' own cost counters. On a Claude subscription it is the value used, not an invoice.
  • (shared): most of the work happened in long sessions that built several apps. Such a session is split: each piece of work (from one message to the agent to the next) goes to the apps it names, in proportion to how often it names each, and a piece that names no app stays factory work, charged to no app. So two apps that share a session never both count all of it. A shared figure is dimmed.
  • ~ est.: work done after a session's last cost record, which the counter hasn't seen yet. It is estimated from the counted part, dimmed, and never added into the measured figure.
  • agent: the time the model spent working; active: session time with idle gaps over 5 minutes taken out. Both are shared the same way, and dimmed when they are.
  • first message → live: calendar time from the first message that named the app to its first deploy, waits included.
  • deploys: how many times it has been deployed, from git history.
  • A figure that can't be worked out says not measured, never 0.
  • The product's total, under its name: the sum of its apps' lines, marked (shared) when any part is.

The build figures come from .claude/scripts/mint_report.py --all --json, which the board runs every hour and on Recompute build costs (at the bottom of this tab). It reads the agent sessions and git on this machine, goes nowhere online, and writes reports/mint/<app>.json and .md for each app that isn't retired. reports/mint/<app>.md explains each figure in full, with the share taken of each session.

Apps that belong to no product are listed under Other apps.

Molds

Molds tab

Each mold with its snapshot version and its tickets (open, in progress, done). A mold marked coming_soon in state/factory.json shows coming soon and its number of planned tickets. Today that's mold_v2 and mold_v3.

Tickets

Tickets tab

  • Filters along the top: All, each priority, and each app that has tickets, with counts.
  • One line per ticket: a coloured priority (P1 red, P2 amber, P3 grey), its short number, the app it's about if any, and the title cut to fit.
  • Clicking: the title opens the ticket.

A ticket

A ticket shows:

  • its priority, status, app and full id;
  • the full title;
  • a line with type, lane, product, which stage it moves the product to, owner and date filed;
  • What happened, Done when (as checkboxes), Waits on (other open tickets, each clickable, and done ones ticked) and Evidence so far.

There are two buttons:

  • ← Back goes back to the list.
  • Work on this puts Work on factory ticket <id> … into your prompt, ready to send.

Analytics

Analytics tab, numbered

  1. Tabs.
  2. App picker: one button per app that isn't retired.
  3. Window: the last 30 days, and when the numbers were collected.
  4. Usage:
  5. people active, chats, chat turns;
  6. tokens in and out;
  7. estimated chat cost;
  8. workflow (helper) runs and their cost (dimmed and marked ~ est. when any of it is estimated).
  9. Chat turns per day: one bar per day, scaled to the busiest day.
  10. Tickets in the app: the tickets people raised inside the app itself (open, in progress, done). These are not the factory's tickets.
  11. By workspace: the same numbers for each workspace in the app.
  12. By agent and By user: the main agent's turns and each specialist's runs, with tokens and cost, and then each person's chats, turns, cost and when they were last active. People are shown by display name, never by email address. A figure that can't be worked out says not measured, never $0. A cost the app recorded is shown plainly. Some older helper runs recorded their tokens but no cost and no model, because Cloudflare Workers AI doesn't report costs and the app didn't yet record which model ran. Their cost is estimated: the tokens are priced at the model that helper is set up to use now, with the app's own price list. An estimate is shown dimmed as ~$1.23 est., so it never looks like a measured figure. The report names the model it used (estimated_from).
  13. Factory tickets for this app: open factory tickets that name this app. Each one is clickable.
  14. Buttons: Refresh checks health again. Collect usage pulls fresh numbers.

The numbers come from .claude/scripts/app_usage.py, which the board runs every 30 minutes and on Collect usage. It reads each app's own database as the app's own restricted role, one workspace at a time, in read-only transactions. Only counts leave the database: no messages, no names, no email addresses. The results are kept in reports/usage/<app>.json, which is not committed.

Uptime alerts

.claude/scripts/uptime.py checks every app that isn't retired once a minute, from a systemd timer on the factory machine (uptime.py install; uptime.py status shows the timer). It loads the same health pages as the board, with a 10-second timeout and one retry, and writes .runs/uptime/state.json, which is not committed.

  • An app is down after 2 failing checks in a row, so a single blip alerts nobody.
  • While any app is down, a red banner sits above the tabs on every tab. It names the app, its address, since when, what it answered (with the failing part and its cause when the health page says, e.g. database: the request was refused (usage limit?)), and whether the operator was emailed. The status line starts with ✕ DOWN: <app>.
  • If the monitor hasn't written anything for 5 minutes, an amber line says it may have stopped.
  • The board only reads the monitor's file, once a minute. It never sends anything itself.
  • Email: the operator gets an email when the app goes down, again every 30 minutes while it stays down, and when it's back up, with how long it was down. This needs the factory machine's own sending key (uptime.py set-email-key, typed by the operator). Without one, the banner is the alert. uptime.py preview-alert prints the exact email and sends nothing.
  • The gap: the monitor runs on the factory machine, so it can't report that machine being down. The top of uptime.py lists free outside options and their trade-offs.

Database plan usage

.claude/scripts/lib/db_usage.py reads each app's database usage from its provider, against the limits its plan states. A systemd timer on the factory machine runs it every 30 minutes (installed with the uptime timer: uptime.py install; uptime.py status shows both), so warnings and tickets never depend on an open board. The board also runs it every 30 minutes while open, on /factory refresh, and when it opens and finds a report missing or more than an hour old. It keeps the results in reports/db-usage/<app>.json, which is not committed.

  • Neon or Supabase through Vercel: read with this machine's Vercel sign-in, so no key of ours is needed. Vercel gives the plan in effect and the limits it states (Neon Free: 100 CU-hours of compute and 1 GB of storage per database). It also gives what the provider reported this billing period (Neon: compute, in "hours") and the provider's own "limit reached" flag. Vercel's compute "hours" are not confirmed to be CU-hours, so they are shown as usage and not compared with the CU-hour limit. Supabase reports no usage figures, so only its flag is read.
  • Neon's own API: if the factory machine has a Neon API key, the check measures compute in CU-hours (and so warns at 80% of it), storage and data transfer. The key is referenced by name only (postgres.usage_key_ref in the app's datastores.json, default NEON_API_KEY; only a name starting NEON_ is used), from the environment or ~/.config/software-factory/db-usage.env (keep it chmod 600; the check warns otherwise), and is never printed.
  • A database on the app's own server: not measured here. provision.py <app> --capacity checks that server's disk.
  • At 80% of any limit, or when the provider says a limit is reached, a banner sits above the tabs on every tab. It names the app, the limit and the upgrade step, for example changing the Neon plan from Free to Launch in Vercel. A paid plan needs the operator's yes. The check also files one factory ticket for that app and limit, and files no other while that one is open. When the limit is reached while a warning ticket is open, that ticket is raised to P1. A ticket the operator closed or dropped this billing period is not filed again unless the level rises (from 80% to the limit).

Run it yourself with python3 .claude/scripts/lib/db_usage.py <app> (prints, writes nothing) or --all. --self-test runs offline.

The status line

A one-line summary sits in the status line, so you can see it without opening the pane:

The summary in the status line

The board checks health every 5 minutes on its own.

Installing

Inside the factory there is nothing to do: .claude/settings.json turns the plugin on from the factory's own marketplace (.claude-plugin/marketplace.json). Elsewhere, type this at a Claude Code prompt, answer y to add the marketplace, then pick a scope:

/plugin install factory-board --marketplace never2average/software-factory

The board reads the factory's records from the folder Claude Code was started in when that folder is the factory, and otherwise from /root/software-factory. It never changes a record or an app. The one ticket it may add is the database usage check's warning, described above.

Developing it

  • hooks/register.tsx holds the pane, its tabs, /factory and the timers.
  • hooks/board.ts holds the pure readers of the state files, the usage report and the build reports.
  • types/index.d.ts declares the values the pane keeps.

The tests are:

  • hooks/board.test.ts for the readers, the build lines, the product totals, the health causes (the same cases as lib/health_cause.py --self-test) and the database lines;
  • hooks/db-usage-ui.test.tsx, which checks that a database at 85% of a limit shows its line and the warning banner, that a down app's card says why, and that opening the board re-measures a stale report (and leaves a fresh one alone), on both surfaces;
  • hooks/uptime-ui.test.tsx, which checks that the red banner and the status line show a down app, and stay away while it's up, on both surfaces;
  • hooks/tickets-ui.test.tsx, which clicks through the tickets, the filters and the Products & apps tab (with its build lines and Recompute build costs) on the terminal and desktop surfaces against a small fake factory.
claude plugin validate plugins/factory-board
claude plugin test plugins/factory-board

The screenshots in docs/ are real captures of the running board, taken on 2026-10-08 in a terminal 170 columns wide.

Source 3 files
hooks/register.tsx 917 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AppRow, Board, Build, Check, DbUsage, Tab, Ticket, Uptime, Usage } from '../types'
5import {
6  STAGES,
7  STAGE_WORDS,
8  ago,
9  buildParts,
10  DB_EVERY_MS,
11  dbBanner,
12  dbLine,
13  dbNeedsMeasure,
14  downReasons,
15  healthCauses,
16  parseDbUsage,
17  summary,
18  parseBuild,
19  sumBuilds,
20  fit,
21  plainTitle,
22  ticketMatches,
23  appRow,
24  isComingSoon,
25  isEstimate,
26  cost,
27  money,
28  moldRow,
29  openTickets,
30  parseTasks,
31  parseUptime,
32  parseUsage,
33  plus,
34  productRows,
35  short,
36  sparkline,
37  ticketsForApp,
38  uptimeBanner,
39  verdict,
40} from './board'
41
42const PANE = 'factory-board'
43const FALLBACK_ROOT = '/root/software-factory'
44const EVERY_MS = 5 * 60_000
45const USAGE_EVERY_MS = 30 * 60_000
46const PROBE_MS = 10_000
47const COLLECT_MS = 5 * 60_000
48const BUILD_EVERY_MS = 60 * 60_000
49const COMPUTE_MS = 10 * 60_000
50/** uptime.py writes its state every minute (systemd timer); the board reads it as often. */
51const UPTIME_EVERY_MS = 60_000
52/** lib/db_usage.py reads each database's plan usage from its provider (a few Vercel API reads per app); DB_EVERY_MS is
53 * also the period of its systemd timer (uptime.py install), so warnings never depend on an open board. */
54const DB_MS = 5 * 60_000
55
56const board = atom({ plugin: 'factory-board', key: 'board' } as const, null)
57const isRefreshing = atom({ plugin: 'factory-board', key: 'isRefreshing' } as const, false)
58const tab = atom({ plugin: 'factory-board', key: 'tab' } as const, 'products')
59const selectedApp = atom({ plugin: 'factory-board', key: 'selectedApp' } as const, '')
60const usage = atom({ plugin: 'factory-board', key: 'usage' } as const, {})
61const isCollecting = atom({ plugin: 'factory-board', key: 'isCollecting' } as const, false)
62const collectError = atom({ plugin: 'factory-board', key: 'collectError' } as const, '')
63const openTicket = atom({ plugin: 'factory-board', key: 'openTicket' } as const, '')
64const ticketFilter = atom({ plugin: 'factory-board', key: 'ticketFilter' } as const, 'all')
65const builds = atom({ plugin: 'factory-board', key: 'builds' } as const, {})
66const isComputing = atom({ plugin: 'factory-board', key: 'isComputing' } as const, false)
67const computeError = atom({ plugin: 'factory-board', key: 'computeError' } as const, '')
68const uptime = atom({ plugin: 'factory-board', key: 'uptime' } as const, null)
69const dbUsage = atom({ plugin: 'factory-board', key: 'dbUsage' } as const, {})
70const dbError = atom({ plugin: 'factory-board', key: 'dbError' } as const, '')
71
72type $ = EngineInterface
73
74let root = FALLBACK_ROOT
75
76// The "in progress" locks live in the module, not in $.state: $.state survives a reload of the plugin, so a lock held
77// there by a refresh the reload cut short would stay set and every later refresh would skip (the board then sat on
78// "Reading…"). A reload starts the module over, and these with it.
79let refreshing = false
80let collecting = false
81let computing = false
82let measuringDb = false
83const STORE_KEY = 'last-board'
84
85async function readJson($: $, path: string): Promise<any> {
86  return JSON.parse(await $.fs.read(path))
87}
88
89/* ---- the factory's records ------------------------------------------------------------------------------------ */
90
91/** Reads the factory's state files into a board; health probes stay pending until `probe`. */
92async function load($: $): Promise<Board> {
93  const now = await $.clock.now()
94  const factory = await readJson($, `${root}/state/factory.json`)
95  const snapshots = new Map<string, string>(
96    (factory.molds ?? []).map((m: any) => [String(m.mold_id), String(m.source?.commit ?? '')]),
97  )
98  const statuses = new Map<string, string>((factory.molds ?? []).map((m: any) => [String(m.mold_id), String(m.status ?? '')]))
99
100  const apps: AppRow[] = []
101  for (const entry of await $.fs.list(`${root}/state/application`)) {
102    if (entry.kind !== 'dir' || entry.name === 'app_id') continue
103    const dir = `${root}/state/application/${entry.name}`
104    try {
105      const [application, infrastructure, datastores] = await Promise.all([
106        readJson($, `${dir}/application.json`),
107        readJson($, `${dir}/infrastructure.json`),
108        readJson($, `${dir}/datastores.json`).catch(() => ({})),
109      ])
110      apps.push(appRow(entry.name, application, infrastructure, datastores, snapshots))
111    } catch {
112      // an app folder without its state files is not an app yet
113    }
114  }
115
116  const tickets = []
117  const molds = []
118  for (const [id, snapshot] of snapshots) {
119    const text = await $.fs.read(`${root}/state/tasks/${id}.jsonl`).catch(() => '')
120    const tasks = parseTasks(text)
121    const status = statuses.get(id) ?? ''
122    molds.push(moldRow(id, status, snapshot, tasks))
123    if (!isComingSoon(status)) tickets.push(...openTickets(tasks))
124  }
125
126  const products = productRows(await readJson($, `${root}/state/products.json`).catch(() => ({})))
127
128  return { root, loadedAt: now, checkedAt: 0, apps, products, molds, tickets }
129}
130
131/** One health page, given up on after PROBE_MS. */
132async function probe($: $, check: Check): Promise<Check> {
133  const answer = await Promise.race([
134    $.http
135      .fetch(check.url)
136      // a failing /api/ops/health answers its parts' state: keep the failing part and its cause, never the text itself
137      .then(r => ({ status: r.status, causes: r.status >= 300 ? healthCauses(String(r.text ?? '')) : [] }))
138      .catch(() => ({ status: 'down' as const, causes: [] })),
139    $.clock.sleep(PROBE_MS).then(() => ({ status: 'down' as const, causes: [] })),
140  ])
141  return { ...check, status: answer.status, ...(answer.causes.length ? { causes: answer.causes } : {}) }
142}
143
144async function refresh($: $): Promise<void> {
145  if (refreshing) return
146  refreshing = true
147  await update($, isRefreshing, () => true)
148  try {
149    const loaded = await load($)
150    await update($, board, () => loaded)
151    const apps = await Promise.all(
152      loaded.apps.map(async app => ({ ...app, checks: await Promise.all(app.checks.map(c => probe($, c))) })),
153    )
154    const checkedAt = await $.clock.now()
155    await update($, board, current => (current ? { ...current, apps, checkedAt } : current))
156    // the last board, kept across sessions, so the next /factory opens on it at once while it refreshes
157    void $.store.set(STORE_KEY, { ...loaded, apps, checkedAt }).catch(() => undefined)
158    $.ui.status(downPrefix(await readUptime($)) + summary(apps, loaded.tickets.length))
159    if (!(await read($, selectedApp))) {
160      const first = apps.find(a => a.status !== 'retired')
161      if (first) await update($, selectedApp, () => first.id)
162    }
163    await readUsage($, apps)
164    await readBuilds($, apps)
165    await readDbUsage($, apps)
166  } catch (error) {
167    const message = error instanceof Error ? error.message : String(error)
168    await update($, board, current => ({
169      ...(current ?? { root, loadedAt: 0, checkedAt: 0, apps: [], products: [], molds: [], tickets: [] }),
170      error: message,
171    }))
172    $.ui.status('factory: could not read state')
173  } finally {
174    refreshing = false
175    await update($, isRefreshing, () => false)
176  }
177}
178
179/* ---- uptime: .runs/uptime/state.json, written every minute by .claude/scripts/uptime.py (a systemd timer) ------------ */
180
181/** Reads the monitor's last state; the board never probes on its behalf. Also puts a down app into the status line. */
182async function readUptime($: $): Promise<Uptime | null> {
183  const raw = await readJson($, `${root}/.runs/uptime/state.json`).catch(() => null)
184  const parsed = parseUptime(raw)
185  await update($, uptime, () => parsed)
186  return parsed
187}
188
189function downPrefix(u: Uptime | null): string {
190  const down = (u?.apps ?? []).filter(a => a.status === 'down').map(a => a.id)
191  return down.length ? `✕ DOWN: ${down.join(', ')} · ` : ''
192}
193
194async function tickUptime($: $): Promise<void> {
195  const u = await readUptime($)
196  const current = await read($, board)
197  if (current && current.checkedAt) $.ui.status(downPrefix(u) + summary(current.apps, current.tickets.length))
198}
199
200/* ---- usage analytics: reports/usage/<app>.json, written by .claude/scripts/app_usage.py -------------------------- */
201
202async function readUsage($: $, apps: readonly AppRow[]): Promise<void> {
203  const found: Record<string, Usage> = {}
204  for (const app of apps) {
205    const raw = await readJson($, `${root}/reports/usage/${app.id}.json`).catch(() => null)
206    if (raw) found[app.id] = parseUsage(raw)
207  }
208  await update($, usage, () => found)
209}
210
211/** Runs the read-only collector for every app, then reads what it wrote. */
212async function collect($: $): Promise<void> {
213  if (collecting) return
214  collecting = true
215  await update($, isCollecting, () => true)
216  await update($, collectError, () => '')
217  try {
218    const script = `${root}/.claude/scripts/app_usage.py`
219    if (!(await $.fs.exists(script))) {
220      await update($, collectError, () => 'The usage collector (.claude/scripts/app_usage.py) is not in this factory yet.')
221      return
222    }
223    const ran = await $.process.run(['python3', script, '--all'], { cwd: root, timeoutMs: COLLECT_MS })
224    if (ran.exitCode !== 0) {
225      const why = (ran.stderr || ran.stdout).trim().split('\n').slice(-1)[0] ?? ''
226      await update($, collectError, () => `The usage collector stopped (exit ${ran.exitCode}). ${why}`.trim())
227    }
228    const current = await read($, board)
229    if (current) await readUsage($, current.apps)
230  } catch (error) {
231    await update($, collectError, () => (error instanceof Error ? error.message : String(error)))
232  } finally {
233    collecting = false
234    await update($, isCollecting, () => false)
235  }
236}
237
238/* ---- build cost and time: reports/mint/<app>.json, written by .claude/scripts/mint_report.py --all -------------------- */
239
240async function readBuilds($: $, apps: readonly AppRow[]): Promise<void> {
241  const found: Record<string, Build> = {}
242  for (const app of apps) {
243    const raw = await readJson($, `${root}/reports/mint/${app.id}.json`).catch(() => null)
244    if (raw) found[app.id] = parseBuild(raw)
245  }
246  await update($, builds, () => found)
247}
248
249/** Recomputes every app's build cost and time from the agent sessions and git (offline, read-only), then reads them. */
250async function computeBuilds($: $): Promise<void> {
251  if (computing) return
252  computing = true
253  await update($, isComputing, () => true)
254  await update($, computeError, () => '')
255  try {
256    const script = `${root}/.claude/scripts/mint_report.py`
257    if (!(await $.fs.exists(script))) {
258      await update($, computeError, () => 'The build report (.claude/scripts/mint_report.py) is not in this factory yet.')
259      return
260    }
261    const ran = await $.process.run(['python3', script, '--all', '--json'], { cwd: root, timeoutMs: COMPUTE_MS })
262    if (ran.exitCode !== 0) {
263      const why = (ran.stderr || ran.stdout).trim().split('\n').slice(-1)[0] ?? ''
264      await update($, computeError, () => `The build report stopped (exit ${ran.exitCode}). ${why}`.trim())
265    }
266    const current = await read($, board)
267    if (current) await readBuilds($, current.apps)
268  } catch (error) {
269    await update($, computeError, () => (error instanceof Error ? error.message : String(error)))
270  } finally {
271    computing = false
272    await update($, isComputing, () => false)
273  }
274}
275
276/* ---- database plan usage: reports/db-usage/<app>.json, written by .claude/scripts/lib/db_usage.py ------------------ */
277
278async function readDbReports($: $, apps: readonly AppRow[]): Promise<Record<string, DbUsage>> {
279  const found: Record<string, DbUsage> = {}
280  for (const app of apps) {
281    const parsed = parseDbUsage(await readJson($, `${root}/reports/db-usage/${app.id}.json`).catch(() => null))
282    if (parsed) found[app.id] = parsed
283  }
284  return found
285}
286
287async function readDbUsage($: $, apps: readonly AppRow[]): Promise<void> {
288  const found = await readDbReports($, apps)
289  await update($, dbUsage, () => found)
290}
291
292/** On opening the board: measure when an app has no report or its report is stale (the timer stopped, or none). */
293async function measureDbIfStale($: $): Promise<void> {
294  const apps = ((await read($, board)) ?? (await load($).catch(() => null)))?.apps ?? []
295  const live = apps.filter(a => a.status !== 'retired')
296  const reports = await readDbReports($, live)
297  if (live.length ? dbNeedsMeasure(live.map(a => a.id), reports, await $.clock.now()) : !(await $.fs.exists(`${root}/reports/db-usage`))) {
298    await measureDb($)
299  }
300}
301
302/** Reads every database's usage from its provider (read-only), files a ticket at 80% of a limit, then reads the reports. */
303async function measureDb($: $): Promise<void> {
304  if (measuringDb) return
305  measuringDb = true
306  try {
307    const script = `${root}/.claude/scripts/lib/db_usage.py`
308    if (!(await $.fs.exists(script))) return
309    const ran = await $.process.run(['python3', script, '--all', '--write', '--file-tickets'], { cwd: root, timeoutMs: DB_MS })
310    const why = (ran.stderr || ran.stdout).trim().split('\n').slice(-1)[0] ?? ''
311    await update($, dbError, () => (ran.exitCode === 0 ? '' : `The database usage check stopped (exit ${ran.exitCode}). ${why}`.trim()))
312    const current = await read($, board)
313    if (current) await readDbUsage($, current.apps)
314  } catch (error) {
315    await update($, dbError, () => (error instanceof Error ? error.message : String(error)))
316  } finally {
317    measuringDb = false
318  }
319}
320
321const COLOR = { healthy: 'success', down: 'error', pending: 'subtle', 'n/a': 'inactive' } as const
322
323function stageColor(status: string): string {
324  if (status === 'reverted') return 'error'
325  if (status === 'retired') return 'inactive'
326  return 'text'
327}
328
329const TABS: { id: Tab; label: string }[] = [
330  { id: 'products', label: 'Products & apps' },
331  { id: 'molds', label: 'Molds' },
332  { id: 'tickets', label: 'Tickets' },
333  { id: 'analytics', label: 'Analytics' },
334]
335
336
337export const register: Register = on => {
338  on('session.start', async ($, e, next) => {
339    const started = await next(e)
340    if (e.cwd && (await $.fs.exists(`${e.cwd}/state/factory.json`))) root = e.cwd
341    await update($, isRefreshing, () => false)
342    await update($, isCollecting, () => false)
343    await update($, isComputing, () => false)
344    if (!(await read($, board))) {
345      const last = (await $.store.get(STORE_KEY).catch(() => undefined)) as Board | undefined
346      if (last && last.root === root) await update($, board, () => last)
347    }
348    await $.command.register({
349      name: 'factory',
350      description: 'Factory board: products and apps, molds, tickets, analytics (/factory products|molds|tickets|analytics [app]|refresh|<ticket id>)',
351    })
352    void refresh($)
353    $.clock.every(EVERY_MS, () => void refresh($))
354    $.clock.every(USAGE_EVERY_MS, () => void collect($))
355    $.clock.every(BUILD_EVERY_MS, () => void computeBuilds($))
356    $.clock.every(UPTIME_EVERY_MS, () => void tickUptime($))
357    $.clock.every(DB_EVERY_MS, () => void measureDb($))
358    return started
359  })
360
361  on('command.run', { command: 'factory' }, async ($, e) => {
362    const [word = '', target = ''] = e.args.trim().split(/\s+/)
363    const arg = word
364    if (word === 'analytics' && target) await update($, selectedApp, () => target)
365    if (arg === 'apps') await update($, tab, () => 'products')
366    else if (arg === 'products' || arg === 'molds' || arg === 'tickets' || arg === 'analytics') await update($, tab, () => arg)
367    else if (/^[a-z0-9_]+-\d+$/i.test(arg)) {
368      await update($, openTicket, () => arg)
369      await update($, tab, () => 'tickets')
370    }
371    await $.ui.open({ id: PANE, title: 'Factory board' })
372    void refresh($)
373    if (arg === 'analytics' && Object.keys(await read($, usage)).length === 0) void collect($)
374    if (arg === 'refresh') void measureDb($)
375    else void measureDbIfStale($)
376    const current = await read($, board)
377    return { text: current ? summary(current.apps, current.tickets.length) : 'Factory board opened.' }
378  })
379
380  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
381    const { Box, Text, Button } = $.ui.resolve(e)
382    const current = await read($, board)
383    const busy = await read($, isRefreshing)
384    const shown = await read($, tab)
385    const now = await $.clock.now()
386    const banner = uptimeBanner(await read($, uptime), now)
387    const dbReports = await read($, dbUsage)
388    const dbWarn = dbBanner(dbReports, now)
389    const dbProblem = await read($, dbError)
390
391    if (!current) return <Text dimColor>{busy ? 'Reading the factory state…' : 'No data yet. Run /factory refresh.'}</Text>
392
393    const tabs = (
394      <Box flexDirection="row" gap={1}>
395        {TABS.map(t => (
396          <Button
397            key={`tab-${t.id}`}
398            label={t.label}
399            variant={t.id === shown ? 'primary' : 'secondary'}
400            onPress={() => void update($, tab, () => t.id)}
401          />
402        ))}
403      </Box>
404    )
405
406    /* -- What it took to build an app (or a product): apportioned and estimated parts are dimmed ------------------ */
407    const buildsByApp = await read($, builds)
408    const computingBuilds = await read($, isComputing)
409    const computeProblem = await read($, computeError)
410    const buildLine = (key: string, b: Build | null | undefined, indent = 2) => (
411      <Box key={key} flexDirection="row" gap={1} paddingLeft={indent}>
412        {buildParts(b).map((part, i) => (
413          <Text key={`${key}-${i}`} dimColor={part.dim}>
414            {part.text}
415          </Text>
416        ))}
417      </Box>
418    )
419
420    /* -- One app: its health checks, deploy, base code and address ------------------------------------------------ */
421    const appCard = (app: AppRow) => {
422      const health = verdict(app.checks)
423      return (
424        <Box flexDirection="column" key={`app-${app.id}`} paddingLeft={2}>
425          <Box flexDirection="row" gap={1}>
426            <Text color={COLOR[health]}>{health === 'healthy' ? '●' : health === 'down' ? '✕' : '○'}</Text>
427            <Text bold>{app.id}</Text>
428            <Text color={COLOR[health]}>{health}</Text>
429            {app.status !== 'stamped' && <Text color={stageColor(app.status)}>{app.status}</Text>}
430            <Text dimColor>{app.target === 'vm_remote' ? 'own server' : app.target}</Text>
431          </Box>
432          <Box flexDirection="row" gap={1} paddingLeft={2}>
433            {app.checks.map(c => (
434              <Text
435                key={c.name}
436                color={typeof c.status === 'number' && c.status < 300 ? 'success' : c.status === 'pending' ? 'subtle' : 'error'}
437              >
438                {c.name} {String(c.status)}
439              </Text>
440            ))}
441            {app.rls && <Text dimColor>RLS {app.rls}</Text>}
442            {app.google === 'not_working' && <Text color="error">Google sign-in NOT working</Text>}
443            {(app.google === 'direct' || app.google === 'hub') && (
444              <Text dimColor>Google sign-in {app.google === 'hub' ? 'via hub' : 'ok'}</Text>
445            )}
446            <Text dimColor>· deployed {ago(app.deployedAt, now)}</Text>
447            <Text color={app.isCurrent ? 'success' : 'warning'}>
448              {app.moldId}@{app.moldCommit || '?'} {app.isCurrent ? 'current' : 'behind'}
449            </Text>
450          </Box>
451          {health === 'down' && (
452            <Box key={`why-${app.id}`} paddingLeft={2}>
453              <Text color="error" wrap="wrap">
454                why: {downReasons(app.checks).join(' · ')}
455              </Text>
456            </Box>
457          )}
458          {app.status !== 'retired' && (() => {
459            const db = dbLine(dbReports[app.id], now)
460            const color = db.level === 'limit' ? 'error' : db.level === 'warn' ? 'warning' : undefined
461            return (
462              <Box key={`db-${app.id}`} paddingLeft={2}>
463                <Text color={color} dimColor={!color} wrap="wrap">
464                  {db.text}
465                </Text>
466              </Box>
467            )
468          })()}
469          {app.url && (
470            <Text dimColor wrap="truncate">
471              {'  '}
472              {app.url}
473            </Text>
474          )}
475          {buildLine(`build-${app.id}`, buildsByApp[app.id])}
476        </Box>
477      )
478    }
479
480    /* -- shared --------------------------------------------------------------------------------------------------- */
481    const width = Math.max(40, (e.props as { bodyColumns?: number } | undefined)?.bodyColumns ?? 100)
482    const priorityColor = (p: number) => (p <= 1 ? 'error' : p === 2 ? 'warning' : 'subtle')
483    const appOf = (t: Ticket) => current.apps.find(a => ticketsForApp([t], a.id).length > 0)?.id
484    const shortId = (id: string) => id.replace(/^mold_v\d+-/, '#')
485    const showTicket = async (id: string) => {
486      await update($, openTicket, () => id)
487      await update($, tab, () => 'tickets')
488    }
489    
490    /* One ticket as one line: priority, number, app, then the title as the thing to click. */
491    const ticketRow = (t: Ticket, keyPrefix = 'ticket') => {
492      const app = appOf(t)
493      const used = 4 + 6 + (app ? app.length + 2 : 0) + (t.status === 'in_progress' ? 13 : 0) + 4
494      return (
495        <Box key={`${keyPrefix}-row-${t.id}`} flexDirection="row" gap={1}>
496          <Text bold color={priorityColor(t.priority)}>
497            P{t.priority}
498          </Text>
499          <Text dimColor>{shortId(t.id).padEnd(5)}</Text>
500          {t.status === 'in_progress' && <Text color="suggestion">in progress</Text>}
501          {t.status === 'blocked' && <Text color="error">blocked</Text>}
502          {app && <Text color="claude">{app}</Text>}
503          <Button key={`${keyPrefix}-${t.id}`} plain label={fit(plainTitle(t), width - used)} onPress={() => void showTicket(t.id)} />
504        </Box>
505      )
506    }
507
508    /* -- Products ------------------------------------------------------------------------------------------------- */
509    const unowned = current.apps.filter(a => !current.products.some(p => p.appIds.includes(a.id)))
510    const productsTab = (
511      <Box flexDirection="column" gap={1}>
512        {current.apps.length === 0 && <Text dimColor>No apps in state/application.</Text>}
513        {current.products.map(p => {
514          const soon = isComingSoon(current.molds.find(m => m.id === p.moldId)?.status ?? '')
515          const apps = current.apps.filter(a => p.appIds.includes(a.id))
516          return (
517            <Box key={`product-${p.id}`} flexDirection="column">
518              <Box flexDirection="row" gap={1}>
519                <Text bold>{p.name}</Text>
520                {soon && <Text color="claude">coming soon</Text>}
521                <Text dimColor>{p.moldId}</Text>
522              </Box>
523              {p.appIds.length > 0 &&
524                buildLine(
525                  `pbuild-${p.id}`,
526                  sumBuilds(p.appIds.map(id => buildsByApp[id]).filter((b): b is Build => b !== undefined)),
527                  0,
528                )}
529              {!soon && (
530                <Box flexDirection="row">
531                  {STAGES.map((s, i) => {
532                    const at = STAGES.indexOf(p.stage as (typeof STAGES)[number])
533                    const done = i <= at
534                    return (
535                      <Text key={`stage-${p.id}-${s}`} color={i === at ? 'success' : done ? 'text' : 'inactive'} bold={i === at}>
536                        {i > 0 ? ' → ' : ''}
537                        {i === at ? '● ' : done ? '✓ ' : '○ '}
538                        {STAGE_WORDS[s]}
539                      </Text>
540                    )
541                  })}
542                </Box>
543              )}
544              {apps.map(a => appCard(a))}
545            </Box>
546          )
547        })}
548        {unowned.length > 0 && (
549          <Box flexDirection="column">
550            <Text bold>Other apps</Text>
551            {unowned.map(a => appCard(a))}
552          </Box>
553        )}
554        <Text dimColor wrap="wrap">
555          built: the AI the factory spent making it, at list prices. (shared): split from sessions that also built other apps;
556          ~ est.: work not yet counted, estimated.
557        </Text>
558        {computeProblem && <Text color="error">{computeProblem}</Text>}
559        {dbProblem && <Text color="error">{dbProblem}</Text>}
560      </Box>
561    )
562
563    /* -- Molds ---------------------------------------------------------------------------------------------------- */
564    const moldsTab = (
565      <Box flexDirection="column">
566        {current.molds.map(m =>
567          isComingSoon(m.status) ? (
568            <Box key={`mold-${m.id}`} flexDirection="row" gap={1}>
569              <Text bold>{m.id}</Text>
570              <Text color="claude">coming soon</Text>
571              <Text dimColor>{m.open + m.inProgress} planned tickets</Text>
572            </Box>
573          ) : (
574            <Box key={`mold-${m.id}`} flexDirection="row" gap={1}>
575              <Text bold>{m.id}</Text>
576              <Text dimColor>@{m.snapshot}</Text>
577              <Text color={m.open + m.inProgress ? 'warning' : 'success'}>{m.open} open</Text>
578              <Text>{m.inProgress} in progress</Text>
579              <Text dimColor>{m.done} done</Text>
580            </Box>
581          ),
582        )}
583      </Box>
584    )
585
586    /* -- One ticket ----------------------------------------------------------------------------------------------- */
587    const openId = await read($, openTicket)
588    const opened: Ticket | undefined = current.tickets.find(t => t.id === openId)
589    const rule = '─'.repeat(Math.min(width - 2, 72))
590
591    const detail = opened && (
592      <Box flexDirection="column" gap={1}>
593        <Box flexDirection="row" gap={1}>
594          <Button key="ticket-back" label="← Back" onPress={() => void update($, openTicket, () => '')} />
595          <Button
596            key="ticket-work"
597            label="Work on this"
598            variant="primary"
599            onPress={() =>
600              void $.prompt.fill({
601                text: `Work on factory ticket ${opened.id} (${opened.mold}): ${opened.title}`,
602                mode: 'replace',
603              })
604            }
605          />
606        </Box>
607        <Box flexDirection="column">
608          <Box flexDirection="row" gap={1}>
609            <Text bold color={priorityColor(opened.priority)}>
610              P{opened.priority}
611            </Text>
612            <Text>{opened.status.replace('_', ' ')}</Text>
613            {appOf(opened) && <Text color="claude">{appOf(opened)}</Text>}
614            <Text dimColor>{opened.id}</Text>
615          </Box>
616          <Text bold wrap="wrap">
617            {opened.title}
618          </Text>
619          <Text dimColor>{rule}</Text>
620          <Text dimColor wrap="wrap">
621            {[
622              opened.type,
623              opened.lane ? `${opened.lane} lane` : '',
624              opened.product ? `product ${opened.product}` : '',
625              opened.advancesStage ? `moves it to ${STAGE_WORDS[opened.advancesStage] ?? opened.advancesStage}` : '',
626              opened.owner ? `owner ${opened.owner}` : '',
627              opened.created ? `filed ${opened.created}` : '',
628              opened.updated && opened.updated !== opened.created ? `updated ${opened.updated}` : '',
629            ]
630              .filter(Boolean)
631              .join(' · ')}
632          </Text>
633        </Box>
634        {opened.detail && (
635          <Box flexDirection="column">
636            <Text bold>What happened</Text>
637            <Text wrap="wrap">{opened.detail}</Text>
638          </Box>
639        )}
640        {opened.acceptance && opened.acceptance.length > 0 && (
641          <Box flexDirection="column">
642            <Text bold>Done when</Text>
643            {opened.acceptance.map((a, i) => (
644              <Text key={`acc-${i}`} wrap="wrap">
645                ☐ {a}
646              </Text>
647            ))}
648          </Box>
649        )}
650        {opened.dependsOn && opened.dependsOn.length > 0 && (
651          <Box flexDirection="column">
652            <Text bold>Waits on</Text>
653            {opened.dependsOn.map(d => {
654              const other = current.tickets.find(t => t.id === d)
655              return other ? (
656                ticketRow(other, 'dep')
657              ) : (
658                <Text key={`dep-done-${d}`} color="success">
659                  ✓ {d} done
660                </Text>
661              )
662            })}
663          </Box>
664        )}
665        {opened.evidence && opened.evidence.length > 0 && (
666          <Box flexDirection="column">
667            <Text bold>Evidence so far</Text>
668            {opened.evidence.map((a, i) => (
669              <Text key={`ev-${i}`} dimColor wrap="wrap">
670                · {a}
671              </Text>
672            ))}
673          </Box>
674        )}
675      </Box>
676    )
677
678    /* -- Open tickets --------------------------------------------------------------------------------------------- */
679    const filter = (await read($, ticketFilter)) || 'all'
680    const shownTickets = current.tickets.filter(t => ticketMatches(t, filter))
681    const priorities = [...new Set(current.tickets.map(t => t.priority))].sort()
682    const ticketApps = current.apps.filter(a => ticketsForApp(current.tickets, a.id).length > 0)
683    const chip = (id: string, label: string) => (
684      <Button
685        key={`filter-${id}`}
686        label={label}
687        variant={filter === id ? 'primary' : 'secondary'}
688        onPress={() => void update($, ticketFilter, () => id)}
689      />
690    )
691    const activeMolds = current.molds.filter(m => !isComingSoon(m.status))
692    const ticketsTab = (
693      <Box flexDirection="column" gap={1}>
694        <Box flexDirection="row" gap={1} flexWrap="wrap">
695          {chip('all', `All ${current.tickets.length}`)}
696          {priorities.map(p => chip(`p${p}`, `P${p} ${current.tickets.filter(t => t.priority === p).length}`))}
697          {ticketApps.map(a => chip(`app:${a.id}`, `${a.id} ${ticketsForApp(current.tickets, a.id).length}`))}
698        </Box>
699        {shownTickets.length === 0 && <Text color="success">Nothing open{filter === 'all' ? '' : ' for this filter'}.</Text>}
700        {activeMolds.map(m => {
701          const mine = shownTickets.filter(t => t.mold === m.id)
702          if (mine.length === 0) return null
703          return (
704            <Box flexDirection="column" key={`tickets-${m.id}`}>
705              <Text dimColor>
706                {m.id} · {mine.length} open
707              </Text>
708              {mine.map(t => ticketRow(t))}
709            </Box>
710          )
711        })}
712        {current.molds.some(m => isComingSoon(m.status)) && (
713          <Text dimColor>
714            Coming-soon molds' planned tickets are not listed (
715            {current.molds
716              .filter(m => isComingSoon(m.status))
717              .map(m => `${m.id} ${m.open + m.inProgress}`)
718              .join(', ')}
719            ).
720          </Text>
721        )}
722      </Box>
723    )
724
725    /* -- Analytics ------------------------------------------------------------------------------------------------ */
726    const reports = await read($, usage)
727    const collecting = await read($, isCollecting)
728    const collectProblem = await read($, collectError)
729    const liveApps = current.apps.filter(a => a.status !== 'retired')
730    const chosenId = (await read($, selectedApp)) || liveApps[0]?.id || ''
731    const chosen = reports[chosenId]
732    const factoryTickets = ticketsForApp(current.tickets, chosenId)
733
734    const analyticsTab = (
735      <Box flexDirection="column" gap={1}>
736        <Box flexDirection="row" gap={1}>
737          {liveApps.map(a => (
738            <Button
739              key={`app-${a.id}`}
740              label={a.id}
741              variant={a.id === chosenId ? 'primary' : 'secondary'}
742              onPress={() => void update($, selectedApp, () => a.id)}
743            />
744          ))}
745        </Box>
746
747        {!chosen && (
748          <Text dimColor>
749            {collecting ? 'Collecting usage from the apps…' : 'No usage report for this app yet. Press Collect usage.'}
750          </Text>
751        )}
752
753        {chosen && (
754          <Box flexDirection="column" gap={1}>
755            <Text dimColor>
756              Last {chosen.days} days · collected {ago(chosen.generated_at, now)}
757            </Text>
758            {chosen.error && <Text color="error">{chosen.error}</Text>}
759
760            <Box flexDirection="column">
761              <Text bold>Usage</Text>
762              <Text>
763                <Text color="suggestion">{short(chosen.totals.people_active)}</Text> people active ·{' '}
764                <Text color="suggestion">{short(chosen.totals.chats)}</Text> chats ·{' '}
765                <Text color="suggestion">{short(chosen.totals.chat_turns)}</Text> chat turns
766              </Text>
767              <Text>
768                {short(chosen.totals.input_tokens)} tokens in · {short(chosen.totals.output_tokens)} out · chat cost{' '}
769                {money(chosen.totals.cost_usd)}
770              </Text>
771              <Text>
772                {short(chosen.totals.workflow_runs)} workflow runs · workflow cost{' '}
773                <Text dimColor={isEstimate(chosen.totals.workflow_cost_basis)}>
774                  {cost(chosen.totals.workflow_cost_usd, chosen.totals.workflow_cost_basis)}
775                </Text>
776              </Text>
777            </Box>
778
779            {chosen.daily.length > 0 && (
780              <Box flexDirection="column">
781                <Text bold>Chat turns per day</Text>
782                <Text color="suggestion">{sparkline(chosen.daily.map(d => d.chat_turns))}</Text>
783                <Text dimColor>
784                  {chosen.daily[0]?.date} → {chosen.daily[chosen.daily.length - 1]?.date} · busiest day{' '}
785                  {Math.max(0, ...chosen.daily.map(d => d.chat_turns ?? 0))} turns
786                </Text>
787              </Box>
788            )}
789
790            <Box flexDirection="column">
791              <Text bold>Tickets in the app</Text>
792              <Text>
793                <Text color={chosen.totals.tickets.open ? 'warning' : 'success'}>{short(chosen.totals.tickets.open)} open</Text> ·{' '}
794                {short(chosen.totals.tickets.in_progress)} in progress · {short(chosen.totals.tickets.done)} done{' '}
795                <Text dimColor>({short(chosen.totals.tickets.total)} in all)</Text>
796              </Text>
797            </Box>
798
799            {chosen.workspaces.length > 0 && (
800              <Box flexDirection="column">
801                <Text bold>By workspace</Text>
802                {chosen.workspaces.map(w => (
803                  <Text key={w.org_id} wrap="truncate">
804                    {w.name}: {short(w.people_active)} people · {short(w.chats)} chats · {short(w.chat_turns)} turns · chat{' '}
805                    {money(w.cost_usd)} · {short(w.workflow_runs)} workflow runs · {short(w.tickets.open)} open tickets
806                  </Text>
807                ))}
808              </Box>
809            )}
810
811            <Box flexDirection="column">
812              <Text bold>By agent</Text>
813              {chosen.by_agent.length === 0 && <Text dimColor>Not collected yet: press Collect usage.</Text>}
814              {chosen.by_agent.slice(0, 12).map(a => (
815                <Box key={`agent-${a.workspace}-${a.agent}`} flexDirection="row" gap={1}>
816                  <Text bold={a.kind === 'main'} color={a.kind === 'main' ? 'suggestion' : 'text'}>
817                    {fit(a.agent, 26).padEnd(26)}
818                  </Text>
819                  <Text>{a.kind === 'main' ? `${short(a.turns)} turns` : `${short(a.runs)} runs`}</Text>
820                  <Text dimColor>
821                    {short(a.input_tokens)} in · {short(a.output_tokens)} out ·
822                  </Text>
823                  {/* An estimate is dimmed and marked "~ est." so it never reads as a measured figure. */}
824                  <Text dimColor={isEstimate(a.cost_basis)}>{cost(a.cost_usd, a.cost_basis)}</Text>
825                  {chosen.workspaces.length > 1 && <Text dimColor>· {a.workspace}</Text>}
826                </Box>
827              ))}
828            </Box>
829
830            <Box flexDirection="column">
831              <Text bold>By user</Text>
832              {chosen.by_user.length === 0 && <Text dimColor>Not collected yet: press Collect usage.</Text>}
833              {chosen.by_user.slice(0, 12).map(u => (
834                <Box key={`user-${u.workspace}-${u.user}`} flexDirection="row" gap={1}>
835                  <Text bold>{fit(u.user, 22).padEnd(22)}</Text>
836                  <Text>
837                    {short(u.chats)} chats · {short(u.chat_turns)} turns
838                  </Text>
839                  <Text dimColor>
840                    · {money(u.cost_usd)}
841                    {u.last_active ? ` · last ${ago(u.last_active, now)}` : ''}
842                  </Text>
843                  {chosen.workspaces.length > 1 && <Text dimColor>· {u.workspace}</Text>}
844                </Box>
845              ))}
846            </Box>
847          </Box>
848        )}
849
850        <Box flexDirection="column">
851          <Text bold>Factory tickets for this app</Text>
852          {factoryTickets.length === 0 && <Text color="success">None open.</Text>}
853          {factoryTickets.map(t => ticketRow(t, 'aticket'))}
854        </Box>
855
856        {collectProblem && <Text color="error">{collectProblem}</Text>}
857      </Box>
858    )
859
860    return (
861      <Box flexDirection="column" gap={1}>
862        {banner.level === 'down' && (
863          <Box key="uptime-banner" flexDirection="column" borderStyle="round" borderColor="error" paddingX={1}>
864            <Text bold color="error">
865              ✕ An app is down. The factory is looking at it.
866            </Text>
867            {banner.lines.map((line, i) => (
868              <Text key={`uptime-line-${i}`} color="error" wrap="wrap">
869                {line}
870              </Text>
871            ))}
872          </Box>
873        )}
874        {dbWarn.level !== 'ok' && (
875          <Box key="db-usage-banner" flexDirection="column" borderStyle="round" borderColor={dbWarn.level === 'limit' ? 'error' : 'warning'} paddingX={1}>
876            <Text bold color={dbWarn.level === 'limit' ? 'error' : 'warning'}>
877              {dbWarn.level === 'limit' ? '✕ A database has reached its plan limit.' : '! A database is near its plan limit.'}
878            </Text>
879            {dbWarn.lines.map((line, i) => (
880              <Text key={`db-line-${i}`} color={dbWarn.level === 'limit' ? 'error' : 'warning'} wrap="wrap">
881                {line}
882              </Text>
883            ))}
884          </Box>
885        )}
886        {banner.level === 'stale' && (
887          <Text key="uptime-stale" color="warning" wrap="wrap">
888            {banner.lines.join(' ')}
889          </Text>
890        )}
891        {tabs}
892        {current.error && <Text color="error">Could not read {current.root}/state: {current.error}</Text>}
893        {shown === 'products' && productsTab}
894        {shown === 'molds' && moldsTab}
895        {shown === 'tickets' && (detail || ticketsTab)}
896        {shown === 'analytics' && analyticsTab}
897        <Box flexDirection="row" gap={1}>
898          <Button key="refresh" label={busy ? 'Refreshing…' : 'Refresh'} onPress={() => void refresh($)} />
899          {shown === 'products' && (
900            <Button
901              key="compute"
902              label={computingBuilds ? 'Computing build costs…' : 'Recompute build costs'}
903              onPress={() => void computeBuilds($)}
904            />
905          )}
906          {shown === 'analytics' && (
907            <Button key="collect" label={collecting ? 'Collecting…' : 'Collect usage'} onPress={() => void collect($)} />
908          )}
909          <Text dimColor>
910            health checked {current.checkedAt ? ago(new Date(current.checkedAt).toISOString(), now) : 'pending'} · every 5 min
911          </Text>
912        </Box>
913      </Box>
914    )
915  })
916}
917
hooks/board.ts 625 lines
1import type { AgentUsage, AppRow, Build, BuildBasis, Check, CostBasis, DbBanner, DbLimit, DbLine, DbUsage, DbWarning, Measured, MoldRow, ProductRow, Ticket, Uptime, UptimeApp, UptimeBanner, Usage, UsageNumbers, UserUsage } from '../types'
2
3// Pure readers of the factory's own state files (state/factory.json, state/products.json,
4// state/application/<id>/*.json, state/tasks/<mold>.jsonl). No I/O here, so the tests drive them directly.
5
6type Json = Record<string, any>
7
8const OPEN = new Set(['todo', 'in_progress', 'blocked'])
9
10/** The latest record per task id: a task file may carry the same id more than once. */
11export function parseTasks(jsonl: string): Ticket[] {
12  const byId = new Map<string, Ticket>()
13  for (const line of jsonl.split('\n')) {
14    if (!line.trim()) continue
15    let row: Json
16    try {
17      row = JSON.parse(line)
18    } catch {
19      continue
20    }
21    if (typeof row.task_id !== 'string') continue
22    byId.set(row.task_id, {
23      id: row.task_id,
24      mold: String(row.mold_id ?? ''),
25      title: String(row.title ?? ''),
26      status: String(row.status ?? ''),
27      priority: Number(row.priority ?? 9),
28      ...(row.type ? { type: String(row.type) } : {}),
29      ...(row.owner ? { owner: String(row.owner) } : {}),
30      ...(row.product_id ? { product: String(row.product_id) } : {}),
31      ...(row.created ? { created: String(row.created) } : {}),
32      ...(row.updated ? { updated: String(row.updated) } : {}),
33      ...(row.advances_stage ? { advancesStage: String(row.advances_stage) } : {}),
34      ...(Array.isArray(row.deps ?? row.depends_on) ? { dependsOn: (row.deps ?? row.depends_on).map(String) } : {}),
35      ...(Array.isArray(row.acceptance) ? { acceptance: row.acceptance.map(String) } : {}),
36      ...(Array.isArray(row.evidence) ? { evidence: row.evidence.map(String) } : {}),
37      ...(row.detail ? { detail: String(row.detail) } : {}),
38      ...(row.lane ? { lane: String(row.lane) } : {}),
39    })
40  }
41  return [...byId.values()]
42}
43
44export function moldRow(id: string, status: string, snapshot: string, tasks: readonly Ticket[]): MoldRow {
45  return {
46    id,
47    status,
48    snapshot: snapshot.slice(0, 7),
49    open: tasks.filter(t => t.status === 'todo' || t.status === 'blocked').length,
50    inProgress: tasks.filter(t => t.status === 'in_progress').length,
51    done: tasks.filter(t => t.status === 'done').length,
52  }
53}
54
55export function openTickets(tasks: readonly Ticket[]): Ticket[] {
56  return tasks
57    .filter(t => OPEN.has(t.status))
58    .sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id))
59}
60
61/** The health pages to probe for one app, by where it runs; none for a retired app. */
62export function healthChecks(application: Json, infrastructure: Json): Check[] {
63  if (application.status === 'retired') return []
64  const target = String(infrastructure.target ?? '')
65  const vercel = infrastructure.vercel ?? {}
66  const remote = infrastructure.vm_remote ?? {}
67  const web = target === 'vm_remote' ? remote.production_url : vercel.production_url
68  const checks: Check[] = []
69  // A single-service mold's app (mold_v0: vercel.projects {api, web}, or compose_remote) answers on /healthz, as
70  // .claude/scripts/uptime.py checks it (the mold's health_path).
71  if (vercel.projects?.api || target === 'compose_remote') {
72    const site = target === 'compose_remote' ? (infrastructure.compose_remote ?? {}).production_url : web
73    if (site) checks.push({ name: 'web', url: `${site}/healthz`, status: 'pending' })
74    if (target !== 'compose_remote' && vercel.api_url) checks.push({ name: 'api', url: `${vercel.api_url}/healthz`, status: 'pending' })
75    return checks
76  }
77  if (web) checks.push({ name: 'web', url: `${web}/api/ops/health`, status: 'pending' })
78  if (target === 'vm_remote' && web) checks.push({ name: 'api', url: `${web}/eve/v1/health`, status: 'pending' })
79  if (target !== 'vm_remote' && vercel.api_url) checks.push({ name: 'api', url: `${vercel.api_url}/eve/v1/health`, status: 'pending' })
80  if (target !== 'vm_remote' && vercel.workflow_url) {
81    checks.push({ name: 'workflow', url: `${vercel.workflow_url}/api/health`, status: 'pending' })
82  }
83  return checks
84}
85
86/**
87 * What provision.py last recorded about "Continue with Google" on this app (infrastructure.json google_sign_in.check,
88 * written after every deploy and --smoke): works directly, through the sign-in hub, not working, or could not be
89 * checked. '' when it was never checked. The board does not ask Google itself.
90 */
91export function googleSignIn(infrastructure: Json): AppRow['google'] {
92  const result = String(infrastructure.google_sign_in?.check?.result ?? '')
93  return result === 'direct' || result === 'hub' || result === 'not_working' || result === 'unknown' ? result : ''
94}
95
96export function appRow(id: string, application: Json, infrastructure: Json, datastores: Json, moldSnapshots: Map<string, string>): AppRow {
97  const target = String(infrastructure.target ?? '?')
98  const url = target === 'vm_remote' ? infrastructure.vm_remote?.production_url : infrastructure.vercel?.production_url
99  const rls = datastores.postgres?.rls_verified
100  const moldId = String(application.mold_id ?? '')
101  const moldCommit = String(application.mold_commit ?? '')
102  const snapshot = moldSnapshots.get(moldId) ?? ''
103  return {
104    id,
105    product: String(application.product_id ?? ''),
106    target,
107    status: String(application.status ?? '?'),
108    moldId,
109    moldCommit: moldCommit.slice(0, 7),
110    isCurrent: moldCommit !== '' && moldCommit === snapshot,
111    url: String(url ?? ''),
112    deployedAt: String(infrastructure.deployed_at ?? ''),
113    rls: rls ? `${rls.protected ?? '?'}/${rls.org_scoped_tables ?? '?'}` : '',
114    google: googleSignIn(infrastructure),
115    checks: healthChecks(application, infrastructure),
116  }
117}
118
119export function productRows(products: Json): ProductRow[] {
120  return (products.products ?? []).map((p: Json) => ({
121    id: String(p.product_id ?? ''),
122    name: String(p.name ?? p.product_id ?? ''),
123    stage: String(p.stage ?? ''),
124    apps: Array.isArray(p.app_ids) ? p.app_ids.length : 0,
125    moldId: String(p.mold_id ?? ''),
126    appIds: Array.isArray(p.app_ids) ? p.app_ids.map(String) : [],
127  }))
128}
129
130/** "3h ago" from an ISO time and now. */
131export function ago(iso: string, now: number): string {
132  const at = Date.parse(iso)
133  if (!Number.isFinite(at)) return '—'
134  const minutes = Math.max(0, Math.round((now - at) / 60_000))
135  if (minutes < 60) return `${minutes}m ago`
136  const hours = Math.round(minutes / 60)
137  if (hours < 48) return `${hours}h ago`
138  return `${Math.round(hours / 24)}d ago`
139}
140
141/** Healthy when every probe answered 2xx; down when any did not; pending until probed. */
142export function verdict(checks: readonly Check[]): 'healthy' | 'down' | 'pending' | 'n/a' {
143  if (checks.length === 0) return 'n/a'
144  if (checks.some(c => c.status === 'pending')) return 'pending'
145  return checks.every(c => typeof c.status === 'number' && c.status >= 200 && c.status < 300) ? 'healthy' : 'down'
146}
147
148/** A mold that is announced but not yet buildable. */
149export const isComingSoon = (status: string): boolean => status === 'coming_soon'
150
151const BARS = '▁▂▃▄▅▆▇█'
152
153/** A one-line bar chart of the values, scaled to the largest; all zero draws the lowest bar. */
154export function sparkline(values: readonly (number | null)[]): string {
155  const top = Math.max(0, ...values.map(v => v ?? 0))
156  return values.map(v => (v === null ? ' ' : BARS[top === 0 ? 0 : Math.min(7, Math.round((v / top) * 7))])).join('')
157}
158
159const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)
160
161/** A report's cost_basis, or null when it says none (an older report, or nothing to cost). */
162export const costBasis = (v: unknown): CostBasis | null => (v === 'recorded' || v === 'estimated' || v === 'mixed' ? v : null)
163
164/** Is this figure (at least partly) an estimate? Then it is shown as one, never as measured. */
165export const isEstimate = (basis: CostBasis | null | undefined): boolean => basis === 'estimated' || basis === 'mixed'
166
167function numbers(raw: Json | undefined): UsageNumbers {
168  const t = raw?.tickets ?? {}
169  return {
170    people_active: num(raw?.people_active),
171    chats: num(raw?.chats),
172    chat_turns: num(raw?.chat_turns),
173    input_tokens: num(raw?.input_tokens),
174    output_tokens: num(raw?.output_tokens),
175    cost_usd: num(raw?.cost_usd),
176    workflow_runs: num(raw?.workflow_runs),
177    workflow_cost_usd: num(raw?.workflow_cost_usd),
178    workflow_cost_basis: costBasis(raw?.workflow_cost_basis),
179    tickets: { open: num(t.open), in_progress: num(t.in_progress), done: num(t.done), total: num(t.total) },
180  }
181}
182
183/** The app_usage.py report, tolerant of missing fields (a missing number reads 0 and the report says what it did not measure). */
184export function parseUsage(raw: Json): Usage {
185  return {
186    app_id: String(raw.app_id ?? ''),
187    generated_at: String(raw.generated_at ?? ''),
188    days: num(raw.days) ?? 30,
189    totals: numbers(raw.totals),
190    workspaces: (Array.isArray(raw.workspaces) ? raw.workspaces : []).map((w: Json) => ({
191      ...numbers(w),
192      org_id: String(w.org_id ?? ''),
193      name: String(w.name ?? w.org_id ?? ''),
194    })),
195    daily: (Array.isArray(raw.daily) ? raw.daily : []).map((d: Json) => ({
196      date: String(d.date ?? ''),
197      chat_turns: num(d.chat_turns),
198      people_active: num(d.people_active),
199    })),
200    not_measured: (Array.isArray(raw.not_measured) ? raw.not_measured : []).map(String),
201    by_agent: (Array.isArray(raw.by_agent) ? raw.by_agent : []).map(
202      (a: Json): AgentUsage => ({
203        agent: String(a.agent ?? ''),
204        kind: a.kind === 'main' ? 'main' : 'specialist',
205        workspace: String(a.workspace ?? ''),
206        turns: num(a.turns),
207        runs: num(a.runs),
208        input_tokens: num(a.input_tokens),
209        output_tokens: num(a.output_tokens),
210        cost_usd: num(a.cost_usd),
211        cost_basis: costBasis(a.cost_basis),
212        estimated_from: typeof a.estimated_from === 'string' && a.estimated_from ? a.estimated_from : null,
213        last_active: String(a.last_active ?? ''),
214      }),
215    ),
216    by_user: (Array.isArray(raw.by_user) ? raw.by_user : []).map(
217      (u: Json): UserUsage => ({
218        user: String(u.user ?? ''),
219        workspace: String(u.workspace ?? ''),
220        chats: num(u.chats),
221        chat_turns: num(u.chat_turns),
222        input_tokens: num(u.input_tokens),
223        output_tokens: num(u.output_tokens),
224        cost_usd: num(u.cost_usd),
225        workflow_runs: num(u.workflow_runs),
226        last_active: String(u.last_active ?? ''),
227      }),
228    ),
229    ...(raw.error ? { error: String(raw.error) } : {}),
230  }
231}
232
233/** The factory's open tickets that name this app. */
234export function ticketsForApp(tickets: readonly Ticket[], appId: string): Ticket[] {
235  const word = new RegExp(`(^|[^a-z0-9_])${appId.replace(/[^a-z0-9_]/gi, '')}($|[^a-z0-9_])`, 'i')
236  return tickets.filter(t => word.test(t.title))
237}
238
239/** 1234567 -> "1.2M", 1234 -> "1.2k"; not measured -> "—". */
240export function short(n: number | null): string {
241  if (n === null) return '—'
242  if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`
243  if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`
244  return String(Math.round(n))
245}
246
247/** "$13.56", "$1,204"; not measured -> "not measured". */
248export function money(n: number | null): string {
249  if (n === null) return 'not measured'
250  return `$${n < 1000 ? n.toFixed(2) : Math.round(n).toLocaleString("en-US")}`
251}
252
253/** money(), and an estimate as "~$1.23 est." so it never reads as a measured figure (the board also dims it). */
254export function cost(n: number | null, basis?: CostBasis | null): string {
255  if (n === null || !isEstimate(basis)) return money(n)
256  return `~${money(n)} est.`
257}
258
259/** a + b, null when either is not measured. */
260export const plus = (a: number | null, b: number | null): number | null => (a === null || b === null ? null : a + b)
261
262/** A product's stages, in order (state/products.json, docs/PRODUCTS.md). */
263export const STAGES = ['defined', 'stamped', 'lanes_passing', 'deployed', 'released'] as const
264
265/** The words the board shows for each stage. */
266export const STAGE_WORDS: Record<string, string> = {
267  defined: 'defined',
268  stamped: 'built',
269  lanes_passing: 'tested',
270  deployed: 'deployed',
271  released: 'released',
272}
273
274/** The stage after this one, or undefined at the last (or an unknown) stage. */
275export function nextStage(stage: string): string | undefined {
276  const at = STAGES.indexOf(stage as (typeof STAGES)[number])
277  return at < 0 ? undefined : STAGES[at + 1]
278}
279
280/** The open tickets that stand between a product and the given stage. */
281export function stageTickets(tickets: readonly Ticket[], productId: string, stage: string): Ticket[] {
282  return tickets.filter(t => t.product === productId && t.advancesStage === stage)
283}
284
285/** Cuts text to `width` cells with an ellipsis. */
286export function fit(text: string, width: number): string {
287  const room = Math.max(4, Math.floor(width))
288  return text.length <= room ? text : `${text.slice(0, room - 1)}…`
289}
290
291/** Whether a ticket passes the tickets tab's filter: "all", "p1", "p2", "p3" or "app:<id>". */
292export function ticketMatches(ticket: Ticket, filter: string): boolean {
293  if (filter === 'all' || filter === '') return true
294  if (/^p\d$/.test(filter)) return ticket.priority === Number(filter.slice(1))
295  if (filter.startsWith('app:')) return ticketsForApp([ticket], filter.slice(4)).length > 0
296  return true
297}
298
299/** A product-gate ticket's title without the "<product> <stage> gate: " lead the board already shows. */
300export function plainTitle(t: Ticket): string {
301  if (!t.product) return t.title
302  const lead = new RegExp(`^${t.product.replace(/[^a-z0-9_]/gi, '')}\\s+[a-z_]+\\s+gate:\\s*`, 'i')
303  const cut = t.title.replace(lead, '')
304  return cut ? cut.charAt(0).toUpperCase() + cut.slice(1) : t.title
305}
306
307/* ---- build cost and time: reports/mint/<app>.json, written by .claude/scripts/mint_report.py --all ------------------ */
308
309export const buildBasis = (v: unknown): BuildBasis | null => (v === 'own' || v === 'apportioned' ? v : null)
310
311const iso = (v: unknown): string => (typeof v === 'string' && Number.isFinite(Date.parse(v)) ? v : '')
312
313/** A mint report's summary; an older report without one reads as not measured throughout, never as 0. */
314export function parseBuild(raw: Json): Build {
315  const s: Json = raw?.summary ?? {}
316  return {
317    cost_usd: num(s.build_cost_usd),
318    basis: buildBasis(s.build_cost_basis),
319    uncounted_est_usd: num(s.build_cost_uncounted_est_usd),
320    agent_model_s: num(s.agent_model_s),
321    agent_tool_s: num(s.agent_tool_s),
322    active_s: num(s.active_s),
323    first_message: iso(s.first_message),
324    first_deploy: iso(s.first_deploy),
325    latest_deploy: iso(s.latest_deploy),
326    deploys: num(s.deploys),
327    calendar_to_first_deploy_s: num(s.calendar_to_first_deploy_s),
328    sessions: num(s.sessions),
329    shares: (Array.isArray(s.build_cost_shares) ? s.build_cost_shares : []).map((x: Json) => ({
330      session: String(x.session ?? ''),
331      basis: buildBasis(x.basis),
332      share: num(x.share),
333    })),
334    generated_at: String(raw?.generated_at ?? ''),
335  }
336}
337
338/** Sum of the numbers that were measured; null when none was (not measured, never 0). */
339const sumOf = (xs: readonly Measured[]): Measured => {
340  const got = xs.filter((x): x is number => x !== null)
341  return got.length ? got.reduce((a, b) => a + b, 0) : null
342}
343
344const earliest = (xs: readonly string[]): string => xs.filter(Boolean).sort((a, b) => Date.parse(a) - Date.parse(b))[0] ?? ''
345const latest = (xs: readonly string[]): string => xs.filter(Boolean).sort((a, b) => Date.parse(b) - Date.parse(a))[0] ?? ''
346
347/** A product's total: the sum of its apps' builds. Apportioned shares of one session add up without counting it twice,
348 * so the sum is honest; it is "apportioned" when any part is. Null when no app of it has a report. */
349export function sumBuilds(builds: readonly Build[]): Build | null {
350  if (builds.length === 0) return null
351  const first = earliest(builds.map(b => b.first_message))
352  const deployed = earliest(builds.map(b => b.first_deploy))
353  const gap = first && deployed ? (Date.parse(deployed) - Date.parse(first)) / 1000 : null
354  const bases = new Set(builds.map(b => b.basis).filter(Boolean))
355  return {
356    cost_usd: sumOf(builds.map(b => b.cost_usd)),
357    basis: bases.size === 0 ? null : bases.has('apportioned') ? 'apportioned' : 'own',
358    uncounted_est_usd: sumOf(builds.map(b => b.uncounted_est_usd)),
359    agent_model_s: sumOf(builds.map(b => b.agent_model_s)),
360    agent_tool_s: sumOf(builds.map(b => b.agent_tool_s)),
361    active_s: sumOf(builds.map(b => b.active_s)),
362    first_message: first,
363    first_deploy: deployed,
364    latest_deploy: latest(builds.map(b => b.latest_deploy)),
365    deploys: sumOf(builds.map(b => b.deploys)),
366    calendar_to_first_deploy_s: gap !== null && gap >= 0 ? gap : null,
367    sessions: new Set(builds.flatMap(b => b.shares.map(s => s.session))).size || sumOf(builds.map(b => b.sessions)),
368    shares: builds.flatMap(b => b.shares),
369    generated_at: latest(builds.map(b => b.generated_at)),
370  }
371}
372
373/** 300 -> "5m", 18720 -> "5h 12m", 187200 -> "2d 4h"; not measured -> "not measured". */
374export function duration(seconds: number | null): string {
375  if (seconds === null || !Number.isFinite(seconds)) return 'not measured'
376  const m = Math.max(0, Math.floor(seconds / 60))
377  if (m < 60) return `${m}m`
378  if (m < 24 * 60) return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
379  return `${Math.floor(m / 1440)}d ${Math.floor((m % 1440) / 60)}h`
380}
381
382/** One app's (or product's) build line as parts; `dim` parts are apportioned or estimated, and are shown dimmed so they
383 * never read as a figure measured for this app alone. */
384export function buildParts(b: Build | null | undefined): { text: string; dim: boolean }[] {
385  if (!b) return [{ text: 'built: not measured', dim: true }]
386  const shared = b.basis === 'apportioned'
387  const parts = [{ text: `built: ${money(b.cost_usd)}${b.cost_usd !== null && shared ? ' (shared)' : ''}`, dim: shared }]
388  if (b.uncounted_est_usd) parts.push({ text: `+ ~${money(b.uncounted_est_usd)} est.`, dim: true })
389  parts.push({ text: `· agent ${duration(b.agent_model_s)}`, dim: shared && b.agent_model_s !== null })
390  parts.push({ text: `· active ${duration(b.active_s)}`, dim: shared && b.active_s !== null })
391  parts.push({ text: `· first message → live ${duration(b.calendar_to_first_deploy_s)}`, dim: false })
392  parts.push({ text: b.deploys === null ? '· deploys not measured' : `· ${b.deploys} deploy${b.deploys === 1 ? '' : 's'}`, dim: false })
393  return parts
394}
395
396/* ---- uptime: .runs/uptime/state.json, written every minute by .claude/scripts/uptime.py ---------------------------- */
397
398/** The monitor counts as stopped when its last check is older than this. */
399export const UPTIME_STALE_MS = 5 * 60_000
400
401const UPTIME_STATUSES = new Set(['up', 'failing', 'down', 'unknown'])
402
403export function parseUptime(raw: Json | null | undefined): Uptime | null {
404  if (!raw || typeof raw !== 'object' || typeof raw.checked_at !== 'string') return null
405  const apps: UptimeApp[] = Object.entries((raw.apps ?? {}) as Record<string, Json>)
406    .map(([id, a]) => ({
407      id,
408      status: (UPTIME_STATUSES.has(String(a?.status)) ? String(a.status) : 'unknown') as UptimeApp['status'],
409      since: String(a?.since ?? a?.down_since ?? ''),
410      address: String(a?.address ?? ''),
411      lastError: String(a?.last_error ?? ''),
412      emailed: typeof a?.email?.sent === 'boolean' ? a.email.sent : null,
413      emailWhy: String(a?.email?.why ?? ''),
414    }))
415    .sort((x, y) => x.id.localeCompare(y.id))
416  return { checkedAt: raw.checked_at, apps, emailOn: raw.email?.configured === true, emailWhy: String(raw.email?.why ?? '') }
417}
418
419/** "35 min" / "2 h 5 min" between an ISO time and now. */
420export function since(iso: string, now: number): string {
421  const at = Date.parse(iso)
422  if (!Number.isFinite(at)) return '?'
423  const minutes = Math.max(0, Math.round((now - at) / 60_000))
424  if (minutes < 60) return `${minutes} min`
425  const h = Math.floor(minutes / 60)
426  return minutes % 60 ? `${h} h ${minutes % 60} min` : `${h} h`
427}
428
429const hhmm = (iso: string): string => {
430  const t = new Date(iso)
431  return Number.isFinite(t.getTime()) ? `${t.toISOString().slice(11, 16)} UTC` : '?'
432}
433
434/** The banner's lines: one per app that is down, in plain words; or a warning that the monitor stopped. */
435export function uptimeBanner(u: Uptime | null, now: number): UptimeBanner {
436  if (!u) return { level: 'missing', lines: ['Uptime monitor: not running yet (python3 .claude/scripts/uptime.py install).'] }
437  const down = u.apps.filter(a => a.status === 'down')
438  const lines = down.map(a => {
439    const told = a.emailed === true ? 'the operator was emailed' : a.emailed === false ? `not emailed: ${a.emailWhy}` : ''
440    return [`${a.id} is DOWN since ${hhmm(a.since)} (${since(a.since, now)})`, a.address, a.lastError, told].filter(Boolean).join(' · ')
441  })
442  const age = now - Date.parse(u.checkedAt)
443  const stale = !Number.isFinite(age) || age > UPTIME_STALE_MS
444  if (stale) lines.push(`Uptime monitor last ran ${since(u.checkedAt, now)} ago; it may have stopped (uptime.py status).`)
445  if (down.length) return { level: 'down', lines }
446  return stale ? { level: 'stale', lines } : { level: 'ok', lines: [] }
447}
448
449/* ---- why an app is down: the app's /api/ops/health JSON ----------------------------------------------------------- */
450
451/** The health JSON's parts, in the order the board names them. */
452const HEALTH_PARTS: [string, string][] = [
453  ['db', 'database'],
454  ['blob', 'file storage'],
455  ['inference', 'the assistant'],
456  ['taskWorkflow', 'background tasks'],
457]
458
459/** First match wins. The TypeScript twin of .claude/scripts/lib/health_cause.py (RULES): change both. */
460const CAUSE_RULES: [RegExp, string][] = [
461  [/\b53000\b|insufficient[_ ]resources|quota|usage limit|exceeded the|limit (?:was |has been )?reached|plan limit/i, 'the request was refused (usage limit?)'],
462  [/\b53300\b|too many (?:clients|connections)|remaining connection slots/i, 'too many connections at once'],
463  [/password authentication failed|\b28P01\b|\b28000\b|role \S+ does not exist/i, 'sign-in to it was refused (wrong password or role)'],
464  [/suspended|endpoint (?:is |has been )?disabled/i, 'it is switched off at the provider (suspended)'],
465  [/ECONNREFUSED|connection refused/i, 'it refused the connection (not running?)'],
466  [/ENOTFOUND|EAI_AGAIN|getaddrinfo|could not be found/i, 'its address could not be found'],
467  [/timed? ?out|timeout|ETIMEDOUT|aborted/i, 'it did not answer in time'],
468  [/MISCONFIGURED|not configured|unset or unusable|\bno [A-Z][A-Z_]{3,}\b/, 'it is not set up (a setting is missing)'],
469  [/returned (\d{3})/, 'it answered with an error (HTTP $1)'],
470  [/not ready|unhealthy/i, 'it reports it is not ready'],
471]
472export const UNKNOWN_CAUSE = 'it failed (a cause the factory does not recognise)'
473
474/** One part's plain cause from its detail text; the text itself is never shown (it can carry a host or a role). */
475export function causeOf(detail: unknown): string {
476  const text = String(detail ?? '')
477  for (const [rx, words] of CAUSE_RULES) {
478    const m = text.match(rx)
479    if (m) return words.replace('$1', m[1] ?? '')
480  }
481  return UNKNOWN_CAUSE
482}
483
484/** "<part>: <cause>" for each part the app's health JSON reports failing; [] when the body is not that JSON. */
485export function healthCauses(body: string): string[] {
486  let data: Json
487  try {
488    data = JSON.parse(body)
489  } catch {
490    return []
491  }
492  if (!data || typeof data !== 'object' || data.ok !== false) return []
493  return HEALTH_PARTS.filter(([key]) => data[key]?.ok === false).map(([key, part]) => `${part}: ${causeOf(data[key]?.detail)}`)
494}
495
496/** What the board says for a down app: each failing page with its causes, e.g. "web 503: database: the request was refused …". */
497export function downReasons(checks: readonly Check[]): string[] {
498  return checks
499    .filter(c => !(typeof c.status === 'number' && c.status >= 200 && c.status < 300) && c.status !== 'pending')
500    .map(c => `${c.name} ${String(c.status)}${c.causes?.length ? `: ${c.causes.join('; ')}` : ''}`)
501}
502
503/** The status-line summary; a down app is named with its first cause, not only counted. */
504export function summary(apps: readonly AppRow[], open: number): string {
505  const live = apps.filter(a => a.checks.length > 0)
506  const healthy = live.filter(a => verdict(a.checks) === 'healthy').length
507  const down = live.filter(a => verdict(a.checks) === 'down')
508  const named = down.map(a => {
509    const cause = a.checks.flatMap(c => c.causes ?? [])[0]
510    return cause ? `${a.id} (${cause})` : a.id
511  })
512  const downText = live.length - healthy ? ` · ${live.length - healthy} down${named.length ? `: ${named.join(', ')}` : ''}` : ''
513  return `factory: ${healthy}/${live.length} apps healthy${downText} · ${open} open ticket${open === 1 ? '' : 's'}`
514}
515
516/* ---- database plan usage: reports/db-usage/<app>.json, written by .claude/scripts/lib/db_usage.py ------------------- */
517
518/** The share of a limit at which the board warns (db_usage.py WARN_AT). */
519export const DB_WARN_PCT = 80
520/** How often the usage is measured: the systemd timer (uptime.py install) and an open board's own tick. */
521export const DB_EVERY_MS = 30 * 60_000
522/** A report older than two periods is stale: whatever it said is no longer a measurement. */
523export const DB_STALE_MS = 2 * DB_EVERY_MS
524
525/** True when the report is older than DB_STALE_MS, or its time cannot be read. */
526export function dbStale(d: DbUsage, now: number): boolean {
527  const at = Date.parse(d.generatedAt)
528  return !Number.isFinite(at) || now - at > DB_STALE_MS
529}
530
531/** Whether the board should measure now: an app (not retired) has no report, or its report is stale. */
532export function dbNeedsMeasure(appIds: readonly string[], reports: Record<string, DbUsage>, now: number): boolean {
533  return appIds.some(id => !reports[id] || dbStale(reports[id]!, now))
534}
535
536const PROVIDER_WORDS: Record<string, string> = { neon: 'Neon', supabase: 'Supabase', self_hosted: 'own server' }
537
538export function parseDbUsage(raw: Json | null | undefined): DbUsage | null {
539  if (!raw || typeof raw !== 'object' || typeof raw.app_id !== 'string') return null
540  const limits: DbLimit[] = (Array.isArray(raw.limits) ? raw.limits : [])
541    .filter((l: Json) => num(l?.limit) !== null && num(l?.used) !== null)
542    .map((l: Json) => ({
543      name: String(l.name ?? ''),
544      limit: num(l.limit)!,
545      unit: String(l.unit ?? ''),
546      used: num(l.used)!,
547      pct: num(l.pct),
548      note: String(l.note ?? ''),
549    }))
550  const warnings: DbWarning[] = (Array.isArray(raw.warnings) ? raw.warnings : []).map((w: Json) => ({
551    limit: String(w?.limit ?? ''),
552    pct: num(w?.pct),
553    level: w?.level === 'limit' ? 'limit' : 'warn',
554    text: String(w?.text ?? ''),
555  }))
556  return {
557    appId: raw.app_id,
558    generatedAt: String(raw.generated_at ?? ''),
559    provider: String(raw.provider ?? ''),
560    resource: String(raw.resource ?? ''),
561    plan: raw.plan && typeof raw.plan === 'object' ? { name: String(raw.plan.name ?? '?'), paid: raw.plan.paid === true } : null,
562    quotaExceeded: typeof raw.quota_exceeded === 'boolean' ? raw.quota_exceeded : null,
563    limits,
564    usage: (Array.isArray(raw.usage) ? raw.usage : [])
565      .filter((u: Json) => num(u?.value) !== null)
566      .map((u: Json) => ({ name: String(u.name ?? ''), value: num(u.value)!, unit: String(u.unit ?? '') })),
567    notMeasured: (Array.isArray(raw.not_measured) ? raw.not_measured : []).map(String),
568    warnings,
569    upgrade: String(raw.upgrade ?? ''),
570  }
571}
572
573const figure = (n: number): string => String(Math.round(n * 100) / 100)
574
575/** One app's database line: its plan, each limit as used/limit (pct), usage with no limit, what was not measured, and
576 * when it was measured. A stale report is "not measured since …": what it said is shown, but never as a calm "ok". */
577export function dbLine(d: DbUsage | null | undefined, now: number): DbLine {
578  if (!d) return { text: 'database: not measured yet', level: 'none' }
579  const line = dbLineOf(d)
580  const when = ago(d.generatedAt, now)
581  if (dbStale(d, now)) {
582    return {
583      text: `database: not measured since ${when} (stale) · last: ${line.text.replace(/^database: /, '')}`,
584      level: line.level === 'ok' ? 'none' : line.level,
585    }
586  }
587  return { text: `${line.text} · measured ${when}`, level: line.level }
588}
589
590function dbLineOf(d: DbUsage): DbLine {
591  const provider = PROVIDER_WORDS[d.provider] ?? (d.provider || 'database')
592  if (!d.plan) {
593    const why = `not measured (${d.notMeasured[0] ?? 'no source'})`
594    // the provider's own flag stands even when the plan could not be read
595    if (d.quotaExceeded) return { text: `database: ${provider} · USAGE LIMIT REACHED · ${why}`, level: 'limit' }
596    return { text: `database: ${provider} · ${why}`, level: 'none' }
597  }
598  const parts = [`database: ${provider} ${d.plan.name}`]
599  if (d.quotaExceeded) parts.push('USAGE LIMIT REACHED')
600  for (const l of d.limits) parts.push(`${l.name.toLowerCase()} ${figure(l.used)}/${figure(l.limit)} ${l.unit}${l.pct === null ? '' : ` (${Math.round(l.pct)}%)`}`)
601  const limited = new Set(d.limits.map(l => l.name.toLowerCase().split(' ')[0]))
602  for (const u of d.usage) {
603    if (!limited.has(u.name.toLowerCase().split(' ')[0])) parts.push(`${u.name.toLowerCase()} ${figure(u.value)} ${u.unit} this period`)
604  }
605  if (d.limits.length === 0 && d.plan.paid) parts.push('billed per use, no fixed limit')
606  const unmeasured = d.notMeasured.filter(n => !/states no fixed usage limit/.test(n))
607  if (unmeasured.length) parts.push(`not measured: ${unmeasured.map(n => n.split(/ \(|: /)[0]).join(', ')}`)
608  // reached only when used >= limit exactly (a pct rounded to 100 is not the limit), or by the provider's own flag
609  const reached = d.limits.some(l => l.limit > 0 && l.used >= l.limit)
610  const near = d.limits.some(l => l.limit > 0 && l.used >= (DB_WARN_PCT / 100) * l.limit)
611  const level = d.quotaExceeded || reached ? 'limit' : near ? 'warn' : 'ok'
612  return { text: parts.join(' · '), level }
613}
614
615/** The banner above the tabs: each app's warning (it names the limit and the upgrade step); quiet when none. A warning
616 * from a stale report stays, with when it was measured. */
617export function dbBanner(reports: Record<string, DbUsage>, now: number): DbBanner {
618  const all = Object.values(reports).sort((a, b) => a.appId.localeCompare(b.appId))
619  const lines = all.flatMap(d =>
620    d.warnings.map(w => (dbStale(d, now) ? `${w.text} (measured ${ago(d.generatedAt, now)}; stale)` : w.text)),
621  )
622  const level = all.some(d => d.quotaExceeded || d.warnings.some(w => w.level === 'limit')) ? 'limit' : lines.length ? 'warn' : 'ok'
623  return { level, lines }
624}
625
types/index.d.ts 214 lines
1export type Check = {
2  name: string
3  url: string
4  status: number | 'down' | 'pending'
5  /** When the page failed and answered the app's health JSON: "<part>: <cause>" per failing part (healthCauses). */
6  causes?: string[]
7}
8
9export type AppRow = {
10  id: string
11  product: string
12  target: string
13  status: string
14  moldId: string
15  moldCommit: string
16  isCurrent: boolean
17  url: string
18  deployedAt: string
19  rls: string
20  /** What the last deploy or --smoke found about "Continue with Google": '' when it was never checked. */
21  google: '' | 'direct' | 'hub' | 'not_working' | 'unknown'
22  checks: Check[]
23}
24
25export type ProductRow = { id: string; name: string; stage: string; apps: number; moldId: string; appIds: string[] }
26
27export type MoldRow = { id: string; status: string; snapshot: string; open: number; inProgress: number; done: number }
28
29export type Ticket = {
30  id: string
31  mold: string
32  title: string
33  status: string
34  priority: number
35  type?: string
36  owner?: string
37  product?: string
38  created?: string
39  updated?: string
40  advancesStage?: string
41  dependsOn?: string[]
42  acceptance?: string[]
43  evidence?: string[]
44  detail?: string
45  lane?: string
46}
47
48export type Board = {
49  root: string
50  loadedAt: number
51  checkedAt: number
52  apps: AppRow[]
53  products: ProductRow[]
54  molds: MoldRow[]
55  tickets: Ticket[]
56  error?: string
57}
58
59/** null: not measured (the report's not_measured says why); a number is a measured value, 0 included. */
60export type Measured = number | null
61
62/** How a cost was arrived at (app_usage.py): recorded by the app; estimated from tokens at the configured model; or both. */
63export type CostBasis = 'recorded' | 'estimated' | 'mixed'
64
65export type TicketCounts = { open: Measured; in_progress: Measured; done: Measured; total: Measured }
66
67export type UsageNumbers = {
68  people_active: Measured
69  chats: Measured
70  chat_turns: Measured
71  input_tokens: Measured
72  output_tokens: Measured
73  cost_usd: Measured
74  workflow_runs: Measured
75  workflow_cost_usd: Measured
76  /** Absent in an older report: read as recorded. */
77  workflow_cost_basis?: CostBasis | null
78  tickets: TicketCounts
79}
80
81export type AgentUsage = {
82  agent: string
83  kind: 'main' | 'specialist'
84  workspace: string
85  turns: Measured
86  runs: Measured
87  input_tokens: Measured
88  output_tokens: Measured
89  cost_usd: Measured
90  /** Absent in an older report: read as recorded. estimated / mixed: shown as an estimate, never as measured. */
91  cost_basis?: CostBasis | null
92  /** The model an estimate was priced at, when there is one. */
93  estimated_from?: string | null
94  last_active: string
95}
96
97export type UserUsage = {
98  user: string
99  workspace: string
100  chats: Measured
101  chat_turns: Measured
102  input_tokens: Measured
103  output_tokens: Measured
104  cost_usd: Measured
105  workflow_runs: Measured
106  last_active: string
107}
108
109export type Usage = {
110  app_id: string
111  generated_at: string
112  days: number
113  totals: UsageNumbers
114  workspaces: (UsageNumbers & { org_id: string; name: string })[]
115  daily: { date: string; chat_turns: Measured; people_active: Measured }[]
116  not_measured: string[]
117  by_agent: AgentUsage[]
118  by_user: UserUsage[]
119  error?: string
120}
121
122/** How an app's build figures were arrived at (mint_report.py): own, every session that names the app names no other;
123 * apportioned, a session shared with other apps was split and this is the app's share (shown as "shared", dimmed). */
124export type BuildBasis = 'own' | 'apportioned'
125
126/** What it took to build one app, or the sum over a product's apps: reports/mint/<app>.json's summary. */
127export type Build = {
128  /** Measured by the sessions' own cost counters (then apportioned when basis says so); null: not measured. */
129  cost_usd: Measured
130  basis: BuildBasis | null
131  /** Agent work after a session's last cost record: always an estimate, never added into cost_usd. */
132  uncounted_est_usd: Measured
133  agent_model_s: Measured
134  agent_tool_s: Measured
135  active_s: Measured
136  first_message: string
137  first_deploy: string
138  latest_deploy: string
139  deploys: Measured
140  calendar_to_first_deploy_s: Measured
141  sessions: Measured
142  /** Each session's share of it, when apportioned. */
143  shares: { session: string; basis: BuildBasis | null; share: Measured }[]
144  generated_at: string
145}
146
147export type Tab = 'products' | 'molds' | 'tickets' | 'analytics'
148
149/** One plan limit compared with what the provider reported (reports/db-usage/<app>.json, lib/db_usage.py). */
150export type DbLimit = { name: string; limit: number; unit: string; used: number; pct: number | null; note: string }
151
152export type DbWarning = { limit: string; pct: number | null; level: 'warn' | 'limit'; text: string }
153
154/** An app's database plan usage, read from the provider; what no source reports is in notMeasured, never a number. */
155export type DbUsage = {
156  appId: string
157  generatedAt: string
158  provider: string
159  resource: string
160  plan: { name: string; paid: boolean } | null
161  /** The provider's own "a usage limit is reached" flag; null when it gives none. */
162  quotaExceeded: boolean | null
163  limits: DbLimit[]
164  usage: { name: string; value: number; unit: string }[]
165  notMeasured: string[]
166  warnings: DbWarning[]
167  upgrade: string
168}
169
170/** The board's database line for one app: ok, warn (80% or more of a limit) or limit (reached). */
171export type DbLine = { text: string; level: 'ok' | 'warn' | 'limit' | 'none' }
172
173export type DbBanner = { level: 'ok' | 'warn' | 'limit'; lines: string[] }
174
175/** One app in .runs/uptime/state.json, written every minute by .claude/scripts/uptime.py. */
176export type UptimeApp = {
177  id: string
178  /** up; failing: one failed check, not yet down; down: two or more in a row. */
179  status: 'up' | 'failing' | 'down' | 'unknown'
180  since: string
181  address: string
182  lastError: string
183  /** null: no email attempted; true: sent; false: not sent, `emailWhy` says why. */
184  emailed: boolean | null
185  emailWhy: string
186}
187
188export type Uptime = { checkedAt: string; apps: UptimeApp[]; emailOn: boolean; emailWhy: string }
189
190/** What the board shows about uptime: red while an app is down, amber when the monitor has not run lately. */
191export type UptimeBanner = { level: 'down' | 'stale' | 'ok' | 'missing'; lines: string[] }
192
193declare module 'claude-code' {
194  interface PluginState {
195    'factory-board': {
196      board: Board | null
197      isRefreshing: boolean
198      tab: Tab
199      selectedApp: string
200      usage: Record<string, Usage>
201      isCollecting: boolean
202      collectError: string
203      openTicket: string
204      ticketFilter: string
205      builds: Record<string, Build>
206      isComputing: boolean
207      computeError: string
208      uptime: Uptime | null
209      dbUsage: Record<string, DbUsage>
210      dbError: string
211    }
212  }
213}
214