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

The `health` MCP tool takes `voice: true` and answers in at most two spoken sentences with no markup, for a client in a car #12552

Merged opened this

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

Merged

torque/forge:torque/12468-the-health-mcp-tool-takes-voice-true-and → main 8 commits fork 3 threads · 3 unresolved

  • Merged. torque/12468-the-health-mcp-tool-takes-voice-true-and was merged into main as 6bc981b.

Review

Sign in to review this change.
9 files changed +336 −5
docs/MCP.md +1 −1
@@ -122,7 +122,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
122122 | `fork_tree` | — | The fork tree around a repo: ancestors, siblings and descendants you may read | 440 |
123123 | `forks` | `chain` | A repo's forks you may see, paged by limit and cursor (next_cursor), each with commits ahead and behind | 480 |
124124 | `front_page` | — | The stranger's front page; admin sets `pinned`/`hidden`/`weights` | 457 |
125 | `health` | — | How this forge is: version, rollout, incidents | 316 |
125 | `health` | — | How this forge is: version, rollout, incidents | 389 |
126126 | `held` | — | What the Later gate holds, and one proposed pass over it | 361 |
127127 | `here` | — | What you may do on a forge page; given an app's link, what its /__forge/ door shows | 237 |
128128 | `hold` | — | Hold a pull (`why`) or `release` it; or `path`: hold new work on a file | 522 |
docs/features/health-voice.md added +31
@@ -0,0 +1,31 @@
1 # Health, spoken
2
3 How the forge is, in at most two plain sentences, for a client that reads the answer aloud.
4 No markup, no links, no ids and no numbers.
5
6 ## MCP
7
8 Call the `health` tool with `voice: true`:
9
10 ```json
11 { "name": "health", "arguments": { "voice": true } }
12 ```
13
14 The answer is a string, for example `The forge is up, with one thing for you. Disk is nearly full.`
15 It is 240 characters at most. Without `voice` the answer is the same object as before; `voice`
16 must be `true` or `false`, anything else is `invalid_voice`. Signed-out callers are refused as
17 for every other `health` call.
18
19 ## What it says
20
21 - The forge cannot tell how it is, when the platform's view is stale.
22 - The forge needs you now (not well), or is up with one thing for you: the first need with a
23 speakable clause, broken before rollout and incidents, those before standing wishes. A clause
24 with a link, id or number is dropped whole; if no need has one, it says to ask for the full health.
25 - Calm: `The forge is calm and nothing needs you.` for an admin. Anyone else cannot see the
26 broken needs, so they hear `Nothing is wrong that you can see.`
27
28 ## Terminal
29
30 Open the palette (`ctrl+k`) and choose **Health — spoken**. It shows the same sentence MCP gives
31 the same user, guest or admin.
src/actions/health_voice.ts added +65
@@ -0,0 +1,65 @@
1 import type { readHealth } from "./health.ts";
2
3 /** What `readHealth` answers: a stranger's, a signed-in user's or an admin's. */
4 export type HealthAnswer = ReturnType<typeof readHealth>;
5
6 /** A voice answer is read aloud: at most this many characters. */
7 export const VOICE_MAX = 240;
8
9 /** A word that cannot be said aloud: a link, a path, an id, a hash or any number. */
10 const unspeakable = (w: string): boolean => /https?:|\/|#\d|\d/.test(w);
11
12 /**
13 * One need as speech: markdown dropped, cut to its first sentence, then to its first clause
14 * (split at commas, colons and semicolons) with nothing unspeakable in it. A clause with a
15 * link, id or number is dropped whole, never word by word, so what is left is still grammar.
16 * Empty when no clause is speakable; the caller falls back to the next need.
17 */
outdated

Dense one-liner that drops id words in place, producing 'at see or.'. Split into named predicates and drop the clause instead of the word. Digits are never removed (box 1).

18 export function spoken(line: string): string {
19 const plain = line
20 .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
21 .replace(/[`*_>|~]/g, "")
22 .replace(/\s+/g, " ")
23 .trim();
24 const sentence = /^.*?[.!?](?=\s|$)/.exec(plain)?.[0] ?? plain;
25 const clause = sentence
26 .split(/[,;:]\s+/)
27 .map((c) => c.replace(/[.!?]+$/, "").trim())
28 .find((c) => c !== "" && !c.split(" ").some(unspeakable));
29 return clause === undefined ? "" : `${clause}.`;
30 }
31
32 /** The first word-boundary cut of `s` that fits `max` characters, ending in a full stop. */
33 function fit(s: string, max: number): string {
34 if (s.length <= max) return s;
35 const cut = s.slice(0, Math.max(0, max - 1)).replace(/\s+\S*$/, "").replace(/[\s,.:;]+$/, "");
36 return cut === "" ? "" : `${cut}.`;
37 }
38
39 /**
40 * The health answer in at most two sentences for a client in a car: whether things are calm,
41 * then the one thing that needs the person, from the words the answer already has (broken
42 * before the rollout and incidents, those before what would merely be liked). It never claims
43 * more than the caller can see: a stale view says it cannot tell, and a caller who is not an
44 * admin (broken needs are theirs alone) is told only that nothing is wrong that they can see.
45 */
46 export function voiceHealth(h: HealthAnswer): string {
47 if ("stale" in h && h.stale) return "The forge cannot tell how it is right now.";
48 const broken = "broken" in h ? h.broken : [];
outdated

Calm is claimed with no regard to h.stale, and a non-admin never sees broken. Say 'not sure' when stale or the caller cannot see everything.

49 const needs = [
50 ...broken,
51 ...(h.draining && broken.length === 0 ? ["The forge is draining."] : []),
52 ..."rollout" in h && h.rollout.state !== "ok" ? [`Rollout is ${h.rollout.state}.`] : [],
53 ...("incidents" in h ? h.incidents.map((i) => i.message) : []),
54 ...("todo" in h ? h.todo : []),
55 ];
56 const one = needs.map(spoken).find((s) => s.length > 1);
57 if (one === undefined) {
58 if (needs.length > 0) return "The forge has something for you; ask for the full health.";
59 if (!h.ok) return "The forge is not well.";
60 return "broken" in h ? "The forge is calm and nothing needs you." : "Nothing is wrong that you can see.";
61 }
62 const head = h.ok ? "The forge is up, with one thing for you." : "The forge needs you now.";
63 const tail = fit(one, VOICE_MAX - head.length - 1);
64 return tail === "" ? head : `${head} ${tail}`;
65 }
src/http/mcp/tools/health.ts +12 −4
@@ -1,12 +1,20 @@
11 import { healthAnswer } from "../../../actions/health.ts";
2 import { good, type Tool } from "../shared.ts";
2 import { voiceHealth } from "../../../actions/health_voice.ts";
3 import { bad, good, type Tool } from "../shared.ts";
34
45 export const tool: Tool = {
56 name: "health",
6 doc: "how this forge is: the version and commit it runs, draining or not, the rollout and its incidents",
7 doc: "how this forge is: the version and commit it runs, draining or not, the rollout and its incidents; `voice` true answers in two spoken sentences",
78 description:
89 "How this forge is: version, rollout, incidents. ok means serving, broken act now, todo would like done.",
9 inputSchema: { type: "object", properties: {} },
10 inputSchema: {
11 type: "object",
12 properties: { voice: { type: "boolean", description: "two plain sentences, no markup" } },
13 },
1014 writes: false,
11 run: (ctx, user) => good(healthAnswer(ctx.app, user)),
15 run: (ctx, user, args) => {
16 if (args["voice"] !== undefined && typeof args["voice"] !== "boolean") return bad("invalid_voice", "voice is true or false");
17 const answer = healthAnswer(ctx.app, user);
18 return good(args["voice"] === true ? voiceHealth(answer) : answer);
19 },
1220 };
src/tui/screens/entries.ts +2
@@ -101,6 +101,7 @@ import { entry as sentinel } from "./sentinel.ts";
101101 import { entry as subscriptions } from "./subscriptions.ts";
102102 import { entry as crewKey } from "./crewkey.ts";
103103 import { entry as crewBudgets } from "./crewbudgets.ts";
104 import { entry as healthVoice } from "./health_voice.ts";
104105 import { entry as system } from "./system.ts";
105106 import { entry as teams } from "./teams.ts";
106107 import { entry as telemetry } from "./telemetry.ts";
@@ -132,6 +133,7 @@ export const ENTRIES: readonly PaletteEntry[] = [
132133 bugs,
133134 homePins,
134135 system,
136 healthVoice,
135137 loopStalls,
136138 footing,
137139 maintenanceWeek,
src/tui/screens/health_voice.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * The forge's health as MCP `health` with `voice: true` says it (#12468): at most two
3 * spoken sentences from `voiceHealth`, the same words for the same user, so what a client
4 * in a car reads aloud can be read here.
5 */
6
7 import { readHealth } from "../../actions/health.ts";
8 import { voiceHealth } from "../../actions/health_voice.ts";
9 import type { Ctx, Screen } from "../app/app.ts";
10 import type { PaletteEntry } from "./entries.ts";
11 import { style } from "../term/style.ts";
12 import { truncate } from "../term/width.ts";
13 import type { Session } from "../session.ts";
14
15 /** The sentences this user is told: what MCP `health` gives them with `voice: true`. */
16 export function voiceLine(f: Session): string {
17 return voiceHealth(readHealth(f.app, f.user));
18 }
19
20 export function healthVoiceScreen(f: Session, ctx: Ctx): Screen {
21 return {
22 title: "Health — spoken",
23 keys: [],
24 key: () => false,
25 render(area, s) {
outdated

New terminal screen with no test and no docs/features/health-voice.md. Both are required.

26 const c = ctx.theme.c;
27 s.text(area.x, area.y, truncate(voiceLine(f), area.w), style(c.fg, c.bg), area.x + area.w);
28 },
29 };
30 }
31
32 /** The palette entry: offered to every reader, guests too. */
33 export const entry: PaletteEntry = {
34 id: "health-voice",
35 title: "Health — spoken",
36 hint: "how the forge is, in two plain sentences",
37 after: ["system", "flow", "boards"],
38 offered: () => true,
39 run: (session, ctx) => ctx.push(healthVoiceScreen(session, ctx)),
40 };
test/health-voice-tui.test.ts added +68
@@ -0,0 +1,68 @@
1 /** The terminal entry "Health, spoken": offered to all, same sentence as MCP `health`. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { readHealth } from "../src/actions/health.ts";
8 import { voiceHealth } from "../src/actions/health_voice.ts";
9 import { createUser, type User } from "../src/core/users.ts";
10 import { createForgeApp } from "../src/tui/forge.ts";
11 import { headlessTerminal } from "../src/tui/term/terminal.ts";
12 import { quietLogs } from "./helpers/globals.ts";
13 import { settleApp } from "./helpers/tui.ts";
14
15 quietLogs();
16
17 let dir: string;
18 let forge: App;
19 let alice: User;
20 let bob: User;
21
22 beforeAll(async () => {
23 dir = await mkdtemp(join(tmpdir(), "forge-health-voice-tui-"));
24 forge = createApp({ dataDir: dir, port: 0 });
25 const make = async (username: string, adminIfFirst: boolean): Promise<User> => {
26 const made = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst });
27 if (!made.ok) throw new Error(made.error);
28 return made.value;
29 };
30 alice = await make("alice", true);
31 bob = await make("bob", false);
32 });
33 afterAll(async () => {
34 forge.close();
35 await rm(dir, { recursive: true, force: true });
36 });
37
38 async function open(user: User | undefined) {
39 const identity = { sshUsername: "t", remoteAddress: "127.0.0.1", ...(user === undefined ? {} : { user }) };
40 const { app } = createForgeApp(forge, identity, { terminal: headlessTerminal(120, 32), exitHooks: false });
41 app.start();
42 const key = (k: string, ctrl = false) => app.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
43 await settleApp(app);
44 key("k", true);
45 await settleApp(app);
46 for (const ch of "spoken") key(ch);
47 await settleApp(app);
48 const offered = app.screen.toText().includes("Health — spoken");
49 key("enter");
50 await settleApp(app);
51 const text = app.screen.toText();
52 app.stop();
53 return { offered, text };
54 }
55
56 for (const [who, user] of [["an admin", () => alice], ["a signed-in user", () => bob], ["a guest", () => undefined]] as const) {
57 test(`${who} is offered the command and reads what MCP health says for them`, async () => {
58 const u = user();
59 const { offered, text } = await open(u);
60 expect(offered).toBe(true);
61 expect(text).toContain(voiceHealth(readHealth(forge, u)));
62 });
63 }
64
65 test("the admin's and the user's sentences differ in what they claim", () => {
66 expect(voiceHealth(readHealth(forge, alice))).toBe("The forge is calm and nothing needs you.");
67 expect(voiceHealth(readHealth(forge, bob))).toBe("Nothing is wrong that you can see.");
68 });
test/mcp-health-voice.test.ts added +113
@@ -0,0 +1,113 @@
1 /** `health` with `voice: true`: at most two plain sentences from the words the answer has. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createToken } from "../src/core/tokens.ts";
8 import { createUser, getUserByName } from "../src/core/users.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { readHealth } from "../src/actions/health.ts";
11 import { spoken, voiceHealth, VOICE_MAX, type HealthAnswer } from "../src/actions/health_voice.ts";
12 import { writeFileSync, mkdirSync } from "node:fs";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let token: string;
21
22 beforeAll(async () => {
23 dataDir = await mkdtemp(join(tmpdir(), "forge-health-voice-"));
24 app = createApp({ dataDir, port: 0 });
25 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
26 if (!made.ok) throw new Error(made.error);
27 token = createToken(app.db, getUserByName(app.db, "alice")!.id, "admin", "admin").token;
28 servers = await serve(app);
29 });
30
31 afterAll(async () => {
32 servers.stop();
33 app.close();
34 await rm(dataDir, { recursive: true, force: true });
35 });
36
37 const post = (args: Record<string, unknown>, auth = true): Promise<Response> =>
38 fetch(`${servers.url}/mcp`, {
39 method: "POST",
40 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...(auth ? { authorization: `Bearer ${token}` } : {}) },
41 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "health", arguments: args } }),
42 });
43 const text = (r: any): string => {
44 const t = r.structuredContent?.result ?? r.content[0].text;
45 return t.startsWith('"') ? JSON.parse(t) : t;
46 };
47 const call = async (args: Record<string, unknown>): Promise<any> => ((await (await post(args)).json()) as any).result;
48
49 const base = { ok: true, version: "1", commit: null, draining: false, rollout: { state: "ok", reason: "" }, incidents: [], stale: false, checkedAt: null } as const;
50 const plain = (s: string): void => {
51 expect(s.length).toBeLessThanOrEqual(VOICE_MAX);
52 expect(s.match(/[.!?](\s|$)/g)!.length).toBeLessThanOrEqual(2);
53 expect(s).not.toMatch(/[`*_#>|\[\]]|https?:|\/|\d/);
54 };
55 const admin = (extra: object = {}): HealthAnswer => ({ ...base, broken: [], todo: [], needs: [], ...extra }) as unknown as HealthAnswer;
56
57 test("a calm forge says so in one plain sentence, and without voice the answer is readHealth's", async () => {
58 const s = text(await call({ voice: true }));
59 expect(s).toBe("The forge is calm and nothing needs you.");
60 plain(s);
61 const without = await call({});
62 const user = getUserByName(app.db, "alice")!;
63 const stable = (h: any) => Object.fromEntries(["ok", "needs", "broken", "todo", "version", "commit", "draining", "rollout", "incidents", "stale"].map((k) => [k, h[k]]));
64 const want = JSON.parse(JSON.stringify(readHealth(app, user)));
65 expect(stable(JSON.parse(without.content[0].text))).toEqual(stable(want));
66 expect((await call({ voice: "yes" })).isError).toBe(true);
67 });
68
69 test("a real incident is the one thing waiting, said plainly through /mcp", async () => {
70 const guard = join(dataDir, "guard");
71 mkdirSync(guard, { recursive: true });
72 writeFileSync(join(guard, "status.json"), JSON.stringify({ incidents: { disk: "Disk is nearly full, see alice/engine #12." } }));
73 writeFileSync(join(guard, "checkedAt"), new Date().toISOString());
74 process.env["FORGE_GUARD_DIR"] = guard;
75 try {
76 const s = text(await call({ voice: true }));
77 expect(s).toBe("The forge needs you now. Disk is nearly full.");
78 plain(s);
79 } finally {
80 delete process.env["FORGE_GUARD_DIR"];
81 }
82 });
83
84 test("a clause with a link, id or number is dropped whole, and the next need is said", () => {
85 expect(spoken("Disk is nearly full at https://x.test/system, see alice/engine #12 or `abc1234def`.")).toBe("");
86 expect(spoken("Disk is nearly full, see alice/engine.")).toBe("Disk is nearly full.");
87 expect(spoken("93% full disk. Since 2 hours.")).toBe("");
88 const s = voiceHealth(admin({ todo: ["93% full disk.", "3 pulls wait.", "Backups are late."] }));
89 expect(s).toBe("The forge is up, with one thing for you. Backups are late.");
90 plain(s);
91 const all = voiceHealth(admin({ todo: ["93% full disk."] }));
92 expect(all).toBe("The forge has something for you; ask for the full health.");
93 });
94
95 test("a broken forge says act now, and a long need is cut to fit two sentences", () => {
96 const long = `Many words here ${"and more words ".repeat(40)}end.`;
97 const s = voiceHealth(admin({ ok: false, broken: [long] }));
98 expect(s.startsWith("The forge needs you now. Many words")).toBe(true);
99 plain(s);
100 expect(voiceHealth(admin({ ok: false, draining: true }))).toBe("The forge needs you now. The forge is draining.");
101 expect(spoken("**Bold** and [link](http://a.b/c) done")).toBe("Bold and link done.");
102 });
103
104 test("it never claims more than the caller can see", () => {
105 expect(voiceHealth({ ...base, stale: true, ok: false } as unknown as HealthAnswer)).toBe("The forge cannot tell how it is right now.");
106 expect(voiceHealth({ ...base } as unknown as HealthAnswer)).toBe("Nothing is wrong that you can see.");
107 expect(voiceHealth({ ok: true, version: "1", commit: null, draining: false })).toBe("Nothing is wrong that you can see.");
108 });
109
110 test("a signed-out caller is refused as health already refuses", async () => {
111 const res = await post({ voice: true }, false);
112 expect(res.status).toBe(401);
113 });
test/palette-roster.test.ts +4
@@ -118,6 +118,7 @@ test("a site-admin person is offered the whole roster", () => {
118118 ["system", "System", "the machine now: CPU, memory, disks, processes"],
119119 ["pulls-to-land", "Pulls to land", "approved pulls, stale crew pulls, unproposed work"],
120120 ["valves", "Valves", "the week's budget as a valve per repository; turn one and the crew obeys"],
121 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
121122 ["refused-asks", "Refused first asks", "the last 20 first asks turned away"],
122123 ["disks", "Disks", "machines' disk readings: 30-day write rate and projected rated-TBW date"],
123124 ["telemetry", "Telemetry", "which agents may read flow and system; enter flips the grant"],
@@ -280,6 +281,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
280281 ["proposal-tokens", "Proposal tokens", "mint, list and revoke what a child proposes with"],
281282 ["can", "What I can do", "your role and what it allows here"],
282283 ["bugs", "Bugs", "open bugs and the bug clock"],
284 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
283285 ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"],
284286 ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"],
285287 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
@@ -373,6 +375,7 @@ test("a member person is offered the signed-in roster without the admin entries"
373375 ["model", "Model budget", "what your crew may spend, and add your own subscription"],
374376 ["can", "What I can do", "your role and what it allows here"],
375377 ["bugs", "Bugs", "open bugs and the bug clock"],
378 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
376379 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
377380 ["archived", "Archived repositories", "put away, not gone: open one or restore it"],
378381 ["claim-start", "Take an agent's work", "claim the repositories an agent started, from its one-time link"],
@@ -432,6 +435,7 @@ test("signed out, the palette offers sign-in and the public entries", () => {
432435 ["docs", "Docs", "the forge's documentation; Enter reads one"],
433436 ["changelog", "Changelog", "the last 30 releases and their pulls"],
434437 ["bugs", "Bugs", "open bugs and the bug clock"],
438 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
435439 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
436440 ["front", "Front page", "the apps a first visitor sees, ranked; an admin pins or hides"],
437441 ["origin-ahead", "New commits upstream", "mirrors whose origin has moved on: take them"],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs