Public: anyone can read this; the crew can change it.

Fleet query language and the fleet table: repos, runs, issues, apps, crew behind one visible query in the URL #464

Closed opened this in answer to
Closed without merging

torque/forge:torque/446-fleet-query-language-and-the-fleet-table → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +1423 −8
CLAUDE.md +4
@@ -138,6 +138,10 @@ src/
138138 page says it in), asks, previews, shelf (an app as one
139139 row, for any page that lists apps), home, app, change, tell,
140140 run, lists, actions, style (the page sheet, assembled)
141 fleet/ the fleet table (docs/FLEET.md): query (the query line's
142 grammar, syntax only), table (each kind as one SELECT over the
143 existing tables, visibility-filtered; terms become bound WHERE
144 clauses; rows, matching count, facet counts)
141145 feed/ a viewer's feed (docs/FEED.md): items (candidates read through
142146 the access every page uses), affinity (decayed counts), rank,
143147 feed (filter, page, cursor)
README.md +4
@@ -319,6 +319,10 @@ mechanical rather than advisory.
319319 `docs/PLANNING.md` is how issues depend on issues: the edge, the map, and
320320 what "ready now" means to a person and to the crew.
321321
322 `docs/FLEET.md` is the fleet table at `/fleet`: repos, runs, issues, apps
323 and crew behind one query line that lives in the URL, its grammar, its
324 units, and the same rows as CSV and JSON.
325
322326 `docs/STUDIO.md` is the front door from the top of this page in full: the five
323327 words and where each is decided, the box, the three lists, a tell, a run
324328 and a change each on its own page, and the board.
docs/FLEET.md +71 −7
@@ -1,4 +1,68 @@
1 # Fleet operations
1 # The fleet
2
3 `/fleet` is one table for everything the viewer can read across the forge —
4 **repos, runs, issues, apps, crew** — driven by one visible query line. The
5 query is the page's only state and it is the URL (`/fleet?q=…`), so a link
6 to a view is the view. It is the first half of fleet operations (#445):
7 select, preview and act will work on the rows this query names.
8
9 ## The query line
10
11 ```
12 run state:queued,running repo:!forge cost>0.5 sort:-cost
13 ```
14
15 | Write | Means |
16 | ---------------- | ---------------------------------------------------------------- |
17 | `run` | the kind, as the first word: repo, run, issue, app, crew (plurals too); absent is `repo` |
18 | `field:value` | equal; text ignores case, `*` is any run of characters, `none` is empty |
19 | `field:a,b` | any of |
20 | `field:!value` | not; `-field:value` says the same |
21 | `field>n` | also `>=`, `<`, `<=`, and `field:>n` — numbers, dollars, dates |
22 | `repo:name` | scoping, by `name` or `owner/name`; `repo:!name` leaves it out |
23 | `sort:field` | ascending; `sort:-field` descending |
24 | `word` | a bare word searches the kind's name or title; `-word` excludes |
25 | `"two words"` | quotes keep spaces and commas |
26
27 A date is `2026-10-01`, an instant, or an age: `7d` is seven days before
28 now (m, h, d, w), so `created>7d` is "created in the last week". Money is
29 US dollars as stored on each run. On a repo, `spent` is agent spend since
30 00:00 UTC — the number its `ceiling` is held against — and `spent_total`
31 is all of it. The page lists every kind's fields under the table.
32
33 A line is at most 500 characters and 24 terms. An unknown field, a value
34 outside an enum, or a comparison on text is an error that names the term
35 and what is allowed — never a silently empty table.
36
37 ## How it runs
38
39 `src/fleet/query.ts` is syntax only. `src/fleet/table.ts` holds each kind
40 as one SELECT over the tables that already exist (`repo`, `run`, `issue`,
41 `app`, `repo_crew`), restricted by `REPO_VISIBLE` — the predicate every
42 list uses — so a row from a repository the viewer cannot read is never
43 selected. A term reaches SQL only after its field is found in the kind's
44 list; every value is a bound parameter. A page is three statements however
45 many rows: the rows (at most 1,000), the facet counts (whose sum is the
46 matching count), and the per-kind totals for the kind links.
47
48 ## The same rows elsewhere
49
50 - `GET /fleet.csv?q=…` — the rows as a file; a cell starting `= + - @` is
51 prefixed with `'` so a spreadsheet keeps it text.
52 - `GET /api/v1/fleet?q=…` — `{ query, kind, matching, limit, sort, columns,
53 counts, items }`; a bad line is `422 { error: "bad_query", message, at }`.
54
55 Both need a signed-in viewer, like the page.
56
57 ## Not yet
58
59 Acting on rows is the API below (fleet operations), which still reads its
60 own smaller grammar (`src/fleet/selection.ts`); selecting rows in this table
61 and acting from the page, the chart beside the table, and the MCP tool are
62 the next issues under #445. Paging past the
63 first 1,000 rows is not built: narrow the query instead.
64
65 ## Fleet operations
266
367 One action over every row a query selects, with the plan shown before
468 anything changes and a receipt kept after.
@@ -16,7 +80,7 @@ curl -sX POST $FORGE/api/v1/fleet/ops -H "authorization: Bearer $ADMIN" \
1680 curl -sX POST $FORGE/api/v1/fleet/ops/$ID/undo -H "authorization: Bearer $ADMIN"
1781 ```
1882
19 ## The query
83 ### The query
2084
2185 A kind — `repo`, `run` or `issue` — then `field:value` terms, all of which
2286 must hold. `!` before a value negates it. `repo:owner/name` (or a bare name)
@@ -29,10 +93,10 @@ works on every kind.
2993 | issue | `repo` `owner` `name` `id` `number` `state` `assignee` (`none`) `label` |
3094
3195 Only rows you can read are selected. More than 500 rows is refused
32 (`too_many`), never cut. This grammar is `src/fleet/selection.ts`; the fleet
33 table (#446) grows it.
96 (`too_many`), never cut. This grammar is `src/fleet/selection.ts`, a subset
97 of the table's query line above; the two are not yet one parser.
3498
35 ## The actions
99 ### The actions
36100
37101 `action` is `{ "verb": …, "value": … }`, or a bare verb when it takes no value.
38102
@@ -49,7 +113,7 @@ table (#446) grows it.
49113 | issue | `label` | a label's name (added) | yes |
50114 | issue | `link` | the number they wait for | yes |
51115
52 ## Who may
116 ### Who may
53117
54118 Every row needs admin of its repository; the rest come back `refused` with
55119 the reason, in the plan and in the receipt. A dry run takes a read token;
@@ -57,7 +121,7 @@ applying and undoing take an admin one. An agent may preview but never
57121 apply. Each row is written through the same action a person's click calls,
58122 so it is authorized again and leaves its own event.
59123
60 ## The receipt
124 ### The receipt
61125
62126 Applying records a `fleet_operation` row (who, the query, the action) and
63127 one row per selected target: the value before, the value asked for, and
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet.test.ts test/fleet-ops.test.ts",
1010 "timeout": 1800
1111 }
1212 }
src/fleet/query.ts added +263
@@ -0,0 +1,263 @@
1 /**
2 * The fleet query: one line of text that says which rows a table shows.
3 *
4 * run state:queued,running repo:!forge cost>0.5 sort:-cost
5 *
6 * Grammar, a term at a time, separated by spaces:
7 *
8 * kind the first word, when it names a kind: repo, run, issue,
9 * app, crew (plurals too). Absent, the kind is `repo`.
10 * field:value equal (text compares without case). `a,b` is any of.
11 * field:!value not equal; `-field:value` says the same.
12 * field>n also >=, <, <=, and `field:>n` — numbers and dates.
13 * repo:x scoping: `x` is a name or `owner/name`; `repo:!x` leaves
14 * it out. Every kind has it.
15 * sort:field ascending; `sort:-field` descending.
16 * word a bare word searches the kind's name or title; `-word`
17 * excludes it. "Quoted text" keeps its spaces.
18 *
19 * This module is syntax only: it knows nothing about which fields a kind
20 * has. `fleet/table.ts` checks names and values against the kind and turns
21 * the terms into SQL, so a field that does not exist is an error there, with
22 * the list of fields that do.
23 */
24
25 import { err, ok, type Result } from "../kernel/result.ts";
26
27 export const KINDS = ["repo", "run", "issue", "app", "crew"] as const;
28 export type Kind = (typeof KINDS)[number];
29
30 export type Op = "=" | "!=" | ">" | ">=" | "<" | "<=";
31
32 /** `field op values` — several values only for = and != (any of / none of). */
33 export interface Term {
34 readonly field: string;
35 readonly op: Op;
36 readonly values: readonly string[];
37 }
38
39 export interface Sort {
40 readonly field: string;
41 readonly dir: "asc" | "desc";
42 }
43
44 export interface Query {
45 readonly kind: Kind;
46 readonly terms: readonly Term[];
47 /** Bare words: each must appear in the kind's name or title. */
48 readonly words: readonly string[];
49 /** Bare `-words`: none may appear. */
50 readonly notWords: readonly string[];
51 readonly sort: Sort | null;
52 }
53
54 export interface QueryError {
55 readonly code: "too_long" | "control" | "syntax" | "too_many";
56 readonly message: string;
57 /** The term that failed, as typed. */
58 readonly at: string;
59 }
60
61 /** A query line longer than this is not one a person typed. */
62 export const MAX_QUERY = 500;
63 export const MAX_TERMS = 24;
64
65 const KIND_WORDS: Record<string, Kind> = {
66 repo: "repo",
67 repos: "repo",
68 run: "run",
69 runs: "run",
70 issue: "issue",
71 issues: "issue",
72 app: "app",
73 apps: "app",
74 crew: "crew",
75 crews: "crew",
76 };
77
78 /** `kind` for a word, or undefined — exported for the page's kind links. */
79 export const kindOf = (word: string): Kind | undefined =>
80 Object.hasOwn(KIND_WORDS, word.toLowerCase())
81 ? KIND_WORDS[word.toLowerCase()]
82 : undefined;
83
84 const FIELD = /^[a-z][a-z0-9_]*$/;
85 // field, then an operator, then the rest. `:` may be followed by its own
86 // comparison (`spent:>50`) or a bang (`state:!ok`).
87 const TERM = /^([A-Za-z][A-Za-z0-9_]*)(:|>=|<=|!=|>|<|=)(.*)$/s;
88
89 /** Split on spaces outside double quotes; quotes are kept for `value`. */
90 function tokens(input: string): Result<string[], QueryError> {
91 const out: string[] = [];
92 let current = "";
93 let quoted = false;
94 for (const ch of input) {
95 if (ch === '"') quoted = !quoted;
96 if (!quoted && /\s/.test(ch)) {
97 if (current !== "") out.push(current);
98 current = "";
99 continue;
100 }
101 current += ch;
102 }
103 if (quoted)
104 return err({
105 code: "syntax",
106 message: "A quote is opened and never closed.",
107 at: current,
108 });
109 if (current !== "") out.push(current);
110 return ok(out);
111 }
112
113 /** `a,"b c",d` → ["a", "b c", "d"]; commas inside quotes stay. */
114 function splitValues(raw: string): string[] {
115 const out: string[] = [];
116 let current = "";
117 let quoted = false;
118 for (const ch of raw) {
119 if (ch === '"') {
120 quoted = !quoted;
121 continue;
122 }
123 if (ch === "," && !quoted) {
124 out.push(current);
125 current = "";
126 continue;
127 }
128 current += ch;
129 }
130 out.push(current);
131 return out;
132 }
133
134 const unquote = (s: string): string =>
135 s.length >= 2 && s.startsWith('"') && s.endsWith('"') ? s.slice(1, -1) : s;
136
137 export function parseQuery(input: string): Result<Query, QueryError> {
138 if (input.length > MAX_QUERY)
139 return err({
140 code: "too_long",
141 message: `A query is at most ${MAX_QUERY} characters.`,
142 at: input.slice(0, 40),
143 });
144 // eslint-disable-next-line no-control-regex
145 if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(input))
146 return err({
147 code: "control",
148 message: "A query cannot carry control characters.",
149 at: "",
150 });
151 const split = tokens(input);
152 if (!split.ok) return split;
153 const list = split.value;
154 if (list.length > MAX_TERMS)
155 return err({
156 code: "too_many",
157 message: `A query has at most ${MAX_TERMS} terms.`,
158 at: list[MAX_TERMS] ?? "",
159 });
160
161 let kind: Kind = "repo";
162 const terms: Term[] = [];
163 const words: string[] = [];
164 const notWords: string[] = [];
165 let sort: Sort | null = null;
166
167 for (const [i, token] of list.entries()) {
168 const first = i === 0 ? kindOf(token) : undefined;
169 if (first !== undefined) {
170 kind = first;
171 continue;
172 }
173 let negate = false;
174 let body = token;
175 if (body.length > 1 && (body.startsWith("-") || body.startsWith("!"))) {
176 negate = true;
177 body = body.slice(1);
178 }
179 const m = body.startsWith('"') ? null : TERM.exec(body);
180 if (m === null) {
181 const word = unquote(body);
182 if (word === "") continue;
183 (negate ? notWords : words).push(word);
184 continue;
185 }
186 const field = m[1]!.toLowerCase();
187 let op = m[2]! as Op | ":";
188 let rest = m[3]!;
189 if (!FIELD.test(field))
190 return err({ code: "syntax", message: "Not a field name.", at: token });
191
192 if (field === "sort") {
193 if (op !== ":" || negate)
194 return err({
195 code: "syntax",
196 message: "Sort is written sort:field or sort:-field.",
197 at: token,
198 });
199 const desc = rest.startsWith("-");
200 const by = (desc ? rest.slice(1) : rest).toLowerCase();
201 if (!FIELD.test(by))
202 return err({
203 code: "syntax",
204 message: "Sort names one field: sort:field or sort:-field.",
205 at: token,
206 });
207 sort = { field: by, dir: desc ? "desc" : "asc" };
208 continue;
209 }
210
211 if (op === ":") {
212 const cmp = /^(>=|<=|>|<|!)/.exec(rest);
213 if (cmp !== null) {
214 op = cmp[1] === "!" ? "!=" : (cmp[1] as Op);
215 rest = rest.slice(cmp[1]!.length);
216 } else op = "=";
217 }
218 let resolved: Op = op;
219 if (negate) {
220 const flip: Record<Op, Op> = {
221 "=": "!=",
222 "!=": "=",
223 ">": "<=",
224 ">=": "<",
225 "<": ">=",
226 "<=": ">",
227 };
228 resolved = flip[resolved];
229 }
230 const values =
231 resolved === "=" || resolved === "!="
232 ? splitValues(rest)
233 : [unquote(rest)];
234 if (values.some((v) => v === ""))
235 return err({
236 code: "syntax",
237 message: `${field} needs a value after the operator.`,
238 at: token,
239 });
240 terms.push({ field, op: resolved, values });
241 }
242 return ok({ kind, terms, words, notWords, sort });
243 }
244
245 /**
246 * The query line with its sort replaced: what a column header links to.
247 * Works on the text, not the parsed form, so everything else the person
248 * typed stays exactly as they typed it.
249 */
250 export function withSort(line: string, field: string, dir: "asc" | "desc"): string {
251 const kept = line
252 .trim()
253 .split(/\s+/)
254 .filter((t) => t !== "" && !/^sort:/i.test(t));
255 kept.push(`sort:${dir === "desc" ? "-" : ""}${field}`);
256 return kept.join(" ");
257 }
258
259 /** The query line with one more term: what a count links to. */
260 export function withTerm(line: string, term: string): string {
261 const trimmed = line.trim();
262 return trimmed === "" ? term : `${trimmed} ${term}`;
263 }
src/fleet/table.ts added +502
@@ -0,0 +1,502 @@
1 /**
2 * The fleet table: a parsed query run against the tables that already hold
3 * repos, runs, issues, apps and crew — one SELECT per kind, filtered and
4 * sorted in SQLite, never in JavaScript.
5 *
6 * Each kind is a `from`: a SELECT over the existing tables that yields one
7 * row per thing with plainly named columns, restricted to the repositories
8 * the viewer may read (`REPO_VISIBLE`, the same predicate every list uses).
9 * The query's terms become a WHERE over that row, every value a bound
10 * parameter — a field name only reaches the SQL after it is found in the
11 * kind's own list, so nothing the person typed is ever spliced in.
12 *
13 * Units, stated once: money is US dollars as stored (`run.cost_usd`);
14 * `spent` on a repo is agent spend since 00:00 UTC — the number its
15 * `ceiling` is held against (`crew/autonomy.ts`) — and `spent_total` is all
16 * of it. A relative date names a moment: `7d` is seven days before now, so
17 * `created>7d` is "created in the last week". Units: m, h, d, w.
18 */
19
20 import type { Database } from "bun:sqlite";
21 import { REPO_VISIBLE } from "../core/visibility.ts";
22 import { startOfTodayUtc } from "../crew/autonomy.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24 import { KINDS, type Kind, type Op, type Query, type Term } from "./query.ts";
25
26 export type FieldType = "text" | "enum" | "number" | "usd" | "date";
27
28 export interface Field {
29 readonly name: string;
30 readonly type: FieldType;
31 /** One line, for the page's field list and an error that names it. */
32 readonly about: string;
33 readonly values?: readonly string[];
34 /** Shown as a column, in this order; false for filter-only fields. */
35 readonly column: boolean;
36 /**
37 * Equality as SQL over the row `t` with the value at `p` — for fields that
38 * are not one column (an issue's labels). Default: the column itself.
39 */
40 readonly match?: (p: string) => string;
41 }
42
43 export interface KindSpec {
44 readonly kind: Kind;
45 readonly plural: string;
46 /** SELECT … yielding the row; `?1` is the viewer, `?2` the start of today. */
47 readonly from: string;
48 readonly fields: readonly Field[];
49 /** Columns a bare word searches. */
50 readonly words: readonly string[];
51 /** The enum whose counts are shown above the table. */
52 readonly facet: string;
53 readonly sort: { readonly field: string; readonly dir: "asc" | "desc" };
54 }
55
56 const text = (name: string, about: string, column = true): Field => ({
57 name,
58 type: "text",
59 about,
60 column,
61 });
62 const choice = (name: string, values: readonly string[], about: string): Field => ({
63 name,
64 type: "enum",
65 values,
66 about,
67 column: true,
68 });
69 const num = (name: string, type: "number" | "usd" | "date", about: string): Field => ({
70 name,
71 type,
72 about,
73 column: true,
74 });
75
76 const REPO_FIELD = text("repo", "owner/name — or just name in a term");
77 // The row's repo as `owner/name`, and its plain name for `repo:name`.
78 const REPO_COLUMNS = `owner.username || '/' || repo.name AS repo,
79 repo.name AS repo_name, owner.username AS owner`;
80 const IN_VISIBLE = `JOIN user AS owner ON owner.id = repo.owner_id
81 WHERE ${REPO_VISIBLE}`;
82
83 export const SPECS: Record<Kind, KindSpec> = {
84 repo: {
85 kind: "repo",
86 plural: "repos",
87 from: `SELECT repo.id AS id, ${REPO_COLUMNS},
88 repo.visibility AS visibility, repo.autonomy AS autonomy,
89 repo.autonomy_slots AS slots, repo.autonomy_ceiling_usd AS ceiling,
90 COALESCE((SELECT SUM(r.cost_usd) FROM run AS r WHERE r.repo_id = repo.id
91 AND r.kind = 'agent' AND r.created_at >= ?2), 0) AS spent,
92 COALESCE((SELECT SUM(r.cost_usd) FROM run AS r WHERE r.repo_id = repo.id
93 AND r.kind = 'agent'), 0) AS spent_total,
94 (SELECT COUNT(*) FROM run AS r WHERE r.repo_id = repo.id
95 AND r.state IN ('queued','running')) AS active,
96 (SELECT COUNT(*) FROM issue AS i WHERE i.repo_id = repo.id
97 AND i.state = 'open' AND i.kind = 'issue') AS issues,
98 (SELECT COUNT(*) FROM issue AS i WHERE i.repo_id = repo.id
99 AND i.state = 'open' AND i.kind = 'pull') AS pulls,
100 repo.created_at AS created
101 FROM repo ${IN_VISIBLE}`,
102 fields: [
103 REPO_FIELD,
104 text("owner", "the user or org that owns it", false),
105 choice("visibility", ["public", "private"], "who may read it"),
106 choice("autonomy", ["off", "assisted", "autonomous"], "what the crew may start on its own"),
107 num("slots", "number", "agent runs at once"),
108 num("ceiling", "usd", "daily agent spend ceiling, USD"),
109 num("spent", "usd", "agent spend since 00:00 UTC, USD"),
110 num("spent_total", "usd", "all agent spend, USD"),
111 num("active", "number", "runs queued or running"),
112 num("issues", "number", "open issues"),
113 num("pulls", "number", "open pulls"),
114 num("created", "date", "when it was created"),
115 ],
116 words: ["repo"],
117 facet: "autonomy",
118 sort: { field: "repo", dir: "asc" },
119 },
120 run: {
121 kind: "run",
122 plural: "runs",
123 from: `SELECT run.id AS id, ${REPO_COLUMNS},
124 run.kind AS kind, run.state AS state, issue.number AS issue,
125 issue.title AS title, actor.username AS actor, run.reason AS reason,
126 run.cost_usd AS cost, run.turns AS turns, run.branch AS branch,
127 run.created_at AS created, run.finished_at AS finished
128 FROM run JOIN repo ON repo.id = run.repo_id
129 LEFT JOIN issue ON issue.id = run.issue_id
130 LEFT JOIN user AS actor ON actor.id = run.actor_id
131 ${IN_VISIBLE}`,
132 fields: [
133 REPO_FIELD,
134 choice("kind", ["deploy", "agent", "check"], "what the run does"),
135 choice("state", ["queued", "running", "ok", "failed", "cancelled"], "where it is"),
136 num("issue", "number", "the issue it works on"),
137 text("title", "that issue's title"),
138 text("actor", "who started it, or the agent that is it"),
139 text("reason", "why it was started"),
140 num("cost", "usd", "what it cost, USD"),
141 num("turns", "number", "model turns taken"),
142 text("branch", "the branch it ran on", false),
143 num("created", "date", "when it was queued"),
144 num("finished", "date", "when it ended"),
145 ],
146 words: ["title", "reason", "branch"],
147 facet: "state",
148 sort: { field: "created", dir: "desc" },
149 },
150 issue: {
151 kind: "issue",
152 plural: "issues",
153 from: `SELECT issue.id AS id, ${REPO_COLUMNS},
154 issue.number AS number, issue.kind AS kind, issue.title AS title,
155 issue.state AS state, author.username AS author,
156 assignee.username AS assignee,
157 (SELECT group_concat(l.name, ', ') FROM issue_label AS il
158 JOIN label AS l ON l.id = il.label_id
159 WHERE il.issue_id = issue.id) AS labels,
160 issue.created_at AS created, issue.updated_at AS updated
161 FROM issue JOIN repo ON repo.id = issue.repo_id
162 LEFT JOIN user AS author ON author.id = issue.author_id
163 LEFT JOIN user AS assignee ON assignee.id = issue.assignee_id
164 ${IN_VISIBLE}`,
165 fields: [
166 REPO_FIELD,
167 num("number", "number", "its number in the repo"),
168 choice("kind", ["issue", "pull"], "an issue or a pull"),
169 text("title", "its title"),
170 choice("state", ["open", "closed"], "open or closed"),
171 text("author", "who opened it"),
172 text("assignee", "who it is on; none for nobody"),
173 {
174 ...text("label", "a label it carries", false),
175 match: (p) => `EXISTS (SELECT 1 FROM issue_label AS il
176 JOIN label AS l ON l.id = il.label_id
177 WHERE il.issue_id = t.id AND l.name = ${p} COLLATE NOCASE)`,
178 },
179 text("labels", "every label, for reading"),
180 num("created", "date", "when it was opened"),
181 num("updated", "date", "when it last changed"),
182 ],
183 words: ["title"],
184 facet: "state",
185 sort: { field: "updated", dir: "desc" },
186 },
187 app: {
188 kind: "app",
189 plural: "apps",
190 from: `SELECT app.id AS id, ${REPO_COLUMNS},
191 app.slug AS slug, app.access AS access, app.preview_data AS preview,
192 repo.autonomy AS autonomy, app.created_at AS created
193 FROM app JOIN repo ON repo.id = app.repo_id
194 ${IN_VISIBLE}`,
195 fields: [
196 REPO_FIELD,
197 text("slug", "its address"),
198 choice("access", ["public", "private"], "who may open it"),
199 choice("preview", ["copy", "empty"], "what a preview's data starts as"),
200 choice("autonomy", ["off", "assisted", "autonomous"], "its repo's autonomy"),
201 num("created", "date", "when it was made an app"),
202 ],
203 words: ["slug", "repo"],
204 facet: "access",
205 sort: { field: "slug", dir: "asc" },
206 },
207 crew: {
208 kind: "crew",
209 plural: "crew",
210 from: `SELECT repo_crew.repo_id || ':' || repo_crew.user_id AS id,
211 ${REPO_COLUMNS}, member.username AS agent, repo_crew.role AS role,
212 COALESCE(agent.model, '') AS model,
213 COALESCE(agent.budget_usd, 0) AS budget,
214 (SELECT COUNT(*) FROM run AS r WHERE r.repo_id = repo.id
215 AND r.actor_id = member.id AND r.kind = 'agent') AS runs,
216 COALESCE((SELECT SUM(r.cost_usd) FROM run AS r WHERE r.repo_id = repo.id
217 AND r.actor_id = member.id AND r.kind = 'agent'), 0) AS spent,
218 repo_crew.added_at AS added
219 FROM repo_crew JOIN repo ON repo.id = repo_crew.repo_id
220 JOIN user AS member ON member.id = repo_crew.user_id
221 LEFT JOIN agent ON agent.user_id = member.id
222 ${IN_VISIBLE}`,
223 fields: [
224 REPO_FIELD,
225 text("agent", "the crew member"),
226 text("role", "what it does on this repo"),
227 text("model", "the model it runs"),
228 num("budget", "usd", "its budget per run, USD"),
229 num("runs", "number", "agent runs on this repo"),
230 num("spent", "usd", "what those runs cost, USD"),
231 num("added", "date", "when it joined the repo"),
232 ],
233 words: ["agent", "role"],
234 facet: "role",
235 sort: { field: "repo", dir: "asc" },
236 },
237 };
238
239 export interface FleetError {
240 readonly code: "unknown_field" | "bad_value" | "bad_operator";
241 readonly message: string;
242 readonly at: string;
243 }
244
245 export interface Compiled {
246 readonly spec: KindSpec;
247 /** `WHERE …` over `t`, without the keyword; "1" when nothing filters. */
248 readonly where: string;
249 readonly order: string;
250 readonly params: (string | number)[];
251 }
252
253 const NUMBER = /^\$?-?\d+(\.\d+)?$/;
254 const DAY = /^\d{4}-\d{2}-\d{2}$/;
255 const INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?Z?$/;
256 const RELATIVE = /^(\d{1,5})([mhdw])$/;
257 const UNIT_MS = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 };
258
259 const like = (s: string): string => s.replace(/[\\%_]/g, (c) => `\\${c}`);
260
261 /** A date value as the ISO instant it names, or undefined. */
262 export function instant(value: string, now: Date): string | undefined {
263 const rel = RELATIVE.exec(value);
264 if (rel !== null) {
265 const ms = Number(rel[1]) * UNIT_MS[rel[2] as keyof typeof UNIT_MS];
266 return new Date(now.getTime() - ms).toISOString();
267 }
268 if (DAY.test(value) || INSTANT.test(value)) {
269 const d = new Date(DAY.test(value) ? `${value}T00:00:00Z` : value);
270 return Number.isNaN(d.getTime()) ? undefined : d.toISOString();
271 }
272 return undefined;
273 }
274
275 /** The kind's fields by name, with a sorted list for error messages. */
276 const fieldOf = (spec: KindSpec, name: string): Field | undefined =>
277 spec.fields.find((f) => f.name === name);
278 const fieldNames = (spec: KindSpec): string =>
279 spec.fields.map((f) => f.name).join(", ");
280
281 export function compile(query: Query, now = new Date()): Result<Compiled, FleetError> {
282 const spec = SPECS[query.kind];
283 // ?1 viewer and ?2 start of today are bound by `runFleet`.
284 const params: (string | number)[] = [];
285 const bind = (v: string | number): string => {
286 params.push(v);
287 return `?${params.length + 2}`;
288 };
289 const where: string[] = [];
290
291 for (const term of query.terms) {
292 const r = termSql(spec, term, bind, now);
293 if (!r.ok) return r;
294 where.push(r.value);
295 }
296 for (const word of query.words)
297 where.push(wordSql(spec, word, bind));
298 for (const word of query.notWords)
299 where.push(`NOT ${wordSql(spec, word, bind)}`);
300
301 const sort = query.sort ?? spec.sort;
302 const by = fieldOf(spec, sort.field);
303 if (by === undefined || by.match !== undefined)
304 return err({
305 code: "unknown_field",
306 message: `${spec.plural} sort by one of: ${spec.fields
307 .filter((f) => f.match === undefined)
308 .map((f) => f.name)
309 .join(", ")}.`,
310 at: `sort:${sort.field}`,
311 });
312 const dir = sort.dir === "desc" ? "DESC" : "ASC";
313 // NULLs last either way, then id so a page is stable.
314 const order = `t.${by.name} IS NULL, t.${by.name}${
315 by.type === "text" ? " COLLATE NOCASE" : ""
316 } ${dir}, t.id ${dir}`;
317 return ok({
318 spec,
319 where: where.length === 0 ? "1" : where.join(" AND "),
320 order,
321 params,
322 });
323 }
324
325 function wordSql(spec: KindSpec, word: string, bind: (v: string) => string): string {
326 const p = bind(`%${like(word)}%`);
327 return `(${spec.words
328 .map((c) => `COALESCE(t.${c}, '') LIKE ${p} ESCAPE '\\'`)
329 .join(" OR ")})`;
330 }
331
332 function termSql(
333 spec: KindSpec,
334 term: Term,
335 bind: (v: string | number) => string,
336 now: Date,
337 ): Result<string, FleetError> {
338 const at = `${term.field}${term.op}${term.values.join(",")}`;
339 const field = fieldOf(spec, term.field);
340 if (field === undefined)
341 return err({
342 code: "unknown_field",
343 message: `${spec.plural} have no field "${term.field}". Fields: ${fieldNames(spec)}.`,
344 at,
345 });
346 const col = `t.${field.name}`;
347 const equality = term.op === "=" || term.op === "!=";
348 const ordered = field.type === "number" || field.type === "usd" || field.type === "date";
349 if (!equality && !ordered)
350 return err({
351 code: "bad_operator",
352 message: `${field.name} is compared with : only — it is ${field.type === "enum" ? "one of a list" : "text"}.`,
353 at,
354 });
355
356 const parts: string[] = [];
357 for (const raw of term.values) {
358 const r = valueSql(field, col, term.op, raw, bind, now);
359 if (!r.ok) return err({ ...r.error, at });
360 parts.push(r.value);
361 }
362 const any = parts.length === 1 ? parts[0]! : `(${parts.join(" OR ")})`;
363 // A NULL is "not equal" to everything: `assignee:!bob` keeps the unassigned.
364 return ok(term.op === "!=" ? `NOT COALESCE(${any}, 0)` : any);
365 }
366
367 function valueSql(
368 field: Field,
369 col: string,
370 op: Op,
371 raw: string,
372 bind: (v: string | number) => string,
373 now: Date,
374 ): Result<string, Omit<FleetError, "at">> {
375 const cmp = op === "!=" ? "=" : op;
376 switch (field.type) {
377 case "enum": {
378 const v = raw.toLowerCase();
379 if (!field.values!.includes(v))
380 return err({
381 code: "bad_value",
382 message: `${field.name} is one of: ${field.values!.join(", ")}.`,
383 });
384 return ok(`${col} = ${bind(v)}`);
385 }
386 case "text": {
387 if (field.match !== undefined) return ok(field.match(bind(raw)));
388 if (raw.toLowerCase() === "none") return ok(`COALESCE(${col}, '') = ''`);
389 if (field.name === "repo" && !raw.includes("/"))
390 return ok(`t.repo_name = ${bind(raw)} COLLATE NOCASE`);
391 if (raw.includes("*"))
392 return ok(
393 `${col} LIKE ${bind(like(raw).replace(/\*/g, "%"))} ESCAPE '\\'`,
394 );
395 return ok(`${col} = ${bind(raw)} COLLATE NOCASE`);
396 }
397 case "number":
398 case "usd": {
399 if (!NUMBER.test(raw))
400 return err({
401 code: "bad_value",
402 message: `${field.name} is a number${field.type === "usd" ? " of dollars" : ""}, like ${field.name}>5.`,
403 });
404 return ok(`${col} ${cmp} ${bind(Number(raw.replace("$", "")))}`);
405 }
406 case "date": {
407 if (cmp === "=" && DAY.test(raw))
408 return ok(`substr(${col}, 1, 10) = ${bind(raw)}`);
409 const at = instant(raw, now);
410 if (at === undefined || cmp === "=")
411 return err({
412 code: "bad_value",
413 message: `${field.name} is a date: 2026-10-01, or an age like 7d (m, h, d, w), compared with > or <.`,
414 });
415 return ok(`${col} ${cmp} ${bind(at)}`);
416 }
417 }
418 }
419
420 export type Cell = string | number | null;
421 export type Row = Record<string, Cell>;
422
423 export interface FleetResult {
424 readonly kind: Kind;
425 readonly columns: readonly Field[];
426 readonly rows: readonly Row[];
427 /** Rows matching the query, all of them — `rows` is at most `limit`. */
428 readonly matching: number;
429 /** The facet's counts within the matching rows, value → count. */
430 readonly facet: { readonly field: string; readonly counts: ReadonlyMap<string, number> };
431 readonly sort: { readonly field: string; readonly dir: "asc" | "desc" };
432 }
433
434 export const FLEET_LIMIT = 1000;
435
436 /**
437 * Only the repo kind reads ?2 (the start of today), and SQLite refuses a
438 * value bound past the last parameter a statement names. Naming it here
439 * keeps one binding order for every kind.
440 */
441 const TODAY_BOUND = "?2 IS NOT NULL";
442
443 /**
444 * Run a compiled query for a viewer: the rows, the count that matched, and
445 * the facet counts — three statements, however many rows there are.
446 */
447 export function runFleet(
448 db: Database,
449 viewerId: string,
450 query: Query,
451 options: { now?: Date; limit?: number } = {},
452 ): Result<FleetResult, FleetError> {
453 const now = options.now ?? new Date();
454 const compiled = compile(query, now);
455 if (!compiled.ok) return compiled;
456 const { spec, where, order, params } = compiled.value;
457 const limit = Math.max(1, Math.min(FLEET_LIMIT, options.limit ?? FLEET_LIMIT));
458 const base: (string | number)[] = [viewerId, startOfTodayUtc(now).toISOString(), ...params];
459 const inner = `(${spec.from}) AS t WHERE ${TODAY_BOUND} AND ${where}`;
460 const rows = db
461 .query<Row, (string | number)[]>(
462 `SELECT * FROM ${inner} ORDER BY ${order} LIMIT ?${base.length + 1}`,
463 )
464 .all(...base, limit);
465 const counted = db
466 .query<{ value: string | null; n: number }, (string | number)[]>(
467 `SELECT t.${spec.facet} AS value, COUNT(*) AS n FROM ${inner}
468 GROUP BY t.${spec.facet}`,
469 )
470 .all(...base);
471 const counts = new Map<string, number>();
472 let matching = 0;
473 for (const c of counted) {
474 matching += c.n;
475 counts.set(c.value ?? "", c.n);
476 }
477 const sort = query.sort ?? spec.sort;
478 return ok({
479 kind: spec.kind,
480 columns: spec.fields.filter((f) => f.column),
481 rows,
482 matching,
483 facet: { field: spec.facet, counts },
484 sort,
485 });
486 }
487
488 /** How many of each kind the viewer can see at all: the kind links' counts. */
489 export function fleetTotals(db: Database, viewerId: string, now = new Date()): Map<Kind, number> {
490 const out = new Map<Kind, number>();
491 const today = startOfTodayUtc(now).toISOString();
492 for (const kind of KINDS) {
493 // The spec's own FROM, so a total can never disagree with its table.
494 const n = db
495 .query<{ n: number }, [string, string]>(
496 `SELECT COUNT(*) AS n FROM (${SPECS[kind].from}) AS t WHERE ${TODAY_BOUND}`,
497 )
498 .get(viewerId, today)?.n;
499 out.set(kind, n ?? 0);
500 }
501 return out;
502 }
src/http/api.ts +9
@@ -200,6 +200,7 @@ import {
200200 import { dependenciesOf, repoGraph } from "../core/dependencies.ts";
201201 import { decisionStats, listDecisions } from "../core/decisions.ts";
202202 import { globalMapJson, mapJson, marksFor } from "../web/pages/map.ts";
203 import { fleetFor, fleetJson } from "../web/pages/fleet.ts";
203204 import { appsRuntime, type AppsRuntime } from "../apps/runtime.ts";
204205 import { isEnvName } from "../apps/data.ts";
205206 import { getAppByRepo } from "../core/apps.ts";
@@ -1788,6 +1789,14 @@ export function apiRoutes(router: Router<Handler>): void {
17881789 router.add("GET", "/api/v1/map", (ctx) =>
17891790 json(globalMapJson(ctx.app, ctx.auth.user)),
17901791 );
1792 // The fleet table as data: `?q=` is the same query line as /fleet.
1793 router.add("GET", "/api/v1/fleet", (ctx) => {
1794 if (!ctx.auth.user) return unauthorized();
1795 const f = fleetFor(ctx, ctx.auth.user.id, ctx.url.searchParams.get("q") ?? "");
1796 if (!f.result)
1797 return json({ error: "bad_query", message: f.error?.message ?? "", at: f.error?.at ?? "" }, 422);
1798 return json(fleetJson(f));
1799 });
17911800
17921801 // The decision ledger: what the crew's decider answered and what came of
17931802 // it, newest first, with the week summed up per kind.
src/http/server.ts +3
@@ -44,6 +44,7 @@ import {
4444 import { confirmPage, searchPage } from "../web/pages/search.ts";
4545 import { followingSubmit } from "../web/pages/following.ts";
4646 import { activityAtom } from "../web/feeds.ts";
47 import { fleetCsv, fleetPage } from "../web/pages/fleet.ts";
4748 import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts";
4849 import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
4950 import {
@@ -460,6 +461,8 @@ export function buildRouter(): Router<Handler> {
460461 router.add("GET", "/migrate/jobs/:job", migrationJobPage);
461462 // Every app on one canvas; a literal route, so it must sit above /:owner.
462463 router.add("GET", "/map", globalMapPage);
464 router.add("GET", "/fleet", fleetPage);
465 router.add("GET", "/fleet.csv", fleetCsv);
463466 // Live regions' own addresses (docs/STUDIO.md, "Live regions"): the
464467 // home's shelf and its "On you" card answer for themselves, so an event
465468 // fetches a region and not the page. Literal, above /:owner.
src/web/layout.ts +3
@@ -203,6 +203,7 @@ function userMenu(user: User, signOut: MenuItem): Html {
203203 { label: "Your repositories", href: "/", icon: "repo" },
204204 { label: "Apps", href: "/apps", icon: "rocket" },
205205 { label: "Map", href: "/map", icon: "map" },
206 { label: "Fleet", href: "/fleet", icon: "activity" },
206207 { separator: true, label: "" },
207208 // The "+" menu is hidden on a phone to keep the topbar inside the
208209 // screen; creating things stays one tap away here.
@@ -275,6 +276,7 @@ const STATIC_PALETTE_DEV: PaletteItem[] = [
275276 { t: "Home", h: "/", c: "Go to" },
276277 { t: "Apps", h: "/apps", c: "Go to" },
277278 { t: "Map", h: "/map", c: "Go to" },
279 { t: "Fleet", h: "/fleet", c: "Go to" },
278280 { t: "New app", h: "/apps/new", c: "Create" },
279281 { t: "New repository", h: "/new", c: "Create" },
280282 { t: "Migrate a repository", h: "/migrate", c: "Create" },
@@ -295,6 +297,7 @@ const STATIC_PALETTE_STUDIO: PaletteItem[] = [
295297 { t: "Home", h: "/", c: "Go to" },
296298 { t: "Apps", h: "/apps", c: "Go to" },
297299 { t: "Map", h: "/map", c: "Go to" },
300 { t: "Fleet", h: "/fleet", c: "Go to" },
298301 { t: "Asks you", h: "/asks", c: "Go to" },
299302 { t: "New app", h: "/apps/new", c: "Create" },
300303 { t: "Migrate a repository", h: "/migrate", c: "Create" },
src/web/pages/fleet.ts added +247
@@ -0,0 +1,247 @@
1 /**
2 * The fleet: repos, runs, issues, apps and crew as one table behind one
3 * visible query line (`fleet/query.ts`). The query is the page's only
4 * state and it lives in the URL, so a link to a view is the view. Every
5 * column header is a link that rewrites the query's `sort:`; every count is
6 * a link that adds its term. Nothing is filtered where a person cannot read
7 * it.
8 *
9 * `GET /fleet.csv` is the same rows as a file and `GET /api/v1/fleet` the
10 * same rows as JSON — one `runFleet` call behind all three.
11 */
12
13 import type { Ctx } from "../../http/context.ts";
14 import { KINDS, parseQuery, withSort, withTerm, type Kind } from "../../fleet/query.ts";
15 import {
16 fleetTotals,
17 FLEET_LIMIT,
18 runFleet,
19 SPECS,
20 type Cell,
21 type Field,
22 type FleetResult,
23 type Row,
24 } from "../../fleet/table.ts";
25 import { pageHead, signInFirst } from "../chrome.ts";
26 import { escapeHtml, html, raw, type Html } from "../html.ts";
27 import { page } from "../layout.ts";
28 import { btn, time } from "../ui.ts";
29
30 const href = (line: string): string =>
31 line.trim() === "" ? "/fleet" : `/fleet?q=${encodeURIComponent(line.trim())}`;
32
33 /** The query line from the URL; absent is the empty line (all repos). */
34 const lineOf = (ctx: Ctx): string => ctx.url.searchParams.get("q") ?? "";
35
36 export interface Fleet {
37 readonly line: string;
38 readonly result: FleetResult | null;
39 readonly error: { message: string; at: string } | null;
40 readonly kind: Kind;
41 }
42
43 /** Parse and run the line for the viewer — the page, the file and the API. */
44 export function fleetFor(ctx: Ctx, viewerId: string, line: string): Fleet {
45 const parsed = parseQuery(line);
46 if (!parsed.ok) return { line, result: null, error: parsed.error, kind: "repo" };
47 const ran = runFleet(ctx.app.db, viewerId, parsed.value);
48 if (!ran.ok) return { line, result: null, error: ran.error, kind: parsed.value.kind };
49 return { line, result: ran.value, error: null, kind: parsed.value.kind };
50 }
51
52 const usd = (n: number): string => `$${n.toFixed(2)}`;
53
54 const repoHrefOf = (row: Row): string =>
55 `/${encodeURIComponent(String(row.owner ?? ""))}/${encodeURIComponent(String(row.repo_name ?? ""))}`;
56
57 /**
58 * One cell as escaped HTML text. The table is up to a thousand rows of a
59 * dozen cells, so cells are strings joined once rather than an `Html` value
60 * each — every value still passes `escapeHtml` on its way in.
61 */
62 function cell(kind: Kind, field: Field, row: Row, repoHref: string): string {
63 const value: Cell = row[field.name] ?? null;
64 const shown = escapeHtml(value === null ? "" : String(value));
65 const link = (to: string): string => `<a href="${escapeHtml(to)}">${shown}</a>`;
66 if (field.name === "repo") return link(repoHref);
67 if (kind === "issue" && field.name === "title")
68 return link(`${repoHref}/${row.kind === "pull" ? "pulls" : "issues"}/${Number(row.number)}`);
69 if (kind === "run" && field.name === "kind")
70 return link(`${repoHref}/runs/${encodeURIComponent(String(row.id))}`);
71 if (kind === "app" && field.name === "slug") return link(repoHref);
72 if (kind === "crew" && field.name === "agent")
73 return link(`/${encodeURIComponent(String(value ?? ""))}`);
74 if (value === null || value === "") return `<span class="faint">—</span>`;
75 if (field.type === "usd") return usd(Number(value));
76 if (field.type === "date") return time(String(value)).text;
77 return shown;
78 }
79
80 function table(f: Fleet, result: FleetResult): Html {
81 const head = result.columns.map((c) => {
82 const sorted = result.sort.field === c.name;
83 // First click sorts the way a person usually wants: numbers and dates
84 // largest first, text A to Z; a second click turns it round.
85 const firstDir = c.type === "text" || c.type === "enum" ? "asc" : "desc";
86 const next = sorted ? (result.sort.dir === "asc" ? "desc" : "asc") : firstDir;
87 const aria = sorted ? (result.sort.dir === "asc" ? "ascending" : "descending") : null;
88 const arrow = sorted ? (result.sort.dir === "asc" ? " ↑" : " ↓") : "";
89 const numeric = c.type === "number" || c.type === "usd";
90 return html`<th scope="col" ${aria ? html`aria-sort="${aria}"` : null}
91 ${numeric ? html`class="num"` : null}
92 ><a href="${href(withSort(f.line, c.name, next))}" title="${c.about}">${c.name}${arrow}</a></th>`;
93 });
94 const opens = result.columns.map((c) =>
95 c.type === "number" || c.type === "usd" ? `<td class="num">` : "<td>",
96 );
97 let rows = "";
98 for (const row of result.rows) {
99 const repoHref = repoHrefOf(row);
100 rows += "<tr>";
101 for (const [i, c] of result.columns.entries())
102 rows += `${opens[i]}${cell(result.kind, c, row, repoHref)}</td>`;
103 rows += "</tr>";
104 }
105 return html`<div class="card table-scroll fleet-table">
106 <table class="table" data-dense>
107 <thead><tr>${head}</tr></thead>
108 <tbody>${raw(rows)}</tbody>
109 </table>
110 </div>`;
111 }
112
113 function countsLine(f: Fleet, result: FleetResult): Html {
114 const facets = [...result.facet.counts.entries()]
115 .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
116 .map(
117 ([value, n]) =>
118 html`<a class="fleet-facet" href="${href(withTerm(f.line, `${result.facet.field}:${value === "" ? "none" : value}`))}"
119 ><b>${n}</b> ${value === "" ? "none" : value}</a
120 >`,
121 );
122 const shown = result.rows.length;
123 return html`<p class="fleet-counts" aria-live="polite">
124 <b>${result.matching}</b> matching
125 ${shown < result.matching
126 ? html`<span class="muted">· showing the first ${shown}; narrow the query for the rest</span>`
127 : null}
128 ${facets.length > 0 ? html`<span class="muted">· by ${result.facet.field}:</span> ${facets}` : null}
129 </p>`;
130 }
131
132 function fieldsHelp(kind: Kind): Html {
133 const spec = SPECS[kind];
134 return html`<details class="fleet-help">
135 <summary>Fields of ${spec.plural} and how to write a query</summary>
136 <table class="table" data-dense>
137 <tbody>
138 ${spec.fields.map(
139 (f) => html`<tr>
140 <td><code>${f.name}</code></td>
141 <td class="muted">${f.values ? f.values.join(" | ") : f.type === "usd" ? "dollars" : f.type}</td>
142 <td>${f.about}</td>
143 </tr>`,
144 )}
145 </tbody>
146 </table>
147 <p class="muted small">
148 <code>field:value</code> equals (text ignores case, <code>*</code> is any
149 run of characters, <code>none</code> is empty); <code>a,b</code> is any
150 of; <code>field:!value</code> or <code>-field:value</code> is not;
151 <code>field&gt;n</code>, <code>&gt;=</code>, <code>&lt;</code>,
152 <code>&lt;=</code> compare numbers and dates. A date is
153 <code>2026-10-01</code> or an age — <code>7d</code> is seven days ago
154 (m, h, d, w), so <code>created&gt;7d</code> is the last week.
155 <code>repo:name</code> or <code>repo:owner/name</code> scopes;
156 <code>sort:field</code>, <code>sort:-field</code> orders. A bare word
157 searches ${spec.words.join(" and ")}. Money is US dollars;
158 <code>spent</code> on a repo is agent spend since 00:00 UTC, the number
159 its ceiling is held against. At most ${FLEET_LIMIT} rows are shown.
160 </p>
161 </details>`;
162 }
163
164 /** GET /fleet */
165 export function fleetPage(ctx: Ctx): Response {
166 const viewer = ctx.auth.user;
167 if (!viewer) return signInFirst(ctx);
168 const f = fleetFor(ctx, viewer.id, lineOf(ctx));
169 const totals = fleetTotals(ctx.app.db, viewer.id);
170 const kinds = KINDS.map(
171 (k) => html`<a href="${href(k)}" ${k === f.kind ? html`aria-current="page"` : null}
172 >${SPECS[k].plural} <span class="muted">${totals.get(k) ?? 0}</span></a
173 >`,
174 );
175 const exports = `?q=${encodeURIComponent(f.line)}`;
176 const body = html`${pageHead("Fleet", {
177 sub: "Every repo, run, issue, app and crew member you can read, behind one query. The query is the URL: copy it to share this view.",
178 })}
179 <nav class="fleet-kinds" aria-label="Kinds">${kinds}</nav>
180 <form class="fleet-query" method="get" action="/fleet" role="search">
181 <label class="sr-only" for="fleet-q">Query</label>
182 <input id="fleet-q" class="input mono" type="search" name="q"
183 value="${f.line}" maxlength="500" autocomplete="off" spellcheck="false"
184 placeholder="run state:queued repo:!forge sort:-created" />
185 ${btn("Run", { type: "submit" })}
186 ${btn("CSV", { href: `/fleet.csv${exports}`, variant: "ghost" })}
187 ${btn("JSON", { href: `/api/v1/fleet${exports}`, variant: "ghost" })}
188 </form>
189 ${f.error
190 ? html`<p class="fleet-error" role="alert">
191 ${f.error.message}${f.error.at ? html` <code>${f.error.at}</code>` : null}
192 </p>`
193 : null}
194 ${f.result ? countsLine(f, f.result) : null}
195 ${f.result
196 ? f.result.rows.length === 0
197 ? html`<p class="no-hits">Nothing matches this query.</p>`
198 : table(f, f.result)
199 : null}
200 ${fieldsHelp(f.kind)}`;
201 return page({ ctx, title: "Fleet", body, wide: true });
202 }
203
204 const csvCell = (v: Cell): string => {
205 const s = v === null ? "" : String(v);
206 // A leading = + - @ makes a spreadsheet evaluate the cell; a quote
207 // in front keeps a title a title.
208 const safe = /^[=+\-@\t\r]/.test(s) && typeof v === "string" ? `'${s}` : s;
209 return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
210 };
211
212 /** GET /fleet.csv — the matching rows (up to the page's limit) as a file. */
213 export function fleetCsv(ctx: Ctx): Response {
214 const viewer = ctx.auth.user;
215 if (!viewer) return signInFirst(ctx);
216 const f = fleetFor(ctx, viewer.id, lineOf(ctx));
217 if (!f.result)
218 return new Response(`${f.error?.message ?? "Bad query."}\n`, {
219 status: 422,
220 headers: { "content-type": "text/plain; charset=utf-8" },
221 });
222 const names = ["id", ...f.result.columns.map((c) => c.name)];
223 const lines = [names.join(",")];
224 for (const row of f.result.rows) lines.push(names.map((n) => csvCell(row[n] ?? null)).join(","));
225 return new Response(lines.join("\r\n") + "\r\n", {
226 headers: {
227 "content-type": "text/csv; charset=utf-8",
228 "content-disposition": `attachment; filename="fleet-${f.result.kind}.csv"`,
229 "cache-control": "private, no-store",
230 },
231 });
232 }
233
234 /** The JSON shape of `GET /api/v1/fleet`. */
235 export function fleetJson(f: Fleet): Record<string, unknown> {
236 const r = f.result!;
237 return {
238 query: f.line,
239 kind: r.kind,
240 matching: r.matching,
241 limit: FLEET_LIMIT,
242 sort: r.sort,
243 columns: r.columns.map((c) => ({ name: c.name, type: c.type, about: c.about })),
244 counts: { field: r.facet.field, values: Object.fromEntries(r.facet.counts) },
245 items: r.rows,
246 };
247 }
src/web/style/content.ts +21
@@ -1009,5 +1009,26 @@ textarea.editor:focus { outline: none; }
10091009 }
10101010 .no-hits .ico { color: var(--faint); flex: none; }
10111011
1012 /* The fleet: kind links, the query line, counts, one sortable table. */
1013 .fleet-kinds { display: flex; flex-wrap: wrap; gap: 4px 14px; margin: 0 0 10px; }
1014 .fleet-kinds a { color: var(--muted-fg); text-decoration: none; }
1015 .fleet-kinds a[aria-current="page"] { color: var(--fg); font-weight: 600; }
1016 .fleet-query { display: flex; gap: 6px; align-items: center; margin: 0 0 10px; }
1017 .fleet-query .input { flex: 1 1 auto; min-width: 0; font-family: var(--mono); }
1018 .fleet-counts { display: flex; flex-wrap: wrap; gap: 4px 10px; margin: 0 0 10px; }
1019 .fleet-facet { color: var(--muted-fg); text-decoration: none; }
1020 .fleet-facet b, .fleet-counts > b { color: var(--fg); font-variant-numeric: tabular-nums; }
1021 .fleet-error { color: var(--danger); margin: 0 0 10px; }
1022 .fleet-table th a { color: inherit; text-decoration: none; }
1023 .fleet-table th[aria-sort] a { color: var(--fg); }
1024 .fleet-table .num { text-align: right; }
1025 .fleet-help { margin: 14px 0 0; }
1026 .fleet-help summary { cursor: pointer; color: var(--muted-fg); }
1027 .fleet-help p { margin: 8px 0 0; max-width: 80ch; }
1028 @media print {
1029 .fleet-query, .fleet-kinds, .fleet-help { display: none; }
1030 .fleet-table { overflow: visible; }
1031 }
1032
10121033 }
10131034 `;
test/fleet.test.ts added +295
@@ -0,0 +1,295 @@
1 /**
2 * The fleet: the query line's grammar, its SQL against the real tables
3 * (counts checked by hand against what was seeded), what a viewer may not
4 * see, and a 1,000-row page answering in under 100 ms.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { parseQuery, withSort, withTerm, type Query } from "../src/fleet/query.ts";
17 import { compile, instant, runFleet, type FleetResult } from "../src/fleet/table.ts";
18
19 const parsed = (line: string): Query => {
20 const r = parseQuery(line);
21 if (!r.ok) throw new Error(r.error.message);
22 return r.value;
23 };
24
25 describe("the fleet query parser", () => {
26 test("an empty line is every repo, in the default order", () => {
27 expect(parsed("")).toEqual({ kind: "repo", terms: [], words: [], notWords: [], sort: null });
28 });
29
30 test("the first word names the kind, singular or plural", () => {
31 expect(parsed("runs").kind).toBe("run");
32 expect(parsed("issue").kind).toBe("issue");
33 expect(parsed("Apps").kind).toBe("app");
34 expect(parsed("crew").kind).toBe("crew");
35 // Not first, it is a word to search for.
36 expect(parsed("state:open run")).toMatchObject({ kind: "repo", words: ["run"] });
37 });
38
39 test("field:value, lists, negation both ways", () => {
40 expect(parsed("run state:queued,running repo:!forge -kind:deploy").terms).toEqual([
41 { field: "state", op: "=", values: ["queued", "running"] },
42 { field: "repo", op: "!=", values: ["forge"] },
43 { field: "kind", op: "!=", values: ["deploy"] },
44 ]);
45 });
46
47 test("comparisons, with or without the colon", () => {
48 expect(parsed("spent>50 slots<=2 ceiling:>=10 created:<7d").terms).toEqual([
49 { field: "spent", op: ">", values: ["50"] },
50 { field: "slots", op: "<=", values: ["2"] },
51 { field: "ceiling", op: ">=", values: ["10"] },
52 { field: "created", op: "<", values: ["7d"] },
53 ]);
54 // Negating a comparison is its complement, not a second operator.
55 expect(parsed("-spent>50").terms).toEqual([{ field: "spent", op: "<=", values: ["50"] }]);
56 });
57
58 test("quotes keep spaces and commas; bare words search", () => {
59 const q = parsed(`issue label:"needs review","a,b" "two words" -draft`);
60 expect(q.terms).toEqual([{ field: "label", op: "=", values: ["needs review", "a,b"] }]);
61 expect(q.words).toEqual(["two words"]);
62 expect(q.notWords).toEqual(["draft"]);
63 });
64
65 test("sort:field and sort:-field", () => {
66 expect(parsed("run sort:-cost").sort).toEqual({ field: "cost", dir: "desc" });
67 expect(parsed("sort:Repo").sort).toEqual({ field: "repo", dir: "asc" });
68 });
69
70 test("malformed lines are errors that name the term", () => {
71 const cases: [string, string][] = [
72 [`title:"open`, "syntax"],
73 ["state:", "syntax"],
74 ["sort:>3", "syntax"],
75 ["-sort:x", "syntax"],
76 ["x".repeat(501), "too_long"],
77 ["state:open\u0000", "control"],
78 [Array.from({ length: 25 }, (_, i) => `w${i}`).join(" "), "too_many"],
79 ];
80 for (const [line, code] of cases) {
81 const r = parseQuery(line);
82 expect(r.ok).toBe(false);
83 if (!r.ok) expect(r.error.code).toBe(code as typeof r.error.code);
84 }
85 });
86
87 test("withSort and withTerm rewrite the line and keep the rest", () => {
88 expect(withSort("run state:ok sort:cost", "cost", "desc")).toBe("run state:ok sort:-cost");
89 expect(withSort("", "repo", "asc")).toBe("sort:repo");
90 expect(withTerm("run", "state:ok")).toBe("run state:ok");
91 expect(withTerm(" ", "autonomy:off")).toBe("autonomy:off");
92 });
93 });
94
95 describe("compiling against a kind", () => {
96 const now = new Date("2026-10-02T12:00:00.000Z");
97
98 test("unknown fields and bad values are refused with what is allowed", () => {
99 const unknown = compile(parsed("run colour:red"), now);
100 expect(unknown.ok).toBe(false);
101 if (!unknown.ok) expect(unknown.error.message).toContain("Fields: repo, kind, state");
102 const enumValue = compile(parsed("autonomy:sometimes"), now);
103 if (!enumValue.ok) expect(enumValue.error.message).toBe("autonomy is one of: off, assisted, autonomous.");
104 expect(enumValue.ok).toBe(false);
105 expect(compile(parsed("spent>lots"), now).ok).toBe(false);
106 expect(compile(parsed("autonomy>off"), now).ok).toBe(false);
107 expect(compile(parsed("created>yesterday"), now).ok).toBe(false);
108 expect(compile(parsed("issue sort:label"), now).ok).toBe(false);
109 });
110
111 test("every value is a bound parameter, never SQL text", () => {
112 const c = compile(parsed(`run title:"x' OR 1=1 --" reason:a*`), now);
113 expect(c.ok).toBe(true);
114 if (!c.ok) return;
115 expect(c.value.where).not.toContain("OR 1=1");
116 expect(c.value.params).toEqual(["x' OR 1=1 --", "a%"]);
117 });
118
119 test("a relative date is that long before now", () => {
120 expect(instant("7d", now)).toBe("2026-09-25T12:00:00.000Z");
121 expect(instant("3h", now)).toBe("2026-10-02T09:00:00.000Z");
122 expect(instant("2026-10-01", now)).toBe("2026-10-01T00:00:00.000Z");
123 expect(instant("soon", now)).toBeUndefined();
124 });
125 });
126
127 describe("the fleet over real tables", () => {
128 let dataDir: string;
129 let app: App;
130 let servers: Servers;
131 let alice: User;
132 let bob: User;
133 let aliceCookie: string;
134 let forge: Repo;
135 let notes: Repo;
136 let hidden: Repo;
137 const base = () => servers.url;
138 const get = (path: string, cookie = aliceCookie) =>
139 fetch(base() + path, { headers: { cookie }, redirect: "manual" });
140 const run = (viewer: User, line: string, now = new Date()): FleetResult => {
141 const r = runFleet(app.db, viewer.id, parsed(line), { now });
142 if (!r.ok) throw new Error(r.error.message);
143 return r.value;
144 };
145
146 beforeAll(async () => {
147 dataDir = await mkdtemp(join(tmpdir(), "forge-fleet-"));
148 app = createApp({ dataDir, port: 0 });
149 servers = await serve(app);
150 const mk = async (username: string, first = false) => {
151 const r = await createUser(app.db, {
152 username,
153 email: `${username}@forge.local`,
154 password: "a-good-passphrase",
155 adminIfFirst: first,
156 });
157 if (!r.ok) throw new Error(r.error);
158 return r.value;
159 };
160 await mk("root", true);
161 alice = await mk("alice");
162 bob = await mk("bob");
163 aliceCookie = `forge_session=${createSession(app.db, alice.id).token}`;
164 const r1 = await createRepo(app, alice, { name: "forge", visibility: "public" });
165 const r2 = await createRepo(app, alice, { name: "notes", visibility: "public" });
166 const r3 = await createRepo(app, alice, { name: "hidden", visibility: "private" });
167 if (!r1.ok || !r2.ok || !r3.ok) throw new Error("repos");
168 [forge, notes, hidden] = [r1.value, r2.value, r3.value];
169 app.db.run(`UPDATE repo SET autonomy = 'autonomous', autonomy_ceiling_usd = 50 WHERE id = ?`, [forge.id]);
170 app.db.run(`UPDATE repo SET autonomy = 'assisted' WHERE id = ?`, [notes.id]);
171
172 // 1,000 runs on notes: 400 queued, 600 ok, each cost i/100 dollars,
173 // one per minute back from 2026-10-02T11:59Z.
174 const insert = app.db.prepare(
175 `INSERT INTO run (id, repo_id, kind, state, cost_usd, created_at, reason)
176 VALUES (?1, ?2, 'agent', ?3, ?4, ?5, ?6)`,
177 );
178 app.db.transaction(() => {
179 for (let i = 0; i < 1000; i++)
180 insert.run(
181 `run${String(i).padStart(4, "0")}`,
182 notes.id,
183 i < 400 ? "queued" : "ok",
184 i / 100,
185 new Date(Date.UTC(2026, 9, 2, 11, 59) - i * 60_000).toISOString(),
186 i === 7 ? `<script>alert(1)</script>` : i === 8 ? "=HYPERLINK(1)" : "",
187 );
188 // forge: two agent runs today, $30 and $25.50 → spent $55.50.
189 insert.run("f1", forge.id, "running", 30, "2026-10-02T08:00:00.000Z", "");
190 insert.run("f2", forge.id, "ok", 25.5, "2026-10-02T09:00:00.000Z", "");
191 insert.run("f3", forge.id, "ok", 100, "2026-10-01T09:00:00.000Z", "");
192 insert.run("h1", hidden.id, "queued", 1, "2026-10-02T09:00:00.000Z", "secret");
193 })();
194 });
195
196 afterAll(async () => {
197 servers.stop();
198 app.close();
199 await rm(dataDir, { recursive: true, force: true });
200 });
201
202 const now = new Date("2026-10-02T12:00:00.000Z");
203
204 test("repos: spent is today's agent spend, compared in dollars", () => {
205 // notes: runs i = 0..719 fall on or after 00:00 UTC, Σ i/100 = 719·720/200.
206 const busy = run(alice, "repo spent>50 sort:-spent", now);
207 expect(busy.rows.map((x) => x.repo)).toEqual(["alice/notes", "alice/forge"]);
208 expect(busy.rows[0]!.spent).toBeCloseTo(2588.4, 6);
209 const r = run(alice, "repo spent>50 spent<100", now);
210 expect(r.rows.map((x) => x.repo)).toEqual(["alice/forge"]);
211 expect(r.rows[0]!.spent).toBe(55.5);
212 expect(r.rows[0]!.spent_total).toBe(155.5);
213 expect(r.rows[0]!.active).toBe(1);
214 expect(run(alice, "autonomy:autonomous,assisted", now).matching).toBe(2);
215 expect(run(alice, "autonomy:!off", now).matching).toBe(2);
216 expect(run(alice, "", now).facet.counts).toEqual(
217 new Map([["autonomous", 1], ["assisted", 1], ["off", 1]]),
218 );
219 });
220
221 test("runs: state, repo scoping, comparisons, sort and counts", () => {
222 const queued = run(alice, "run state:queued repo:!forge", now);
223 // 400 on notes + 1 on hidden (alice owns it).
224 expect(queued.matching).toBe(401);
225 expect(run(alice, "run state:queued repo:alice/notes", now).matching).toBe(400);
226 // cost >= 9.9 dollars: i in 990..999.
227 const dear = run(alice, "run repo:notes cost>=9.9 sort:-cost", now);
228 expect(dear.matching).toBe(10);
229 expect(dear.rows[0]!.cost).toBe(9.99);
230 expect(dear.rows.at(-1)!.cost).toBe(9.9);
231 // The last hour, on notes: minutes 11:00..11:59 → 60 runs (i 0..59).
232 expect(run(alice, "run repo:notes created>=1h", now).matching).toBe(60);
233 const all = run(alice, "run repo:notes", now);
234 expect(all.facet.counts).toEqual(new Map([["ok", 600], ["queued", 400]]));
235 expect(all.rows).toHaveLength(1000);
236 });
237
238 test("a viewer never sees a repository they cannot read", () => {
239 expect(run(bob, "run reason:secret", now).matching).toBe(0);
240 expect(run(bob, "repo", now).rows.map((x) => x.repo)).toEqual(["alice/forge", "alice/notes"]);
241 expect(run(alice, "run reason:secret", now).matching).toBe(1);
242 });
243
244 test("/fleet asks a stranger to sign in", async () => {
245 const res = await get("/fleet", "");
246 expect(res.status).toBe(303);
247 expect((await get("/api/v1/fleet", "")).status).toBe(401);
248 });
249
250 test("the page shows the query, the counts and sortable columns, escaped", async () => {
251 const res = await get(`/fleet?q=${encodeURIComponent('run repo:notes reason:"<script>*"')}`);
252 expect(res.status).toBe(200);
253 const body = await res.text();
254 expect(body).toContain('value="run repo:notes reason:&quot;&lt;script&gt;*&quot;"');
255 expect(body).toContain("<b>1</b> matching");
256 expect(body).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
257 expect(body).not.toContain("<script>alert(1)");
258 expect(body).toContain(`href="/fleet?q=${encodeURIComponent('run repo:notes reason:"<script>*" sort:-cost').replace(/'/g, "&#39;")}"`);
259 expect(res.headers.get("content-security-policy")).toBeTruthy();
260 });
261
262 test("a bad query says what is wrong instead of a table", async () => {
263 const body = await (await get("/fleet?q=run+colour%3Ared")).text();
264 expect(body).toContain('role="alert"');
265 expect(body).toContain("runs have no field");
266 const api = await get("/api/v1/fleet?q=run+colour%3Ared");
267 expect(api.status).toBe(422);
268 expect(((await api.json()) as { error: string }).error).toBe("bad_query");
269 });
270
271 test("CSV and JSON carry the same rows; CSV cells cannot become formulas", async () => {
272 const csv = await (await get("/fleet.csv?q=run+repo:notes+reason:*HYPERLINK*")).text();
273 expect(csv.split("\r\n")[0]).toBe("id,repo,kind,state,issue,title,actor,reason,cost,turns,created,finished");
274 expect(csv).toContain("'=HYPERLINK(1)");
275 const json = (await (await get("/api/v1/fleet?q=run+state:queued+repo:notes")).json()) as {
276 matching: number;
277 counts: unknown;
278 };
279 expect(json.matching).toBe(400);
280 expect(json.counts).toEqual({ field: "state", values: { queued: 400 } });
281 });
282
283 test("a 1,000-row page answers in under 100 ms", async () => {
284 const path = `/fleet?q=${encodeURIComponent("run repo:notes")}`;
285 await (await get(path)).text(); // warm: statements compiled, page code loaded
286 let best = Infinity;
287 for (let i = 0; i < 5; i++) {
288 const t0 = performance.now();
289 const body = await (await get(path)).text();
290 best = Math.min(best, performance.now() - t0);
291 expect(body.match(/<tr><td[ >]/g)?.length).toBe(1000);
292 }
293 expect(best).toBeLessThan(100);
294 });
295 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs