Merge branch 'build/907-project-people-page'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 10c8b54, 8d0b858 · Browse files · 5 files·+1157 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+1157 added−10 removed
- tests:+536 added−0 removed
- other:+621 added−10 removed
Provenance
- Commit
3c231ba- Tree
697292f- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
10c8b54- Parent 2
8d0b858
5 files changed+1157 added−10 removed
added:apps/web/e2e/people.e2e.ts+79 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879/** * The deployed people page, as a browser shows it: who decides which paths * and the commit the config is read at, saved as `e2e/out/people.png` for * the shot list. * * It runs only against `WEB_URL` (a stage's web origin) and is skipped * without it. `WEB_PROJECT` picks the project (datekit, which the seed puts * on every stage, unless given). It only reads. */import { expect, test } from "@playwright/test";import { Config, Effect, Option } from "effect";
/** What the check reads of its env: where the web lives, and which project to look at. */const settings = Effect.runSync( Effect.gen(function* () { return { project: yield* Config.NonEmptyString("WEB_PROJECT").pipe( Config.withDefault("datekit") ), web: Option.map( yield* Config.option(Config.NonEmptyString("WEB_URL")), (url) => url.replace(/\/+$/u, "") ), }; }));
const { project } = settings;
/** Where the screenshot goes: `e2e/out/people.png`. */const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);
/** What every page that could not reach the platform says instead of its content. */const UNREACHABLE = "The platform did not answer";
test.describe("the deployed people page", () => { test.skip( Option.isNone(settings.web), "WEB_URL is not set: point it at a deployed web's origin to run this check" );
test(`${project}'s people page shows its deciders and the commit they are read at`, ({ page: browser, }) => Effect.runPromise( Effect.gen(function* () { const web = Option.getOrElse(settings.web, () => "");
const response = yield* Effect.promise(() => browser.goto(`${web}/${project}/people`) );
expect(response?.status()).toBe(200);
// The deciders table: its header and at least the whole-repo glob's row. yield* Effect.promise(() => expect( browser.getByRole("columnheader", { name: "Deciders" }) ).toBeVisible() );
yield* Effect.promise(() => expect(browser.locator('tr[data-paths="**"]')).toBeVisible() );
yield* Effect.promise(() => expect(browser.getByText(/^As of [0-9a-f]{7}/u).first()).toBeVisible() );
yield* Effect.promise(() => expect(browser.getByText(UNREACHABLE)).toHaveCount(0) );
yield* Effect.promise(() => browser.screenshot({ fullPage: true, path: `${out}people.png` }) ); }) ));});added:apps/web/src/client/policy.ts+21 added
123456789101112131415161718192021/** * A project's evaluated policy (the people page's read, the data pattern in * `src/surfaces.ts`): `projectPolicy` over the browser's `/rpc`, keyed by * the project's policy, so a landing (`Landed`, which `watch.ts` turns into * `keys.policy`) makes it read again. It is keyed by the project too: when * the watch's stream fails at connect, its poll changes only the project's * keys. The people page seeds it with what its loader read on the server. */import type { ProjectName } from "@repo/protocol/ids";import { Atom } from "effect/reactivity";
import { ContractsClient } from "../surfaces.ts";import { keys } from "./keys.ts";
export const policyAtom = Atom.family((project: ProjectName) => ContractsClient.query( "projectPolicy", { project }, { reactivityKeys: [...keys.policy(project), ...keys.project(project)] } ));added:apps/web/src/features/project-people/people-view.tsx+406 added
1+/**2+ * A project's people and permissions, as its config folder states them at3+ * the landed commit: who decides which paths, the vouch rule and the vouch4+ * file's lines, each layer's audience, readers and writers (from the5+ * ledger, so the page works without the visibility cartridge), the caps,6+ * budget and timings, and whether landings disclose agents. Each section7+ * links the file it comes from at that commit.8+ *9+ * Props in, markup out: the route reads `projectPolicy` and `ledger`10+ * (`src/client/{policy,ledger}.ts`) and hands them here. The page is11+ * read-only: the one way to change any of it is to land a change to the12+ * config folder, and it says so with the commands.13+ */14+import { Brand } from "@repo/brand";15+import type { PublicPolicy } from "@repo/protocol/domain/policy";16+import type {17+ Disclosure,18+ Layer,19+ Ledger,20+ Members,21+} from "@repo/protocol/domain/visibility";22+import type { Handle, ProjectName } from "@repo/protocol/ids";23+import { Option } from "effect";24+import { Fragment } from "react";25+import type { ReactNode } from "react";26+27+import {28+ Table,29+ TableBody,30+ TableCell,31+ TableHead,32+ TableHeader,33+ TableRow,34+} from "@/components/ui/table";35+36+import { CODE, Field, Fields, LINK, Region } from "../ask/fields.tsx";37+import { ledgerPath } from "../ledger/path.ts";38+import { ProjectNav } from "../project/project-nav.tsx";39+import { CommandLine } from "../shared/command.tsx";40+import { EmptyState } from "../shared/empty.tsx";41+import { HandleLink } from "../shared/handle.tsx";42+import { PageShell } from "../shared/layout.tsx";43+44+type Vouches = PublicPolicy["vouches"];45+46+/** The project's config file, `project.ts` in the config folder. */47+const PROJECT_FILE = `${Brand.configDir}/project.ts`;48+49+const HOUR_MS = 3_600_000;50+51+const plural = (count: number, one: string, many: string) =>52+ `${count} ${count === 1 ? one : many}`;53+54+/** A claim timing as a reader says it: whole hours up to two days, then days. */55+const spanOf = (ms: number) => {56+ if (ms % HOUR_MS !== 0) {57+ return plural(Math.round(ms / 60_000), "minute", "minutes");58+ }59+60+ const hours = ms / HOUR_MS;61+62+ return hours > 48 && hours % 24 === 063+ ? plural(hours / 24, "day", "days")64+ : plural(hours, "hour", "hours");65+};66+67+/** A commit as git abbreviates it. */68+const short = (sha: string) => sha.slice(0, 7);69+70+/** A file at a commit, on the code browser. */71+const blobPath = (project: ProjectName, at: string, path: string) =>72+ `/${project}/blob/${at}/${path}`;73+74+/** What a vouch gates, in words. */75+const vouchModes = {76+ all: "For everything: claiming an ask, offering a sealed answer and proposing an ask all need a vouch.",77+ bansOnly:78+ "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or propose.",79+ forCode:80+ "For code: claiming an ask or offering a sealed answer needs a vouch; anyone not denounced may propose an ask.",81+} as const satisfies Record<PublicPolicy["vouch"]["mode"], string>;82+83+/** What people outside a layer's audience learn about what it holds. */84+const disclosures = {85+ counted: "counted: how many it holds, and when they open",86+ declared: "declared: that it exists, with its kinds and reason",87+ hidden: "hidden: nothing beyond its name",88+ public: "public: everything",89+ sealed: "sealed: counts, authors and a salted root, never contents",90+ writeOnly: "write-only: who set each value and when, never a value",91+} as const satisfies Record<Disclosure, string>;92+93+const Code = ({ children }: { readonly children: ReactNode }) => (94+ <code className={CODE}>{children}</code>95+);96+97+/** Handles, each linked to their page, comma-separated. */98+const Handles = ({ handles }: { readonly handles: readonly Handle[] }) =>99+ handles.map((handle, index) => (100+ <Fragment key={handle}>101+ {index === 0 ? null : ", "}102+ <HandleLink handle={handle} />103+ </Fragment>104+ ));105+106+const MembersOf = ({ members }: { readonly members: Members }) =>107+ members === "deciders" ? "the deciders" : <Handles handles={members} />;108+109+/** "From <config folder>/project.ts", linked at the commit. */110+const Source = ({111+ href,112+ path,113+}: {114+ readonly href: string;115+ readonly path: string;116+}) => (117+ <p className="text-muted-foreground text-sm">118+ {"From "}119+ <a className={`${LINK} ${CODE}`} href={href}>120+ {path}121+ </a>122+ </p>123+);124+125+const DecidersTable = ({126+ deciders,127+}: {128+ readonly deciders: PublicPolicy["deciders"];129+}) => (130+ <Table className="text-sm">131+ <TableHeader>132+ <TableRow>133+ <TableHead>Paths</TableHead>134+ <TableHead>Deciders</TableHead>135+ </TableRow>136+ </TableHeader>137+ <TableBody>138+ {deciders.map(({ handles, paths }) => (139+ <TableRow data-paths={paths} key={paths}>140+ <TableCell className="whitespace-normal">141+ <Code>{paths}</Code>142+ </TableCell>143+ <TableCell className="whitespace-normal">144+ <Handles handles={handles} />145+ </TableCell>146+ </TableRow>147+ ))}148+ </TableBody>149+ </Table>150+);151+152+const VouchList = ({153+ label,154+ vouches,155+}: {156+ readonly label: string;157+ readonly vouches: Vouches;158+}) => (159+ <div className="flex min-w-0 flex-col gap-1">160+ <h3 className="text-muted-foreground text-xs font-medium">{label}</h3>161+ {vouches.length === 0 ? (162+ <p className="text-sm">Nobody.</p>163+ ) : (164+ <ul className="flex flex-col gap-1 text-sm">165+ {vouches.map(({ handle, note }) => (166+ <li167+ className="[overflow-wrap:anywhere]"168+ data-vouch={handle}169+ key={handle}170+ >171+ <HandleLink handle={handle} />172+ {note === undefined ? null : (173+ <span className="text-muted-foreground">{` — ${note}`}</span>174+ )}175+ </li>176+ ))}177+ </ul>178+ )}179+ </div>180+);181+182+const Vouching = ({183+ policy,184+ project,185+}: {186+ readonly policy: PublicPolicy;187+ readonly project: ProjectName;188+}) => {189+ const { vouch, vouches } = policy;190+ const denounced = vouches.filter((line) => line.denounced);191+ const vouched = vouches.filter((line) => !line.denounced);192+193+ return (194+ <Region id="vouching" title="Vouching">195+ <p className="max-w-[70ch] text-sm">{vouchModes[vouch.mode]}</p>196+ {vouches.length === 0 ? (197+ <p className="text-sm">198+ <Code>{vouch.file}</Code> vouches for nobody and denounces nobody.199+ </p>200+ ) : (201+ <div className="grid gap-4 sm:grid-cols-2">202+ <VouchList label="Vouched for" vouches={vouched} />203+ <VouchList label="Denounced" vouches={denounced} />204+ </div>205+ )}206+ {policy.source === "config" || vouches.length > 0 ? (207+ <Source208+ href={blobPath(project, policy.at, vouch.file)}209+ path={vouch.file}210+ />211+ ) : null}212+ </Region>213+ );214+};215+216+const LayerBlock = ({ layer }: { readonly layer: Layer }) => (217+ <li className="flex min-w-0 flex-col gap-2" data-layer={layer.name}>218+ <h3 className={`${CODE} font-medium`}>{layer.name}</h3>219+ <Fields label={`Layer ${layer.name}`}>220+ <Field label="Audience">{layer.audience}</Field>221+ <Field label="Readers">222+ <MembersOf members={layer.readers} />223+ </Field>224+ <Field label="Writers">225+ <MembersOf members={layer.writers} />226+ </Field>227+ <Field label="Disclosure">{disclosures[layer.disclose]}</Field>228+ <Field label="Reason">{layer.reason}</Field>229+ {layer.sunsetDays === undefined ? null : (230+ <Field label="Sunset">{`released after ${plural(layer.sunsetDays, "day", "days")}`}</Field>231+ )}232+ </Fields>233+ </li>234+);235+236+const Layers = ({237+ ledger,238+ project,239+}: {240+ readonly ledger: Ledger;241+ readonly project: ProjectName;242+}) => (243+ <Region id="layers" title="Layers">244+ {ledger.layers.length === 0 ? (245+ <EmptyState246+ title={`Open: nothing is held back. ${project} declares no layers, so everyone reads and writes the same public repo.`}247+ />248+ ) : (249+ <ul className="flex flex-col gap-6">250+ {ledger.layers.map((layer) => (251+ <LayerBlock key={layer.name} layer={layer} />252+ ))}253+ </ul>254+ )}255+ <p className="text-muted-foreground text-sm">256+ {"Each layer's history is on "}257+ <a className={LINK} href={ledgerPath(project)}>258+ the ledger259+ </a>260+ .261+ </p>262+ </Region>263+);264+265+const Limits = ({266+ policy,267+ source,268+}: {269+ readonly policy: PublicPolicy;270+ readonly source: ReactNode;271+}) => {272+ const { budget, caps, claims, record } = policy;273+274+ return (275+ <Region id="limits" title="Limits">276+ <Fields label="Limits">277+ <Field label="Claims">278+ {`${plural(caps.claimsPerPerson, "claim", "claims")} per person at once`}279+ </Field>280+ <Field label="Proposals">281+ {caps.proposalsPerPerson === 0282+ ? "Proposals are off"283+ : `${plural(caps.proposalsPerPerson, "proposal", "proposals")} per person at once`}284+ </Field>285+ <Field label="Budget">286+ {`${plural(budget.decisionsPerDay, "decision", "decisions")} a day per decider; an undecided one takes its default after ${plural(budget.expireDays, "day", "days")}`}287+ </Field>288+ <Field label="Claim timing">289+ {`warned after ${spanOf(claims.warnAfterMs)} without a push; lapses after ${spanOf(claims.lapseAfterMs)}`}290+ </Field>291+ <Field label="Record">292+ {`a landing counts ${293+ record.countsAfterDays === 0294+ ? "from the day it lands"295+ : `once it has stood ${plural(record.countsAfterDays, "day", "days")}`296+ }, for ${plural(record.windowDays, "day", "days")}`}297+ </Field>298+ </Fields>299+ {source}300+ </Region>301+ );302+};303+304+const Agents = ({305+ policy,306+ source,307+}: {308+ readonly policy: PublicPolicy;309+ readonly source: ReactNode;310+}) => (311+ <Region id="agents" title="Agents">312+ <p className="max-w-[70ch] text-sm">313+ {policy.agents === "trailer" ? (314+ <>315+ Each landing names the agents its people worked through, in an{" "}316+ <Code>Assisted-by:</Code> trailer.317+ </>318+ ) : (319+ <>320+ Landings carry no <Code>Assisted-by:</Code> trailer.321+ </>322+ )}323+ </p>324+ {source}325+ </Region>326+);327+328+/** The page over an evaluated policy: its commit, then each section. */329+const Evaluated = ({330+ ledger,331+ policy,332+ project,333+}: {334+ readonly ledger: Ledger;335+ readonly policy: PublicPolicy;336+ readonly project: ProjectName;337+}) => {338+ const projectFile =339+ policy.source === "config" ? (340+ <Source341+ href={blobPath(project, policy.at, PROJECT_FILE)}342+ path={PROJECT_FILE}343+ />344+ ) : null;345+346+ return (347+ <>348+ <p className="text-muted-foreground -mt-2 text-sm">349+ {"As of "}350+ <a351+ className={`${LINK} ${CODE}`}352+ href={`/${project}/commit/${policy.at}`}353+ >354+ {short(policy.at)}355+ </a>356+ , the landed commit.357+ </p>358+ {policy.source === "defaults" ? (359+ <p className="max-w-[70ch]" data-source="defaults">360+ {`This project has no ${PROJECT_FILE}: the person who set it up decides everything, under the platform's defaults.`}361+ </p>362+ ) : null}363+ <Region id="deciders" title="Deciders by path">364+ <DecidersTable deciders={policy.deciders} />365+ {projectFile}366+ </Region>367+ <Vouching policy={policy} project={project} />368+ <Layers ledger={ledger} project={project} />369+ <Limits policy={policy} source={projectFile} />370+ <Agents policy={policy} source={projectFile} />371+ </>372+ );373+};374+375+export const PeopleView = ({376+ ledger,377+ policy,378+ project,379+}: {380+ readonly ledger: Ledger;381+ readonly policy: Option.Option<PublicPolicy>;382+ readonly project: ProjectName;383+}): ReactNode => (384+ <PageShell title={`${project}: people`}>385+ <ProjectNav current="people" project={project} />386+ {Option.isSome(policy) ? (387+ <Evaluated ledger={ledger} policy={policy.value} project={project} />388+ ) : (389+ <>390+ <EmptyState title="The config at the landed commit has not been evaluated yet. It is evaluated once per landing; this page shows it once that is done." />391+ <Layers ledger={ledger} project={project} />392+ </>393+ )}394+ <Region id="editing" title="Changing these">395+ <p className="max-w-[70ch] text-sm">396+ {`Change these by landing a change to ${Brand.configDir}/: open an ask for it, or, as a decider, land your own change.`}397+ </p>398+ <CommandLine399+ command={`${Brand.cli} ask open <ask> --project ${project} --files <files> --yes`}400+ />401+ <CommandLine402+ command={`${Brand.cli} land --project ${project} --base <base> --head $(git rev-parse HEAD) --message <message> --requestId land-$(git rev-parse HEAD) --yes`}403+ />404+ </Region>405+ </PageShell>406+);modified:apps/web/src/routes/$project/people.tsx+115 added-10 removed
123456789110111213141516171819202142223624252627282989303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283841213148586878816899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312422125126127128129130131import { RegistryProvider, useAtomMount, useAtomValue,} from "@effect/atom-react";import { Client } from "@repo/protocol/contracts";import { PublicPolicy } from "@repo/protocol/domain/policy";import { Ledger } from "@repo/protocol/domain/visibility";import { ProjectName } from "@repo/protocol/ids";import { createFileRoute } from "@tanstack/react-router";import { createFileRoute, notFound } from "@tanstack/react-router";import { createServerFn } from "@tanstack/react-start";import { env } from "cloudflare:workers";import { Effect, Option, Schema } from "effect";import { AsyncResult, Atom } from "effect/reactivity";
import { ledgerAtom } from "../../client/ledger.ts";import { policyAtom } from "../../client/policy.ts";import { watchAtom } from "../../client/watch.ts";import { PeopleView } from "../../features/project-people/people-view.tsx";import { UnknownProjectView } from "../../features/project/unknown-project.tsx";import { pageTitle } from "../../features/shared/layout.tsx";import { NotBuilt } from "../../features/shared/not-built.tsx";import { serverClient } from "../../server/client.ts";
// Who decides what, who is vouched for, and who reads and writes each layer. A stub until 907 builds it.// Who decides what in a project, who is vouched for, and who reads and// writes each layer: the evaluated policy at the landed commit beside the// ledger. The loader reads both on the server, so the page arrives whole// and an address naming no project is a 404; in the browser each reads// again as the platform lands changes and appends entries.
const Page = () => { const { project } = Route.useParams();/** What the page's loader carries from the server, encoded: the policy (absent until evaluated) and the ledger. */const PeoplePageData = Schema.Struct({ ledger: Ledger, policy: Schema.optionalKey(PublicPolicy),});
type PeoplePageData = typeof PeoplePageData.Type;
/** The policy and ledger of the project `name`, or a not-found when there is no such project (a 404). */export const readPeople = (name: string) => Effect.gen(function* () { const project = yield* Schema.decodeEffect(ProjectName)(name).pipe( Effect.mapError(() => notFound()) );
const client = yield* Client;
const [{ policy }, ledger] = yield* Effect.all( [client.projectPolicy({ project }), client.ledger({ project })], { concurrency: 2 } ).pipe(Effect.catchTag("UnknownProject", () => Effect.fail(notFound())));
return yield* Schema.encodeEffect(PeoplePageData)( policy === undefined ? { ledger } : { ledger, policy } ); });
const peoplePage = createServerFn({ method: "GET" }) .validator((name: string) => name) .handler(({ data }) => Effect.runPromise(readPeople(data).pipe(Effect.provide(serverClient(env)))) );
/** The page over the two atoms, which start from what the loader read and read again as the project changes. */const FreshPeople = ({ project, read,}: { readonly project: ProjectName; readonly read: PeoplePageData;}) => { // Live: a landing re-reads the policy, a ledger entry the layers. useAtomMount(watchAtom(project));
const { policy } = Option.getOrElse( AsyncResult.value(useAtomValue(policyAtom(project))), () => read );
const ledger = Option.getOrElse( AsyncResult.value(useAtomValue(ledgerAtom(project))), () => read.ledger );
return ( <NotBuilt current="people" issue="907" <PeopleView ledger={ledger} policy={Option.fromUndefinedOr(policy)} project={project} title={`${project}: people`} /> );};
const PeoplePage = () => { const read = Schema.decodeSync(PeoplePageData)(Route.useLoaderData()); const { project } = read.ledger;
return ( <RegistryProvider initialValues={[ Atom.initialValue( policyAtom(project), AsyncResult.success( read.policy === undefined ? {} : { policy: read.policy } ) ), Atom.initialValue( ledgerAtom(project), AsyncResult.success(read.ledger) ), ]} key={project} > <FreshPeople project={project} read={read} /> </RegistryProvider> );};
const Unknown = () => { const { project } = Route.useParams();
return <UnknownProjectView name={project} />;};
export const Route = createFileRoute("/$project/people")({ component: Page, loader: ({ params }) => peoplePage({ data: params.project }), head: ({ params: { project } }) => ({ meta: [{ title: pageTitle(`${project}: people`) }], }), component: PeoplePage, notFoundComponent: Unknown,});added:apps/web/test/project-people.test.tsx+536 added
1+/**2+ * A project's people page, rendered to HTML with `react-dom/server` from3+ * fixtures decoded with the protocol's own schemas (`PublicPolicy` from4+ * `projectPolicy`, `Ledger` from `ledger`): who decides which paths, who is5+ * vouched for and denounced, each layer's readers and writers, the caps,6+ * budget and timings, and where each comes from at the landed commit. The7+ * page is read-only, and it shows nothing the two contracts don't carry.8+ */9+import { describe, expect, it } from "@effect/vitest";10+import { commandDocs } from "@repo/agent-kit/command-doc";11+import { Brand } from "@repo/brand";12+import { Client, Contracts } from "@repo/protocol/contracts";13+import { PublicPolicy } from "@repo/protocol/domain/policy";14+import { Ledger } from "@repo/protocol/domain/visibility";15+import { ProjectName } from "@repo/protocol/ids";16+import { UnknownProject } from "@repo/protocol/refusal";17+import { asTester, unanswered } from "@repo/protocol/testing";18+import { isNotFound } from "@tanstack/react-router";19+import { Effect, Layer, Option, Ref, Schema } from "effect";20+import { RpcTest } from "effect/rpc";21+22+import { PeopleView } from "../src/features/project-people/people-view.tsx";23+import { readPeople } from "../src/routes/$project/people.tsx";24+import { inOrder, markupOf, plainText, textOf } from "./ask-fixtures.ts";25+26+const datekit = ProjectName.make("datekit");27+28+const sha = "4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c";29+30+const decodePolicy = Schema.decodeSync(PublicPolicy);31+32+const decodeLedger = Schema.decodeSync(Ledger);33+34+/** What every policy below shares: the parts the page doesn't show. */35+const unshown = {36+ judge: { paths: [`${Brand.configDir}/**`], pointers: [] },37+ kinds: [],38+ modules: [],39+ ratchets: [],40+ run: { checks: { unit: "bun test" }, test: "bun test {path}" },41+ weakening: { markers: [] },42+};43+44+/** datekit's evaluated config folder at `sha`, as `projectPolicy` returns it. */45+const datekitPolicy = decodePolicy({46+ ...unshown,47+ agents: "trailer",48+ at: sha,49+ budget: { decisionsPerDay: 5, expireDays: 14 },50+ caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },51+ claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },52+ deciders: [53+ { handles: ["ines-v"], paths: "**" },54+ { handles: ["okonkwo", "bram"], paths: "src/format/**" },55+ { handles: ["okonkwo"], paths: "src/tz.ts" },56+ ],57+ record: { countsAfterDays: 30, windowDays: 365 },58+ source: "config",59+ vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },60+ vouches: [61+ { denounced: false, handle: "bram", note: "first answer landed in 0.4.0" },62+ { denounced: false, handle: "ines-v", note: "maintainer" },63+ { denounced: true, handle: "spam-bot", note: "opened 40 proposals" },64+ ],65+});66+67+/** datekit's ledger: one maintainers layer. */68+const datekitLedger = decodeLedger({69+ entries: [],70+ layers: [71+ {72+ audience: "maintainers",73+ disclose: "sealed",74+ holds: ["checks", "notes"],75+ name: "maintainers",76+ readers: "deciders",77+ reason: "Held-back checks judge an answer by the ask's words.",78+ repo: "datekit--maintainers",79+ sunsetDays: 90,80+ writers: ["ines-v", "okonkwo"],81+ },82+ ],83+ posture: "openWithSealedEvidence",84+ postureLabel: "Open with sealed evidence",85+ project: "datekit",86+});87+88+/** An imported repo with no `project.ts` in its config folder: the platform's defaults, its initializer deciding. */89+const burrowPolicy = decodePolicy({90+ ...unshown,91+ agents: "trailer",92+ at: sha,93+ budget: { decisionsPerDay: 5, expireDays: 14 },94+ caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },95+ claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },96+ deciders: [{ handles: ["wren"], paths: "**" }],97+ record: { countsAfterDays: 30, windowDays: 365 },98+ source: "defaults",99+ vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },100+ vouches: [],101+});102+103+const burrowLedger = decodeLedger({104+ entries: [],105+ layers: [],106+ posture: "open",107+ postureLabel: "Open",108+ project: "burrow",109+});110+111+const page = (112+ <PeopleView113+ ledger={datekitLedger}114+ policy={Option.some(datekitPolicy)}115+ project={datekit}116+ />117+);118+119+/** The markup from `start` up to `end` (or to the end): one section of the page. */120+const between = (markup: string, start: string, end?: string) =>121+ markup.slice(122+ markup.indexOf(start),123+ end === undefined ? undefined : markup.indexOf(end)124+ );125+126+/** The markup of the section whose heading has the id `id`. */127+const sectionOf = (markup: string, id: string) => {128+ const heading = markup.indexOf(`id="${id}"`);129+130+ return markup.slice(131+ markup.lastIndexOf("<section", heading),132+ markup.indexOf("</section>", heading)133+ );134+};135+136+/** Each shell line the page offers to copy, as typed. */137+const commandsOf = (markup: string) =>138+ [139+ ...markup.matchAll(/<code\b[^>]*select-all[^>]*>(?<line>.*?)<\/code>/gsu),140+ ].map((found) => plainText(found.groups?.line ?? "").trim());141+142+/** The CLI command a line runs: the longest command path it starts with. */143+const commandOf = (line: string) =>144+ commandDocs(Contracts)145+ .filter(({ path }) => line.startsWith(`${Brand.cli} ${path.join(" ")} `))146+ .toSorted((one, other) => other.path.length - one.path.length)147+ .at(0);148+149+/** Each `<tr>`'s text, in order. */150+const rowsOf = (markup: string) =>151+ [...markup.matchAll(/<tr\b[^>]*>(?<row>.*?)<\/tr>/gsu)].map((found) =>152+ plainText(found.groups?.row ?? "").trim()153+ );154+155+describe("a project's people page", () => {156+ it("lists who decides which paths, in the policy's order, each handle linked to their page", () => {157+ const markup = markupOf(page);158+ const table = between(markup, "<table", "</table>");159+160+ expect(rowsOf(table)).toStrictEqual([161+ "Paths Deciders",162+ "** ines-v",163+ "src/format/** okonkwo , bram",164+ "src/tz.ts okonkwo",165+ ]);166+ expect(table).toMatch(167+ /<a\b[^>]*href="\/people\/okonkwo"[^>]*>okonkwo<\/a>/u168+ );169+ expect(table).toMatch(/<a\b[^>]*href="\/people\/bram"[^>]*>bram<\/a>/u);170+ });171+172+ it("states the vouch rule in words and splits the file into vouched and denounced, with notes", () => {173+ const markup = markupOf(page);174+ const vouching = plainText(between(markup, 'id="vouching"', 'id="layers"'));175+176+ expect(vouching).toContain("For code");177+ expect(178+ inOrder(vouching, [179+ "Vouched for",180+ "bram",181+ "first answer landed in 0.4.0",182+ "ines-v",183+ "maintainer",184+ "Denounced",185+ "spam-bot",186+ "opened 40 proposals",187+ ])188+ ).toBeTruthy();189+ expect(markup).toContain(190+ `href="/datekit/blob/${sha}/${Brand.configDir}/vouched.td"`191+ );192+ });193+194+ it("shows each layer's audience, readers, writers, disclosure, reason and sunset, from the ledger", () => {195+ const layers = plainText(196+ between(markupOf(page), 'id="layers"', 'id="limits"')197+ );198+199+ expect(200+ inOrder(layers, [201+ "maintainers",202+ "Audience",203+ "maintainers",204+ "Readers",205+ "the deciders",206+ "Writers",207+ "ines-v",208+ "okonkwo",209+ "Disclosure",210+ "sealed",211+ "Reason",212+ "Held-back checks judge an answer by the ask's words.",213+ "Sunset",214+ "90 days",215+ ])216+ ).toBeTruthy();217+ });218+219+ it("shows the caps, budget, claim timing and record window", () => {220+ const limits = plainText(221+ between(markupOf(page), 'id="limits"', 'id="agents"')222+ );223+224+ for (const words of [225+ "3 claims per person",226+ "2 proposals per person",227+ "5 decisions a day",228+ "14 days",229+ "2 hours",230+ "24 hours",231+ "30 days",232+ "365 days",233+ ]) {234+ expect(limits).toContain(words);235+ }236+ });237+238+ it("says whether landings disclose the agents people worked through", () => {239+ const disclosed = plainText(sectionOf(markupOf(page), "agents"));240+241+ const undisclosed = plainText(242+ sectionOf(243+ markupOf(244+ <PeopleView245+ ledger={datekitLedger}246+ policy={Option.some({ ...datekitPolicy, agents: "none" })}247+ project={datekit}248+ />249+ ),250+ "agents"251+ )252+ );253+254+ expect(disclosed).toContain(255+ "Each landing names the agents its people worked through"256+ );257+ expect(undisclosed).toContain("Landings carry no Assisted-by: trailer");258+ expect(undisclosed).not.toContain("names the agents");259+ });260+261+ it("says a denouncement still bars a person when the vouch rule is bans only", () => {262+ const vouching = plainText(263+ sectionOf(264+ markupOf(265+ <PeopleView266+ ledger={datekitLedger}267+ policy={Option.some({268+ ...datekitPolicy,269+ vouch: { ...datekitPolicy.vouch, mode: "bansOnly" },270+ })}271+ project={datekit}272+ />273+ ),274+ "vouching"275+ )276+ );277+278+ expect(vouching).toContain("Bans only: nobody needs a vouch");279+ expect(vouching).toContain(280+ "a denounced person still may not claim, push or propose"281+ );282+ });283+284+ it("links the file each section comes from, inside that section", () => {285+ const markup = markupOf(page);286+ const projectFile = `href="/datekit/blob/${sha}/${Brand.configDir}/project.ts"`;287+288+ for (const id of ["deciders", "limits", "agents"]) {289+ expect(sectionOf(markup, id)).toContain(projectFile);290+ }291+292+ expect(sectionOf(markup, "vouching")).toContain(293+ `href="/datekit/blob/${sha}/${Brand.configDir}/vouched.td"`294+ );295+ expect(markup.split(projectFile)).toHaveLength(4);296+ });297+298+ it("says which commit it is as of, and links each source file at that commit", () => {299+ const markup = markupOf(page);300+301+ expect(textOf(page)).toContain(`As of ${sha.slice(0, 7)}`);302+ expect(markup).toMatch(303+ new RegExp(304+ `<a\\b[^>]*href="/datekit/commit/${sha}"[^>]*>${sha.slice(0, 7)}</a>`,305+ "u"306+ )307+ );308+ expect(markup).toContain(309+ `href="/datekit/blob/${sha}/${Brand.configDir}/project.ts"`310+ );311+ });312+313+ it("offers no control, only how to change it: land a change to the config folder", () => {314+ const markup = markupOf(page);315+ const text = plainText(markup);316+317+ for (const control of ["<input", "<textarea", "<form", "<select"]) {318+ expect(markup).not.toContain(control);319+ }320+321+ expect(text).toContain(322+ `Change these by landing a change to ${Brand.configDir}/`323+ );324+ expect(text).toContain(`${Brand.cli} ask open`);325+ expect(text).toContain(`${Brand.cli} land`);326+ });327+328+ it("shows each command whole: a real CLI command, with every flag its payload takes and --yes", () => {329+ const lines = commandsOf(markupOf(page));330+331+ expect(lines.map((line) => commandOf(line)?.contract)).toStrictEqual([332+ "openAsk",333+ "land",334+ ]);335+336+ for (const line of lines) {337+ const doc = commandOf(line);338+ const given = line.split(" ").filter((word) => word.startsWith("--"));339+340+ const payload = (doc?.flags ?? []).filter(341+ (flag) => !["--dry-run", "--json", "--yes"].includes(flag)342+ );343+344+ expect(345+ given.filter((flag) => !(doc?.flags ?? []).includes(flag))346+ ).toStrictEqual([]);347+ expect(payload.filter((flag) => !given.includes(flag))).toStrictEqual([]);348+ expect(given.includes("--yes")).toBe(doc?.needsApproval);349+ }350+ });351+352+ it("adds no sealed path, check name, salt or read log to what it was given", () => {353+ const markup = markupOf(page);354+355+ for (const leak of [356+ "layers/",357+ "held-back/",358+ ".test.ts",359+ "sha256:",360+ "read log",361+ ]) {362+ expect(markup).not.toContain(leak);363+ }364+ });365+366+ it("says a project without a project.ts runs on defaults, its initializer deciding everything", () => {367+ const view = (368+ <PeopleView369+ ledger={burrowLedger}370+ policy={Option.some(burrowPolicy)}371+ project={ProjectName.make("burrow")}372+ />373+ );374+375+ const markup = markupOf(view);376+377+ expect(textOf(view)).toContain(378+ `This project has no ${Brand.configDir}/project.ts: the person who set it up decides everything`379+ );380+ expect(rowsOf(between(markup, "<table", "</table>"))).toStrictEqual([381+ "Paths Deciders",382+ "** wren",383+ ]);384+ expect(markup).not.toContain(`/${Brand.configDir}/project.ts"`);385+ expect(textOf(view)).toContain("vouches for nobody");386+ });387+388+ it("says the config has not been evaluated yet, and shows no tables, when there is no policy", () => {389+ const view = (390+ <PeopleView391+ ledger={datekitLedger}392+ policy={Option.none()}393+ project={datekit}394+ />395+ );396+397+ const markup = markupOf(view);398+399+ expect(textOf(view)).toContain("has not been evaluated yet");400+ expect(markup).not.toContain("<table");401+ expect(markup).not.toContain('id="vouching"');402+ });403+404+ it("shows a project without layers as open, with nothing held back", () => {405+ const view = (406+ <PeopleView407+ ledger={burrowLedger}408+ policy={Option.some(burrowPolicy)}409+ project={ProjectName.make("burrow")}410+ />411+ );412+413+ expect(textOf(view)).toContain("Open: nothing is held back");414+ });415+});416+417+/** A platform that knows only datekit, counting the reads it is asked for. */418+const platformOf = (419+ asked: Ref.Ref<number>,420+ policy: Option.Option<PublicPolicy>421+) =>422+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(423+ Layer.provide(424+ Layer.mergeAll(425+ unanswered,426+ Contracts.toLayerHandler("projectPolicy", ({ project }) =>427+ Effect.gen(function* () {428+ yield* Ref.update(asked, (seen) => seen + 1);429+430+ if (project !== datekit) {431+ return yield* new UnknownProject({ project });432+ }433+434+ return Option.match(policy, {435+ onNone: () => ({}),436+ onSome: (evaluated) => ({ policy: evaluated }),437+ });438+ })439+ ),440+ Contracts.toLayerHandler("ledger", ({ project }) =>441+ Effect.gen(function* () {442+ yield* Ref.update(asked, (seen) => seen + 1);443+444+ if (project !== datekit) {445+ return yield* new UnknownProject({ project });446+ }447+448+ return datekitLedger;449+ })450+ ),451+ asTester452+ )453+ )454+ );455+456+describe(readPeople, () => {457+ it.effect("reads the project's policy and ledger together", () =>458+ Effect.gen(function* () {459+ const asked = yield* Ref.make(0);460+461+ const read = yield* readPeople("datekit").pipe(462+ Effect.provide(platformOf(asked, Option.some(datekitPolicy)))463+ );464+465+ expect(read.policy?.at).toBe(sha);466+ expect(read.ledger.layers.map(({ name }) => name)).toStrictEqual([467+ "maintainers",468+ ]);469+ expect(yield* Ref.get(asked)).toBe(2);470+ })471+ );472+473+ it.effect("carries no policy while the config has not evaluated", () =>474+ Effect.gen(function* () {475+ const asked = yield* Ref.make(0);476+477+ const read = yield* readPeople("datekit").pipe(478+ Effect.provide(platformOf(asked, Option.none()))479+ );480+481+ expect(read.policy).toBeUndefined();482+ })483+ );484+485+ it.effect("is a not-found for a project the platform does not know", () =>486+ Effect.gen(function* () {487+ const asked = yield* Ref.make(0);488+489+ const failed = yield* Effect.flip(490+ readPeople("no-such-project").pipe(491+ Effect.provide(platformOf(asked, Option.some(datekitPolicy)))492+ )493+ );494+495+ expect(isNotFound(failed)).toBeTruthy();496+ })497+ );498+499+ it.effect(500+ "is a not-found, asking nothing, for an address that names no project",501+ () =>502+ Effect.gen(function* () {503+ const asked = yield* Ref.make(0);504+505+ const failed = yield* Effect.flip(506+ readPeople("Not_A-Project").pipe(507+ Effect.provide(platformOf(asked, Option.some(datekitPolicy)))508+ )509+ );510+511+ expect(isNotFound(failed)).toBeTruthy();512+ expect(yield* Ref.get(asked)).toBe(0);513+ })514+ );515+});516+517+describe("the people view", () => {518+ // Views only: props in, markup out, and outside the visibility cartridge.519+ const sources: Readonly<Record<string, string>> = import.meta.glob(520+ "../src/features/project-people/**/*.{ts,tsx}",521+ { eager: true, import: "default", query: "?raw" }522+ );523+524+ const reaching =525+ /from\s+["'](?:@repo\/visibility[^"']*|@repo\/protocol\/contracts|effect\/(?:rpc|http|reactivity)|#backend|[./]+\/(?:surfaces|client\/[^"']*|server\/[^"']*)(?:\.tsx?)?)["']|\.visibility\b/u;526+527+ it("imports no transport, nothing from the visibility cartridge, and reads no policy layers", () => {528+ expect(Object.keys(sources).length).toBeGreaterThanOrEqual(1);529+530+ expect(531+ Object.entries(sources).flatMap(([path, source]) =>532+ reaching.test(source) ? [path] : []533+ )534+ ).toStrictEqual([]);535+ });536+});