Public: anyone can read this; the crew can change it.
Teams as a forge primitive: a named group of crew members (and people) with a goal, a shared map, roles, and coordination metrics #523
scout/forge:scout/484-teams-as-a-forge-primitive-a-named-group → main 2 commits fork
12 files
changed +785
−14
README.md +22
| @@ -278,6 +278,28 @@ model, a brief in its own voice and a spend budget; a repository admin puts it | ||
| 278 | 278 | on the repository's **crew**, which is the one grant an agent can hold — it |
| 279 | 279 | reads and writes that repository and administers nothing. |
| 280 | 280 | |
| 281 | ### Teams drive the crew | |
| 282 | ||
| 283 | A repository's crew is its own roster plus the **agents on the teams assigned | |
| 284 | to it**, each in the role (`builder`, `planner`, `reviewer`) their team | |
| 285 | membership carries. The repo roster wins for an agent on both, so today's | |
| 286 | per-repo crew keeps working untouched until it is migrated. People on a team | |
| 287 | gain no crew seat from it. | |
| 288 | ||
| 289 | sh | |
| 290 | # a role on a member (also changes the role of an existing member) | |
| 291 | POST /api/v1/orgs/:org/teams/:team/members {"user":"juniper","role":"reviewer"} | |
| 292 | # put a team on a repo (admin of the repo and of the team's org); GET lists | |
| 293 | PUT|DELETE /api/v1/repos/:owner/:name/teams/:org/:team | |
| 294 | # members, repos and coordination metrics over ?hours= (default 24) | |
| 295 | GET /api/v1/orgs/:org/teams/:team | |
| 296 | ||
| 297 | ||
| 298 | Metrics are a read over the run, pull, review and issue ledgers (nothing is | |
| 299 | stored): throughput, pull lead time, pull→review hand-off, rework rate (pulls | |
| 300 | with changes requested), duplicate issues, held slot-hours (runs cancelled by | |
| 301 | hand after 20+ min), parallelism against slots, and cost per merged pull. | |
| 302 | ||
| 281 | 303 | Assign an issue to an agent and it starts: the forge clones the repository, |
| 282 | 304 | puts the agent on a branch named after the issue, and runs Claude Code |
| 283 | 305 | headless with a brief that says who it is, what the task is, how to finish, |
forge.json +1 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | "ready": 90 |
| 7 | 7 | }, |
| 8 | 8 | "check": { |
| 9 | "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts", | |
| 9 | "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts test/teams.test.ts", | |
| 10 | 10 | "timeout": 1800 |
| 11 | 11 | } |
| 12 | 12 | } |
src/actions/orgs.ts +9
| @@ -16,6 +16,8 @@ import { | ||
| 16 | 16 | type Permission, |
| 17 | 17 | type Team, |
| 18 | 18 | } from "../core/orgs.ts"; |
| 19 | import { isCrewRole, type CrewRole } from "../core/agents.ts"; | |
| 20 | import { setMemberRole as setRole } from "../core/teams.ts"; | |
| 19 | 21 | import { getUserByName, type User } from "../core/users.ts"; |
| 20 | 22 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 21 | 23 | import { requireOrgAdmin, requireUser } from "./access.ts"; |
| @@ -86,6 +88,7 @@ export function addTeamMember( | ||
| 86 | 88 | org: User, |
| 87 | 89 | team: Team, |
| 88 | 90 | username: string, |
| 91 | role?: CrewRole, | |
| 89 | 92 | ): Result<{ added: boolean }, "not_found" | "no_such_user"> { |
| 90 | 93 | const admin = requireOrgAdmin(app, actor, org); |
| 91 | 94 | if (!admin.ok) return admin; |
| @@ -93,6 +96,8 @@ export function addTeamMember( | ||
| 93 | 96 | const user = getUserByName(app.db, username); |
| 94 | 97 | if (!user || user.kind === "org") return err("no_such_user"); |
| 95 | 98 | const added = insertMember(app.db, team, user.id); |
| 99 | // Naming a role sets it, new member or old; silence leaves it be. | |
| 100 | if (role) setRole(app.db, team.id, user.id, role); | |
| 96 | 101 | if (added) |
| 97 | 102 | app.bus.append({ |
| 98 | 103 | kind: "team.member_added", |
| @@ -124,3 +129,7 @@ export function removeTeamMember( | ||
| 124 | 129 | }); |
| 125 | 130 | return ok({ removed }); |
| 126 | 131 | } |
| 132 | ||
| 133 | /** Parse a role from input: absent is "none", unrecognised is "invalid". */ | |
| 134 | export const roleOf = (raw: unknown): CrewRole | "none" | "invalid" => | |
| 135 | raw === undefined || raw === "" ? "none" : isCrewRole(raw) ? raw : "invalid"; |
src/actions/teams.ts added +64
| @@ -0,0 +1,64 @@ | ||
| 1 | /** | |
| 2 | * Teams on repositories: assigning a team puts its agents on the repo's crew. | |
| 3 | * Both sides must agree — an admin of the repository and an admin of the | |
| 4 | * team's org — so no one can draft another org's agents onto their own repo. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { Team } from "../core/orgs.ts"; | |
| 9 | import type { Repo } from "../core/repos.ts"; | |
| 10 | import { assignTeam, unassignTeam } from "../core/teams.ts"; | |
| 11 | import { getUserById, type User } from "../core/users.ts"; | |
| 12 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 13 | import { requireOrgAdmin, requireRepoAdmin } from "./access.ts"; | |
| 14 | ||
| 15 | function admins( | |
| 16 | app: App, | |
| 17 | actor: User | undefined, | |
| 18 | repo: Repo, | |
| 19 | team: Team, | |
| 20 | ): Result<User, "not_found"> { | |
| 21 | const repoAdmin = requireRepoAdmin(app, actor, repo); | |
| 22 | if (!repoAdmin.ok) return repoAdmin; | |
| 23 | const org = getUserById(app.db, team.orgId); | |
| 24 | if (!org) return err("not_found"); | |
| 25 | return requireOrgAdmin(app, actor, org); | |
| 26 | } | |
| 27 | ||
| 28 | export function assignTeamToRepo( | |
| 29 | app: App, | |
| 30 | actor: User | undefined, | |
| 31 | repo: Repo, | |
| 32 | team: Team, | |
| 33 | ): Result<{ added: boolean }, "not_found"> { | |
| 34 | const admin = admins(app, actor, repo, team); | |
| 35 | if (!admin.ok) return admin; | |
| 36 | const added = assignTeam(app.db, repo.id, team.id, admin.value.id); | |
| 37 | if (added) | |
| 38 | app.bus.append({ | |
| 39 | kind: "team.assigned", | |
| 40 | repoId: repo.id, | |
| 41 | actorId: admin.value.id, | |
| 42 | payload: { teamId: team.id, name: team.name }, | |
| 43 | }); | |
| 44 | return ok({ added }); | |
| 45 | } | |
| 46 | ||
| 47 | export function unassignTeamFromRepo( | |
| 48 | app: App, | |
| 49 | actor: User | undefined, | |
| 50 | repo: Repo, | |
| 51 | team: Team, | |
| 52 | ): Result<{ removed: boolean }, "not_found"> { | |
| 53 | const admin = admins(app, actor, repo, team); | |
| 54 | if (!admin.ok) return admin; | |
| 55 | const removed = unassignTeam(app.db, repo.id, team.id); | |
| 56 | if (removed) | |
| 57 | app.bus.append({ | |
| 58 | kind: "team.unassigned", | |
| 59 | repoId: repo.id, | |
| 60 | actorId: admin.value.id, | |
| 61 | payload: { teamId: team.id, name: team.name }, | |
| 62 | }); | |
| 63 | return ok({ removed }); | |
| 64 | } |
src/core/agents.ts +10 −10
| @@ -176,7 +176,7 @@ export function isCrew(db: Database, repoId: string, userId: string): boolean { | ||
| 176 | 176 | .query< |
| 177 | 177 | { n: number }, |
| 178 | 178 | [string, string] |
| 179 | >("SELECT 1 AS n FROM repo_crew WHERE repo_id = ?1 AND user_id = ?2") | |
| 179 | >("SELECT 1 AS n FROM crew_member WHERE repo_id = ?1 AND user_id = ?2") | |
| 180 | 180 | .get(repoId, userId) !== null |
| 181 | 181 | ); |
| 182 | 182 | } |
| @@ -185,10 +185,10 @@ export function isCrew(db: Database, repoId: string, userId: string): boolean { | ||
| 185 | 185 | export function listCrew(db: Database, repoId: string): Agent[] { |
| 186 | 186 | const rows = db |
| 187 | 187 | .query<AgentRow, [string]>( |
| 188 | `SELECT agent.* FROM repo_crew | |
| 189 | JOIN agent ON agent.user_id = repo_crew.user_id | |
| 188 | `SELECT agent.* FROM crew_member | |
| 189 | JOIN agent ON agent.user_id = crew_member.user_id | |
| 190 | 190 | JOIN user ON user.id = agent.user_id |
| 191 | WHERE repo_crew.repo_id = ?1 ORDER BY user.username COLLATE NOCASE`, | |
| 191 | WHERE crew_member.repo_id = ?1 ORDER BY user.username COLLATE NOCASE`, | |
| 192 | 192 | ) |
| 193 | 193 | .all(repoId); |
| 194 | 194 | const out: Agent[] = []; |
| @@ -211,9 +211,9 @@ export function crewForRepos( | ||
| 211 | 211 | const batch = unique.slice(i, i + CHUNK); |
| 212 | 212 | const rows = db |
| 213 | 213 | .query<{ repo_id: string; username: string }, string[]>( |
| 214 | `SELECT repo_crew.repo_id, user.username FROM repo_crew | |
| 215 | JOIN user ON user.id = repo_crew.user_id | |
| 216 | WHERE repo_crew.repo_id IN (${batch.map((_, n) => `?${n + 1}`).join(",")}) | |
| 214 | `SELECT crew_member.repo_id, user.username FROM crew_member | |
| 215 | JOIN user ON user.id = crew_member.user_id | |
| 216 | WHERE crew_member.repo_id IN (${batch.map((_, n) => `?${n + 1}`).join(",")}) | |
| 217 | 217 | ORDER BY user.username COLLATE NOCASE`, |
| 218 | 218 | ) |
| 219 | 219 | .all(...batch); |
| @@ -274,7 +274,7 @@ export function crewRole( | ||
| 274 | 274 | .query< |
| 275 | 275 | { role: string }, |
| 276 | 276 | [string, string] |
| 277 | >("SELECT role FROM repo_crew WHERE repo_id = ?1 AND user_id = ?2") | |
| 277 | >("SELECT role FROM crew_member WHERE repo_id = ?1 AND user_id = ?2") | |
| 278 | 278 | .get(repoId, userId); |
| 279 | 279 | return row && isCrewRole(row.role) ? row.role : row ? "builder" : undefined; |
| 280 | 280 | } |
| @@ -302,7 +302,7 @@ export function listCrewRoles( | ||
| 302 | 302 | const roles = new Map( |
| 303 | 303 | db |
| 304 | 304 | .query<{ user_id: string; role: string }, [string]>( |
| 305 | "SELECT user_id, role FROM repo_crew WHERE repo_id = ?1", | |
| 305 | "SELECT user_id, role FROM crew_member WHERE repo_id = ?1", | |
| 306 | 306 | ) |
| 307 | 307 | .all(repoId) |
| 308 | 308 | .map( |
| @@ -332,7 +332,7 @@ export function reposWithBuilder( | ||
| 332 | 332 | const batch = unique.slice(i, i + CHUNK); |
| 333 | 333 | const rows = db |
| 334 | 334 | .query<{ repo_id: string }, string[]>( |
| 335 | `SELECT DISTINCT repo_id FROM repo_crew | |
| 335 | `SELECT DISTINCT repo_id FROM crew_member | |
| 336 | 336 | WHERE role = 'builder' AND repo_id IN (${batch.map((_, n) => `?${n + 1}`).join(",")})`, |
| 337 | 337 | ) |
| 338 | 338 | .all(...batch); |
src/core/repos.ts +1 −1
| @@ -609,7 +609,7 @@ function onCrew(db: Database, repo: Repo, user: User | undefined): boolean { | ||
| 609 | 609 | .query< |
| 610 | 610 | { n: number }, |
| 611 | 611 | [string, string] |
| 612 | >("SELECT 1 AS n FROM repo_crew WHERE repo_id = ?1 AND user_id = ?2") | |
| 612 | >("SELECT 1 AS n FROM crew_member WHERE repo_id = ?1 AND user_id = ?2") | |
| 613 | 613 | .get(repo.id, user.id) !== null |
| 614 | 614 | ); |
| 615 | 615 | } |
src/core/schema.ts +32
| @@ -1081,4 +1081,36 @@ export const migrations: readonly string[] = [ | ||
| 1081 | 1081 | PRIMARY KEY (operation_id, position) |
| 1082 | 1082 | ); |
| 1083 | 1083 | `, |
| 1084 | ||
| 1085 | ||
| 1086 | // 41 — teams drive the crew. A team member carries a role (planner, | |
| 1087 | // builder, reviewer); a repository is assigned teams; and `crew_member` is | |
| 1088 | // the one place that reads "who works here" — the repo's own roster | |
| 1089 | // (repo_crew) first, then the agents on its teams for anyone not listed. | |
| 1090 | // Agents only: a person on a team gains no repo access from this. | |
| 1091 | ` | |
| 1092 | ALTER TABLE team_member ADD COLUMN role TEXT NOT NULL DEFAULT 'builder' | |
| 1093 | CHECK (role IN ('builder','planner','reviewer')); | |
| 1094 | ||
| 1095 | CREATE TABLE repo_team ( | |
| 1096 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 1097 | team_id TEXT NOT NULL REFERENCES team(id) ON DELETE CASCADE, | |
| 1098 | added_by TEXT REFERENCES user(id) ON DELETE SET NULL, | |
| 1099 | added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 1100 | PRIMARY KEY (repo_id, team_id) | |
| 1101 | ); | |
| 1102 | CREATE INDEX repo_team_team ON repo_team(team_id); | |
| 1103 | ||
| 1104 | CREATE VIEW crew_member AS | |
| 1105 | SELECT repo_id, user_id, role FROM repo_crew | |
| 1106 | UNION ALL | |
| 1107 | SELECT repo_team.repo_id, team_member.user_id, MIN(team_member.role) | |
| 1108 | FROM repo_team | |
| 1109 | JOIN team_member ON team_member.team_id = repo_team.team_id | |
| 1110 | JOIN user ON user.id = team_member.user_id AND user.is_agent = 1 | |
| 1111 | WHERE NOT EXISTS (SELECT 1 FROM repo_crew | |
| 1112 | WHERE repo_crew.repo_id = repo_team.repo_id | |
| 1113 | AND repo_crew.user_id = team_member.user_id) | |
| 1114 | GROUP BY repo_team.repo_id, team_member.user_id; | |
| 1115 | `, | |
| 1084 | 1116 | ]; |
src/core/teams.ts added +325
| @@ -0,0 +1,325 @@ | ||
| 1 | /** | |
| 2 | * Teams as the crew. A team (core/orgs.ts) is assigned to repositories; the | |
| 3 | * agents on it work there, each in the role their membership carries. The | |
| 4 | * `crew_member` view (schema 40) is where that is read; this module writes the | |
| 5 | * assignment and measures how a team coordinates, from the same ledger the | |
| 6 | * rest of the forge keeps — runs, pulls, reviews. Nothing here is stored: a | |
| 7 | * metric is a read over a window. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import { isCrewRole, type CrewRole } from "./agents.ts"; | |
| 12 | import type { Team } from "./orgs.ts"; | |
| 13 | ||
| 14 | export interface TeamRepo { | |
| 15 | readonly repoId: string; | |
| 16 | readonly owner: string; | |
| 17 | readonly name: string; | |
| 18 | } | |
| 19 | ||
| 20 | export function assignTeam( | |
| 21 | db: Database, | |
| 22 | repoId: string, | |
| 23 | teamId: string, | |
| 24 | addedBy?: string, | |
| 25 | ): boolean { | |
| 26 | return ( | |
| 27 | db | |
| 28 | .query( | |
| 29 | "INSERT OR IGNORE INTO repo_team (repo_id, team_id, added_by) VALUES (?1, ?2, ?3)", | |
| 30 | ) | |
| 31 | .run(repoId, teamId, addedBy ?? null).changes > 0 | |
| 32 | ); | |
| 33 | } | |
| 34 | ||
| 35 | export function unassignTeam( | |
| 36 | db: Database, | |
| 37 | repoId: string, | |
| 38 | teamId: string, | |
| 39 | ): boolean { | |
| 40 | return ( | |
| 41 | db | |
| 42 | .query("DELETE FROM repo_team WHERE repo_id = ?1 AND team_id = ?2") | |
| 43 | .run(repoId, teamId).changes > 0 | |
| 44 | ); | |
| 45 | } | |
| 46 | ||
| 47 | /** The teams assigned to a repository. */ | |
| 48 | export function listRepoTeams(db: Database, repoId: string): Team[] { | |
| 49 | return db | |
| 50 | .query< | |
| 51 | { id: string; org_id: string; name: string; permission: Team["permission"] }, | |
| 52 | [string] | |
| 53 | >( | |
| 54 | `SELECT team.* FROM repo_team JOIN team ON team.id = repo_team.team_id | |
| 55 | WHERE repo_team.repo_id = ?1 ORDER BY team.name`, | |
| 56 | ) | |
| 57 | .all(repoId) | |
| 58 | .map((r) => ({ | |
| 59 | id: r.id, | |
| 60 | orgId: r.org_id, | |
| 61 | name: r.name, | |
| 62 | permission: r.permission, | |
| 63 | })); | |
| 64 | } | |
| 65 | ||
| 66 | /** The repositories a team is assigned to. */ | |
| 67 | export function listTeamRepos(db: Database, teamId: string): TeamRepo[] { | |
| 68 | return db | |
| 69 | .query<{ id: string; owner: string; name: string }, [string]>( | |
| 70 | `SELECT repo.id, user.username AS owner, repo.name FROM repo_team | |
| 71 | JOIN repo ON repo.id = repo_team.repo_id | |
| 72 | JOIN user ON user.id = repo.owner_id | |
| 73 | WHERE repo_team.team_id = ?1 ORDER BY user.username, repo.name`, | |
| 74 | ) | |
| 75 | .all(teamId) | |
| 76 | .map((r) => ({ repoId: r.id, owner: r.owner, name: r.name })); | |
| 77 | } | |
| 78 | ||
| 79 | /** Set the role a member plays in a team. False when they are not a member. */ | |
| 80 | export function setMemberRole( | |
| 81 | db: Database, | |
| 82 | teamId: string, | |
| 83 | userId: string, | |
| 84 | role: CrewRole, | |
| 85 | ): boolean { | |
| 86 | if (!isCrewRole(role)) return false; | |
| 87 | return ( | |
| 88 | db | |
| 89 | .query( | |
| 90 | "UPDATE team_member SET role = ?3 WHERE team_id = ?1 AND user_id = ?2", | |
| 91 | ) | |
| 92 | .run(teamId, userId, role).changes > 0 | |
| 93 | ); | |
| 94 | } | |
| 95 | ||
| 96 | export function listMemberRoles( | |
| 97 | db: Database, | |
| 98 | teamId: string, | |
| 99 | ): { username: string; kind: string; role: CrewRole }[] { | |
| 100 | return db | |
| 101 | .query<{ username: string; kind: string; role: string }, [string]>( | |
| 102 | `SELECT user.username, CASE WHEN user.is_agent = 1 THEN 'agent' ELSE 'user' END AS kind, | |
| 103 | team_member.role FROM team_member | |
| 104 | JOIN user ON user.id = team_member.user_id | |
| 105 | WHERE team_member.team_id = ?1 ORDER BY user.username COLLATE NOCASE`, | |
| 106 | ) | |
| 107 | .all(teamId) | |
| 108 | .map((r) => ({ | |
| 109 | username: r.username, | |
| 110 | kind: r.kind, | |
| 111 | role: isCrewRole(r.role) ? r.role : "builder", | |
| 112 | })); | |
| 113 | } | |
| 114 | ||
| 115 | // ---- coordination metrics ---- | |
| 116 | ||
| 117 | export interface TeamMetrics { | |
| 118 | readonly windowHours: number; | |
| 119 | readonly members: number; | |
| 120 | readonly repos: number; | |
| 121 | readonly slots: number; | |
| 122 | readonly issuesClosed: number; | |
| 123 | readonly throughputPerHour: number; | |
| 124 | readonly pullsOpened: number; | |
| 125 | readonly pullsMerged: number; | |
| 126 | readonly leadTimeHoursMedian: number | null; | |
| 127 | readonly handoffPullToReviewMinMedian: number | null; | |
| 128 | readonly pullsWithoutReview: number; | |
| 129 | readonly reworkRate: number | null; | |
| 130 | readonly duplicateIssues: number; | |
| 131 | readonly runs: { total: number; ok: number; failed: number; cancelled: number }; | |
| 132 | readonly heldRuns: number; | |
| 133 | readonly heldSlotHours: number; | |
| 134 | readonly busySlotHours: number; | |
| 135 | readonly avgParallelism: number; | |
| 136 | readonly peakParallelism: number; | |
| 137 | readonly costUsd: number; | |
| 138 | readonly costPerShippedUsd: number | null; | |
| 139 | } | |
| 140 | ||
| 141 | const HELD_MIN = 20; | |
| 142 | const ms = (s: string) => Date.parse(s); | |
| 143 | ||
| 144 | function median(xs: number[]): number | null { | |
| 145 | if (xs.length === 0) return null; | |
| 146 | const s = [...xs].sort((a, b) => a - b); | |
| 147 | const m = s.length >> 1; | |
| 148 | const v = s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2; | |
| 149 | return Math.round(v * 10) / 10; | |
| 150 | } | |
| 151 | const round1 = (n: number) => Math.round(n * 10) / 10; | |
| 152 | ||
| 153 | /** | |
| 154 | * How a team coordinated over the last `hours`: its agents' runs, and the | |
| 155 | * pulls and issues of the repositories it is assigned to. A team with no | |
| 156 | * repositories or no agents measures as zeros, never as an error. | |
| 157 | */ | |
| 158 | export function teamMetrics( | |
| 159 | db: Database, | |
| 160 | teamId: string, | |
| 161 | hours: number, | |
| 162 | now: number = Date.now(), | |
| 163 | ): TeamMetrics { | |
| 164 | const h = Math.min(Math.max(Math.floor(hours) || 24, 1), 24 * 90); | |
| 165 | const t0 = now - h * 3600_000; | |
| 166 | const since = new Date(t0).toISOString(); | |
| 167 | ||
| 168 | const agents = db | |
| 169 | .query<{ user_id: string }, [string]>( | |
| 170 | `SELECT team_member.user_id FROM team_member | |
| 171 | JOIN user ON user.id = team_member.user_id AND user.is_agent = 1 | |
| 172 | WHERE team_member.team_id = ?1`, | |
| 173 | ) | |
| 174 | .all(teamId) | |
| 175 | .map((r) => r.user_id); | |
| 176 | const members = | |
| 177 | db | |
| 178 | .query<{ n: number }, [string]>( | |
| 179 | "SELECT COUNT(*) AS n FROM team_member WHERE team_id = ?1", | |
| 180 | ) | |
| 181 | .get(teamId)?.n ?? 0; | |
| 182 | const repos = db | |
| 183 | .query<{ repo_id: string; slots: number }, [string]>( | |
| 184 | `SELECT repo_team.repo_id, repo.autonomy_slots AS slots FROM repo_team | |
| 185 | JOIN repo ON repo.id = repo_team.repo_id WHERE repo_team.team_id = ?1`, | |
| 186 | ) | |
| 187 | .all(teamId); | |
| 188 | const slots = repos.reduce((n, r) => n + r.slots, 0); | |
| 189 | const marks = (xs: readonly unknown[]) => xs.map(() => "?").join(","); | |
| 190 | const repoIds = repos.map((r) => r.repo_id); | |
| 191 | ||
| 192 | const empty = agents.length === 0 || repoIds.length === 0; | |
| 193 | ||
| 194 | const runs = empty | |
| 195 | ? [] | |
| 196 | : db | |
| 197 | .query< | |
| 198 | { | |
| 199 | state: string; | |
| 200 | summary: string; | |
| 201 | cost_usd: number; | |
| 202 | started_at: string; | |
| 203 | finished_at: string | null; | |
| 204 | }, | |
| 205 | string[] | |
| 206 | >( | |
| 207 | `SELECT state, summary, cost_usd, started_at, finished_at FROM run | |
| 208 | WHERE kind = 'agent' AND started_at IS NOT NULL | |
| 209 | AND repo_id IN (${marks(repoIds)}) AND actor_id IN (${marks(agents)}) | |
| 210 | AND (finished_at IS NULL OR finished_at >= ?)`, | |
| 211 | ) | |
| 212 | .all(...repoIds, ...agents, since); | |
| 213 | ||
| 214 | const edges: [number, number][] = []; | |
| 215 | let busy = 0; | |
| 216 | let held = 0; | |
| 217 | let heldH = 0; | |
| 218 | let cost = 0; | |
| 219 | const count = { total: 0, ok: 0, failed: 0, cancelled: 0 }; | |
| 220 | for (const r of runs) { | |
| 221 | const a = Math.max(ms(r.started_at), t0); | |
| 222 | const b = Math.min(r.finished_at ? ms(r.finished_at) : now, now); | |
| 223 | if (b < a) continue; | |
| 224 | count.total++; | |
| 225 | if (r.state === "ok") count.ok++; | |
| 226 | else if (r.state === "failed") count.failed++; | |
| 227 | else if (r.state === "cancelled") count.cancelled++; | |
| 228 | busy += (b - a) / 3600_000; | |
| 229 | cost += r.cost_usd; | |
| 230 | edges.push([a, 1], [b, -1]); | |
| 231 | const min = (b - a) / 60_000; | |
| 232 | if (r.finished_at && min >= HELD_MIN && r.summary.startsWith("cancelled by")) { | |
| 233 | held++; | |
| 234 | heldH += min / 60; | |
| 235 | } | |
| 236 | } | |
| 237 | edges.sort((x, y) => x[0] - y[0] || x[1] - y[1]); | |
| 238 | let live = 0; | |
| 239 | let peak = 0; | |
| 240 | for (const [, d] of edges) peak = Math.max(peak, (live += d)); | |
| 241 | ||
| 242 | let issuesClosed = 0; | |
| 243 | const pulls: { | |
| 244 | id: string; | |
| 245 | created_at: string; | |
| 246 | merged_at: string | null; | |
| 247 | head_branch: string; | |
| 248 | }[] = []; | |
| 249 | if (repoIds.length > 0 && agents.length > 0) { | |
| 250 | issuesClosed = | |
| 251 | db | |
| 252 | .query<{ n: number }, string[]>( | |
| 253 | `SELECT COUNT(*) AS n FROM issue WHERE kind = 'issue' AND state = 'closed' | |
| 254 | AND closed_at >= ? AND repo_id IN (${marks(repoIds)})`, | |
| 255 | ) | |
| 256 | .get(since, ...repoIds)?.n ?? 0; | |
| 257 | pulls.push( | |
| 258 | ...db | |
| 259 | .query<(typeof pulls)[number], string[]>( | |
| 260 | `SELECT issue.id, issue.created_at, pull.merged_at, pull.head_branch | |
| 261 | FROM issue JOIN pull ON pull.issue_id = issue.id | |
| 262 | WHERE issue.kind = 'pull' AND issue.created_at >= ? | |
| 263 | AND issue.repo_id IN (${marks(repoIds)}) | |
| 264 | AND issue.author_id IN (${marks(agents)})`, | |
| 265 | ) | |
| 266 | .all(since, ...repoIds, ...agents), | |
| 267 | ); | |
| 268 | } | |
| 269 | ||
| 270 | const merged = pulls.filter((p) => p.merged_at !== null); | |
| 271 | const leads = merged.map((p) => (ms(p.merged_at!) - ms(p.created_at)) / 3600_000); | |
| 272 | ||
| 273 | const reviews = new Map<string, { first: number; changes: boolean }>(); | |
| 274 | if (pulls.length > 0 && members > 0) { | |
| 275 | for (const r of db | |
| 276 | .query<{ issue_id: string; state: string; created_at: string }, string[]>( | |
| 277 | `SELECT review.issue_id, review.state, review.created_at FROM review | |
| 278 | JOIN team_member ON team_member.user_id = review.author_id AND team_member.team_id = ? | |
| 279 | WHERE review.issue_id IN (${marks(pulls)})`, | |
| 280 | ) | |
| 281 | .all(teamId, ...pulls.map((p) => p.id))) { | |
| 282 | const cur = reviews.get(r.issue_id) ?? { first: Infinity, changes: false }; | |
| 283 | cur.first = Math.min(cur.first, ms(r.created_at)); | |
| 284 | cur.changes ||= r.state === "changes_requested"; | |
| 285 | reviews.set(r.issue_id, cur); | |
| 286 | } | |
| 287 | } | |
| 288 | const handoffs = pulls | |
| 289 | .filter((p) => reviews.has(p.id)) | |
| 290 | .map((p) => (reviews.get(p.id)!.first - ms(p.created_at)) / 60_000); | |
| 291 | const reworked = pulls.filter((p) => reviews.get(p.id)?.changes).length; | |
| 292 | ||
| 293 | // Duplicate work: two pulls whose branch names one issue, `<agent>/<n>-…`. | |
| 294 | const byNumber = new Map<string, number>(); | |
| 295 | for (const p of pulls) { | |
| 296 | const n = /^[^/]+\/(\d+)-/.exec(p.head_branch)?.[1]; | |
| 297 | if (n) byNumber.set(n, (byNumber.get(n) ?? 0) + 1); | |
| 298 | } | |
| 299 | ||
| 300 | return { | |
| 301 | windowHours: h, | |
| 302 | members, | |
| 303 | repos: repoIds.length, | |
| 304 | slots, | |
| 305 | issuesClosed, | |
| 306 | throughputPerHour: Math.round((issuesClosed / h) * 100) / 100, | |
| 307 | pullsOpened: pulls.length, | |
| 308 | pullsMerged: merged.length, | |
| 309 | leadTimeHoursMedian: median(leads), | |
| 310 | handoffPullToReviewMinMedian: median(handoffs), | |
| 311 | pullsWithoutReview: pulls.length - reviews.size, | |
| 312 | reworkRate: pulls.length ? Math.round((reworked / pulls.length) * 100) / 100 : null, | |
| 313 | duplicateIssues: [...byNumber.values()].filter((n) => n > 1).length, | |
| 314 | runs: count, | |
| 315 | heldRuns: held, | |
| 316 | heldSlotHours: round1(heldH), | |
| 317 | busySlotHours: round1(busy), | |
| 318 | avgParallelism: Math.round((busy / h) * 100) / 100, | |
| 319 | peakParallelism: peak, | |
| 320 | costUsd: Math.round(cost * 100) / 100, | |
| 321 | costPerShippedUsd: merged.length | |
| 322 | ? Math.round((cost / merged.length) * 100) / 100 | |
| 323 | : null, | |
| 324 | }; | |
| 325 | } |
src/core/visibility.ts +1 −1
| @@ -36,7 +36,7 @@ export const REPO_WRITABLE = `( | ||
| 36 | 36 | SELECT team.org_id FROM team |
| 37 | 37 | JOIN team_member ON team_member.team_id = team.id |
| 38 | 38 | WHERE team_member.user_id = ?1 AND team.permission IN ('write','admin')) |
| 39 | OR repo.id IN (SELECT repo_crew.repo_id FROM repo_crew WHERE repo_crew.user_id = ?1) | |
| 39 | OR repo.id IN (SELECT crew_member.repo_id FROM crew_member WHERE crew_member.user_id = ?1) | |
| 40 | 40 | OR EXISTS (SELECT 1 FROM user AS me WHERE me.id = ?1 AND me.is_admin = 1) |
| 41 | 41 | )`; |
| 42 | 42 |
src/feed/affinity.ts +1 −1
| @@ -167,7 +167,7 @@ function seedCrew( | ||
| 167 | 167 | const marks = repos.map((_, n) => `?${n + 1}`).join(","); |
| 168 | 168 | for (const row of db |
| 169 | 169 | .query<{ user_id: string }, string[]>( |
| 170 | `SELECT DISTINCT user_id FROM repo_crew WHERE repo_id IN (${marks})`, | |
| 170 | `SELECT DISTINCT user_id FROM crew_member WHERE repo_id IN (${marks})`, | |
| 171 | 171 | ) |
| 172 | 172 | .all(...repos.map((r) => r.id))) |
| 173 | 173 | aff.add(`actor:${row.user_id}`, "crew", 1, now); |
src/http/api.ts +57
| @@ -24,7 +24,18 @@ import { | ||
| 24 | 24 | createTeam, |
| 25 | 25 | deleteTeam, |
| 26 | 26 | removeTeamMember, |
| 27 | roleOf, | |
| 27 | 28 | } from "../actions/orgs.ts"; |
| 29 | import { | |
| 30 | assignTeamToRepo, | |
| 31 | unassignTeamFromRepo, | |
| 32 | } from "../actions/teams.ts"; | |
| 33 | import { | |
| 34 | listMemberRoles, | |
| 35 | listRepoTeams, | |
| 36 | listTeamRepos, | |
| 37 | teamMetrics, | |
| 38 | } from "../core/teams.ts"; | |
| 28 | 39 | import { |
| 29 | 40 | connectOrigin, |
| 30 | 41 | deleteOriginApp, |
| @@ -1028,18 +1039,64 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1028 | 1039 | return json(listTeamMembers(ctx.app.db, found.team.id).map(publicProfile)); |
| 1029 | 1040 | }); |
| 1030 | 1041 | |
| 1042 | router.add("GET", "/api/v1/orgs/:org/teams/:team", (ctx) => { | |
| 1043 | const found = loadTeam(ctx); | |
| 1044 | if ("error" in found) return found.error; | |
| 1045 | if (!teamVisible(ctx, found.org, found.team)) return notFound(); | |
| 1046 | const hours = Number(ctx.url.searchParams.get("hours") ?? 24); | |
| 1047 | return json({ | |
| 1048 | ...found.team, | |
| 1049 | members: listMemberRoles(ctx.app.db, found.team.id), | |
| 1050 | repos: listTeamRepos(ctx.app.db, found.team.id), | |
| 1051 | metrics: teamMetrics(ctx.app.db, found.team.id, hours), | |
| 1052 | }); | |
| 1053 | }); | |
| 1054 | ||
| 1055 | router.add("PUT", "/api/v1/repos/:owner/:name/teams/:org/:team", (ctx) => { | |
| 1056 | const denied = requireScope(ctx, "admin"); | |
| 1057 | if (denied) return denied; | |
| 1058 | const repo = loadRepo(ctx); | |
| 1059 | if (!repo) return notFound(); | |
| 1060 | const found = loadTeam(ctx); | |
| 1061 | if ("error" in found) return found.error; | |
| 1062 | const done = assignTeamToRepo(ctx.app, ctx.auth.user, repo, found.team); | |
| 1063 | if (!done.ok) return notFound(); | |
| 1064 | return json(done.value, done.value.added ? 201 : 200); | |
| 1065 | }); | |
| 1066 | ||
| 1067 | router.add("DELETE", "/api/v1/repos/:owner/:name/teams/:org/:team", (ctx) => { | |
| 1068 | const denied = requireScope(ctx, "admin"); | |
| 1069 | if (denied) return denied; | |
| 1070 | const repo = loadRepo(ctx); | |
| 1071 | if (!repo) return notFound(); | |
| 1072 | const found = loadTeam(ctx); | |
| 1073 | if ("error" in found) return found.error; | |
| 1074 | const done = unassignTeamFromRepo(ctx.app, ctx.auth.user, repo, found.team); | |
| 1075 | if (!done.ok) return notFound(); | |
| 1076 | return new Response(null, { status: 204 }); | |
| 1077 | }); | |
| 1078 | ||
| 1079 | router.add("GET", "/api/v1/repos/:owner/:name/teams", (ctx) => { | |
| 1080 | const repo = loadRepo(ctx); | |
| 1081 | if (!repo) return notFound(); | |
| 1082 | return json({ items: listRepoTeams(ctx.app.db, repo.id), next_cursor: null }); | |
| 1083 | }); | |
| 1084 | ||
| 1031 | 1085 | router.add("POST", "/api/v1/orgs/:org/teams/:team/members", async (ctx) => { |
| 1032 | 1086 | const denied = requireScope(ctx, "admin"); |
| 1033 | 1087 | if (denied) return denied; |
| 1034 | 1088 | const found = loadTeam(ctx); |
| 1035 | 1089 | if ("error" in found) return found.error; |
| 1036 | 1090 | const input = await body(ctx.request); |
| 1091 | const role = roleOf(input.role); | |
| 1092 | if (role === "invalid") return json({ error: "invalid_role" }, 422); | |
| 1037 | 1093 | const added = addTeamMember( |
| 1038 | 1094 | ctx.app, |
| 1039 | 1095 | ctx.auth.user, |
| 1040 | 1096 | found.org, |
| 1041 | 1097 | found.team, |
| 1042 | 1098 | str(input.user), |
| 1099 | role === "none" ? undefined : role, | |
| 1043 | 1100 | ); |
| 1044 | 1101 | if (!added.ok) return respondAccess(added.error, 422); |
| 1045 | 1102 | return json(added.value, added.value.added ? 201 : 200); |
test/teams.test.ts added +262
| @@ -0,0 +1,262 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createApp, type App } from "../src/app.ts"; | |
| 6 | import { | |
| 7 | addCrew, | |
| 8 | createAgentRow, | |
| 9 | crewRole, | |
| 10 | isCrew, | |
| 11 | listCrew, | |
| 12 | } from "../src/core/agents.ts"; | |
| 13 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 14 | import { canRead, createRepo } from "../src/core/repos.ts"; | |
| 15 | import { | |
| 16 | assignTeam, | |
| 17 | setMemberRole, | |
| 18 | teamMetrics, | |
| 19 | unassignTeam, | |
| 20 | } from "../src/core/teams.ts"; | |
| 21 | import { createUser, getUserById } from "../src/core/users.ts"; | |
| 22 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 23 | ||
| 24 | describe("teams drive the crew", () => { | |
| 25 | let dataDir: string; | |
| 26 | let app: App; | |
| 27 | beforeAll(async () => { | |
| 28 | dataDir = await mkdtemp(join(tmpdir(), "forge-teams-")); | |
| 29 | app = createApp({ dataDir, port: 0 }); | |
| 30 | }); | |
| 31 | afterAll(async () => { | |
| 32 | app.close(); | |
| 33 | await rm(dataDir, { recursive: true, force: true }); | |
| 34 | }); | |
| 35 | ||
| 36 | async function person(name: string, agent = false) { | |
| 37 | const made = await createUser(app.db, { | |
| 38 | username: name, | |
| 39 | email: `${name}@f.dev`, | |
| 40 | password: "teams-test-pass", | |
| 41 | }); | |
| 42 | if (!made.ok) throw new Error("user"); | |
| 43 | if (agent) { | |
| 44 | app.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(made.value.id); | |
| 45 | createAgentRow(app.db, { userId: made.value.id }); | |
| 46 | } | |
| 47 | return getUserById(app.db, made.value.id)!; | |
| 48 | } | |
| 49 | ||
| 50 | test("crew is the repo roster plus the agents of assigned teams, with roles", async () => { | |
| 51 | const owner = await person("tOwner"); | |
| 52 | const builder = await person("tBuilder", true); | |
| 53 | const judge = await person("tJudge", true); | |
| 54 | const solo = await person("tSolo", true); | |
| 55 | const human = await person("tHuman"); | |
| 56 | const org = createOrg(app.db, "tforge", owner.id); | |
| 57 | if (!org.ok) throw new Error("org"); | |
| 58 | const team = createTeam(app.db, org.value.id, "builders", "write"); | |
| 59 | if (!team.ok) throw new Error("team"); | |
| 60 | for (const u of [builder, judge, human]) addTeamMember(app.db, team.value, u.id); | |
| 61 | expect(setMemberRole(app.db, team.value.id, judge.id, "reviewer")).toBe(true); | |
| 62 | expect(setMemberRole(app.db, team.value.id, builder.id, "nonsense" as never)).toBe(false); | |
| 63 | ||
| 64 | const repo = await createRepo(app.db, app.reposRoot, { | |
| 65 | ownerId: owner.id, | |
| 66 | name: "work", | |
| 67 | visibility: "private", | |
| 68 | }); | |
| 69 | if (!repo.ok) throw new Error("repo"); | |
| 70 | addCrew(app.db, repo.value.id, solo.id); | |
| 71 | ||
| 72 | // Before assignment: only today's roster. | |
| 73 | expect(listCrew(app.db, repo.value.id).map((a) => a.user.username)).toEqual(["tSolo"]); | |
| 74 | expect(isCrew(app.db, repo.value.id, builder.id)).toBe(false); | |
| 75 | expect(canRead(app.db, repo.value, builder)).toBe(false); | |
| 76 | ||
| 77 | expect(assignTeam(app.db, repo.value.id, team.value.id)).toBe(true); | |
| 78 | expect(assignTeam(app.db, repo.value.id, team.value.id)).toBe(false); | |
| 79 | expect(listCrew(app.db, repo.value.id).map((a) => a.user.username)).toEqual([ | |
| 80 | "tBuilder", | |
| 81 | "tJudge", | |
| 82 | "tSolo", | |
| 83 | ]); | |
| 84 | expect(crewRole(app.db, repo.value.id, judge.id)).toBe("reviewer"); | |
| 85 | expect(crewRole(app.db, repo.value.id, builder.id)).toBe("builder"); | |
| 86 | expect(canRead(app.db, repo.value, builder)).toBe(true); | |
| 87 | // A person on the team gains no crew seat and no repo access from it. | |
| 88 | expect(isCrew(app.db, repo.value.id, human.id)).toBe(false); | |
| 89 | expect(canRead(app.db, repo.value, human)).toBe(false); | |
| 90 | ||
| 91 | // The repo's own roster wins over the team's role for the same agent. | |
| 92 | addCrew(app.db, repo.value.id, judge.id); | |
| 93 | expect(crewRole(app.db, repo.value.id, judge.id)).toBe("builder"); | |
| 94 | ||
| 95 | // Leaving the team takes the agent off; unassigning takes the team off. | |
| 96 | app.db.query("DELETE FROM team_member WHERE user_id = ?1").run(builder.id); | |
| 97 | expect(isCrew(app.db, repo.value.id, builder.id)).toBe(false); | |
| 98 | expect(unassignTeam(app.db, repo.value.id, team.value.id)).toBe(true); | |
| 99 | expect(isCrew(app.db, repo.value.id, judge.id)).toBe(true); // roster entry stays | |
| 100 | }, 60_000); | |
| 101 | ||
| 102 | test("metrics read the ledger of the team's agents on the team's repos", async () => { | |
| 103 | const owner = await person("mOwner"); | |
| 104 | const a = await person("mBuilder", true); | |
| 105 | const r = await person("mReviewer", true); | |
| 106 | const org = createOrg(app.db, "mforge", owner.id); | |
| 107 | if (!org.ok) throw new Error("org"); | |
| 108 | const team = createTeam(app.db, org.value.id, "pair", "write"); | |
| 109 | if (!team.ok) throw new Error("team"); | |
| 110 | addTeamMember(app.db, team.value, a.id); | |
| 111 | addTeamMember(app.db, team.value, r.id); | |
| 112 | const repo = await createRepo(app.db, app.reposRoot, { | |
| 113 | ownerId: owner.id, | |
| 114 | name: "lab", | |
| 115 | visibility: "private", | |
| 116 | }); | |
| 117 | if (!repo.ok) throw new Error("repo"); | |
| 118 | const now = Date.parse("2026-10-02T12:00:00Z"); | |
| 119 | const at = (min: number) => new Date(now - min * 60_000).toISOString(); | |
| 120 | ||
| 121 | // Nothing assigned: zeros, not an error. | |
| 122 | expect(teamMetrics(app.db, team.value.id, 24, now).runs.total).toBe(0); | |
| 123 | assignTeam(app.db, repo.value.id, team.value.id); | |
| 124 | ||
| 125 | const run = (actor: string, state: string, from: number, to: number, cost: number, summary = "") => | |
| 126 | app.db | |
| 127 | .query( | |
| 128 | `INSERT INTO run (id, repo_id, kind, state, actor_id, cost_usd, started_at, finished_at, summary) | |
| 129 | VALUES (?1, ?2, 'agent', ?3, ?4, ?5, ?6, ?7, ?8)`, | |
| 130 | ) | |
| 131 | .run(crypto.randomUUID(), repo.value.id, state, actor, cost, at(from), at(to), summary); | |
| 132 | run(a.id, "ok", 120, 60, 1); | |
| 133 | run(r.id, "ok", 90, 30, 0.5); | |
| 134 | run(r.id, "cancelled", 300, 250, 0.25, "cancelled by trevato"); | |
| 135 | ||
| 136 | const pull = (n: number, branch: string, openedMin: number, mergedMin: number | null) => { | |
| 137 | const id = crypto.randomUUID(); | |
| 138 | app.db | |
| 139 | .query( | |
| 140 | `INSERT INTO issue (id, repo_id, number, kind, title, author_id, created_at) | |
| 141 | VALUES (?1, ?2, ?3, 'pull', 't', ?4, ?5)`, | |
| 142 | ) | |
| 143 | .run(id, repo.value.id, n, a.id, at(openedMin)); | |
| 144 | app.db | |
| 145 | .query( | |
| 146 | `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) | |
| 147 | VALUES (?1, 'main', ?2, 'x', 'y', ?3)`, | |
| 148 | ) | |
| 149 | .run(id, branch, mergedMin === null ? null : at(mergedMin)); | |
| 150 | return id; | |
| 151 | }; | |
| 152 | const p1 = pull(1, "mBuilder/7-first", 200, 20); | |
| 153 | pull(2, "mBuilder/7-again", 150, null); | |
| 154 | app.db | |
| 155 | .query( | |
| 156 | `INSERT INTO review (id, issue_id, author_id, state, created_at) VALUES (?1, ?2, ?3, 'changes_requested', ?4)`, | |
| 157 | ) | |
| 158 | .run(crypto.randomUUID(), p1, r.id, at(170)); | |
| 159 | ||
| 160 | const m = teamMetrics(app.db, team.value.id, 24, now); | |
| 161 | expect(m.members).toBe(2); | |
| 162 | expect(m.slots).toBe(1); | |
| 163 | expect(m.runs).toEqual({ total: 3, ok: 2, failed: 0, cancelled: 1 }); | |
| 164 | expect(m.busySlotHours).toBe(2.8); | |
| 165 | expect(m.peakParallelism).toBe(2); | |
| 166 | expect(m.heldRuns).toBe(1); | |
| 167 | expect(m.heldSlotHours).toBe(0.8); | |
| 168 | expect(m.costUsd).toBe(1.75); | |
| 169 | expect(m.pullsOpened).toBe(2); | |
| 170 | expect(m.pullsMerged).toBe(1); | |
| 171 | expect(m.leadTimeHoursMedian).toBe(3); | |
| 172 | expect(m.handoffPullToReviewMinMedian).toBe(30); | |
| 173 | expect(m.pullsWithoutReview).toBe(1); | |
| 174 | expect(m.reworkRate).toBe(0.5); | |
| 175 | expect(m.duplicateIssues).toBe(1); | |
| 176 | expect(m.costPerShippedUsd).toBe(1.75); | |
| 177 | // A narrower window leaves out what finished before it. | |
| 178 | expect(teamMetrics(app.db, team.value.id, 1, now).runs.total).toBe(2); | |
| 179 | }, 60_000); | |
| 180 | }); | |
| 181 | ||
| 182 | describe("teams over the API", () => { | |
| 183 | let dataDir: string; | |
| 184 | let app: App; | |
| 185 | let servers: Servers; | |
| 186 | let base: string; | |
| 187 | const tokens: Record<string, string> = {}; | |
| 188 | ||
| 189 | async function mkUser(username: string): Promise<string> { | |
| 190 | const json = { "content-type": "application/json" }; | |
| 191 | await fetch(`${base}/api/v1/users`, { | |
| 192 | method: "POST", | |
| 193 | headers: json, | |
| 194 | body: JSON.stringify({ username, email: `${username}@f.dev`, password: "teams-http-pass" }), | |
| 195 | }); | |
| 196 | const t = await fetch(`${base}/api/v1/tokens`, { | |
| 197 | method: "POST", | |
| 198 | headers: json, | |
| 199 | body: JSON.stringify({ username, password: "teams-http-pass", name: "c", scope: "admin" }), | |
| 200 | }).then((r) => r.json() as Promise<{ token: string }>); | |
| 201 | return t.token; | |
| 202 | } | |
| 203 | const call = (who: string, method: string, path: string, body?: unknown) => | |
| 204 | fetch(`${base}${path}`, { | |
| 205 | method, | |
| 206 | headers: { authorization: `Bearer ${tokens[who]}`, "content-type": "application/json" }, | |
| 207 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 208 | }); | |
| 209 | ||
| 210 | beforeAll(async () => { | |
| 211 | dataDir = await mkdtemp(join(tmpdir(), "forge-teams-http-")); | |
| 212 | app = createApp({ dataDir, port: 0 }); | |
| 213 | servers = await serve(app); | |
| 214 | base = servers.url; | |
| 215 | for (const n of ["hboss", "hother"]) tokens[n] = await mkUser(n); | |
| 216 | }, 60_000); | |
| 217 | afterAll(async () => { | |
| 218 | servers.stop(); | |
| 219 | app.close(); | |
| 220 | await rm(dataDir, { recursive: true, force: true }); | |
| 221 | }); | |
| 222 | ||
| 223 | test("roles, assignment, and metrics are admin-gated and validated", async () => { | |
| 224 | expect((await call("hboss", "POST", "/api/v1/orgs", { name: "hforge" })).status).toBe(201); | |
| 225 | expect( | |
| 226 | (await call("hboss", "POST", "/api/v1/orgs/hforge/teams", { name: "builders", permission: "write" })).status, | |
| 227 | ).toBe(201); | |
| 228 | expect((await call("hboss", "POST", "/api/v1/repos", { name: "r", owner: "hboss", visibility: "private" })).status).toBe(201); | |
| 229 | const agent = await createUser(app.db, { username: "hbot", email: "[email protected]", password: "teams-http-pass" }); | |
| 230 | if (!agent.ok) throw new Error("agent"); | |
| 231 | app.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(agent.value.id); | |
| 232 | createAgentRow(app.db, { userId: agent.value.id }); | |
| 233 | ||
| 234 | // A role must be one of the three. | |
| 235 | const bad = await call("hboss", "POST", "/api/v1/orgs/hforge/teams/builders/members", { user: "hbot", role: "boss" }); | |
| 236 | expect(bad.status).toBe(422); | |
| 237 | const ok = await call("hboss", "POST", "/api/v1/orgs/hforge/teams/builders/members", { user: "hbot", role: "reviewer" }); | |
| 238 | expect(ok.status).toBe(201); | |
| 239 | ||
| 240 | // Someone who is not an admin of both sides cannot assign. | |
| 241 | expect((await call("hother", "PUT", "/api/v1/repos/hboss/r/teams/hforge/builders")).status).toBe(404); | |
| 242 | expect((await call("hboss", "PUT", "/api/v1/repos/hboss/r/teams/hforge/builders")).status).toBe(201); | |
| 243 | expect((await call("hboss", "PUT", "/api/v1/repos/hboss/r/teams/hforge/builders")).status).toBe(200); | |
| 244 | ||
| 245 | const crew = (await (await call("hboss", "GET", "/api/v1/repos/hboss/r/crew")).json()) as { items: { username?: string }[] }; | |
| 246 | expect(JSON.stringify(crew)).toContain("hbot"); | |
| 247 | ||
| 248 | const team = (await (await call("hboss", "GET", "/api/v1/orgs/hforge/teams/builders?hours=48")).json()) as { | |
| 249 | members: { username: string; kind: string; role: string }[]; | |
| 250 | repos: { name: string }[]; | |
| 251 | metrics: { windowHours: number; repos: number }; | |
| 252 | }; | |
| 253 | expect(team.members).toEqual([{ username: "hbot", kind: "agent", role: "reviewer" }]); | |
| 254 | expect(team.repos.map((r) => r.name)).toEqual(["r"]); | |
| 255 | expect(team.metrics.windowHours).toBe(48); | |
| 256 | expect(team.metrics.repos).toBe(1); | |
| 257 | // Not a member, not an admin: the team does not exist for them. | |
| 258 | expect((await call("hother", "GET", "/api/v1/orgs/hforge/teams/builders")).status).toBe(404); | |
| 259 | ||
| 260 | expect((await call("hboss", "DELETE", "/api/v1/repos/hboss/r/teams/hforge/builders")).status).toBe(204); | |
| 261 | }, 60_000); | |
| 262 | }); |
new above
offline