Merge build/1205-dev-fixtures
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents bbace25, c1616ab · Browse files · 12 files·+4644 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+4644 added−28 removed
- tests:+746 added−0 removed
- other:+3898 added−28 removed
Provenance
- Commit
c816189- Tree
9cf7bfe- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
bbace25- Parent 2
c1616ab
12 files changed+4644 added−28 removed
added:apps/web/src/dev/fixtures/fillers.ts+249 added
1+/**2+ * Six small fictional projects beside the others, so a list of projects3+ * runs past what fits beside it, each made through the project service as4+ * datekit is: created, its first commit pushed, one ask opened by its5+ * decider. `mossgate` opens none: a visitor's proposal is all it holds, so6+ * it lists with no open asks.7+ */8+import { Brand } from "@repo/brand";9+import { CheckSpec } from "@repo/protocol/domain/check";10+import type { Handle } from "@repo/protocol/ids";11+import { AskId, ProjectName, RepoPath } from "@repo/protocol/ids";12+import { Person } from "@repo/protocol/principal";13+import { Array, Effect, Schema } from "effect";14+15+import { DevClock, devMinute } from "../clock.ts";16+import {17+ askFileOf,18+ burrowPeople,19+ datekitPeople,20+ policyJson,21+} from "../examples.ts";22+import type { StatedAsk } from "../examples.ts";23+import type { Files } from "../git.ts";24+import { opened, startedAt, visitors } from "../seed.ts";25+26+const encodeCheck = Schema.encodeSync(CheckSpec);27+28+const { configDir } = Brand;29+30+interface Filler {31+ readonly project: ProjectName;32+ readonly decider: Handle;33+ readonly summary: string;34+ readonly source: string;35+ readonly ask?: { readonly id: string; readonly want: string };36+}37+38+const filler = (input: {39+ readonly project: string;40+ readonly decider: Handle;41+ readonly summary: string;42+ readonly source: string;43+ readonly ask?: { readonly id: string; readonly want: string };44+}): Filler => ({ ...input, project: ProjectName.make(input.project) });45+46+const fillers: readonly Filler[] = [47+ filler({48+ ask: {49+ id: "redact-header-values",50+ want: "Logged request headers hide the values of Authorization and Cookie.",51+ },52+ decider: burrowPeople.decider,53+ project: "amberlog",54+ source: "log",55+ summary: "Structured logs for small services.",56+ }),57+ filler({58+ ask: {59+ id: "skip-unchanged-steps",60+ want: "A build step whose inputs hash the same as last time is skipped.",61+ },62+ decider: burrowPeople.second,63+ project: "cinderbox",64+ source: "cache",65+ summary: "A tiny build cache keyed by the hashes of its inputs.",66+ }),67+ filler({68+ ask: {69+ id: "quote-embedded-newlines",70+ want: "A field holding a newline is written quoted.",71+ },72+ decider: datekitPeople.zones,73+ project: "fernwick",74+ source: "csv",75+ summary: "Reads and writes CSV with types.",76+ }),77+ filler({78+ decider: burrowPeople.second,79+ project: "mossgate",80+ source: "limit",81+ summary: "A rate limiter for edge functions.",82+ }),83+ filler({84+ ask: {85+ id: "due-cards-first",86+ want: "A review session shows the cards that are due before any new card.",87+ },88+ decider: burrowPeople.decider,89+ project: "quillon",90+ source: "cards",91+ summary: "Spaced-repetition flashcards in the terminal.",92+ }),93+ filler({94+ ask: {95+ id: "drain-on-shutdown",96+ want: "Closing the pool waits for every borrowed connection to come back.",97+ },98+ decider: datekitPeople.zones,99+ project: "tidepool",100+ source: "pool",101+ summary: "A connection pool that queues borrowers fairly.",102+ }),103+];104+105+/** `drain-on-shutdown` → `drainOnShutdown`: the export an ask's check looks for. */106+export const exportNameOf = (ask: string) =>107+ ask.replaceAll(/-(?<letter>[a-z0-9])/gu, (_match, letter: string) =>108+ letter.toUpperCase()109+ );110+111+/** A check that fails on main by its assertion: the module exports no function by the ask's name. */112+export const checkOf = (module: string, ask: string, want: string) =>113+ [114+ 'import { expect, test } from "bun:test";',115+ "",116+ `import * as module from "../../src/${module}.ts";`,117+ "",118+ `test(${JSON.stringify(want)}, () => {`,119+ ` expect(typeof Reflect.get(module, ${JSON.stringify(exportNameOf(ask))})).toBe("function");`,120+ "});",121+ "",122+ ].join("\n");123+124+/** The ask a filler states, as its `policy.json` holds it. */125+const statedOf = (126+ project: Filler,127+ ask: NonNullable<Filler["ask"]>128+): StatedAsk => ({129+ askedBy: project.decider,130+ blockedBy: [],131+ brief: { want: ask.want },132+ check: encodeCheck(133+ CheckSpec.cases.RedThenGreen.make({134+ path: RepoPath.make(`test/asks/${ask.id}.test.ts`),135+ })136+ ),137+ file: `${configDir}/asks/${ask.id}.ask.ts`,138+ id: ask.id,139+ kind: "fix",140+ territory: { module: ".", paths: [`src/${project.source}.ts`] },141+});142+143+const filesOf = (project: Filler, stated: readonly StatedAsk[]): Files =>144+ new Map([145+ [146+ "README.md",147+ [148+ `# ${project.project}`,149+ "",150+ project.summary,151+ "",152+ "A fictional project: it and its people are invented.",153+ "",154+ ].join("\n"),155+ ],156+ [157+ "package.json",158+ `${JSON.stringify({ name: project.project, scripts: { test: "bun test" }, type: "module", version: "0.1.0" }, null, 2)}\n`,159+ ],160+ [161+ `src/${project.source}.ts`,162+ `/** ${project.summary} */\nexport const ${project.source} = () => undefined;\n`,163+ ],164+ [165+ `${configDir}/policy.json`,166+ policyJson({167+ asks: [...stated],168+ deciders: [{ handles: [project.decider], paths: "**" }],169+ functions: { admit: false, opensAlone: false },170+ kinds: [171+ {172+ checkKind: "redThenGreen",173+ claimers: "vouched",174+ finish: "optional",175+ name: "fix",176+ oneWay: false,177+ race: 1,178+ requires: ["want", "check", "territory"],179+ strength: "assertion",180+ },181+ ],182+ ratchets: [],183+ run: { checks: { unit: "bun test" }, test: "bun test {path}" },184+ source: "config",185+ weakening: { markers: [".skip(", ".only(", ".todo("] },186+ }),187+ ],188+ [189+ `${configDir}/vouched.td`,190+ `# The people ${project.project}'s deciders vouch for.\n`,191+ ],192+ ]);193+194+/**195+ * Every filler made and adopted, one every three minutes from `minute`,196+ * each one's ask (or, in mossgate, a visitor's proposal) a minute after its197+ * first push.198+ */199+export const seedFillers = (minute: number) =>200+ Effect.forEach(201+ fillers,202+ (project, index) =>203+ Effect.gen(function* () {204+ const at = minute + index * 3;205+206+ const stated = Array.fromNullishOr(project.ask).map((ask) =>207+ statedOf(project, ask)208+ );209+210+ const { api } = yield* startedAt(211+ project.project,212+ project.decider,213+ filesOf(project, stated),214+ devMinute(at)215+ );216+217+ if (Array.isReadonlyArrayNonEmpty(stated)) {218+ yield* opened(219+ api,220+ project.decider,221+ stated.map((each) => {222+ const file = askFileOf(each);223+224+ return [225+ AskId.make(each.id),226+ [227+ file,228+ {229+ content: checkOf(project.source, each.id, each.brief.want),230+ path: RepoPath.make(`test/asks/${each.id}.test.ts`),231+ },232+ ],233+ ] as const;234+ }),235+ at + 2236+ );237+238+ return;239+ }240+241+ const clock = yield* DevClock;242+243+ yield* clock.set(devMinute(at + 2));244+ yield* api.proposeAsk(Person.make({ handle: visitors.regular }), {245+ want: `${project.project} sheds load by route, not only in total.`,246+ });247+ }),248+ { discard: true }249+ );added:apps/web/src/dev/fixtures/record.ts+260 added
1+/**2+ * A fixture project's record: everything its reads answer with, held as3+ * one value so every contract reads the same story (the asks, the events4+ * `watch` replays, the verdicts, the landings, the decisions, the ledger,5+ * the env shape, the proposals and the claims). Every part is decoded6+ * through the protocol's own schema before the world serves it7+ * (`decodeRecord`), so a fixture cannot drift from the wire.8+ *9+ * The reads a record answers are derived here by the service's own pure10+ * functions where it has them: Today by `today` (budget, overflow, what11+ * expires within the day, newcomers, what landed without anyone), credits12+ * by `creditsByArea`, a listing by `listingOf`.13+ */14+import { creditsByArea } from "@repo/project/attention/credits";15+import { today } from "@repo/project/attention/today";16+import { listingOf } from "@repo/project/events";17+import type { Verdict } from "@repo/protocol/domain/answer";18+import {19+ AnswerView,20+ Verdict as VerdictSchema,21+} from "@repo/protocol/domain/answer";22+import { Ask } from "@repo/protocol/domain/ask";23+import type { AskListing } from "@repo/protocol/domain/ask";24+import { ClaimView } from "@repo/protocol/domain/claim";25+import { ForkRef } from "@repo/protocol/domain/code";26+import { ConfigFile } from "@repo/protocol/domain/common";27+import { Decision } from "@repo/protocol/domain/decision";28+import type { Choice, Today } from "@repo/protocol/domain/decision";29+import { EnvSchemaView } from "@repo/protocol/domain/env";30+import { ProjectEvent } from "@repo/protocol/domain/event";31+import { LandingView } from "@repo/protocol/domain/landing";32+import { Proposal } from "@repo/protocol/domain/proposal";33+import type { CreditSummary } from "@repo/protocol/domain/record";34+import { Ledger } from "@repo/protocol/domain/visibility";35+import { sameHandle } from "@repo/protocol/ids";36+import type {37+ AskId,38+ CommitSha,39+ DecisionId,40+ Handle,41+ LandedSha,42+ ProposalId,43+} from "@repo/protocol/ids";44+import {45+ DecisionClosed,46+ NotDecider,47+ UnknownDecision,48+} from "@repo/protocol/refusal";49+import { Array, DateTime, Effect, Option, Schema } from "effect";50+51+import { present } from "./story.ts";52+53+/** One proposal and the files it holds. */54+export interface HeldProposal {55+ readonly files: readonly ConfigFile[];56+ readonly proposal: Proposal;57+}58+59+/** A log a failing lane left, as `evidence` reads it back. */60+export interface KeptLog {61+ readonly claimant: Handle;62+ readonly lane: Verdict["lanes"][number]["lane"];63+ readonly text: string;64+}65+66+/** A fixture project's whole record. */67+export interface FixtureRecord {68+ /** Every claim's answers: one per round, oldest first. */69+ readonly answers: readonly AnswerView[];70+ readonly asks: ReadonlyMap<AskId, Ask>;71+ /** Every claim, as its claimant's `status` shows it. */72+ readonly claims: readonly ClaimView[];73+ readonly decisions: readonly Decision[];74+ readonly env: EnvSchemaView;75+ readonly events: readonly ProjectEvent[];76+ /** Each person's first claim, older history included. */77+ readonly firstClaims: readonly {78+ readonly at: DateTime.Utc;79+ readonly handle: Handle;80+ }[];81+ readonly forks: readonly ForkRef[];82+ /** Main's landed commit. */83+ readonly head: LandedSha;84+ readonly landings: readonly LandingView[];85+ readonly ledger: Ledger;86+ readonly logs: ReadonlyMap<string, KeptLog>;87+ readonly proposals: ReadonlyMap<ProposalId, HeldProposal>;88+ /** Each answered ask's verdicts, one per round, oldest first. */89+ readonly verdicts: ReadonlyMap<AskId, readonly Verdict[]>;90+}91+92+const asType = <S extends Schema.Top>(schema: S) =>93+ Schema.decodeUnknownEffect(Schema.toType(schema));94+95+/**96+ * `record` decoded part by part through the protocol's schemas: a value97+ * that fails is a defect of the fixture's, found when the world is built.98+ */99+export const decodeRecord = (100+ record: FixtureRecord101+): Effect.Effect<FixtureRecord> =>102+ Effect.gen(function* () {103+ const many = <S extends Schema.Top>(104+ schema: S,105+ values: readonly unknown[]106+ ) => asType(Schema.Array(schema))(values);107+108+ yield* many(Ask, [...record.asks.values()]);109+ yield* many(ProjectEvent, record.events);110+ yield* many(VerdictSchema, [...record.verdicts.values()].flat());111+ yield* many(AnswerView, record.answers);112+ yield* many(LandingView, record.landings);113+ yield* many(Decision, record.decisions);114+ yield* many(ClaimView, record.claims);115+ yield* many(ForkRef, record.forks);116+ yield* many(117+ Proposal,118+ [...record.proposals.values()].map((held) => held.proposal)119+ );120+ yield* many(121+ ConfigFile,122+ [...record.proposals.values()].flatMap(({ files }) => files)123+ );124+ yield* asType(Ledger)(record.ledger);125+ yield* asType(EnvSchemaView)(record.env);126+127+ return record;128+ }).pipe(Effect.orDie);129+130+// ------------------------------------------------------------ reads131+132+/** The open asks, as `listAsks` lists them. */133+export const listedOf = (record: FixtureRecord): readonly AskListing[] =>134+ [...record.asks.values()].flatMap((ask) =>135+ ask.state === "closed" ? [] : [listingOf(ask)]136+ );137+138+/** The verdict on `head`, or the latest; its outcome where the answer stands now. */139+export const verdictIn = (140+ record: FixtureRecord,141+ ask: AskId,142+ head: CommitSha | undefined143+): Option.Option<Verdict> => {144+ const rounds = record.verdicts.get(ask) ?? [];145+146+ return Array.findLast(147+ rounds,148+ (verdict) => head === undefined || verdict.head === head149+ );150+};151+152+/** The landing at `sha`, if the record holds one. */153+export const landingIn = (record: FixtureRecord, sha: CommitSha) =>154+ Array.findFirst(record.landings, (landing) => landing.sha === sha);155+156+/** How many decisions and finishes `decider` took on the day of `now`. */157+const spentBy = (record: FixtureRecord, decider: Handle, now: DateTime.Utc) => {158+ const day = DateTime.formatIsoDateUtc(now);159+160+ return record.decisions.filter(161+ ({ decided }) =>162+ decided !== undefined &&163+ sameHandle(decided.by, decider) &&164+ DateTime.formatIsoDateUtc(decided.at) === day165+ ).length;166+};167+168+/** `decider`'s Today in the record, as the service computes one; none for anyone who decides nothing in it. */169+export const todayIn = (170+ record: FixtureRecord,171+ decider: Handle,172+ now: DateTime.Utc,173+ perDay: number174+): Option.Option<Today> =>175+ record.decisions.some(({ deciders }) =>176+ deciders.some((each) => sameHandle(each, decider))177+ )178+ ? Option.some(179+ today({180+ budget: {181+ finishes: 0,182+ total: perDay,183+ used: spentBy(record, decider, now),184+ },185+ decider,186+ decisions: record.decisions,187+ firstClaims: record.firstClaims,188+ landings: record.landings,189+ now,190+ })191+ )192+ : Option.none();193+194+/** A person's credits in the record, by area and role. */195+export const creditsIn = (196+ record: FixtureRecord,197+ handle: Handle198+): readonly CreditSummary[] =>199+ creditsByArea({ asks: record.asks, handle, landings: record.landings });200+201+/** The caller's claims still in play, and their answers. */202+export const statusIn = (record: FixtureRecord, who: Handle) => ({203+ answers: record.answers.filter(({ ask }) =>204+ record.claims.some(205+ (claim) => claim.ask === ask && sameHandle(claim.claimant, who)206+ )207+ ),208+ claims: record.claims.filter(209+ ({ claimant, state }) =>210+ sameHandle(claimant, who) && (state === "live" || state === "warned")211+ ),212+});213+214+/**215+ * The decision `who` takes when they choose `choice` on `id` at `now`, with216+ * its record (by, choice, when, note); or why they may not: no such217+ * decision, one already taken or expired, or one they do not decide.218+ */219+export const decisionTaken = (220+ record: FixtureRecord,221+ input: {222+ readonly choice: Choice;223+ readonly decision: DecisionId;224+ readonly note?: string;225+ readonly now: DateTime.Utc;226+ readonly who: Handle;227+ }228+): Effect.Effect<Decision, UnknownDecision | DecisionClosed | NotDecider> =>229+ Effect.gen(function* () {230+ const found = record.decisions.find(({ id }) => id === input.decision);231+232+ if (found === undefined) {233+ return yield* new UnknownDecision({ decision: input.decision });234+ }235+236+ if (237+ found.decided !== undefined ||238+ DateTime.isLessThanOrEqualTo(found.expiresAt, input.now)239+ ) {240+ return yield* new DecisionClosed({ decision: input.decision });241+ }242+243+ if (!found.deciders.some((each) => sameHandle(each, input.who))) {244+ return yield* new NotDecider({});245+ }246+247+ return {248+ ...found,249+ decided: {250+ at: input.now,251+ by: input.who,252+ choice: input.choice,253+ ...present("note", input.note),254+ },255+ };256+ });257+258+/** The number of the record's last event. */259+export const lastSeqOf = (record: FixtureRecord): number =>260+ Math.max(0, ...record.events.map(({ seq }) => seq));added:apps/web/src/dev/fixtures/story.ts+850 added
1+/**2+ * How a fixture project's record is written: a story told in the order3+ * things happened, each step writing what the service would have written4+ * for it (the events `watch` replays, numbered in order, the asks, each5+ * round's verdict, the claims and the landings). A landing is a real6+ * commit on the project's canonical `main` in the world's repo host,7+ * committed by the platform with its credit trailers, so the code pages,8+ * the log and every landing link read real git. An answer's head names no9+ * commit the world holds (its fork is never made): it is a stable id made10+ * from the step's name, as are merged trees, patch ids and suite roots.11+ */12+import { RefName, RefOutcome, RepoHost } from "@repo/artifacts/repo-host";13+import { Brand } from "@repo/brand";14+import { formatLanding } from "@repo/git/trailers";15+import { listingOf } from "@repo/project/events";16+import type {17+ AnswerView,18+ HeldBackResult,19+ LaneOutcome,20+ LaneResult,21+ Verdict,22+} from "@repo/protocol/domain/answer";23+import type { Ask } from "@repo/protocol/domain/ask";24+import { CheckSpec } from "@repo/protocol/domain/check";25+import type { ClaimState, ClaimView } from "@repo/protocol/domain/claim";26+import type { ForkRef } from "@repo/protocol/domain/code";27+import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";28+import type { Decision } from "@repo/protocol/domain/decision";29+import { ProjectEvent } from "@repo/protocol/domain/event";30+import type { LandingView } from "@repo/protocol/domain/landing";31+import { Outcome } from "@repo/protocol/domain/outcome";32+import type { StageName } from "@repo/protocol/domain/outcome";33+import type { LedgerEntry } from "@repo/protocol/domain/visibility";34+import {35+ CheckVersion,36+ CommitSha,37+ LandedSha,38+ LaneName,39+ PatchId,40+ RepoName,41+ RequestId,42+ SuiteRoot,43+ TreeSha,44+} from "@repo/protocol/ids";45+import type {46+ AskId,47+ Handle,48+ ProjectName,49+ ProposalId,50+} from "@repo/protocol/ids";51+import { Array, DateTime, Effect, Option, Record } from "effect";52+53+import { overlay, personIdentity, platformIdentity, scratch } from "../git.ts";54+import type { Files } from "../git.ts";55+import type { FixtureRecord, HeldProposal, KeptLog } from "./record.ts";56+57+// ------------------------------------------------------------- ids58+59+/** The largest prime below 2^32: each block of eight digits is a hash modulo it. */60+const MODULUS = 4_294_967_291;61+62+/** `count` hex digits made from `label` alone: a polynomial hash, a fresh seed per eight digits. */63+export const hexOf = (label: string, count: number): string => {64+ let out = "";65+66+ for (let block = 0; out.length < count; block += 1) {67+ let hash = 2_166_136_261 + block * 16_777_619;68+69+ for (const char of `${block}:${label}`) {70+ hash = (hash * 257 + (char.codePointAt(0) ?? 0)) % MODULUS;71+ }72+73+ out += hash.toString(16).padStart(8, "0");74+ }75+76+ return out.slice(0, count);77+};78+79+/** `{ [key]: value }` when there is a value, else nothing: an optional key, spread. */80+export const present = <K extends string, A>(81+ key: K,82+ value: A | undefined83+): Partial<Record<K, A>> =>84+ Option.match(Option.fromUndefinedOr(value), {85+ onNone: () => ({}),86+ onSome: (held) => Record.singleton(key, held),87+ });88+89+/** A commit id made from `label`: an answer's head, which no repo of the world holds. */90+export const headOf = (label: string) => CommitSha.make(hexOf(label, 40));91+92+/** A held-back suite's commitment, made from its area's name. */93+export const suiteOf = (area: string) =>94+ SuiteRoot.make(`sha256:${hexOf(`suite:${area}`, 64)}`);95+96+/** An instant, from `2026-10-07T10:00`, in UTC. */97+export const instant = (text: string): DateTime.Utc =>98+ DateTime.toUtc(DateTime.makeUnsafe(`${text}:00Z`));99+100+// ----------------------------------------------------------- lanes101+102+/** The project's own lanes, by name, with their commands. */103+export type Lanes = Readonly<Record<string, string>>;104+105+/** The lane an ask's own check reports as, and its command. */106+const askLane = (ask: Ask, test: string): readonly [string, string] =>107+ CheckSpec.match(ask.check, {108+ LintToZero: ({ command }) => ["lintToZero", command],109+ Migrate: ({ count }) => ["migrate", count],110+ Ratchet: ({ ratchet }) => ["ratchet", `ratchet ${ratchet}`],111+ RedThenGreen: ({ path }) => ["redThenGreen", test.replace("{path}", path)],112+ SymbolAbsent: ({ count }) => ["symbolAbsent", count],113+ });114+115+// ------------------------------------------------------------ story116+117+/** What one landing carries beside its commit. */118+interface LandingInput {119+ readonly assisted?: readonly AgentTrailer[];120+ readonly at: DateTime.Utc;121+ readonly author: Handle;122+ readonly ask?: AskId;123+ readonly changes: Files;124+ readonly credits: readonly Credit[];125+ readonly heldBack?: string;126+ readonly message: { readonly body: string; readonly subject: string };127+ readonly opened?: AskId;128+ readonly requestId: RequestId;129+ readonly verdict?: Verdict;130+}131+132+/** One claim as the story keeps it. */133+interface Held {134+ readonly at: DateTime.Utc;135+ readonly base: LandedSha;136+ readonly claimant: Handle;137+ readonly lastPush?: DateTime.Utc;138+ readonly state: ClaimState;139+ readonly suite?: SuiteRoot;140+}141+142+/**143+ * A story over `project`'s canonical repo, whose `main` stands at `base`144+ * with `files`: each step writes what the service would, in order.145+ */146+export const storyOf = (input: {147+ readonly base: LandedSha;148+ readonly files: Files;149+ readonly lanes: Lanes;150+ readonly project: ProjectName;151+ readonly test: string;152+ readonly lapseAfter: { readonly hours: number };153+ readonly warnAfter: { readonly hours: number };154+}) =>155+ Effect.gen(function* () {156+ const host = yield* RepoHost;157+ const { project } = input;158+ const repo = RepoName.make(project);159+ const main = RefName.make("refs/heads/main");160+161+ let head = input.base;162+ let { files } = input;163+ const asks = new Map<AskId, Ask>();164+ const events: ProjectEvent[] = [];165+ const verdicts = new Map<AskId, Verdict[]>();166+ const answers: AnswerView[] = [];167+ const landings: LandingView[] = [];168+ const claims = new Map<AskId, Held[]>();169+ const decisions: Decision[] = [];170+ const ledger: LedgerEntry[] = [];171+ const proposals = new Map<ProposalId, HeldProposal>();172+ const logs = new Map<string, KeptLog>();173+ const firstClaims = new Map<Handle, DateTime.Utc>();174+175+ const nextSeq = () => events.length + 1;176+177+ /** One event, numbered next. */178+ const tell = (made: (seq: number) => ProjectEvent) => {179+ events.push(made(nextSeq()));180+ };181+182+ const askOf = (id: AskId) => {183+ const found = asks.get(id);184+185+ if (found === undefined) {186+ throw new Error(`the story names no ask ${id}`);187+ }188+189+ return found;190+ };191+192+ const setAsk = (ask: Ask) => {193+ asks.set(ask.id, ask);194+ };195+196+ const claimOf = (id: AskId) => {197+ const held = claims.get(id)?.at(-1);198+199+ if (held === undefined) {200+ throw new Error(`nobody claimed ${id}`);201+ }202+203+ return held;204+ };205+206+ const moveClaim = (id: AskId, change: (held: Held) => Held) => {207+ const all = claims.get(id) ?? [];208+ const last = claimOf(id);209+210+ claims.set(id, [...all.slice(0, -1), change(last)]);211+ };212+213+ /** A commit of `changes` on main, by the platform for `author`, at `at`. */214+ const commit = (landing: LandingInput) =>215+ Effect.gen(function* () {216+ const into = yield* scratch;217+ const next = overlay(files, landing.changes);218+219+ const sha = yield* into.commit({220+ at: landing.at,221+ author: personIdentity(landing.author),222+ committer: platformIdentity,223+ message: formatLanding({224+ ...present(225+ "ask",226+ landing.ask === undefined227+ ? undefined228+ : { ask: landing.ask, project }229+ ),230+ assisted: landing.assisted ?? [],231+ body: landing.message.body,232+ credits: landing.credits,233+ ...present("heldBack", landing.heldBack),234+ requestId: landing.requestId,235+ subject: landing.message.subject,236+ ...present("verdict", landing.verdict),237+ }),238+ parents: [head],239+ tree: yield* into.tree(next),240+ });241+242+ const outcomes = yield* Effect.orDie(243+ host.push(repo, into.source, [244+ { from: Option.some(head), ref: main, to: sha },245+ ])246+ );247+248+ if (!outcomes.every(RefOutcome.$is("Updated"))) {249+ return yield* Effect.die(`${repo}'s main moved under the fixtures`);250+ }251+252+ const view: LandingView = {253+ assisted: landing.assisted ?? [],254+ author: landing.author,255+ credits: landing.credits,256+ landedAt: landing.at,257+ parent: head,258+ project,259+ requestId: landing.requestId,260+ sha: LandedSha.make(sha),261+ ...present("ask", landing.ask),262+ ...present("opened", landing.opened),263+ ...present("heldBackTrailer", landing.heldBack),264+ ...present("verdict", landing.verdict),265+ };266+267+ files = next;268+ head = view.sha;269+ landings.push(view);270+271+ return view;272+ });273+274+ /** The child of a family that waits on the rest opens once they have all closed. */275+ const familyMoves = (landed: Ask, at: DateTime.Utc) => {276+ if (landed.parent === undefined) {277+ return;278+ }279+280+ for (const child of asks.values()) {281+ if (282+ child.parent === landed.parent &&283+ child.state === "waitingOnParent" &&284+ child.blockedBy.every((id) => asks.get(id)?.state === "closed")285+ ) {286+ const opened: Ask = { ...child, state: "open" };287+288+ setAsk(opened);289+ tell((seq) =>290+ ProjectEvent.cases.AskOpened.make({291+ ask: listingOf(opened),292+ at,293+ seq,294+ })295+ );296+ }297+ }298+ };299+300+ const lanesOf = (301+ ask: Ask,302+ results: Readonly<Record<string, LaneOutcome>>,303+ requestId: RequestId304+ ): readonly LaneResult[] =>305+ [askLane(ask, input.test), ...Object.entries(input.lanes)].flatMap(306+ ([lane, command]) => {307+ const result = results[lane];308+309+ return result === undefined310+ ? []311+ : [312+ {313+ command,314+ durationMs:315+ 800 +316+ (Number.parseInt(hexOf(`${requestId}/${lane}`, 4), 16) %317+ 9000),318+ lane: LaneName.make(lane),319+ result,320+ ...present(321+ "logRef",322+ result === "failed" ? `${requestId}/${lane}` : undefined323+ ),324+ },325+ ];326+ }327+ );328+329+ return {330+ /** An ask's id, read back; the story names only asks it opened. */331+ ask: askOf,332+333+ /**334+ * The asks a decider opens in one landing: their files on main, an335+ * `AskOpened` for each that opens now (a child waiting on the rest336+ * opens later), and the landing, which names the first as opened.337+ */338+ open: (step: {339+ readonly asks: Array.NonEmptyReadonlyArray<340+ Omit<Ask, "openedAt" | "openedIn" | "project">341+ >;342+ readonly at: DateTime.Utc;343+ readonly by: Handle;344+ readonly files: Files;345+ }) =>346+ Effect.gen(function* () {347+ const [first] = step.asks;348+ const children = step.asks.slice(1).map(({ id }) => `- ${id}`);349+350+ const landing = yield* commit({351+ at: step.at,352+ author: step.by,353+ changes: step.files,354+ credits: [{ handle: first.askedBy, role: "Asked-by" }],355+ message: {356+ body:357+ children.length === 0358+ ? first.brief.want359+ : [360+ first.brief.want,361+ "",362+ "Its child asks, the last waiting on the rest:",363+ ...children,364+ ].join("\n"),365+ subject: `Open ask ${first.id}`,366+ },367+ opened: first.id,368+ requestId: RequestId.make(`open-${hexOf(`open:${first.id}`, 40)}`),369+ });370+371+ for (const stated of step.asks) {372+ const ask: Ask = {373+ ...stated,374+ openedAt: step.at,375+ openedIn: landing.sha,376+ project,377+ };378+379+ setAsk(ask);380+381+ if (ask.state === "open") {382+ tell((seq) =>383+ ProjectEvent.cases.AskOpened.make({384+ ask: listingOf(ask),385+ at: step.at,386+ seq,387+ })388+ );389+ }390+ }391+392+ tell((seq) =>393+ ProjectEvent.cases.Landed.make({ at: step.at, landing, seq })394+ );395+396+ return landing;397+ }),398+399+ /** `who` claims `id`; an answer to it is judged by `suite` when its claim pins one. */400+ claim: (id: AskId, who: Handle, at: DateTime.Utc, suite?: SuiteRoot) => {401+ claims.set(id, [402+ ...(claims.get(id) ?? []),403+ {404+ at,405+ base: head,406+ claimant: who,407+ state: "live",408+ ...present("suite", suite),409+ },410+ ]);411+412+ if (!firstClaims.has(who)) {413+ firstClaims.set(who, at);414+ }415+416+ setAsk({ ...askOf(id), state: "claimed" });417+ tell((seq) =>418+ ProjectEvent.cases.Claimed.make({ ask: id, at, claimant: who, seq })419+ );420+ },421+422+ /** The claimant pushes to the claim's fork: its head, named for `round`. */423+ push: (id: AskId, at: DateTime.Utc, round = 1) => {424+ const claimed = claimOf(id);425+ const pushed = headOf(`${project}/${id}/${claimed.claimant}/${round}`);426+427+ moveClaim(id, (held) => ({ ...held, lastPush: at, state: "live" }));428+ tell((seq) =>429+ ProjectEvent.cases.Pushed.make({ ask: id, at, head: pushed, seq })430+ );431+432+ return pushed;433+ },434+435+ /**436+ * The answer at `pushed` checked: its verdict, kept as a round of the437+ * ask, and a `Judged` event with where it stands.438+ */439+ judge: (440+ id: AskId,441+ pushed: CommitSha,442+ step: {443+ readonly at: DateTime.Utc;444+ readonly heldBack?: readonly HeldBackResult[];445+ readonly lanes: Readonly<Record<string, LaneOutcome>>;446+ readonly outcome: Outcome;447+ readonly stage: StageName;448+ readonly logs?: Readonly<Record<string, string>>;449+ }450+ ) => {451+ const ask = askOf(id);452+ const claimed = claimOf(id);453+ const requestId = RequestId.make(`push-${pushed}-${claimed.claimant}`);454+ const lanes = lanesOf(ask, step.lanes, requestId);455+456+ const verdict: Verdict = {457+ ask: id,458+ at: step.at,459+ base: claimed.base,460+ checkVersion: CheckVersion.make(461+ `${askLane(ask, input.test)[0]}@0.0.0+${hexOf(`version:${id}`, 16)}`462+ ),463+ head: pushed,464+ heldBack: step.heldBack ?? [],465+ lanes,466+ outcome: step.outcome,467+ patchId: PatchId.make(hexOf(`patch:${pushed}`, 64)),468+ project,469+ stage: step.stage,470+ tree: TreeSha.make(hexOf(`tree:${pushed}`, 40)),471+ verifier: "platform",472+ };473+474+ for (const lane of lanes) {475+ const text = step.logs?.[lane.lane];476+477+ if (lane.logRef !== undefined && text !== undefined) {478+ logs.set(lane.logRef, {479+ claimant: claimed.claimant,480+ lane: lane.lane,481+ text,482+ });483+ }484+ }485+486+ verdicts.set(id, [...(verdicts.get(id) ?? []), verdict]);487+ answers.push({488+ ask: id,489+ at: step.at,490+ head: pushed,491+ outcome: step.outcome,492+ requestId,493+ });494+ tell((seq) =>495+ ProjectEvent.cases.Judged.make({496+ ask: id,497+ at: step.at,498+ head: pushed,499+ outcome: step.outcome,500+ seq,501+ })502+ );503+504+ return verdict;505+ },506+507+ /**508+ * The ask's last judged answer lands: a platform commit of `changes`509+ * crediting the asker, the answerer and anyone who decided on it,510+ * then `Landed` and `AskClosed`, and the family's next step opens511+ * once every sibling has landed.512+ */513+ land: (514+ id: AskId,515+ step: {516+ readonly assisted?: readonly AgentTrailer[];517+ readonly at: DateTime.Utc;518+ readonly changes: Files;519+ readonly decidedBy?: Handle;520+ }521+ ) =>522+ Effect.gen(function* () {523+ const ask = askOf(id);524+ const claimed = claimOf(id);525+ const rounds = verdicts.get(id) ?? [];526+ const last = rounds.at(-1);527+528+ if (last === undefined) {529+ return yield* Effect.die(`${id} has no judged answer to land`);530+ }531+532+ const trailer = Array.isReadonlyArrayNonEmpty(last.heldBack)533+ ? last.heldBack534+ .map(535+ ({ area, passed, suite, total }) =>536+ `${area} ${passed}/${total} @ ${suite}`537+ )538+ .join("; ")539+ : undefined;540+541+ const credits: Credit[] = [542+ { handle: ask.askedBy, role: "Asked-by" },543+ { handle: claimed.claimant, role: "Signed-off-by" },544+ ...(step.decidedBy === undefined545+ ? []546+ : [{ handle: step.decidedBy, role: "Decided-by" as const }]),547+ ...(ask.mentor === undefined548+ ? []549+ : [{ handle: ask.mentor, role: "Mentored-by" as const }]),550+ ];551+552+ // The landing's sha is the commit's: the verdict it carries553+ // names it once the commit exists.554+ const landing = yield* commit({555+ ask: id,556+ at: step.at,557+ author: claimed.claimant,558+ changes: step.changes,559+ credits,560+ message: { body: ask.brief.want, subject: `Answer ${id}` },561+ requestId: RequestId.make(`push-${last.head}-${claimed.claimant}`),562+ verdict: last,563+ ...present("assisted", step.assisted),564+ ...present("heldBack", trailer),565+ });566+567+ const outcome = Outcome.cases.Landed.make({ sha: landing.sha });568+ const verdict: Verdict = { ...last, outcome };569+ const view: LandingView = { ...landing, verdict };570+571+ landings[landings.length - 1] = view;572+ verdicts.set(id, [...rounds.slice(0, -1), verdict]);573+574+ const answered = answers.findLastIndex(575+ (answer) => answer.ask === id && answer.head === last.head576+ );577+578+ if (answered !== -1) {579+ const was = answers[answered];580+581+ if (was !== undefined) {582+ answers[answered] = { ...was, outcome };583+ }584+ }585+586+ moveClaim(id, (held) => ({ ...held, state: "answered" }));587+588+ const closed: Ask = { ...ask, state: "closed" };589+590+ setAsk(closed);591+ tell((seq) =>592+ ProjectEvent.cases.Landed.make({ at: step.at, landing: view, seq })593+ );594+ tell((seq) =>595+ ProjectEvent.cases.AskClosed.make({596+ ask: id,597+ at: step.at,598+ landing: landing.sha,599+ seq,600+ })601+ );602+ familyMoves(closed, step.at);603+604+ return view;605+ }),606+607+ /**608+ * The checks still running on the ask's last answer finish with609+ * `lanes`, and it passes every stage: its verdict, kept, stands at the610+ * last stage until it lands.611+ */612+ finishChecks: (613+ id: AskId,614+ lanes: Readonly<Record<string, LaneOutcome>>615+ ) => {616+ const rounds = verdicts.get(id) ?? [];617+ const last = rounds.at(-1);618+619+ if (last !== undefined) {620+ const requestId = RequestId.make(621+ `push-${last.head}-${claimOf(id).claimant}`622+ );623+624+ verdicts.set(id, [625+ ...rounds.slice(0, -1),626+ {627+ ...last,628+ lanes: lanesOf(askOf(id), lanes, requestId),629+ outcome: Outcome.cases.Checking.make({ stage: "human" }),630+ stage: "human",631+ },632+ ]);633+ }634+ },635+636+ /** A landing that answers no ask: a release from a layer, a decider's own change. */637+ landOwn: (step: {638+ readonly at: DateTime.Utc;639+ readonly author: Handle;640+ readonly changes: Files;641+ readonly credits: readonly Credit[];642+ readonly message: { readonly body: string; readonly subject: string };643+ }) =>644+ Effect.gen(function* () {645+ const view = yield* commit({646+ ...step,647+ requestId: RequestId.make(648+ `land-${hexOf(`land:${step.message.subject}`, 40)}`649+ ),650+ });651+652+ tell((seq) =>653+ ProjectEvent.cases.Landed.make({ at: step.at, landing: view, seq })654+ );655+656+ return view;657+ }),658+659+ /** The claim is warned: no push for a while. */660+ warn: (id: AskId, at: DateTime.Utc) => {661+ moveClaim(id, (held) => ({ ...held, state: "warned" }));662+ tell((seq) => ProjectEvent.cases.Warned.make({ ask: id, at, seq }));663+ },664+665+ /** The claim lapsed, and the ask is open again. */666+ lapse: (id: AskId, at: DateTime.Utc) => {667+ moveClaim(id, (held) => ({ ...held, state: "lapsed" }));668+ setAsk({ ...askOf(id), state: "open" });669+ tell((seq) => ProjectEvent.cases.Lapsed.make({ ask: id, at, seq }));670+ },671+672+ /** The claimant let the ask go, and it is open again. */673+ release: (id: AskId, at: DateTime.Utc) => {674+ moveClaim(id, (held) => ({ ...held, state: "released" }));675+ setAsk({ ...askOf(id), state: "open" });676+ tell((seq) => ProjectEvent.cases.Released.make({ ask: id, at, seq }));677+ },678+679+ /** A decision put to its deciders. */680+ decision: (decision: Decision) => {681+ decisions.push(decision);682+ },683+684+ /** A decider takes a decision put earlier. */685+ decide: (id: Decision["id"], taken: NonNullable<Decision["decided"]>) => {686+ const index = decisions.findIndex((each) => each.id === id);687+ const found = decisions[index];688+689+ if (found === undefined) {690+ throw new Error(`no decision ${id}`);691+ }692+693+ decisions[index] = { ...found, decided: taken };694+ tell((seq) =>695+ ProjectEvent.cases.Decided.make({696+ at: taken.at,697+ choice: taken.choice,698+ decision: id,699+ seq,700+ })701+ );702+ },703+704+ /** A ledger entry, numbered next in the ledger, and its event. */705+ record: (entry: (seq: number) => LedgerEntry) => {706+ const made = entry(ledger.length + 1);707+708+ ledger.push(made);709+ tell((seq) =>710+ ProjectEvent.cases.LedgerAppended.make({711+ at: made.at,712+ entry: made,713+ seq,714+ })715+ );716+ },717+718+ /** A proposal opened, as anyone reads it now, and its events. */719+ propose: (720+ held: HeldProposal,721+ settled?: { readonly at: DateTime.Utc; readonly ready: boolean }722+ ) => {723+ proposals.set(held.proposal.id, held);724+ tell((seq) =>725+ ProjectEvent.cases.ProposalOpened.make({726+ at: held.proposal.openedAt,727+ proposal: held.proposal.id,728+ seq,729+ })730+ );731+732+ if (settled !== undefined) {733+ tell((seq) =>734+ ProjectEvent.cases.ProposalDrafted.make({735+ at: settled.at,736+ proposal: held.proposal.id,737+ ready: settled.ready,738+ seq,739+ })740+ );741+ }742+ },743+744+ /** A later round of a proposal's draft settled. */745+ drafted: (id: ProposalId, at: DateTime.Utc, ready: boolean) => {746+ tell((seq) =>747+ ProjectEvent.cases.ProposalDrafted.make({748+ at,749+ proposal: id,750+ ready,751+ seq,752+ })753+ );754+ },755+756+ /** A decider accepted the proposal: it is closed, and its ask opens. */757+ accepted: (id: ProposalId) => {758+ const held = proposals.get(id);759+760+ if (held !== undefined) {761+ proposals.set(id, {762+ ...held,763+ proposal: { ...held.proposal, state: "accepted" },764+ });765+ }766+ },767+768+ /** A tag on `sha`, as a release names it. */769+ tag: (name: string, sha: LandedSha) =>770+ Effect.gen(function* () {771+ const into = yield* scratch;772+773+ yield* Effect.orDie(774+ host.push(repo, into.source, [775+ {776+ from: Option.none(),777+ ref: RefName.make(`refs/tags/${name}`),778+ to: sha,779+ },780+ ])781+ );782+ }),783+784+ /** Main's landed commit now. */785+ head: () => head,786+787+ /** The record the story wrote, with what it keeps apart from the story. */788+ told: (789+ apart: Pick<FixtureRecord, "env" | "ledger"> & {790+ readonly working: readonly Handle[];791+ }792+ ): FixtureRecord => {793+ const claimViews = [...claims].flatMap(([ask, held]) =>794+ held.map((each): ClaimView => ({795+ ask,796+ base: each.base,797+ checkCommand: `${Brand.cli} check`,798+ claimant: each.claimant,799+ fork: RepoName.make(`${project}--${ask}--${each.claimant}`),800+ lapsesAt: DateTime.add(each.lastPush ?? each.at, input.lapseAfter),801+ openedAt: each.at,802+ project,803+ remote: `/${project}--${ask}--${each.claimant}.git`,804+ state: each.state,805+ warnsAt: DateTime.add(each.lastPush ?? each.at, input.warnAfter),806+ ...present("lastPushAt", each.lastPush),807+ ...present("suite", each.suite),808+ }))809+ );810+811+ const forks: readonly ForkRef[] = [812+ ...claimViews.map((claim): ForkRef => ({813+ ask: claim.ask,814+ handle: claim.claimant,815+ kind: "claim",816+ repo: claim.fork,817+ state: claim.state,818+ })),819+ ...apart.working.map((handle): ForkRef => ({820+ handle,821+ kind: "working",822+ repo: RepoName.make(`${project}--me--${handle}`),823+ })),824+ ];825+826+ // A copy of each part: a later step writes the story's own arrays827+ // and maps in place, and a record already served must not change828+ // under a read while that step is under way.829+ return {830+ answers: [...answers],831+ asks: new Map(asks),832+ claims: claimViews,833+ decisions: [...decisions],834+ env: apart.env,835+ events: [...events],836+ firstClaims: [...firstClaims].map(([handle, at]) => ({ at, handle })),837+ forks,838+ head,839+ landings: [...landings],840+ ledger: { ...apart.ledger, entries: [...ledger] },841+ logs: new Map(logs),842+ proposals: new Map(proposals),843+ verdicts: new Map(verdicts),844+ };845+ },846+ };847+ });848+849+/** A story under way: its steps, and the record it has written so far. */850+export type Story = Effect.Success<ReturnType<typeof storyOf>>;added:apps/web/src/dev/fixtures/vellum.ts+1978 added
1+/**2+ * vellum: the fixture project, a six-package library that reads and3+ * writes a small document format, with its held-back checks in two areas4+ * (export and parser) and a write-only token for its error reports. Its5+ * record is told as a story (`story.ts`) from its first asks in September6+ * to the morning the world stands at, so each state a page draws is there7+ * once, reached the way the service would reach it:8+ *9+ * - answers: checking, waiting on a decision, waiting for a finish,10+ * waiting on another ask, refused at Shape, at the held-back stage and at11+ * the checks, landed with a decision and held-back results, landed with12+ * neither, and one in its third round;13+ * - asks: open, held for newcomers, claimed with and without a push, a14+ * released claim, a lapsed one, and a want too long for a title;15+ * - two families: one with a child in every mark and its delete child16+ * waiting, one whose children all landed and whose delete child opened;17+ * - a decision of every kind, two taken this morning, one due within the18+ * day; proposals drafting, ready and failed;19+ * - a ledger with a layer, two committed areas and history of every kind,20+ * an env shape with a write-only item someone set, and a policy that21+ * names deciders by path and one denounced person.22+ *23+ * Its people are the examples' own (`examples.ts`, `seed.ts`): `ines-v`24+ * decides, `okonkwo` decides the export package, the env schema and the25+ * vouch file, `lin-h` decides the config folder with her; `bram`,26+ * `okafor` and `lin-h` have answered here for weeks; `tove` and `sefa`27+ * are new; `wren` is denounced.28+ */29+import { Brand } from "@repo/brand";30+import { childId, deleteChildId } from "@repo/project/migrate";31+import type { HeldBackResult } from "@repo/protocol/domain/answer";32+import type { Ask } from "@repo/protocol/domain/ask";33+import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";34+import { Command, JsonPath, SymbolName } from "@repo/protocol/domain/common";35+import type { Decision, DecisionSubject } from "@repo/protocol/domain/decision";36+import { DecisionSubject as Subject } from "@repo/protocol/domain/decision";37+import type { EnvSchemaView } from "@repo/protocol/domain/env";38+import { Outcome } from "@repo/protocol/domain/outcome";39+import { DraftState } from "@repo/protocol/domain/proposal";40+import type { Proposal } from "@repo/protocol/domain/proposal";41+import { Territory } from "@repo/protocol/domain/territory";42+import { LedgerEntry } from "@repo/protocol/domain/visibility";43+import type { Ledger } from "@repo/protocol/domain/visibility";44+import type { Handle, LandedSha } from "@repo/protocol/ids";45+import {46+ AreaName,47+ AskId,48+ DecisionId,49+ EnvKey,50+ KindName,51+ LaneName,52+ LayerName,53+ ProjectName,54+ ProposalId,55+ RatchetName,56+ RepoName,57+ RepoPath,58+} from "@repo/protocol/ids";59+import {60+ ChecksFailed,61+ HeldBackFailed,62+ OutOfScope,63+ Weakened,64+} from "@repo/protocol/refusal";65+import { Array, DateTime, Effect, Schema } from "effect";66+67+import {68+ askFileOf,69+ burrowPeople,70+ datekitPeople,71+ policyJson,72+} from "../examples.ts";73+import type { StatedAsk } from "../examples.ts";74+import type { Files } from "../git.ts";75+import { visitors } from "../seed.ts";76+import { checkOf } from "./fillers.ts";77+import { headOf, instant, present, storyOf, suiteOf } from "./story.ts";78+import type { Story } from "./story.ts";79+80+export const vellum = ProjectName.make("vellum");81+82+/** Where the world's clock stands once the fixtures are told. */83+export const fixturesNow = instant("2026-10-07T10:00");84+85+/** When vellum's first commit was pushed, by its initializer. */86+export const vellumStart = instant("2026-08-24T09:00");87+88+const dir = Brand.configDir;89+90+const people = {91+ bram: datekitPeople.contributor,92+ ines: datekitPeople.decider,93+ lin: burrowPeople.second,94+ okafor: burrowPeople.decider,95+ okonkwo: datekitPeople.zones,96+ sefa: visitors.flagger,97+ tove: visitors.proposer,98+ wren: visitors.regular,99+} as const;100+101+/** vellum's initializer, who decides everything not named for someone else. */102+export const vellumInitializer = people.ines;103+104+const MODULES = [105+ "cli",106+ "export",107+ "lint",108+ "parser",109+ "render",110+ "themes",111+] as const;112+113+type Module = (typeof MODULES)[number];114+115+const moduleName = (module: Module) => `@vellum/${module}`;116+117+const territoryOf = (module: Module): Territory => ({118+ module: moduleName(module),119+ paths: [120+ Schema.decodeSync(Territory.fields.paths)([`packages/${module}/**`])[0],121+ ],122+});123+124+const LANES = {125+ lint: "bun run lint",126+ types: "bun run typecheck",127+ unit: "bun test",128+} as const;129+130+const TEST = "bun test {path}";131+132+const MAIN_REF = Schema.decodeSync(Subject.cases.StrayPush.fields.ref)(133+ "refs/heads/main"134+);135+136+const WIDER_HOSTS = Schema.decodeSync(Subject.cases.ProxyWidened.fields.hosts)([137+ "sentry.io",138+ "ingest.sentry.io",139+]);140+141+// The areas whose checks the maintainers hold back, and their commitments.142+const EXPORT = AreaName.make("export");143+144+const PARSER = AreaName.make("parser");145+146+const exportSuite = suiteOf("export");147+148+const parserSuite = suiteOf("parser");149+150+const held = (151+ area: AreaName,152+ passed: number,153+ total: number154+): HeldBackResult => ({155+ area,156+ passed,157+ suite: area === EXPORT ? exportSuite : parserSuite,158+ total,159+});160+161+// --------------------------------------------------------------- files162+163+const encodeCheck = Schema.encodeSync(CheckSpec);164+165+const COUNT = Command.make("bun scripts/count-callers.ts oldTokenize --json");166+167+const COUNT_PAGES = Command.make(168+ "bun scripts/count-callers.ts pageSize --json"169+);170+171+const packageJson = (module: Module) =>172+ `${JSON.stringify(173+ {174+ exports: { ".": "./src/index.ts" },175+ name: moduleName(module),176+ type: "module",177+ },178+ null,179+ 2180+ )}\n`;181+182+/** A module's entry, calling the old tokenizer twice. */183+const entryOf = (module: Module, tokenize: string) =>184+ [185+ `import { ${tokenize} } from "@vellum/parser/tokenize";`,186+ "",187+ `/** ${moduleName(module)}: reads a document's words, then its marks. */`,188+ `export const words = (text: string) => ${tokenize}(text).filter((token) => token.kind === "word");`,189+ "",190+ `export const marks = (text: string) => ${tokenize}(text).filter((token) => token.kind === "mark");`,191+ "",192+ ].join("\n");193+194+/** A module's page settings, under the old name or the new. */195+const pageOf = (module: Module, name: string) =>196+ [197+ `/** ${moduleName(module)}'s page: A4 unless a theme says otherwise. */`,198+ `export const ${name} = { height: 297, width: 210 } as const;`,199+ "",200+ ].join("\n");201+202+const PAGED: readonly Module[] = ["cli", "render", "themes"];203+204+const ENV_SCHEMA = [205+ "# vellum's environment. Values never live in the repo.",206+ "",207+ "# @sensitive @required",208+ "# @type=string(startsWith=sntrys_)",209+ "# @docsUrl=https://docs.sentry.io/account/auth-tokens/",210+ "# Uploads source maps and error reports from `vellum export`.",211+ "SENTRY_AUTH_TOKEN=",212+ "",213+ "# @type=url",214+ "# Where error reports go; public.",215+ "SENTRY_DSN=",216+ "",217+ "# @type=string",218+ "# A folder of fonts the PDF export embeds.",219+ "VELLUM_FONT_DIR=",220+ "",221+ "# @deprecated The PDF export no longer shells out; it is ignored.",222+ "LEGACY_PDF_ENGINE=",223+ "",224+].join("\n");225+226+/** How many decisions a vellum decider takes a day (its `policy.json`'s budget). */227+export const decisionsPerDay = 5;228+229+/** How long a claim goes without a push before it is warned, then lapses. */230+const CLAIMS = { lapseAfter: { hours: 96 }, warnAfter: { hours: 48 } } as const;231+232+const HOUR_MS = 3_600_000;233+234+const policy = policyJson({235+ asks: [],236+ budget: { decisionsPerDay, expireDays: 3 },237+ caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },238+ claims: {239+ lapseAfterMs: CLAIMS.lapseAfter.hours * HOUR_MS,240+ warnAfterMs: CLAIMS.warnAfter.hours * HOUR_MS,241+ },242+ deciders: [243+ { handles: [people.ines], paths: "**" },244+ { handles: [people.ines, people.lin], paths: `${dir}/**` },245+ { handles: [people.okonkwo], paths: "packages/export/**" },246+ { handles: [people.okonkwo], paths: ".env.schema" },247+ { handles: [people.okonkwo], paths: `${dir}/vouched.td` },248+ ],249+ functions: { admit: false, opensAlone: false },250+ kinds: [251+ {252+ checkKind: "redThenGreen",253+ claimers: "vouched",254+ finish: "optional",255+ name: "fix",256+ oneWay: false,257+ race: 1,258+ requires: ["want", "check", "territory"],259+ strength: "assertion",260+ },261+ {262+ checkKind: "redThenGreen",263+ claimers: "vouched",264+ finish: "required",265+ name: "polish",266+ oneWay: false,267+ race: 1,268+ requires: ["want", "check", "territory"],269+ strength: "assertion",270+ },271+ {272+ checkKind: "migrate",273+ claimers: "vouched",274+ finish: "never",275+ name: "migrate",276+ oneWay: false,277+ race: 1,278+ requires: ["want", "check", "territory"],279+ strength: "assertion",280+ },281+ ],282+ ratchets: [283+ {284+ measure: Schema.encodeSync(RatchetMeasure)(285+ RatchetMeasure.cases.Metric.make({286+ command: Command.make("bun scripts/bundle-size.ts --json"),287+ path: JsonPath.make("$.bytes"),288+ })289+ ),290+ name: "bundle-bytes",291+ },292+ ],293+ run: { checks: LANES, test: TEST },294+ source: "config",295+ weakening: { markers: [".skip(", ".only(", ".todo("] },296+});297+298+/** vellum's first push: six packages, its config folder and its env schema. */299+export const vellumFiles: Files = new Map([300+ [301+ "README.md",302+ [303+ "# vellum",304+ "",305+ "Reads and writes a small document format: a parser, a renderer, themes, a linter, an exporter (HTML, EPUB and PDF) and a CLI.",306+ "",307+ "A fictional project: it and its people are invented.",308+ "",309+ ].join("\n"),310+ ],311+ [312+ "package.json",313+ `${JSON.stringify(314+ {315+ name: "vellum",316+ private: true,317+ scripts: {318+ lint: "oxlint",319+ test: "bun test",320+ typecheck: "tsc --noEmit",321+ },322+ workspaces: ["packages/*"],323+ },324+ null,325+ 2326+ )}\n`,327+ ],328+ [".env.schema", ENV_SCHEMA],329+ [330+ "scripts/count-callers.ts",331+ [332+ "// Prints how many times each package calls a name, as JSON.",333+ 'import { Glob } from "bun";',334+ "",335+ "const [name] = Bun.argv.slice(2);",336+ "const byModule: Record<string, number> = {};",337+ "",338+ 'for await (const path of new Glob("packages/*/src/**/*.ts").scan()) {',339+ ' const module = "@vellum/" + path.split("/")[1];',340+ ' byModule[module] = (byModule[module] ?? 0) + ((await Bun.file(path).text()).split(name + "(").length - 1);',341+ "}",342+ "",343+ "console.log(JSON.stringify({ byModule, total: Object.values(byModule).reduce((a, b) => a + b, 0) }));",344+ "",345+ ].join("\n"),346+ ],347+ ...MODULES.flatMap((module): (readonly [string, string])[] => [348+ [`packages/${module}/package.json`, packageJson(module)],349+ [350+ `packages/${module}/src/index.ts`,351+ module === "parser"352+ ? [353+ "export interface Token {",354+ ' readonly kind: "word" | "mark";',355+ " readonly text: string;",356+ "}",357+ "",358+ 'export { oldTokenize, tokenize } from "./tokenize.ts";',359+ "",360+ ].join("\n")361+ : entryOf(module, "oldTokenize"),362+ ],363+ ]),364+ [365+ "packages/parser/src/tokenize.ts",366+ [367+ 'import type { Token } from "./index.ts";',368+ "",369+ "const read = (text: string): Token[] =>",370+ " text.split(/(\\s+|[*_`#>])/u).filter(Boolean).map((part) => ({",371+ ' kind: /^[*_`#>]$/u.test(part) ? "mark" : "word",',372+ " text: part,",373+ " }));",374+ "",375+ "/** The tokenizer every package moves to. */",376+ "export const tokenize = read;",377+ "",378+ "/** The first tokenizer, kept until nothing calls it. */",379+ "export const oldTokenize = (text: string): Token[] => read(text.trim());",380+ "",381+ ].join("\n"),382+ ],383+ ...PAGED.map(384+ (module) =>385+ [`packages/${module}/src/page.ts`, pageOf(module, "pageSize")] as const386+ ),387+ [`${dir}/policy.json`, policy],388+ [389+ `${dir}/vouched.td`,390+ [391+ "# The people vellum's deciders vouch for.",392+ people.bram,393+ people.okafor,394+ people.lin,395+ `${people.tove} Started with the CLI docs.`,396+ `${people.sefa} Came from the parser's issue thread.`,397+ `-${people.wren} Opened proposals that advertised a paid fork.`,398+ "",399+ ].join("\n"),400+ ],401+]);402+403+// ---------------------------------------------------------------- asks404+405+/** An ask as the story opens it: everything but where and when it opened. */406+type Stated = Omit<Ask, "openedAt" | "openedIn" | "project">;407+408+const fix = (input: {409+ readonly id: string;410+ readonly module: Module;411+ /** A territory other than the module's own. */412+ readonly territory?: Territory;413+ readonly want: string;414+ readonly current?: string;415+ readonly askedBy?: Handle;416+ readonly kind?: "fix" | "polish";417+ readonly blockedBy?: readonly AskId[];418+ readonly mentor?: Handle;419+}): Stated => {420+ const id = AskId.make(input.id);421+422+ const territory = input.territory ?? territoryOf(input.module);423+ const home = `packages/${input.module}`;424+425+ return {426+ askedBy: input.askedBy ?? people.ines,427+ blockedBy: input.blockedBy ?? [],428+ brief: {429+ want: input.want,430+ ...present("current", input.current),431+ },432+ check: CheckSpec.cases.RedThenGreen.make({433+ path: RepoPath.make(`${home}/test/asks/${input.id}.test.ts`),434+ }),435+ file: RepoPath.make(`${dir}/asks/${input.id}.ask.ts`),436+ id,437+ kind: KindName.make(input.kind ?? "fix"),438+ state: "open",439+ territory,440+ ...present("mentor", input.mentor),441+ ...present(442+ "reserve",443+ input.mentor === undefined ? undefined : ("newcomers" as const)444+ ),445+ };446+};447+448+/** The ask's file as its maintainer writes it, and its check's test. */449+const filesOf = (asks: readonly Stated[]): Files =>450+ new Map(451+ asks.flatMap((ask) => {452+ const stated: StatedAsk = {453+ askedBy: ask.askedBy,454+ blockedBy: [...ask.blockedBy],455+ brief: ask.brief,456+ check: encodeCheck(ask.check),457+ file: ask.file,458+ id: ask.id,459+ kind: ask.kind,460+ territory: {461+ module: ask.territory.module,462+ paths: [...ask.territory.paths],463+ },464+ ...present("mentor", ask.mentor),465+ ...present("parent", ask.parent),466+ ...present("reserve", ask.reserve),467+ };468+469+ const file = askFileOf(stated);470+471+ const test = CheckSpec.guards.RedThenGreen(ask.check)472+ ? [[ask.check.path, checkOf(ask.id, ask.id, ask.brief.want)] as const]473+ : [];474+475+ return [[file.path, file.content] as const, ...test];476+ })477+ );478+479+/** A migrate ask split as the service splits one: a child per module, then the delete child. */480+const familyOf = (input: {481+ readonly id: string;482+ readonly from: string;483+ readonly to: string;484+ readonly count: Command;485+ readonly modules: Array.NonEmptyReadonlyArray<Module>;486+ readonly callers: number;487+}) => {488+ const parentId = AskId.make(input.id);489+490+ const check = CheckSpec.cases.Migrate.make({491+ count: input.count,492+ from: SymbolName.make(input.from),493+ to: SymbolName.make(input.to),494+ });495+496+ const whole: Territory = {497+ module: ".",498+ paths: Array.map(input.modules, (module) => territoryOf(module).paths[0]),499+ };500+501+ const member = (502+ id: AskId,503+ own: Pick<Stated, "blockedBy" | "brief" | "check" | "state" | "territory">504+ ): Stated => ({505+ askedBy: people.ines,506+ file: RepoPath.make(`${dir}/asks/${id}.ask.ts`),507+ id,508+ kind: KindName.make("migrate"),509+ parent: parentId,510+ ...own,511+ });512+513+ const children = Array.map(input.modules, (module) =>514+ member(childId(parentId, moduleName(module)), {515+ blockedBy: [],516+ brief: {517+ want: `${moduleName(module)}: ${input.callers} callers of ${input.from} → ${input.to}`,518+ },519+ check,520+ state: "open",521+ territory: territoryOf(module),522+ })523+ );524+525+ const ids = children.map(({ id }) => id);526+ const deleteId = deleteChildId(parentId);527+528+ const last = member(deleteId, {529+ blockedBy: ids,530+ brief: { want: `Delete ${input.from}: nothing calls it any more` },531+ check: CheckSpec.cases.SymbolAbsent.make({532+ count: input.count,533+ symbol: SymbolName.make(input.from),534+ }),535+ state: "waitingOnParent",536+ territory: whole,537+ });538+539+ const parent: Stated = {540+ askedBy: people.ines,541+ blockedBy: [...ids, deleteId],542+ brief: {543+ want: `Replace every call to ${input.from} with ${input.to}, then delete ${input.from}.`,544+ },545+ check,546+ file: RepoPath.make(`${dir}/asks/${input.id}.ask.ts`),547+ id: parentId,548+ kind: KindName.make("migrate"),549+ state: "open",550+ territory: whole,551+ };552+553+ return {554+ asks: Array.make(parent, ...children, last),555+ child: (module: Module) => childId(parentId, moduleName(module)),556+ };557+};558+559+const tokenizer = familyOf({560+ callers: 2,561+ count: COUNT,562+ from: "oldTokenize",563+ id: "retire-old-tokenizer",564+ modules: ["cli", "export", "lint", "parser", "render", "themes"],565+ to: "tokenize",566+});567+568+const pageSize = familyOf({569+ callers: 1,570+ count: COUNT_PAGES,571+ from: "pageSize",572+ id: "rename-page-size",573+ modules: ["cli", "render", "themes"],574+ to: "pageFormat",575+});576+577+const ask = {578+ carry: fix({579+ current: "An EPUB export drops every footnote.",580+ id: "carry-footnotes-to-epub",581+ module: "parser",582+ territory: {583+ module: ".",584+ paths: Schema.decodeSync(Territory.fields.paths)([585+ "packages/parser/src/footnotes.ts",586+ "packages/export/src/epub.ts",587+ ]),588+ },589+ want: "Footnotes the parser reads reach the EPUB export as linked endnotes.",590+ }),591+ cliVersion: fix({592+ id: "cli-version-flag",593+ module: "cli",594+ want: "vellum --version prints the version and exits 0.",595+ }),596+ docs: fix({597+ current: "vellum --help lists flags with no word on what they do.",598+ id: "document-cli-flags",599+ mentor: people.okonkwo,600+ module: "cli",601+ want: "vellum --help says what each flag does, in one line each.",602+ }),603+ escape: fix({604+ id: "escape-attribute-quotes",605+ module: "render",606+ want: "The HTML renderer escapes quotes inside attribute values.",607+ }),608+ exportErrors: fix({609+ id: "report-export-errors",610+ module: "export",611+ want: "A failed export reports its error, with the document's path, to the project's error tracker.",612+ }),613+ exportPages: fix({614+ id: "export-page-numbers",615+ module: "export",616+ want: "The PDF export prints page numbers in the footer.",617+ }),618+ headings: fix({619+ askedBy: people.tove,620+ id: "lint-heading-levels",621+ module: "lint",622+ want: "The linter reports a heading that skips a level, such as a level-two heading followed by a level-four one, with the line of the skip.",623+ }),624+ nested: fix({625+ id: "render-nested-lists",626+ module: "render",627+ want: "A list nested three deep renders with its indentation.",628+ }),629+ backrefs: fix({630+ blockedBy: [AskId.make("number-footnotes")],631+ id: "footnote-backrefs",632+ module: "render",633+ want: "Each footnote links back to where it is cited.",634+ }),635+ codeBlocks: fix({636+ id: "render-code-blocks",637+ module: "render",638+ want: "A fenced code block keeps its blank lines.",639+ }),640+ numbers: fix({641+ id: "number-footnotes",642+ module: "parser",643+ want: "The parser numbers footnotes in the order they are cited.",644+ }),645+ quotes: fix({646+ id: "parse-smart-quotes",647+ module: "parser",648+ want: "The parser reads curly quotes as quotes.",649+ }),650+ altText: fix({651+ id: "export-alt-text",652+ module: "export",653+ want: "The HTML export keeps an image's alt text.",654+ }),655+ palette: fix({656+ id: "themes-dark-palette",657+ module: "themes",658+ want: "The default theme has a dark palette.",659+ }),660+ trim: fix({661+ id: "trim-trailing-spaces",662+ module: "lint",663+ want: "The linter reports trailing spaces at the end of a line.",664+ }),665+ wrap: fix({666+ id: "wrap-long-table-cells",667+ kind: "polish",668+ module: "render",669+ want: "A table cell longer than the column wraps instead of widening the table.",670+ }),671+} as const;672+673+/** An answer's change: one file in the ask's own module. */674+const answerFiles = (stated: Stated, body: string): Files => {675+ const home =676+ stated.territory.module === "."677+ ? "packages/parser"678+ : `packages/${stated.territory.module.replace("@vellum/", "")}`;679+680+ return new Map([681+ [682+ `${home}/src/${stated.id}.ts`,683+ [`/** ${stated.brief.want} */`, body, ""].join("\n"),684+ ],685+ ]);686+};687+688+const passed = { lint: "passed", types: "passed", unit: "passed" } as const;689+690+const allPassed = (askLane: string) =>691+ ({ ...passed, [askLane]: "passed" }) as const;692+693+// ----------------------------------------------------------- decisions694+695+const decisionId = (n: number) =>696+ DecisionId.make(`dec-${String(n).padStart(6, "0")}`);697+698+const proposalId = (n: number) =>699+ ProposalId.make(`prop-${String(n).padStart(6, "0")}`);700+701+const EXPIRY = { days: 3 } as const;702+703+const decision = (input: {704+ readonly n: number;705+ readonly at: DateTime.Utc;706+ readonly deciders: Array.NonEmptyReadonlyArray<Handle>;707+ readonly subject: DecisionSubject;708+ readonly evidence: Decision["evidence"];709+ readonly default?: Decision["default"];710+}): Decision => ({711+ deciders: input.deciders,712+ default: input.default ?? "decline",713+ evidence: input.evidence,714+ expiresAt: DateTime.add(input.at, EXPIRY),715+ id: decisionId(input.n),716+ openedAt: input.at,717+ project: vellum,718+ subject: input.subject,719+});720+721+/** The finish's diff: the answer's second round, whose test the first round had narrowed with `.only(`. */722+const WRAP_PATCH = [723+ "diff --git a/packages/render/src/table.ts b/packages/render/src/table.ts",724+ "index 5d1c0e2..a8f4b71 100644",725+ "--- a/packages/render/src/table.ts",726+ "+++ b/packages/render/src/table.ts",727+ "@@ -1,8 +1,14 @@",728+ ' import type { Token } from "@vellum/parser";',729+ " ",730+ "+const MAX_CELL = 40;",731+ "+",732+ " /** One table cell, as HTML. */",733+ "-export const cell = (tokens: Token[]) =>",734+ '- "<td>" + tokens.map((token) => token.text).join("") + "</td>";',735+ "+export const cell = (tokens: Token[]) => {",736+ '+ const text = tokens.map((token) => token.text).join("");',737+ '+ const wrap = text.length > MAX_CELL ? \' style="overflow-wrap:anywhere"\' : "";',738+ "+",739+ '+ return "<td" + wrap + ">" + text + "</td>";',740+ "+};",741+ " ",742+ " /** One table, as HTML. */",743+ " export const table = (rows: Token[][][]) =>",744+ "diff --git a/packages/render/test/table.test.ts b/packages/render/test/table.test.ts",745+ "new file mode 100644",746+ "index 0000000..3b9e2d4",747+ "--- /dev/null",748+ "+++ b/packages/render/test/table.test.ts",749+ "@@ -0,0 +1,18 @@",750+ '+import { expect, test } from "bun:test";',751+ "+",752+ '+import { cell } from "../src/table.ts";',753+ "+",754+ '+const word = (text: string) => ({ kind: "word" as const, text });',755+ "+",756+ '+test("a short cell stays on one line", () => {',757+ '+ expect(cell([word("short")])).toBe("<td>short</td>");',758+ "+});",759+ "+",760+ '+test("a long cell wraps instead of widening its table", () => {',761+ '+ const long = word("a".repeat(64));',762+ "+",763+ '+ expect(cell([long])).toContain("overflow-wrap:anywhere");',764+ "+ expect(cell([long])).toContain(long.text);",765+ "+});",766+ "+",767+ "+// One case per width the renderer supports lives in table.widths.test.ts.",768+ "",769+].join("\n");770+771+// ---------------------------------------------------------------- ledger772+773+/** The ledger's standing parts; its entries are told with the story. */774+const ledger: Ledger = {775+ entries: [],776+ layers: [777+ {778+ audience: "maintainers",779+ disclose: "sealed",780+ holds: ["checks", "notes"],781+ name: LayerName.make("maintainers"),782+ readers: [people.ines, people.okonkwo, people.lin],783+ reason:784+ "Held-back checks for the export and the parser, written by the maintainers so an answer cannot be fitted to them.",785+ repo: RepoName.make("vellum--maintainers"),786+ writers: "deciders",787+ },788+ ],789+ posture: "openWithSealedEvidence",790+ postureLabel: "Open with sealed evidence · sealed checks in export, parser",791+ project: vellum,792+};793+794+/** The env shape at `at`: four items, one write-only and set, none with a value or placeholder. */795+const envAt = (at: LandedSha): EnvSchemaView => ({796+ at,797+ file: RepoPath.make(".env.schema"),798+ imports: [],799+ items: [800+ {801+ description:802+ "Uploads source maps and error reports from `vellum export`.",803+ docs: "https://docs.sentry.io/account/auth-tokens/",804+ key: EnvKey.make("SENTRY_AUTH_TOKEN"),805+ proxy: { domains: ["sentry.io"], path: "/api/**" },806+ required: true,807+ sensitive: true,808+ tags: ["export", "errors"],809+ type: 'string(startsWith="sntrys_")',810+ value: { setAt: instant("2026-10-06T16:30"), setBy: people.ines },811+ },812+ {813+ description: "Where error reports go; public.",814+ key: EnvKey.make("SENTRY_DSN"),815+ required: false,816+ sensitive: false,817+ tags: ["errors"],818+ type: "url",819+ },820+ {821+ description: "A folder of fonts the PDF export embeds.",822+ key: EnvKey.make("VELLUM_FONT_DIR"),823+ required: "depends",824+ sensitive: false,825+ tags: ["export"],826+ type: "string",827+ },828+ {829+ deprecated: true,830+ description: "The PDF export no longer shells out; it is ignored.",831+ key: EnvKey.make("LEGACY_PDF_ENGINE"),832+ required: false,833+ sensitive: false,834+ tags: [],835+ },836+ ],837+ project: vellum,838+});839+840+// ------------------------------------------------------------- proposals841+842+const proposal = (input: {843+ readonly n: number;844+ readonly at: DateTime.Utc;845+ readonly proposer: Handle;846+ readonly want: string;847+ readonly files: readonly RepoPath[];848+ readonly draft?: Proposal["draft"];849+ readonly state?: Proposal["state"];850+}): Proposal => ({851+ expiresAt: DateTime.add(input.at, { days: 14 }),852+ files: input.files,853+ id: proposalId(input.n),854+ openedAt: input.at,855+ project: vellum,856+ proposer: input.proposer,857+ state: input.state ?? "open",858+ want: input.want,859+ ...present("draft", input.draft),860+});861+862+/** A drafted ask's three files: its ask file, its check, and the document the check reads. */863+const draftedFiles = (id: string, module: Module, want: string) => {864+ const stated = fix({ id, module, want });865+ const [askFile, testFile] = [...filesOf([stated])];866+867+ const fixture = [868+ `packages/${module}/test/fixtures/${id}.vm`,869+ "- a list item\n > a quote inside it\n",870+ ] as const;871+872+ return [askFile, testFile, fixture].flatMap((entry) =>873+ entry === undefined874+ ? []875+ : [{ content: entry[1], path: RepoPath.make(entry[0]) }]876+ );877+};878+879+/** A family child's change: its module's entry on the new tokenizer. */880+const childEntry = (module: Module): Files =>881+ new Map([[`packages/${module}/src/index.ts`, entryOf(module, "tokenize")]]);882+883+/** A family child's change: its module's page settings under the new name. */884+const childPage = (module: Module): Files =>885+ new Map([[`packages/${module}/src/page.ts`, pageOf(module, "pageFormat")]]);886+887+// ------------------------------------------------------------- the story888+889+/** The record vellum's story writes, over its canonical repo standing at `base`. */890+export const tellVellum = (base: LandedSha) =>891+ Effect.gen(function* () {892+ const t = instant;893+894+ const story = yield* storyOf({895+ base,896+ files: vellumFiles,897+ lanes: LANES,898+ lapseAfter: CLAIMS.lapseAfter,899+ project: vellum,900+ test: TEST,901+ warnAfter: CLAIMS.warnAfter,902+ });903+904+ const answerAndLand = (input: {905+ readonly stated: Stated;906+ readonly who: Handle;907+ readonly claimed: string;908+ readonly landed: string;909+ readonly lane?: string;910+ readonly heldBack?: readonly HeldBackResult[];911+ readonly changes?: Files;912+ readonly suite?: HeldBackResult["suite"];913+ }) =>914+ Effect.gen(function* () {915+ story.claim(input.stated.id, input.who, t(input.claimed), input.suite);916+917+ const head = story.push(input.stated.id, t(input.landed));918+919+ story.judge(input.stated.id, head, {920+ at: t(input.landed),921+ lanes: allPassed(input.lane ?? "redThenGreen"),922+ outcome: Outcome.cases.Checking.make({ stage: "human" }),923+ stage: "human",924+ ...present("heldBack", input.heldBack),925+ });926+927+ return yield* story.land(input.stated.id, {928+ at: t(input.landed),929+ changes:930+ input.changes ??931+ answerFiles(932+ input.stated,933+ `export const answered = ${JSON.stringify(input.stated.id)};`934+ ),935+ });936+ });937+938+ // September: the first asks, answered by the people who have been here longest.939+ yield* story.open({940+ asks: [ask.quotes],941+ at: t("2026-09-01T10:00"),942+ by: people.ines,943+ files: filesOf([ask.quotes]),944+ });945+ yield* answerAndLand({946+ claimed: "2026-09-02T10:00",947+ landed: "2026-09-03T14:00",948+ stated: ask.quotes,949+ who: people.bram,950+ });951+ yield* story.open({952+ asks: [ask.altText],953+ at: t("2026-09-09T10:00"),954+ by: people.ines,955+ files: filesOf([ask.altText]),956+ });957+ yield* answerAndLand({958+ claimed: "2026-09-10T09:00",959+ landed: "2026-09-11T11:00",960+ stated: ask.altText,961+ who: people.okafor,962+ });963+ yield* story.open({964+ asks: [ask.palette],965+ at: t("2026-09-15T10:00"),966+ by: people.ines,967+ files: filesOf([ask.palette]),968+ });969+970+ const palette = yield* answerAndLand({971+ claimed: "2026-09-15T11:00",972+ landed: "2026-09-16T16:00",973+ stated: ask.palette,974+ who: people.lin,975+ });976+977+ yield* story.tag("v0.8.0", palette.sha);978+979+ // The maintainers' layer, and the posture change that seals its checks.980+ story.decision(981+ decision({982+ at: t("2026-09-28T09:00"),983+ deciders: [people.ines, people.lin],984+ evidence: [985+ {986+ label: "why",987+ value:988+ "Answers to the export and the parser were fitted to their tests; held-back checks judge them instead.",989+ },990+ { label: "notice", value: "3 days" },991+ ],992+ n: 1,993+ subject: Subject.cases.PostureChange.make({994+ from: "open",995+ to: "openWithSealedEvidence",996+ }),997+ })998+ );999+ story.record((seq) =>1000+ LedgerEntry.cases.LayerDeclared.make({1001+ at: t("2026-09-29T10:00"),1002+ disclose: "sealed",1003+ kinds: ["checks", "notes"],1004+ layer: LayerName.make("maintainers"),1005+ seq,1006+ })1007+ );1008+ story.decide(decisionId(1), {1009+ at: t("2026-10-01T08:30"),1010+ by: people.ines,1011+ choice: "accept",1012+ note: "Notice runs three days; the suites go in on the 4th.",1013+ });1014+1015+ yield* story.open({1016+ asks: [ask.docs],1017+ at: t("2026-10-01T15:00"),1018+ by: people.ines,1019+ files: filesOf([ask.docs]),1020+ });1021+ story.claim(ask.docs.id, people.tove, t("2026-10-02T10:00"));1022+1023+ story.record((seq) =>1024+ LedgerEntry.cases.PostureChanged.make({1025+ at: t("2026-10-04T09:00"),1026+ decision: decisionId(1),1027+ from: "open",1028+ seq,1029+ to: "openWithSealedEvidence",1030+ })1031+ );1032+ story.record((seq) =>1033+ LedgerEntry.cases.CommitmentPublished.make({1034+ area: EXPORT,1035+ at: t("2026-10-04T09:05"),1036+ authors: 3,1037+ checks: 7,1038+ seq,1039+ suite: exportSuite,1040+ })1041+ );1042+ story.record((seq) =>1043+ LedgerEntry.cases.CommitmentPublished.make({1044+ area: PARSER,1045+ at: t("2026-10-04T09:06"),1046+ authors: 3,1047+ checks: 4,1048+ seq,1049+ suite: parserSuite,1050+ })1051+ );1052+1053+ // October 4: the second family opens, and the standalone asks.1054+ yield* story.open({1055+ asks: pageSize.asks,1056+ at: t("2026-10-04T09:30"),1057+ by: people.ines,1058+ files: filesOf(pageSize.asks),1059+ });1060+1061+ for (const [stated, minute] of [1062+ [ask.codeBlocks, "40"],1063+ [ask.escape, "41"],1064+ [ask.wrap, "42"],1065+ ] as const) {1066+ yield* story.open({1067+ asks: [stated],1068+ at: t(`2026-10-04T09:${minute}`),1069+ by: people.ines,1070+ files: filesOf([stated]),1071+ });1072+ }1073+1074+ story.warn(ask.docs.id, t("2026-10-04T10:00"));1075+1076+ // render-code-blocks: refused twice, landed in its third round.1077+ story.claim(ask.codeBlocks.id, people.lin, t("2026-10-04T10:00"));1078+1079+ const codeRound1 = story.push(ask.codeBlocks.id, t("2026-10-04T11:00"), 1);1080+1081+ story.judge(ask.codeBlocks.id, codeRound1, {1082+ at: t("2026-10-04T11:00"),1083+ lanes: {1084+ lint: "passed",1085+ redThenGreen: "passed",1086+ types: "failed",1087+ unit: "passed",1088+ },1089+ logs: {1090+ types:1091+ "packages/render/src/code-blocks.ts(4,7): error TS2322: Type 'string | undefined' is not assignable to type 'string'.\n",1092+ },1093+ outcome: Outcome.cases.Refused.make({1094+ refusals: [1095+ new ChecksFailed({1096+ lane: "types",1097+ logRef: `push-${codeRound1}-${people.lin}/types`,1098+ next: LANES.types,1099+ }),1100+ ],1101+ }),1102+ stage: "checks",1103+ });1104+1105+ story.claim(ask.escape.id, people.bram, t("2026-10-04T12:00"));1106+ story.claim(pageSize.child("cli"), people.bram, t("2026-10-04T13:00"));1107+1108+ const codeRound2 = story.push(ask.codeBlocks.id, t("2026-10-04T15:00"), 2);1109+1110+ story.judge(ask.codeBlocks.id, codeRound2, {1111+ at: t("2026-10-04T15:00"),1112+ lanes: {},1113+ outcome: Outcome.cases.Refused.make({1114+ refusals: [1115+ new Weakened({1116+ at: {1117+ line: 22,1118+ path: RepoPath.make("packages/render/test/code-blocks.test.ts"),1119+ },1120+ weakening: { marker: ".skip(" },1121+ }),1122+ ],1123+ }),1124+ stage: "shape",1125+ });1126+1127+ // escape-attribute-quotes waits on a waiver for the test it skips.1128+ const escapeHead = story.push(ask.escape.id, t("2026-10-04T15:00"));1129+1130+ const escapeAt = {1131+ line: 9,1132+ path: RepoPath.make("packages/render/test/attributes.test.ts"),1133+ };1134+1135+ const escapeReason =1136+ "A quote inside a code span needs the escaper's context; split out as its own ask.";1137+1138+ story.judge(ask.escape.id, escapeHead, {1139+ at: t("2026-10-04T15:00"),1140+ lanes: allPassed("redThenGreen"),1141+ outcome: Outcome.cases.AwaitingDecision.make({ decision: decisionId(2) }),1142+ stage: "human",1143+ });1144+ story.decision(1145+ decision({1146+ at: t("2026-10-04T15:00"),1147+ deciders: [people.ines],1148+ evidence: [1149+ {1150+ label: "answer",1151+ value: `${people.bram} at ${escapeHead} (push-${escapeHead}-${people.bram})`,1152+ },1153+ {1154+ label: "escape",1155+ value: `${escapeAt.path}:${escapeAt.line}: .skip( -- ${escapeReason}`,1156+ },1157+ ],1158+ n: 2,1159+ subject: Subject.cases.Waiver.make({1160+ ask: ask.escape.id,1161+ at: escapeAt,1162+ marker: ".skip(",1163+ reason: escapeReason,1164+ }),1165+ })1166+ );1167+1168+ story.claim(ask.wrap.id, people.okafor, t("2026-10-04T16:00"));1169+1170+ const cliPage = story.push(pageSize.child("cli"), t("2026-10-04T17:00"));1171+1172+ story.judge(pageSize.child("cli"), cliPage, {1173+ at: t("2026-10-04T17:00"),1174+ lanes: allPassed("migrate"),1175+ outcome: Outcome.cases.Checking.make({ stage: "human" }),1176+ stage: "human",1177+ });1178+ yield* story.land(pageSize.child("cli"), {1179+ at: t("2026-10-04T17:00"),1180+ changes: childPage("cli"),1181+ });1182+1183+ // October 5.1184+ story.record((seq) =>1185+ LedgerEntry.cases.Admitted.make({1186+ area: EXPORT,1187+ at: t("2026-10-05T07:00"),1188+ knownBadCaught: 3,1189+ mainRuns: 12,1190+ seq,1191+ suite: exportSuite,1192+ })1193+ );1194+ story.record((seq) =>1195+ LedgerEntry.cases.CountChanged.make({1196+ area: EXPORT,1197+ at: t("2026-10-05T07:01"),1198+ count: 7,1199+ layer: LayerName.make("maintainers"),1200+ seq,1201+ })1202+ );1203+1204+ story.claim(pageSize.child("render"), people.okafor, t("2026-10-05T08:00"));1205+ story.claim(pageSize.child("themes"), people.lin, t("2026-10-05T09:00"));1206+ yield* story.open({1207+ asks: tokenizer.asks,1208+ at: t("2026-10-05T09:00"),1209+ by: people.ines,1210+ files: filesOf(tokenizer.asks),1211+ });1212+1213+ const codeRound3 = story.push(ask.codeBlocks.id, t("2026-10-05T09:30"), 3);1214+1215+ story.judge(ask.codeBlocks.id, codeRound3, {1216+ at: t("2026-10-05T09:30"),1217+ lanes: allPassed("redThenGreen"),1218+ outcome: Outcome.cases.Checking.make({ stage: "human" }),1219+ stage: "human",1220+ });1221+ yield* story.land(ask.codeBlocks.id, {1222+ at: t("2026-10-05T09:30"),1223+ changes: answerFiles(1224+ ask.codeBlocks,1225+ "export const keepsBlankLines = true;"1226+ ),1227+ });1228+1229+ story.claim(tokenizer.child("render"), people.sefa, t("2026-10-05T09:30"));1230+ story.claim(tokenizer.child("cli"), people.bram, t("2026-10-05T10:00"));1231+1232+ // wrap-long-table-cells: narrowed with .only( in its first round, then waiting for a finish.1233+ const wrapRound1 = story.push(ask.wrap.id, t("2026-10-05T10:00"), 1);1234+1235+ story.judge(ask.wrap.id, wrapRound1, {1236+ at: t("2026-10-05T10:00"),1237+ lanes: {},1238+ outcome: Outcome.cases.Refused.make({1239+ refusals: [1240+ new Weakened({1241+ at: {1242+ line: 14,1243+ path: RepoPath.make("packages/render/test/table.test.ts"),1244+ },1245+ weakening: { marker: ".only(" },1246+ }),1247+ ],1248+ }),1249+ stage: "shape",1250+ });1251+1252+ story.claim(1253+ tokenizer.child("export"),1254+ people.okafor,1255+ t("2026-10-05T11:00"),1256+ exportSuite1257+ );1258+1259+ const renderPage = story.push(1260+ pageSize.child("render"),1261+ t("2026-10-05T11:00")1262+ );1263+1264+ story.judge(pageSize.child("render"), renderPage, {1265+ at: t("2026-10-05T11:00"),1266+ lanes: allPassed("migrate"),1267+ outcome: Outcome.cases.Checking.make({ stage: "human" }),1268+ stage: "human",1269+ });1270+ yield* story.land(pageSize.child("render"), {1271+ at: t("2026-10-05T11:00"),1272+ changes: childPage("render"),1273+ });1274+1275+ const themesPage = story.push(1276+ pageSize.child("themes"),1277+ t("2026-10-05T12:00")1278+ );1279+1280+ story.judge(pageSize.child("themes"), themesPage, {1281+ at: t("2026-10-05T12:00"),1282+ lanes: allPassed("migrate"),1283+ outcome: Outcome.cases.Checking.make({ stage: "human" }),1284+ stage: "human",1285+ });1286+ yield* story.land(pageSize.child("themes"), {1287+ at: t("2026-10-05T12:00"),1288+ changes: childPage("themes"),1289+ });1290+1291+ // The lint ask came from tove's proposal.1292+ story.propose({1293+ files: [],1294+ proposal: proposal({1295+ at: t("2026-10-05T13:00"),1296+ files: [],1297+ n: 1,1298+ proposer: people.tove,1299+ want: ask.headings.brief.want,1300+ }),1301+ });1302+ story.decision(1303+ decision({1304+ at: t("2026-10-05T13:00"),1305+ deciders: [people.ines, people.lin],1306+ evidence: [1307+ { label: "want", value: ask.headings.brief.want },1308+ { label: "territory", value: "@vellum/lint" },1309+ ],1310+ n: 3,1311+ subject: Subject.cases.OpenProposal.make({ proposal: proposalId(1) }),1312+ })1313+ );1314+1315+ const wrapHead = story.push(ask.wrap.id, t("2026-10-05T14:00"), 2);1316+1317+ story.judge(ask.wrap.id, wrapHead, {1318+ at: t("2026-10-05T14:00"),1319+ lanes: allPassed("redThenGreen"),1320+ outcome: Outcome.cases.AwaitingFinish.make({ decider: people.ines }),1321+ stage: "human",1322+ });1323+ story.decision(1324+ decision({1325+ at: t("2026-10-05T14:00"),1326+ default: "accept",1327+ deciders: [people.ines],1328+ evidence: [1329+ {1330+ label: "answer",1331+ value: `${people.okafor} at ${wrapHead} (push-${wrapHead}-${people.okafor})`,1332+ },1333+ { label: "patch", value: WRAP_PATCH },1334+ {1335+ label: "fork",1336+ value: `${vellum}--${ask.wrap.id}--${people.okafor}`,1337+ },1338+ ],1339+ n: 4,1340+ subject: Subject.cases.Finish.make({1341+ ask: ask.wrap.id,1342+ head: wrapHead,1343+ }),1344+ })1345+ );1346+1347+ const cliChild = story.push(tokenizer.child("cli"), t("2026-10-05T14:00"));1348+1349+ story.judge(tokenizer.child("cli"), cliChild, {1350+ at: t("2026-10-05T14:00"),1351+ lanes: allPassed("migrate"),1352+ outcome: Outcome.cases.Checking.make({ stage: "human" }),1353+ stage: "human",1354+ });1355+1356+ const released = yield* story.land(tokenizer.child("cli"), {1357+ at: t("2026-10-05T14:00"),1358+ changes: childEntry("cli"),1359+ });1360+1361+ yield* story.tag("v0.9.0", released.sha);1362+1363+ for (const [stated, minute] of [1364+ [ask.numbers, "10"],1365+ [ask.backrefs, "11"],1366+ [ask.trim, "12"],1367+ [ask.nested, "13"],1368+ [ask.cliVersion, "14"],1369+ [ask.exportPages, "15"],1370+ [ask.exportErrors, "16"],1371+ [ask.carry, "17"],1372+ ] as const) {1373+ yield* story.open({1374+ asks: [stated],1375+ at: t(`2026-10-05T15:${minute}`),1376+ by: people.ines,1377+ files: filesOf([stated]),1378+ });1379+ }1380+1381+ const ready = draftedFiles(1382+ "parse-nested-quotes",1383+ "parser",1384+ "The parser reads a blockquote nested inside a list item."1385+ );1386+1387+ story.propose(1388+ {1389+ files: ready,1390+ proposal: proposal({1391+ at: t("2026-10-05T15:30"),1392+ draft: DraftState.cases.Ready.make({1393+ attempts: 1,1394+ model: "memory",1395+ red: {1396+ lane: LaneName.make("redThenGreen"),1397+ signature: "expected 1 blockquote, received 0",1398+ },1399+ round: 1,1400+ }),1401+ files: ready.map(({ path }) => path),1402+ n: 2,1403+ proposer: people.bram,1404+ want: "The parser reads a blockquote nested inside a list item.",1405+ }),1406+ },1407+ { at: t("2026-10-05T16:00"), ready: true }1408+ );1409+ story.decision(1410+ decision({1411+ at: t("2026-10-05T16:00"),1412+ deciders: [people.ines],1413+ evidence: [1414+ {1415+ label: "want",1416+ value: "The parser reads a blockquote nested inside a list item.",1417+ },1418+ { label: "territory", value: "@vellum/parser" },1419+ ...ready.map(({ content, path }) => ({1420+ label: path,1421+ value: content,1422+ })),1423+ {1424+ label: "red first",1425+ value: "redThenGreen: expected 1 blockquote, received 0",1426+ },1427+ { label: "drafted by", value: "memory, attempt 1 of 3" },1428+ ],1429+ n: 5,1430+ subject: Subject.cases.OpenProposal.make({ proposal: proposalId(2) }),1431+ })1432+ );1433+1434+ story.claim(1435+ tokenizer.child("parser"),1436+ people.tove,1437+ t("2026-10-05T16:00"),1438+ parserSuite1439+ );1440+1441+ // October 6.1442+ story.decision(1443+ decision({1444+ at: t("2026-10-06T07:00"),1445+ deciders: [people.ines, people.lin],1446+ evidence: [1447+ {1448+ label: "why",1449+ value:1450+ "The maintainers' notes become public a month after each release.",1451+ },1452+ {1453+ label: "notice",1454+ value:1455+ "3 days: it takes effect on the third day after it is accepted",1456+ },1457+ ],1458+ n: 6,1459+ subject: Subject.cases.PostureChange.make({1460+ from: "openWithSealedEvidence",1461+ to: "openOnSchedule",1462+ }),1463+ })1464+ );1465+1466+ story.claim(ask.nested.id, people.tove, t("2026-10-06T08:00"));1467+ story.claim(ask.carry.id, people.okafor, t("2026-10-06T08:30"));1468+1469+ const exportChild = story.push(1470+ tokenizer.child("export"),1471+ t("2026-10-06T09:00")1472+ );1473+1474+ story.judge(tokenizer.child("export"), exportChild, {1475+ at: t("2026-10-06T09:00"),1476+ heldBack: [held(EXPORT, 7, 7)],1477+ lanes: allPassed("migrate"),1478+ outcome: Outcome.cases.Checking.make({ stage: "human" }),1479+ stage: "human",1480+ });1481+ yield* story.land(tokenizer.child("export"), {1482+ at: t("2026-10-06T09:00"),1483+ changes: childEntry("export"),1484+ });1485+1486+ story.claim(ask.numbers.id, people.lin, t("2026-10-06T09:00"), parserSuite);1487+ story.claim(tokenizer.child("lint"), people.lin, t("2026-10-06T10:00"));1488+ story.lapse(ask.docs.id, t("2026-10-06T10:00"));1489+ story.claim(ask.backrefs.id, people.bram, t("2026-10-06T11:00"));1490+ story.decision(1491+ decision({1492+ at: t("2026-10-06T11:00"),1493+ default: "revert",1494+ deciders: [people.ines, people.lin],1495+ evidence: [1496+ { label: "ref", value: "refs/heads/main" },1497+ {1498+ label: "pusher",1499+ value: "not known: the push came past the platform",1500+ },1501+ ],1502+ n: 7,1503+ subject: Subject.cases.StrayPush.make({1504+ after: headOf("vellum/stray"),1505+ before: story.head(),1506+ ref: MAIN_REF,1507+ }),1508+ })1509+ );1510+1511+ story.claim(ask.trim.id, people.sefa, t("2026-10-06T12:00"));1512+1513+ const release = yield* story.landOwn({1514+ at: t("2026-10-06T12:00"),1515+ author: people.okonkwo,1516+ changes: new Map([1517+ [1518+ "packages/export/test/fixtures/epub-minimal.vm",1519+ "# A title\n\nOne paragraph.\n",1520+ ],1521+ [1522+ "packages/export/test/fixtures/epub-footnotes.vm",1523+ "A claim.[^1]\n\n[^1]: Its source.\n",1524+ ],1525+ ]),1526+ credits: [{ handle: people.okonkwo, role: "Released-by" }],1527+ message: {1528+ body: "Two documents the export's held-back checks read, released from the maintainers' layer.",1529+ subject: "Release two export fixtures",1530+ },1531+ });1532+1533+ story.record((seq) =>1534+ LedgerEntry.cases.Released.make({1535+ at: t("2026-10-06T12:00"),1536+ by: people.okonkwo,1537+ landing: release.sha,1538+ layer: LayerName.make("maintainers"),1539+ paths: 2,1540+ seq,1541+ })1542+ );1543+1544+ // render-nested-lists: refused at the checks, with the failing lane's log.1545+ const nestedHead = story.push(ask.nested.id, t("2026-10-06T12:30"));1546+1547+ story.judge(ask.nested.id, nestedHead, {1548+ at: t("2026-10-06T12:30"),1549+ lanes: {1550+ lint: "passed",1551+ redThenGreen: "passed",1552+ types: "passed",1553+ unit: "failed",1554+ },1555+ logs: {1556+ unit: [1557+ "bun test v1.4.2",1558+ "",1559+ "packages/render/test/lists.test.ts:",1560+ "✓ a flat list renders [0.41ms]",1561+ "✗ a list nested two deep keeps its indentation [1.02ms]",1562+ ' expected: "<ul><li>a<ul><li>b</li></ul></li></ul>"',1563+ ' received: "<ul><li>a</li><li>b</li></ul>"',1564+ "",1565+ " 1 pass",1566+ " 1 fail",1567+ "",1568+ ].join("\n"),1569+ },1570+ outcome: Outcome.cases.Refused.make({1571+ refusals: [1572+ new ChecksFailed({1573+ lane: "unit",1574+ logRef: `push-${nestedHead}-${people.tove}/unit`,1575+ next: LANES.unit,1576+ }),1577+ ],1578+ }),1579+ stage: "checks",1580+ });1581+1582+ // trim-trailing-spaces: refused at Shape, a change outside its territory.1583+ const trimHead = story.push(ask.trim.id, t("2026-10-06T13:00"));1584+ const outside = RepoPath.make("packages/cli/src/args.ts");1585+1586+ story.judge(ask.trim.id, trimHead, {1587+ at: t("2026-10-06T13:00"),1588+ lanes: {},1589+ outcome: Outcome.cases.Refused.make({1590+ refusals: [1591+ new OutOfScope({ at: { line: 3, path: outside }, paths: [outside] }),1592+ ],1593+ }),1594+ stage: "shape",1595+ });1596+1597+ story.claim(ask.cliVersion.id, people.bram, t("2026-10-06T13:00"));1598+ story.claim(1599+ ask.exportPages.id,1600+ people.okafor,1601+ t("2026-10-06T13:30"),1602+ exportSuite1603+ );1604+1605+ const pagesHead = story.push(ask.exportPages.id, t("2026-10-06T14:00"));1606+1607+ story.judge(ask.exportPages.id, pagesHead, {1608+ at: t("2026-10-06T14:00"),1609+ heldBack: [held(EXPORT, 7, 7)],1610+ lanes: allPassed("redThenGreen"),1611+ outcome: Outcome.cases.AwaitingDecision.make({ decision: decisionId(8) }),1612+ stage: "human",1613+ });1614+ story.decision(1615+ decision({1616+ at: t("2026-10-06T14:00"),1617+ deciders: [people.okonkwo],1618+ evidence: [1619+ {1620+ label: "answer",1621+ value: `${people.okafor} at ${pagesHead} (push-${pagesHead}-${people.okafor})`,1622+ },1623+ {1624+ label: "ratchet",1625+ value: "bundle-bytes in @vellum/export: 41200 to 41850",1626+ },1627+ ],1628+ n: 8,1629+ subject: Subject.cases.RaiseRatchet.make({1630+ after: 41_850,1631+ ask: ask.exportPages.id,1632+ before: 41_200,1633+ ratchet: RatchetName.make("bundle-bytes"),1634+ territory: "@vellum/export",1635+ }),1636+ })1637+ );1638+1639+ story.propose(1640+ {1641+ files: [],1642+ proposal: proposal({1643+ at: t("2026-10-06T14:30"),1644+ draft: DraftState.cases.Failed.make({1645+ attempts: 3,1646+ model: "memory",1647+ refusal: "NotRedFirst",1648+ round: 1,1649+ }),1650+ files: [],1651+ n: 3,1652+ proposer: people.sefa,1653+ want: "Themes can set their own font for code blocks.",1654+ }),1655+ },1656+ { at: t("2026-10-06T15:00"), ready: false }1657+ );1658+ story.decision(1659+ decision({1660+ at: t("2026-10-06T15:00"),1661+ deciders: [people.ines, people.lin],1662+ evidence: [1663+ {1664+ label: "want",1665+ value: "Themes can set their own font for code blocks.",1666+ },1667+ {1668+ label: "draft failed",1669+ value:1670+ "The check passed on main, so it proves nothing about an answer.",1671+ },1672+ ],1673+ n: 9,1674+ subject: Subject.cases.OpenProposal.make({ proposal: proposalId(3) }),1675+ })1676+ );1677+1678+ // The parser child: every lane passed, one held-back check in the parser did not.1679+ const parserHead = story.push(1680+ tokenizer.child("parser"),1681+ t("2026-10-06T15:00")1682+ );1683+1684+ story.judge(tokenizer.child("parser"), parserHead, {1685+ at: t("2026-10-06T15:00"),1686+ heldBack: [held(PARSER, 3, 4)],1687+ lanes: allPassed("migrate"),1688+ outcome: Outcome.cases.Refused.make({1689+ refusals: [new HeldBackFailed({ area: PARSER, suite: parserSuite })],1690+ }),1691+ stage: "heldBack",1692+ });1693+1694+ // footnote-backrefs passed, and waits for number-footnotes to land first.1695+ const backrefsHead = story.push(ask.backrefs.id, t("2026-10-06T16:00"));1696+1697+ story.judge(ask.backrefs.id, backrefsHead, {1698+ at: t("2026-10-06T16:00"),1699+ lanes: allPassed("redThenGreen"),1700+ outcome: Outcome.cases.WaitingOnParent.make({ ask: ask.numbers.id }),1701+ stage: "human",1702+ });1703+1704+ const token = EnvKey.make("SENTRY_AUTH_TOKEN");1705+1706+ story.decision(1707+ decision({1708+ at: t("2026-10-06T16:00"),1709+ deciders: [people.okonkwo],1710+ evidence: [1711+ { label: "item", value: token },1712+ { label: "hosts now", value: "sentry.io" },1713+ { label: "hosts after", value: "sentry.io, ingest.sentry.io" },1714+ ],1715+ n: 10,1716+ subject: Subject.cases.ProxyWidened.make({1717+ hosts: WIDER_HOSTS,1718+ item: token,1719+ }),1720+ })1721+ );1722+ story.record((seq) =>1723+ LedgerEntry.cases.ValueSet.make({1724+ at: t("2026-10-06T16:30"),1725+ by: people.ines,1726+ key: token,1727+ seq,1728+ })1729+ );1730+1731+ // cli-version-flag lands with no decision and nothing held back.1732+ const versionHead = story.push(ask.cliVersion.id, t("2026-10-06T17:30"));1733+1734+ story.judge(ask.cliVersion.id, versionHead, {1735+ at: t("2026-10-06T17:30"),1736+ lanes: allPassed("redThenGreen"),1737+ outcome: Outcome.cases.Checking.make({ stage: "human" }),1738+ stage: "human",1739+ });1740+ yield* story.land(ask.cliVersion.id, {1741+ assisted: [{ harness: "claude-code", model: "haiku", verified: false }],1742+ at: t("2026-10-06T17:30"),1743+ changes: answerFiles(ask.cliVersion, 'export const version = "0.9.0";'),1744+ });1745+1746+ // carry-footnotes-to-epub waits on a waiver for a `.todo(`, then lands with it.1747+ const carryHead = story.push(ask.carry.id, t("2026-10-06T18:00"));1748+1749+ const carryAt = {1750+ line: 31,1751+ path: RepoPath.make("packages/export/test/epub.test.ts"),1752+ };1753+1754+ const carryReason = "EPUB 2 readers come later; their own ask is drafted.";1755+1756+ story.judge(ask.carry.id, carryHead, {1757+ at: t("2026-10-06T18:00"),1758+ heldBack: [held(EXPORT, 7, 7), held(PARSER, 4, 4)],1759+ lanes: allPassed("redThenGreen"),1760+ outcome: Outcome.cases.AwaitingDecision.make({1761+ decision: decisionId(11),1762+ }),1763+ stage: "human",1764+ });1765+ story.decision(1766+ decision({1767+ at: t("2026-10-06T18:00"),1768+ deciders: [people.ines],1769+ evidence: [1770+ {1771+ label: "answer",1772+ value: `${people.okafor} at ${carryHead} (push-${carryHead}-${people.okafor})`,1773+ },1774+ {1775+ label: "escape",1776+ value: `${carryAt.path}:${carryAt.line}: .todo( -- ${carryReason}`,1777+ },1778+ ],1779+ n: 11,1780+ subject: Subject.cases.Waiver.make({1781+ ask: ask.carry.id,1782+ at: carryAt,1783+ marker: ".todo(",1784+ reason: carryReason,1785+ }),1786+ })1787+ );1788+1789+ const subsets = draftedFiles(1790+ "export-font-subsets",1791+ "export",1792+ "Export embeds only the font subsets a document uses."1793+ );1794+1795+ story.propose(1796+ {1797+ files: subsets,1798+ proposal: proposal({1799+ at: t("2026-10-06T18:30"),1800+ draft: DraftState.cases.Failed.make({1801+ attempts: 1,1802+ model: "memory",1803+ refusal: "VerifierBlocked",1804+ round: 2,1805+ }),1806+ files: subsets.map(({ path }) => path),1807+ n: 4,1808+ proposer: people.okafor,1809+ want: "Export embeds only the font subsets a document uses.",1810+ }),1811+ },1812+ { at: t("2026-10-06T19:00"), ready: true }1813+ );1814+ story.drafted(proposalId(4), t("2026-10-06T20:00"), false);1815+ story.decision(1816+ decision({1817+ at: t("2026-10-06T20:00"),1818+ deciders: [people.okonkwo],1819+ evidence: [1820+ {1821+ label: "want",1822+ value: "Export embeds only the font subsets a document uses.",1823+ },1824+ { label: "territory", value: "@vellum/export" },1825+ ...subsets.map(({ content, path }) => ({1826+ label: path,1827+ value: content,1828+ })),1829+ {1830+ label: "draft failed",1831+ value:1832+ "The Checker was busy; the platform could not run the check this round.",1833+ },1834+ ],1835+ n: 12,1836+ subject: Subject.cases.OpenProposal.make({ proposal: proposalId(4) }),1837+ })1838+ );1839+1840+ // October 7, this morning.1841+ story.claim(1842+ ask.exportErrors.id,1843+ people.tove,1844+ t("2026-10-07T07:00"),1845+ exportSuite1846+ );1847+1848+ const errorsHead = story.push(ask.exportErrors.id, t("2026-10-07T07:30"));1849+1850+ story.judge(ask.exportErrors.id, errorsHead, {1851+ at: t("2026-10-07T07:30"),1852+ lanes: allPassed("redThenGreen"),1853+ outcome: Outcome.cases.AwaitingDecision.make({1854+ decision: decisionId(13),1855+ }),1856+ stage: "human",1857+ });1858+ story.decision(1859+ decision({1860+ at: t("2026-10-07T07:30"),1861+ deciders: [people.okonkwo],1862+ evidence: [1863+ {1864+ label: "answer",1865+ value: `${people.tove} at ${errorsHead} (push-${errorsHead}-${people.tove})`,1866+ },1867+ { label: "item", value: token },1868+ {1869+ label: "where",1870+ value:1871+ "a file in the answer's tree holds the item's stored value; the answer is held aside",1872+ },1873+ ],1874+ n: 13,1875+ subject: Subject.cases.SecretInTree.make({1876+ ask: ask.exportErrors.id,1877+ item: token,1878+ }),1879+ })1880+ );1881+ story.decision(1882+ decision({1883+ at: t("2026-10-07T08:00"),1884+ deciders: [people.okonkwo],1885+ evidence: [1886+ { label: "handle", value: people.wren },1887+ {1888+ label: "line",1889+ value: `${people.wren} Asks to come back; proposals since are on topic.`,1890+ },1891+ ],1892+ n: 14,1893+ subject: Subject.cases.Vouch.make({ handle: people.wren }),1894+ })1895+ );1896+1897+ story.push(ask.numbers.id, t("2026-10-07T08:15"));1898+1899+ story.decide(decisionId(3), {1900+ at: t("2026-10-07T08:30"),1901+ by: people.ines,1902+ choice: "accept",1903+ note: "Clear want; tove's test covers the skip.",1904+ });1905+ story.accepted(proposalId(1));1906+ yield* story.open({1907+ asks: [ask.headings],1908+ at: t("2026-10-07T08:30"),1909+ by: people.ines,1910+ files: filesOf([ask.headings]),1911+ });1912+ story.claim(ask.headings.id, people.bram, t("2026-10-07T08:40"));1913+ story.release(ask.headings.id, t("2026-10-07T09:00"));1914+1915+ story.decide(decisionId(11), {1916+ at: t("2026-10-07T09:10"),1917+ by: people.ines,1918+ choice: "accept",1919+ note: "EPUB 2 is out of scope here.",1920+ });1921+ yield* story.land(ask.carry.id, {1922+ at: t("2026-10-07T09:12"),1923+ changes: answerFiles(ask.carry, "export const endnotes = true;"),1924+ decidedBy: people.ines,1925+ });1926+1927+ story.warn(tokenizer.child("render"), t("2026-10-07T09:30"));1928+1929+ const lintHead = story.push(tokenizer.child("lint"), t("2026-10-07T09:40"));1930+1931+ story.judge(tokenizer.child("lint"), lintHead, {1932+ at: t("2026-10-07T09:40"),1933+ lanes: { migrate: "passed", types: "passed" },1934+ outcome: Outcome.cases.Checking.make({ stage: "checks" }),1935+ stage: "checks",1936+ });1937+1938+ story.propose({1939+ files: [],1940+ proposal: proposal({1941+ at: t("2026-10-07T09:50"),1942+ draft: DraftState.cases.Drafting.make({1943+ round: 1,1944+ startedAt: t("2026-10-07T09:50"),1945+ }),1946+ files: [],1947+ n: 5,1948+ proposer: people.lin,1949+ want: "The CLI prints a table of contents with --toc.",1950+ }),1951+ });1952+1953+ const apart = {1954+ env: envAt(story.head()),1955+ ledger,1956+ working: [people.ines, people.okonkwo],1957+ };1958+1959+ return { story, told: () => story.told(apart) };1960+ });1961+1962+/**1963+ * The live landing: the first family's lint child, checking since this1964+ * morning, passes its last lanes and lands at `at`, one more of six.1965+ */1966+export const landLintChild = (story: Story, at: DateTime.Utc) =>1967+ Effect.gen(function* () {1968+ const child = tokenizer.child("lint");1969+1970+ story.finishChecks(child, allPassed("migrate"));1971+1972+ return yield* story.land(child, {1973+ at,1974+ changes: new Map([1975+ ["packages/lint/src/index.ts", entryOf("lint", "tokenize")],1976+ ]),1977+ });1978+ });modified:apps/web/src/dev/backend.ts+2 added-1 removed
12 unmodified lines1314151617181919202122232412 unmodified lines * production build carries none of it (`test/production-bundle.test.ts`). */import type { Backend } from "../server/rpc.ts";import { credentialFrom, withCredential } from "../server/session.ts";import { fixturesMode } from "./fixtures.ts";import { devServer } from "./server.ts";
const served = devServer();const served = devServer({ fixtures: fixturesMode });
/** The development backend: every request answered by the dev world, as the platform is asked; the env unused. */export const backend: Backend = (request) => served.handler(withCredential(request, credentialFrom(request)));modified:apps/web/src/dev/examples.ts+5 added-5 removed
37 unmodified lines38 39 const encodeMeasure = Schema.encodeSync(RatchetMeasure);40 41 /** What a project's `policy.json` states, as the file holds it. */42-type Stated = typeof PolicyInput.Encoded;42+export type Stated = typeof PolicyInput.Encoded;43 44 /** One ask as `policy.json` states it. */45-type StatedAsk = Stated["asks"][number];45+export type StatedAsk = Stated["asks"][number];46 47 /** A `policy.json` from what its project states, with every default written out. */48-const policyJson = (stated: Stated) =>48+export const policyJson = (stated: Stated) =>49 `${JSON.stringify(50 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),51 null,52 253 )}\n`;54 55 /** One file an ask opens with. */56-interface AskFile {56+export interface AskFile {57 readonly content: string;58 readonly path: RepoPath;59 }60 38 unmodified lines99 ? `territory.paths(${paths.map(spelled).join(", ")})`100 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;101 102 /** An ask's file: the SDK call that states `stated`, as its maintainer writes it. */103-const askFileOf = (stated: StatedAsk): AskFile => {103+export const askFileOf = (stated: StatedAsk): AskFile => {104 const territory = territoryOf(stated.territory);105 106 const passed = Object.entries({107 ...checkArgs(stated.check),588 unmodified linesadded:apps/web/src/dev/fixtures.ts+487 added
1+/**2+ * The dev world's fixtures: the states a page draws that the default world3+ * never reaches, served through the same contracts, beside datekit and4+ * burrow. Off unless the dev server is started with the switch:5+ *6+ * VITE_DEV_FIXTURES=1 bun run --cwd apps/web dev # the fixtures7+ * VITE_DEV_FIXTURES=live bun run --cwd apps/web dev # and the live landing8+ *9+ * The switch is a `VITE_` variable because the dev world runs in the10+ * Worker's runtime, which sees no other variable of the shell that started11+ * Vite; Vite writes `VITE_` ones into the modules it serves.12+ *13+ * With the switch on the world holds, beside the default two:14+ *15+ * - six small projects made through the project service, as the seed makes16+ * datekit (`fixtures/fillers.ts`), so the project list runs past eight,17+ * one of them with no open asks;18+ * - `vellum`, whose record is told as a story (`fixtures/vellum.ts`). Its19+ * repo and policy are real: the service made the project and took its20+ * first push, and every landing is a commit on its `main`. What the21+ * service cannot reach in a world with no visibility cartridge (a ledger22+ * with layers, sealed areas, an env item someone set, a refusal at Shape23+ * kept as a verdict, a finish put to a decider) is in the record, which24+ * answers vellum's reads in place of the service's own: its asks,25+ * events, verdicts, landings, decisions and Today, ledger, env shape,26+ * proposals, claims and forks. Writes other than a decision reach the27+ * service underneath, which holds none of the record's asks.28+ *29+ * In live mode the lint child of vellum's first family, checking since the30+ * morning, lands `LIVE_AFTER` after the world first answers vellum's31+ * `watch`: on the first read of vellum after that, as the dev world's pages32+ * poll, so a page left open sees one more landing arrive.33+ */34+import { RepoHost } from "@repo/artifacts/repo-host";35+import { envSchemaMethod } from "@repo/project/deciders";36+import type { ProjectApi } from "@repo/project/project";37+import { ProjectedEvent } from "@repo/project/projection";38+import { Projects } from "@repo/project/projects";39+import type { Ask } from "@repo/protocol/domain/ask";40+import type { ProjectName } from "@repo/protocol/ids";41+import { sameHandle } from "@repo/protocol/ids";42+import { Principal } from "@repo/protocol/principal";43+import type { Person } from "@repo/protocol/principal";44+import {45+ NotDecider,46+ UnknownAsk,47+ UnknownCommit,48+ UnknownProject,49+ UnknownProposal,50+} from "@repo/protocol/refusal";51+import {52+ Clock,53+ Context,54+ DateTime,55+ Duration,56+ Effect,57+ Layer,58+ Option,59+ Ref,60+ Schema,61+ Semaphore,62+} from "effect";63+64+import { DevClock } from "./clock.ts";65+import { seedFillers } from "./fixtures/fillers.ts";66+import {67+ creditsIn,68+ decisionTaken,69+ decodeRecord,70+ landingIn,71+ lastSeqOf,72+ listedOf,73+ statusIn,74+ todayIn,75+ verdictIn,76+} from "./fixtures/record.ts";77+import type { FixtureRecord } from "./fixtures/record.ts";78+import type { Story } from "./fixtures/story.ts";79+import {80+ decisionsPerDay,81+ fixturesNow,82+ landLintChild,83+ tellVellum,84+ vellum,85+ vellumFiles,86+ vellumInitializer,87+ vellumStart,88+} from "./fixtures/vellum.ts";89+import { DevProjected } from "./projection.ts";90+import { seedDev, startedAt } from "./seed.ts";91+import { devWorldWith } from "./world.ts";92+93+/** Off, on, or on with the live landing. */94+export type FixtureMode = "off" | "on" | "live";95+96+const Switch = Schema.Literals(["1", "on", "live"]);97+98+/** The switch, read once from where Vite puts it. */99+export const fixturesMode: FixtureMode = Option.match(100+ Schema.decodeUnknownOption(Switch)(import.meta.env.VITE_DEV_FIXTURES),101+ {102+ onNone: (): FixtureMode => "off",103+ onSome: (on): FixtureMode => (on === "live" ? "live" : "on"),104+ }105+);106+107+/** Whether the dev world adds the fixtures. */108+export const fixturesOn = fixturesMode !== "off";109+110+/** How long after vellum's `watch` is first answered its lint child lands, in live mode. */111+export const LIVE_AFTER = Duration.seconds(20);112+113+/** vellum's story, and the record it has told so far, decoded. */114+interface Told {115+ readonly record: FixtureRecord;116+ readonly story: Story;117+ readonly told: () => FixtureRecord;118+}119+120+/** The fixtures' state in one world: vellum's story once told, and the live landing's clock. */121+export class Fixtures extends Context.Service<122+ Fixtures,123+ {124+ readonly told: Ref.Ref<Option.Option<Told>>;125+ /** How long after the first `watch` the live landing waits; none, no live landing. */126+ readonly liveAfter: Option.Option<Duration.Duration>;127+ /** When vellum's `watch` was first answered, by the monotonic clock. */128+ readonly armedAt: Ref.Ref<Option.Option<bigint>>;129+ readonly landed: Ref.Ref<boolean>;130+ /** One write to the story at a time. */131+ readonly lock: Semaphore.Semaphore;132+ }133+>()("web/dev/Fixtures") {}134+135+const fixturesLayer = (liveAfter: Option.Option<Duration.Duration>) =>136+ Layer.effect(137+ Fixtures,138+ Effect.gen(function* () {139+ return Fixtures.of({140+ armedAt: yield* Ref.make(Option.none<bigint>()),141+ landed: yield* Ref.make(false),142+ liveAfter,143+ lock: yield* Semaphore.make(1),144+ told: yield* Ref.make(Option.none<Told>()),145+ });146+ })147+ );148+149+/** The person calling, when someone signed in is. */150+const callerOf = (principal: Principal) =>151+ Principal.match(principal, {152+ Anonymous: () => Option.none<Person>(),153+ Person: (person) => Option.some(person),154+ });155+156+/** Whether `project` is one whose reads the fixtures answer. */157+const isFixture = (project: ProjectName) => project === vellum;158+159+/** The ask as an answerer reads it first, in Markdown. */160+const briefOf = (ask: Ask): string =>161+ [162+ `# ${ask.brief.want}`,163+ "",164+ `Ask \`${ask.id}\` in ${ask.project}, a \`${ask.kind}\` ask from ${ask.askedBy}.`,165+ "",166+ "## Territory",167+ "",168+ ask.territory.module === "."169+ ? `The paths ${ask.territory.paths.map((path) => `\`${path}\``).join(", ")}.`170+ : `The module \`${ask.territory.module}\`: ${ask.territory.paths.map((path) => `\`${path}\``).join(", ")}.`,171+ ...(ask.brief.current === undefined172+ ? []173+ : ["", "## Current", "", ask.brief.current]),174+ "",175+ ].join("\n");176+177+/**178+ * vellum's reads answered from its record, everything else by the service179+ * underneath; and the projection's events with vellum's from the record.180+ */181+const overlay: Layer.Layer<182+ Projects | DevProjected,183+ never,184+ Projects | DevProjected | Fixtures | RepoHost | DevClock185+> = Layer.effectContext(186+ Effect.gen(function* () {187+ const projects = yield* Projects;188+ const projected = yield* DevProjected;189+ const fixtures = yield* Fixtures;190+ const host = yield* RepoHost;191+ const devClock = yield* DevClock;192+ const clock = yield* Clock.Clock;193+194+ const now = Effect.sync(() =>195+ DateTime.toUtc(DateTime.makeUnsafe(clock.currentTimeMillisUnsafe()))196+ );197+198+ const provided = <A, E>(effect: Effect.Effect<A, E, RepoHost | DevClock>) =>199+ effect.pipe(200+ Effect.provideService(RepoHost, host),201+ Effect.provideService(DevClock, devClock)202+ );203+204+ /** The record's latest, once told. */205+ const current = Effect.flatMap(Ref.get(fixtures.told), (told) =>206+ Option.match(told, {207+ onNone: () => Effect.die("vellum's story is not told yet"),208+ onSome: ({ record }) => Effect.succeed(record),209+ })210+ );211+212+ /** A write to the story, under the lock, and the record told again. */213+ const write = <A, E>(214+ step: (story: Story) => Effect.Effect<A, E, RepoHost | DevClock>215+ ) =>216+ fixtures.lock.withPermits(1)(217+ Effect.gen(function* () {218+ const told = yield* Effect.flatMap(219+ Ref.get(fixtures.told),220+ Effect.fromOption221+ ).pipe(Effect.orDie);222+223+ const out = yield* provided(step(told.story));224+ const record = yield* decodeRecord(told.told());225+226+ yield* Ref.set(fixtures.told, Option.some({ ...told, record }));227+228+ return out;229+ })230+ );231+232+ /**233+ * vellum's `watch` was read from `since`: the first read arms the live234+ * landing, and a read once it is due lands the lint child first. Only a235+ * read's start counts (from the first event, or from the last one, as a236+ * page that follows the stream asks); a later page of the same replay237+ * never lands it in the middle of the replay.238+ */239+ const heard = (since: number) =>240+ Option.match(fixtures.liveAfter, {241+ onNone: () => Effect.void,242+ onSome: (after) =>243+ Effect.gen(function* () {244+ const record = yield* current;245+246+ if (since !== 0 && since < lastSeqOf(record)) {247+ return;248+ }249+250+ const at = yield* Clock.monotonicTimeNanos;251+252+ // The read before this one armed it, or this read arms it.253+ const armed = yield* Ref.modify(254+ fixtures.armedAt,255+ (was): readonly [Option.Option<bigint>, Option.Option<bigint>] =>256+ Option.isSome(was)257+ ? [was, was]258+ : [Option.none(), Option.some(at)]259+ );260+261+ if (Option.isNone(armed)) {262+ return;263+ }264+265+ const waited = Duration.nanos(at - armed.value);266+267+ // Taken in one step, so two reads at once land it only once.268+ if (269+ Duration.isLessThan(waited, after) ||270+ (yield* Ref.getAndSet(fixtures.landed, true))271+ ) {272+ return;273+ }274+275+ yield* write((story) =>276+ Effect.gen(function* () {277+ const landedAt = DateTime.add(yield* now, { minutes: 1 });278+279+ yield* devClock.set(landedAt);280+281+ return yield* landLintChild(story, landedAt);282+ })283+ );284+ }).pipe(Effect.provideService(Clock.Clock, clock)),285+ });286+287+ const overlaid = (api: ProjectApi): ProjectApi => ({288+ ...api,289+ credits: (_caller, handle) =>290+ Effect.map(current, (record) => ({291+ credits: creditsIn(record, handle),292+ })),293+ decide: (caller, input) =>294+ write((story) =>295+ Effect.gen(function* () {296+ const decision = yield* decisionTaken(yield* current, {297+ ...input,298+ now: yield* now,299+ who: caller.handle,300+ });301+302+ if (decision.decided !== undefined) {303+ story.decide(decision.id, decision.decided);304+ }305+306+ return { decision };307+ })308+ ),309+ [envSchemaMethod]: () => Effect.map(current, ({ env }) => env),310+ events: (since, limit) =>311+ Effect.andThen(312+ heard(since),313+ Effect.map(current, ({ events }) =>314+ events315+ .filter(({ seq }) => seq > since)316+ .slice(0, limit)317+ .map((event) => ({ event, seq: event.seq }))318+ )319+ ),320+ // As the service answers: a decider here or the log's claimant may321+ // read; anyone else hears `NotDecider` whether or not a log is kept,322+ // so the reply tells no one which logs exist.323+ evidence: (caller, ref) =>324+ Effect.gen(function* () {325+ const record = yield* current;326+ const log = Option.fromUndefinedOr(record.logs.get(ref));327+328+ const allowed = Option.exists(329+ callerOf(caller),330+ ({ handle }) =>331+ record.decisions.some(({ deciders }) =>332+ deciders.some((each) => sameHandle(each, handle))333+ ) ||334+ Option.exists(log, ({ claimant }) => sameHandle(claimant, handle))335+ );336+337+ if (!allowed) {338+ return yield* new NotDecider({});339+ }340+341+ if (Option.isNone(log)) {342+ return yield* new UnknownProject({ project: vellum });343+ }344+345+ return {346+ lane: log.value.lane,347+ text: log.value.text,348+ truncated: false,349+ };350+ }),351+ forks: () => Effect.map(current, ({ forks }) => forks),352+ head: () => Effect.map(current, ({ head }) => ({ landed: head })),353+ landing: (_caller, sha) =>354+ Effect.flatMap(current, (record) =>355+ Option.match(landingIn(record, sha), {356+ onNone: () => Effect.fail(new UnknownCommit({ sha })),357+ onSome: (landing) => Effect.succeed({ landing }),358+ })359+ ),360+ landings: (shas) =>361+ Effect.map(current, ({ landings }) =>362+ shas.flatMap((sha) =>363+ landings.filter((landing) => landing.sha === sha).slice(0, 1)364+ )365+ ),366+ ledger: () => Effect.map(current, ({ ledger }) => ledger),367+ listAsks: () =>368+ Effect.map(current, (record) => ({ asks: listedOf(record) })),369+ policy: () =>370+ Effect.flatMap(current, ({ head }) =>371+ Effect.map(api.policy(), (status) =>372+ status.policy === undefined373+ ? status374+ : { ...status, policy: { ...status.policy, at: head } }375+ )376+ ),377+ showAsk: (_caller, id) =>378+ Effect.flatMap(current, ({ asks }) =>379+ Effect.fromOption(Option.fromUndefinedOr(asks.get(id))).pipe(380+ Effect.mapError(() => new UnknownAsk({ ask: id })),381+ Effect.map((ask) => ({ ask, brief: briefOf(ask) }))382+ )383+ ),384+ showProposal: (_caller, id) =>385+ Effect.flatMap(current, ({ proposals }) =>386+ Effect.fromOption(Option.fromUndefinedOr(proposals.get(id))).pipe(387+ Effect.mapError(() => new UnknownProposal({ proposal: id }))388+ )389+ ),390+ status: (caller) =>391+ Effect.map(current, (record) => statusIn(record, caller.handle)),392+ today: (caller) =>393+ Effect.flatMap(Effect.zip(current, now), ([record, at]) =>394+ Effect.fromOption(395+ todayIn(record, caller.handle, at, decisionsPerDay)396+ ).pipe(Effect.mapError(() => new NotDecider({})))397+ ),398+ verdict: (_caller, input) =>399+ Effect.flatMap(current, (record) =>400+ record.asks.has(input.ask)401+ ? Effect.succeed(402+ Option.match(verdictIn(record, input.ask, input.head), {403+ onNone: () => ({}),404+ onSome: (verdict) => ({ verdict }),405+ })406+ )407+ : Effect.fail(new UnknownAsk({ ask: input.ask }))408+ ),409+ });410+411+ return Context.make(412+ Projects,413+ Projects.of({414+ create: projects.create,415+ get: (project) =>416+ isFixture(project)417+ ? Effect.map(projects.get(project), overlaid)418+ : projects.get(project),419+ })420+ ).pipe(421+ Context.add(DevProjected, {422+ events: Effect.gen(function* () {423+ const all = yield* projected.events;424+ const told = yield* Ref.get(fixtures.told);425+426+ return [427+ ...all.filter(({ project }) => !isFixture(project)),428+ ...Option.match(told, {429+ onNone: () => [],430+ onSome: ({ record }) =>431+ record.events.map((event) =>432+ ProjectedEvent.make({ event, project: vellum })433+ ),434+ }),435+ ];436+ }),437+ })438+ );439+ })440+);441+442+/**443+ * The fixtures told into a world the default seed has seeded: the fillers,444+ * then vellum (made and first pushed through the service, its record told445+ * over its repo), and the world's clock left at the record's morning.446+ */447+const seedFixtures = Effect.gen(function* () {448+ const fixtures = yield* Fixtures;449+450+ yield* seedFillers(30);451+452+ const { landed } = yield* startedAt(453+ vellum,454+ vellumInitializer,455+ vellumFiles,456+ vellumStart457+ );458+459+ const { story, told } = yield* tellVellum(landed);460+ const record = yield* decodeRecord(told());461+462+ yield* Ref.set(fixtures.told, Option.some({ record, story, told }));463+ yield* (yield* DevClock).set(fixturesNow);464+}).pipe(Effect.orDie);465+466+/**467+ * A fresh world with the fixtures, seeded: the default seed, then the468+ * fixtures. In `live` mode the lint child lands `liveAfter` after vellum's469+ * `watch` is first answered.470+ */471+export const withFixtures = (472+ mode: "on" | "live",473+ liveAfter: Duration.Duration = LIVE_AFTER474+) =>475+ Layer.effectDiscard(Effect.andThen(seedDev, seedFixtures)).pipe(476+ Layer.provideMerge(477+ devWorldWith(478+ overlay.pipe(479+ Layer.provideMerge(480+ fixturesLayer(481+ mode === "live" ? Option.some(liveAfter) : Option.none()482+ )483+ )484+ )485+ )486+ )487+ );modified:apps/web/src/dev/seed.ts+23 added-10 removed
37 unmodified lines38 39 const mainRef = RefName.make("refs/heads/main");40 41 /** People who propose and flag in datekit; nobody vouched for them. */42-const visitors = {42+export const visitors = {43 flagger: Handle.make("sefa"),44 proposer: Handle.make("tove"),45 regular: Handle.make("wren"),46 } as const;71 unmodified lines118 clock.set(devMinute(minute))119 );120 121 /**122- * A project made and adopted: its initializer creates it, pushes its first123- * commit, and the gateway reports the push.122+ * A project made and adopted at `when`: its initializer creates it, pushes123+ * its first commit a minute later, and the gateway reports the push.124 */125-const started = (125+export const startedAt = (126 project: ProjectName,127 initializer: Handle,128 files: Files,129- minute: number129+ when: DateTime.Utc130 ) =>131 Effect.gen(function* () {132 const projects = yield* Projects;133+ const clock = yield* DevClock;134 134- yield* at(minute);135+ yield* clock.set(when);136 137 const api = yield* projects.create(project);138 139 yield* api.initProject(as(initializer), {});139- yield* at(minute + 1);140+ yield* clock.set(DateTime.add(when, { minutes: 1 }));141 142 const first = yield* pushed(RepoName.make(project), {143 author: initializer,144 files,145 message: "First commit",146 parent: Option.none(),147 });148 148- yield* api.recordFirstPush(as(initializer), first);149+ const { landed } = yield* api.recordFirstPush(as(initializer), first);150 150- return api;151+ return { api, landed };152 });153 154+/** A project made and adopted at `minute` minutes after the world's start. */155+const started = (156+ project: ProjectName,157+ initializer: Handle,158+ files: Files,159+ minute: number160+) =>161+ Effect.map(162+ startedAt(project, initializer, files, devMinute(minute)),163+ ({ api }) => api164+ );165+166 /** Each ask opened by `decider` from its files, a minute apart from `minute`. */154-const opened = (167+export const opened = (168 api: ProjectApi,169 decider: Handle,170 asks: readonly (readonly [AskId, Opening])[],171 minute: number193 unmodified linesmodified:apps/web/src/dev/server.ts+20 added-6 removed
11 unmodified lines12131415161718192021222324252624252627272829303132333435363738394041424344454628 unmodified lines757677786579808182832 unmodified lines868788897690919211 unmodified linesimport { Projects } from "@repo/project/projects";import { Contracts } from "@repo/protocol/contracts";import { ProjectName } from "@repo/protocol/ids";import { Context, Effect, Layer, Option, Schema } from "effect";import type { Duration } from "effect";import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";import { RpcSerialization, RpcServer } from "effect/rpc";
import { withFixtures } from "./fixtures.ts";import type { FixtureMode } from "./fixtures.ts";import { devHandlers } from "./handlers.ts";import { seedDev } from "./seed.ts";import { devSessions } from "./sessions.ts";import { devWorld } from "./world.ts";
/** A fresh world, seeded. */const seededWorld = Layer.effectDiscard(seedDev).pipe( Layer.provideMerge(devWorld));/** How a dev world is made: with the fixtures or without, and how soon the live landing comes. */export interface DevWorldOptions { readonly fixtures?: FixtureMode; /** In `live` mode, how long after vellum's `watch` is first answered its lint child lands. */ readonly liveAfter?: Duration.Duration;}
/** A fresh world, seeded; with the fixtures when `options` asks for them. */const seededWorld = (options: DevWorldOptions) => { const { fixtures = "off" } = options;
return fixtures === "off" ? Layer.effectDiscard(seedDev).pipe(Layer.provideMerge(devWorld)) : withFixtures(fixtures, options.liveAfter);};
const decodeProject = Schema.decodeUnknownOption(ProjectName);
/** `/<project>/raw/<rev>/<path…>`: a project's raw files, as the platform serves them. */const raw = Layer.unwrap(28 unmodified lines * its layer as soon as it is called, so the world is made and seeded from * that moment, and a request that arrives before the seed is done waits for * it. `dispose` ends the world. */export const devServer = () =>export const devServer = (options: DevWorldOptions = {}) => HttpRouter.toWebHandler( Layer.merge( RpcServer.layerHttp({ group: Contracts,2 unmodified lines }).pipe( Layer.provide([devHandlers, devSessions, RpcSerialization.layerJson]) ), raw ).pipe(Layer.provide(seededWorld)), ).pipe(Layer.provide(seededWorld(options))), { disableLogger: true } );modified:apps/web/src/dev/world.ts+24 added-6 removed
44 unmodified lines454647484950515253545556575859606162636465666768697071727374757677785657585960617944 unmodified lines Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)), Layer.provideMerge(RepoHostMemory));
/** The project service over every port, before anything reads it. */const core = withDraftRunsInline(ProjectsMemory).pipe( Layer.provideMerge(ports));
/** What the read side of a world is built over: its projects and their projected events. */export type DevCore = Layer.Success<typeof core> | DevClock;
/** * A fresh world whose front page and handlers read through `between`, * which may stand in for the projects and the projected events it is * given (the fixtures do, `fixtures.ts`). Built twice, it is two worlds. */export const devWorldWith = <Out, E, In extends DevCore>( between: Layer.Layer<Out, E, In>) => Layer.mergeAll(DevFrontPage, EvidenceStoreMemory).pipe( Layer.provideMerge(between), Layer.provideMerge(core), Layer.provideMerge(devClockAt(devStart)), Layer.fresh );
/** * A fresh, empty world: its projects, the front page over them, the lane * logs, the repo host the people's git pushes to, and its clock at * `devStart`. Built twice, it is two worlds. */export const devWorld: Layer.Layer< Projects | FrontPage | EvidenceStore | RepoHost | DevClock> = Layer.mergeAll(DevFrontPage, EvidenceStoreMemory).pipe( Layer.provideMerge(withDraftRunsInline(ProjectsMemory)), Layer.provideMerge(ports), Layer.provideMerge(devClockAt(devStart)), Layer.fresh);> = devWorldWith(Layer.empty);modified:apps/web/test/dev-backend.test.ts+23 added
204 unmodified lines205 expect(Equal.equals(first, second)).toBeTruthy();206 })207 );208 209+ it.live("adds none of the fixtures without their switch", () =>210+ Effect.gen(function* () {211+ const { entries, projects } = yield* pages;212+ const listed = new Set(projects.map(({ project }) => project));213+214+ for (const fixture of [215+ "vellum",216+ "amberlog",217+ "cinderbox",218+ "fernwick",219+ "mossgate",220+ "quillon",221+ "tidepool",222+ ]) {223+ expect(listed.has(ProjectName.make(fixture))).toBeFalsy();224+ }225+226+ expect(227+ entries.every(({ project }) => PROJECTS.includes(project))228+ ).toBeTruthy();229+ })230+ );231+232 it.live("counts every time it holds in whole minutes from one start", () =>233 Effect.gen(function* () {234 const seen = yield* instants;235 const minute = Duration.toMillis(Duration.minutes(1));184 unmodified linesadded:apps/web/test/dev-fixtures.test.ts+723 added
1+/**2+ * The dev world with its fixtures switched on: every state a page draws,3+ * served through the contracts the pages call, beside datekit and burrow.4+ * Each case reads a fresh world the way a browser would, over `/rpc`.5+ */6+import { describe, expect, it } from "@effect/vitest";7+import { Client, Contracts } from "@repo/protocol/contracts";8+import { DecisionSubject } from "@repo/protocol/domain/decision";9+import { ProjectEvent } from "@repo/protocol/domain/event";10+import { Outcome } from "@repo/protocol/domain/outcome";11+import { LedgerEntry } from "@repo/protocol/domain/visibility";12+import {13+ AskId,14+ DecisionId,15+ Handle,16+ ProjectName,17+ ProposalId,18+} from "@repo/protocol/ids";19+import { Context, DateTime, Duration, Effect, Layer, Stream } from "effect";20+import type { Scope } from "effect";21+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";22+import { RpcClient, RpcSerialization } from "effect/rpc";23+24+import { askStates, familyMarks } from "../src/client/events.ts";25+import type { DevWorldOptions } from "../src/dev/server.ts";26+import { devServer } from "../src/dev/server.ts";27+import { devToken } from "../src/dev/sessions.ts";28+29+const vellum = ProjectName.make("vellum");30+31+const ask = (id: string) => AskId.make(id);32+33+const signedIn = (handle: string) => devToken(Handle.make(handle));34+35+/** A client of `handler`'s `/rpc`, whose calls carry `token` as their bearer when there is one. */36+const connect = (37+ handler: (request: Request) => Promise<Response>,38+ token?: string39+) =>40+ Effect.map(41+ Layer.build(42+ Layer.effect(Client)(RpcClient.make(Contracts)).pipe(43+ Layer.provide(44+ RpcClient.layerProtocolHttp({45+ transformClient: HttpClient.mapRequest((request) =>46+ token === undefined47+ ? request48+ : HttpClientRequest.bearerToken(request, token)49+ ),50+ url: "http://localhost/rpc",51+ })52+ ),53+ Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson]),54+ Layer.provide(55+ Layer.succeed(FetchHttpClient.Fetch, (input, init) =>56+ handler(new Request(input, init))57+ )58+ )59+ )60+ ),61+ Context.get(Client)62+ );63+64+type Reader = Effect.Success<ReturnType<typeof connect>>;65+66+/** A fresh world with `options`, served, and `read` run against it. */67+const inWorld = <A, E>(68+ options: DevWorldOptions,69+ read: (70+ as: (token?: string) => Effect.Effect<Reader, never, Scope.Scope>71+ ) => Effect.Effect<A, E, Scope.Scope>72+) =>73+ Effect.scoped(74+ Effect.gen(function* () {75+ const { dispose, handler } = devServer(options);76+77+ yield* Effect.addFinalizer(() => Effect.promise(dispose));78+79+ return yield* read((token) => connect(handler, token));80+ })81+ );82+83+const withFixtures: DevWorldOptions = { fixtures: "on" };84+85+/** vellum's events, as `watch` replays them from the first. */86+const eventsOf = (client: Reader) =>87+ Effect.map(88+ Stream.runCollect(client.watch({ project: vellum })),89+ (events): readonly ProjectEvent[] => events90+ );91+92+/** The `AskClosed` events among `events`. */93+const closedIn = (events: readonly ProjectEvent[]) =>94+ events.filter(ProjectEvent.guards.AskClosed);95+96+/** The tag of each answer state's verdict outcome, by ask. */97+const ANSWERS = {98+ "carry-footnotes-to-epub": "Landed",99+ "cli-version-flag": "Landed",100+ "escape-attribute-quotes": "AwaitingDecision",101+ "footnote-backrefs": "WaitingOnParent",102+ "render-code-blocks": "Landed",103+ "render-nested-lists": "Refused",104+ "retire-old-tokenizer-vellum-lint": "Checking",105+ "retire-old-tokenizer-vellum-parser": "Refused",106+ "trim-trailing-spaces": "Refused",107+ "wrap-long-table-cells": "AwaitingFinish",108+} as const;109+110+const answersRead = inWorld(withFixtures, (as) =>111+ Effect.gen(function* () {112+ const anyone = yield* as();113+114+ const verdicts = yield* Effect.forEach(Object.keys(ANSWERS), (id) =>115+ Effect.map(116+ anyone.verdict({ ask: ask(id), project: vellum }),117+ ({ verdict }) => [id, verdict] as const118+ )119+ );120+121+ const byAsk = new Map(verdicts);122+123+ const landingOf = (id: string) => {124+ const outcome = byAsk.get(id)?.outcome;125+126+ return outcome !== undefined && Outcome.guards.Landed(outcome)127+ ? Effect.map(128+ anyone.landing({ project: vellum, sha: outcome.sha }),129+ ({ landing }) => landing130+ )131+ : Effect.die(`${id} did not land`);132+ };133+134+ return {135+ byAsk,136+ decided: yield* landingOf("carry-footnotes-to-epub"),137+ events: yield* eventsOf(anyone),138+ plain: yield* landingOf("cli-version-flag"),139+ };140+ })141+);142+143+/** Each refusal of a refused outcome, as its tag and the place it points at. */144+const refusalsOf = (outcome: Outcome | undefined) =>145+ outcome !== undefined && Outcome.guards.Refused(outcome)146+ ? outcome.refusals147+ : [];148+149+/**150+ * Each hunk of a unified diff, as its header declares its old and new151+ * lengths and as its lines count them, so a patch a diff view cannot parse152+ * shows as a mismatch.153+ */154+const hunksOf = (patch: string) => {155+ const hunks: { declared: string; counted: string }[] = [];156+ let old = 0;157+ let fresh = 0;158+ let declared: string | undefined;159+160+ const close = () => {161+ if (declared !== undefined) {162+ hunks.push({ counted: `${old}/${fresh}`, declared });163+ }164+ };165+166+ for (const line of patch.split("\n")) {167+ const header =168+ /^@@ -\d+(?:,(?<old>\d+))? \+\d+(?:,(?<fresh>\d+))? @@/u.exec(line);169+170+ if (header !== null) {171+ close();172+ declared = `${header.groups?.old ?? "1"}/${header.groups?.fresh ?? "1"}`;173+ old = 0;174+ fresh = 0;175+ } else if (line.startsWith("diff --git ")) {176+ close();177+ declared = undefined;178+ } else if (declared !== undefined && line !== "") {179+ old += line.startsWith("+") ? 0 : 1;180+ fresh += line.startsWith("-") ? 0 : 1;181+ }182+ }183+184+ close();185+186+ return hunks;187+};188+189+/**190+ * Each test seeds a whole world with its fixtures while turbo runs every191+ * package's tests at once, as `dev-backend.test.ts` does.192+ */193+const seededWorlds = { timeout: 30_000 };194+195+describe("the dev world's fixtures", seededWorlds, () => {196+ it.live(197+ "list more than eight projects, vellum and one with no open asks among them",198+ () =>199+ inWorld(withFixtures, (as) =>200+ Effect.gen(function* () {201+ const { projects } = yield* (yield* as()).listProjects({});202+ const names = new Set(projects.map(({ project }) => project));203+204+ expect(projects.length).toBeGreaterThan(8);205+ expect(206+ ["burrow", "datekit", "vellum"].filter(207+ (name) => !names.has(ProjectName.make(name))208+ )209+ ).toStrictEqual([]);210+ expect(211+ projects.find(({ project }) => project === "mossgate")?.openAsks212+ ).toBe(0);213+ })214+ )215+ );216+217+ it.live("give every answer state its verdict", () =>218+ Effect.gen(function* () {219+ const { byAsk } = yield* answersRead;220+221+ expect(222+ Object.fromEntries(223+ [...byAsk].map(([id, verdict]) => [id, verdict?.outcome._tag])224+ )225+ ).toStrictEqual(ANSWERS);226+ expect({227+ checking: byAsk.get("retire-old-tokenizer-vellum-lint")?.outcome,228+ decision: byAsk.get("escape-attribute-quotes")?.outcome,229+ finish: byAsk.get("wrap-long-table-cells")?.outcome,230+ parent: byAsk.get("footnote-backrefs")?.outcome,231+ }).toStrictEqual({232+ checking: Outcome.cases.Checking.make({ stage: "checks" }),233+ decision: Outcome.cases.AwaitingDecision.make({234+ decision: DecisionId.make("dec-000002"),235+ }),236+ finish: Outcome.cases.AwaitingFinish.make({237+ decider: Handle.make("ines-v"),238+ }),239+ parent: Outcome.cases.WaitingOnParent.make({240+ ask: ask("number-footnotes"),241+ }),242+ });243+ })244+ );245+246+ it.live(247+ "refuse at Shape with a place, at the held-back stage by area, and at the checks with a failed lane's log",248+ () =>249+ Effect.gen(function* () {250+ const { byAsk } = yield* answersRead;251+ const scope = byAsk.get("trim-trailing-spaces");252+ const held = byAsk.get("retire-old-tokenizer-vellum-parser");253+ const checks = byAsk.get("render-nested-lists");254+255+ const [outside] = refusalsOf(scope?.outcome);256+ const [sealed] = refusalsOf(held?.outcome);257+ const [failed] = refusalsOf(checks?.outcome);258+259+ expect([scope?.stage, outside?._tag, outside?.at]).toStrictEqual([260+ "shape",261+ "OutOfScope",262+ { line: 3, path: "packages/cli/src/args.ts" },263+ ]);264+ expect([held?.stage, sealed?._tag, held?.heldBack]).toMatchObject([265+ "heldBack",266+ "HeldBackFailed",267+ [{ area: "parser", passed: 3, total: 4 }],268+ ]);269+ expect([checks?.stage, failed?._tag]).toStrictEqual([270+ "checks",271+ "ChecksFailed",272+ ]);273+ expect(274+ checks?.lanes275+ .filter(({ result }) => result === "failed")276+ .map(({ lane, logRef }) => [lane, logRef !== undefined])277+ ).toStrictEqual([["unit", true]]);278+ })279+ );280+281+ it.live(282+ "give a failed lane's log to its claimant, and the same NotDecider to anyone else whether or not a log is kept",283+ () =>284+ inWorld(withFixtures, (as) =>285+ Effect.gen(function* () {286+ const anyone = yield* as();287+ const nested = ask("render-nested-lists");288+289+ const { verdict } = yield* anyone.verdict({290+ ask: nested,291+ project: vellum,292+ });293+294+ const ref = verdict?.lanes.find(295+ ({ logRef }) => logRef !== undefined296+ )?.logRef;297+298+ const claimant = askStates(yield* eventsOf(anyone)).get(299+ nested300+ )?.claimant;301+302+ const read = (client: Reader, logRef: string) =>303+ Effect.match(client.evidence({ project: vellum, ref: logRef }), {304+ onFailure: ({ _tag }): string => _tag,305+ onSuccess: ({ lane }): string => lane,306+ });307+308+ const owner = yield* as(signedIn(claimant ?? "nobody"));309+ const stranger = yield* as(signedIn("wren"));310+311+ expect(claimant).toBeDefined();312+ expect([313+ yield* read(owner, ref ?? ""),314+ yield* read(stranger, ref ?? ""),315+ yield* read(316+ stranger,317+ "push-0000000000000000000000000000000000000000-wren/unit"318+ ),319+ ]).toStrictEqual(["unit", "NotDecider", "NotDecider"]);320+ })321+ )322+ );323+324+ it.live(325+ "land one answer with a decision and the Held-back trailer, and one with neither",326+ () =>327+ Effect.gen(function* () {328+ const { byAsk, decided, plain } = yield* answersRead;329+330+ expect(decided.heldBackTrailer).toMatch(331+ /^export 7\/7 @ sha256:[0-9a-f]{64}; parser 4\/4 @ sha256:[0-9a-f]{64}$/u332+ );333+ expect(decided.credits.map(({ role }) => role)).toContain("Decided-by");334+ expect({335+ attended: plain.credits.filter(336+ ({ role }) => role === "Decided-by" || role === "Finished-by"337+ ),338+ heldBack: byAsk.get("cli-version-flag")?.heldBack,339+ trailer: plain.heldBackTrailer,340+ }).toStrictEqual({ attended: [], heldBack: [], trailer: undefined });341+ })342+ );343+344+ it.live("replay an answer's three rounds: refused twice, then landed", () =>345+ Effect.gen(function* () {346+ const { events } = yield* answersRead;347+ const progress = askStates(events).get(ask("render-code-blocks"));348+349+ expect(progress?.rounds.map(({ outcome }) => outcome._tag)).toStrictEqual(350+ ["Refused", "Refused", "Checking"]351+ );352+ expect(progress?.landed).toBeDefined();353+ })354+ );355+356+ it.live(357+ "fold the first family's events into one child in every mark, its delete child waiting",358+ () =>359+ inWorld(withFixtures, (as) =>360+ Effect.gen(function* () {361+ const anyone = yield* as();362+ const parent = ask("retire-old-tokenizer");363+ const shown = yield* anyone.showAsk({ ask: parent, project: vellum });364+ const states = askStates(yield* eventsOf(anyone));365+ const family = familyMarks(shown.ask, states);366+ const { asks } = yield* anyone.listAsks({ project: vellum });367+368+ // The parent stores its six children, then the delete child.369+ expect(shown.ask.blockedBy).toHaveLength(7);370+ expect(shown.ask.blockedBy.at(-1)).toBe(371+ "retire-old-tokenizer-delete"372+ );373+ expect(374+ family.children.slice(0, 6).map(({ mark }) => mark)375+ ).toStrictEqual([376+ "landed",377+ "landed",378+ "checking",379+ "refused",380+ "claimed",381+ "open",382+ ]);383+ expect(384+ asks.find(({ ask: id }) => id === "retire-old-tokenizer-delete")385+ ).toBeDefined();386+ })387+ )388+ );389+390+ it.live(391+ "land the second family's children and open its delete child to take",392+ () =>393+ inWorld(withFixtures, (as) =>394+ Effect.gen(function* () {395+ const anyone = yield* as();396+ const parent = ask("rename-page-size");397+ const shown = yield* anyone.showAsk({ ask: parent, project: vellum });398+ const states = askStates(yield* eventsOf(anyone));399+ const { entries } = yield* anyone.frontPage({});400+401+ const children = shown.ask.blockedBy.filter(402+ (child) => child !== "rename-page-size-delete"403+ );404+405+ expect(children.length).toBeGreaterThanOrEqual(2);406+ expect(407+ children.filter((child) => states.get(child)?.landed === undefined)408+ ).toStrictEqual([]);409+ expect(410+ entries.find(411+ (entry) =>412+ entry.project === vellum &&413+ entry.ask.ask === "rename-page-size-delete"414+ )?.takeable415+ ).toBeTruthy();416+ })417+ )418+ );419+420+ it.live(421+ "hold asks open, held for newcomers, claimed with and without a push, and one with a long want",422+ () =>423+ inWorld(withFixtures, (as) =>424+ Effect.gen(function* () {425+ const anyone = yield* as();426+ const { asks } = yield* anyone.listAsks({ project: vellum });427+ const states = askStates(yield* eventsOf(anyone));428+ const held = asks.find(({ reserve }) => reserve === "newcomers");429+430+ const mentored = yield* anyone.showAsk({431+ ask: held?.ask ?? ask("missing"),432+ project: vellum,433+ });434+435+ const render = states.get(ask("retire-old-tokenizer-vellum-render"));436+437+ expect(mentored.ask.mentor).toBe("okonkwo");438+ expect(asks.some(({ want }) => want.length > 80)).toBeTruthy();439+ expect([render?.claimant, render?.lastPush]).toStrictEqual([440+ "sefa",441+ undefined,442+ ]);443+ expect(states.get(ask("number-footnotes"))?.lastPush).toBeDefined();444+ })445+ )446+ );447+448+ it.live(449+ "put every kind of decision on a decider's Today, one due within the day and two of five taken",450+ () =>451+ inWorld(withFixtures, (as) =>452+ Effect.gen(function* () {453+ const project = vellum;454+ const ines = yield* as(signedIn("ines-v"));455+ const mine = yield* ines.today({ project });456+ const merged = yield* ines.today({});457+458+ const others = yield* Effect.forEach(["okonkwo", "lin-h"], (handle) =>459+ Effect.flatMap(as(signedIn(handle)), (client) =>460+ client.today({ project })461+ )462+ );463+464+ const kinds = new Set(465+ [mine, ...others].flatMap(({ decisions }) =>466+ decisions.map(({ subject }) => subject._tag)467+ )468+ );469+470+ expect({471+ budget: [mine.budget.used, mine.budget.total],472+ dueToday: mine.expiringSoon.length,473+ overflow: mine.overflow,474+ shown: mine.decisions.some(({ id }) => id === mine.expiringSoon[0]),475+ }).toStrictEqual({476+ budget: [2, 5],477+ dueToday: 1,478+ overflow: 3,479+ shown: true,480+ });481+ expect([482+ mine.newcomers.length > 0,483+ mine.unattended.length > 0,484+ merged.overflow >= 3,485+ ]).toStrictEqual([true, true, true]);486+ expect([...kinds].toSorted()).toStrictEqual(487+ Object.keys(DecisionSubject.cases).toSorted()488+ );489+ })490+ )491+ );492+493+ it.live(494+ "show a Finish decision with its diff, a refusal's place inside it, and the fork to finish from",495+ () =>496+ inWorld(withFixtures, (as) =>497+ Effect.gen(function* () {498+ const ines = yield* as(signedIn("ines-v"));499+ const { decisions } = yield* ines.today({ project: vellum });500+501+ const finish = decisions.find(({ subject }) =>502+ DecisionSubject.guards.Finish(subject)503+ );504+505+ const patch = finish?.evidence.find(506+ ({ label }) => label === "patch"507+ )?.value;508+509+ const rounds =510+ askStates(yield* eventsOf(ines)).get(ask("wrap-long-table-cells"))511+ ?.rounds ?? [];512+513+ const placed = rounds514+ .flatMap(({ outcome }) => refusalsOf(outcome))515+ .flatMap(({ at }) => (at === undefined ? [] : [at]));516+517+ expect(finish?.evidence.map(({ label }) => label)).toContain("fork");518+ expect(placed).toHaveLength(1);519+ expect(patch).toContain(`+++ b/${placed[0]?.path}`);520+521+ // Every hunk holds the lines its header declares, or the diff view refuses it.522+ const hunks = hunksOf(patch ?? "");523+524+ expect(hunks.length).toBeGreaterThan(0);525+ expect(hunks.map(({ counted }) => counted)).toStrictEqual(526+ hunks.map(({ declared }) => declared)527+ );528+ })529+ )530+ );531+532+ it.live(533+ "keep a ledger of sealed evidence: a layer, two areas, and history of every kind",534+ () =>535+ inWorld(withFixtures, (as) =>536+ Effect.gen(function* () {537+ const anyone = yield* as();538+ const ledger = yield* anyone.ledger({ project: vellum });539+ const { projects } = yield* anyone.listProjects({});540+541+ expect([542+ ledger.posture,543+ projects.find(({ project }) => project === vellum)?.posture,544+ ]).toStrictEqual([545+ "openWithSealedEvidence",546+ "openWithSealedEvidence",547+ ]);548+ expect(549+ ledger.layers.map(({ name, reason }) => [name, reason.length > 0])550+ ).toStrictEqual([["maintainers", true]]);551+ expect(552+ ledger.entries.flatMap((entry) =>553+ LedgerEntry.guards.CommitmentPublished(entry)554+ ? [[entry.area, entry.checks, entry.authors]]555+ : []556+ )557+ ).toStrictEqual([558+ ["export", 7, 3],559+ ["parser", 4, 3],560+ ]);561+ expect(new Set(ledger.entries.map(({ _tag }) => _tag))).toStrictEqual(562+ new Set([563+ "Admitted",564+ "CommitmentPublished",565+ "CountChanged",566+ "LayerDeclared",567+ "PostureChanged",568+ "Released",569+ "ValueSet",570+ ])571+ );572+ })573+ )574+ );575+576+ it.live(577+ "declare an env schema with a write-only item someone set, and never a value",578+ () =>579+ inWorld(withFixtures, (as) =>580+ Effect.gen(function* () {581+ const declared = yield* (yield* as()).envShape({ project: vellum });582+583+ const token = declared.items.find(584+ ({ key }) => key === "SENTRY_AUTH_TOKEN"585+ );586+587+ expect(declared.items).toHaveLength(4);588+ expect({589+ proxy: token?.proxy,590+ sensitive: token?.sensitive,591+ setBy: token?.value?.setBy,592+ }).toStrictEqual({593+ proxy: { domains: ["sentry.io"], path: "/api/**" },594+ sensitive: true,595+ setBy: "ines-v",596+ });597+ expect(598+ declared.items.some(({ deprecated }) => deprecated === true)599+ ).toBeTruthy();600+ expect(601+ declared.items.filter(602+ ({ placeholder }) => placeholder !== undefined603+ )604+ ).toStrictEqual([]);605+ })606+ )607+ );608+609+ it.live("state a policy with deciders by path and a denounced person", () =>610+ inWorld(withFixtures, (as) =>611+ Effect.gen(function* () {612+ const { policy } = yield* (yield* as()).projectPolicy({613+ project: vellum,614+ });615+616+ expect(617+ new Set(policy?.deciders.map(({ paths }) => paths)).size618+ ).toBeGreaterThan(2);619+ expect(620+ policy?.vouches621+ .filter(({ denounced }) => denounced)622+ .map(({ handle }) => handle)623+ ).toStrictEqual(["wren"]);624+ })625+ )626+ );627+628+ it.live("draft proposals into every state a draft settles in", () =>629+ inWorld(withFixtures, (as) =>630+ Effect.gen(function* () {631+ const anyone = yield* as();632+633+ const shown = yield* Effect.forEach(634+ ["prop-000002", "prop-000003", "prop-000004", "prop-000005"],635+ (id) =>636+ anyone.showProposal({637+ project: vellum,638+ proposal: ProposalId.make(id),639+ })640+ );641+642+ expect(643+ shown.map(({ files, proposal }) => [644+ proposal.draft?._tag,645+ files.length,646+ ])647+ ).toStrictEqual([648+ ["Ready", 3],649+ ["Failed", 0],650+ ["Failed", 3],651+ ["Drafting", 0],652+ ]);653+ })654+ )655+ );656+657+ it.live(658+ "list landings across three days, tags, and claim forks in every state",659+ () =>660+ inWorld(withFixtures, (as) =>661+ Effect.gen(function* () {662+ const anyone = yield* as();663+ const refs = yield* anyone.listRefs({ project: vellum });664+ const { commits } = yield* anyone.log({ project: vellum });665+666+ const landings = commits.flatMap(({ landing }) =>667+ landing === undefined ? [] : [landing]668+ );669+670+ expect(refs.tags.length).toBeGreaterThan(0);671+ expect(672+ new Set(refs.forks.map(({ kind, state }) => state ?? kind))673+ ).toStrictEqual(674+ new Set([675+ "answered",676+ "lapsed",677+ "live",678+ "released",679+ "warned",680+ "working",681+ ])682+ );683+ expect(684+ new Set(685+ landings.map(({ landedAt }) =>686+ DateTime.formatIsoDateUtc(landedAt)687+ )688+ ).size689+ ).toBeGreaterThanOrEqual(3);690+ expect([691+ landings.some(({ opened }) => opened !== undefined),692+ landings.some(693+ ({ heldBackTrailer }) => heldBackTrailer !== undefined694+ ),695+ ]).toStrictEqual([true, true]);696+ })697+ )698+ );699+});700+701+describe("the dev world's live landing", seededWorlds, () => {702+ it.live(703+ "lands one more child of the first family after the project's watch is first read",704+ () =>705+ inWorld({ fixtures: "live", liveAfter: Duration.zero }, (as) =>706+ Effect.gen(function* () {707+ const anyone = yield* as();708+ const first = yield* eventsOf(anyone);709+ const second = yield* eventsOf(anyone);710+711+ const landed = closedIn(second).find(712+ (event) => !closedIn(first).some(({ seq }) => seq === event.seq)713+ );714+715+ expect(closedIn(second)).toHaveLength(closedIn(first).length + 1);716+ expect(landed?.ask).toBe("retire-old-tokenizer-vellum-lint");717+ expect(landed?.seq).toBeGreaterThan(718+ Math.max(...first.map(({ seq }) => seq))719+ );720+ })721+ )722+ );723+});