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

Surface the flow report in the terminal Flow dialog and the MCP flow tool #16999

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/6756-surface-the-flow-report-in-the-terminal → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/6756-surface-the-flow-report-in-the-terminal was merged into main as ade4088.

Review

Sign in to review this change.
5 files changed +132 −4
docs/features/flow-report.md added +13
@@ -0,0 +1,13 @@
1 ---
2 topic: Tell the crew
3 row: the flow report: ten flow reads, one line each
4 ---
5 # The flow report (#6756)
6
7 Ten reads under `src/flow/` (build yield, review latency, outsiders, checks pile, stale reds, gate minutes, oldest approved, idle pulls, lead time, openers), each as one plain line, in a fixed order (`flowReadings` and `flowReportLines`, `src/flow/report.ts`).
8
9 ## Where to read it
10
11 - **Shell:** `bun scripts/flow-report.ts` (`--json`, `--public`).
12 - **Terminal:** the Flow command (palette, admins and agents with `telemetry:read`) ends with "Flow report:" and the ten lines.
13 - **Agents:** the `flow` MCP tool with `{ kind: "report" }` returns `{ readings, lines }`. An agent's reads keep to public repositories (`flowReportFor`); an agent without the `telemetry:read` grant is refused, as for the plain `flow` read.
src/flow/report.ts +6
@@ -56,3 +56,9 @@ export function flowReportLines(r: FlowReadings): string[] {
5656 `openers: ${r.openers.length === 0 ? "none in 1 h" : r.openers.map((p) => `${p.author} ${p.opened} (${p.flow} flow)`).join(", ")}`,
5757 ];
5858 }
59
60 /** The report as one reader may see it: an agent's reads keep to public repositories. */
61 export function flowReportFor(db: Database, reader: { kind: "owner" | "agent" }, now = new Date()) {
62 const readings = flowReadings(db, now, reader.kind === "agent");
63 return { readings, lines: flowReportLines(readings) };
64 }
src/http/mcp/tools/flow.ts +12 −3
@@ -19,6 +19,7 @@ import { cpuStops } from "../../../flow/cpu_stops.ts";
1919 import { forgeCeiling } from "../../../flow/ceiling.ts";
2020 import { LANES, lanePicture } from "../../../flow/lanes.ts";
2121 import { timesOf } from "../../../flow/lane_times.ts";
22 import { flowReportFor } from "../../../flow/report.ts";
2223 import { flowCached } from "../../../system/flow_cache.ts";
2324 import { scopeAllows } from "../../../core/tokens.ts";
2425 import { applyFleetOp, previewFleetOp } from "../../../actions/fleet.ts";
@@ -38,13 +39,13 @@ const said = (subject: string, why: Why) =>
3839
3940 export const tool: Tool = {
4041 name: "flow",
41 doc: "with no arguments, the forge's pipeline (a forge admin's, or an agent the owner granted `telemetry:read`; private repositories cut out): per stage counts, `oldestWaiting`, `capacity`, the bottleneck, the merge `queue` and what each reviewer has `reviewing`, and `declines` (crew runs declined in 24 h, by reason) (the `ui://forge/flow` card); with `{ q, sort? }`, the rows a fleet query line selects: `{ kind, columns, items }`, only rows you may read, `sort` a column key led by `-` to reverse, a bad line answers its reason; with `{ q, action: { verb, value }, apply? }`, a fleet operation over those rows as `POST /api/v1/fleet/ops` answers it: the dry-run plan `{ dryRun: true, query, kind, verb, value, reversible, rows, counts }` and nothing changed, or with `apply: true` (an admin token, a person) the receipt `{ dryRun: false, id, rows, … }` whose id `limb` undoes; with `{ kind: drift }`, `{ drifting: [{ repo, number, landings, hours }] }` the open pulls over 25 landings or 6 h behind main, furthest first; each is brought up to date by `POST /{repo}/pulls/{number}/update`, or with `{ kind: drift, repo, pull, action: update }` (a repository writer) the same: `{ updating, by }` names the agent, or a refusal in the route's words; with `{ kind: bugs }`, `{ open, overdue, bugs: [{ repo, number, priority, dueAt }] }` soonest due first, at most 100 (an admin sees all, anyone else public repositories); with `{ kind: cpu }`, `{ stopped, closed: [{ repo, number, closedAt }] }` the hour's checks stopped for CPU (an admin's) and the pulls closed unmerged after one, newest first, at most 20, to queue again; with `{ repo, issue? or pull? }` (a repository writer), why it is not moving: `{ subject, moving, state?, cause, says, clears, next? }`, the first of wall (a person decides access), ceiling, hot_file, blocked_by, later_gate, no_builder, no_headroom, red_check, waiting_review that holds it (`flow/why.ts`); with `{ kind: growth, repo }` (anyone who can read it), is the work growing: `{ open: { issues, pulls }, perDay, daysQueued, growingRun, sentences, suggest }` as `/queue` shows, over its 14 days; `suggest` is words only, null when no pause is worth considering; `repo` alone asks about the repository's builders",
42 doc: "with no arguments, the forge's pipeline (a forge admin's, or an agent the owner granted `telemetry:read`; private repositories cut out): per stage counts, `oldestWaiting`, `capacity`, the bottleneck, the merge `queue` and what each reviewer has `reviewing`, and `declines` (crew runs declined in 24 h, by reason) (the `ui://forge/flow` card); with `{ q, sort? }`, the rows a fleet query line selects: `{ kind, columns, items }`, only rows you may read, `sort` a column key led by `-` to reverse, a bad line answers its reason; with `{ q, action: { verb, value }, apply? }`, a fleet operation over those rows as `POST /api/v1/fleet/ops` answers it: the dry-run plan `{ dryRun: true, query, kind, verb, value, reversible, rows, counts }` and nothing changed, or with `apply: true` (an admin token, a person) the receipt `{ dryRun: false, id, rows, … }` whose id `limb` undoes; with `{ kind: report }` (as the no-argument read: an admin, or an agent granted `telemetry:read`, public repositories only), `{ readings, lines }` the ten flow reads and the line that words each, as `bun scripts/flow-report.ts`; with `{ kind: drift }`, `{ drifting: [{ repo, number, landings, hours }] }` the open pulls over 25 landings or 6 h behind main, furthest first; each is brought up to date by `POST /{repo}/pulls/{number}/update`, or with `{ kind: drift, repo, pull, action: update }` (a repository writer) the same: `{ updating, by }` names the agent, or a refusal in the route's words; with `{ kind: bugs }`, `{ open, overdue, bugs: [{ repo, number, priority, dueAt }] }` soonest due first, at most 100 (an admin sees all, anyone else public repositories); with `{ kind: cpu }`, `{ stopped, closed: [{ repo, number, closedAt }] }` the hour's checks stopped for CPU (an admin's) and the pulls closed unmerged after one, newest first, at most 20, to queue again; with `{ repo, issue? or pull? }` (a repository writer), why it is not moving: `{ subject, moving, state?, cause, says, clears, next? }`, the first of wall (a person decides access), ceiling, hot_file, blocked_by, later_gate, no_builder, no_headroom, red_check, waiting_review that holds it (`flow/why.ts`); with `{ kind: growth, repo }` (anyone who can read it), is the work growing: `{ open: { issues, pulls }, perDay, daysQueued, growingRun, sentences, suggest }` as `/queue` shows, over its 14 days; `suggest` is words only, null when no pause is worth considering; `repo` alone asks about the repository's builders",
outdated

Says 'the nine flow reads'; there are ten. Fix the count.

4243 description:
4344 "Pipeline (admin); `q`: `/fleet` rows, `action` plans an op, `apply` does it; `kind:bugs`; `repo`: why stuck.",
4445 inputSchema: {
4546 type: "object",
4647 properties: {
47 kind: { type: "string", enum: ["bugs", "cpu", "drift", "growth", "lanes"] },
48 kind: { type: "string", enum: ["bugs", "cpu", "drift", "growth", "lanes", "report"] },
4849 q: { type: "string", maxLength: 500 },
4950 sort: { type: "string" },
5051 action: {},
@@ -104,6 +105,14 @@ export const tool: Tool = {
104105 return good({ kind: view.kind, columns: COLUMNS[view.kind], items: sortRows(view.rows, sort) });
105106 }
106107 if (args["kind"] !== undefined) {
108 if (args["kind"] === "report") {
109 const reader = telemetryReader(ctx.app, user);
110 if (!reader)
111 return badBlocked("forbidden", noTelemetryBlocked(ctx.app, user, "Reading this forge's flow report takes the telemetry:read grant."));
112 noteRead(ctx.app, user, reader, "flow");
113 countRead("flow", user.username);
114 return good(flowReportFor(ctx.app.db, reader));
115 }
107116 if (args["kind"] === "growth") {
108117 const repo = repoArg(ctx, user, args);
109118 if (isAnswer(repo)) return repo;
@@ -143,7 +152,7 @@ export const tool: Tool = {
143152 const now = new Date();
144153 return good({ stopped: admin ? cpuStops(ctx.app.db, now).stopped : 0, closed: cpuClosedPulls(ctx.app.db, now, { publicOnly: !admin }) });
145154 }
146 if (args["kind"] !== "bugs") return bad("invalid", "kind is bugs, cpu, drift, growth or lanes");
155 if (args["kind"] !== "bugs") return bad("invalid", "kind is bugs, cpu, drift, growth, lanes or report");
147156 // As the terminal's bugs screen: an admin sees every repository, anyone else public ones.
148157 const all = openBugs(ctx.app.db, user.isAdmin && user.kind !== "agent" ? {} : { publicOnly: true });
149158 const now = Date.now();
src/tui/forge.ts +4 −1
@@ -94,6 +94,8 @@ import { originAppsScreen } from "./screens/originapps.ts";
9494 import { addEntries } from "./screens/entries.ts";
9595 import { capacityScreen, mayCapacity } from "./screens/capacity.ts";
9696 import { crawlersScreen } from "./screens/crawlers.ts";
97 import { wrap } from "./term/width.ts";
98 import { flowReportFor } from "../flow/report.ts";
9799 import { forgeCeiling } from "../flow/ceiling.ts";
98100 import { flowLines, flowScreen } from "./screens/flow.ts";
99101 import { laneTimeLines } from "./screens/lane_times.ts";
@@ -603,6 +605,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
603605 if (session.user) noteRead(session.app, session.user, flowReader, "flow");
604606 const keeper = readKeeper(session.db, flowReader.kind === "owner");
605607 const user = session.user;
608 const reportLines = ["", "Flow report:", ...flowReportFor(session.db, flowReader).lines.flatMap((l) => wrap(l, 58))];
606609 ctx.push(flowScreen(ctx, flowLines(
607610 session.db,
608611 new Date(),
@@ -620,7 +623,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
620623 session.app.config.dataDir,
621624 flowReader.kind === "owner" ? beatLine(lastBeat(session.db), new Date()) : undefined,
622625 publicOrigin(session.app.config.url, `http://${session.app.config.host ?? "localhost"}:${session.app.config.port ?? 3000}`),
623 ).concat(laneTimeLines(session.db, user)), keeper.ask && user ? { ask: keeper.ask, answer: () => answerKeeper(session.app, keeper.ask!.id, user.id) } : undefined,
626 ).concat(laneTimeLines(session.db, user), reportLines), keeper.ask && user ? { ask: keeper.ask, answer: () => answerKeeper(session.app, keeper.ask!.id, user.id) } : undefined,
624627 mayDrift(session)
625628 ? { read: async () => readHandoverLists(session.db, await readDrifts(session.app), Date.now()), update: (n) => askUpdate(session, n) }
626629 : undefined));
test/flow-report-doors.test.ts added +97
@@ -0,0 +1,97 @@
1 /**
2 * The flow report (#6756) reaches the terminal's Flow dialog and the MCP `flow` tool, cut to public
3 * for an agent.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createAgent } from "../src/actions/crew.ts";
11 import { setTelemetryGrant } from "../src/actions/telemetry.ts";
12 import { createToken } from "../src/core/tokens.ts";
13 import { createUser, getUserByName, type User } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { createForgeApp, forgeCommands } from "../src/tui/forge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { flowReportFor } from "../src/flow/report.ts";
18 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { mcpTool } from "./helpers/mcp.ts";
21 import { openTopicPull } from "./helpers/open-pull.ts";
22 import { settleApp } from "./helpers/tui.ts";
23
24 quietLogs();
25
26 let dir = "";
27 let app: App;
28 let servers: Servers;
29 let owner = "";
30 let botToken = "";
31 let loneToken = "";
32
33 const call = (token: string, args: unknown) => mcpTool(servers.url, token, "flow", args);
34
35 beforeAll(async () => {
36 dir = await mkdtemp(join(tmpdir(), "forge-flow-doors-"));
37 app = createApp({ dataDir: dir, port: 0 });
38 servers = await serve(app);
39 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-report-passphrase", isAdmin: true });
40 if (!a.ok) throw new Error("alice");
41 owner = createToken(app.db, a.value.id, "t", "admin").token;
42 const alice = getUserByName(app.db, "alice")!;
43 const bot = await createAgent(app, alice, { username: "bot" });
44 const lone = await createAgent(app, alice, { username: "lone" });
45 if (!bot.ok || !lone.ok) throw new Error("agents");
46 setTelemetryGrant(app, alice, "bot", true);
47 botToken = createToken(app.db, bot.value.user.id, "t", "ro").token;
48 loneToken = createToken(app.db, lone.value.user.id, "t", "ro").token;
49 }, 30_000);
50
51 afterAll(async () => {
52 servers.stop();
53 app.close();
54 await rm(dir, { recursive: true, force: true });
55 });
56
57 describe("flow report doors", () => {
58 test("MCP: kind report answers the readings and their lines; an agent without the grant is refused", async () => {
59 const r = await call(owner, { kind: "report" });
60 expect(r.error).toBeUndefined();
61 expect(r.value.lines).toHaveLength(10);
62 expect(r.value.lines[0]).toStartWith("build_yield:");
63 expect(Object.keys(r.value.readings)).toContain("lead_time");
64 expect(r.value.lines).toEqual(flowReportFor(app.db, { kind: "owner" }).lines);
65 expect((await call(botToken, { kind: "report" })).value.lines).toHaveLength(10);
66 expect((await call(loneToken, { kind: "report" })).error).toBeDefined();
67 });
68
69 test("MCP: the granted agent's report leaves out private repositories; the owner's counts them", async () => {
70 const alice = getUserByName(app.db, "alice") as User;
71 const repo = await createRepo(app, alice, { name: "hidden", visibility: "private" });
72 if (!repo.ok) throw new Error("repo");
73 const seeded = await commitToBranch(app, alice, repo.value, { message: "start", files: [{ path: "README.md", content: "r\n" }] });
74 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
75 await openTopicPull(app, alice, repo.value, 1, true);
outdated

This only checks that the granted agent gets 10 lines. It would still pass if flowReadings were called without publicOnly. Seed private data and assert that the agent's report differs from the owner's.

76 const opener = (r: { value?: any }) => r.value.lines.find((l: string) => l.startsWith("openers:")) as string;
77 expect(opener(await call(owner, { kind: "report" }))).toContain("alice 1");
78 expect(opener(await call(botToken, { kind: "report" }))).toBe("openers: none in 1 h");
79 });
80
81 test("terminal: the Flow dialog ends with the report's lines", async () => {
82 const alice = getUserByName(app.db, "alice") as User;
83 const terminal = headlessTerminal(100, 200);
84 const { app: tui, session } = createForgeApp(
85 app,
86 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
87 { terminal, exitHooks: false },
88 );
89 tui.start();
90 forgeCommands(session)(tui.ctx).find((c) => c.id === "flow")!.run();
91 await settleApp(tui);
92 const text = tui.screen.toText();
93 expect(text).toContain("Flow report:");
94 expect(text).toContain("build_yield:");
95 expect(text).toContain("openers:");
96 });
97 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs