Merge build/1212-people-agents-platform-pages
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents a6808d3, e9fbe8b · Browse files · 13 files·+1672 added−294 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+1672 added−294 removed
- tests:+937 added−109 removed
- other:+735 added−185 removed
Provenance
- Commit
f44d349- Tree
9d29731- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
a6808d3- Parent 2
e9fbe8b
13 files changed+1672 added−294 removed
modified:apps/platform/src/auth/pages.ts+77 added-23 removed
42 unmodified lines43 .replaceAll(">", ">")44 .replaceAll('"', """)45 .replaceAll("'", "'");46 47+/**48+ * The web's look, as far as a page that loads nothing can take it: its49+ * tokens as literal colours for both schemes (paper, ink, surface, muted,50+ * rule, the input border at 3:1, refused for an error, waiting for a51+ * warning), square controls with hairline borders, a 2 px ink focus ring.52+ * The type is the system's sans, since no font may load here.53+ */54 const STYLE = `48-body{font:16px/1.5 system-ui,sans-serif;margin:0;background:#f6f5f2;color:#1c1b19}49-main{max-width:26rem;margin:3rem auto;padding:0 1rem}50-h1{font-size:1.4rem;margin:0 0 1rem}51-label{display:block;margin:.75rem 0}52-input{display:block;width:100%;box-sizing:border-box;padding:.5rem;font:inherit;margin-top:.25rem}53-button{margin-top:1rem;padding:.5rem 1rem;font:inherit}54-.error{color:#9b1c1c;font-weight:600}55-.warn{background:#fff4d6;padding:.5rem .75rem}56-@media (prefers-color-scheme:dark){body{background:#1c1b19;color:#f6f5f2}.warn{background:#4a3b12}.error{color:#ff9b9b}}55+:root{color-scheme:light dark;--paper:#f5f8fa;--ink:#14191f;--surface:#edf0f3;--muted:#595e65;--rule:#ced1d6;--input:#82868c;--refused:#b32322;--waiting:#875814;--selection:#175fa438}56+@media (prefers-color-scheme:dark){:root{--paper:#0e1114;--ink:#e9ebee;--surface:#171a1e;--muted:#a1a5ab;--rule:#32363b;--input:#6e7278;--refused:#f87e77;--waiting:#efba64;--selection:#79b6f438}}57+*{box-sizing:border-box}58+body{margin:0;background-color:var(--paper);color:var(--ink);caret-color:var(--ink);font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;font-size:16px;line-height:1.5;-webkit-text-size-adjust:100%;text-size-adjust:100%}59+::selection{background-color:var(--selection);color:var(--ink)}60+main{max-width:26rem;margin:0 auto;padding:48px 16px 64px}61+main.document{max-width:44rem}62+h1{font-size:1.5rem;line-height:2rem;font-weight:600;letter-spacing:-.015em;margin:0 0 24px;text-wrap:balance;overflow-wrap:anywhere}63+h2{font-size:1.1875rem;line-height:1.6rem;font-weight:600;letter-spacing:-.01em;margin:40px 0 12px}64+p{margin:0 0 16px}65+a{color:var(--ink);text-decoration-color:var(--input);text-decoration-thickness:1px;text-underline-offset:.2em}66+a:hover{text-decoration-color:currentColor}67+:focus-visible{outline:2px solid var(--ink);outline-offset:2px}68+strong{font-weight:600}69+.consent{border-top:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:16px 0;margin:0 0 24px;overflow-wrap:anywhere}70+.consent p{margin:0}71+.consent p+p{margin-top:4px}72+.consent .warning{margin-top:12px}73+.warn{color:var(--waiting);font-weight:600;white-space:nowrap}74+.warn svg{width:16px;height:16px;vertical-align:-2px;margin-right:6px}75+.error{color:var(--refused);font-weight:600;overflow-wrap:anywhere}76+.muted{color:var(--muted)}77+form{margin:0 0 24px}78+label{display:block;margin:0 0 16px;font-size:.875rem;line-height:1.3rem;font-weight:500}79+input{display:block;width:100%;height:44px;margin-top:6px;padding:0 12px;font-family:inherit;font-size:16px;font-weight:400;color:var(--ink);background-color:var(--paper);border:1px solid;border-color:var(--input);border-radius:0}80+button,.button{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:0 16px;font-family:inherit;font-size:1rem;font-weight:500;text-decoration:none;border:1px solid;border-radius:0;cursor:pointer}81+button{color:var(--paper);background-color:var(--ink);border-color:var(--ink)}82+button.secondary,.button{color:var(--ink);background-color:var(--paper);border-color:var(--input)}83+button:hover{opacity:.88}84+button.secondary:hover,.button:hover{background-color:var(--surface);opacity:1}85+.button{display:flex;width:100%}86+.actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:24px}87+pre{margin:8px 0 12px;padding:8px 12px;overflow-x:auto;background-color:var(--surface);border:1px solid var(--rule)}88+code{font-family:ui-monospace,"SF Mono",Menlo,Consolas,monospace;font-size:.8125rem;overflow-wrap:anywhere}89+ul{margin:0;padding-left:1.25rem}90+li{margin:0 0 8px}91 `;92 93+/** How wide a page reads: a form's one column, or a document's. */94+type Width = "form" | "document";95+96 /** A page titled `title` around `body`, which is HTML already escaped. */60-export const page = (title: string, body: string) =>97+export const page = (title: string, body: string, width: Width = "form") =>98 `<!doctype html>99 <html lang="en">100 <head>101 <meta charset="utf-8">102 <meta name="viewport" content="width=device-width, initial-scale=1">103+<meta name="color-scheme" content="light dark">104 <title>${escapeHtml(title)} · ${escapeHtml(Brand.name)}</title>105 <style>${STYLE}</style>106 </head>69-<body><main>107+<body><main${width === "document" ? ' class="document"' : ""}>108 ${body}109 </main></body>110 </html>111 `;112 75-/** Who asks, where access goes, and the loopback warning. */113+/** A warning's mark: a triangle drawn in the line's colour, hidden from a screen reader. */114+const WARNING_MARK = `<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M8 1.75 14.75 14H1.25z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/><path d="M8 6.25v3.5M8 11.75v.25" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>`;115+116+/**117+ * The consent, first under the title in its own ruled block: who asks,118+ * where access goes, and the loopback warning when it applies.119+ */120 const askerParagraphs = (asker: Asker) => {121 const name = `<strong>${escapeHtml(asker.clientName)}</strong>`;122 123 const domain =1 unmodified line125 ? ""126 : ` (published by ${escapeHtml(asker.clientDomain)})`;127 128 const loopback = asker.redirectIsLoopback85- ? `<p class="warn">This sends access to an app on your computer. Continue only if you just started signing in from it.</p>`129+ ? `<p class="warning"><strong class="warn">${WARNING_MARK}Warning</strong> This sends access to an app on your computer. Continue only if you just started signing in from it.</p>`130 : "";131 132+ return `<section class="consent" aria-label="Who asks">133+<p>${name}${domain} asks to act as you.</p>88- return `<p>${name}${domain} asks to act as you. Access goes to <strong>${escapeHtml(asker.redirectHost)}</strong>.</p>89-${loopback}`;134+<p>Access goes to <strong>${escapeHtml(asker.redirectHost)}</strong>.</p>135+${loopback}136+</section>`;137 };138 139 const messageParagraph = (message?: string) =>140 message === undefined11 unmodified lines152 */153 const googleChoices = (offers: Offers, form: PendingForm) =>154 offers.google155 ? {109- link: `<button type="submit" formaction="${GOOGLE_PATHS.link}">Sign in and link Google</button>`,110- start: `<p><a href="${GOOGLE_PATHS.start}?request=${encodeURIComponent(form.request)}">Continue with Google</a></p>111-<p>Or sign in with your handle and password.</p>`,156+ link: `<button type="submit" class="secondary" formaction="${GOOGLE_PATHS.link}">Sign in and link Google</button>`,157+ start: `<p><a href="${GOOGLE_PATHS.start}?request=${encodeURIComponent(form.request)}" class="button">Continue with Google</a></p>158+<p class="muted">Or sign in with your handle and password.</p>`,159 }160 : { link: "", start: "" };161 162 /** The sign-in form, posting back to `/authorize`, with a way to sign up instead. */8 unmodified lines171 return page(172 "Sign in",173 `<h1>Sign in to ${escapeHtml(Brand.name)}</h1>174 ${askerParagraphs(asker)}128-${messageParagraph(message)}175 ${google.start}176+${messageParagraph(message)}177 <form method="post" action="/authorize">178 ${hiddenFields(form)}179 <label>Handle <input name="handle" autocomplete="username" autocapitalize="none" spellcheck="false" required></label>180 <label>Password <input type="password" name="password" autocomplete="current-password" required></label>181+<div class="actions">182 <button type="submit">Sign in</button>183 ${google.link}184+</div>185 </form>186 <p>New here? <a href="/signup?request=${encodeURIComponent(form.request)}">Choose a handle and sign up</a>.</p>`187 );188 };18 unmodified lines207 ${messageParagraph(message)}208 <form method="post" action="${GOOGLE_PATHS.handle}">209 ${hiddenFields(form)}210 <label>Handle <input name="handle" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="39" required></label>162-<button type="submit">Sign up</button>211+<div class="actions"><button type="submit">Sign up</button></div>212 </form>213 <p>Have an account with a password? <a href="${escapeHtml(signInHref)}">Sign in with it</a> and choose "Sign in and link Google".</p>`214 );215 12 unmodified lines228 <form method="post" action="/signup">229 ${hiddenFields(form)}230 <label>Handle <input name="handle" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="39" required></label>231 <label>Password, 12 to 256 characters <input type="password" name="password" autocomplete="new-password" minlength="12" maxlength="256" required></label>183-<button type="submit">Sign up</button>232+<div class="actions"><button type="submit">Sign up</button></div>233 </form>234 <p>Have an account? <a href="${escapeHtml(signInHref)}">Sign in</a>.</p>`235 );236 188-/** A page with nothing to do but read why, and start again from the app. */237+/**238+ * A page with nothing to do but read why, and start again from the app. The239+ * problem is not a refusal (a page expired, a client could not be read),240+ * so it reads in ink, with one way onward.241+ */242 export const problemPage = (message: string) =>243 page(244 "Sign-in problem",245 `<h1>Signing in did not work</h1>193-${messageParagraph(message)}`246+<p role="alert">${escapeHtml(message)}</p>247+<p><a href="/">What this host serves</a></p>`248 );modified:apps/platform/src/home.ts+3 added-11 removed
87 unmodified lines88 89 const list = (items: readonly string[]) =>90 `<ul>\n${items.map(item).join("\n")}\n</ul>`;91 92-/** Wider than sign-in's column, for clone and install lines. */93-const STYLE = `<style>94-main{max-width:44rem}95-h2{font-size:1.1rem;margin:2rem 0 .5rem}96-pre{overflow-x:auto;padding:.5rem .75rem;background:rgba(127,127,127,.12)}97-code{font-family:ui-monospace,monospace;font-size:.9em}98-li{margin:.25rem 0}99-</style>`;100-92 const projectsSection = (origin: string, projects: readonly ProjectListing[]) =>93 section(94 "Projects",95 projects.length === 017 unmodified lines113 114 return page(115 "What this host serves",116 [126- STYLE,117 `<h1>${escapeHtml(Brand.name)}</h1>`,118 `<p>A Git platform where everything a project ships is public. A project states each change it wants as an ask; you answer one with a commit, and the platform lands it only once its checks pass.</p>`,119 ...Option.toArray(120 Option.map(29 unmodified lines150 "Drafting",151 `<p>A member can ask the platform's agent to draft a proposed ask (Workers AI, ${code(draftModel)}); a decider accepts it, and only people are credited.</p>`152 ),153 section("Health", `<p>${link(`${origin}/health`)}</p>`),164- ].join("\n")154+ ].join("\n"),155+ // Wider than sign-in's column, for clone and install lines.156+ "document"157 );158 };159 160 /** `/` for `request`: Markdown for an agent that asks for it, else the page. */44 unmodified linesadded:apps/platform/test/pages.test.ts+426 added
1+/**2+ * The platform's own HTML pages (sign-in, which is an MCP client's3+ * consent, sign-up, Google's handle page, the problem page, and `/`) load4+ * nothing, so each carries its look in one inline `<style>`. This reads5+ * that style the way a browser would for each colour scheme and holds its6+ * literal colours to WCAG's contrast floors in both: text and links at7+ * 4.5:1, input borders at 3:1. The formulas are WCAG 2.2's own (relative8+ * luminance over sRGB), written here.9+ */10+import { describe, expect, it } from "@effect/vitest";11+import { FrontPageMemory } from "@repo/project/front-page/memory";12+import { Projects } from "@repo/project/projects";13+import { ProjectName } from "@repo/protocol/ids";14+import { UnknownProject } from "@repo/protocol/refusal";15+import { Effect, Layer, Option } from "effect";16+17+import {18+ pickHandlePage,19+ problemPage,20+ signInPage,21+ signUpPage,22+} from "../src/auth/pages.ts";23+import type { Asker, PendingForm } from "../src/auth/pages.ts";24+import { homeResponse } from "../src/home.ts";25+import { HostInfo } from "../src/host-info.ts";26+27+// --- The pages, from stand-in inputs ------------------------------------------28+29+const claude: Asker = {30+ clientDomain: "claude.ai",31+ clientName: "Claude",32+ redirectHost: "claude.ai",33+ redirectIsLoopback: false,34+};35+36+const local: Asker = {37+ clientName: "A CLI",38+ redirectHost: "127.0.0.1:53682",39+ redirectIsLoopback: true,40+};41+42+const form: PendingForm = { csrf: "csrf-token", request: "sealed-request" };43+44+const home = Effect.gen(function* () {45+ const response = yield* homeResponse(46+ new Request("https://platform.example/", {47+ headers: { accept: "text/html" },48+ })49+ );50+51+ return yield* Effect.promise(() => response.text());52+}).pipe(53+ Effect.provide(54+ Layer.mergeAll(55+ FrontPageMemory.layer({56+ credits: [],57+ entries: [],58+ projects: [59+ {60+ openAsks: 2,61+ posture: "open",62+ project: ProjectName.make("datekit"),63+ },64+ ],65+ }),66+ Layer.succeed(67+ Projects,68+ Projects.of({69+ create: () => Effect.die("the home page makes no project"),70+ get: (project) => Effect.fail(new UnknownProject({ project })),71+ })72+ ),73+ Layer.succeed(74+ HostInfo,75+ HostInfo.of({76+ draftModel: "@cf/test/drafter",77+ webUrl: Option.some("https://web.example"),78+ })79+ )80+ )81+ )82+);83+84+const PAGES = {85+ "Google's handle page": pickHandlePage(86+ local,87+ form,88+ "/authorize?x=1",89+ "That handle is taken. Choose another, or sign in."90+ ),91+ "sign-in": signInPage(92+ claude,93+ form,94+ { google: true },95+ "The handle or password is wrong."96+ ),97+ "sign-up": signUpPage(98+ local,99+ form,100+ "/authorize?x=1",101+ "A password is 12 to 256 characters."102+ ),103+ "the problem page": problemPage(104+ "This sign-in page expired or was not opened here. Start signing in again from your app."105+ ),106+} as const;107+108+/** The pages with a form: each input's border must be seen. */109+const FORMS = new Set(["Google's handle page", "sign-in", "sign-up"]);110+111+// --- Reading a style as a browser would ---------------------------------------112+113+interface Rule {114+ readonly selectors: readonly string[];115+ readonly declarations: ReadonlyMap<string, string>;116+ /** Whether it sits in the dark scheme's media query. */117+ readonly dark: boolean;118+}119+120+/** The one inline style of a page. */121+const styleOf = (html: string) => {122+ const styles = [...html.matchAll(/<style>(?<css>.*?)<\/style>/gsu)];123+124+ expect(styles).toHaveLength(1);125+126+ return styles[0]?.groups?.css ?? "";127+};128+129+/** How a brace moves the depth of a rule. */130+const DEPTH: ReadonlyMap<string, number> = new Map([131+ ["{", 1],132+ ["}", -1],133+]);134+135+const DARK = /^@media\s*\(\s*prefers-color-scheme\s*:\s*dark\s*\)$/u;136+137+/** Every rule of `css`, a dark-scheme media query's marked dark. */138+const rulesOf = (css: string, dark = false): readonly Rule[] => {139+ const rules: Rule[] = [];140+ const text = css.replaceAll(/\/\*.*?\*\//gsu, "");141+ let at = 0;142+143+ while (at < text.length) {144+ const open = text.indexOf("{", at);145+146+ if (open === -1) {147+ break;148+ }149+150+ const head = text.slice(at, open).trim();151+ let depth = 1;152+ let close = open + 1;153+154+ while (depth > 0 && close < text.length) {155+ depth += DEPTH.get(text[close] ?? "") ?? 0;156+ close += 1;157+ }158+159+ const body = text.slice(open + 1, close - 1);160+161+ if (head.startsWith("@media")) {162+ rules.push(...(DARK.test(head) ? rulesOf(body, true) : []));163+ } else {164+ rules.push({165+ dark,166+ declarations: new Map(167+ body168+ .split(";")169+ .map((declaration) => declaration.split(":"))170+ .filter((parts) => parts.length >= 2)171+ .map(([name = "", ...value]) => [172+ name.trim(),173+ value.join(":").trim(),174+ ])175+ ),176+ selectors: head.split(",").map((selector) => selector.trim()),177+ });178+ }179+180+ at = close;181+ }182+183+ return rules;184+};185+186+type Scheme = "dark" | "light";187+188+/** A property's value as the scheme sets it, with whether the dark query set any of it. */189+interface Resolved {190+ readonly value: string | undefined;191+ readonly fromDark: boolean;192+}193+194+/** `property` on `selector` in `scheme`: the last rule that sets it wins, and `var()` resolves on `:root`. */195+const resolve = (196+ rules: readonly Rule[],197+ scheme: Scheme,198+ selector: string,199+ property: string200+): Resolved => {201+ const applying = rules.filter(202+ (rule) =>203+ (scheme === "dark" || !rule.dark) &&204+ rule.selectors.includes(selector) &&205+ rule.declarations.has(property)206+ );207+208+ const rule = applying.at(-1);209+ const value = rule?.declarations.get(property);210+211+ const variable = /^var\((?<name>--[\w-]+)\)$/u.exec(value ?? "")?.groups212+ ?.name;213+214+ if (variable === undefined) {215+ return { fromDark: rule?.dark ?? false, value };216+ }217+218+ const inner = resolve(rules, scheme, ":root", variable);219+220+ return {221+ fromDark: (rule?.dark ?? false) || inner.fromDark,222+ value: inner.value,223+ };224+};225+226+/** `#rgb` or `#rrggbb` as its three channels, 0–255. */227+const channelsOf = (hex: string) => {228+ const digits = /^#(?<body>[\da-f]{3}|[\da-f]{6})$/iu.exec(hex)?.groups?.body;229+230+ expect(digits, `${hex} is a literal hex colour`).toBeDefined();231+232+ const full =233+ digits?.length === 3234+ ? digits.replaceAll(/(?<digit>.)/gu, "$<digit>$<digit>")235+ : (digits ?? "000000");236+237+ return [0, 2, 4].map((start) =>238+ Number.parseInt(full.slice(start, start + 2), 16)239+ );240+};241+242+/** WCAG 2.2's relative luminance of an sRGB colour. */243+const luminanceOf = (hex: string) => {244+ const [r = 0, g = 0, b = 0] = channelsOf(hex).map((channel) => {245+ const unit = channel / 255;246+247+ return unit <= 0.04045 ? unit / 12.92 : ((unit + 0.055) / 1.055) ** 2.4;248+ });249+250+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;251+};252+253+/** WCAG 2.2's contrast ratio of two colours. */254+const contrast = (one: string, other: string) => {255+ const [light, dark] = [luminanceOf(one), luminanceOf(other)].toSorted(256+ (a, b) => b - a257+ );258+259+ return ((light ?? 0) + 0.05) / ((dark ?? 0) + 0.05);260+};261+262+/** A colour the scheme sets: fails the test when it sets none. */263+const colour = (264+ rules: readonly Rule[],265+ scheme: Scheme,266+ selector: string,267+ property: string268+) => {269+ const { value } = resolve(rules, scheme, selector, property);270+271+ expect(value, `${selector} sets ${property} in ${scheme}`).toBeDefined();272+273+ return value ?? "";274+};275+276+// --- The checks -----------------------------------------------------------------277+278+/** Every floor, in one scheme, on one page's style. */279+const holdsTheFloors = (280+ rules: readonly Rule[],281+ scheme: Scheme,282+ hasForm: boolean283+) => {284+ const paper = colour(rules, scheme, "body", "background-color");285+286+ const at = (selector: string, property = "color") =>287+ contrast(colour(rules, scheme, selector, property), paper);288+289+ expect(at("body"), "body text").toBeGreaterThanOrEqual(4.5);290+ expect(at("a"), "links").toBeGreaterThanOrEqual(4.5);291+ expect(at(".error"), "an error").toBeGreaterThanOrEqual(4.5);292+ expect(at(".muted"), "muted text").toBeGreaterThanOrEqual(4.5);293+ expect(at(".warn"), "the warning's word").toBeGreaterThanOrEqual(4.5);294+295+ if (hasForm) {296+ expect(at("input", "border-color"), "input borders").toBeGreaterThanOrEqual(297+ 3298+ );299+ expect(300+ contrast(301+ colour(rules, scheme, "input", "color"),302+ colour(rules, scheme, "input", "background-color")303+ ),304+ "input text"305+ ).toBeGreaterThanOrEqual(4.5);306+ expect(307+ contrast(308+ colour(rules, scheme, "button", "color"),309+ colour(rules, scheme, "button", "background-color")310+ ),311+ "the primary button"312+ ).toBeGreaterThanOrEqual(4.5);313+ }314+};315+316+describe("the platform's own pages", () => {317+ const each = [318+ ...Object.entries(PAGES).map(([name, html]) => ({319+ form: FORMS.has(name),320+ html: Effect.succeed(html),321+ name,322+ })),323+ { form: false, html: home, name: "the platform's /" },324+ ];325+326+ describe.each(each)("$name", (page) => {327+ it.effect("loads nothing: no script, stylesheet, font or image", () =>328+ Effect.gen(function* () {329+ expect(yield* page.html).not.toMatch(330+ /<script|<link|<img|src=|url\(|@import|@font-face/u331+ );332+ })333+ );334+335+ it.effect("follows the system's scheme and colours its links in both", () =>336+ Effect.gen(function* () {337+ const rules = rulesOf(styleOf(yield* page.html));338+339+ expect(resolve(rules, "light", ":root", "color-scheme").value).toBe(340+ "light dark"341+ );342+ expect(resolve(rules, "dark", "a", "color").fromDark).toBeTruthy();343+ expect(344+ resolve(rules, "dark", "body", "background-color").fromDark345+ ).toBeTruthy();346+ })347+ );348+349+ it.effect("holds every contrast floor in the light and dark schemes", () =>350+ Effect.gen(function* () {351+ const rules = rulesOf(styleOf(yield* page.html));352+353+ holdsTheFloors(rules, "light", page.form);354+ holdsTheFloors(rules, "dark", page.form);355+ })356+ );357+358+ it.effect("reads at 16 px, inputs too", () =>359+ Effect.gen(function* () {360+ const rules = rulesOf(styleOf(yield* page.html));361+362+ expect(resolve(rules, "light", "body", "font-size").value).toBe("16px");363+ expect(resolve(rules, "light", "input", "font-size").value).toBe(364+ "16px"365+ );366+ })367+ );368+ });369+});370+371+describe("the sign-in page, as an MCP client's consent", () => {372+ it("says who asks and where access goes before Google and the form", () => {373+ const html = PAGES["sign-in"];374+ const asks = html.indexOf("asks to act as you");375+ const goes = html.indexOf("Access goes to");376+ const google = html.indexOf("Continue with Google");377+ const formAt = html.indexOf("<form");378+379+ expect(asks).toBeGreaterThan(html.indexOf("<h1"));380+ expect(goes).toBeGreaterThan(asks);381+ expect(google).toBeGreaterThan(goes);382+ expect(formAt).toBeGreaterThan(google);383+ expect(html.indexOf("New here?")).toBeGreaterThan(formAt);384+ });385+386+ it("puts the loopback warning in the consent, as a word, before the form", () => {387+ const html = signInPage(local, form, { google: false });388+ const warning = html.indexOf("Warning");389+390+ expect(warning).toBeGreaterThan(html.indexOf("Access goes to"));391+ expect(warning).toBeLessThan(html.indexOf("<form"));392+ expect(html).toContain(393+ "This sends access to an app on your computer. Continue only if you just started signing in from it."394+ );395+ expect(signInPage(claude, form, { google: false })).not.toContain(396+ "Warning"397+ );398+ });399+400+ it("escapes every value a client supplies", () => {401+ const html = signInPage(402+ {403+ clientDomain: `"><img src=x>`,404+ clientName: `<script>alert("x")</script>`,405+ redirectHost: "evil.example<b>",406+ redirectIsLoopback: false,407+ },408+ { csrf: `"><script>`, request: `a"b` },409+ { google: true }410+ );411+412+ expect(html).not.toContain("<script>");413+ expect(html).not.toContain("<img");414+ expect(html).not.toContain("<b>");415+ expect(html).toContain("<script>alert("x")</script>");416+ expect(html).toContain("evil.example<b>");417+ });418+419+ it("draws an error in the refusal's colour, and the problem page's in ink", () => {420+ expect(PAGES["sign-in"]).toMatch(421+ /<p class="error" role="alert">The handle or password is wrong\.<\/p>/u422+ );423+ expect(PAGES["the problem page"]).not.toContain('class="error"');424+ expect(PAGES["the problem page"]).toMatch(/<a href="\/">/u);425+ });426+});added:apps/web/src/features/agents/reference.tsx+172 added
1+/**2+ * The For agents page's reference sections, set like a man page: the3+ * CLI's synopsis, the endpoints, the limits and the refusals. Every word4+ * that is not a heading comes from `@repo/agent-kit` (`synopsis`,5+ * `agentEndpoints`, `agentLimits`) or the refusal union itself, so the6+ * page and `/agents.md` say the same. Mono only for what a terminal takes:7+ * commands, addresses and tags.8+ */9+import type {10+ Endpoint,11+ Limit,12+ SynopsisLine,13+} from "@repo/agent-kit/agent-setup";14+import { groups } from "@repo/protocol/refusal";15+import { Fragment } from "react";16+import type { ReactNode } from "react";17+18+/** A link in running text: the rule colour's underline, ink on hover. */19+export const LINK =20+ "decoration-rule underline underline-offset-[0.2em] hover:decoration-current";21+22+/** One section of the reference: its heading at Title size, in the sans, then its body. */23+export const ReferenceSection = ({24+ children,25+ id,26+ title,27+}: {28+ readonly children: ReactNode;29+ readonly id: string;30+ readonly title: string;31+}) => (32+ <section aria-labelledby={id} className="flex min-w-0 flex-col gap-4">33+ {/* The anchor's target: its margin clears the sticky bars above main. */}34+ <h2 className="text-title scroll-mt-16" id={id}>35+ {title}36+ </h2>37+ {children}38+ </section>39+);40+41+/**42+ * A usage line that wraps only between its words, never inside a flag43+ * (`[--json]` stays whole), so a phone reads it as typed.44+ */45+const Usage = ({ usage }: { readonly usage: string }) => (46+ <code className="text-mono font-mono">47+ {usage.split(" ").map((word, index) => (48+ <Fragment key={index}>49+ {index === 0 ? null : " "}50+ <span className="whitespace-nowrap">{word}</span>51+ </Fragment>52+ ))}53+ </code>54+);55+56+/** Every command as typed, each over what it does, set close like a man page's synopsis. */57+export const Synopsis = ({58+ lines,59+}: {60+ readonly lines: readonly SynopsisLine[];61+}) => (62+ <ul className="flex flex-col gap-3">63+ {lines.map(({ summary, usage }) => (64+ <li className="flex min-w-0 flex-col" key={usage}>65+ <Usage usage={usage} />66+ <p className="text-ui text-muted-foreground max-w-[70ch]">{summary}</p>67+ </li>68+ ))}69+ </ul>70+);71+72+/** Each address an agent reads, one line each, linked where a browser can open it. */73+export const Endpoints = ({74+ endpoints,75+}: {76+ readonly endpoints: readonly Endpoint[];77+}) => (78+ <ul className="border-rule flex flex-col border-t">79+ {endpoints.map(({ readable, url, what }) => {80+ const address = (81+ <code className="text-mono font-mono [overflow-wrap:anywhere]">82+ {url}83+ </code>84+ );85+86+ return (87+ <li88+ className="border-rule flex min-w-0 flex-col gap-0.5 border-b py-2.5"89+ key={url}90+ >91+ {readable ? (92+ // A server's own text, not a page of the app.93+ <a className={`${LINK} w-fit max-w-full`} href={url}>94+ {address}95+ </a>96+ ) : (97+ address98+ )}99+ <p className="text-ui text-muted-foreground max-w-[70ch]">{what}</p>100+ </li>101+ );102+ })}103+ </ul>104+);105+106+/** The limits, as a plain table. */107+export const Limits = ({ limits }: { readonly limits: readonly Limit[] }) => (108+ <table className="text-ui w-full max-w-[48rem] border-collapse text-left">109+ <thead>110+ <tr className="border-rule border-b">111+ <th className="text-label text-muted-foreground py-2 pr-6" scope="col">112+ Limit113+ </th>114+ <th className="text-label text-muted-foreground py-2" scope="col">115+ Value116+ </th>117+ </tr>118+ </thead>119+ <tbody>120+ {limits.map(({ limit, value }) => (121+ <tr className="border-rule border-b align-baseline" key={limit}>122+ <th className="py-2.5 pr-6 font-normal" scope="row">123+ {limit}124+ </th>125+ <td className="py-2.5 tabular-nums">{value}</td>126+ </tr>127+ ))}128+ </tbody>129+ </table>130+);131+132+/**133+ * Where `/llms-full.txt` lists a refusal: a text fragment on its table row134+ * (`` `Tag` | Group ``), which nothing else in the file reads. A dash ends135+ * a fragment's word, so it is escaped as well.136+ */137+const rowOf = (tag: string, group: string) =>138+ `/llms-full.txt#:~:text=${encodeURIComponent(`\`${tag}\` | ${group}`).replaceAll("-", "%2D")}`;139+140+/** Every refusal of the union, by group, each tag linked to its row. */141+export const Refusals = () => (142+ <>143+ <p className="text-ui text-muted-foreground max-w-[70ch]">144+ Each tag opens its row in{" "}145+ <a className={LINK} href="/llms-full.txt">146+ llms-full.txt147+ </a>148+ .149+ </p>150+ <dl className="border-rule flex flex-col border-t">151+ {groups.map(({ members, name }) => (152+ <div153+ className="border-rule shell:grid shell:grid-cols-[12rem_minmax(0,1fr)] shell:gap-4 flex min-w-0 flex-col gap-1 border-b py-2.5"154+ key={name}155+ >156+ <dt className="text-ui font-medium">{name}</dt>157+ <dd className="flex min-w-0 flex-wrap gap-x-3 gap-y-1">158+ {members.map(({ identifier }) => (159+ <a160+ className={LINK}161+ href={rowOf(identifier, name)}162+ key={identifier}163+ >164+ <code className="text-mono font-mono">{identifier}</code>165+ </a>166+ ))}167+ </dd>168+ </div>169+ ))}170+ </dl>171+ </>172+);modified:apps/web/src/features/agents/setup-page.tsx+127 added-52 removed
1232345675689108111213141516171819202122231011122425262728293031323334353615161737383940414243444546474849192021222324252627505152535455565758596061626364656667293068697071723473747576772 unmodified lines80818283454647484950515253545556575859606162636465666768697071848586878889909192939472739596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149/** * The Agents page: each way an agent connects, as `@repo/agent-kit`'s * `agentSetup` gives it, so the page has no text of its own for a snippet * The For agents page: one reference, in the order a reader reaches for * it: the CLI's synopsis, the ways to connect, the endpoints, the limits * and the refusals. The inspector is its contents. Every snippet and every * line of reference is `@repo/agent-kit`'s (`agentSetup` and its * neighbours), so the page has no text of its own for any of them * (principle 4). A shell line is a `CommandLine`; JSON and text to paste * sit in a block with the same copy affordance. A view: channels in, * markup out. * sit in a block with the same copy affordance. A view: the CLI's commands * and the two hosts' URLs in, markup out. */import type { SetupChannel, SetupSnippet } from "@repo/agent-kit/agent-setup";import { agentEndpoints, agentLimits, agentSetup, synopsis,} from "@repo/agent-kit/agent-setup";import type { SetupChannel, SetupInput, SetupSnippet,} from "@repo/agent-kit/agent-setup";import { Check, Copy } from "lucide-react";
import { Region } from "../ask/fields.tsx";import { CopyButton } from "../code/copy.tsx";import { LINK } from "../shared/classes.ts";import { Button } from "../../components/ui/button.tsx";import { CommandLine } from "../shared/command.tsx";import { useCopy } from "../shared/copy-action.tsx";import { Workspace } from "../shared/shell/workspace.tsx";import { Endpoints, Limits, LINK, ReferenceSection, Refusals, Synopsis,} from "./reference.tsx";
/** A channel's heading id, from its title: `agents-remote-mcp`. */const idOf = (title: string) => `agents-${title.toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-")}`;/** The reference's sections, in order: each one's anchor and heading. */const SECTIONS = [ { id: "synopsis", title: "Synopsis" }, { id: "connect", title: "Connect" }, { id: "endpoints", title: "Endpoints" }, { id: "limits", title: "Limits" }, { id: "refusals", title: "Refusals" },] as const;
/** JSON or text to paste: whole, wrapping, with a button that copies it. */const SnippetBlock = ({ snippet }: { readonly snippet: SetupSnippet }) => { const { copied, copy } = useCopy(snippet.text);
const SnippetBlock = ({ snippet }: { readonly snippet: SetupSnippet }) => ( <div className="border-rule bg-surface flex max-w-full min-w-0 items-start gap-2 border py-1 pr-1 pl-3"> <pre className="min-w-0 flex-1 overflow-x-auto py-0.5 font-mono text-[0.8125rem] leading-6 whitespace-pre-wrap"> <code className="[overflow-wrap:anywhere] select-all"> {snippet.text} </code> </pre> <div className="shrink-0"> <CopyButton label="Copy" text={snippet.text} /> return ( <div className="border-rule bg-surface flex max-w-full min-w-0 items-start gap-2 border py-1 pr-1 pl-3"> <pre className="text-mono leading-terminal min-w-0 flex-1 overflow-x-auto py-0.5 font-mono whitespace-pre-wrap"> <code className="[overflow-wrap:anywhere] select-all"> {snippet.text} </code> </pre> <Button className="shrink-0" onClick={copy} size="sm" type="button" variant="ghost" > {copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />} <span aria-live="polite">{copied ? "Copied" : "Copy"}</span> </Button> </div> </div>); );};
const Snippet = ({ snippet }: { readonly snippet: SetupSnippet }) => ( <figure className="flex min-w-0 flex-col gap-1.5"> <figcaption className="text-muted-foreground text-sm"> <figcaption className="text-ui text-muted-foreground"> {snippet.label} </figcaption> {snippet.language === "sh" ? ( <CommandLine command={snippet.text} />2 unmodified lines )} </figure>);
export const AgentSetupView = ({ channels,}: { readonly channels: readonly SetupChannel[];}) => ( <> <p className="max-w-[70ch]"> Pick the way your agent works. Each one reaches the same asks, claims and verdicts; an agent that reads Markdown can read{" "} <a className={LINK} href="/agents.md"> this page as Markdown </a> . </p> {channels.map((channel) => ( <Region id={idOf(channel.title)} key={channel.title} title={channel.title} > <p className="max-w-[70ch]">{channel.useWhen}</p> <div className="flex max-w-[80ch] flex-col gap-4"> {channel.snippets.map((snippet) => ( <Snippet key={snippet.label} snippet={snippet} /> ))} </div> </Region>/** One way to connect: its name, the agent it is for, and what to copy. */const Channel = ({ channel }: { readonly channel: SetupChannel }) => ( <div className="border-rule flex min-w-0 flex-col gap-3 border-t pt-4"> <h3 className="text-want font-semibold">{channel.title}</h3> <p className="max-w-[70ch]">{channel.useWhen}</p> <div className="flex max-w-[80ch] flex-col gap-4"> {channel.snippets.map((snippet) => ( <Snippet key={snippet.label} snippet={snippet} /> ))} </div> </div> ))} </>);
/** The inspector: the sections, as anchors. */const Contents = () => ( <nav aria-label="Contents"> <ul className="flex flex-col"> {SECTIONS.map(({ id, title }) => ( <li key={id}> {/* An anchor in this page, not a page of its own. */} <a className="text-ui hover:bg-surface -mx-2 flex h-8 items-center px-2 transition-colors duration-[120ms]" href={`#${id}`} > {title} </a> </li> ))} </ul> </nav>);
export const AgentsView = (input: SetupInput) => ( <Workspace facts={<Contents />} factsHeading="Contents" meta={ <> Every way in reaches the same asks, claims and verdicts. As Markdown:{" "} {/* A server route, not a page of the app. */} <a className={`text-foreground ${LINK}`} href="/agents.md"> agents.md </a> </> } title="For agents" > <ReferenceSection id="synopsis" title="Synopsis"> <Synopsis lines={synopsis(input.commands)} /> </ReferenceSection> <ReferenceSection id="connect" title="Connect"> {agentSetup(input).map((channel) => ( <Channel channel={channel} key={channel.title} /> ))} </ReferenceSection> <ReferenceSection id="endpoints" title="Endpoints"> <Endpoints endpoints={agentEndpoints(input)} /> </ReferenceSection> <ReferenceSection id="limits" title="Limits"> <Limits limits={agentLimits()} /> </ReferenceSection> <ReferenceSection id="refusals" title="Refusals"> <Refusals /> </ReferenceSection> </Workspace>);modified:apps/web/src/features/people/person-page.tsx+130 added-73 removed
1 /**2 * A person's page: their credit, read from the trailers on landed commits,3- * grouped by project and then by area, each role with how many landings4- * name them in it. Credit gates nothing and ranks no one (GLOSSARY.md5- * "Credit", "Record"), so the page orders by name, never by count, and adds6- * nothing up.3+ * grouped by project and then by area, each area one sentence of the roles4+ * they hold there ("Answered and asked in datekit/src"), linked to the5+ * project's landings. Credit gates nothing and ranks no one (GLOSSARY.md6+ * "Credit", "Record"): the read counts landings per role, and the page7+ * draws none of those counts, orders by name, and adds nothing up.8 */9 import { CreditRole } from "@repo/protocol/domain/credit";10 import type { CreditSummary } from "@repo/protocol/domain/record";11 import type { Handle, ProjectName } from "@repo/protocol/ids";12 import { Array, Order } from "effect";13 13-import { SECTION } from "../shared/classes.ts";14 import { EmptyState } from "../shared/empty.tsx";15 import { PageShell } from "../shared/layout.tsx";16+import { AppLink } from "../shared/link.tsx";17 import { projectPath } from "../shared/paths.ts";18+import { MetaCode, MetaLine, Row, RowGroup } from "../shared/row.tsx";19+import { projectSections } from "../shared/shell/sections.ts";20+import { Workspace } from "../shared/shell/workspace.tsx";21 18-/** One area of a project: each role a person holds there, with its count. */22+/** One area of a project: each role a person holds there. */23 export interface AreaCredit {24 readonly area: string;21- readonly roles: readonly {22- readonly count: number;23- readonly role: CreditRole;24- }[];25+ readonly roles: readonly CreditRole[];26 }27 28 /** One project: the areas a person is credited in. */29 export interface ProjectCredit {30 readonly areas: readonly AreaCredit[];31 readonly project: ProjectName;32 }33 34+/** Each role as the sentence says it, in the past: the trailer names what they did. */35+const ROLE_WORD = {36+ "Advised-by": "advised",37+ "Asked-by": "asked",38+ "Decided-by": "decided",39+ "Finished-by": "finished",40+ "Mentored-by": "mentored",41+ "Released-by": "released",42+ "Signed-off-by": "answered",43+} as const satisfies Record<CreditRole, string>;44+45+/**46+ * The order a sentence names roles in: the answer first (it is the work47+ * the landing is), then the trailers' own order.48+ */49+const SENTENCE_ORDER: readonly CreditRole[] = [50+ "Signed-off-by",51+ ...CreditRole.literals.filter((role) => role !== "Signed-off-by"),52+];53+33-const byRole = Order.mapInput(Order.Number, (role: CreditRole) =>34- CreditRole.literals.indexOf(role)54+const bySentence = Order.mapInput(Order.Number, (role: CreditRole) =>55+ SENTENCE_ORDER.indexOf(role)56 );57 58+/** Words joined as a sentence lists them: `a`, `a and b`, `a, b and c`. */59+const listed = (words: readonly string[]) =>60+ words.length < 261+ ? words.join("")62+ : `${words.slice(0, -1).join(", ")} and ${words.at(-1) ?? ""}`;63+64+/** Where an area sits, in words: "the whole project" for its root. */65+const whereOf = (project: string, area: string) =>66+ area === "." || area === "" ? "the whole project" : `${project}/${area}`;67+68+/**69+ * An area's roles as one sentence: "Answered and asked in datekit/src",70+ * "Decided in the whole project".71+ */72+export const areaSentence = (73+ project: string,74+ area: string,75+ roles: readonly CreditRole[]76+) => {77+ const words = Array.dedupe(Array.sort(roles, bySentence)).map(78+ (role) => ROLE_WORD[role]79+ );80+81+ const sentence = `${listed(words)} in ${whereOf(project, area)}`;82+83+ return `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}`;84+};85+86 /** `rows` grouped by `key`, the groups in the order their keys sort. */87 const groupBy = <A,>(88 rows: readonly A[],89 key: (row: A) => string1 unmodified line91 Object.entries(Array.groupBy(rows, key))92 .toSorted(([one], [other]) => one.localeCompare(other))93 .map(([, group]) => group);94 46-/**47- * A person's credit by project, then by area (each by name), each area's48- * roles in trailer order; a role listed twice in one area counts once, with49- * both counts.50- */95+/** A person's credit by project, then by area (each by name), each area's roles once each. */96 export const creditsByProject = (97 credits: readonly CreditSummary[]98 ): readonly ProjectCredit[] =>99 groupBy(credits, ({ project }) => project).map((inProject) => ({100 areas: groupBy(inProject, ({ area }) => area).map((inArea) => ({101 area: Array.headNonEmpty(inArea).area,57- roles: groupBy(inArea, ({ role }) => role)58- .map((rows) => ({59- count: rows.reduce((sum, row) => sum + row.count, 0),60- role: Array.headNonEmpty(rows).role,61- }))62- .toSorted((one, other) => byRole(one.role, other.role)),102+ roles: Array.dedupe(103+ Array.sort(104+ inArea.map(({ role }) => role),105+ bySentence106+ )107+ ),108 })),109 project: Array.headNonEmpty(inProject).project,110 }));111 67-const Area = ({ area }: { readonly area: AreaCredit }) => (68- <section className="border-rule grid gap-x-6 gap-y-2 border-t py-3 sm:grid-cols-[12rem_minmax(0,1fr)]">69- <h3 className="font-mono text-[0.8125rem] font-medium [overflow-wrap:anywhere]">70- {area.area}71- </h3>72- <dl className="grid grid-cols-[max-content_minmax(0,1fr)] gap-x-4 font-mono text-[0.8125rem] leading-6">73- {area.roles.map(({ count, role }) => (74- <div className="col-span-2 grid grid-cols-subgrid" key={role}>75- <dt className="text-muted-foreground">{role}</dt>76- <dd>77- {count} {count === 1 ? "landing" : "landings"}78- </dd>79- </div>80- ))}81- </dl>82- </section>112+/** The project's landings, where an area's credits are the trailers. */113+const landingsOf = (project: ProjectName) =>114+ projectSections(project).find(({ tab }) => tab === "landings")?.to ??115+ projectPath(project);116+117+const Project = ({ credit }: { readonly credit: ProjectCredit }) => (118+ <RowGroup119+ label={credit.project}120+ name={<AppLink to={projectPath(credit.project)}>{credit.project}</AppLink>}121+ under="bar"122+ >123+ {credit.areas.map(({ area, roles }) => (124+ <Row125+ data={{ "data-area": area, "data-project": credit.project }}126+ href={landingsOf(credit.project)}127+ id={`${credit.project}/${area}`}128+ key={area}129+ meta={130+ <MetaLine131+ parts={roles.map((role) => (132+ <MetaCode key={role}>{role}</MetaCode>133+ ))}134+ />135+ }136+ title={areaSentence(credit.project, area, roles)}137+ />138+ ))}139+ </RowGroup>140 );141 142 export const PersonView = ({143 credits,144 handle,145 }: {146 readonly credits: readonly CreditSummary[];147 readonly handle: Handle;91-}) => (92- <PageShell title={handle}>93- <p className="text-muted-foreground max-w-[70ch]">94- Credit, as the trailers on landed commits name {handle}: by project, by95- area, and by role, with how many landings name them in each.96- </p>97- {credits.length === 0 ? (98- <EmptyState title="No credited landings yet." />99- ) : (100- creditsByProject(credits).map(({ areas, project }) => (101- <section102- aria-labelledby={`project-${project}`}103- className="flex flex-col gap-3"104- key={project}105- >106- <h2 className={SECTION} id={`project-${project}`}>107- <a108- className="decoration-rule underline hover:decoration-current"109- href={projectPath(project)}110- >111- {project}112- </a>113- </h2>114- <div className="border-rule flex flex-col border-b">115- {areas.map((area) => (116- <Area area={area} key={area.area} />117- ))}118- </div>119- </section>120- ))121- )}122- </PageShell>123-);148+}) => {149+ const projects = creditsByProject(credits);150 151+ return (152+ <Workspace153+ meta={154+ projects.length === 0155+ ? undefined156+ : `Credited on landings in ${listed(projects.map(({ project }) => project))}.`157+ }158+ title={handle}159+ >160+ {projects.length === 0 ? (161+ <EmptyState162+ onward={<AppLink to="/">Open asks</AppLink>}163+ title="No credited landings yet."164+ />165+ ) : (166+ <div className="flex flex-col gap-6" data-credits="">167+ {projects.map((credit) => (168+ <Project credit={credit} key={credit.project} />169+ ))}170+ </div>171+ )}172+ <p className="text-ui text-muted-foreground">173+ Credit is the trailers on each landing; nothing here is a score.174+ </p>175+ </Workspace>176+ );177+};178+179 /** The page for an address whose last part cannot be a handle. */180 export const NoSuchPersonView = () => (181 <PageShell title="No such person">128- <EmptyState title="A handle is letters, digits and dashes, starting with a letter or digit, and this address names none." />182+ <EmptyState183+ onward={<AppLink to="/">Open asks</AppLink>}184+ title="A handle is letters, digits and dashes, starting with a letter or digit, and this address names none."185+ />186 </PageShell>187 );modified:apps/web/src/routes/people/$handle.tsx+8 added-3 removed
10 unmodified lines1112131415161516171819202116 unmodified lines38394041414243444546474849507 unmodified lines10 unmodified lines} from "../../features/people/person-page.tsx";import { pageHead } from "../../features/shared/head.ts";import { Reading, Unreachable } from "../../features/shared/pending.tsx";
// A person's page: their credit by project, area and role, read once by the// browser. An address whose last part cannot be a handle is a 404.// A person's page: the roles they hold in each project's landings, by area,// read once by the browser. An address whose last part cannot be a handle// is a 404.
const decodeHandle = Schema.decodeUnknownOption(Handle);
const Credits = ({ handle }: { readonly handle: Handle }) =>16 unmodified lines};
export const Route = createFileRoute("/people/$handle")({ component: PersonPage, head: ({ params }) => pageHead({ title: params.handle }), head: ({ params }) => pageHead({ description: `What ${params.handle} is credited for, by project and area.`, title: params.handle, }), // A 404 for an address that names no handle. loader: ({ params }) => Effect.runPromise( Effect.asVoid(7 unmodified linesmodified:apps/web/src/routes/agents.tsx+12 added-13 removed
1-import { agentSetup } from "@repo/agent-kit/agent-setup";1 import {2 createFileRoute,3 getRouteApi,4 useRouter,5 } from "@tanstack/react-router";6 7 import { commands } from "../features/agents/catalog.ts";9-import { AgentSetupView } from "../features/agents/setup-page.tsx";8+import { AgentsView } from "../features/agents/setup-page.tsx";9 import { pageHead } from "../features/shared/head.ts";11-import { PageShell } from "../features/shared/layout.tsx";10 13-// `/agents`: how each agent connects, drawn from `@repo/agent-kit`'s14-// `agentSetup` for this stage's platform and the web's own origin (the15-// router's: the request's on the server, the page's in the browser), so16-// the server's render and the browser's agree. `/agents.md` is the same11+// `/agents`: the reference an agent and the person running it read, drawn12+// from `@repo/agent-kit` for this stage's platform and the web's own origin13+// (the router's: the request's on the server, the page's in the browser),14+// so the server's render and the browser's agree. `/agents.md` is the same15 // text as Markdown.16 17 const root = getRouteApi("__root__");18 1 unmodified line20 const { platformUrl } = root.useLoaderData();21 const { origin } = useRouter();22 23 return (26- <PageShell title="Agents">27- <AgentSetupView28- channels={agentSetup({ commands, platformUrl, webUrl: origin })}29- />30- </PageShell>24+ <AgentsView commands={commands} platformUrl={platformUrl} webUrl={origin} />25 );26 };27 28 export const Route = createFileRoute("/agents")({29 component: AgentsPage,36- head: () => pageHead({ title: "Agents" }),30+ head: () =>31+ pageHead({32+ description:33+ "How an agent reaches the platform: the CLI's commands, the ways to connect, the endpoints, the limits and the refusals.",34+ title: "For agents",35+ }),36 });modified:apps/web/test/agents.test.tsx+217 added-43 removed
1 /**2- * The Agents page: how each agent connects, drawn from `@repo/agent-kit`'s3- * `agentSetup`, so the page has no text of its own for a snippet4- * (principle 4); `/agents.md` is the same channels as Markdown.2+ * The For agents page: a reference in five sections (Synopsis, Connect,3+ * Endpoints, Limits, Refusals), every word of it from `@repo/agent-kit`,4+ * so the page has no text of its own for a snippet, a command or an5+ * endpoint (principle 4); `/agents.md` is the same reference as Markdown.6 */7 import { describe, expect, it } from "@effect/vitest";7-import { agentSetup, agentSetupMarkdown } from "@repo/agent-kit/agent-setup";8+import {9+ agentEndpoints,10+ agentLimits,11+ agentSetup,12+ agentSetupMarkdown,13+} from "@repo/agent-kit/agent-setup";14+import { Brand } from "@repo/brand";15+import { groups } from "@repo/protocol/refusal";16 import { Effect } from "effect";9-import type { ReactElement } from "react";10-import { renderToStaticMarkup } from "react-dom/server";17 18 import { commands } from "../src/features/agents/catalog.ts";13-import { AgentSetupView } from "../src/features/agents/setup-page.tsx";19+import { AgentsView } from "../src/features/agents/setup-page.tsx";20 import { agentsMarkdownHandler } from "../src/routes/agents[.]md.ts";21+import { renderAt } from "./render.tsx";22 23 const platformUrl = "https://platform-test.example.workers.dev";24 25 const webUrl = "https://web-test.example.workers.dev";14 unmodified lines40 /&(?:#x27|amp|gt|lt|quot);/gu,41 (entity) => ENTITIES.get(entity) ?? entity42 );43 37-const markupOf = (element: ReactElement) => renderToStaticMarkup(element);38-44 /** What a reader sees: the markup without its tags, entities decoded. */40-const textOf = (element: ReactElement) =>41- decoded(markupOf(element).replaceAll(/<[^>]+>/gu, ""));45+const textOf = (html: string) => decoded(html.replaceAll(/<[^>]+>/gu, ""));46 43-/** The text of every `<code>` on the page, in order. */44-const codeOf = (element: ReactElement) =>45- [...markupOf(element).matchAll(/<code\b[^>]*>(?<body>.*?)<\/code>/gsu)].map(46- ({ groups }) => decoded(groups?.body ?? "")47+/** The text of every `<code>` in `html`, in order. */48+const codeOf = (html: string) =>49+ [...html.matchAll(/<code\b[^>]*>(?<body>.*?)<\/code>/gsu)].map(50+ ({ groups: found }) => textOf(found?.body ?? "")51 );52 49-describe("the Agents page", () => {50- const page = <AgentSetupView channels={channels} />;53+/** The page at `/agents`, inside a router. */54+const page = renderAt(55+ "/agents",56+ <AgentsView commands={commands} platformUrl={platformUrl} webUrl={webUrl} />57+);58 52- it("shows every snippet agentSetup gives, and no code of its own", () => {53- expect(codeOf(page)).toStrictEqual(54- channels.flatMap(({ snippets }) => snippets.map(({ text }) => text))55- );56- });59+/** The section whose id is `id`: its markup, from its tag to its close. */60+const sectionOf = (html: string, id: string) => {61+ const start = html.indexOf(`<section aria-labelledby="${id}"`);62+ const end = html.indexOf("</section>", start);63 58- it("heads each channel with its title and says when to use it", () => {59- const text = textOf(page);64+ expect(start).toBeGreaterThanOrEqual(0);65 61- for (const { snippets, title, useWhen } of channels) {62- expect(text).toContain(title);63- expect(text).toContain(useWhen);66+ return html.slice(start, end);67+};68 65- for (const { label } of snippets) {66- expect(text).toContain(label);69+const SECTIONS = [70+ ["synopsis", "Synopsis"],71+ ["connect", "Connect"],72+ ["endpoints", "Endpoints"],73+ ["limits", "Limits"],74+ ["refusals", "Refusals"],75+] as const;76+77+describe("the For agents page", () => {78+ it.effect("is titled For agents", () =>79+ Effect.gen(function* () {80+ expect(yield* page).toMatch(/<h1\b[^>]*>For agents<\/h1>/u);81+ })82+ );83+84+ it.effect(85+ "has its five sections in order, headed in the sans in sentence case",86+ () =>87+ Effect.gen(function* () {88+ const html = yield* page;89+90+ const headings = [91+ ...html.matchAll(92+ /<h2 (?<attributes>[^>]*)id="(?<id>[a-z]+)"[^>]*>(?<text>[^<]*)<\/h2>/gu93+ ),94+ ];95+96+ expect(97+ headings.map(({ groups: found }) => [found?.id, found?.text])98+ ).toStrictEqual(SECTIONS.map(([id, title]) => [id, title]));99+100+ for (const { groups: found } of headings) {101+ expect(found?.attributes).not.toContain("font-mono");102+ expect(found?.attributes).not.toContain("uppercase");103+ }104+105+ for (const { groups: found } of html.matchAll(106+ /<h(?<level>[1-4])\b[^>]*>(?<text>.*?)<\/h\k<level>>/gu107+ )) {108+ const words = textOf(found?.text ?? "");109+110+ expect(111+ words === words.toUpperCase() && /[A-Z]/u.test(words)112+ ).toBeFalsy();113+ }114+ })115+ );116+117+ it.effect("lists the five sections, as anchors, in its contents", () =>118+ Effect.gen(function* () {119+ const html = yield* page;120+ const inspector = html.slice(html.indexOf('data-facts="inspector"'));121+122+ const anchors = [123+ ...inspector.matchAll(/<a\b[^>]*href="#(?<id>[a-z]+)"/gu),124+ ].map(({ groups: found }) => found?.id);125+126+ expect(anchors).toStrictEqual(SECTIONS.map(([id]) => id));127+ })128+ );129+130+ it.effect(131+ "lands each anchor's heading below the sticky bars, not under them",132+ () =>133+ Effect.gen(function* () {134+ const html = yield* page;135+136+ for (const [id] of SECTIONS) {137+ // The element the fragment scrolls to is the one with the id: its138+ // own scroll margin is the one the browser reads.139+ const target = new RegExp(140+ `<[a-z0-9]+\\b[^>]*\\bid="${id}"[^>]*>`,141+ "u"142+ )143+ .exec(html)144+ ?.at(0);145+146+ expect(target, `#${id}`).toMatch(/\bscroll-mt-\d+\b/u);147+ }148+ })149+ );150+151+ it.effect("gives every command of the CLI a synopsis line, in mono", () =>152+ Effect.gen(function* () {153+ const synopsis = codeOf(sectionOf(yield* page, "synopsis"));154+155+ expect(synopsis).toHaveLength(commands.length);156+157+ for (const [index, command] of commands.entries()) {158+ expect(159+ synopsis[index]?.startsWith(`${Brand.cli} ${command.path.join(" ")}`)160+ ).toBeTruthy();161 }68- }69- });162+ })163+ );164 71- it("gives every snippet a button that copies it", () => {72- const buttons = markupOf(page).match(73- /<button\b[^>]*>.*?Copy.*?<\/button>/gu74- );165+ it.effect(166+ "shows every snippet agentSetup gives under Connect, and no code of its own",167+ () =>168+ Effect.gen(function* () {169+ const connect = sectionOf(yield* page, "connect");170 76- expect(buttons).toHaveLength(77- channels.reduce((count, { snippets }) => count + snippets.length, 0)78- );79- });171+ expect(codeOf(connect)).toStrictEqual(172+ channels.flatMap(({ snippets }) => snippets.map(({ text }) => text))173+ );174 81- it("links the same channels as Markdown", () => {82- expect(markupOf(page)).toMatch(/<a\b[^>]*href="\/agents\.md"[^>]*>/u);83- });175+ const text = textOf(connect);176+177+ for (const { snippets, title, useWhen } of channels) {178+ expect(text).toContain(title);179+ expect(text).toContain(useWhen);180+181+ for (const { label } of snippets) {182+ expect(text).toContain(label);183+ }184+ }185+ })186+ );187+188+ it.effect("gives every snippet a button that copies it", () =>189+ Effect.gen(function* () {190+ const buttons = sectionOf(yield* page, "connect").match(191+ /<button\b[^>]*>.*?Copy.*?<\/button>/gu192+ );193+194+ expect(buttons).toHaveLength(195+ channels.reduce((count, { snippets }) => count + snippets.length, 0)196+ );197+ })198+ );199+200+ it.effect("names every endpoint and limit agent-kit gives", () =>201+ Effect.gen(function* () {202+ const html = yield* page;203+ const endpoints = sectionOf(html, "endpoints");204+205+ expect(codeOf(endpoints)).toStrictEqual(206+ agentEndpoints({ platformUrl, webUrl }).map(({ url }) => url)207+ );208+209+ for (const { readable, url, what } of agentEndpoints({210+ platformUrl,211+ webUrl,212+ })) {213+ expect(textOf(endpoints)).toContain(what);214+ expect(endpoints.includes(`href="${url}"`)).toBe(readable);215+ }216+217+ const limits = textOf(sectionOf(html, "limits"));218+219+ for (const { limit, value } of agentLimits()) {220+ expect(limits).toContain(limit);221+ expect(limits).toContain(value);222+ }223+ })224+ );225+226+ it.effect(227+ "names every refusal of the union, each linked to its row in /llms-full.txt",228+ () =>229+ Effect.gen(function* () {230+ const refusals = sectionOf(yield* page, "refusals");231+232+ const tags = groups.flatMap(({ members }) =>233+ members.map(({ identifier }) => identifier)234+ );235+236+ expect(codeOf(refusals)).toStrictEqual(tags);237+238+ for (const { members, name } of groups) {239+ expect(textOf(refusals)).toContain(name);240+241+ for (const { identifier } of members) {242+ expect(refusals).toMatch(243+ new RegExp(244+ `<a\\b[^>]*href="/llms-full\\.txt#:~:text=%60${identifier}%60[^"]*"[^>]*><code\\b[^>]*>${identifier}</code>`,245+ "u"246+ )247+ );248+ }249+ }250+ })251+ );252+253+ it.effect("links the same reference as Markdown", () =>254+ Effect.gen(function* () {255+ expect(yield* page).toMatch(/<a\b[^>]*href="\/agents\.md"[^>]*>/u);256+ })257+ );258 });259 260 describe("/agents.md", () => {87- it.effect("answers the channels as Markdown for the web's own origin", () =>261+ it.effect("answers the reference as Markdown for the web's own origin", () =>262 Effect.gen(function* () {263 const response = yield* Effect.promise(() =>264 agentsMarkdownHandler(platformUrl)({265 request: new Request(`${webUrl}/agents.md`),13 unmodified linesmodified:apps/web/test/people.test.tsx+128 added-58 removed
1 /**2- * A person's page, rendered to HTML with `react-dom/server` from fixtures3- * decoded with the protocol's own schemas: their credit by project, area4- * and role, counted, and never ranked.2+ * A person's page, rendered inside a router from fixtures decoded with the3+ * protocol's own schemas: their credit by project and area, each area one4+ * sentence of the roles they hold there, and no number anywhere (the No5+ * Score Rule): the counts the read carries are never drawn.6 */7 import { describe, expect, it } from "@effect/vitest";8 import { CreditSummary } from "@repo/protocol/domain/record";9 import { Handle } from "@repo/protocol/ids";9-import { Schema } from "effect";10+import { Effect, Schema } from "effect";11 import type { ReactElement } from "react";11-import { renderToStaticMarkup } from "react-dom/server";12 13+import {14+ areaSentence,15+ PersonView,13-import { PersonView } from "../src/features/people/person-page.tsx";16+} from "../src/features/people/person-page.tsx";17+import { renderAt } from "./render.tsx";18 import { reachingTransport } from "./transport.ts";19 16-const markupOf = (element: ReactElement) => renderToStaticMarkup(element);17-18-/** What a reader sees: the markup without its tags, entities decoded. */19-const textOf = (element: ReactElement) =>20- markupOf(element)21- .replaceAll(/<[^>]+>/gu, "")22- .replaceAll("'", "'")23- .replaceAll("&", "&");24-20 const handle = Schema.decodeSync(Handle)("ines-v");21 22 const credits = Schema.decodeSync(Schema.Array(CreditSummary))([23 { area: "core", count: 4, project: "datekit", role: "Signed-off-by" },24 { area: "docs", count: 1, project: "datekit", role: "Signed-off-by" },25 { area: "format", count: 1, project: "burrow", role: "Finished-by" },26 { area: "core", count: 2, project: "datekit", role: "Asked-by" },27+ { area: ".", count: 7, project: "burrow", role: "Decided-by" },28+ { area: "core", count: 12, project: "datekit", role: "Signed-off-by" },29 ]);30 34-const page = <PersonView credits={credits} handle={handle} />;31+const markupOf = (element: ReactElement) =>32+ renderAt(`/people/${handle}`, element);33 36-/** Each group heading's text, top to bottom: projects as `h2`, areas as `h3`. */37-const headingsOf = (element: ReactElement) =>38- [39- ...markupOf(element).matchAll(40- /<(?<level>h[23])\b[^>]*>(?<text>.*?)<\/h[23]>/gu41- ),42- ].map(43- ({ groups }) =>44- `${groups?.level}:${groups?.text?.replaceAll(/<[^>]+>/gu, "")}`34+/** What a reader sees: the markup without its tags, entities decoded. */35+const textOf = (html: string) =>36+ html37+ .replaceAll(/<[^>]+>/gu, "")38+ .replaceAll("'", "'")39+ .replaceAll("&", "&");40+41+/** The credits: every project's group, from the first to the last. */42+const creditsOf = (html: string) => {43+ const start = html.indexOf('data-credits=""');44+ const end = html.indexOf("</main>", start);45+46+ expect(start).toBeGreaterThanOrEqual(0);47+48+ return html.slice(start, end);49+};50+51+const page = markupOf(<PersonView credits={credits} handle={handle} />);52+53+describe("a person's page", () => {54+ it.effect("is titled with the handle, and has no inspector", () =>55+ Effect.gen(function* () {56+ const html = yield* page;57+58+ expect(html).toMatch(/<h1\b[^>]*>ines-v<\/h1>/u);59+ expect(html).not.toContain('data-facts="inspector"');60+ expect(html).not.toContain("<img");61+ })62 );63 47-describe(PersonView, () => {48- it("groups credit by project, then by area", () => {49- expect(headingsOf(page)).toStrictEqual([50- "h2:burrow",51- "h3:format",52- "h2:datekit",53- "h3:core",54- "h3:docs",55- ]);56- });64+ it.effect("groups credit by project, each area one sentence of roles", () =>65+ Effect.gen(function* () {66+ const html = creditsOf(yield* page);67 58- it("lists the roles in each area with their counts, in trailer order", () => {59- const text = textOf(page);60- const core = text.slice(text.indexOf("core"), text.indexOf("docs"));68+ const groups = [...html.matchAll(/<h2\b[^>]*>(?<name>.*?)<\/h2>/gu)].map(69+ ({ groups: found }) => textOf(found?.name ?? "")70+ );71 62- expect(core.indexOf("Asked-by")).toBeGreaterThanOrEqual(0);63- expect(core.indexOf("Signed-off-by")).toBeGreaterThan(64- core.indexOf("Asked-by")65- );66- expect(core).toMatch(/Asked-by\D*2 landings/u);67- expect(core).toMatch(/Signed-off-by\D*4 landings/u);68- expect(text).toMatch(/Finished-by\D*1 landing(?!s)/u);69- });72+ expect(groups).toStrictEqual(["burrow", "datekit"]);73 71- it("links each project to its page", () => {72- expect(markupOf(page)).toContain('href="/datekit"');73- expect(markupOf(page)).toContain('href="/burrow"');74- });74+ const sentences = [75+ ...html.matchAll(/data-area="(?<area>[^"]*)"[^>]*>/gu),76+ ].map(({ groups: found }) => found?.area);77 76- it("never reads as a score", () => {77- const markup = markupOf(page).toLowerCase();78+ expect(sentences).toStrictEqual([".", "format", "core", "docs"]);79 80+ const text = textOf(html);81+82+ for (const sentence of [83+ "Decided in the whole project",84+ "Finished in burrow/format",85+ "Answered and asked in datekit/core",86+ "Answered in datekit/docs",87+ ]) {88+ expect(text).toContain(sentence);89+ }90+ })91+ );92+93+ it.effect("links each project, and each area to the project's landings", () =>94+ Effect.gen(function* () {95+ const html = creditsOf(yield* page);96+97+ for (const project of ["datekit", "burrow"]) {98+ expect(html).toContain(`href="/${project}"`);99+ expect(html).toContain(`href="/${project}/commits/main"`);100+ }101+ })102+ );103+104+ it.effect("draws no number in its credits, whatever the read counts", () =>105+ Effect.gen(function* () {106+ const html = yield* page;107+108+ expect(textOf(creditsOf(html))).not.toMatch(/\d/u);109+ expect(html).not.toMatch(110+ /\b(?:landings?|credits?)\b\s*\d|\d+\s*(?:landings?|credits?)\b/iu111+ );112+ })113+ );114+115+ it.effect("says credit is the trailers, and nothing on it is a score", () =>116+ Effect.gen(function* () {117+ const text = textOf(yield* page);118+119+ expect(text).toContain(120+ "Credit is the trailers on each landing; nothing here is a score."121+ );122+79- for (const word of ["score", "rank", "points", "reputation"]) {80- expect(markup).not.toContain(word);81- }123+ for (const word of ["rank", "points", "reputation"]) {124+ expect(text.toLowerCase()).not.toContain(word);125+ }126+ })127+ );128+129+ it.effect(130+ "says a person with no credit has none yet, with a way onward",131+ () =>132+ Effect.gen(function* () {133+ const html = yield* markupOf(134+ <PersonView credits={[]} handle={handle} />135+ );136+137+ expect(textOf(html)).toContain("No credited landings yet.");138+ expect(html).toContain('href="/"');139+ })140+ );141+});142+143+describe("an area's sentence", () => {144+ it("names the roles in words, the answer first, then in trailer order", () => {145+ expect(146+ areaSentence("datekit", "src", [147+ "Asked-by",148+ "Signed-off-by",149+ "Decided-by",150+ ])151+ ).toBe("Answered, asked and decided in datekit/src");152 });153 84- it("says a person with no credit has none yet", () => {85- expect(textOf(<PersonView credits={[]} handle={handle} />)).toContain(86- "No credited landings yet"154+ it("reads the whole project for an area of '.'", () => {155+ expect(areaSentence("datekit", ".", ["Mentored-by"])).toBe(156+ "Mentored in the whole project"157 );158 });159 });160 11 unmodified linesmodified:packages/agent-kit/src/agent-setup.ts+206 added-10 removed
1 /**2- * How an agent connects to the platform, one channel at a time: remote MCP3- * for a client that signs in over OAuth, MCP over stdio through the CLI,4- * the CLI itself, a sentence any agent can be handed, and the skills. Each5- * channel says when to use it and gives the snippets to copy. The web draws2+ * How an agent reaches the platform, set as a reference: a synopsis of the3+ * CLI's commands; the channels it connects through (remote MCP for a client4+ * that signs in over OAuth, MCP over stdio through the CLI, the CLI itself,5+ * a sentence any agent can be handed, and the skills), each saying when to6+ * use it and giving the snippets to copy; the endpoints an agent reads; the7+ * limits a project's policy sets by default; and the refusals. The web draws8 * it as `/agents` and serves `agentSetupMarkdown` as `/agents.md`.9 *10 * Pure: the hosts hand in the CLI's commands as this package's one list11 * holds them and the two hosts' URLs. Each client's MCP JSON comes from6 unmodified lines18 * entry being its `url`; VS Code reads `.vscode/mcp.json`'s `servers`, a19 * remote entry being `{type: "http", url}`.20 */21 import { Brand } from "@repo/brand";22+import { PolicyInput } from "@repo/protocol/domain/policy";23+import { groups } from "@repo/protocol/refusal";20-import { Array as Arr } from "effect";24+import { Array as Arr, Schema } from "effect";25 26 import type { CommandDoc } from "./command-doc.ts";27 import { mcpServersFor } from "./platform.ts";24-import { page, printJson } from "./text.ts";28+import { span } from "./sections.ts";29+import { code, listed, page, printJson, table } from "./text.ts";30 31 export interface SetupSnippet {32 /** What the snippet is, or where it goes: a client, a file. */33 readonly label: string;119 unmodified lines153 anyAgent(input),154 skills(input),155 ];156 157+// --- Synopsis -------------------------------------------------------------------158+159+/** One command as a synopsis gives it: how it is typed, and what it does. */160+export interface SynopsisLine {161+ /** The CLI's name, its words, its arguments, then each flag it takes in brackets. */162+ readonly usage: string;163+ readonly summary: string;164+}165+166+/** Every command, one line each, in the catalog's order. */167+export const synopsis = (168+ commands: readonly CommandDoc[]169+): readonly SynopsisLine[] =>170+ commands.map(({ flags, path, positional, summary }) => ({171+ summary,172+ usage: [173+ Brand.cli,174+ ...path,175+ ...positional.map((name) => `<${name}>`),176+ ...flags177+ .filter((flag) => !positional.includes(flag.replace(/^--/u, "")))178+ .map((flag) => `[${flag}]`),179+ ].join(" "),180+ }));181+182+// --- Endpoints ------------------------------------------------------------------183+184+/** One address an agent reads or calls. */185+export interface Endpoint {186+ /** The address whole; `<…>` marks a part the reader fills in. */187+ readonly url: string;188+ readonly what: string;189+ /** A plain GET in a browser shows it. */190+ readonly readable: boolean;191+}192+193+/** Every address an agent reads, the web's first, then the platform's. */194+export const agentEndpoints = ({195+ platformUrl,196+ webUrl,197+}: Pick<SetupInput, "platformUrl" | "webUrl">): readonly Endpoint[] => [198+ {199+ readable: true,200+ url: `${webUrl}/llms.txt`,201+ what: "The index: how to take an ask, every command and every project.",202+ },203+ {204+ readable: true,205+ url: `${webUrl}/llms-full.txt`,206+ what: "The rest in one file: every refusal, git here, how a landing happens, the events a watcher hears.",207+ },208+ {209+ readable: false,210+ url: `${webUrl}/<project>/llms.txt`,211+ what: "One project: its posture, how to clone it and its open asks.",212+ },213+ {214+ readable: false,215+ url: `${webUrl}/<project>/asks/<ask>.md`,216+ what: "One ask's brief as Markdown.",217+ },218+ {219+ readable: true,220+ url: `${webUrl}/agents.md`,221+ what: "This reference as Markdown.",222+ },223+ {224+ readable: true,225+ url: `${webUrl}/.well-known/mcp.json`,226+ what: "The MCP server's card: its endpoint, transport and protocol, and how to sign in.",227+ },228+ {229+ readable: true,230+ url: `${webUrl}/.well-known/agent-skills/index.json`,231+ what: "Every project's contribute skill, with its digest.",232+ },233+ {234+ readable: false,235+ url: `${platformUrl}/mcp`,236+ what: "MCP over streamable HTTP, signed in over OAuth.",237+ },238+ {239+ readable: false,240+ url: `${platformUrl}/<repo>.git`,241+ what: "Git over smart HTTP: clone a project, push an answer to your fork.",242+ },243+];244+245+// --- Limits ---------------------------------------------------------------------246+247+/** One limit and its value, as a person says them. */248+export interface Limit {249+ readonly limit: string;250+ readonly value: string;251+}252+253+/** What a policy that sets nothing takes: the defaults its schema fills in. */254+const policyDefaults = () =>255+ Schema.decodeSync(256+ Schema.Struct({257+ budget: PolicyInput.fields.budget,258+ caps: PolicyInput.fields.caps,259+ claims: PolicyInput.fields.claims,260+ })261+ )({});262+263+/**264+ * The limits an agent meets: each project's policy may set its own, so the265+ * values are the defaults; the platform's own rate limits stand in front.266+ */267+export const agentLimits = (): readonly Limit[] => {268+ const { budget, caps, claims } = policyDefaults();269+270+ return [271+ {272+ limit: "Claims one person holds at once, in a project",273+ value: `${caps.claimsPerPerson} by default`,274+ },275+ {276+ limit: "Open proposals one person holds, in a project",277+ value: `${caps.proposalsPerPerson} by default; 0 turns proposals off`,278+ },279+ {280+ limit: "A claim without a push",281+ value: `Warned after ${span(claims.warnAfterMs)}, lapses after ${span(claims.lapseAfterMs)}, by default`,282+ },283+ {284+ limit: "Decisions a decider takes a day",285+ value: `${budget.decisionsPerDay} by default`,286+ },287+ {288+ limit: "A decision nobody takes",289+ value: `${span(budget.expireDays * 86_400_000)} by default, then it takes its default`,290+ },291+ {292+ limit: "Claims, proposals and drafts across the platform, per person",293+ value:294+ "A set number a minute; past it, CapReached says when to try again",295+ },296+ ];297+};298+299+// --- Markdown -------------------------------------------------------------------300+301 const snippetLines = ({ label, language, text }: SetupSnippet) => [302 `${label}:`,303 "",304 `\`\`\`${language}`,2 unmodified lines307 "",308 ];309 310 const channelLines = ({ snippets, title, useWhen }: SetupChannel) => [162- `## ${title}`,311+ `### ${title}`,312 "",313 `Use this when ${useWhen.charAt(0).toLowerCase()}${useWhen.slice(1)}`,314 "",315 ...snippets.flatMap(snippetLines),316 ];317 318+const synopsisLines = (commands: readonly CommandDoc[]) => [319+ "## Synopsis",320+ "",321+ ...synopsis(commands).map(322+ ({ summary, usage }) => `- ${code(usage)}: ${summary}`323+ ),324+ "",325+];326+327+const endpointLines = (input: SetupInput) => [328+ "## Endpoints",329+ "",330+ ...table(331+ ["Address", "What it is"],332+ agentEndpoints(input).map(({ url, what }) => [code(url), what])333+ ),334+ "",335+];336+337+const limitLines = () => [338+ "## Limits",339+ "",340+ ...table(341+ ["Limit", "Value"],342+ agentLimits().map(({ limit, value }) => [limit, value])343+ ),344+ "",345+];346+347+const refusalLines = ({ webUrl }: SetupInput) => [348+ "## Refusals",349+ "",350+ `Every refusal the platform gives, by group. Each one's row in ${webUrl}/llms-full.txt says whether retrying helps, its \`next\` and what to do.`,351+ "",352+ ...groups.map(353+ ({ members, name }) =>354+ `- ${name}: ${listed(members.map((member) => code(member.identifier)))}`355+ ),356+ "",357+];358+169-/** The same channels as one Markdown document: `/agents.md`. */359+/** The whole reference as one Markdown document: `/agents.md`. */360 export const agentSetupMarkdown = (input: SetupInput) =>361 page([172- "# Agents",362+ "# For agents",363 "",174- `> How an agent connects to ${Brand.name}: over MCP, through the CLI, with a sentence to paste, or as skills. Each section says when to use it.`,364+ `> How an agent reaches ${Brand.name}: the CLI's commands, the ways to connect (over MCP, through the CLI, with a sentence to paste, or as skills), the endpoints, the limits and the refusals.`,365 "",366+ ...synopsisLines(input.commands),367+ "## Connect",368+ "",369 ...agentSetup(input).flatMap(channelLines),370+ ...endpointLines(input),371+ ...limitLines(),372+ ...refusalLines(input),373 ]);modified:packages/agent-kit/test/golden/agent-setup.txt+59 added-7 removed
1-# Agents1+# For agents2 3-> How an agent connects to __NAME__: over MCP, through the CLI, with a sentence to paste, or as skills. Each section says when to use it.3+> How an agent reaches __NAME__: the CLI's commands, the ways to connect (over MCP, through the CLI, with a sentence to paste, or as skills), the endpoints, the limits and the refusals.4 5-## Remote MCP5+## Synopsis6 7+- `__CLI__ asks [--project] [--json]`: List a project's open asks.8+- `__CLI__ claim <ask> [--project] [--json] [--dry-run]`: Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim.9+- `__CLI__ vouch [--project] [--handle] [--verdict] [--note] [--json] [--yes] [--dry-run]`: Vouch for a person, or denounce them, by landing a line in the project's vouch file.10+- `__CLI__ check [--ask] [--project] [--base] [--json]`: Run the gate's checks on your answer locally, before you push.11+- `__CLI__ login [--url] [--json]`: Sign in to a platform.12+- `__CLI__ mcp`: Serve the platform's tools over MCP on stdio.13+14+## Connect15+16+### Remote MCP17+18 Use this when your client signs in over OAuth: it opens a browser once, you sign in with your account on __NAME__, and it calls the platform's tools at https://platform-test.example.workers.dev/mcp.19 20 Claude Code, then /mcp in a session to sign in:21 25 unmodified lines47 }48 }49 ```50 40-## MCP over stdio51+### MCP over stdio52 53 Use this when your client starts its MCP servers as local commands, or cannot sign in over OAuth: the CLI serves the same tools over stdio, with the token the CLI stored when you signed in.54 55 The server's command, once you have signed in with the CLI:1 unmodified line57 ```sh58 __CLI__ mcp59 ```60 50-## The CLI61+### The CLI62 63 Use this when your agent has a shell: it finds and claims asks, checks an answer before it pushes and reads verdicts with the CLI, and pushes with git.64 65 Install:7 unmodified lines73 ```sh74 __CLI__ login --url https://platform-test.example.workers.dev75 ```76 66-## Text for any agent77+### Text for any agent78 79 Use this when your agent can fetch a URL but has no MCP client or CLI set up: hand it the platform's index and it reads the rest as Markdown.80 81 Paste into the agent's prompt:1 unmodified line83 ```text84 Use https://web-test.example.workers.dev/llms.txt as the source of truth for __NAME__: it says how to take an ask and lists every command and project. Each ask reads as Markdown at https://web-test.example.workers.dev/<project>/asks/<ask>.md.85 ```86 76-## Skills87+### Skills88 89 Use this when your agent loads skills: each project's contribute skill is listed, with its digest, at https://web-test.example.workers.dev/.well-known/agent-skills/index.json.90 91 Add every project's contribute skill:92 93 ```sh94 npx skills add https://web-test.example.workers.dev95 ```96+97+## Endpoints98+99+| Address | What it is |100+| --- | --- |101+| `https://web-test.example.workers.dev/llms.txt` | The index: how to take an ask, every command and every project. |102+| `https://web-test.example.workers.dev/llms-full.txt` | The rest in one file: every refusal, git here, how a landing happens, the events a watcher hears. |103+| `https://web-test.example.workers.dev/<project>/llms.txt` | One project: its posture, how to clone it and its open asks. |104+| `https://web-test.example.workers.dev/<project>/asks/<ask>.md` | One ask's brief as Markdown. |105+| `https://web-test.example.workers.dev/agents.md` | This reference as Markdown. |106+| `https://web-test.example.workers.dev/.well-known/mcp.json` | The MCP server's card: its endpoint, transport and protocol, and how to sign in. |107+| `https://web-test.example.workers.dev/.well-known/agent-skills/index.json` | Every project's contribute skill, with its digest. |108+| `https://platform-test.example.workers.dev/mcp` | MCP over streamable HTTP, signed in over OAuth. |109+| `https://platform-test.example.workers.dev/<repo>.git` | Git over smart HTTP: clone a project, push an answer to your fork. |110+111+## Limits112+113+| Limit | Value |114+| --- | --- |115+| Claims one person holds at once, in a project | 3 by default |116+| Open proposals one person holds, in a project | 2 by default; 0 turns proposals off |117+| A claim without a push | Warned after 2 hours, lapses after 1 day, by default |118+| Decisions a decider takes a day | 5 by default |119+| A decision nobody takes | 2 weeks by default, then it takes its default |120+| Claims, proposals and drafts across the platform, per person | A set number a minute; past it, CapReached says when to try again |121+122+## Refusals123+124+Every refusal the platform gives, by group. Each one's row in https://web-test.example.workers.dev/llms-full.txt says whether retrying helps, its `next` and what to do.125+126+- Push and claim: `NotClaimed`, `ClaimLapsed`, `NotVouched`, `CapReached`, `AskFull`, `NoAsk`, `RepoBusy`, `DirectPush`, `AskBlocked` and `Denounced`127+- Shape: `OutOfScope`, `TouchedJudge`, `Weakened`, `PrivatePathInPublicTree` and `ReachedInternals`128+- Merge: `StaleBase` and `StaleLayer`129+- Checks: `ChecksFailed`, `HeldBackFailed` and `AttemptsExhausted`130+- Never counted against the answerer: `Flake` and `VerifierBlocked`131+- At ask open: `NotRedFirst`, `WeakCheck` and `IncompleteBrief`132+- Maintainers only: `LayerContentInPublicTree`, `SecretInOutput` and `UnstatedRequirement`133+- Decision: `PostureChange`, `NotDecider`, `DecisionClosed`, `ProposalClosed` and `DraftInProgress`134+- Lookup: `UnknownProject`, `UnknownAsk`, `UnknownCommit`, `UnknownDecision`, `UnknownPath`, `UnknownRevision` and `UnknownProposal`135+- Setup: `ProjectExists` and `ImportFailed`136+- Env: `UnknownEnvItem`, `NotSensitive` and `ValueTooShort`modified:packages/agent-kit/test/agent-setup.test.ts+107 added-1 removed
6 unmodified lines7 */8 import { NodeServices } from "@effect/platform-node";9 import { describe, expect, it } from "@effect/vitest";10 import { Brand } from "@repo/brand";11+import { groups } from "@repo/protocol/refusal";12 import { Array as Arr, Effect, Option, Schema } from "effect";13 13-import { agentSetup, agentSetupMarkdown } from "../src/agent-setup.ts";14+import {15+ agentEndpoints,16+ agentLimits,17+ agentSetup,18+ agentSetupMarkdown,19+ synopsis,20+} from "../src/agent-setup.ts";21 import type { SetupChannel } from "../src/agent-setup.ts";22 import type { CommandDoc } from "../src/command-doc.ts";23 import { claudePlugin } from "../src/platform.ts";24 import { commands as someCommands } from "./fixtures.ts";156 unmodified lines181 }182 }183 });184 });185+186+describe("the Agents page's reference sections", () => {187+ it("gives every command one synopsis line, as typed, with its summary", () => {188+ const lines = synopsis(commands);189+190+ expect(lines.map(({ summary }) => summary)).toStrictEqual(191+ commands.map(({ summary }) => summary)192+ );193+194+ for (const [index, command] of commands.entries()) {195+ const line = lines[index]?.usage ?? "";196+197+ expect(198+ line.startsWith(`${Brand.cli} ${command.path.join(" ")}`)199+ ).toBeTruthy();200+201+ for (const name of command.positional) {202+ expect(line).toContain(`<${name}>`);203+ }204+ }205+206+ expect(synopsis([login])).toStrictEqual([207+ {208+ summary: login.summary,209+ usage: `${Brand.cli} login [--url] [--json]`,210+ },211+ ]);212+ });213+214+ it("names every endpoint an agent reads, on the host that serves it", () => {215+ const endpoints = agentEndpoints({ platformUrl, webUrl });216+217+ expect(endpoints.map(({ url }) => url)).toStrictEqual([218+ `${webUrl}/llms.txt`,219+ `${webUrl}/llms-full.txt`,220+ `${webUrl}/<project>/llms.txt`,221+ `${webUrl}/<project>/asks/<ask>.md`,222+ `${webUrl}/agents.md`,223+ `${webUrl}/.well-known/mcp.json`,224+ `${webUrl}/.well-known/agent-skills/index.json`,225+ `${platformUrl}/mcp`,226+ `${platformUrl}/<repo>.git`,227+ ]);228+229+ for (const { what } of endpoints) {230+ expect(what).not.toBe("");231+ }232+233+ expect(234+ endpoints.filter(({ readable }) => readable).map(({ url }) => url)235+ ).toStrictEqual([236+ `${webUrl}/llms.txt`,237+ `${webUrl}/llms-full.txt`,238+ `${webUrl}/agents.md`,239+ `${webUrl}/.well-known/mcp.json`,240+ `${webUrl}/.well-known/agent-skills/index.json`,241+ ]);242+ });243+244+ it("states the limits a policy sets by default, as a person says them", () => {245+ const values = agentLimits().map(({ value }) => value);246+247+ expect(values).toStrictEqual([248+ "3 by default",249+ "2 by default; 0 turns proposals off",250+ "Warned after 2 hours, lapses after 1 day, by default",251+ "5 by default",252+ "2 weeks by default, then it takes its default",253+ "A set number a minute; past it, CapReached says when to try again",254+ ]);255+256+ for (const { limit } of agentLimits()) {257+ expect(limit).not.toBe("");258+ }259+ });260+261+ it("writes the reference sections into the Markdown, in the page's order", () => {262+ const text = agentSetupMarkdown({ commands, platformUrl, webUrl });263+ const at = (heading: string) => text.indexOf(`\n## ${heading}\n`);264+265+ const order = ["Synopsis", "Connect", "Endpoints", "Limits", "Refusals"];266+267+ for (const heading of order) {268+ expect(at(heading)).toBeGreaterThan(0);269+ }270+271+ expect(order.map(at)).toStrictEqual(272+ order.map(at).toSorted((a, b) => a - b)273+ );274+275+ for (const group of groups) {276+ for (const member of group.members) {277+ expect(text).toContain(`\`${member.identifier}\``);278+ }279+ }280+281+ expect(text).toContain(`${webUrl}/llms-full.txt`);282+ });283+});