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

/explore sorts by ?sort=ships, forks or fresh, kept in the URL, defaulting to today's ranking #14174

Merged opened this

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

Merged

scout/forge:scout/14129-explore-sorts-by-sort-ships-forks-or-fre → main 4 commits fork 1 thread · 1 unresolved

  • Merged. scout/14129-explore-sorts-by-sort-ships-forks-or-fre was merged into main as 3ee4bed.

Review

Sign in to review this change.
1 file changed +121 −0
test/explore-sort-words.test.ts added +121
@@ -0,0 +1,121 @@
1 /** /explore and the explore MCP tool take sort=ships, forks or fresh in the same words (#14129). */
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 { createRepo } from "../src/actions/repos.ts";
8 import { createApp as insertApp } from "../src/core/apps.ts";
9 import { createIssue } from "../src/core/issues.ts";
10 import { createToken } from "../src/core/tokens.ts";
11 import { createUser, getUserByName } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { promote } from "./helpers/members.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17 const DAY = 86_400_000;
18 let dir = "";
19 let app: App;
20 let servers: Servers;
21 let token = "";
22
23 // Names sort apple < birch < cedar, so no order below is the alphabetical one.
24 // ships: birch 3, cedar 2, apple 1. forks: cedar 3, apple 2, birch 1. last ship: apple, cedar,
25 // birch.
26 const SHIPS: Record<string, number[]> = { apple: [1], birch: [5, 6, 7], cedar: [3, 4] };
27 const FORKS: Record<string, number> = { cedar: 3, apple: 2, birch: 1 };
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-explore-sort-words-"));
31 app = createApp({ dataDir: dir, port: 0 });
32 servers = await serve(app);
33 const founder = await createUser(app.db, { origin: "seed", trusted: true, username: "founder", email: "[email protected]", password: "a-long-words-passphrase", adminIfFirst: true });
34 if (!founder.ok) throw new Error("founder");
35 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "olive", email: "[email protected]", password: "a-long-words-passphrase" });
36 if (!made.ok) throw new Error("user");
37 promote(app.db, made.value);
38 const olive = getUserByName(app.db, "olive")!;
39 const now = Date.now();
40 for (const name of ["apple", "birch", "cedar"]) {
41 const repo = await createRepo(app, olive, { name, visibility: "public" });
42 if (!repo.ok) throw new Error("repo");
43 const rec = insertApp(app.db, { repoId: repo.value.id, slug: `olive-${name}`, access: "public" });
44 if (!rec.ok) throw new Error("app");
45 for (const days of SHIPS[name]!) {
46 const issue = createIssue(app.db, { repoId: repo.value.id, authorId: olive.id, title: "change", kind: "pull" });
47 if (!issue.ok) throw new Error("issue");
48 app.db
49 .query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', 'b', '', '', ?2)`)
50 .run(issue.value.id, new Date(now - days * DAY).toISOString());
51 }
52 for (let i = 0; i < FORKS[name]!; i++) {
53 const fork = await createRepo(app, olive, { name: `${name}-f${i}`, visibility: "public" });
54 if (!fork.ok) throw new Error("fork");
55 app.db.query(`UPDATE repo SET fork_parent_id = ?1 WHERE id = ?2`).run(repo.value.id, fork.value.id);
56 }
57 }
58 token = createToken(app.db, olive.id, "t", "rw").token;
59 }, 30_000);
60
61 afterAll(async () => {
62 await servers.stop();
63 app.close();
64 await rm(dir, { recursive: true, force: true });
65 });
66
67 const page = async (qs: string) => {
68 const res = await fetch(`${servers.url}/explore${qs}`);
69 const html = await res.text();
70 const list = /<ul class="list">([\s\S]*?)<\/ul>/.exec(html);
71 const order = list === null ? [] : [...list[1]!.matchAll(/<li[^>]*>[\s\S]*?<a href="(\/[^"?]*)">/g)].map((m) => m[1]!.replace("/olive/", ""));
72 return { status: res.status, html, order };
73 };
74 const mcp = async (args: unknown): Promise<string[]> => {
75 const res = await fetch(`${servers.url}/mcp`, {
76 method: "POST",
77 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
78 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "explore", arguments: args } }),
79 });
80 const body = JSON.parse(((await res.json()) as any).result.content[0].text) as { items: { kind: string; name?: string; repo?: string }[] };
81 return body.items.filter((i) => i.kind === "app").map((i) => String(i.name ?? i.repo).replace(/^.*\//, ""));
82 };
83
84 const EXPECTED = { ships: ["birch", "cedar", "apple"], forks: ["cedar", "apple", "birch"], fresh: ["apple", "cedar", "birch"] };
85
86 const LABEL: Record<string, string> = { ships: "Shipped", forks: "Forks", fresh: "Fresh" };
87
88 for (const [sort, want] of Object.entries(EXPECTED)) {
89 test(`sort=${sort} orders the page, marks itself and is kept in links`, async () => {
90 const res = await page(`?kind=app&sort=${sort}`);
91 expect(res.status).toBe(200);
92 expect(res.order).toEqual(want);
93 expect(res.html).toMatch(new RegExp(`<a[^>]*aria-current="[^"]+"[^>]*>\\s*${LABEL[sort]}\\s*</a>`));
94 expect(res.html).toContain(`sort=${sort}`);
95 });
96 test(`the explore tool orders by sort=${sort} in the same words`, async () => {
97 expect(await mcp({ kind: "app", sort })).toEqual(want);
98 expect(await mcp({ q: `kind:app sort:${sort}` })).toEqual(want);
99 });
100 }
101
102 test("any other sort shows the default ranking on the page; the tool refuses it by name", async () => {
103 const plain = await page("?kind=app");
104 const bad = await page("?kind=app&sort=bogus");
105 expect(bad.status).toBe(200);
106 expect(bad.order).toEqual(plain.order);
107 const tool = await mcp({ kind: "app" });
outdated

Weak assertion: .catch(() => null) with r === null lets a thrown/errored tool call pass. Replace with expect(await mcp({kind:"app",sort:"bogus"})).toEqual(await mcp({kind:"app"})) and also toEqual(plain.order).

108 expect(tool.length).toBeGreaterThan(0);
109 expect(tool).toEqual(plain.order);
110 // The tool does not guess: it refuses the word by name and returns no rows to mistake for a
111 // ranking.
112 const res = await fetch(`${servers.url}/mcp`, {
113 method: "POST",
114 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
115 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "explore", arguments: { kind: "app", sort: "bogus" } } }),
116 });
117 const text = ((await res.json()) as any).result.content[0].text as string;
118 expect(text).toContain("unknown_filter");
119 expect(text).toContain("sort:bogus");
120 expect(text).not.toContain('"items"');
121 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs