Public: anyone can read this; the crew can change it.
A repository can have contributors: they read it, enter its app and ask its crew, and the week's cap holds their runs #16357
Check · Review · Land · Live done — Landed and live in production.
talk/invite-a → main 0 commits 3 threads · 3 unresolved
23 files
changed +809
−15
docs/features/contributors.md added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Invite someone to work on an app: they ask its crew, you land | |
| 4 | --- | |
| 5 | # Working with others on an app | |
| 6 | ||
| 7 | The repository's admin invites a person as a **contributor**. A contributor reads the repository, enters its app and previews, and asks its crew for changes from their own Talk. What they ask lands as pulls the owner lands: a contributor merges nothing, changes no setting, sees no variable or webhook, opens no terminal on the app, and invites nobody. Their asks run on the owner's crew and subscription, so the week's cap holds them as it holds the crew's own work: a run passes the cap only for someone who writes the repository, and that holds for an outsider's run too. | |
| 8 | ||
| 9 | - **Talk and MCP**: `invite { repo, who }`, one confirm, makes a person with an account a contributor at once; their Talk works on the app from then on. `invite { repo, who, remove: true }` takes them off; `invite { repo }` lists who works on it (a read, never held). The repository's admin only: a contributor is told it is the admin's, anyone else gets not found. | |
| 10 | - **The terminal**: on an app's deploys screen, `W` lists who works on it; `a` invites a person by username and `d` takes the one under the cursor off, each after a confirm. | |
| 11 | - **Taking someone off** is at once: every read, app entry and crew direction asks the row on its request. | |
| 12 | ||
| 13 | Someone without an account cannot be invited yet: a one-use link for them is the next step. | |
| 14 | ||
| 15 | Proof: `test/invite-contributors.test.ts`. The rules are `core/invites.ts` and `actions/invites.ts`; the checks are `canRead`, `canEnterApp` (`core/repos.ts`), `REPO_VISIBLE` (`core/visibility.ts`) and `mayDirectCrew` (`crew/direct.ts`). |
src/actions/invites.ts +83 −1
| @@ -4,7 +4,19 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import type { App } from "../app.ts"; |
| 7 | import { listInvites, mintInvite, parseDays, revokeInvite, type Invite } from "../core/invites.ts"; | |
| 7 | import { | |
| 8 | addContributor, | |
| 9 | listContributors, | |
| 10 | listInvites, | |
| 11 | mintInvite, | |
| 12 | parseDays, | |
| 13 | removeContributor, | |
| 14 | revokeInvite, | |
| 15 | type Invite, | |
| 16 | } from "../core/invites.ts"; | |
| 17 | import { canRead, canWrite, type Repo } from "../core/repos.ts"; | |
| 18 | import { getUserByName } from "../core/users.ts"; | |
| 19 | import { requireRepoAdmin, type AccessError } from "./access.ts"; | |
| 8 | 20 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 9 | 21 | import type { User } from "../core/users.ts"; |
| 10 | 22 | |
| @@ -51,3 +63,73 @@ export function inviteExpiryLine(when: string): string { | ||
| 51 | 63 | export function inviteExpiredLine(from: string | undefined): string { |
| 52 | 64 | return `This link has expired. Ask ${from ?? "whoever sent it"} for a new one.`; |
| 53 | 65 | } |
| 66 | ||
| 67 | /** | |
| 68 | * Working with others on an app (the owner: "collaboration should feel native"). The repository's | |
| 69 | * admin makes a person with an account a contributor: they read the repository, enter its app and | |
| 70 | * previews, and ask its crew for changes from their own Talk; what they ask lands as pulls the | |
| 71 | * owner lands, on the owner's crew and subscription. A contributor lands nothing, changes no | |
| 72 | * setting and invites nobody. Every check reads the row on the request, so taking someone off is | |
| 73 | * at once. | |
| 74 | */ | |
| 75 | ||
| 76 | export type ContributorError = | |
| 77 | | AccessError | |
| 78 | /** No account by that name. */ | |
| 79 | | "no_such_person" | |
| 80 | /** An agent or an organization: only a person contributes. */ | |
| 81 | | "not_a_person" | |
| 82 | /** They already write here. */ | |
| 83 | | "already_writes" | |
| 84 | | "no_such_contributor"; | |
| 85 | ||
| 86 | /** The refusals, in the words every door says. */ | |
| 87 | export const CONTRIBUTOR_WORDS: Record<Exclude<ContributorError, AccessError>, string> = { | |
| 88 | no_such_person: "Nobody here has that username: they need an account on this forge first.", | |
| 89 | not_a_person: "Only a person is invited as a contributor, never an agent or an organization.", | |
| 90 | already_writes: "They already write here: a contributor is someone who does not.", | |
| 91 | no_such_contributor: "They are not a contributor here.", | |
| 92 | }; | |
| 93 | ||
| 94 | /** | |
| 95 | * The repository's admin, or the refusal: `forbidden` to someone who reads it, else `not_found`. | |
| 96 | */ | |
| 97 | function adminOf(app: App, actor: User | undefined, repo: Repo): Result<User, AccessError> { | |
| 98 | const admin = requireRepoAdmin(app, actor, repo); | |
| 99 | if (admin.ok) return admin.value.kind === "user" ? admin : err("forbidden"); | |
| 100 | return actor !== undefined && canRead(app.db, repo, actor) ? err("forbidden") : admin; | |
| 101 | } | |
| 102 | ||
| 103 | /** Make the person `who` names a contributor to `repo`; `added: false` when they already were. */ | |
| 104 | export function inviteContributor( | |
| 105 | app: App, | |
| 106 | actor: User | undefined, | |
| 107 | repo: Repo, | |
| 108 | who: string, | |
| 109 | ): Result<{ username: string; added: boolean }, ContributorError> { | |
| 110 | const admin = adminOf(app, actor, repo); | |
| 111 | if (!admin.ok) return admin; | |
| 112 | const person = getUserByName(app.db, who.trim().replace(/^@/, "")); | |
| 113 | if (person === undefined) return err("no_such_person"); | |
| 114 | if (person.kind !== "user") return err("not_a_person"); | |
| 115 | if (canWrite(app.db, repo, person)) return err("already_writes"); | |
| 116 | if (!addContributor(app.db, repo.id, person.id, admin.value.id)) return ok({ username: person.username, added: false }); | |
| 117 | app.bus.append({ kind: "repo.contributor_added", repoId: repo.id, actorId: admin.value.id, payload: { username: person.username } }); | |
| 118 | return ok({ username: person.username, added: true }); | |
| 119 | } | |
| 120 | ||
| 121 | /** Who works on `repo` as a contributor: its admin's to read. */ | |
| 122 | export function repoContributors(app: App, actor: User | undefined, repo: Repo): Result<ReturnType<typeof listContributors>, AccessError> { | |
| 123 | const admin = adminOf(app, actor, repo); | |
| 124 | return admin.ok ? ok(listContributors(app.db, repo.id)) : admin; | |
| 125 | } | |
| 126 | ||
| 127 | /** Take `username` off `repo`: their next request reads, enters and directs nothing here. */ | |
| 128 | export function removeContributorFrom(app: App, actor: User | undefined, repo: Repo, username: string): Result<void, ContributorError> { | |
| 129 | const admin = adminOf(app, actor, repo); | |
| 130 | if (!admin.ok) return admin; | |
| 131 | const person = getUserByName(app.db, username.trim().replace(/^@/, "")); | |
| 132 | if (person === undefined || !removeContributor(app.db, repo.id, person.id)) return err("no_such_contributor"); | |
| 133 | app.bus.append({ kind: "repo.contributor_removed", repoId: repo.id, actorId: admin.value.id, payload: { username: person.username } }); | |
| 134 | return ok(undefined); | |
| 135 | } |
src/actions/issues.ts +7 −4
| @@ -55,7 +55,7 @@ import { | ||
| 55 | 55 | } from "../core/issues.ts"; |
| 56 | 56 | import { isStructural, pillarsOf } from "../core/pillars.ts"; |
| 57 | 57 | import { closesFromBody, getPull } from "../core/pulls.ts"; |
| 58 | import { canRead, canWrite, type Repo } from "../core/repos.ts"; | |
| 58 | import { canRead, canWrite, contributes, type Repo } from "../core/repos.ts"; | |
| 59 | 59 | import { getUserById, type User } from "../core/users.ts"; |
| 60 | 60 | import { personActing } from "../core/acting_via.ts"; |
| 61 | 61 | import { |
| @@ -366,7 +366,10 @@ export function assignIssue( | ||
| 366 | 366 | Issue, |
| 367 | 367 | AccessError | "assignee_cannot_read" | "agent_not_on_crew" | "unverified" | "not_member" | "archived" |
| 368 | 368 | > { |
| 369 | const writer = requireWriter(app, actor, repo); | |
| 369 | // A contributor (`core/invites.ts`) directs the crew: it hands work to an agent on it, and | |
| 370 | // nothing else (no person, no unassigning). | |
| 371 | const handing = actor !== undefined && assignee?.kind === "agent" && contributes(app.db, repo, actor); | |
| 372 | const writer = handing ? ok(actor) : requireWriter(app, actor, repo); | |
| 370 | 373 | if (!writer.ok) return writer; |
| 371 | 374 | if (issue.repoId !== repo.id) return err("not_found"); |
| 372 | 375 | // Assigning an agent starts a run that costs money; only a person may |
| @@ -382,8 +385,8 @@ export function assignIssue( | ||
| 382 | 385 | // A run costs: only a proven account may start one. |
| 383 | 386 | if (assignee.kind === "agent" && !requireVerified(app, writer.value).ok) |
| 384 | 387 | return err("unverified"); |
| 385 | // ...and only a member's allowance pays for it. | |
| 386 | if (assignee.kind === "agent" && !requireAbility(app, writer.value, "run_crew").ok) | |
| 388 | // ...and only a member's allowance pays for it; a contributor's asks are the owner's to pay. | |
| 389 | if (assignee.kind === "agent" && !handing && !requireAbility(app, writer.value, "run_crew").ok) | |
| 387 | 390 | return err("not_member"); |
| 388 | 391 | // Assigning an agent starts a run, and an archived repository starts none. |
| 389 | 392 | if (assignee.kind === "agent" && repo.archivedAt !== null) return err("archived"); |
src/core/event_audience.ts +2
| @@ -277,6 +277,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 277 | 277 | kind.startsWith("keeper_") || |
| 278 | 278 | kind === "forge_down" || |
| 279 | 279 | kind === "forge_up" || |
| 280 | // Who works on a repository as a contributor is its admins' to hear (`actions/invites.ts`). | |
| 281 | kind.startsWith("repo.contributor_") || | |
| 280 | 282 | // A repository's monthly spend cap, set or cleared, is its admins' (`actions/wallet.ts`). |
| 281 | 283 | kind === "wallet.cap" || |
| 282 | 284 | // A wallet under a tenth of its cap, once a month, is theirs to hear first (`core/wallet.ts`). |
src/core/invites.ts +36
| @@ -150,3 +150,39 @@ export function inviteByToken( | ||
| 150 | 150 | const from = db.query<{ username: string }, [string]>("SELECT username FROM user WHERE id = ?1").get(row.created_by); |
| 151 | 151 | return { invite: view(row, now), from: from?.username }; |
| 152 | 152 | } |
| 153 | ||
| 154 | /** | |
| 155 | * Whether `userId` is a contributor to the repository: read on every request, so removal is at | |
| 156 | * once. | |
| 157 | */ | |
| 158 | export function isContributor(db: Database, repoId: string, userId: string): boolean { | |
| 159 | return db.query("SELECT 1 FROM repo_contributor WHERE repo_id = ?1 AND user_id = ?2").get(repoId, userId) !== null; | |
| 160 | } | |
| 161 | ||
| 162 | /** Make `userId` a contributor; false when they already were. */ | |
| 163 | export function addContributor(db: Database, repoId: string, userId: string, byId: string, now: number = Date.now()): boolean { | |
| 164 | return ( | |
| 165 | db | |
| 166 | .query("INSERT OR IGNORE INTO repo_contributor (repo_id, user_id, by_id, at) VALUES (?1, ?2, ?3, ?4)") | |
| 167 | .run(repoId, userId, byId, new Date(now).toISOString()).changes === 1 | |
| 168 | ); | |
| 169 | } | |
| 170 | ||
| 171 | /** Take `userId` off the repository; false when they were not on it. */ | |
| 172 | export function removeContributor(db: Database, repoId: string, userId: string): boolean { | |
| 173 | return db.query("DELETE FROM repo_contributor WHERE repo_id = ?1 AND user_id = ?2").run(repoId, userId).changes === 1; | |
| 174 | } | |
| 175 | ||
| 176 | /** A repository's contributors, by username, with when and by whom each was let in. */ | |
| 177 | export function listContributors( | |
| 178 | db: Database, | |
| 179 | repoId: string, | |
| 180 | ): { userId: string; username: string; at: string; by: string | null }[] { | |
| 181 | return db | |
| 182 | .query<{ userId: string; username: string; at: string; by: string | null }, [string]>( | |
| 183 | `SELECT c.user_id AS userId, u.username AS username, c.at AS at, b.username AS by | |
| 184 | FROM repo_contributor c JOIN user u ON u.id = c.user_id LEFT JOIN user b ON b.id = c.by_id | |
| 185 | WHERE c.repo_id = ?1 ORDER BY u.username`, | |
| 186 | ) | |
| 187 | .all(repoId); | |
| 188 | } |
src/core/migration-pins/20261124234131-contributors.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 3c5c3d084af40f3d35564cf837cfe7811bfb7329f2fa495917f595039c3985a7 |
src/core/migrations/20261124234131-contributors.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | // The people a repository's admin invited to work on it (`core/invites.ts`): a contributor reads | |
| 2 | // the repository, enters its app and directs its crew, and lands nothing, changes no setting and | |
| 3 | // invites nobody. Its rows go with the person or the repository. Additive. | |
| 4 | export default ` | |
| 5 | CREATE TABLE repo_contributor ( | |
| 6 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 7 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 8 | by_id TEXT REFERENCES user(id) ON DELETE SET NULL, | |
| 9 | at TEXT NOT NULL, | |
| 10 | PRIMARY KEY (repo_id, user_id) | |
| 11 | ) WITHOUT ROWID; | |
| 12 | CREATE INDEX repo_contributor_user ON repo_contributor(user_id); | |
| 13 | `; |
src/core/repo_fields.ts +5
| @@ -75,6 +75,11 @@ const CREW_FIELDS = { | ||
| 75 | 75 | sealedFor: "string|null", |
| 76 | 76 | severedAt: "string|null", |
| 77 | 77 | madeFrom: "string|null", |
| 78 | /** | |
| 79 | * Whether anyone works on it as a contributor: the owner's to know; who they are is `invite`'s | |
| 80 | * list. | |
| 81 | */ | |
| 82 | contributed: "boolean", | |
| 78 | 83 | } as const satisfies Readonly<Record<string, string>>; |
| 79 | 84 | |
| 80 | 85 | /** A list item as a writer gets it: the stored row whole, `detached` included. */ |
src/core/repos.ts +37 −3
| @@ -26,6 +26,7 @@ import { id } from "../kernel/id.ts"; | ||
| 26 | 26 | import { createLog } from "../kernel/log.ts"; |
| 27 | 27 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 28 | 28 | import { appsNaming, isAppMember } from "./app_members.ts"; |
| 29 | import { isContributor } from "./invites.ts"; | |
| 29 | 30 | import { forgetListings } from "./listings.ts"; |
| 30 | 31 | import { clearDeleting, isDeleting, markDeleting } from "./repo_deleting.ts"; |
| 31 | 32 | import { forgetRepoCursors } from "./origins.ts"; |
| @@ -202,6 +203,11 @@ export interface Repo { | ||
| 202 | 203 | * own; `core/repo_source.ts` judges it again before anything draws it. |
| 203 | 204 | */ |
| 204 | 205 | readonly madeFrom: string | null; |
| 206 | /** | |
| 207 | * Whether anyone contributes here (`repo_contributor`), read on the same row, so a repository | |
| 208 | * nobody was invited to pays no statement for the contributor checks (`contributes`). | |
| 209 | */ | |
| 210 | readonly contributed: boolean; | |
| 205 | 211 | /** |
| 206 | 212 | * Open issue and pull counts. Absent from a bare `getRepo` — a single |
| 207 | 213 | * fetch on a hot path should not pay for a count nobody asked for — and |
| @@ -246,16 +252,21 @@ interface RepoRow { | ||
| 246 | 252 | fetch_error: string; |
| 247 | 253 | origin_detached_at: string | null; |
| 248 | 254 | made_from: string | null; |
| 255 | has_contributors: number; | |
| 249 | 256 | } |
| 250 | 257 | |
| 251 | 258 | // LEFT JOIN, because the origin may have been disconnected out from under a |
| 252 | 259 | // mirror — the repo survives, the link does not. |
| 253 | 260 | const SELECT = ` |
| 254 | 261 | SELECT repo.*, user.username AS owner_name, origin.kind AS origin_kind, made.source AS made_from, |
| 255 | origin.software AS origin_software | |
| 262 | origin.software AS origin_software, contributed.repo_id IS NOT NULL AS has_contributors | |
| 256 | 263 | FROM repo JOIN user ON user.id = repo.owner_id |
| 257 | 264 | LEFT JOIN origin ON origin.id = repo.origin_id |
| 258 | LEFT JOIN repo_made_from made ON made.repo_id = repo.id`; | |
| 265 | LEFT JOIN repo_made_from made ON made.repo_id = repo.id | |
| 266 | LEFT JOIN repo_contributor contributed ON contributed.repo_id = repo.id | |
| 267 | AND contributed.user_id = (SELECT c.user_id FROM repo_contributor c WHERE c.repo_id = repo.id LIMIT 1)`; | |
| 268 | // The contributor join is a correlated lookup on the table's primary key, one row at most per | |
| 269 | // repository: no scan of the table on a read, and the statement still reads `FROM repo` first. | |
| 259 | 270 | |
| 260 | 271 | /** The by-name match `getRepo` and `repoVisibility` share, so the two cannot drift. */ |
| 261 | 272 | const BY_NAME = "user.username = ?1 COLLATE NOCASE AND repo.name = ?2 COLLATE NOCASE"; |
| @@ -302,6 +313,7 @@ function toRepo(row: RepoRow): Repo { | ||
| 302 | 313 | : null, |
| 303 | 314 | severedAt: row.origin_id === null && row.origin_full_name === null ? row.origin_detached_at : null, |
| 304 | 315 | madeFrom: row.made_from, |
| 316 | contributed: row.has_contributors === 1, | |
| 305 | 317 | detached: |
| 306 | 318 | row.origin_id === null && |
| 307 | 319 | row.origin_full_name !== null && |
| @@ -1379,6 +1391,7 @@ export function canRead( | ||
| 1379 | 1391 | if (repo.visibility === "public") return true; |
| 1380 | 1392 | if (personalOrDirect(repo, user)) return true; |
| 1381 | 1393 | if (onCrew(db, repo, user)) return true; |
| 1394 | if (contributes(db, repo, user)) return true; | |
| 1382 | 1395 | // The work on a sealed report is read by whoever may see the report on |
| 1383 | 1396 | // its base: the base's writers and crew, and nobody else (`sealed.ts`). |
| 1384 | 1397 | if (repo.sealedFor !== null) { |
| @@ -1419,6 +1432,8 @@ export function canEnterApp( | ||
| 1419 | 1432 | ): boolean { |
| 1420 | 1433 | if (app.access === "public") return true; |
| 1421 | 1434 | if (canWrite(db, repo, user) || onCrew(db, repo, user)) return true; |
| 1435 | // A contributor (`core/invites.ts`) enters the app and its previews, never its terminal. | |
| 1436 | if (named && contributes(db, repo, user)) return true; | |
| 1422 | 1437 | return ( |
| 1423 | 1438 | named && |
| 1424 | 1439 | user !== undefined && |
| @@ -1464,11 +1479,30 @@ export function enterableApps( | ||
| 1464 | 1479 | closed.map((r) => r.app.id), |
| 1465 | 1480 | ) |
| 1466 | 1481 | : new Set<string>(); |
| 1482 | const contributing = | |
| 1483 | named && user.kind === "user" && isActive(user) && closed.some((r) => r.repo.contributed) ? contributorRepoIds(db, user.id) : new Set<string>(); | |
| 1467 | 1484 | for (const r of closed) |
| 1468 | if (writable.has(r.repo.id) || naming.has(r.app.id)) out.add(r.app.id); | |
| 1485 | if (writable.has(r.repo.id) || naming.has(r.app.id) || contributing.has(r.repo.id)) out.add(r.app.id); | |
| 1469 | 1486 | return out; |
| 1470 | 1487 | } |
| 1471 | 1488 | |
| 1489 | /** | |
| 1490 | * Whether `user` is an active person the repository's admin made a contributor (`core/invites.ts`). | |
| 1491 | */ | |
| 1492 | export function contributes(db: Database, repo: Repo, user: User | undefined): boolean { | |
| 1493 | return repo.contributed && user !== undefined && user.kind === "user" && isActive(user) && isContributor(db, repo.id, user.id); | |
| 1494 | } | |
| 1495 | ||
| 1496 | /** The repositories `userId` contributes to. */ | |
| 1497 | function contributorRepoIds(db: Database, userId: string): Set<string> { | |
| 1498 | return new Set( | |
| 1499 | db | |
| 1500 | .query<{ id: string }, [string]>("SELECT repo_id AS id FROM repo_contributor INDEXED BY repo_contributor_user WHERE user_id = ?1") | |
| 1501 | .all(userId) | |
| 1502 | .map((r) => r.id), | |
| 1503 | ); | |
| 1504 | } | |
| 1505 | ||
| 1472 | 1506 | /** |
| 1473 | 1507 | * Money, the crew roster, autonomy limits and a run's own cost describe |
| 1474 | 1508 | * running the app, not what it is — a stranger who can only read a public |
src/core/visibility.ts +5 −1
| @@ -34,7 +34,11 @@ export const REPO_VISIBLE = `( | ||
| 34 | 34 | OR repo.owner_id IN ( |
| 35 | 35 | SELECT team.org_id FROM team |
| 36 | 36 | JOIN team_member ON team_member.team_id = team.id |
| 37 | WHERE team_member.user_id = ?1))) | |
| 37 | WHERE team_member.user_id = ?1) | |
| 38 | OR EXISTS (SELECT 1 FROM repo_contributor | |
| 39 | JOIN user AS contributor ON contributor.id = repo_contributor.user_id | |
| 40 | WHERE repo_contributor.repo_id = repo.id AND repo_contributor.user_id = ?1 | |
| 41 | AND contributor.suspended_at IS NULL AND contributor.removed_at IS NULL))) | |
| 38 | 42 | )`; |
| 39 | 43 | |
| 40 | 44 | /** |
src/crew/conversation_ask.ts +6
| @@ -273,6 +273,12 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 273 | 273 | return verbs[String(a["verb"])] ?? `Change ${which}`; |
| 274 | 274 | }, |
| 275 | 275 | pinned_forge: (a) => pinnedForge(a), |
| 276 | invite: (a) => | |
| 277 | val(a, "who") === "" | |
| 278 | ? `List who works on ${repo(a)}` | |
| 279 | : a["remove"] === true | |
| 280 | ? `Take ${val(a, "who")} off ${repo(a)}: they can no longer open it, its app or ask its crew` | |
| 281 | : `Make ${val(a, "who")} a contributor on ${repo(a)}: they can open the app and ask the crew for changes; they cannot merge or change settings`, | |
| 276 | 282 | outsiders: (a) => |
| 277 | 283 | a["on"] === false |
| 278 | 284 | ? `Stop people who cannot write to ${repo(a)} from directing its crew` |
src/crew/conversation_confirm.ts +1
| @@ -106,6 +106,7 @@ export const ASKING: Readonly<Record<string, Asking>> = { | ||
| 106 | 106 | land_past_gate: {}, |
| 107 | 107 | share: {}, |
| 108 | 108 | invites: { asks: (a) => a["action"] !== "list" }, |
| 109 | invite: { asks: (a) => typeof a["who"] === "string" && a["who"] !== "" }, | |
| 109 | 110 | egress_grants: { asks: not("op", "list") }, |
| 110 | 111 | sever: {}, |
| 111 | 112 | parent_unlink: {}, |
src/crew/direct.ts +3 −1
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | import type { Database } from "bun:sqlite"; |
| 18 | 18 | import { crewRole } from "../core/agents.ts"; |
| 19 | import { canRead, canWrite, type Repo } from "../core/repos.ts"; | |
| 19 | import { canRead, canWrite, contributes, type Repo } from "../core/repos.ts"; | |
| 20 | 20 | import type { Issue } from "../core/issues.ts"; |
| 21 | 21 | import { isProposed } from "../core/pull_trust.ts"; |
| 22 | 22 | import { foldsIn } from "../core/trusted_sources.ts"; |
| @@ -47,6 +47,8 @@ export function mayDirectCrew( | ||
| 47 | 47 | ): boolean { |
| 48 | 48 | if (actor === undefined || actor.kind === "org") return false; |
| 49 | 49 | if (canWrite(db, repo, actor)) return true; |
| 50 | // A contributor the repository's admin invited directs its crew; what it asks lands as pulls. | |
| 51 | if (contributes(db, repo, actor)) return true; | |
| 50 | 52 | if (actor.kind === "agent") |
| 51 | 53 | return crewRole(db, repo.id, actor.id) === "reviewer"; |
| 52 | 54 | return repo.crewOutsiders && canRead(db, repo, actor); |
src/crew/dispatch.ts +8 −3
| @@ -63,7 +63,7 @@ import { peopleFirst } from "./people_first.ts"; | ||
| 63 | 63 | import { inFocus } from "./focus.ts"; |
| 64 | 64 | import { inMaintenance } from "../maintenance/state.ts"; |
| 65 | 65 | import { gateQueue } from "../flow/valve_gate.ts"; |
| 66 | import { ARCHIVED_WHY, getRepoById, type Repo } from "../core/repos.ts"; | |
| 66 | import { ARCHIVED_WHY, canWrite, contributes, getRepoById, type Repo } from "../core/repos.ts"; | |
| 67 | 67 | import { listReviews } from "../core/reviews.ts"; |
| 68 | 68 | import { |
| 69 | 69 | greenHead, |
| @@ -579,11 +579,16 @@ export function queueAgentRun( | ||
| 579 | 579 | // A guest's word starts no run (a comment is still a comment); the |
| 580 | 580 | // actions that start one by name refuse out loud before they get here. |
| 581 | 581 | const asker = actorId === undefined ? undefined : getUserById(app.db, actorId); |
| 582 | if (asker !== undefined && lacks(app.db, asker, "run_crew")) return undefined; | |
| 582 | // A contributor asks on the owner's crew and allowance (`core/invites.ts`): theirs is not the | |
| 583 | // ability read. | |
| 584 | if (asker !== undefined && lacks(app.db, asker, "run_crew") && !contributes(app.db, repo, asker)) return undefined; | |
| 583 | 585 | // A run a person sent: by an event their request wrote, in their own request now (a re-run, a |
| 584 | 586 | // proposal taken), or carried on from one they sent. The week's cap holds only the crew's own |
| 585 | 587 | // work; a review stays under it whoever opened the pull, until the owner says otherwise. |
| 586 | const directed = sent || again?.sent === true || (asker !== undefined && personActing(asker)); | |
| 588 | // Sent is the owner's word only: a person who cannot write here (a contributor, an outsider) asks | |
| 589 | // on the owner's crew and subscription, so the week's cap holds their work as the crew's own. | |
| 590 | const owners = asker === undefined || asker.kind !== "user" || canWrite(app.db, repo, asker); | |
| 591 | const directed = owners && (sent || again?.sent === true || (asker !== undefined && personActing(asker))); | |
| 587 | 592 | // The week's share gates every run the crew starts on its own, not only |
| 588 | 593 | // the picks: a review, a feedback run or a conflict run past the week's share |
| 589 | 594 | // is money the person did not agree to. A person's own assignment is not |
src/http/mcp/catalog.ts +1 −1
| @@ -46,7 +46,7 @@ export const DEFAULT_TOOLS: readonly string[] = [ | ||
| 46 | 46 | export const TALK_TOOLS: readonly string[] = [ |
| 47 | 47 | ...DEFAULT_TOOLS, |
| 48 | 48 | "issue", "issues", "pull", "pulls", "commits", "threads", "search", "read_file", "repo", "run_log", |
| 49 | "preview", "assigned", "health", "releases", "person", "whoami_can", "show", "pane", "origins", | |
| 49 | "preview", "assigned", "health", "releases", "person", "whoami_can", "show", "pane", "origins", "invite", | |
| 50 | 50 | "close", "assign", "labels", "edit", "review", "merge", "keep_plan", "steer", "stop", |
| 51 | 51 | "write_file", "branches", "open_pull", "new_app", |
| 52 | 52 | ]; |
src/http/mcp/tools/index.ts +1
| @@ -88,6 +88,7 @@ export { tool as held } from "./held.ts"; | ||
| 88 | 88 | export { tool as here } from "./here.ts"; |
| 89 | 89 | export { tool as hold } from "./hold.ts"; |
| 90 | 90 | export { tool as hooks } from "./hooks.ts"; |
| 91 | export { tool as invite } from "./invite.ts"; | |
| 91 | 92 | export { tool as invites } from "./invites.ts"; |
| 92 | 93 | export { tool as issue } from "./issue.ts"; |
| 93 | 94 | export { tool as issue_teams } from "./issue_teams.ts"; |
src/http/mcp/tools/invite.ts added +51
| @@ -0,0 +1,51 @@ | ||
| 1 | import { | |
| 2 | CONTRIBUTOR_WORDS, | |
| 3 | inviteContributor, | |
| 4 | removeContributorFrom, | |
| 5 | repoContributors, | |
| 6 | type ContributorError, | |
| 7 | } from "../../../actions/invites.ts"; | |
| 8 | import { type Answer, bad, good, isAnswer, REPO_ARG, repoArg, str, type Tool } from "../shared.ts"; | |
| 9 | ||
| 10 | /** A refusal in the words every door says. */ | |
| 11 | const refused = (e: ContributorError): Answer => | |
| 12 | e === "forbidden" || e === "unauthorized" | |
| 13 | ? bad("forbidden", "only the repository's admin invites, lists or takes off its contributors") | |
| 14 | : e === "not_found" | |
| 15 | ? bad("not_found", "no such app or repository (owner/name)") | |
| 16 | : bad(e, CONTRIBUTOR_WORDS[e]); | |
| 17 | ||
| 18 | export const tool: Tool = { | |
| 19 | name: "invite", | |
| 20 | doc: "`{ repo, who?, remove? }`: admin adds or takes off contributor `who`; none lists", | |
| 21 | description: "Invite someone with an account to work on an app; list or remove contributors.", | |
| 22 | inputSchema: { | |
| 23 | type: "object", | |
| 24 | properties: { repo: REPO_ARG, who: { type: "string" }, remove: { type: "boolean" } }, | |
| 25 | required: ["repo"], | |
| 26 | }, | |
| 27 | writes: true, | |
| 28 | // The list only reads: the agent need not ask for it. | |
| 29 | heldNotWhen: (args) => str(args["who"]) === "", | |
| 30 | run(ctx, user, args) { | |
| 31 | const repo = repoArg(ctx, user, args); | |
| 32 | if (isAnswer(repo)) return repo; | |
| 33 | const who = str(args["who"]); | |
| 34 | const name = `${repo.ownerName}/${repo.name}`; | |
| 35 | if (who === "") { | |
| 36 | const people = repoContributors(ctx.app, user, repo); | |
| 37 | return people.ok ? good({ contributors: people.value }) : refused(people.error); | |
| 38 | } | |
| 39 | if (args["remove"] === true) { | |
| 40 | const done = removeContributorFrom(ctx.app, user, repo, who); | |
| 41 | return done.ok ? good({ removed: who, says: `${who} is no longer a contributor to ${name}.` }) : refused(done.error); | |
| 42 | } | |
| 43 | const made = inviteContributor(ctx.app, user, repo, who); | |
| 44 | if (!made.ok) return refused(made.error); | |
| 45 | const v = made.value; | |
| 46 | return good({ | |
| 47 | contributor: v.username, | |
| 48 | says: v.added ? `${v.username} works on ${name} now: they hear it, and can ask Talk for changes there.` : `${v.username} already works on ${name}.`, | |
| 49 | }); | |
| 50 | }, | |
| 51 | }; |
src/tui/screens/deploys.ts +114 −1
| @@ -120,7 +120,7 @@ import { binding } from "../app/keys.ts"; | ||
| 120 | 120 | import type { Session } from "../session.ts"; |
| 121 | 121 | import type { Rect } from "../term/screen.ts"; |
| 122 | 122 | import { style } from "../term/style.ts"; |
| 123 | import { truncate } from "../term/width.ts"; | |
| 123 | import { truncate, wrap } from "../term/width.ts"; | |
| 124 | 124 | import { fill, len, split } from "../ui/layout.ts"; |
| 125 | 125 | import { emptyState } from "../ui/widgets.ts"; |
| 126 | 126 | import { |
| @@ -129,6 +129,7 @@ import { | ||
| 129 | 129 | confirmScreen, |
| 130 | 130 | drawList, |
| 131 | 131 | hitList, |
| 132 | later, | |
| 132 | 133 | promptScreen, |
| 133 | 134 | runAsync, |
| 134 | 135 | yesNo, |
| @@ -139,6 +140,7 @@ import { envTone } from "./runwords.ts"; | ||
| 139 | 140 | import { pullScreen } from "./pull.ts"; |
| 140 | 141 | import { local } from "./where.ts"; |
| 141 | 142 | import { appMembersScreen } from "./appmembers.ts"; |
| 143 | import { CONTRIBUTOR_WORDS, inviteContributor, removeContributorFrom, repoContributors, type ContributorError } from "../../actions/invites.ts"; | |
| 142 | 144 | import { mayManagePrompts, promptsScreen } from "./prompts.ts"; |
| 143 | 145 | import { editDnsFromTerminal } from "./domain_dns.ts"; |
| 144 | 146 | import type { DnsStep } from "../../actions/domain_dns.ts"; |
| @@ -241,6 +243,8 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 241 | 243 | let inPreviews = false; |
| 242 | 244 | let production: Production = { state: "", redeploy: false, stop: false, alwaysOn: false }; |
| 243 | 245 | let members = false; |
| 246 | // Inviting is the repository admin's (`inviteContributor` decides; this only shows the key). | |
| 247 | const mayInvite = (): boolean => f.user !== undefined && f.user.kind === "user" && canAdmin(f.db, repo, f.user); | |
| 244 | 248 | let prompts = false; |
| 245 | 249 | let stoppable = false; |
| 246 | 250 | let isApp = true; |
| @@ -418,6 +422,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 418 | 422 | ]), |
| 419 | 423 | ...(mayProbe ? [binding(["p"], "probe the running app's doors")] : []), |
| 420 | 424 | ...(members ? [binding(["m"], "members")] : []), |
| 425 | ...(mayInvite() ? [binding(["W"], "who works on it: invite, list, take off")] : []), | |
| 421 | 426 | ...(domains !== undefined ? [binding(["n"], "the app's own domains")] : []), |
| 422 | 427 | ...(prompts ? [binding(["i"], "prompt source (Instagram)")] : []), |
| 423 | 428 | ...(stoppable ? [binding(["X"], STOP_APP.toLowerCase())] : []), |
| @@ -581,6 +586,10 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 581 | 586 | ctx.push(appMembersScreen(f, ctx, repo)); |
| 582 | 587 | return true; |
| 583 | 588 | } |
| 589 | if (e.key === "W" && mayInvite()) { | |
| 590 | ctx.push(contributorsScreen(f, ctx, repo)); | |
| 591 | return true; | |
| 592 | } | |
| 584 | 593 | if (e.key === "n" && domains !== undefined) { |
| 585 | 594 | ctx.push(domainsScreen(f, ctx, repo, read)); |
| 586 | 595 | return true; |
| @@ -1007,3 +1016,107 @@ export function domainsScreen(f: Session, ctx: Ctx, repo: Repo, changed: () => v | ||
| 1007 | 1016 | }; |
| 1008 | 1017 | return self; |
| 1009 | 1018 | } |
| 1019 | ||
| 1020 | /** A contributor refusal in the words MCP `invite` says. */ | |
| 1021 | export function contributorRefusal(e: ContributorError): string { | |
| 1022 | return e === "forbidden" || e === "unauthorized" | |
| 1023 | ? "Only the repository's admin invites, lists or takes off its contributors." | |
| 1024 | : e === "not_found" | |
| 1025 | ? "no such app or repository (owner/name)" | |
| 1026 | : CONTRIBUTOR_WORDS[e]; | |
| 1027 | } | |
| 1028 | ||
| 1029 | /** | |
| 1030 | * Who works on an app with its owner, in the terminal: `W` on the deploys screen, the same list | |
| 1031 | * and actions as Talk's `invite` (`actions/invites.ts`). `a` invites a person by username and `d` | |
| 1032 | * takes the one under the cursor off, each after a confirm. The repository's admin only. | |
| 1033 | */ | |
| 1034 | export function contributorsScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 1035 | const state = new ListState(); | |
| 1036 | let people: readonly string[] = []; | |
| 1037 | let canChange = false; | |
| 1038 | let note = ""; | |
| 1039 | const name = `${repo.ownerName}/${repo.name}`; | |
| 1040 | const reload = (): void => { | |
| 1041 | const read = repoContributors(f.app, f.user, repo); | |
| 1042 | canChange = read.ok; | |
| 1043 | people = read.ok ? read.value.map((c) => c.username) : []; | |
| 1044 | if (!read.ok && note === "") note = contributorRefusal(read.error); | |
| 1045 | state.clamp(people.length); | |
| 1046 | ctx.invalidate(); | |
| 1047 | }; | |
| 1048 | reload(); | |
| 1049 | const say = (text: string): void => { | |
| 1050 | note = text; | |
| 1051 | reload(); | |
| 1052 | }; | |
| 1053 | const confirm = (title: string, body: string, verb: string, act: () => void): void => | |
| 1054 | void later(ctx, () => | |
| 1055 | confirmScreen(ctx, screen, { | |
| 1056 | title, | |
| 1057 | body: [body], | |
| 1058 | actions: [{ label: "Cancel", variant: "ghost" }, { label: verb }], | |
| 1059 | selected: 1, | |
| 1060 | onChoose: (i) => { | |
| 1061 | if (i === 1) act(); | |
| 1062 | }, | |
| 1063 | }), | |
| 1064 | ); | |
| 1065 | const invite = (): Screen => | |
| 1066 | promptScreen(ctx, screen, { | |
| 1067 | title: "Invite someone to work on it", | |
| 1068 | label: "their username", | |
| 1069 | placeholder: "ben", | |
| 1070 | onSubmit: (raw) => { | |
| 1071 | const who = raw.trim(); | |
| 1072 | if (who === "") return "Name a person."; | |
| 1073 | confirm("Invite", `${who} works on ${name}: they read it and ask its crew for changes, and land nothing.`, "Invite", () => { | |
| 1074 | const made = inviteContributor(f.app, f.user, repo, who); | |
| 1075 | if (!made.ok) return say(contributorRefusal(made.error)); | |
| 1076 | say(made.value.added ? `${made.value.username} works on ${name} now.` : `${made.value.username} already works on ${name}.`); | |
| 1077 | }); | |
| 1078 | return undefined; | |
| 1079 | }, | |
| 1080 | }); | |
| 1081 | const screen: Screen = { | |
| 1082 | title: "Contributors", | |
| 1083 | get keys() { | |
| 1084 | return [ | |
| 1085 | binding(["j", "k"], "move"), | |
| 1086 | ...(canChange ? [binding(["a"], "invite someone"), binding(["d"], "take them off")] : []), | |
| 1087 | binding(["esc"], "back"), | |
| 1088 | ]; | |
| 1089 | }, | |
| 1090 | render(area, s) { | |
| 1091 | const c = ctx.theme.c; | |
| 1092 | const text = | |
| 1093 | note !== "" | |
| 1094 | ? note | |
| 1095 | : people.length === 0 | |
| 1096 | ? `Nobody works on ${name} with you yet. Press a to invite someone.` | |
| 1097 | : `${people.length} work on ${name} with you: they read it, enter the app and ask its crew for changes.`; | |
| 1098 | const said = wrap(text, Math.max(1, area.w)).slice(0, 4); | |
| 1099 | const [head, list] = split(area, "v", [len(said.length), fill(1)]); | |
| 1100 | said.forEach((line, i) => s.text(head!.x, head!.y + i, line, style(c.mutedFg, c.bg), head!.x + head!.w)); | |
| 1101 | drawList(s, list!, c, state, people.map((p) => ({ title: p }))); | |
| 1102 | }, | |
| 1103 | key(e) { | |
| 1104 | if (state.key(e, people.length)) return true; | |
| 1105 | if (e.ctrl || e.alt || !canChange) return false; | |
| 1106 | if (e.key === "a") { | |
| 1107 | ctx.push(invite()); | |
| 1108 | return true; | |
| 1109 | } | |
| 1110 | const who = people[state.index]; | |
| 1111 | if (e.key === "d" && who !== undefined) { | |
| 1112 | confirm("Take off", `${who} reads, enters and asks for nothing on ${name} from now on.`, "Take off", () => { | |
| 1113 | const done = removeContributorFrom(f.app, f.user, repo, who); | |
| 1114 | say(done.ok ? `${who} is no longer a contributor here.` : contributorRefusal(done.error)); | |
| 1115 | }); | |
| 1116 | return true; | |
| 1117 | } | |
| 1118 | return false; | |
| 1119 | }, | |
| 1120 | }; | |
| 1121 | return screen; | |
| 1122 | } |
test/conversation-ask.test.ts +2
| @@ -478,6 +478,8 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 478 | 478 | { verb: "rename", provider: "hetzner", name: "eu", to: "eu2" }, |
| 479 | 479 | "Rename the hetzner account eu to eu2.", |
| 480 | 480 | ], |
| 481 | ["invite", { repo: "marin/cakes", who: "ben" }, "Make ben a contributor on marin/cakes: they can open the app and ask the crew for changes; they cannot merge or change settings."], | |
| 482 | ["invite", { repo: "marin/cakes", who: "ben", remove: true }, "Take ben off marin/cakes: they can no longer open it, its app or ask its crew."], | |
| 481 | 483 | [ |
| 482 | 484 | "pinned_forge", |
| 483 | 485 | { verb: "deploy", name: "shop", target: "hetzner" }, |
test/delete-tier.test.ts +1
| @@ -125,6 +125,7 @@ const SPARED: Readonly<Record<string, string>> = { | ||
| 125 | 125 | crew: "an agent taken off a repository's crew is seated again with `add`; nothing it did is lost", |
| 126 | 126 | egress_grants: "a revoked grant is granted again by the same tool; no data goes with it", |
| 127 | 127 | invites: "a revoked invite is an unused link; a new one is minted in its place", |
| 128 | invite: "a contributor taken off is let in again with the same tool; their work, pulls and account are untouched", | |
| 128 | 129 | sever: "it unlinks and, as it says, deletes nothing: both sides keep all they hold", |
| 129 | 130 | }; |
| 130 | 131 |
test/invite-contributors.test.ts added +415
| @@ -0,0 +1,415 @@ | ||
| 1 | /** | |
| 2 | * Working with others on an app (the owner: "i want to start working with others on apps... that | |
| 3 | * should feel native"). A contributor, whom the repository's admin lets in, reads the repository, | |
| 4 | * enters its app and previews but never its terminal, and asks its crew for changes; they land | |
| 5 | * nothing, change no setting and see nothing outside it. Their asks run on the owner's crew and | |
| 6 | * subscription, so the week's cap holds them as the crew's own work, and an outsider's the same: | |
| 7 | * only a writer's run passes the cap. Taking someone off is at once, on their next request. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { addCrew } from "../src/core/agents.ts"; | |
| 11 | import { tell } from "../src/actions/tell.ts"; | |
| 12 | import { | |
| 13 | updateRepoSettings, | |
| 14 | createRepo, | |
| 15 | commitToBranch, | |
| 16 | } from "../src/actions/repos.ts"; | |
| 17 | import { assignIssue, openIssue } from "../src/actions/issues.ts"; | |
| 18 | import { mergePull } from "../src/actions/pulls.ts"; | |
| 19 | import { createIssue } from "../src/core/issues.ts"; | |
| 20 | import { createOrg } from "../src/core/orgs.ts"; | |
| 21 | import { getPull } from "../src/core/pulls.ts"; | |
| 22 | import { actingVia } from "../src/core/acting_via.ts"; | |
| 23 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 24 | import { setAppEnv } from "../src/core/app_env.ts"; | |
| 25 | import { noteMeasure } from "../src/core/measure.ts"; | |
| 26 | import { | |
| 27 | canEnterApp, | |
| 28 | canRead, | |
| 29 | canWrite, | |
| 30 | getRepoById, | |
| 31 | readableRepoIds, | |
| 32 | type Repo, | |
| 33 | } from "../src/core/repos.ts"; | |
| 34 | import { listRuns, type Run } from "../src/core/runs.ts"; | |
| 35 | import { createSession } from "../src/core/sessions.ts"; | |
| 36 | import { setHeadroom } from "../src/core/standing.ts"; | |
| 37 | import { addSubscription } from "../src/core/subscriptions.ts"; | |
| 38 | import { createToken } from "../src/core/tokens.ts"; | |
| 39 | import { createUser, type User } from "../src/core/users.ts"; | |
| 40 | import { createWebhook } from "../src/core/webhooks.ts"; | |
| 41 | import { mayDirectCrew } from "../src/crew/direct.ts"; | |
| 42 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 43 | import { contributorsScreen } from "../src/tui/screens/deploys.ts"; | |
| 44 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 45 | import { settleApp } from "./helpers/tui.ts"; | |
| 46 | import { queueAgentRun } from "../src/crew/dispatch.ts"; | |
| 47 | import { getAgentByName } from "../src/core/agents.ts"; | |
| 48 | import { forgetWeek } from "../src/crew/week_read.ts"; | |
| 49 | import { TALK_TOOLS } from "../src/http/mcp/catalog.ts"; | |
| 50 | import { readRunLog } from "../src/runs/log.ts"; | |
| 51 | import { | |
| 52 | startStandInCrew, | |
| 53 | stopStandInCrew, | |
| 54 | type StandInCrew, | |
| 55 | } from "./helpers/crew-standin.ts"; | |
| 56 | import { promote } from "./helpers/members.ts"; | |
| 57 | import { pollUntil } from "./helpers/poll.ts"; | |
| 58 | ||
| 59 | /** | |
| 60 | * What nothing outside the app may ever answer a contributor: planted where only its owner reads. | |
| 61 | */ | |
| 62 | const VAULT = "ZQX-VAULT-7731"; | |
| 63 | const ENV_NAME = "ZQX_HIDDEN_NAME"; | |
| 64 | const HOOK = "zqx-hook-5519"; | |
| 65 | /** The owner's subscription, by name: what `usage` tells its owner, and nobody else. */ | |
| 66 | const SUB = "zqx-sub-4410"; | |
| 67 | ||
| 68 | let standIn: StandInCrew; | |
| 69 | let repo: Repo; | |
| 70 | let alice: User; | |
| 71 | let ben: User; | |
| 72 | let carol: User; | |
| 73 | let dave: User; | |
| 74 | let url = ""; | |
| 75 | let id = 1; | |
| 76 | ||
| 77 | const person = async (username: string): Promise<User> => { | |
| 78 | const made = await createUser(standIn.app.db, { | |
| 79 | origin: "seed", | |
| 80 | trusted: true, | |
| 81 | username, | |
| 82 | email: `${username}@forge.test`, | |
| 83 | password: "a-good-passphrase", | |
| 84 | }); | |
| 85 | if (!made.ok) throw new Error(made.error); | |
| 86 | return made.value; | |
| 87 | }; | |
| 88 | const mcp = async ( | |
| 89 | who: User, | |
| 90 | name: string, | |
| 91 | args: Record<string, unknown>, | |
| 92 | ): Promise<{ text: string; error: boolean }> => { | |
| 93 | const res = await fetch(`${url}/mcp`, { | |
| 94 | method: "POST", | |
| 95 | headers: { | |
| 96 | authorization: `Bearer ${createToken(standIn.app.db, who.id, "t", "rw").token}`, | |
| 97 | "content-type": "application/json", | |
| 98 | accept: "application/json, text/event-stream", | |
| 99 | }, | |
| 100 | body: JSON.stringify({ | |
| 101 | jsonrpc: "2.0", | |
| 102 | id: id++, | |
| 103 | method: "tools/call", | |
| 104 | params: { name, arguments: args }, | |
| 105 | }), | |
| 106 | }); | |
| 107 | const body = (await res.json()) as { | |
| 108 | result?: { isError?: boolean; content: { text: string }[] }; | |
| 109 | error?: unknown; | |
| 110 | }; | |
| 111 | return { | |
| 112 | text: | |
| 113 | body.result?.content.map((c) => c.text).join("\n") ?? | |
| 114 | JSON.stringify(body.error), | |
| 115 | error: body.result?.isError === true || body.result === undefined, | |
| 116 | }; | |
| 117 | }; | |
| 118 | const page = async ( | |
| 119 | who: User | undefined, | |
| 120 | path: string, | |
| 121 | init: RequestInit = {}, | |
| 122 | ) => | |
| 123 | fetch(`${url}${path}`, { | |
| 124 | redirect: "manual", | |
| 125 | ...init, | |
| 126 | headers: { | |
| 127 | ...(who === undefined | |
| 128 | ? {} | |
| 129 | : { | |
| 130 | cookie: `forge_session=${createSession(standIn.app.db, who.id).token}`, | |
| 131 | }), | |
| 132 | origin: url, | |
| 133 | ...(init.body === undefined | |
| 134 | ? {} | |
| 135 | : { "content-type": "application/x-www-form-urlencoded" }), | |
| 136 | }, | |
| 137 | }); | |
| 138 | /** Talk's `invite`, as the repository's admin calls it: the door that lets a person in, or out. */ | |
| 139 | const letIn = async (who: User): Promise<string> => (await mcp(alice, "invite", { repo: name(), who: who.username })).text; | |
| 140 | const takeOff = async (who: User): Promise<string> => (await mcp(alice, "invite", { repo: name(), who: who.username, remove: true })).text; | |
| 141 | const fresh = () => getRepoById(standIn.app.db, repo.id)!; | |
| 142 | const name = () => `${repo.ownerName}/${repo.name}`; | |
| 143 | ||
| 144 | beforeAll(async () => { | |
| 145 | standIn = await startStandInCrew(); | |
| 146 | ({ repo, alice } = standIn); | |
| 147 | url = standIn.servers.url; | |
| 148 | const { app } = standIn; | |
| 149 | const record = createAppRecord(app.db, { | |
| 150 | repoId: repo.id, | |
| 151 | slug: "garden", | |
| 152 | access: "private", | |
| 153 | }); | |
| 154 | if (!record.ok) throw new Error(record.error); | |
| 155 | [ben, carol, dave] = [ | |
| 156 | await person("ben"), | |
| 157 | await person("carol"), | |
| 158 | await person("dave"), | |
| 159 | ]; | |
| 160 | // What only the owner reads: another private repository, the app's variable names, a webhook. | |
| 161 | const vault = await createRepo(app, alice, { | |
| 162 | name: "vault", | |
| 163 | visibility: "private", | |
| 164 | }); | |
| 165 | if (!vault.ok) throw new Error(String(vault.error)); | |
| 166 | const seeded = await commitToBranch(app, alice, vault.value, { | |
| 167 | message: VAULT, | |
| 168 | files: [{ path: "README.md", content: `# ${VAULT}\n` }], | |
| 169 | }); | |
| 170 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 171 | if (!openIssue(app, alice, vault.value, { title: VAULT, body: VAULT }).ok) | |
| 172 | throw new Error("issue"); | |
| 173 | if ( | |
| 174 | !setAppEnv( | |
| 175 | app.db, | |
| 176 | app.config.dataDir, | |
| 177 | record.value.id, | |
| 178 | ENV_NAME, | |
| 179 | "s3cret-value", | |
| 180 | ).ok | |
| 181 | ) | |
| 182 | throw new Error("env"); | |
| 183 | if ( | |
| 184 | !createWebhook(app.db, { | |
| 185 | repoId: repo.id, | |
| 186 | url: `https://${HOOK}.example/hook`, | |
| 187 | kinds: "push", | |
| 188 | }).ok | |
| 189 | ) | |
| 190 | throw new Error("hook"); | |
| 191 | const sub = addSubscription(app.db, standIn.dataDir, { name: SUB, token: "sk-ant-oat01-zqx-owner-only" }); | |
| 192 | if (!sub.ok) throw new Error(sub.error); | |
| 193 | // Granted to the other repository, so the money test's own grant on the app stays its alone. | |
| 194 | app.db.query("INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', ?2)").run(vault.value.id, sub.value.id); | |
| 195 | }, 30_000); | |
| 196 | afterAll(() => stopStandInCrew(standIn), 30_000); | |
| 197 | ||
| 198 | describe("a contributor: reads, enters, directs; nothing outside the repository", () => { | |
| 199 | test("a contributor reads the repository, enters its app but never its terminal, directs its crew", async () => { | |
| 200 | const { app } = standIn; | |
| 201 | expect([ | |
| 202 | canRead(app.db, fresh(), ben), | |
| 203 | mayDirectCrew(app.db, fresh(), ben), | |
| 204 | ]).toEqual([false, false]); | |
| 205 | // The repository's admin lets him in through Talk's `invite`. | |
| 206 | expect(await letIn(ben)).toContain("ben works on alice/garden now"); | |
| 207 | const record = { id: "", access: "private" as const }; | |
| 208 | record.id = app.db | |
| 209 | .query<{ id: string }, [string]>("SELECT id FROM app WHERE repo_id = ?1") | |
| 210 | .get(repo.id)!.id; | |
| 211 | expect([ | |
| 212 | canRead(app.db, fresh(), ben), | |
| 213 | mayDirectCrew(app.db, fresh(), ben), | |
| 214 | canEnterApp(app.db, fresh(), record, ben), | |
| 215 | ]).toEqual([true, true, true]); | |
| 216 | // Never its terminal. | |
| 217 | expect(canEnterApp(app.db, fresh(), record, ben, { named: false })).toBe( | |
| 218 | false, | |
| 219 | ); | |
| 220 | expect(readableRepoIds(app.db, ben, [repo.id]).has(repo.id)).toBe(true); | |
| 221 | expect((await page(ben, `/${name()}`)).status).toBe(200); | |
| 222 | }); | |
| 223 | ||
| 224 | test("a contributor walks every Talk tool and nothing the owner alone is told answers: no other repository, no subscription", async () => { | |
| 225 | const shapes: Record<string, unknown>[] = [ | |
| 226 | {}, | |
| 227 | { repo: "alice/vault" }, | |
| 228 | { repo: "alice/vault", number: 1 }, | |
| 229 | { repo: "alice/vault", path: "README.md" }, | |
| 230 | { repo: name() }, | |
| 231 | { repo: name(), action: "list" }, | |
| 232 | { query: VAULT }, | |
| 233 | { q: VAULT }, | |
| 234 | { user: "alice" }, | |
| 235 | { username: "alice" }, | |
| 236 | ]; | |
| 237 | // The markers each walk finds, as `tool args: marker`. | |
| 238 | const walk = async (who: User): Promise<string[]> => { | |
| 239 | const found: string[] = []; | |
| 240 | for (const tool of TALK_TOOLS) | |
| 241 | for (const args of shapes) { | |
| 242 | const got = await mcp(who, tool, args); | |
| 243 | for (const marker of [VAULT, SUB]) if (got.text.includes(marker)) found.push(`${tool} ${JSON.stringify(args)}: ${marker}`); | |
| 244 | } | |
| 245 | return found; | |
| 246 | }; | |
| 247 | // The owner's walk finds both, so the contributor's could: another private repository (read, | |
| 248 | // listed, searched) and the owner's subscription (`usage`). | |
| 249 | const owners = await walk(alice); | |
| 250 | expect(new Set(owners.map((f) => f.slice(f.lastIndexOf(": ") + 2)))).toEqual(new Set([VAULT, SUB])); | |
| 251 | expect(await walk(ben)).toEqual([]); | |
| 252 | // The app's variable names and its webhook no Talk tool tells even its owner: the pages that do | |
| 253 | // are its admin's, and show the contributor neither. | |
| 254 | for (const [path, marker] of [[`/${name()}/settings/hooks`, HOOK], [`/${name()}/settings/app`, ENV_NAME]] as const) { | |
| 255 | expect([path, (await (await page(alice, path)).text()).includes(marker)]).toEqual([path, true]); | |
| 256 | expect([path, (await (await page(ben, path)).text()).includes(marker)]).toEqual([path, false]); | |
| 257 | } | |
| 258 | expect((await page(ben, "/alice/vault")).status).toBe(404); | |
| 259 | }, 180_000); | |
| 260 | }); | |
| 261 | ||
| 262 | describe("the doors: Talk's invite and the terminal", () => { | |
| 263 | test("only the repository's admin invites: a contributor is told it is the admin's, a stranger is told nothing, a name with no account is said so", async () => { | |
| 264 | expect((await mcp(ben, "invite", { repo: name(), who: "carol" })).text).toContain("only the repository's admin"); | |
| 265 | expect((await mcp(carol, "invite", { repo: name(), who: "carol" })).text).toContain("not_found"); | |
| 266 | expect((await mcp(alice, "invite", { repo: name(), who: "nobody-here" })).text).toContain("they need an account on this forge first"); | |
| 267 | expect(canRead(standIn.app.db, fresh(), carol)).toBe(false); | |
| 268 | // The admin's list names who works on it; the list only reads. | |
| 269 | expect((await mcp(alice, "invite", { repo: name() })).text).toContain('"username":"ben"'); | |
| 270 | }); | |
| 271 | ||
| 272 | test("only a person who does not already write is invited, and only a contributor is taken off", async () => { | |
| 273 | // An agent and an organization are not people; the owner already writes. | |
| 274 | expect((await mcp(alice, "invite", { repo: name(), who: "bot" })).text).toContain("Only a person is invited as a contributor"); | |
| 275 | if (!createOrg(standIn.app.db, "gardeners", alice.id).ok) throw new Error("org"); | |
| 276 | expect((await mcp(alice, "invite", { repo: name(), who: "gardeners" })).text).toContain("Only a person is invited as a contributor"); | |
| 277 | expect((await mcp(alice, "invite", { repo: name(), who: "alice" })).text).toContain("They already write here"); | |
| 278 | expect((await mcp(alice, "invite", { repo: name(), who: "carol", remove: true })).text).toContain("They are not a contributor here."); | |
| 279 | }); | |
| 280 | ||
| 281 | test("a contributor lands nothing: no write, no merge, no settings; they hand work to the crew and nothing else", async () => { | |
| 282 | const { app } = standIn; | |
| 283 | expect(canWrite(app.db, fresh(), ben)).toBe(false); | |
| 284 | // A pull to try to land: refused before anything is read of it. | |
| 285 | const proposed = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title: "A path", body: "", kind: "pull" }); | |
| 286 | if (!proposed.ok) throw new Error(proposed.error); | |
| 287 | app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', 'path', 'a', 'b')", [proposed.value.id]); | |
| 288 | const landed = await mergePull(app, ben, fresh(), getPull(app.db, repo.id, proposed.value.number)!, "merge"); | |
| 289 | expect(landed.ok).toBe(false); | |
| 290 | expect((await updateRepoSettings(app, ben, fresh(), { autonomySlots: 9 })).ok).toBe(false); | |
| 291 | expect(fresh().autonomySlots).not.toBe(9); | |
| 292 | // `assignIssue`'s one widening: a contributor hands an issue to an agent on the crew, and may | |
| 293 | // neither assign a person nor take the assignee off. | |
| 294 | const work = openIssue(app, ben, fresh(), { title: "Water the beans", body: "b" }); | |
| 295 | if (!work.ok) throw new Error(String(work.error)); | |
| 296 | expect(assignIssue(app, ben, fresh(), work.value, standIn.bot).ok).toBe(true); | |
| 297 | expect(assignIssue(app, ben, fresh(), work.value, alice).ok).toBe(false); | |
| 298 | expect(assignIssue(app, ben, fresh(), work.value, null).ok).toBe(false); | |
| 299 | }); | |
| 300 | ||
| 301 | test("the terminal lists who works on it, invites by a confirm and takes off by a confirm; a contributor is refused", async () => { | |
| 302 | const drive = async (who: User, keys: string[]) => { | |
| 303 | const terminal = headlessTerminal(160, 44); | |
| 304 | const { app: tui, session } = createForgeApp(standIn.app, { sshUsername: who.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: who }, { terminal, exitHooks: false }); | |
| 305 | tui.start(); | |
| 306 | await settleApp(tui); | |
| 307 | tui.push(contributorsScreen(session, tui.ctx, fresh())); | |
| 308 | await settleApp(tui); | |
| 309 | for (const k of keys) { | |
| 310 | terminal.feed(k); | |
| 311 | await settleApp(tui); | |
| 312 | } | |
| 313 | const shown = tui.screen.toText(); | |
| 314 | tui.stop(); | |
| 315 | return shown; | |
| 316 | }; | |
| 317 | expect(await drive(alice, [])).toContain("ben"); | |
| 318 | await drive(alice, ["a", "dave", "\r", "\x1b[C", "\r"]); | |
| 319 | expect(canRead(standIn.app.db, fresh(), dave)).toBe(true); | |
| 320 | // dave is the second in the list: down once, take off, confirm. | |
| 321 | await drive(alice, ["j", "d", "\x1b[C", "\r"]); | |
| 322 | expect(canRead(standIn.app.db, fresh(), dave)).toBe(false); | |
| 323 | expect(await drive(ben, [])).toContain("Only the repository's admin"); | |
| 324 | }, 30_000); | |
| 325 | }); | |
| 326 | ||
| 327 | describe("taking someone off is at once", () => { | |
| 328 | test("dave's next request after removal reads, enters and directs nothing", async () => { | |
| 329 | const { app } = standIn; | |
| 330 | expect(await letIn(dave)).toContain("dave works on alice/garden now"); | |
| 331 | expect((await page(dave, `/${name()}`)).status).toBe(200); | |
| 332 | expect(await takeOff(dave)).toContain("dave is no longer a contributor"); | |
| 333 | expect((await page(dave, `/${name()}`)).status).toBe(404); | |
| 334 | expect([canRead(app.db, fresh(), dave), mayDirectCrew(app.db, fresh(), dave)]).toEqual([false, false]); | |
| 335 | expect(readableRepoIds(app.db, dave, [repo.id]).has(repo.id)).toBe(false); | |
| 336 | expect((await mcp(dave, "tell", { repo: name(), text: "Make it blue" })).error).toBe(true); | |
| 337 | }); | |
| 338 | }); | |
| 339 | ||
| 340 | describe("money: a contributor's asks run on the owner's crew, and the week's cap holds them", () => { | |
| 341 | test("ben's tell, in his own request, is not sent: past the cap it waits, and its log says why", async () => { | |
| 342 | const { app } = standIn; | |
| 343 | const sub = addSubscription(app.db, standIn.dataDir, { | |
| 344 | name: "main", | |
| 345 | token: "sk-ant-oat01-invite-contributors", | |
| 346 | }); | |
| 347 | if (!sub.ok) throw new Error(sub.error); | |
| 348 | setHeadroom(app.db, sub.value.id, 0); | |
| 349 | app.db | |
| 350 | .query( | |
| 351 | "INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', ?2)", | |
| 352 | ) | |
| 353 | .run(repo.id, sub.value.id); | |
| 354 | const now = Date.now(); | |
| 355 | noteMeasure(app.db, sub.value.id, { | |
| 356 | window: "week", | |
| 357 | usedPct: 95, | |
| 358 | resetsAt: new Date(now + 3.5 * 86_400_000).toISOString(), | |
| 359 | observedAt: new Date(now).toISOString(), | |
| 360 | }); | |
| 361 | forgetWeek(); | |
| 362 | const on = await updateRepoSettings(app, alice, fresh(), { | |
| 363 | autonomy: "autonomous", | |
| 364 | autonomyDirection: "Ship.", | |
| 365 | autonomySlots: 4, | |
| 366 | autonomyBy: alice.id, | |
| 367 | }); | |
| 368 | expect(on.ok).toBe(true); | |
| 369 | addCrew(app.db, repo.id, standIn.bot.id, alice.id); | |
| 370 | const told = await actingVia({ userId: ben.id, door: "session" }, () => | |
| 371 | tell(app, ben, fresh(), "Make the button blue"), | |
| 372 | ); | |
| 373 | if (!told.ok) throw new Error(String(told.error)); | |
| 374 | expect(told.value.assigned).toBe(true); | |
| 375 | const run = (): Run | undefined => | |
| 376 | listRuns(app.db, repo.id, { kind: "agent", limit: 20 }).find( | |
| 377 | (r) => r.issueId === told.value.issue.id, | |
| 378 | ); | |
| 379 | await pollUntil( | |
| 380 | () => | |
| 381 | run() !== undefined && | |
| 382 | readRunLog(app.config.dataDir, run()!.id) | |
| 383 | .lines.join("\n") | |
| 384 | .includes("95% of the week used"), | |
| 385 | "ben's run to wait at the cap", | |
| 386 | 8_000, | |
| 387 | ); | |
| 388 | expect([run()!.state, run()!.sent]).toEqual(["queued", false]); | |
| 389 | }, 30_000); | |
| 390 | ||
| 391 | test("an outsider's run no longer passes the weekly cap: only writers' runs do", async () => { | |
| 392 | const { app } = standIn; | |
| 393 | // The owner lets people who cannot write direct the crew, and anyone may read it. | |
| 394 | const open = await updateRepoSettings(app, alice, fresh(), { crewOutsiders: true, visibility: "public" }); | |
| 395 | expect(open.ok).toBe(true); | |
| 396 | expect([canRead(app.db, fresh(), carol), canWrite(app.db, fresh(), carol), mayDirectCrew(app.db, fresh(), carol)]).toEqual([true, false, true]); | |
| 397 | const bot = getAgentByName(app.db, "bot")!; | |
| 398 | // The same run, asked by each in their own request: carol's is not sent, so the week's cap | |
| 399 | // holds it (before, any person's own request passed the cap); alice's, who writes here, is | |
| 400 | // sent. | |
| 401 | const asked = (who: User, title: string) => { | |
| 402 | const made = openIssue(app, alice, fresh(), { title, body: "Make it green." }); | |
| 403 | if (!made.ok) throw new Error(String(made.error)); | |
| 404 | return actingVia({ userId: who.id, door: "session" }, () => | |
| 405 | queueAgentRun(app, fresh(), made.value, bot, "assigned", who.id, undefined, undefined, false, false, true), | |
| 406 | ); | |
| 407 | }; | |
| 408 | // A member, whose own allowance could start a run: what holds it is the cap alone. | |
| 409 | promote(app.db, carol); | |
| 410 | const outsider = asked(carol, "The header, by an outsider"); | |
| 411 | const owner = asked(alice, "The header, by the owner"); | |
| 412 | expect([outsider?.sent, owner?.sent]).toEqual([false, true]); | |
| 413 | await pollUntil(() => readRunLog(app.config.dataDir, outsider!.id).lines.join("\n").includes("95% of the week used"), "the outsider's run to wait at the cap", 8_000); | |
| 414 | }, 30_000); | |
| 415 | }); |
test/mcp-forge-protocol.test.ts +1
| @@ -150,6 +150,7 @@ describe("the forge over MCP: protocol", () => { | ||
| 150 | 150 | "seal", |
| 151 | 151 | "secrets", |
| 152 | 152 | "issue_teams", |
| 153 | "invite", | |
| 153 | 154 | "issues", |
| 154 | 155 | "iterations", |
| 155 | 156 | "keep_plan", |
test/mcp-talk-tools.test.ts +1
| @@ -283,6 +283,7 @@ describe("every write Talk's agent is newly listed is held after it reads someon | ||
| 283 | 283 | branches: { repo: "alice/hostile", name: "evil", action: "create" }, |
| 284 | 284 | close: { repo: "alice/hostile", number: 1 }, |
| 285 | 285 | edit: { repo: "alice/hostile", number: 1, title: "pwned" }, |
| 286 | invite: { repo: "alice/hostile", who: "mallory" }, | |
| 286 | 287 | keep_plan: { repo: "alice/hostile", number: 1, items: ["pwned"] }, |
| 287 | 288 | labels: { repo: "alice/hostile", number: 1, labels: ["pwned"] }, |
| 288 | 289 | merge: { repo: "alice/hostile", number: 2, dryRun: false }, |
new above
offline
A DISTINCT subquery is materialized and scanned on every repository read. Replace it with a correlated
EXISTS (SELECT 1 FROM repo_contributor WHERE repo_id = repo.id) AS has_contributors.