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

Repository names: a bare name finds yours, a miss says why and suggests (#16462, #16465) #16472

Merged opened this

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

Merged

voice/repo-names → main 0 commits 2 threads · 2 unresolved

  • Merged. voice/repo-names was merged into main as d1589b0.

Review

Sign in to review this change.
7 files changed +233 −25
docs/features/repo-names.md added +17
@@ -0,0 +1,17 @@
1 ---
2 topic: Getting around: keys, the palette and search
3 row: A repository said the way you say it is found, or the miss says what you meant
4 ---
5 # Saying a repository's name
6
7 Every place that takes a repository by name answers a miss the same way: the 404 page, the terminal's `owner/name` prompt, and every MCP tool's `repo` argument (so Talk and any voice client). One lookup, `nearRepos` (`core/near_repos.ts`), names what you may have meant, only from what you can read:
8
9 1. the same name under any owner (a wrong owner, such as `trevato/car-duel` for `marin/car-duel`);
10 2. a near name under the owner you named (a typo, a word left off: `car-duel` for `car-duel-2`);
11 3. any repository whose `owner/name` is within two letters of what you typed.
12
13 Through MCP a bare name works too: `voxel` is your own repository by that name, else the one by that name you can read; two others are both named back for you to choose. A leading `@` and spaces around the name are ignored.
14
15 A miss never says whether a private repository by that name exists: "it does not exist, or it is private and not shared with you", the same words either way, and a guess names only what you read.
16
17 Proof: `test/mcp-repo-names.test.ts` and `test/did-you-mean.test.ts`.
src/core/near_repos.ts +50 −12
@@ -1,19 +1,58 @@
11 import type { Database } from "bun:sqlite";
2 import { listReposVisibleTo, type Repo } from "./repos.ts";
2 import { canRead, listReposVisibleTo, reposByNameOrOwner, type Repo } from "./repos.ts";
33 import type { User } from "./users.ts";
44 import { editDistance } from "../text/edit_distance.ts";
55
66 const NEAR_MAX = 2;
77 const NEAR_SHOWN = 3;
88 const NEAR_SCAN = 500;
9 /** Rows one page of the name-or-owner read takes, and the most it reads in all. */
10 const NAMED_PAGE = 200;
11 const NAMED_SCAN_MAX = 4_000;
912
10 /** Up to three repositories the viewer may read whose `owner/name` is within
11 * edit distance 2 of what was typed. Visibility is filtered by the listing
12 * before any ranking; only the first 500 visible are compared. Asked only
13 * when an address already missed: never on a page that was found. */
14 export function nearRepos(db: Database, viewer: User | undefined, owner: string, name: string): Repo[] {
15 if (!owner || !name) return [];
16 const asked = `${owner}/${name.replace(/\.git$/, "")}`.toLowerCase().slice(0, 200);
13 /**
14 * Up to `limit` repositories the viewer may read that an address or a name may have meant, the
15 * one answer the 404 page, the terminal's palette and every MCP `repo` argument give: first the
16 * same name under any owner (a wrong owner, or a bare name with `owner` empty), then a near name
17 * under the owner named (a typo, a word left off), then any whose `owner/name` is within edit
18 * distance 2. Visibility is filtered before anything is ranked or counted, so the answer is the
19 * same whether a private repository by that name exists or not. Asked only when an address
20 * already missed: never on a page that was found.
21 */
22 export function nearRepos(db: Database, viewer: User | undefined, owner: string, name: string, limit = NEAR_SHOWN): Repo[] {
23 const bare = name.replace(/\.git$/, "");
24 if (!bare) return [];
25 // A signed-out miss is what scrapers send most: it reads one bounded page of public names and no
26 // more (the whole address within two letters). The wider guess is a signed-in caller's.
27 if (viewer === undefined) return owner ? addressNear(db, viewer, owner, bare, [], limit) : [];
28 const want = bare.toLowerCase();
29 const sameOwner = (r: Repo): boolean => r.ownerName.toLowerCase() === owner.toLowerCase();
30 const close = (n: string): boolean => {
31 const have = n.toLowerCase();
32 return have.includes(want) || want.includes(have) || editDistance(have, want, NEAR_MAX) <= NEAR_MAX;
33 };
34 const exact: Repo[] = [];
35 const near: Repo[] = [];
36 // A page at a time, each filtered by what the viewer reads before the next is read, so a name
37 // many owners share, or an owner with many repositories, never cuts a readable match off.
38 for (let offset = 0; offset < NAMED_SCAN_MAX && exact.length + near.length < limit; offset += NAMED_PAGE) {
39 const rows = reposByNameOrOwner(db, owner, bare, NAMED_PAGE, offset);
40 for (const r of rows) {
41 const is = r.name.toLowerCase() === want;
42 if ((is || (sameOwner(r) && close(r.name))) && canRead(db, r, viewer)) (is ? exact : near).push(r);
43 }
44 if (rows.length < NAMED_PAGE) break;
45 }
46 const named = [...exact, ...near];
47 if (named.length >= limit || !owner) return named.slice(0, limit);
48 return addressNear(db, viewer, owner, bare, named, limit);
49 }
50
51 /**
52 * After `named`, the repositories the viewer reads whose whole `owner/name` is within two letters.
53 */
54 function addressNear(db: Database, viewer: User | undefined, owner: string, bare: string, named: Repo[], limit: number): Repo[] {
55 const asked = `${owner}/${bare}`.toLowerCase().slice(0, 200);
1756 const found: { repo: Repo; d: number }[] = [];
1857 let cursor: string | undefined;
1958 for (let seen = 0; seen < NEAR_SCAN; ) {
@@ -29,8 +68,7 @@ export function nearRepos(db: Database, viewer: User | undefined, owner: string,
2968 if (batch.length < 200) break;
3069 cursor = batch[batch.length - 1]!.id;
3170 }
32 return found
33 .sort((x, y) => x.d - y.d)
34 .slice(0, NEAR_SHOWN)
35 .map((f) => f.repo);
71 const have = new Set(named.map((r) => r.id));
72 const rest = found.sort((x, y) => x.d - y.d).map((f) => f.repo).filter((r) => !have.has(r.id));
73 return [...named, ...rest].slice(0, limit);
3674 }
src/core/repos.ts +15
@@ -1382,6 +1382,21 @@ export function ownerInStanding(db: Database, repo: Repo): boolean {
13821382 );
13831383 }
13841384
1385 /**
1386 * Repositories named `name` under any owner, or any repository of `owner` (empty: none), a page
1387 * at a time, exact names first: what `nearRepos` (`core/near_repos.ts`) reads. No access is
1388 * checked here; the caller filters by what the viewer reads.
1389 */
1390 export function reposByNameOrOwner(db: Database, owner: string, name: string, limit: number, offset: number): Repo[] {
1391 return db
1392 .query<RepoRow, [string, string, number, number]>(
1393 `${SELECT} WHERE repo.name = ?2 COLLATE NOCASE OR (?1 <> '' AND user.username = ?1 COLLATE NOCASE)
1394 ORDER BY repo.name = ?2 COLLATE NOCASE DESC, repo.id LIMIT ?3 OFFSET ?4`,
1395 )
1396 .all(owner, name, limit, offset)
1397 .map(toRepo);
1398 }
1399
13851400 export function canRead(
13861401 db: Database,
13871402 repo: Repo,
src/http/mcp/shared.ts +30 −9
@@ -4,6 +4,7 @@ import { blockedFields, blockedText, type Blocked } from "../../kernel/blocked.t
44 import { mayView } from "../../core/sealed.ts";
55 import { getIssue, LIST_LIMIT_MAX } from "../../core/issues.ts";
66 import { canRead, canWrite, getRepo, type Repo } from "../../core/repos.ts";
7 import { nearRepos } from "../../core/near_repos.ts";
78 import { scopeAllows } from "../../core/tokens.ts";
89 import { getUserByName, type User } from "../../core/users.ts";
910 import { applyFleetIds, previewFleetIds } from "../../actions/fleet.ts";
@@ -387,17 +388,37 @@ export const REPO_ARG = { type: "string" } as const;
387388
388389 /** A repository the caller may read, by `owner/name`; a wrong one is answered with that form. */
389390 export function repoArg(ctx: Ctx, user: User | undefined, args: Args): Repo | Answer {
390 const [owner, name, ...rest] = str(args["repo"]).split("/");
391 const repo =
392 owner && name && rest.length === 0
393 ? getRepo(ctx.app.db, owner, name)
394 : undefined;
395 // One answer for "no such repository" and "not yours to see".
396 return repo !== undefined && canRead(ctx.app.db, repo, user)
397 ? repo
398 : bad("not_found", "no such app or repository (owner/name)");
391 const [owner, name, ...rest] = str(args["repo"]).trim().replace(/^@/, "").split("/");
392 const named = (r: Repo): string => `${r.ownerName}/${r.name}`;
393 // A bare name, as a voice says it ("voxel"): the caller's own repository by that name, else the
394 // one by that name the caller reads.
395 if (owner && name === undefined) {
396 const own = user === undefined ? undefined : getRepo(ctx.app.db, user.username, owner);
outdated

Prefer the caller's own repository here: if exactly one of mine has ownerName equal to the caller's username, return it. Only report ambiguity otherwise.

397 if (own !== undefined && canRead(ctx.app.db, own, user)) return own;
398 const same = (r: Repo): boolean => r.name.toLowerCase() === owner.toLowerCase();
399 const found = nearRepos(ctx.app.db, user, "", owner, 4).filter(same);
400 if (found.length === 1) return found[0]!;
401 return bad(
402 "not_found",
403 found.length === 0
404 ? `${MISS}: no repository you can read has that name alone; say it as owner/name`
405 : `${MISS}: ${owner} names more than one you can read (${found.map(named).join(", ")}); say which`,
406 );
407 }
408 const repo = owner && name && rest.length === 0 ? getRepo(ctx.app.db, owner, name) : undefined;
409 if (repo !== undefined && canRead(ctx.app.db, repo, user)) return repo;
410 // One answer for "no such repository" and "not yours to see": it says both, and a guess names
411 // only what the caller reads, so it is the same either way.
412 const meant = owner && name && rest.length === 0 ? nearRepos(ctx.app.db, user, owner, name) : [];
413 const guess = meant.length === 0 ? "" : `. Did you mean ${meant.map(named).join(" or ")}?`;
414 return bad("not_found", `${MISS}: ${NOT_READ}${guess}`);
399415 }
400416
417 /** How every miss of a repository argument begins. */
418 const MISS = "no such app or repository (owner/name)";
419 /** Why, in words that are the same for a hidden repository and a missing one. */
420 const NOT_READ = "none by that name that you can read; it does not exist, or it is private and not shared with you";
421
401422 export const MAX_ARCHIVE_REPOS = 50;
402423
403424 /** `archive` over `repos`: the fleet's own operation, each row's outcome and the id to undo. */
test/did-you-mean.test.ts +15 −3
@@ -25,8 +25,13 @@ const FOUND_QUERIES = 36;
2525 const BARE_404_QUERIES = 0; // a 404 with no owner/name to suggest from
2626 // The same 404 for a mistyped repository (6 since #15940). One of them is the noindex lookup that
2727 // answerGet makes for every /:owner/:name route before its handler runs (1e71740ab, #14305,
28 // src/http/archived_noindex.ts); on a missing repository it finds nothing.
29 const NEAR_404_QUERIES = 6;
28 // src/http/archived_noindex.ts); on a missing repository it finds nothing. Four more since the
29 // shared lookup also reads the same name under any owner and near names under the owner named
30 // (#16462): one page of names, and the read checks on the owner's repositories it finds.
31 const NEAR_404_QUERIES = 10;
32 // The same 404 signed out: the whole address against one bounded page of public names, as before
33 // the wider guess, which is a signed-in caller's alone.
34 const ANON_NEAR_404_QUERIES = 2;
3035 const cookies: Record<string, string> = {};
3136
3237 beforeAll(async () => {
@@ -95,7 +100,7 @@ test("a private repository is suggested to its owner and never to a stranger or
95100 });
96101
97102 /** Every statement a request makes, whichever way it is prepared. */
98 async function queriesFor(path: string, who: string): Promise<number> {
103 async function queriesFor(path: string, who?: string): Promise<number> {
99104 let n = 0;
100105 const db = app.db as unknown as Record<string, unknown>;
101106 const saved = { query: db.query, prepare: db.prepare };
@@ -125,6 +130,13 @@ test("the suggestion costs queries on a 404 only: the 200 path's count is pinned
125130 expect(missed).toBeGreaterThan(bare);
126131 });
127132
133 test("a signed-out miss stays as cheap as it was: one bounded read of public names, nothing wider", async () => {
134 await get("/trevato/forge"); // warm
135 // Scrapers send these most (#11120 public scales): pinned at the count before the wider guess.
136 expect(await queriesFor("/trevato/forg")).toBe(ANON_NEAR_404_QUERIES);
137 expect(ANON_NEAR_404_QUERIES).toBeLessThan(NEAR_404_QUERIES);
138 });
139
128140 test("the shared lookup, which the terminal's owner/name prompt uses, hides what the viewer cannot read", async () => {
129141 const { nearRepos } = await import("../src/core/near_repos.ts");
130142 const { getUserByName } = await import("../src/core/users.ts");
test/mcp-pins.test.ts +2 −1
@@ -113,7 +113,8 @@ describe("MCP pins", () => {
113113 });
114114 // Once it is off, it answers like a repository that does not exist.
115115 const gone = (await tool(bobRw, { action: "unpin", repo: "alice/later" })).error;
116 expect(gone).toBe((await tool(bobRw, { action: "unpin", repo: "alice/nope" })).error);
116 // A name with no near repository the caller reads: "did you mean" names only what they read.
117 expect(gone).toBe((await tool(bobRw, { action: "unpin", repo: "alice/qqqqqqqq" })).error);
117118 expect(gone).toContain("not_found");
118119 });
119120
test/mcp-repo-names.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * A repository named the way a voice says it (#16462, #16465): a bare name the caller reads under
3 * one owner is that repository; a wrong owner or a near miss is told "did you mean", naming only
4 * what the caller reads; and a miss says why in words that are the same whether a private
5 * repository by that name exists or not.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19 let dir: string, app: App, servers: Servers;
20 let trevato: User, ben: User, carol: User;
21 let id = 1;
22
23 const person = async (username: string, isAdmin = false): Promise<User> => {
24 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.test`, password: "a-good-passphrase", isAdmin });
25 if (!made.ok) throw new Error(made.error);
26 return made.value;
27 };
28 const repo = async (owner: User, name: string, visibility: "public" | "private") => {
29 const made = await createRepo(app, owner, { name, visibility });
30 if (!made.ok) throw new Error(String(made.error));
31 };
32
33 /** The text of one `repo` call by `who`. */
34 const call = async (who: User, name: string): Promise<string> => {
35 const res = await fetch(`${servers.url}/mcp`, {
36 method: "POST",
37 headers: {
38 authorization: `Bearer ${createToken(app.db, who.id, "t", "ro").token}`,
39 "content-type": "application/json",
40 accept: "application/json, text/event-stream",
41 },
42 body: JSON.stringify({ jsonrpc: "2.0", id: id++, method: "tools/call", params: { name: "repo", arguments: { repo: name } } }),
43 });
44 const body = (await res.json()) as { result: { content: { text: string }[] } };
45 return body.result.content.map((c) => c.text).join("\n");
46 };
47
48 beforeAll(async () => {
49 dir = await mkdtemp(join(tmpdir(), "forge-repo-names-"));
50 app = createApp({ dataDir: dir, port: 0 });
51 trevato = await person("trevato", true);
52 ben = await person("ben", true);
53 carol = await person("carol");
54 // ben is an admin only to make repositories; he reads as a stranger once demoted below.
55 await repo(trevato, "voxel", "public");
56 await repo(trevato, "car-duel-2", "public");
57 await repo(trevato, "vault", "private");
58 await repo(trevato, "vaultx", "public");
59 await repo(ben, "garden", "public");
60 await repo(trevato, "garden", "public");
61 app.db.run("UPDATE user SET is_admin = 0 WHERE id = ?1", [ben.id]);
62 ben = { ...ben, isAdmin: false };
63 servers = await serve(app);
64 });
65 afterAll(async () => {
66 await servers.stop();
67 app.close();
68 await rm(dir, { recursive: true, force: true });
69 });
70
71 test("a bare name is the caller's own first, else the one they read; two others are both named", async () => {
72 expect(await call(ben, "voxel")).toContain('"repo":"trevato/voxel"');
73 // ben owns ben/garden: his wins over trevato/garden.
74 expect(await call(ben, "garden")).toContain('"repo":"ben/garden"');
75 // carol owns neither: both are named back to choose from.
76 const two = await call(carol, "garden");
77 expect(two).toContain("garden names more than one you can read (");
78 expect([two.includes("ben/garden"), two.includes("trevato/garden")]).toEqual([true, true]);
79 // An @ before a name and spaces around it are the same name.
80 expect(await call(ben, " @trevato/voxel ")).toContain('"repo":"trevato/voxel"');
81 expect(await call(ben, " voxel ")).toContain('"repo":"trevato/voxel"');
82 expect(await call(ben, "nothing-here")).toContain("no repository you can read has that name alone");
83 });
84
85 test("a wrong owner or a near miss is told what was meant, never a repository the caller cannot read", async () => {
86 expect(await call(ben, "ben/voxel")).toContain("Did you mean trevato/voxel?");
87 expect(await call(ben, "trevato/car-duel")).toContain("Did you mean trevato/car-duel-2?");
88 // A private one ben cannot read is never offered, and its owner is told it.
89 expect(await call(ben, "trevato/vaul")).not.toMatch(/trevato\/vault(?!x)/);
90 expect(await call(trevato, "trevato/vaul")).toContain("Did you mean trevato/vault or trevato/vaultx?");
91 // Beside a private lookalike, the public near name alone is offered to ben.
92 const near = await call(ben, "trevato/vaulty");
93 expect(near).toContain("Did you mean trevato/vaultx?");
94 expect(near).not.toMatch(/trevato\/vault(?!x)/);
95 });
96
97 test("a miss says why in the same words whether a private repository by that name exists or not", async () => {
98 const hidden = await call(ben, "trevato/vault");
99 const missing = await call(ben, "trevato/vaulz");
100 expect(hidden).toContain("it does not exist, or it is private and not shared with you");
101 // Both near the public vaultx, both are offered it, and nothing else tells them apart.
102 expect(hidden).toContain("Did you mean trevato/vaultx?");
103 expect(hidden).toBe(missing);
104 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs