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

Every repository and app page says who can see it in a sentence that names the people, and the API and MCP say the same #977

Closed opened this
Closed without merging

scout/forge:scout/809-every-repository-and-app-page-says-who-c → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +403 −4
docs/MCP.md +1 −1
@@ -27,7 +27,7 @@ for a tunnel and a forge that sleeps.
2727
2828 | tool | does | writes |
2929 | -------------- | ------------------------------------------------------------------------------------------------- | ------ |
30 | `apps` | the apps you can see: live or not, where served, how each runs itself, what is working | |
30 | `apps` | the apps you can see: live or not, where served, how each runs itself, what is working, and `audience` (`{ level, sentence }`: who can see it, in words, the same as `GET /api/v1/repos/:owner/:name`; counts, never names) | |
3131 | `tell` | a sentence becomes an issue, a builder is picked, a run starts on the crew's next tick | yes |
3232 | `say` | speak on an issue or a pull; a working builder hears it as its next step | yes |
3333 | `edit` | a new title or body for an issue or a pull: its author's, or a writer's; an agent edits only what it wrote | yes |
src/core/audience.ts added +177
@@ -0,0 +1,177 @@
1 /**
2 * Who can see a repository, and an app, in one sentence that names the
3 * people (#809). The Private/Public badge says a word; this says whose.
4 *
5 * `audienceOf` is pure: plain facts in, words out, so the page, the API and
6 * the MCP cannot phrase it differently. `audienceFor` reads the facts, and
7 * reads them from the same rule `REPO_VISIBLE` / `REPO_WRITABLE` enforce —
8 * the owner, the teams of the owning org by permission, the crew — so a
9 * count cannot say someone's work is safer than the rule makes it. Counts
10 * only: a reader is told how many people can change a repository, never
11 * who, and an org's private members are never listed.
12 */
13
14 import type { Database } from "bun:sqlite";
15 import { getAppByRepo, type AppRecord } from "./apps.ts";
16 import { isOrgMember } from "./orgs.ts";
17 import type { Repo } from "./repos.ts";
18 import type { User } from "./users.ts";
19
20 export interface AudienceFacts {
21 readonly visibility: "public" | "private";
22 readonly ownerKind: "user" | "org";
23 readonly owner: string;
24 /** The viewer is one of the people counted: the owner, or an org member. */
25 readonly you: boolean;
26 /** People who can change the repository (an owner counts as one). */
27 readonly writers: number;
28 /** People who can read it and cannot change it. */
29 readonly readers: number;
30 /** Whether any agent works here. */
31 readonly crew: boolean;
32 /** Present when the repository is an app. */
33 readonly app?: { readonly access: "public" | "private"; readonly named: number };
34 }
35
36 export interface Audience {
37 readonly level: "public" | "private";
38 readonly sentence: string;
39 }
40
41 const plural = (n: number, one: string, many: string): string =>
42 `${String(n)} ${n === 1 ? one : many}`;
43
44 function list(parts: readonly string[]): string {
45 if (parts.length <= 1) return parts.join("");
46 return `${parts.slice(0, -1).join(", ")}${parts.length > 2 ? "," : ""} and ${parts[parts.length - 1]!}`;
47 }
48
49 /** "Private: …" without its lead, so an app's sentence can carry it. */
50 function privateWho(f: AudienceFacts): string {
51 const others = Math.max(0, f.writers + f.readers - (f.you ? 1 : 0));
52 const parts: string[] = [];
53 if (f.you) parts.push("you");
54 if (others > 0 && !f.you && f.ownerKind === "user") parts.push(f.owner);
55 else if (others > 0)
56 parts.push(
57 f.ownerKind === "org"
58 ? `${plural(others, "person", "people")} in ${f.owner}`
59 : plural(others, "other person", "other people"),
60 );
61 else if (!f.you) parts.push(f.owner);
62 if (f.crew) parts.push("the crew");
63 const only = others === 0 || f.ownerKind === "user" ? "only " : "";
64 return `${only}${list(parts)}`;
65 }
66
67 function publicWho(f: AudienceFacts): string {
68 const change =
69 f.writers > 0
70 ? `; ${plural(f.writers, "person", "people")} can change it`
71 : "";
72 return `anyone on the internet can read this${change}`;
73 }
74
75 export function audienceOf(f: AudienceFacts): Audience {
76 const repo =
77 f.visibility === "public"
78 ? `Public: ${publicWho(f)}.`
79 : `Private: ${privateWho(f)}.`;
80 if (f.app === undefined || f.app.access === f.visibility && f.visibility === "public")
81 return { level: f.visibility, sentence: repo };
82 if (f.app.access === "public")
83 return {
84 level: "public",
85 sentence: `${repo} The app is open to anyone.`,
86 };
87 const who = list([
88 ...(f.writers > 0
89 ? [
90 f.writers === 1
91 ? "the person who can change it"
92 : `the ${String(f.writers)} people who can change it`,
93 ]
94 : []),
95 ...(f.crew ? ["the crew"] : []),
96 ...(f.app.named > 0 ? [`${plural(f.app.named, "named person", "named people")}`] : []),
97 ]);
98 const app = `the app answers only to ${who === "" ? "nobody" : who}`;
99 return {
100 level: "private",
101 sentence:
102 f.visibility === "public"
103 ? `The code is public; ${app}.`
104 : `${repo} The ${app.slice(4)}.`,
105 };
106 }
107
108 /** The facts for `repo`, in at most four indexed reads. */
109 export function audienceFacts(
110 db: Database,
111 repo: Repo,
112 viewer: User | undefined,
113 app: AppRecord | undefined = getAppByRepo(db, repo.id),
114 ): AudienceFacts {
115 const org =
116 db
117 .query<{ kind: string }, [string]>(`SELECT kind FROM user WHERE id = ?1`)
118 .get(repo.ownerId)?.kind === "org";
119 let writers = 1;
120 let readers = 0;
121 if (org) {
122 // The teams of the owning org: write and admin change, any team reads.
123 const row = db
124 .query<{ w: number; a: number }, [string]>(
125 `SELECT COUNT(DISTINCT CASE WHEN team.permission IN ('write','admin')
126 THEN team_member.user_id END) AS w,
127 COUNT(DISTINCT team_member.user_id) AS a
128 FROM team JOIN team_member ON team_member.team_id = team.id
129 WHERE team.org_id = ?1`,
130 )
131 .get(repo.ownerId);
132 writers = row?.w ?? 0;
133 readers = (row?.a ?? 0) - writers;
134 }
135 const crew =
136 db
137 .query<{ n: number }, [string]>(
138 `SELECT 1 AS n FROM repo_crew JOIN user ON user.id = repo_crew.user_id
139 WHERE repo_crew.repo_id = ?1 AND user.is_agent = 1 LIMIT 1`,
140 )
141 .get(repo.id) !== null;
142 const named =
143 app === undefined
144 ? 0
145 : (db
146 .query<{ n: number }, [string]>(
147 `SELECT COUNT(*) AS n FROM app_member
148 JOIN user ON user.id = app_member.user_id
149 WHERE app_member.app_id = ?1 AND user.suspended_at IS NULL
150 AND user.removed_at IS NULL`,
151 )
152 .get(app.id)?.n ?? 0);
153 return {
154 visibility: repo.visibility,
155 ownerKind: org ? "org" : "user",
156 owner: repo.ownerName,
157 you:
158 viewer !== undefined &&
159 (org ? isOrgMember(db, repo.ownerId, viewer.id) : viewer.id === repo.ownerId),
160 writers,
161 readers,
162 crew,
163 ...(app === undefined
164 ? {}
165 : { app: { access: app.access, named } }),
166 };
167 }
168
169 /** The sentence for this viewer: what the page, the API and the MCP say. */
170 export function audienceFor(
171 db: Database,
172 repo: Repo,
173 viewer: User | undefined,
174 app?: AppRecord,
175 ): Audience {
176 return audienceOf(audienceFacts(db, repo, viewer, app));
177 }
src/http/api.ts +7 −1
@@ -123,6 +123,7 @@ import {
123123 updateProfile,
124124 } from "../actions/users.ts";
125125 import { listEvents } from "../core/events.ts";
126 import { audienceFor } from "../core/audience.ts";
126127 import { audienceFilter } from "../core/event_audience.ts";
127128 import {
128129 forkParentFor,
@@ -1580,7 +1581,12 @@ export function apiRoutes(router: Router<Handler>): void {
15801581
15811582 router.add("GET", "/api/v1/repos/:owner/:name", (ctx) => {
15821583 const repo = loadRepo(ctx);
1583 return repo ? json(repoJson(ctx, repo)) : notFound();
1584 return repo
1585 ? json({
1586 ...repoJson(ctx, repo),
1587 audience: audienceFor(ctx.app.db, repo, ctx.auth.user),
1588 })
1589 : notFound();
15841590 });
15851591
15861592 router.add("PATCH", "/api/v1/repos/:owner/:name", async (ctx) => {
src/http/mcp.ts +2
@@ -60,6 +60,7 @@ import { waitsForPerson } from "../crew/review.ts";
6060 import { getPull } from "../core/pulls.ts";
6161 import { repoGraph } from "../core/dependencies.ts";
6262 import { pillarView } from "../core/pillars.ts";
63 import { audienceFor } from "../core/audience.ts";
6364 import { getAppByRepo } from "../core/apps.ts";
6465 import {
6566 canRead,
@@ -234,6 +235,7 @@ const TOOLS: readonly Tool[] = [
234235 url: runtime?.urlFor(record, "production") ?? null,
235236 autonomy: repo.autonomy,
236237 working: active.filter((r) => r.repoId === repo.id).length,
238 audience: audienceFor(ctx.app.db, repo, user, record),
237239 };
238240 }),
239241 );
src/web/chrome.ts +19 −2
@@ -12,6 +12,7 @@ import { sshCommand } from "../ssh/command.ts";
1212 import { mayDirectCrew } from "../crew/direct.ts";
1313 import { mayReadRuns } from "../actions/runs.ts";
1414 import { getAppByRepo } from "../core/apps.ts";
15 import { audienceFor } from "../core/audience.ts";
1516 import { edgeLoginUrl } from "../http/edge.ts";
1617 import {
1718 canAdmin,
@@ -165,8 +166,9 @@ export function scopeHeader(
165166 ? undefined
166167 : forkParentFor(ctx.app.db, repo, ctx.auth.user);
167168
168 const isApp =
169 repo !== undefined && getAppByRepo(ctx.app.db, repo.id) !== undefined;
169 const appRecord =
170 repo === undefined ? undefined : getAppByRepo(ctx.app.db, repo.id);
171 const isApp = appRecord !== undefined;
170172 // An app speaks the studio's words (told, changes), a plain repository
171173 // git's (issues, pulls, commits, branches) — for every viewer (#603).
172174 const studio = isApp;
@@ -291,6 +293,20 @@ export function scopeHeader(
291293 shortcut: "g s",
292294 });
293295
296 // Who can see it, in words (#809): beside the badge, one line, the whole
297 // sentence in `title`. A writer's link goes where it is changed.
298 const said =
299 repo === undefined
300 ? undefined
301 : audienceFor(ctx.app.db, repo, ctx.auth.user, appRecord).sentence;
302 const audienceLine =
303 said === undefined
304 ? null
305 : admin
306 ? html`<a class="audience" href="${base}/settings" title="${said}"
307 >${said}</a
308 >`
309 : html`<span class="audience" title="${said}">${said}</span>`;
294310 const owner = facts.owner;
295311 const actions = options.actions ?? browseActions(scope);
296312 const title = html`${icon(
@@ -309,6 +325,7 @@ export function scopeHeader(
309325 ${facts.visibility === "private"
310326 ? badge("Private", { icon: "lock", variant: "secondary" })
311327 : badge("Public", { variant: "secondary" })}
328 ${audienceLine}
312329 ${actions.text.trim() !== ""
313330 ? html`<span class="repo-actions">${actions}</span>`
314331 : null}`;
src/web/style/content.ts +2
@@ -222,6 +222,8 @@ a.origin-chip:hover { border-color: var(--border-strong); color: var(--fg); }
222222
223223 .bar > .device-code { flex: 1 1 auto; }
224224
225 .audience { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; color: var(--muted-fg); }
226 a.audience:hover { color: var(--fg); }
225227 .repo-actions { display: flex; align-items: center; gap: 6px; margin-left: auto; }
226228
227229 .repo-layout { display: grid; gap: 16px; margin-top: 16px; align-items: start; }
test/audience.test.ts added +195
@@ -0,0 +1,195 @@
1 /**
2 * Who can see a repository, in a sentence that names the people (#809). The
3 * words are one pure function; the counts come from the rule the forge
4 * enforces (`REPO_VISIBLE` / `REPO_WRITABLE`), checked here user by user.
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 { createAgent } from "../src/actions/crew.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { addCrew } from "../src/core/agents.ts";
14 import { audienceFor, audienceOf, type AudienceFacts } from "../src/core/audience.ts";
15 import { createApp as makeApp } from "../src/core/apps.ts";
16 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { REPO_VISIBLE, REPO_WRITABLE } from "../src/core/visibility.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21
22 const base: AudienceFacts = {
23 visibility: "private",
24 ownerKind: "user",
25 owner: "olive",
26 you: true,
27 writers: 1,
28 readers: 0,
29 crew: true,
30 };
31
32 describe("the sentence", () => {
33 test("private, personal", () => {
34 expect(audienceOf(base)).toEqual({
35 level: "private",
36 sentence: "Private: only you and the crew.",
37 });
38 expect(audienceOf({ ...base, you: false, crew: false }).sentence).toBe(
39 "Private: only olive.",
40 );
41 });
42 test("private, org", () => {
43 const org = { ...base, ownerKind: "org", owner: "acme", writers: 2, readers: 2 } as const;
44 expect(audienceOf(org).sentence).toBe(
45 "Private: you, 3 people in acme, and the crew.",
46 );
47 expect(audienceOf({ ...org, you: false }).sentence).toBe(
48 "Private: 4 people in acme and the crew.",
49 );
50 });
51 test("public", () => {
52 expect(
53 audienceOf({ ...base, visibility: "public", writers: 2, crew: false }),
54 ).toEqual({
55 level: "public",
56 sentence: "Public: anyone on the internet can read this; 2 people can change it.",
57 });
58 });
59 test("a private app on a public repository", () => {
60 const f: AudienceFacts = {
61 ...base,
62 visibility: "public",
63 app: { access: "private", named: 0 },
64 };
65 const a = audienceOf(f);
66 expect(a.level).toBe("private");
67 expect(a.sentence).toBe(
68 "The code is public; the app answers only to the person who can change it and the crew.",
69 );
70 expect(audienceOf({ ...f, app: { access: "private", named: 2 } }).sentence).toContain(
71 "2 named people",
72 );
73 });
74 });
75
76 describe("the counts are the enforced rule", () => {
77 let dataDir: string;
78 let app: App;
79 let servers: Servers;
80 let olive: User;
81 let wren: User;
82 let rita: User;
83 let sam: User;
84 let acme: User;
85
86 const person = async (username: string, adminIfFirst = false) => {
87 const made = await createUser(app.db, {
88 trusted: true,
89 username,
90 email: `${username}@f.dev`,
91 password: "a-good-passphrase",
92 adminIfFirst,
93 });
94 if (!made.ok) throw new Error(made.error);
95 return made.value;
96 };
97
98 beforeAll(async () => {
99 dataDir = await mkdtemp(join(tmpdir(), "forge-audience-"));
100 app = createApp({ dataDir, port: 0 });
101 servers = await serve(app);
102 olive = await person("olive", true);
103 wren = await person("wren");
104 rita = await person("rita");
105 sam = await person("sam");
106 const org = createOrg(app.db, "acme", olive.id);
107 if (!org.ok) throw new Error(org.error);
108 acme = org.value;
109 const writers = createTeam(app.db, acme.id, "builders", "write");
110 const readers = createTeam(app.db, acme.id, "watchers", "read");
111 if (!writers.ok || !readers.ok) throw new Error("teams");
112 addTeamMember(app.db, writers.value, wren.id);
113 addTeamMember(app.db, readers.value, rita.id);
114 });
115 afterAll(async () => {
116 servers.stop();
117 app.close();
118 await rm(dataDir, { recursive: true, force: true });
119 });
120
121 test("a seeded org: a writer, a reader and an outsider", async () => {
122 const made = await createRepo(app, olive, {
123 name: "vault",
124 visibility: "private",
125 owner: "acme",
126 });
127 if (!made.ok) throw new Error(String(made.error));
128 const repo = made.value;
129
130 // Ask the enforced SQL about every person, and count what it says.
131 const can = (expr: string, who: User) =>
132 app.db
133 .query<{ n: number }, [string, string]>(
134 `SELECT COUNT(*) AS n FROM repo WHERE repo.id = ?2 AND ${expr}`,
135 )
136 .get(who.id, repo.id)!.n === 1;
137 const people = [olive, wren, rita, sam];
138 const writing = people.filter((u) => can(REPO_WRITABLE, u)).length;
139 const reading = people.filter(
140 (u) => can(REPO_VISIBLE, u) && !can(REPO_WRITABLE, u),
141 ).length;
142 expect([writing, reading]).toEqual([2, 1]);
143
144 const viewed = audienceFor(app.db, repo, olive);
145 expect(viewed.sentence).toBe("Private: you and 2 people in acme.");
146 // The same counts, as the rule gives them; the outsider is in neither.
147 expect(writing + reading - 1).toBe(2);
148
149 const outsider = audienceFor(app.db, repo, sam);
150 expect(outsider.sentence).toBe("Private: 3 people in acme.");
151
152 const agent = await createAgent(app, olive, { username: "scout", brief: "b" });
153 if (!agent.ok) throw new Error(String(agent.error));
154 addCrew(app.db, repo.id, agent.value.user.id, olive.id);
155 expect(audienceFor(app.db, repo, olive).sentence).toBe(
156 "Private: you, 2 people in acme, and the crew.",
157 );
158 });
159
160 test("the API and the MCP say the same words, and no names", async () => {
161 const made = await createRepo(app, olive, { name: "garden", visibility: "public" });
162 if (!made.ok) throw new Error(String(made.error));
163 makeApp(app.db, { repoId: made.value.id, slug: "garden", access: "private" });
164 const token = createToken(app.db, olive.id, "t", "ro").token;
165 const res = await fetch(`${servers.url}/api/v1/repos/olive/garden`, {
166 headers: { authorization: `Bearer ${token}` },
167 });
168 const body = (await res.json()) as { audience: { level: string; sentence: string } };
169 expect(body.audience).toEqual(audienceFor(app.db, made.value, olive));
170 expect(body.audience.sentence).toStartWith("The code is public; the app answers only to");
171
172 const mcp = await fetch(`${servers.url}/mcp`, {
173 method: "POST",
174 headers: {
175 authorization: `Bearer ${token}`,
176 "content-type": "application/json",
177 accept: "application/json, text/event-stream",
178 },
179 body: JSON.stringify({
180 jsonrpc: "2.0",
181 id: 1,
182 method: "tools/call",
183 params: { name: "apps", arguments: {} },
184 }),
185 });
186 expect(await mcp.text()).toContain("The code is public; the app answers only to");
187
188 // The page: a sentence beside the badge, plain text for a reader.
189 const page = await (await fetch(`${servers.url}/olive/garden`, {
190 headers: { authorization: `Bearer ${token}` },
191 })).text();
192 expect(page).toContain('class="audience"');
193 expect(page).not.toContain("wren");
194 });
195 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs