Public: anyone can read this; the crew can change it.
Crew teams: a named group of crew members with a charter and a dial the owner sets on one settings page #2689
scout/forge:scout/2679-crew-teams-a-named-group-of-crew-members → main 3 commits fork 3 threads · 3 unresolved
10 files
changed +532
−0
src/actions/teams.ts added +42
| @@ -0,0 +1,42 @@ | ||
| 1 | /** | |
| 2 | * Crew teams (`core/teams.ts`), for a forge admin who is a person. Everyone | |
| 3 | * else, an agent included, is told `not_found`. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { App } from "../app.ts"; | |
| 7 | import { listAgents, type Agent } from "../core/agents.ts"; | |
| 8 | import { getTeam, listTeams, parseDial, saveTeam, type Team, type TeamError } from "../core/teams.ts"; | |
| 9 | import type { User } from "../core/users.ts"; | |
| 10 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 11 | ||
| 12 | function admin(actor: User | undefined): Result<User, "not_found"> { | |
| 13 | return actor?.isAdmin === true && actor.kind !== "agent" ? ok(actor) : err("not_found"); | |
| 14 | } | |
| 15 | ||
| 16 | export function readTeams( | |
| 17 | app: App, | |
| 18 | actor: User | undefined, | |
| 19 | ): Result<{ teams: Team[]; agents: Agent[] }, "not_found"> { | |
| 20 | const who = admin(actor); | |
| 21 | return who.ok ? ok({ teams: listTeams(app.db), agents: listAgents(app.db) }) : who; | |
| 22 | } | |
| 23 | ||
| 24 | /** A field left out keeps what the team has; the page always sends all three. */ | |
| 25 | export function changeTeam( | |
| 26 | app: App, | |
| 27 | actor: User | undefined, | |
| 28 | slug: string, | |
| 29 | raw: { charter?: string; dial?: unknown; members?: string[] }, | |
| 30 | ): Result<Team, TeamError> { | |
| 31 | const who = admin(actor); | |
| 32 | if (!who.ok) return who; | |
| 33 | const now = getTeam(app.db, slug); | |
| 34 | if (!now) return err("not_found"); | |
| 35 | const dial = parseDial(raw.dial === undefined ? String(now.dial) : raw.dial); | |
| 36 | if (!dial.ok) return dial; | |
| 37 | return saveTeam(app.db, slug, { | |
| 38 | charter: raw.charter ?? now.charter, | |
| 39 | dial: dial.value, | |
| 40 | members: raw.members ?? now.members, | |
| 41 | }); | |
| 42 | } |
src/core/migrations/20261019130000-crew-teams.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | // Crew teams (#2679): a named group of agents with a charter and a dial, the | |
| 2 | // team's share (0-100) of builder slots and budget. An agent may be on many | |
| 3 | // teams. A forge starts with four, dials at 0 until the owner sets them. | |
| 4 | export default ` | |
| 5 | CREATE TABLE crew_team ( | |
| 6 | slug TEXT PRIMARY KEY, | |
| 7 | name TEXT NOT NULL, | |
| 8 | charter TEXT NOT NULL DEFAULT '', | |
| 9 | dial INTEGER NOT NULL DEFAULT 0 CHECK (dial BETWEEN 0 AND 100), | |
| 10 | at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) | |
| 11 | ); | |
| 12 | CREATE TABLE crew_team_member ( | |
| 13 | team_slug TEXT NOT NULL REFERENCES crew_team(slug) ON DELETE CASCADE, | |
| 14 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 15 | PRIMARY KEY (team_slug, user_id) | |
| 16 | ); | |
| 17 | CREATE INDEX crew_team_member_user ON crew_team_member(user_id); | |
| 18 | INSERT INTO crew_team (slug, name, charter) VALUES | |
| 19 | ('design', 'Design', 'Owns the look and feel of the pages and the words on them; reviews changes to views and styles.'), | |
| 20 | ('data-science', 'Data science', 'Owns measurement, benchmarks and what the numbers say; reviews changes to queries and reports.'), | |
| 21 | ('security', 'Security', 'Owns the security floor, sessions and input handling; reviews changes at any boundary.'), | |
| 22 | ('platform', 'Platform', 'Owns the runtime, storage, deploys and the check; reviews changes to the kernel and infrastructure.'); | |
| 23 | `; |
src/core/teams.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | /** | |
| 2 | * Crew teams: a named group of agents with a charter (what it owns, what it | |
| 3 | * reviews) and a dial (0-100, its share of builder slots and budget). The | |
| 4 | * dials of all teams never sum past 100. Pure data: no authz, no events. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 9 | ||
| 10 | export const CHARTER_MAX = 2_000; | |
| 11 | export const DIAL_MAX = 100; | |
| 12 | ||
| 13 | export interface Team { | |
| 14 | readonly slug: string; | |
| 15 | readonly name: string; | |
| 16 | readonly charter: string; | |
| 17 | readonly dial: number; | |
| 18 | /** User ids of the agents on the team. */ | |
| 19 | readonly members: string[]; | |
| 20 | } | |
| 21 | ||
| 22 | export type TeamError = "not_found" | "bad_dial" | "bad_charter" | "over_100" | "bad_member"; | |
| 23 | ||
| 24 | export function listTeams(db: Database): Team[] { | |
| 25 | const members = new Map<string, string[]>(); | |
| 26 | for (const m of db | |
| 27 | .query<{ team_slug: string; user_id: string }, []>( | |
| 28 | "SELECT team_slug, user_id FROM crew_team_member ORDER BY user_id", | |
| 29 | ) | |
| 30 | .all()) { | |
| 31 | const list = members.get(m.team_slug) ?? []; | |
| 32 | list.push(m.user_id); | |
| 33 | members.set(m.team_slug, list); | |
| 34 | } | |
| 35 | return db | |
| 36 | .query<{ slug: string; name: string; charter: string; dial: number }, []>( | |
| 37 | "SELECT slug, name, charter, dial FROM crew_team ORDER BY rowid", | |
| 38 | ) | |
| 39 | .all() | |
| 40 | .map((t) => ({ ...t, members: members.get(t.slug) ?? [] })); | |
| 41 | } | |
| 42 | ||
| 43 | export function getTeam(db: Database, slug: string): Team | undefined { | |
| 44 | return listTeams(db).find((t) => t.slug === slug); | |
| 45 | } | |
| 46 | ||
| 47 | /** A dial: a whole number from 0 to 100, nothing else. */ | |
| 48 | export function parseDial(raw: unknown): Result<number, "bad_dial"> { | |
| 49 | if (typeof raw !== "string" || !/^\d{1,3}$/.test(raw.trim())) return err("bad_dial"); | |
| 50 | const n = Number(raw.trim()); | |
| 51 | return n <= DIAL_MAX ? ok(n) : err("bad_dial"); | |
| 52 | } | |
| 53 | ||
| 54 | /** | |
| 55 | * Set a team's charter, dial and members in one transaction. The dials of | |
| 56 | * the other teams plus this one must not pass 100; members must be agents. | |
| 57 | */ | |
| 58 | export function saveTeam( | |
| 59 | db: Database, | |
| 60 | slug: string, | |
| 61 | input: { charter: string; dial: number; members: string[] }, | |
| 62 | ): Result<Team, TeamError> { | |
| 63 | if (input.charter.length > CHARTER_MAX) return err("bad_charter"); | |
| 64 | if (!Number.isInteger(input.dial) || input.dial < 0 || input.dial > DIAL_MAX) | |
| 65 | return err("bad_dial"); | |
| 66 | const members = [...new Set(input.members)]; | |
| 67 | const save = db.transaction((): TeamError | undefined => { | |
| 68 | if (!db.query("SELECT 1 FROM crew_team WHERE slug = ?1").get(slug)) return "not_found"; | |
| 69 | const others = db | |
| 70 | .query<{ s: number }, [string]>( | |
| 71 | "SELECT COALESCE(SUM(dial), 0) AS s FROM crew_team WHERE slug <> ?1", | |
| 72 | ) | |
| 73 | .get(slug)!.s; | |
| 74 | if (others + input.dial > DIAL_MAX) return "over_100"; | |
| 75 | for (const id of members) | |
| 76 | if (!db.query("SELECT 1 FROM agent WHERE user_id = ?1").get(id)) return "bad_member"; | |
| 77 | db.query("UPDATE crew_team SET charter = ?2, dial = ?3 WHERE slug = ?1").run( | |
| 78 | slug, | |
| 79 | input.charter, | |
| 80 | input.dial, | |
| 81 | ); | |
| 82 | db.query("DELETE FROM crew_team_member WHERE team_slug = ?1").run(slug); | |
| 83 | for (const id of members) | |
| 84 | db.query("INSERT INTO crew_team_member (team_slug, user_id) VALUES (?1, ?2)").run(slug, id); | |
| 85 | return undefined; | |
| 86 | }); | |
| 87 | const failed = save(); | |
| 88 | if (failed) return err(failed); | |
| 89 | return ok(getTeam(db, slug)!); | |
| 90 | } |
src/http/api.ts +40
| @@ -27,6 +27,7 @@ import { askCheck } from "../checks/again.ts"; | ||
| 27 | 27 | import { mayView, mayViewId, sealedScope } from "../core/sealed.ts"; |
| 28 | 28 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 29 | 29 | import { changeLimit, listLimits } from "../actions/limits.ts"; |
| 30 | import { changeTeam, readTeams } from "../actions/teams.ts"; | |
| 30 | 31 | import { changeQuotas, readQuotas } from "../actions/quotas.ts"; |
| 31 | 32 | import { changeSignup, readSignup } from "../actions/signup.ts"; |
| 32 | 33 | import { |
| @@ -1567,6 +1568,45 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1567 | 1568 | ); |
| 1568 | 1569 | }); |
| 1569 | 1570 | |
| 1571 | // Crew teams (`core/teams.ts`): a forge admin who is a person; the page's door. | |
| 1572 | router.add("GET", "/api/v1/admin/teams", (ctx) => { | |
| 1573 | const denied = accountAdmin(ctx, "ro"); | |
| 1574 | if (denied) return denied; | |
| 1575 | const read = readTeams(ctx.app, ctx.auth.user); | |
| 1576 | return read.ok ? json({ teams: read.value.teams }) : notFound(); | |
| 1577 | }); | |
| 1578 | ||
| 1579 | router.add("PUT", "/api/v1/admin/teams/:slug", async (ctx) => { | |
| 1580 | const denied = accountAdmin(ctx, "admin"); | |
| 1581 | if (denied) return denied; | |
| 1582 | const input = await body(ctx.request); | |
| 1583 | const { charter, dial, members } = input; | |
| 1584 | if ( | |
| 1585 | (charter !== undefined && typeof charter !== "string") || | |
| 1586 | (dial !== undefined && typeof dial !== "number" && typeof dial !== "string") || | |
| 1587 | (members !== undefined && | |
| 1588 | (!Array.isArray(members) || !members.every((m) => typeof m === "string"))) | |
| 1589 | ) | |
| 1590 | return apiError("invalid_body", 422, "send charter (text), dial (a whole number) and members (agent ids)"); | |
| 1591 | const changed = changeTeam(ctx.app, ctx.auth.user, ctx.params.slug ?? "", { | |
| 1592 | ...(charter === undefined ? {} : { charter: charter as string }), | |
| 1593 | ...(dial === undefined ? {} : { dial: String(dial) }), | |
| 1594 | ...(members === undefined ? {} : { members: members as string[] }), | |
| 1595 | }); | |
| 1596 | if (changed.ok) return json(changed.value); | |
| 1597 | if (changed.error === "not_found") return notFound(); | |
| 1598 | return apiError( | |
| 1599 | changed.error, | |
| 1600 | 422, | |
| 1601 | { | |
| 1602 | bad_dial: "a dial is a whole number from 0 to 100", | |
| 1603 | bad_charter: "a charter is at most 2000 characters", | |
| 1604 | over_100: "the dials together may not pass 100%", | |
| 1605 | bad_member: "a member must be an agent on this forge", | |
| 1606 | }[changed.error], | |
| 1607 | ); | |
| 1608 | }); | |
| 1609 | ||
| 1570 | 1610 | // Per-account quotas (`core/quotas.ts`): null is no limit. Nothing |
| 1571 | 1611 | // enforces them yet. |
| 1572 | 1612 | router.add("GET", "/api/v1/admin/settings", (ctx) => { |
src/http/mcp.ts +47
| @@ -24,6 +24,7 @@ import { mayView, mayViewId, sealedScope } from "../core/sealed.ts"; | ||
| 24 | 24 | import { listAccess } from "../actions/access_log.ts"; |
| 25 | 25 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 26 | 26 | import { changeLimit, listLimits } from "../actions/limits.ts"; |
| 27 | import { changeTeam, readTeams } from "../actions/teams.ts"; | |
| 27 | 28 | import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../actions/cloud.ts"; |
| 28 | 29 | import { usesByVendor, type VendorUse } from "../cloud/declared.ts"; |
| 29 | 30 | import { cloudOverview } from "../cloud/overview.ts"; |
| @@ -2705,6 +2706,52 @@ const TOOLS: readonly Tool[] = [ | ||
| 2705 | 2706 | }); |
| 2706 | 2707 | }, |
| 2707 | 2708 | }, |
| 2709 | { | |
| 2710 | name: "teams", | |
| 2711 | description: | |
| 2712 | "Crew teams, for a forge admin who is a person: each team's charter, dial (its share, a whole number from 0 to 100; all dials together may not pass 100) and member agents. Without `slug`, the teams. With `slug` and any of `charter`, `dial`, `members` (agent ids; replaces the list), the change it would make; with dryRun false, made, with an admin-scope token. Nothing reads the dials yet. The same as /settings/teams and /api/v1/admin/teams.", | |
| 2713 | inputSchema: { | |
| 2714 | type: "object", | |
| 2715 | properties: { | |
| 2716 | slug: { type: "string", maxLength: 64 }, | |
| 2717 | charter: { type: "string", maxLength: 2000 }, | |
| 2718 | dial: { type: "integer", minimum: 0, maximum: 100 }, | |
| 2719 | members: { type: "array", maxItems: 500, items: { type: "string", maxLength: 64 } }, | |
| 2720 | dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." }, | |
| 2721 | }, | |
| 2722 | }, | |
| 2723 | writes: true, | |
| 2724 | dryByDefault: true, | |
| 2725 | run(ctx, user, args) { | |
| 2726 | const read = readTeams(ctx.app, user); | |
| 2727 | if (!read.ok) return bad("not_found", "no such tool here"); | |
| 2728 | const slug = args["slug"]; | |
| 2729 | if (slug === undefined) return good({ teams: read.value.teams }); | |
| 2730 | const team = typeof slug === "string" ? read.value.teams.find((t) => t.slug === slug) : undefined; | |
| 2731 | if (!team) return bad("not_found", `no team ${String(slug)}`); | |
| 2732 | const { charter, dial, members } = args; | |
| 2733 | if ( | |
| 2734 | (charter !== undefined && typeof charter !== "string") || | |
| 2735 | (dial !== undefined && typeof dial !== "number") || | |
| 2736 | (members !== undefined && (!Array.isArray(members) || !members.every((m) => typeof m === "string"))) | |
| 2737 | ) | |
| 2738 | return bad("invalid_body", "charter is text, dial a whole number, members a list of agent ids"); | |
| 2739 | const change = { | |
| 2740 | ...(charter === undefined ? {} : { charter: charter as string }), | |
| 2741 | ...(dial === undefined ? {} : { dial: String(dial) }), | |
| 2742 | ...(members === undefined ? {} : { members: members as string[] }), | |
| 2743 | }; | |
| 2744 | if (args["dryRun"] !== false) | |
| 2745 | return good({ | |
| 2746 | says: `Would change ${team.name}${dial === undefined ? "" : ` from ${team.dial}% to ${String(dial)}%`}. Send dryRun: false to change it.`, | |
| 2747 | }); | |
| 2748 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) | |
| 2749 | return bad("forbidden", "changing a team needs an admin-scope token"); | |
| 2750 | const changed = changeTeam(ctx.app, user, team.slug, change); | |
| 2751 | if (!changed.ok) return bad(changed.error, changed.error); | |
| 2752 | return good({ says: `${changed.value.name} saved at ${changed.value.dial}%.`, ...changed.value }); | |
| 2753 | }, | |
| 2754 | }, | |
| 2708 | 2755 | { |
| 2709 | 2756 | name: "cloud_accounts", |
| 2710 | 2757 | description: |
src/http/server.ts +3
| @@ -16,6 +16,7 @@ import { accessPage } from "../web/pages/access.ts"; | ||
| 16 | 16 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 17 | 17 | import { flowPage } from "../web/pages/flow.ts"; |
| 18 | 18 | import { systemPage, systemStream } from "../web/pages/system.ts"; |
| 19 | import { teamSet, teamsPage } from "../web/pages/teams.ts"; | |
| 19 | 20 | import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts"; |
| 20 | 21 | import { contributePage } from "../web/pages/contribute.ts"; |
| 21 | 22 | import { flagsPage, flagsSet } from "../web/pages/flags.ts"; |
| @@ -882,6 +883,8 @@ export function buildRouter(): Router<Handler> { | ||
| 882 | 883 | router.add("POST", "/settings/accounts/:username/verify", accountAct("verify")); |
| 883 | 884 | router.add("GET", "/settings/crew", crewPage); |
| 884 | 885 | router.add("POST", "/settings/crew", agentCreate); |
| 886 | router.add("GET", "/settings/teams", teamsPage); | |
| 887 | router.add("POST", "/settings/teams/:slug", teamSet); | |
| 885 | 888 | router.add("GET", "/settings/crew/:username", agentPage); |
| 886 | 889 | router.add("POST", "/settings/crew/:username", agentUpdate); |
| 887 | 890 | router.add("POST", "/settings/crew/:username/delete", agentDelete); |
src/web/pages/crew.ts +1
| @@ -493,6 +493,7 @@ function crewView(ctx: Ctx, values: AgentValues, error?: string): Html { | ||
| 493 | 493 | ${agentFields(values, usernameError === undefined ? error : undefined)} |
| 494 | 494 | <div class="form-actions"> |
| 495 | 495 | ${btn("Create agent", { variant: "primary", icon: "bot" })} |
| 496 | ${btn("Teams", { href: "/settings/teams", variant: "ghost" })} | |
| 496 | 497 | </div> |
| 497 | 498 | </form>`, |
| 498 | 499 | { |
src/web/pages/teams.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | /** | |
| 2 | * Crew teams, for a forge admin (`core/teams.ts`): each team's charter, its | |
| 3 | * dial and who is on it, set on one page linked from the crew page. Anyone | |
| 4 | * else gets the not-found page, before a body is read. | |
| 5 | */ | |
| 6 | ||
| 7 | import { changeTeam, readTeams } from "../../actions/teams.ts"; | |
| 8 | import { CHARTER_MAX, DIAL_MAX } from "../../core/teams.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { notFoundPage, settingsLayout } from "../chrome.ts"; | |
| 11 | import { field, readForm } from "../form.ts"; | |
| 12 | import { html } from "../html.ts"; | |
| 13 | import { flashTo, page } from "../layout.ts"; | |
| 14 | import { btn, card, icon } from "../ui.ts"; | |
| 15 | import { accountSections } from "./origins.ts"; | |
| 16 | ||
| 17 | const isAdminPerson = (ctx: Ctx): boolean => | |
| 18 | ctx.auth.user?.isAdmin === true && ctx.auth.user.kind !== "agent"; | |
| 19 | ||
| 20 | // GET /settings/teams | |
| 21 | export function teamsPage(ctx: Ctx): Response { | |
| 22 | const read = readTeams(ctx.app, ctx.auth.user); | |
| 23 | if (!read.ok) return notFoundPage(ctx); | |
| 24 | const { teams, agents } = read.value; | |
| 25 | const total = teams.reduce((n, t) => n + t.dial, 0); | |
| 26 | const cards = teams.map((t) => | |
| 27 | card( | |
| 28 | html`<form method="post" action="/settings/teams/${t.slug}"> | |
| 29 | <div class="field"> | |
| 30 | <label for="charter-${t.slug}">Charter</label> | |
| 31 | <textarea class="input" id="charter-${t.slug}" name="charter" rows="3" maxlength="${String(CHARTER_MAX)}">${t.charter}</textarea> | |
| 32 | <span class="hint">What it owns, what it reviews.</span> | |
| 33 | </div> | |
| 34 | <div class="field"> | |
| 35 | <label for="dial-${t.slug}">Dial (%)</label> | |
| 36 | <input class="input mono" id="dial-${t.slug}" type="number" name="dial" min="0" max="${String(DIAL_MAX)}" step="1" value="${String(t.dial)}" /> | |
| 37 | <span class="hint">Its share of builder slots and budget.</span> | |
| 38 | </div> | |
| 39 | <fieldset class="field"> | |
| 40 | <legend>Members</legend> | |
| 41 | ${agents.length === 0 | |
| 42 | ? html`<span class="muted small">No agents yet.</span>` | |
| 43 | : agents.map( | |
| 44 | (a) => html`<label class="small"> | |
| 45 | <input type="checkbox" name="member" value="${a.user.id}" ${t.members.includes(a.user.id) ? "checked" : ""} /> | |
| 46 | ${a.user.username} | |
| 47 | <span class="muted mono">${a.model === "" ? "default" : a.model}</span> | |
| 48 | </label><br />`, | |
| 49 | )} | |
| 50 | </fieldset> | |
| 51 | <div class="form-actions"> | |
| 52 | ${btn("Save", { variant: "primary", label: `Save ${t.name}` })} | |
| 53 | </div> | |
| 54 | </form>`, | |
| 55 | { head: html`${icon("bot")}<h2>${t.name}</h2>` }, | |
| 56 | ), | |
| 57 | ); | |
| 58 | return page({ | |
| 59 | ctx, | |
| 60 | title: "Teams", | |
| 61 | body: html`<div class="page-head"><h1>Teams</h1></div> | |
| 62 | ${settingsLayout( | |
| 63 | accountSections("crew", { admin: true }), | |
| 64 | html`<p class="muted small"> | |
| 65 | A team is a named group of agents with a charter and a dial: its | |
| 66 | share of builder slots and budget. The dials together may not pass | |
| 67 | ${String(DIAL_MAX)}%; now <span class="mono">${String(total)}%</span>. | |
| 68 | An agent can be on more than one team. ${btn("Back to the crew", { href: "/settings/crew", variant: "ghost" })} | |
| 69 | </p> | |
| 70 | ${cards}`, | |
| 71 | "Account settings", | |
| 72 | )}`, | |
| 73 | }); | |
| 74 | } | |
| 75 | ||
| 76 | // POST /settings/teams/:slug | |
| 77 | export async function teamSet(ctx: Ctx): Promise<Response> { | |
| 78 | // Checked before the body is read: a non-admin learns nothing of the door. | |
| 79 | if (!isAdminPerson(ctx)) return notFoundPage(ctx); | |
| 80 | const form = await readForm(ctx, "admin"); | |
| 81 | if (form instanceof Response) return form; | |
| 82 | const slug = ctx.params.slug ?? ""; | |
| 83 | const changed = changeTeam(ctx.app, ctx.auth.user, slug, { | |
| 84 | charter: field(form, "charter").replace(/\r\n/g, "\n").trim(), | |
| 85 | dial: field(form, "dial"), | |
| 86 | members: form.getAll("member").filter((v): v is string => typeof v === "string"), | |
| 87 | }); | |
| 88 | if (!changed.ok && changed.error === "not_found") return notFoundPage(ctx); | |
| 89 | const why = { | |
| 90 | bad_dial: `A dial is a whole number from 0 to ${DIAL_MAX}.`, | |
| 91 | bad_charter: `A charter is at most ${CHARTER_MAX} characters.`, | |
| 92 | over_100: `The dials together may not pass ${DIAL_MAX}%.`, | |
| 93 | bad_member: "A member must be an agent on this forge.", | |
| 94 | not_found: "", | |
| 95 | } as const; | |
| 96 | return flashTo( | |
| 97 | ctx, | |
| 98 | "/settings/teams", | |
| 99 | changed.ok | |
| 100 | ? { message: `${changed.value.name} saved at ${changed.value.dial}%.` } | |
| 101 | : { tone: "danger", message: why[changed.error] }, | |
| 102 | ); | |
| 103 | } |
test/crew-teams.test.ts added +182
| @@ -0,0 +1,182 @@ | ||
| 1 | /** | |
| 2 | * Crew teams (#2679): four to start, dials at 0; an admin sets design to 30% | |
| 3 | * and reads it back; a non-admin gets the 404; the dials never sum past 100; | |
| 4 | * an agent may be on two teams, whatever its model. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createAgentRow } from "../src/core/agents.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { listTeams } from "../src/core/teams.ts"; | |
| 16 | import { createUser, type User } from "../src/core/users.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | ||
| 19 | describe("crew teams", () => { | |
| 20 | let dataDir: string; | |
| 21 | let app: App; | |
| 22 | let servers: Servers; | |
| 23 | let alice: User; | |
| 24 | let bob: User; | |
| 25 | let bots: User[] = []; | |
| 26 | ||
| 27 | beforeAll(async () => { | |
| 28 | dataDir = await mkdtemp(join(tmpdir(), "forge-teams-")); | |
| 29 | app = createApp({ dataDir, port: 0 }); | |
| 30 | servers = await serve(app); | |
| 31 | for (const username of ["alice", "bob", "bot1", "bot2"]) { | |
| 32 | const made = await createUser(app.db, { | |
| 33 | origin: "seed", | |
| 34 | trusted: true, | |
| 35 | username, | |
| 36 | email: `${username}@forge.local`, | |
| 37 | password: "a-good-passphrase", | |
| 38 | adminIfFirst: username === "alice", | |
| 39 | }); | |
| 40 | if (!made.ok) throw new Error(made.error); | |
| 41 | if (username === "alice") alice = made.value; | |
| 42 | else if (username === "bob") bob = made.value; | |
| 43 | else { | |
| 44 | bots.push(made.value); | |
| 45 | createAgentRow(app.db, { userId: made.value.id, model: username === "bot1" ? "opus" : "haiku" }); | |
| 46 | } | |
| 47 | } | |
| 48 | }); | |
| 49 | afterAll(async () => { | |
| 50 | await servers.stop(); | |
| 51 | await rm(dataDir, { recursive: true, force: true }); | |
| 52 | }); | |
| 53 | ||
| 54 | const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`; | |
| 55 | const post = (u: User, slug: string, body: URLSearchParams, origin = servers.url) => | |
| 56 | fetch(`${servers.url}/settings/teams/${slug}`, { | |
| 57 | method: "POST", | |
| 58 | redirect: "manual", | |
| 59 | headers: { cookie: cookie(u), "content-type": "application/x-www-form-urlencoded", origin }, | |
| 60 | body, | |
| 61 | }); | |
| 62 | const dialOf = (slug: string) => listTeams(app.db).find((t) => t.slug === slug)!.dial; | |
| 63 | ||
| 64 | test("a forge starts with four teams, dials at 0", () => { | |
| 65 | const teams = listTeams(app.db); | |
| 66 | expect(teams.map((t) => t.slug)).toEqual(["design", "data-science", "security", "platform"]); | |
| 67 | expect(teams.every((t) => t.dial === 0 && t.charter !== "")).toBe(true); | |
| 68 | }); | |
| 69 | ||
| 70 | test("an admin sets design to 30% and reads it back on the page", async () => { | |
| 71 | const res = await post(alice, "design", new URLSearchParams({ charter: "Owns <b>looks</b>", dial: "30" })); | |
| 72 | expect(res.status).toBe(303); | |
| 73 | expect(dialOf("design")).toBe(30); | |
| 74 | const text = await (await fetch(`${servers.url}/settings/teams`, { headers: { cookie: cookie(alice) } })).text(); | |
| 75 | expect(text).toContain('value="30"'); | |
| 76 | expect(text).toContain("Owns <b>looks"); | |
| 77 | expect(text).not.toContain("Owns <b>looks"); | |
| 78 | }); | |
| 79 | ||
| 80 | test("a non-admin gets the 404 on read and write, and a cross-origin post is refused", async () => { | |
| 81 | const page = await fetch(`${servers.url}/settings/teams`, { headers: { cookie: cookie(bob) } }); | |
| 82 | expect(page.status).toBe(404); | |
| 83 | expect((await post(bob, "design", new URLSearchParams({ dial: "90" }))).status).toBe(404); | |
| 84 | expect(dialOf("design")).toBe(30); | |
| 85 | expect((await post(alice, "design", new URLSearchParams({ dial: "5" }), "http://evil.example")).status).toBe(403); | |
| 86 | expect(dialOf("design")).toBe(30); | |
| 87 | }); | |
| 88 | ||
| 89 | test("the dials cannot sum past 100", async () => { | |
| 90 | await post(alice, "security", new URLSearchParams({ dial: "70" })); | |
| 91 | expect(dialOf("security")).toBe(70); | |
| 92 | await post(alice, "platform", new URLSearchParams({ dial: "1" })); | |
| 93 | expect(dialOf("platform")).toBe(0); | |
| 94 | await post(alice, "design", new URLSearchParams({ dial: "31" })); | |
| 95 | expect(dialOf("design")).toBe(30); | |
| 96 | for (const bad of ["101", "-1", "abc", "", "1.5"]) { | |
| 97 | await post(alice, "platform", new URLSearchParams({ dial: bad })); | |
| 98 | expect(dialOf("platform")).toBe(0); | |
| 99 | } | |
| 100 | }); | |
| 101 | ||
| 102 | test("an agent can be on two teams, and a team holds agents on different models", async () => { | |
| 103 | const [b1, b2] = bots as [User, User]; | |
| 104 | const members = (ids: string[]) => { | |
| 105 | const p = new URLSearchParams({ dial: "0" }); | |
| 106 | for (const id of ids) p.append("member", id); | |
| 107 | return p; | |
| 108 | }; | |
| 109 | await post(alice, "platform", members([b1.id, b2.id])); | |
| 110 | await post(alice, "data-science", members([b1.id])); | |
| 111 | const byTeam = Object.fromEntries(listTeams(app.db).map((t) => [t.slug, t.members])); | |
| 112 | expect(byTeam["platform"]!.sort()).toEqual([b1.id, b2.id].sort()); | |
| 113 | expect(byTeam["data-science"]).toEqual([b1.id]); | |
| 114 | // A person is not an agent. | |
| 115 | const refused = await post(alice, "platform", members([bob.id])); | |
outdated
|
||
| 116 | const told = decodeURIComponent( | |
| 117 | `${refused.headers.get("location") ?? ""} ${refused.headers.get("set-cookie") ?? ""}`, | |
| 118 | ).replace(/\+/g, " "); | |
| 119 | expect(told).toContain("must be an agent"); | |
| 120 | expect(listTeams(app.db).find((t) => t.slug === "platform")!.members.length).toBe(2); | |
| 121 | }); | |
| 122 | ||
| 123 | const api = (u: User, method: string, path: string, body?: unknown, scope: "ro" | "admin" = "admin") => | |
| 124 | fetch(`${servers.url}${path}`, { | |
| 125 | method, | |
| 126 | headers: { | |
| 127 | "content-type": "application/json", | |
| 128 | authorization: `Bearer ${createToken(app.db, u.id, "t", scope).token}`, | |
| 129 | }, | |
| 130 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 131 | }); | |
| 132 | const mcp = async (u: User, name: string, args: unknown, scope: "ro" | "admin" = "admin") => { | |
| 133 | const res = await fetch(`${servers.url}/mcp`, { | |
| 134 | method: "POST", | |
| 135 | headers: { | |
| 136 | "content-type": "application/json", | |
| 137 | accept: "application/json, text/event-stream", | |
| 138 | authorization: `Bearer ${createToken(app.db, u.id, "t", scope).token}`, | |
| 139 | }, | |
| 140 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }), | |
| 141 | }); | |
| 142 | const body = (await res.json()) as any; | |
| 143 | const text = body.result.content[0].text as string; | |
| 144 | try { | |
| 145 | return JSON.parse(text); | |
| 146 | } catch { | |
| 147 | return { error: text }; | |
| 148 | } | |
| 149 | }; | |
| 150 | ||
| 151 | test("the JSON API reads and sets a team, keeps what is left out, and refuses the rest", async () => { | |
| 152 | const [b1] = bots as [User]; | |
| 153 | expect((await api(alice, "GET", "/api/v1/admin/teams")).status).toBe(200); | |
| 154 | const set = await api(alice, "PUT", "/api/v1/admin/teams/design", { dial: 25, members: [b1.id] }); | |
| 155 | expect(set.status).toBe(200); | |
| 156 | expect(await set.json()).toMatchObject({ slug: "design", dial: 25, members: [b1.id] }); | |
| 157 | await api(alice, "PUT", "/api/v1/admin/teams/design", { charter: "Owns the look." }); | |
| 158 | const kept = listTeams(app.db).find((t) => t.slug === "design")!; | |
| 159 | expect([kept.charter, kept.dial, kept.members]).toEqual(["Owns the look.", 25, [b1.id]]); | |
| 160 | expect((await api(alice, "PUT", "/api/v1/admin/teams/design", { dial: 101 })).status).toBe(422); | |
| 161 | expect((await api(alice, "PUT", "/api/v1/admin/teams/design", { dial: 1.5 })).status).toBe(422); | |
| 162 | expect((await api(alice, "PUT", "/api/v1/admin/teams/design", { members: [bob.id] })).status).toBe(422); | |
| 163 | expect((await api(alice, "PUT", "/api/v1/admin/teams/nope", { dial: 1 })).status).toBe(404); | |
| 164 | expect((await api(alice, "PUT", "/api/v1/admin/teams/design", { dial: 5 }, "ro")).status).toBe(403); | |
| 165 | expect((await api(bob, "GET", "/api/v1/admin/teams")).status).toBe(403); | |
| 166 | expect((await api(bob, "PUT", "/api/v1/admin/teams/design", { dial: 1 })).status).toBe(403); | |
| 167 | expect(listTeams(app.db).find((t) => t.slug === "design")!.dial).toBe(25); | |
| 168 | }); | |
| 169 | ||
| 170 | test("the teams tool plans by default, changes with dryRun false, and is not for a non-admin", async () => { | |
| 171 | const planned = await mcp(alice, "teams", { slug: "security", dial: 10 }); | |
| 172 | expect(planned.says).toContain("Would change"); | |
| 173 | expect(listTeams(app.db).find((t) => t.slug === "security")!.dial).toBe(70); | |
| 174 | const done = await mcp(alice, "teams", { slug: "security", dial: 10, dryRun: false }); | |
| 175 | expect(done).toMatchObject({ slug: "security", dial: 10 }); | |
| 176 | expect(listTeams(app.db).find((t) => t.slug === "security")!.dial).toBe(10); | |
| 177 | const over = await mcp(alice, "teams", { slug: "security", dial: 90, dryRun: false }); | |
| 178 | expect(JSON.stringify(over)).toContain("over_100"); | |
| 179 | expect(JSON.stringify(await mcp(bob, "teams", {}))).toContain("not_found"); | |
| 180 | expect(listTeams(app.db).find((t) => t.slug === "security")!.dial).toBe(10); | |
| 181 | }); | |
| 182 | }); |
test/mcp.test.ts +1
| @@ -231,6 +231,7 @@ describe("the forge over MCP", () => { | ||
| 231 | 231 | "system", |
| 232 | 232 | "contribute", |
| 233 | 233 | "limits", |
| 234 | "teams", | |
| 234 | 235 | "cloud_accounts", |
| 235 | 236 | "cloud_account", |
| 236 | 237 | "quotas", |
new above
offline
The page is the only caller of
changeTeam. Add a JSON API route (PUT /api/v1/admin/teams/:slug) and ateamsMCP tool that call it, as limits does, each with a test. Then teams can be reached through MCP as the direction requires.