Public: anyone can read this; the crew can change it.
The forge watches its own use: every page, fragment, route and tool counted, a usage map, and what nobody uses is proposed for the drop #1446
scout/forge:scout/1136-the-forge-watches-its-own-use-every-page → main 8 commits fork
16 files
changed +915
−9
README.md +15
| @@ -375,6 +375,21 @@ The terminal has no backups view, so it has no readout. | ||
| 375 | 375 | grew up in switched off: what a host owes it, the moves in order, and what is |
| 376 | 376 | given up. |
| 377 | 377 | |
| 378 | ## Usage | |
| 379 | ||
| 380 | The forge counts its own use so what nobody uses can be dropped. Each | |
| 381 | answered request is counted once by route *pattern* (`/:owner/:name`, never | |
| 382 | the path), method, status, the viewer's role (stranger, reader, writer, | |
| 383 | owner, admin, agent) and surface (page, fragment, API, MCP, tool); no path, | |
| 384 | id, query, body or person is kept (`src/core/hits.ts`, tables `hit_hour` and | |
| 385 | `hit_day`). Writes are batched; whole past days roll up daily. An admin | |
| 386 | reads it at `/usage` (tabs: pages, fragments, tools, settings, API, never | |
| 387 | used), `GET /api/v1/usage` and the MCP `use_map` tool. The sentinel | |
| 388 | (`src/crew/sentinel.ts`) turns anything no person used for 30 days into a | |
| 389 | drop proposal quoting the numbers, but only once the forge has counted for 30 | |
| 390 | days. Not yet: SSH commands are not counted, flag variants are recorded | |
| 391 | empty until flags exist, and the proposals are not yet filed as asks. | |
| 392 | ||
| 378 | 393 | ## Cloud accounts |
| 379 | 394 | |
| 380 | 395 | **Settings → Cloud accounts** (admins) holds provider keys — Cloudflare, |
docs/MCP.md +1
| @@ -40,6 +40,7 @@ for a tunnel and a forge that sleeps. | ||
| 40 | 40 | | `probe` | knock on a running app's doors as nobody, a user and an admin; the ones that disobey its contract | | |
| 41 | 41 | | `following` | where a fork stands against what it follows, and what the crew is doing about it | | |
| 42 | 42 | | `spawn` | `{ name, apps?, crew?, dryRun? }`: a child forge, planned first (`dryRun` is true unless `false`); an admin's, and an `ro` token may plan but not make | yes | |
| 43 | | `use_map` | `{ tab? }`: how the forge is used, counted by route pattern: ranked over 7/30/90 days, last used, by role, trend, and what nobody uses. An admin's | | | |
| 43 | 44 | | `claim_link` | `{ name }`: a new claim link for a child you spawned that nobody has claimed; the old one stops working. An admin's | yes | |
| 44 | 45 | | `take_updates` | a fork takes its parent's updates when git can do it alone; a conflict is refused | yes | |
| 45 | 46 | | `converge` | the fork's crew merges where both sides changed the same files; comes back as a pull | yes | |
scripts/gate.ts +1
| @@ -44,6 +44,7 @@ export const GATE: readonly string[] = [ | ||
| 44 | 44 | "test/commit-identity.test.ts", |
| 45 | 45 | "test/enterable-apps.test.ts", |
| 46 | 46 | "test/event-order.test.ts", |
| 47 | "test/hits.test.ts", | |
| 47 | 48 | "test/refresh-meta.test.ts", |
| 48 | 49 | "test/restore-card.test.ts", |
| 49 | 50 | "test/returns.test.ts", |
src/actions/hits.ts added +142
| @@ -0,0 +1,142 @@ | ||
| 1 | /** | |
| 2 | * The usage map — what the forge's own use looks like (`core/hits.ts`): | |
| 3 | * each route ranked by use over 7, 30 and 90 days, when it was last used, | |
| 4 | * by which roles, and whether it is rising or falling; and what is | |
| 5 | * registered yet nobody has used. Read by `/usage`, `GET /api/v1/usage`, | |
| 6 | * the MCP `use_map` tool and the sentinel (`crew/sentinel.ts`). | |
| 7 | * | |
| 8 | * Units, stated once: `usesN` is answered requests in the last N whole | |
| 9 | * days including today (UTC); `trend` compares the last 7 days with the 7 | |
| 10 | * before; `people` is every role but `agent`. Plain data, no authz: the | |
| 11 | * caller decides who may read (admin or owner). | |
| 12 | */ | |
| 13 | ||
| 14 | import type { Database } from "bun:sqlite"; | |
| 15 | import { dayOf, hitRows, ROLES, watchingSince, type Role, type Surface } from "../core/hits.ts"; | |
| 16 | ||
| 17 | export type Tab = "pages" | "fragments" | "tools" | "settings" | "api"; | |
| 18 | export const TABS: readonly Tab[] = ["pages", "fragments", "tools", "settings", "api"]; | |
| 19 | ||
| 20 | /** Something that exists and could be used: a registered route or a tool. */ | |
| 21 | export interface Known { | |
| 22 | readonly route: string; | |
| 23 | readonly method: string; | |
| 24 | readonly surface: Surface; | |
| 25 | } | |
| 26 | ||
| 27 | export type Trend = "new" | "up" | "down" | "flat"; | |
| 28 | ||
| 29 | export interface UsageLine { | |
| 30 | readonly route: string; | |
| 31 | readonly method: string; | |
| 32 | readonly surface: Surface; | |
| 33 | readonly tab: Tab; | |
| 34 | readonly uses7: number; | |
| 35 | readonly uses30: number; | |
| 36 | readonly uses90: number; | |
| 37 | readonly people30: number; | |
| 38 | /** Counts by viewer role over 90 days; roles with none are left out. */ | |
| 39 | readonly byRole: Readonly<Partial<Record<Role, number>>>; | |
| 40 | /** Of the 90 days' answers, those that were 4xx or 5xx. */ | |
| 41 | readonly errors90: number; | |
| 42 | readonly trend: Trend; | |
| 43 | /** Last hour used, `YYYY-MM-DDTHH:00:00Z`; null when never in 90 days. */ | |
| 44 | readonly last: string | null; | |
| 45 | } | |
| 46 | ||
| 47 | export interface UsageMap { | |
| 48 | readonly now: string; | |
| 49 | /** First day anything was counted; null before the first answer. */ | |
| 50 | readonly watchingSince: string | null; | |
| 51 | readonly watchingDays: number; | |
| 52 | readonly lines: readonly UsageLine[]; | |
| 53 | /** Registered, and not used once in 90 days. */ | |
| 54 | readonly neverUsed: readonly Known[]; | |
| 55 | } | |
| 56 | ||
| 57 | export const tabOf = (route: string, surface: Surface): Tab => | |
| 58 | surface === "tool" | |
| 59 | ? "tools" | |
| 60 | : /^\/(api\/v1\/)?settings(\/|$)/.test(route) | |
| 61 | ? "settings" | |
| 62 | : surface === "fragment" | |
| 63 | ? "fragments" | |
| 64 | : surface === "api" || surface === "mcp" | |
| 65 | ? "api" | |
| 66 | : "pages"; | |
| 67 | ||
| 68 | const DAY = 86_400_000; | |
| 69 | const daysAgo = (now: Date, n: number): string => dayOf(new Date(now.getTime() - n * DAY)); | |
| 70 | ||
| 71 | export function usageMap(db: Database, known: readonly Known[], now: Date = new Date()): UsageMap { | |
| 72 | const since90 = daysAgo(now, 89); | |
| 73 | const since30 = daysAgo(now, 29); | |
| 74 | const since7 = daysAgo(now, 6); | |
| 75 | const prev7from = daysAgo(now, 13); | |
| 76 | interface Acc { | |
| 77 | route: string; | |
| 78 | method: string; | |
| 79 | surface: Surface; | |
| 80 | u7: number; | |
| 81 | u30: number; | |
| 82 | u90: number; | |
| 83 | p30: number; | |
| 84 | prev: number; | |
| 85 | err: number; | |
| 86 | last: string; | |
| 87 | roles: Partial<Record<Role, number>>; | |
| 88 | } | |
| 89 | const acc = new Map<string, Acc>(); | |
| 90 | const seen = new Set<string>(); | |
| 91 | for (const r of hitRows(db, since90)) { | |
| 92 | seen.add(`${r.method} ${r.route}`); | |
| 93 | const key = `${r.surface} ${r.method} ${r.route}`; | |
| 94 | let a = acc.get(key); | |
| 95 | if (a === undefined) { | |
| 96 | a = { route: r.route, method: r.method, surface: r.surface, u7: 0, u30: 0, u90: 0, p30: 0, prev: 0, err: 0, last: "", roles: {} }; | |
| 97 | acc.set(key, a); | |
| 98 | } | |
| 99 | a.u90 += r.n; | |
| 100 | if (r.day >= since30) { | |
| 101 | a.u30 += r.n; | |
| 102 | if (r.role !== "agent") a.p30 += r.n; | |
| 103 | } | |
| 104 | if (r.day >= since7) a.u7 += r.n; | |
| 105 | else if (r.day >= prev7from) a.prev += r.n; | |
| 106 | if (r.status >= 400) a.err += r.n; | |
| 107 | if (r.last > a.last) a.last = r.last; | |
| 108 | a.roles[r.role] = (a.roles[r.role] ?? 0) + r.n; | |
| 109 | } | |
| 110 | const lines: UsageLine[] = [...acc.values()].map((a) => ({ | |
| 111 | route: a.route, | |
| 112 | method: a.method, | |
| 113 | surface: a.surface, | |
| 114 | tab: tabOf(a.route, a.surface), | |
| 115 | uses7: a.u7, | |
| 116 | uses30: a.u30, | |
| 117 | uses90: a.u90, | |
| 118 | people30: a.p30, | |
| 119 | byRole: Object.fromEntries(ROLES.filter((x) => a.roles[x]).map((x) => [x, a.roles[x]!])), | |
| 120 | errors90: a.err, | |
| 121 | trend: a.u7 === 0 && a.prev === 0 ? "flat" : a.prev === 0 ? "new" : a.u7 > a.prev * 1.2 ? "up" : a.u7 < a.prev * 0.8 ? "down" : "flat", | |
| 122 | last: a.last === "" ? null : `${a.last}:00:00Z`, | |
| 123 | })); | |
| 124 | lines.sort( | |
| 125 | (x, y) => | |
| 126 | y.uses7 - x.uses7 || | |
| 127 | y.uses30 - x.uses30 || | |
| 128 | y.uses90 - x.uses90 || | |
| 129 | `${x.method} ${x.route}`.localeCompare(`${y.method} ${y.route}`), | |
| 130 | ); | |
| 131 | const first = watchingSince(db) ?? null; | |
| 132 | const neverUsed = known | |
| 133 | .filter((k) => !seen.has(`${k.method} ${k.route}`)) | |
| 134 | .sort((a, b) => `${a.route} ${a.method}`.localeCompare(`${b.route} ${b.method}`)); | |
| 135 | return { | |
| 136 | now: now.toISOString(), | |
| 137 | watchingSince: first, | |
| 138 | watchingDays: first === null ? 0 : Math.floor((Date.parse(dayOf(now)) - Date.parse(first)) / DAY) + 1, | |
| 139 | lines, | |
| 140 | neverUsed, | |
| 141 | }; | |
| 142 | } |
src/core/hits.ts added +187
| @@ -0,0 +1,187 @@ | ||
| 1 | /** | |
| 2 | * Hits — the forge watching its own use (#1136). Every request it answers | |
| 3 | * is counted once, after the answer: by route *pattern* (`/:owner/:name`, | |
| 4 | * never the path asked), method, status, the viewer's role, the surface it | |
| 5 | * came through and the flag variant it ran under. Nothing else is kept: no | |
| 6 | * path, id, query string or body, and no person — only counts by role. | |
| 7 | * | |
| 8 | * Named `hits` because `core/usage.ts` is the crew's spend ledger. | |
| 9 | * | |
| 10 | * Units, stated once: a count is one answered request (or one MCP tool | |
| 11 | * call, counted on its own under surface `tool`); an hour and a day are UTC. | |
| 12 | * Writes are batched in memory and flushed in one transaction through one | |
| 13 | * prepared statement, on a short timer, past a size, and before any read. | |
| 14 | * `hit_hour` holds today; `rollUp` folds each whole past day into `hit_day` | |
| 15 | * and drops its hour rows, so a day is in exactly one table and a read | |
| 16 | * (`hitRows`) is the two joined without double counting. | |
| 17 | * | |
| 18 | * Pure data: no authz. Who may read it is the caller's to decide. | |
| 19 | */ | |
| 20 | ||
| 21 | import type { Database } from "bun:sqlite"; | |
| 22 | ||
| 23 | export type Role = "stranger" | "reader" | "writer" | "owner" | "admin" | "agent"; | |
| 24 | export const ROLES: readonly Role[] = [ | |
| 25 | "stranger", | |
| 26 | "reader", | |
| 27 | "writer", | |
| 28 | "owner", | |
| 29 | "admin", | |
| 30 | "agent", | |
| 31 | ]; | |
| 32 | ||
| 33 | export type Surface = "page" | "fragment" | "api" | "mcp" | "tool" | "ssh"; | |
| 34 | export const SURFACES: readonly Surface[] = [ | |
| 35 | "page", | |
| 36 | "fragment", | |
| 37 | "api", | |
| 38 | "mcp", | |
| 39 | "tool", | |
| 40 | "ssh", | |
| 41 | ]; | |
| 42 | ||
| 43 | export interface Hit { | |
| 44 | /** The registered pattern, or `tool:<name>`; never a raw path. */ | |
| 45 | readonly route: string; | |
| 46 | readonly method: string; | |
| 47 | readonly status: number; | |
| 48 | readonly role: Role; | |
| 49 | readonly surface: Surface; | |
| 50 | /** The flag variant the request ran under; empty when none. */ | |
| 51 | readonly variant?: string | undefined; | |
| 52 | /** For tests; the clock otherwise. */ | |
| 53 | readonly at?: Date | undefined; | |
| 54 | } | |
| 55 | ||
| 56 | const FLUSH_AT = 200; | |
| 57 | const FLUSH_MS = 5_000; | |
| 58 | /** Longest piece of a key we keep: a pattern is short, a bug is not. */ | |
| 59 | const KEY_MAX = 200; | |
| 60 | ||
| 61 | interface Buffer { | |
| 62 | rows: Map<string, { hour: string; hit: Omit<Required<Hit>, "at" | "variant"> & { variant: string }; n: number }>; | |
| 63 | timer: ReturnType<typeof setTimeout> | undefined; | |
| 64 | } | |
| 65 | const buffers = new WeakMap<Database, Buffer>(); | |
| 66 | ||
| 67 | const clip = (s: string): string => s.slice(0, KEY_MAX); | |
| 68 | const hourOf = (d: Date): string => d.toISOString().slice(0, 13); | |
| 69 | export const dayOf = (d: Date): string => d.toISOString().slice(0, 10); | |
| 70 | ||
| 71 | /** Count one answered request. Cheap: a map increment; the disk waits. */ | |
| 72 | export function recordHit(db: Database, hit: Hit): void { | |
| 73 | let buf = buffers.get(db); | |
| 74 | if (buf === undefined) { | |
| 75 | buf = { rows: new Map(), timer: undefined }; | |
| 76 | buffers.set(db, buf); | |
| 77 | } | |
| 78 | const hour = hourOf(hit.at ?? new Date()); | |
| 79 | const full = { | |
| 80 | route: clip(hit.route), | |
| 81 | method: clip(hit.method), | |
| 82 | status: Number.isInteger(hit.status) ? hit.status : 0, | |
| 83 | role: hit.role, | |
| 84 | surface: hit.surface, | |
| 85 | variant: clip(hit.variant ?? ""), | |
| 86 | }; | |
| 87 | const key = [hour, full.route, full.method, full.status, full.role, full.surface, full.variant].join("\u0000"); | |
| 88 | const row = buf.rows.get(key); | |
| 89 | if (row !== undefined) row.n += 1; | |
| 90 | else buf.rows.set(key, { hour, hit: full, n: 1 }); | |
| 91 | if (buf.rows.size >= FLUSH_AT) { | |
| 92 | flushHits(db); | |
| 93 | return; | |
| 94 | } | |
| 95 | if (buf.timer === undefined) { | |
| 96 | buf.timer = setTimeout(() => { | |
| 97 | try { | |
| 98 | flushHits(db); | |
| 99 | } catch { | |
| 100 | // The database closed under us (shutdown, a test): the count is lost, the forge is not. | |
| 101 | } | |
| 102 | }, FLUSH_MS); | |
| 103 | buf.timer.unref?.(); | |
| 104 | } | |
| 105 | } | |
| 106 | ||
| 107 | /** Write what is waiting, in one transaction. */ | |
| 108 | export function flushHits(db: Database): void { | |
| 109 | const buf = buffers.get(db); | |
| 110 | if (buf === undefined) return; | |
| 111 | if (buf.timer !== undefined) clearTimeout(buf.timer); | |
| 112 | buf.timer = undefined; | |
| 113 | if (buf.rows.size === 0) return; | |
| 114 | const rows = [...buf.rows.values()]; | |
| 115 | buf.rows.clear(); | |
| 116 | const put = db.prepare( | |
| 117 | `INSERT INTO hit_hour (hour, route, method, status, role, surface, variant, n) | |
| 118 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) | |
| 119 | ON CONFLICT (hour, route, method, status, role, surface, variant) | |
| 120 | DO UPDATE SET n = n + excluded.n`, | |
| 121 | ); | |
| 122 | db.transaction(() => { | |
| 123 | for (const { hour, hit, n } of rows) | |
| 124 | put.run(hour, hit.route, hit.method, hit.status, hit.role, hit.surface, hit.variant, n); | |
| 125 | })(); | |
| 126 | } | |
| 127 | ||
| 128 | /** | |
| 129 | * Fold every whole day before `now`'s into `hit_day` and drop its hour | |
| 130 | * rows. Idempotent; the day's totals are the sum of its hours, exactly. | |
| 131 | */ | |
| 132 | export function rollUp(db: Database, now: Date = new Date()): number { | |
| 133 | flushHits(db); | |
| 134 | const today = dayOf(now); | |
| 135 | return db.transaction(() => { | |
| 136 | db.run( | |
| 137 | `INSERT INTO hit_day (day, route, method, status, role, surface, variant, n, last) | |
| 138 | SELECT substr(hour, 1, 10), route, method, status, role, surface, variant, SUM(n), MAX(hour) | |
| 139 | FROM hit_hour WHERE substr(hour, 1, 10) < ?1 | |
| 140 | GROUP BY substr(hour, 1, 10), route, method, status, role, surface, variant | |
| 141 | ON CONFLICT (day, route, method, status, role, surface, variant) | |
| 142 | DO UPDATE SET n = n + excluded.n, last = MAX(last, excluded.last)`, | |
| 143 | [today], | |
| 144 | ); | |
| 145 | // The map reads 90 days; a month of slack, then the day goes. | |
| 146 | db.run(`DELETE FROM hit_day WHERE day < ?1`, [dayOf(new Date(now.getTime() - 120 * 86_400_000))]); | |
| 147 | return db.run(`DELETE FROM hit_hour WHERE substr(hour, 1, 10) < ?1`, [today]).changes; | |
| 148 | })(); | |
| 149 | } | |
| 150 | ||
| 151 | export interface HitRow { | |
| 152 | readonly day: string; | |
| 153 | readonly route: string; | |
| 154 | readonly method: string; | |
| 155 | readonly status: number; | |
| 156 | readonly role: Role; | |
| 157 | readonly surface: Surface; | |
| 158 | readonly variant: string; | |
| 159 | readonly n: number; | |
| 160 | /** The last hour it happened in (`YYYY-MM-DDTHH`). */ | |
| 161 | readonly last: string; | |
| 162 | } | |
| 163 | ||
| 164 | /** Every counted row since `sinceDay` (inclusive), days and today's hours as one. */ | |
| 165 | export function hitRows(db: Database, sinceDay: string): HitRow[] { | |
| 166 | flushHits(db); | |
| 167 | return db | |
| 168 | .query<HitRow, [string]>( | |
| 169 | `SELECT day, route, method, status, role, surface, variant, n, last FROM hit_day WHERE day >= ?1 | |
| 170 | UNION ALL | |
| 171 | SELECT substr(hour, 1, 10), route, method, status, role, surface, variant, n, hour | |
| 172 | FROM hit_hour WHERE substr(hour, 1, 10) >= ?1`, | |
| 173 | ) | |
| 174 | .all(sinceDay); | |
| 175 | } | |
| 176 | ||
| 177 | /** The first day anything was counted, or undefined: how long the forge has watched. */ | |
| 178 | export function watchingSince(db: Database): string | undefined { | |
| 179 | flushHits(db); | |
| 180 | const row = db | |
| 181 | .query<{ d: string | null }, []>( | |
| 182 | `SELECT MIN(d) AS d FROM (SELECT MIN(day) AS d FROM hit_day | |
| 183 | UNION ALL SELECT MIN(substr(hour, 1, 10)) FROM hit_hour)`, | |
| 184 | ) | |
| 185 | .get(); | |
| 186 | return row?.d ?? undefined; | |
| 187 | } |
src/core/reserved.ts +1
| @@ -92,6 +92,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 92 | 92 | "sw.js", |
| 93 | 93 | "tell", |
| 94 | 94 | "theme", |
| 95 | "usage", | |
| 95 | 96 | "verify", |
| 96 | 97 | "www", |
| 97 | 98 | "asked", |
src/core/schema.ts +29
| @@ -1595,6 +1595,35 @@ export const migrations: readonly string[] = [ | ||
| 1595 | 1595 | PRIMARY KEY (repo_id, parent_id, issue_id) |
| 1596 | 1596 | ); |
| 1597 | 1597 | `, |
| 1598 | // 76 — what the forge's own use looks like (#1136). Counts only: a route | |
| 1599 | // pattern, method, status, the viewer's role, the surface and the flag | |
| 1600 | // variant, per hour; whole past days fold into \`hit_day\` and their hour | |
| 1601 | // rows go. No path, no id, no query, no body, no person. | |
| 1602 | ` | |
| 1603 | CREATE TABLE hit_hour ( | |
| 1604 | hour TEXT NOT NULL, | |
| 1605 | route TEXT NOT NULL, | |
| 1606 | method TEXT NOT NULL, | |
| 1607 | status INTEGER NOT NULL, | |
| 1608 | role TEXT NOT NULL, | |
| 1609 | surface TEXT NOT NULL, | |
| 1610 | variant TEXT NOT NULL DEFAULT '', | |
| 1611 | n INTEGER NOT NULL, | |
| 1612 | PRIMARY KEY (hour, route, method, status, role, surface, variant) | |
| 1613 | ) WITHOUT ROWID; | |
| 1614 | CREATE TABLE hit_day ( | |
| 1615 | day TEXT NOT NULL, | |
| 1616 | route TEXT NOT NULL, | |
| 1617 | method TEXT NOT NULL, | |
| 1618 | status INTEGER NOT NULL, | |
| 1619 | role TEXT NOT NULL, | |
| 1620 | surface TEXT NOT NULL, | |
| 1621 | variant TEXT NOT NULL DEFAULT '', | |
| 1622 | n INTEGER NOT NULL, | |
| 1623 | last TEXT NOT NULL, | |
| 1624 | PRIMARY KEY (day, route, method, status, role, surface, variant) | |
| 1625 | ) WITHOUT ROWID; | |
| 1626 | `, | |
| 1598 | 1627 | ]; |
| 1599 | 1628 | |
| 1600 | 1629 | /** |
src/crew/sentinel.ts added +56
| @@ -0,0 +1,56 @@ | ||
| 1 | /** | |
| 2 | * The sentinel's eye on use (#1136): a route, page, setting or tool that no | |
| 3 | * person has used for 30 days becomes one proposal to drop it, with the | |
| 4 | * numbers quoted. The forge only proposes — the owner nods or keeps it at | |
| 5 | * the plan-approval door — and a drop is a pull that removes the code and | |
| 6 | * says what it removed. | |
| 7 | * | |
| 8 | * It never proposes before the forge has watched for the full 30 days: a | |
| 9 | * count that began yesterday says nothing about a month. Agents' own calls | |
| 10 | * do not keep a thing alive; a person's do. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | import { usageMap, type Known } from "../actions/hits.ts"; | |
| 15 | ||
| 16 | export const QUIET_DAYS = 30; | |
| 17 | ||
| 18 | export interface DropProposal { | |
| 19 | /** Stable, so asking twice is one proposal: `drop:<surface> <METHOD> <route>`. */ | |
| 20 | readonly key: string; | |
| 21 | readonly title: string; | |
| 22 | readonly body: string; | |
| 23 | } | |
| 24 | ||
| 25 | export function dropProposals( | |
| 26 | db: Database, | |
| 27 | known: readonly Known[], | |
| 28 | now: Date = new Date(), | |
| 29 | ): DropProposal[] { | |
| 30 | const map = usageMap(db, known, now); | |
| 31 | if (map.watchingDays < QUIET_DAYS) return []; | |
| 32 | const used = new Map(map.lines.map((l) => [`${l.surface} ${l.method} ${l.route}`, l])); | |
| 33 | const out: DropProposal[] = []; | |
| 34 | for (const k of known) { | |
| 35 | const line = used.get(`${k.surface} ${k.method} ${k.route}`); | |
| 36 | // Used by a person in the window under any surface keeps it. | |
| 37 | const peopleAnywhere = map.lines.some( | |
| 38 | (l) => l.method === k.method && l.route === k.route && l.people30 > 0, | |
| 39 | ); | |
| 40 | if (peopleAnywhere) continue; | |
| 41 | const uses30 = line?.uses30 ?? 0; | |
| 42 | const uses90 = line?.uses90 ?? 0; | |
| 43 | const agents = uses30 - (line?.people30 ?? 0); | |
| 44 | out.push({ | |
| 45 | key: `drop:${k.surface} ${k.method} ${k.route}`, | |
| 46 | title: `Drop ${k.method} ${k.route}? Nobody has used it in ${QUIET_DAYS} days`, | |
| 47 | body: [ | |
| 48 | `${k.surface} ${k.method} ${k.route}: 0 uses by people in the last ${QUIET_DAYS} days`, | |
| 49 | `(${agents} by agents; ${uses90} in 90 days; last used ${line?.last ?? "never"}).`, | |
| 50 | `The forge has counted use since ${map.watchingSince} (${map.watchingDays} days).`, | |
| 51 | `Keep it, or approve a pull that removes the code and says what it removed.`, | |
| 52 | ].join(" "), | |
| 53 | }); | |
| 54 | } | |
| 55 | return out; | |
| 56 | } |
src/http/api.ts +10
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | |
| 11 | 11 | import { askCheck } from "../checks/again.ts"; |
| 12 | 12 | import { mayView, mayViewId, sealedScope } from "../core/sealed.ts"; |
| 13 | import { usageMap } from "../actions/hits.ts"; | |
| 14 | import { knownFor } from "./count.ts"; | |
| 13 | 15 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 14 | 16 | import { |
| 15 | 17 | accountSignIns, |
| @@ -1263,6 +1265,14 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1263 | 1265 | ); |
| 1264 | 1266 | }); |
| 1265 | 1267 | |
| 1268 | // How the forge is used (`actions/hits.ts`): counts by route pattern, an | |
| 1269 | // admin's to read; anyone else is told the door is not there. | |
| 1270 | router.add("GET", "/api/v1/usage", (ctx) => { | |
| 1271 | const denied = accountAdmin(ctx, "ro"); | |
| 1272 | if (denied) return denied; | |
| 1273 | return json(usageMap(ctx.app.db, knownFor(ctx.app))); | |
| 1274 | }); | |
| 1275 | ||
| 1266 | 1276 | router.add("GET", "/api/v1/admin/accounts", (ctx) => { |
| 1267 | 1277 | const denied = accountAdmin(ctx, "ro"); |
| 1268 | 1278 | if (denied) return denied; |
src/http/count.ts added +91
| @@ -0,0 +1,91 @@ | ||
| 1 | /** | |
| 2 | * Counting the forge's own use (`core/hits.ts`) from where a request is | |
| 3 | * answered: which pattern it matched, who asked, through which door. Only | |
| 4 | * these — the pattern, the method, the status, the role, the surface — ever | |
| 5 | * leave this file; the path and query are read for shape and dropped. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Known } from "../actions/hits.ts"; | |
| 9 | import { recordHit, type Role, type Surface } from "../core/hits.ts"; | |
| 10 | import type { Auth } from "./context.ts"; | |
| 11 | import type { Router } from "./router.ts"; | |
| 12 | import type { App } from "../app.ts"; | |
| 13 | ||
| 14 | /** What `answerGet` learns on the way, handed back for the one count. */ | |
| 15 | export interface Note { | |
| 16 | pattern?: string | undefined; | |
| 17 | params?: Record<string, string> | undefined; | |
| 18 | auth?: Auth | undefined; | |
| 19 | } | |
| 20 | ||
| 21 | /** Static bytes are not "use" of a feature; counting them would drown it. */ | |
| 22 | const UNCOUNTED = /^\/(assets\/|icons\/|sw\.js$|healthz$)/; | |
| 23 | ||
| 24 | export function roleOf(auth: Auth | undefined, params: Record<string, string> | undefined): Role { | |
| 25 | const user = auth?.user; | |
| 26 | if (user === undefined) return "stranger"; | |
| 27 | if (user.kind === "agent") return "agent"; | |
| 28 | if (user.isAdmin) return "admin"; | |
| 29 | const owner = params?.["owner"] ?? params?.["username"]; | |
| 30 | if (owner !== undefined && owner.toLowerCase() === user.username.toLowerCase()) return "owner"; | |
| 31 | return auth?.via === "token" && auth.scope === "ro" ? "reader" : "writer"; | |
| 32 | } | |
| 33 | ||
| 34 | export function surfaceOf(url: URL): Surface { | |
| 35 | if (url.pathname === "/mcp") return "mcp"; | |
| 36 | if (url.pathname === "/api" || url.pathname.startsWith("/api/")) return "api"; | |
| 37 | return url.searchParams.get("fragment") === "1" ? "fragment" : "page"; | |
| 38 | } | |
| 39 | ||
| 40 | /** Count one answered request. Never throws: counting must not break answering. */ | |
| 41 | export function countAnswer(app: App, request: Request, url: URL, status: number, note: Note): void { | |
| 42 | if (UNCOUNTED.test(url.pathname)) return; | |
| 43 | try { | |
| 44 | recordHit(app.db, { | |
| 45 | route: note.pattern ?? "(no route)", | |
| 46 | method: request.method === "HEAD" ? "GET" : request.method, | |
| 47 | status, | |
| 48 | role: roleOf(note.auth, note.params), | |
| 49 | surface: surfaceOf(url), | |
| 50 | }); | |
| 51 | } catch { | |
| 52 | // A full disk or closed database loses a count, not an answer. | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 56 | /** Everything registered that a person or agent could use. */ | |
| 57 | export function knownUse( | |
| 58 | router: Router<unknown>, | |
| 59 | apiRouter: Router<unknown>, | |
| 60 | tools: readonly string[], | |
| 61 | ): Known[] { | |
| 62 | const out: Known[] = []; | |
| 63 | for (const { method, pattern } of router.patterns()) | |
| 64 | if (!UNCOUNTED.test(pattern)) out.push({ route: pattern, method, surface: pattern === "/mcp" ? "mcp" : "page" }); | |
| 65 | for (const { method, pattern } of apiRouter.patterns()) | |
| 66 | out.push({ route: pattern, method, surface: "api" }); | |
| 67 | for (const t of tools) out.push({ route: `tool:${t}`, method: "CALL", surface: "tool" }); | |
| 68 | return out; | |
| 69 | } | |
| 70 | ||
| 71 | const registered = new WeakMap<App, Known[]>(); | |
| 72 | /** The routers are built once per app; what they hold is what `/usage` measures against. */ | |
| 73 | export function rememberKnown(app: App, known: Known[]): void { | |
| 74 | registered.set(app, known); | |
| 75 | } | |
| 76 | export const knownFor = (app: App): readonly Known[] => registered.get(app) ?? []; | |
| 77 | ||
| 78 | /** One MCP tool call, counted on its own beside the `/mcp` request that carried it. */ | |
| 79 | export function countTool(ctx: { app: App; auth: Auth; params: Record<string, string> }, name: string, ok: boolean): void { | |
| 80 | try { | |
| 81 | recordHit(ctx.app.db, { | |
| 82 | route: `tool:${name}`, | |
| 83 | method: "CALL", | |
| 84 | status: ok ? 200 : 422, | |
| 85 | role: roleOf(ctx.auth, ctx.params), | |
| 86 | surface: "tool", | |
| 87 | }); | |
| 88 | } catch { | |
| 89 | // As above: a lost count, not a lost answer. | |
| 90 | } | |
| 91 | } |
src/http/mcp.ts +33 −4
| @@ -17,6 +17,8 @@ | ||
| 17 | 17 | * no page. `ro` tokens read; `rw` tokens act. |
| 18 | 18 | */ |
| 19 | 19 | |
| 20 | import { usageMap, TABS } from "../actions/hits.ts"; | |
| 21 | import { countTool, knownFor } from "./count.ts"; | |
| 20 | 22 | import { mayView, mayViewId, sealedScope } from "../core/sealed.ts"; |
| 21 | 23 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 22 | 24 | import { relationOf, takeUpdates } from "../actions/forks.ts"; |
| @@ -220,6 +222,9 @@ function issueArg(ctx: Ctx, repo: Repo, args: Args, key: string) { | ||
| 220 | 222 | |
| 221 | 223 | const isAnswer = (v: Repo | Answer): v is Answer => "ok" in v; |
| 222 | 224 | |
| 225 | /** Every tool's name, for the usage map to say which have never been called. */ | |
| 226 | export const toolNames = (): string[] => TOOLS.map((t) => t.name); | |
| 227 | ||
| 223 | 228 | const TOOLS: readonly Tool[] = [ |
| 224 | 229 | { |
| 225 | 230 | name: "apps", |
| @@ -822,6 +827,29 @@ const TOOLS: readonly Tool[] = [ | ||
| 822 | 827 | }); |
| 823 | 828 | }, |
| 824 | 829 | }, |
| 830 | { | |
| 831 | name: "use_map", | |
| 832 | description: | |
| 833 | "What the forge's own use looks like (an admin's view): every route and tool ranked by answered requests over 7, 30 and 90 days, when last used, by which roles, rising or falling, and `neverUsed` — what exists and nobody has used in 90 days. Ask it \"what does nobody use\". Counts only; no paths, ids or people. `watchingDays` says how long the forge has been counting.", | |
| 834 | inputSchema: { | |
| 835 | type: "object", | |
| 836 | properties: { | |
| 837 | tab: { type: "string", enum: [...TABS], description: "Only this kind of thing." }, | |
| 838 | }, | |
| 839 | }, | |
| 840 | writes: false, | |
| 841 | run(ctx, user, args) { | |
| 842 | if (!user.isAdmin) | |
| 843 | return bad("forbidden", "only an admin of this forge sees how it is used"); | |
| 844 | const map = usageMap(ctx.app.db, knownFor(ctx.app)); | |
| 845 | const tab = str(args["tab"]); | |
| 846 | return good( | |
| 847 | tab === "" | |
| 848 | ? map | |
| 849 | : { ...map, lines: map.lines.filter((l) => l.tab === tab) }, | |
| 850 | ); | |
| 851 | }, | |
| 852 | }, | |
| 825 | 853 | { |
| 826 | 854 | name: "forges", |
| 827 | 855 | description: |
| @@ -1794,8 +1822,9 @@ function rpcOne( | ||
| 1794 | 1822 | ], |
| 1795 | 1823 | isError: true, |
| 1796 | 1824 | }); |
| 1797 | return Promise.resolve(tool.run(ctx, user, args)).then((answer) => | |
| 1798 | reply( | |
| 1825 | return Promise.resolve(tool.run(ctx, user, args)).then((answer) => { | |
| 1826 | countTool(ctx, tool.name, answer.ok); | |
| 1827 | return reply( | |
| 1799 | 1828 | answer.ok |
| 1800 | 1829 | ? { |
| 1801 | 1830 | content: [{ type: "text", text: JSON.stringify(answer.value) }], |
| @@ -1806,8 +1835,8 @@ function rpcOne( | ||
| 1806 | 1835 | ], |
| 1807 | 1836 | isError: true, |
| 1808 | 1837 | }, |
| 1809 | ), | |
| 1810 | ); | |
| 1838 | ); | |
| 1839 | }); | |
| 1811 | 1840 | } |
| 1812 | 1841 | default: |
| 1813 | 1842 | return refuse(-32601, `no method ${String(m["method"])}`); |
src/http/router.ts +11 −3
| @@ -16,11 +16,14 @@ type Segment = | ||
| 16 | 16 | |
| 17 | 17 | export interface Match<H> { |
| 18 | 18 | handler: H; |
| 19 | /** The route as registered (`/:owner/:name`), never the path asked. */ | |
| 20 | pattern: string; | |
| 19 | 21 | params: Params; |
| 20 | 22 | } |
| 21 | 23 | |
| 22 | 24 | interface CompiledRoute<H> { |
| 23 | 25 | method: string; |
| 26 | pattern: string; | |
| 24 | 27 | segments: Segment[]; |
| 25 | 28 | handler: H; |
| 26 | 29 | } |
| @@ -65,8 +68,13 @@ export class Router<H> { | ||
| 65 | 68 | return [...heads].sort(); |
| 66 | 69 | } |
| 67 | 70 | |
| 71 | /** Every registered route, for naming what exists beside what was used. */ | |
| 72 | patterns(): { method: string; pattern: string }[] { | |
| 73 | return this.routes.map((r) => ({ method: r.method, pattern: r.pattern })); | |
| 74 | } | |
| 75 | ||
| 68 | 76 | add(method: string, pattern: string, handler: H): this { |
| 69 | this.routes.push({ method, segments: compile(pattern), handler }); | |
| 77 | this.routes.push({ method, pattern, segments: compile(pattern), handler }); | |
| 70 | 78 | return this; |
| 71 | 79 | } |
| 72 | 80 | |
| @@ -80,7 +88,7 @@ export class Router<H> { | ||
| 80 | 88 | const decoded = parts.slice(i).map(decodeSegment); |
| 81 | 89 | if (decoded.some((d) => d === undefined)) continue outer; |
| 82 | 90 | params[segment.name] = decoded.join("/"); |
| 83 | return { handler: route.handler, params }; | |
| 91 | return { handler: route.handler, pattern: route.pattern, params }; | |
| 84 | 92 | } |
| 85 | 93 | const part = parts[i]; |
| 86 | 94 | if (part === undefined) continue outer; |
| @@ -99,7 +107,7 @@ export class Router<H> { | ||
| 99 | 107 | } |
| 100 | 108 | } |
| 101 | 109 | if (parts.length !== route.segments.length) continue; |
| 102 | return { handler: route.handler, params }; | |
| 110 | return { handler: route.handler, pattern: route.pattern, params }; | |
| 103 | 111 | } |
| 104 | 112 | return undefined; |
| 105 | 113 | } |
src/http/server.ts +30 −2
| @@ -238,6 +238,7 @@ import { | ||
| 238 | 238 | runsList, |
| 239 | 239 | } from "../web/pages/runs.ts"; |
| 240 | 240 | import { lookImage } from "../web/pages/looks.ts"; |
| 241 | import { usagePage } from "../web/pages/usage.ts"; | |
| 241 | 242 | import { bigRedirect, boardPage } from "../web/pages/board.ts"; |
| 242 | 243 | import { returnsPage } from "../web/pages/returns.ts"; |
| 243 | 244 | import { |
| @@ -366,7 +367,7 @@ import { notFoundPage } from "../web/chrome.ts"; | ||
| 366 | 367 | import { targetForShortCode } from "../origins/oauth.ts"; |
| 367 | 368 | import { apiRoutes } from "./api.ts"; |
| 368 | 369 | import { feedRoutes } from "./feed.ts"; |
| 369 | import { mcpRoutes } from "./mcp.ts"; | |
| 370 | import { mcpRoutes, toolNames } from "./mcp.ts"; | |
| 370 | 371 | import { oauthRoutes } from "./oauth.ts"; |
| 371 | 372 | import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts"; |
| 372 | 373 | import { parseCidrs } from "../kernel/cidr.ts"; |
| @@ -404,6 +405,8 @@ import { | ||
| 404 | 405 | } from "../core/idempotency.ts"; |
| 405 | 406 | import { sseStream, viewerStream } from "./sse.ts"; |
| 406 | 407 | import { Router } from "./router.ts"; |
| 408 | import { rollUp } from "../core/hits.ts"; | |
| 409 | import { countAnswer, knownUse, rememberKnown, type Note } from "./count.ts"; | |
| 407 | 410 | import { getUserById } from "../core/users.ts"; |
| 408 | 411 | import { appsRuntime } from "../apps/runtime.ts"; |
| 409 | 412 | import { |
| @@ -567,6 +570,8 @@ export function buildRouter(): Router<Handler> { | ||
| 567 | 570 | router.add("POST", "/logout", logoutSubmit); |
| 568 | 571 | router.add("POST", "/theme", themeSubmit); |
| 569 | 572 | // The board: a live wall of the crews at work, for a second monitor. |
| 573 | // How the forge is used, counted by route pattern (core/hits.ts); an admin's. | |
| 574 | router.add("GET", "/usage", usagePage); | |
| 570 | 575 | router.add("GET", "/board", boardPage); |
| 571 | 576 | // The board's tokens line, opened: what the spend bought (core/returns.ts). |
| 572 | 577 | router.add("GET", "/board/returns", returnsPage); |
| @@ -1614,6 +1619,7 @@ export function forgeHttp(app: App): ForgeHttp { | ||
| 1614 | 1619 | const router = buildRouter(); |
| 1615 | 1620 | const apiRouter = buildApiRouter(); |
| 1616 | 1621 | const limiter = new RateLimiter(); |
| 1622 | rememberKnown(app, knownUse(router, apiRouter, toolNames())); | |
| 1617 | 1623 | return { |
| 1618 | 1624 | handle: (request) => answer(app, router, apiRouter, limiter, request), |
| 1619 | 1625 | // App lifetime is owned by spawn/host.ts (closeHostedChildren). |
| @@ -1628,6 +1634,18 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1628 | 1634 | // One limiter per listener: its state is a minute of timestamps, and two |
| 1629 | 1635 | // forges in one process (every test file) must not share a budget. |
| 1630 | 1636 | const limiter = new RateLimiter(); |
| 1637 | rememberKnown(app, knownUse(router, apiRouter, toolNames())); | |
| 1638 | // Whole past days fold into their daily rollup: once now, then hourly. | |
| 1639 | const fold = (): void => { | |
| 1640 | try { | |
| 1641 | rollUp(app.db); | |
| 1642 | } catch (error) { | |
| 1643 | app.log.warn("the usage rollup failed", { error: String(error) }); | |
| 1644 | } | |
| 1645 | }; | |
| 1646 | fold(); | |
| 1647 | const folding = setInterval(fold, 3_600_000); | |
| 1648 | folding.unref?.(); | |
| 1631 | 1649 | // Hosted children answered in-process: one ForgeHttp per child dataDir. |
| 1632 | 1650 | const childHttps = new Map<string, ForgeHttp>(); |
| 1633 | 1651 | // An account suspended or removed ends what it has open on this |
| @@ -1776,6 +1794,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1776 | 1794 | for (const http of childHttps.values()) http.close(); |
| 1777 | 1795 | childHttps.clear(); |
| 1778 | 1796 | closeHostedChildren(app); |
| 1797 | clearInterval(folding); | |
| 1779 | 1798 | web.stop(true); |
| 1780 | 1799 | internal.stop(true); |
| 1781 | 1800 | // Our socket goes with us; a corpse is only ever an unclean exit's. |
| @@ -1802,7 +1821,12 @@ async function answer( | ||
| 1802 | 1821 | limiter: RateLimiter, |
| 1803 | 1822 | request: Request, |
| 1804 | 1823 | ): Promise<Response> { |
| 1805 | const response = await answerGet(app, router, apiRouter, limiter, request); | |
| 1824 | const note: Note = {}; | |
| 1825 | const response = await answerGet(app, router, apiRouter, limiter, request, note); | |
| 1826 | // Counted once, after it is answered, from the one place every answer passes. | |
| 1827 | const url = publicUrl(request, app.config.url); | |
| 1828 | if (url.pathname !== "/healthz") | |
| 1829 | countAnswer(app, request, url, response.status, note); | |
| 1806 | 1830 | return request.method === "HEAD" |
| 1807 | 1831 | ? new Response(null, { status: response.status, headers: response.headers }) |
| 1808 | 1832 | : response; |
| @@ -1814,6 +1838,7 @@ async function answerGet( | ||
| 1814 | 1838 | apiRouter: Router<Handler>, |
| 1815 | 1839 | limiter: RateLimiter, |
| 1816 | 1840 | request: Request, |
| 1841 | note: Note, | |
| 1817 | 1842 | ): Promise<Response> { |
| 1818 | 1843 | const url = publicUrl(request, app.config.url); |
| 1819 | 1844 | if (url.pathname === "/healthz") |
| @@ -1852,7 +1877,10 @@ async function answerGet( | ||
| 1852 | 1877 | } |
| 1853 | 1878 | return noRoute(request.method, url.pathname); |
| 1854 | 1879 | } |
| 1880 | note.pattern = matched.pattern; | |
| 1881 | note.params = matched.params; | |
| 1855 | 1882 | const auth = await resolveAuth(app, request); |
| 1883 | note.auth = auth; | |
| 1856 | 1884 | // From here a body's cap depends on who is asking (`http/limits.ts`), and |
| 1857 | 1885 | // a stream this request opens is the account's, to end with it. |
| 1858 | 1886 | if (auth.user !== undefined) { |
src/web/pages/usage.ts added +105
| @@ -0,0 +1,105 @@ | ||
| 1 | /** | |
| 2 | * /usage — how the forge is used (`actions/hits.ts`): routes ranked by use | |
| 3 | * over 7, 30 and 90 days with last use, who, and trend; pages, fragments, | |
| 4 | * tools, settings and the API each as a tab; and the list of what exists | |
| 5 | * and nobody has used. For the forge's admin; anyone else gets the 404. | |
| 6 | * Counts only: no path, id or person appears here. | |
| 7 | */ | |
| 8 | ||
| 9 | import { TABS, usageMap, type Tab, type UsageLine } from "../../actions/hits.ts"; | |
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { knownFor } from "../../http/count.ts"; | |
| 12 | import { notFoundPage, signInFirst } from "../chrome.ts"; | |
| 13 | import { html, type Html } from "../html.ts"; | |
| 14 | import { page } from "../layout.ts"; | |
| 15 | import { empty, tabs, time } from "../ui.ts"; | |
| 16 | ||
| 17 | const TAB_WORDS: Readonly<Record<Tab, string>> = { | |
| 18 | pages: "Pages", | |
| 19 | fragments: "Fragments", | |
| 20 | tools: "Tools", | |
| 21 | settings: "Settings", | |
| 22 | api: "API", | |
| 23 | }; | |
| 24 | const TREND_WORDS = { new: "new ↑", up: "up ↑", down: "down ↓", flat: "flat →" } as const; | |
| 25 | ||
| 26 | function row(l: UsageLine): Html { | |
| 27 | const roles = Object.entries(l.byRole) | |
| 28 | .map(([r, n]) => `${r} ${n}`) | |
| 29 | .join(", "); | |
| 30 | return html`<tr> | |
| 31 | <th scope="row"><code>${l.method} ${l.route}</code></th> | |
| 32 | <td class="num">${String(l.uses7)}</td> | |
| 33 | <td class="num">${String(l.uses30)}</td> | |
| 34 | <td class="num">${String(l.uses90)}</td> | |
| 35 | <td>${l.last === null ? "—" : time(l.last)}</td> | |
| 36 | <td>${roles}</td> | |
| 37 | <td>${TREND_WORDS[l.trend]}</td> | |
| 38 | </tr>`; | |
| 39 | } | |
| 40 | ||
| 41 | export function usagePage(ctx: Ctx): Response { | |
| 42 | const user = ctx.auth.user; | |
| 43 | if (!user) return signInFirst(ctx); | |
| 44 | if (!user.isAdmin) return notFoundPage(ctx); | |
| 45 | const asked = ctx.url.searchParams.get("tab") ?? "pages"; | |
| 46 | const tab: Tab | "never" = asked === "never" ? "never" : (TABS.find((t) => t === asked) ?? "pages"); | |
| 47 | const map = usageMap(ctx.app.db, knownFor(ctx.app)); | |
| 48 | const lines = tab === "never" ? [] : map.lines.filter((l) => l.tab === tab); | |
| 49 | const items = [ | |
| 50 | ...TABS.map((t) => ({ | |
| 51 | label: TAB_WORDS[t], | |
| 52 | href: `/usage?tab=${t}`, | |
| 53 | current: tab === t, | |
| 54 | })), | |
| 55 | { | |
| 56 | label: "Never used", | |
| 57 | href: "/usage?tab=never", | |
| 58 | count: map.neverUsed.length, | |
| 59 | current: tab === "never", | |
| 60 | }, | |
| 61 | ]; | |
| 62 | const body = | |
| 63 | tab === "never" | |
| 64 | ? map.neverUsed.length === 0 | |
| 65 | ? empty({ title: "Everything registered has been used.", note: "In the last 90 days." }) | |
| 66 | : html`<table class="table"> | |
| 67 | <thead> | |
| 68 | <tr><th scope="col">Registered, not used in 90 days</th><th scope="col">Door</th></tr> | |
| 69 | </thead> | |
| 70 | <tbody> | |
| 71 | ${map.neverUsed.map( | |
| 72 | (k) => html`<tr> | |
| 73 | <th scope="row"><code>${k.method} ${k.route}</code></th> | |
| 74 | <td>${k.surface}</td> | |
| 75 | </tr>`, | |
| 76 | )} | |
| 77 | </tbody> | |
| 78 | </table>` | |
| 79 | : lines.length === 0 | |
| 80 | ? empty({ title: "Nothing counted here yet.", note: "Use is counted as requests are answered." }) | |
| 81 | : html`<table class="table" data-tab="${tab}"> | |
| 82 | <thead> | |
| 83 | <tr> | |
| 84 | <th scope="col">Route</th> | |
| 85 | <th scope="col" class="num">7 d</th> | |
| 86 | <th scope="col" class="num">30 d</th> | |
| 87 | <th scope="col" class="num">90 d</th> | |
| 88 | <th scope="col">Last used</th> | |
| 89 | <th scope="col">By (90 d)</th> | |
| 90 | <th scope="col">Trend</th> | |
| 91 | </tr> | |
| 92 | </thead> | |
| 93 | <tbody>${lines.map(row)}</tbody> | |
| 94 | </table>`; | |
| 95 | return page({ | |
| 96 | ctx, | |
| 97 | title: "Usage", | |
| 98 | body: html`<div class="page-head"><h1>Usage</h1></div> | |
| 99 | <p class="muted"> | |
| 100 | Counted since ${map.watchingSince ?? "the first request"} | |
| 101 | (${String(map.watchingDays)} days). Route patterns only: no path, id or person is kept. | |
| 102 | </p> | |
| 103 | ${tabs(items, "Usage")} ${body}`, | |
| 104 | }); | |
| 105 | } |
test/hits.test.ts added +202
| @@ -0,0 +1,202 @@ | ||
| 1 | /** | |
| 2 | * The forge watching its own use (#1136): each answered request counted | |
| 3 | * once by route pattern and role, no id or query in the table, the rollup | |
| 4 | * equal to the raw rows, the map ranked, and the sentinel's drop proposal | |
| 5 | * quoting the right numbers. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { usageMap, type Known } from "../src/actions/hits.ts"; | |
| 13 | import { signUp } from "../src/actions/users.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { flushHits, hitRows, recordHit, rollUp } from "../src/core/hits.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { dropProposals } from "../src/crew/sentinel.ts"; | |
| 18 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 19 | ||
| 20 | const DAY = 86_400_000; | |
| 21 | ||
| 22 | describe("counting answered requests", () => { | |
| 23 | let dataDir: string; | |
| 24 | let app: App; | |
| 25 | let http: ForgeHttp; | |
| 26 | let adminToken: string; | |
| 27 | let plainToken: string; | |
| 28 | ||
| 29 | const get = (path: string, token?: string, init: RequestInit = {}) => | |
| 30 | http.handle(new Request(`https://forge.example${path}`, { | |
| 31 | ...init, | |
| 32 | headers: { | |
| 33 | ...(token ? { authorization: `Bearer ${token}` } : {}), | |
| 34 | ...(init.headers as Record<string, string> | undefined), | |
| 35 | }, | |
| 36 | })); | |
| 37 | const table = () => { | |
| 38 | flushHits(app.db); | |
| 39 | return app.db | |
| 40 | .query<{ route: string; method: string; status: number; role: string; surface: string; n: number }, []>( | |
| 41 | "SELECT route, method, status, role, surface, n FROM hit_hour", | |
| 42 | ) | |
| 43 | .all(); | |
| 44 | }; | |
| 45 | ||
| 46 | beforeAll(async () => { | |
| 47 | dataDir = await mkdtemp(join(tmpdir(), "forge-hits-")); | |
| 48 | app = createApp({ dataDir, port: 0, url: "https://forge.example" }); | |
| 49 | http = forgeHttp(app); | |
| 50 | const admin = await signUp(app, { username: "olive", email: "[email protected]", password: "owner-passphrase" }); | |
| 51 | if (!admin.ok) throw new Error(admin.error); | |
| 52 | adminToken = createToken(app.db, admin.value.id, "t", "admin").token; | |
| 53 | const plain = await signUp(app, { username: "pat", email: "[email protected]", password: "plain-passphrase" }); | |
| 54 | if (!plain.ok) throw new Error(plain.error); | |
| 55 | plainToken = createToken(app.db, plain.value.id, "t", "ro").token; | |
| 56 | }); | |
| 57 | afterAll(async () => { | |
| 58 | http.close(); | |
| 59 | app.close(); | |
| 60 | await rm(dataDir, { recursive: true, force: true }); | |
| 61 | }); | |
| 62 | ||
| 63 | test("a request is counted once, by pattern and role, never by path, id or query", async () => { | |
| 64 | await get("/olive/secret-repo-name?token=hunter2&q=private"); | |
| 65 | await get("/olive/secret-repo-name?fragment=1", adminToken); | |
| 66 | await get("/api/v1/usage", plainToken); | |
| 67 | const rows = table(); | |
| 68 | const dump = JSON.stringify(rows); | |
| 69 | expect(dump).not.toContain("secret-repo-name"); | |
| 70 | expect(dump).not.toContain("hunter2"); | |
| 71 | const stranger = rows.find((r) => r.route === "/:owner/:name" && r.role === "stranger"); | |
| 72 | expect(stranger).toMatchObject({ method: "GET", surface: "page", n: 1 }); | |
| 73 | const admin = rows.find((r) => r.route === "/:owner/:name" && r.role === "admin"); | |
| 74 | expect(admin).toMatchObject({ surface: "fragment", n: 1 }); | |
| 75 | // The non-admin's refused ask is still an answer, counted with its status. | |
| 76 | expect(rows.find((r) => r.route === "/api/v1/usage")).toMatchObject({ | |
| 77 | role: "reader", | |
| 78 | surface: "api", | |
| 79 | status: 404, | |
| 80 | n: 1, | |
| 81 | }); | |
| 82 | }); | |
| 83 | ||
| 84 | test("health checks and static bytes are not use", async () => { | |
| 85 | const before = table().length; | |
| 86 | await get("/healthz"); | |
| 87 | await get("/assets/nothing.css"); | |
| 88 | expect(table().length).toBe(before); | |
| 89 | }); | |
| 90 | ||
| 91 | test("/usage and the API are an admin's; the MCP tool counts itself", async () => { | |
| 92 | expect((await get("/usage")).status).not.toBe(200); | |
| 93 | const asPat = await get("/usage", plainToken); | |
| 94 | expect(asPat.status).toBe(404); | |
| 95 | const api = await get("/api/v1/usage", adminToken); | |
| 96 | expect(api.status).toBe(200); | |
| 97 | const map = (await api.json()) as { lines: { route: string }[]; neverUsed: unknown[] }; | |
| 98 | expect(map.lines.some((l) => l.route === "/:owner/:name")).toBe(true); | |
| 99 | expect(map.neverUsed.length).toBeGreaterThan(0); | |
| 100 | ||
| 101 | const call = (token: string, name: string) => | |
| 102 | get("/mcp", token, { | |
| 103 | method: "POST", | |
| 104 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream" }, | |
| 105 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: {} } }), | |
| 106 | }); | |
| 107 | const res = await call(adminToken, "use_map"); | |
| 108 | expect(res.status).toBe(200); | |
| 109 | expect(await res.text()).toContain("neverUsed"); | |
| 110 | const tool = table().find((r) => r.route === "tool:use_map"); | |
| 111 | expect(tool).toMatchObject({ surface: "tool", role: "admin", n: 1 }); | |
| 112 | const denied = await (await call(plainToken, "use_map")).text(); | |
| 113 | expect(denied).toContain("forbidden"); | |
| 114 | }); | |
| 115 | }); | |
| 116 | ||
| 117 | describe("the rollup and the map", () => { | |
| 118 | let dataDir: string; | |
| 119 | let app: App; | |
| 120 | const now = new Date("2026-10-13T12:00:00Z"); | |
| 121 | const at = (daysAgo: number, hour = 9) => | |
| 122 | new Date(Date.UTC(2026, 9, 13 - daysAgo, hour)); | |
| 123 | const hit = (route: string, role: "admin" | "agent" | "stranger", daysAgo: number, n = 1) => { | |
| 124 | for (let i = 0; i < n; i++) | |
| 125 | recordHit(app.db, { route, method: "GET", status: 200, role, surface: "page", at: at(daysAgo) }); | |
| 126 | }; | |
| 127 | ||
| 128 | beforeAll(async () => { | |
| 129 | dataDir = await mkdtemp(join(tmpdir(), "forge-hits-map-")); | |
| 130 | app = createApp({ dataDir, port: 0, url: "https://forge.example" }); | |
| 131 | }); | |
| 132 | afterAll(async () => { | |
| 133 | app.close(); | |
| 134 | await rm(dataDir, { recursive: true, force: true }); | |
| 135 | }); | |
| 136 | ||
| 137 | test("the rollup equals the raw rows, and a day lives in one table", () => { | |
| 138 | hit("/a", "stranger", 3, 4); | |
| 139 | hit("/a", "admin", 3, 2); | |
| 140 | hit("/b", "admin", 0, 5); | |
| 141 | flushHits(app.db); | |
| 142 | const sum = (rows: { n: number }[]) => rows.reduce((t, r) => t + r.n, 0); | |
| 143 | const rawBefore = sum(hitRows(app.db, "2026-01-01")); | |
| 144 | expect(rawBefore).toBe(11); | |
| 145 | expect(rollUp(app.db, now)).toBeGreaterThan(0); | |
| 146 | expect(sum(hitRows(app.db, "2026-01-01"))).toBe(rawBefore); | |
| 147 | const day = app.db | |
| 148 | .query<{ n: number }, []>("SELECT SUM(n) AS n FROM hit_day WHERE route = '/a'") | |
| 149 | .get()!.n; | |
| 150 | expect(day).toBe(6); | |
| 151 | // Today stays in hours; rolling up twice changes nothing. | |
| 152 | expect(app.db.query<{ c: number }, []>("SELECT COUNT(*) AS c FROM hit_hour").get()!.c).toBe(1); | |
| 153 | rollUp(app.db, now); | |
| 154 | expect(sum(hitRows(app.db, "2026-01-01"))).toBe(rawBefore); | |
| 155 | }); | |
| 156 | ||
| 157 | test("routes rank by 7-day use, then 30, then 90; unused ones are listed", () => { | |
| 158 | hit("/c", "admin", 20, 9); // 30 d only | |
| 159 | hit("/d", "admin", 60, 20); // 90 d only | |
| 160 | flushHits(app.db); | |
| 161 | const known: Known[] = ["/a", "/b", "/c", "/d", "/e"].map((route) => ({ route, method: "GET", surface: "page" })); | |
| 162 | const map = usageMap(app.db, known, now); | |
| 163 | expect(map.lines.map((l) => l.route)).toEqual(["/a", "/b", "/c", "/d"]); | |
| 164 | const a = map.lines.find((l) => l.route === "/a")!; | |
| 165 | expect([a.uses7, a.uses30, a.uses90]).toEqual([6, 6, 6]); | |
| 166 | expect(a.byRole).toEqual({ stranger: 4, admin: 2 }); | |
| 167 | expect(map.lines.find((l) => l.route === "/b")!.last).toBe("2026-10-13T09:00:00Z"); | |
| 168 | expect(map.neverUsed.map((k) => k.route)).toEqual(["/e"]); | |
| 169 | expect(map.watchingSince).toBe("2026-08-14"); | |
| 170 | }); | |
| 171 | ||
| 172 | test("the sentinel proposes a drop for what no person used in 30 days, quoting the numbers", () => { | |
| 173 | hit("/agents-only", "agent", 2, 3); | |
| 174 | flushHits(app.db); | |
| 175 | const known: Known[] = ["/a", "/c", "/d", "/e", "/agents-only"].map((route) => ({ route, method: "GET", surface: "page" })); | |
| 176 | const proposals = dropProposals(app.db, known, now); | |
| 177 | // /a and /c were used by people inside the window; /d and /e were not. | |
| 178 | expect(proposals.map((p) => p.key).sort()).toEqual([ | |
| 179 | "drop:page GET /agents-only", | |
| 180 | "drop:page GET /d", | |
| 181 | "drop:page GET /e", | |
| 182 | ]); | |
| 183 | const agents = proposals.find((p) => p.key.endsWith("/agents-only"))!; | |
| 184 | expect(agents.body).toContain("0 uses by people in the last 30 days"); | |
| 185 | expect(agents.body).toContain("3 by agents"); | |
| 186 | const d = proposals.find((p) => p.key.endsWith("GET /d"))!; | |
| 187 | expect(d.body).toContain("20 in 90 days"); | |
| 188 | expect(d.body).toContain("since 2026-08-14"); | |
| 189 | }); | |
| 190 | ||
| 191 | test("it proposes nothing until the forge has watched for 30 days", async () => { | |
| 192 | const dir = await mkdtemp(join(tmpdir(), "forge-hits-young-")); | |
| 193 | const young = createApp({ dataDir: dir, port: 0, url: "https://forge.example" }); | |
| 194 | try { | |
| 195 | recordHit(young.db, { route: "/a", method: "GET", status: 200, role: "admin", surface: "page", at: new Date(now.getTime() - 3 * DAY) }); | |
| 196 | expect(dropProposals(young.db, [{ route: "/z", method: "GET", surface: "page" }], now)).toEqual([]); | |
| 197 | } finally { | |
| 198 | young.close(); | |
| 199 | await rm(dir, { recursive: true, force: true }); | |
| 200 | } | |
| 201 | }); | |
| 202 | }); |
test/mcp.test.ts +1
| @@ -171,6 +171,7 @@ describe("the forge over MCP", () => { | ||
| 171 | 171 | "probe", |
| 172 | 172 | "following", |
| 173 | 173 | "spawn", |
| 174 | "use_map", | |
| 174 | 175 | "forges", |
| 175 | 176 | "claim_link", |
| 176 | 177 | "take_updates", |
new above
offline