Trim comments in agent-kit, artifacts, brand and config to the essential ones
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parent ca0f25c · Browse files · 84 files·+128 added−1847 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
84 files+128 added−1847 removed
- tests:+65 added−878 removed
- other:+63 added−969 removed
Provenance
- Commit
022043d- Tree
b9abc7b- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
ca0f25c
84 files changed+128 added−1847 removed
modified:packages/agent-kit/src/docs/answer-an-ask.ts-5 removed
12345123458 unmodified lines/** * The contributor's guide: install and sign in, find an ask, claim it, * answer it in git, check it before the push, push, read the verdict, and * what to do when it is refused. */import { Brand } from "@repo/brand";
import { installCommand } from "../install.ts";import { code } from "../text.ts";58 unmodified linesmodified:packages/agent-kit/src/docs/connect-an-agent.ts-6 removed
123456123423 unmodified lines/** * The agent guide: the ways an agent reaches the platform, each pointing * to the For agents page that holds the exact setup, and the rules that * hold for any agent. */
import { code } from "../text.ts";import type { DocSource } from "./page.ts";import { cli } from "./page.ts";
23 unmodified linesmodified:packages/agent-kit/src/docs/entries.ts-11 removed
1-/**2- * What names each page of the docs: its title, its one-line summary and3- * whether it is a guide or the reference, in the order the index lists4- * them. Apart from the pages' text, so a route's head and its not-found5- * read it without carrying every page into the first load.6- */1 import { Option } from "effect";2 9-/** A guide, written for a person doing one job, or a page of the reference. */3 export type DocPart = "guide" | "reference";4 12-/** What names a page, before it is written: enough for a list or a head. */5 export interface DocEntry {6 readonly slug: string;7 readonly title: string;8 readonly summary: string;9 readonly part: DocPart;10 }11 20-/** Every page as the index lists it, guides first. */12 export const docEntries = [13 {14 part: "guide",15 slug: "start-here",77 unmodified lines93 title: "Imported projects",94 },95 ] as const satisfies readonly DocEntry[];96 106-/** A page's slug: the last segment of its address. */97 export type DocSlug = (typeof docEntries)[number]["slug"];98 109-/** The page at `slug` as a list or a head names it; none for a slug no page has. */99 export const docEntry = (slug: string): Option.Option<DocEntry> =>100 Option.fromUndefinedOr(docEntries.find((entry) => entry.slug === slug));modified:packages/agent-kit/src/docs/held-back-checks.ts-5 removed
12345123451 unmodified lines/** * The visibility guide: layers and their audiences, held-back checks and * what an answerer learns of them, the posture and the ledger anyone can * read, and the env shape with its write-only values. */import { Brand } from "@repo/brand";
import { code } from "../text.ts";import type { DocSource } from "./page.ts";51 unmodified linesmodified:packages/agent-kit/src/docs/imported-note.ts-5 removed
1234512/** * What an imported project is, in the words the docs' Imported projects * page, the project's own page and the CLI's `policy` share. A module of * its own, so a page that says it does not carry the imported list. */export const IMPORTED_NOTE = "a copy of a public repo, read-only here and not run by its maintainers";modified:packages/agent-kit/src/docs/imported.ts-13 removed
1-/**2- * The open-source projects imported onto the platform for reading, each a3- * copy of a public repo under its own licence, read-only here and not run4- * by its maintainers. A copy of the import script's plan, which a test in5- * `packages/config` holds equal to it, so the docs can name each one's6- * source and licence.7- */1 import { ProjectKey, ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";2 import { Option } from "effect";3 11-/**12- * One imported project: its name here, after its source namespace13- * (`github.com/pallets/click`), the key it was imported under (`click`),14- * its source, its licence, and what it is.15- */4 export interface ImportedProject {5 readonly name: ProjectName;6 readonly key: ProjectKey;7 readonly url: string;13 unmodified lines21 name: ProjectName.make(`${Option.getOrThrow(sourceNamespaceOf(url))}/${key}`),22 url,23 });24 37-/** Every imported project, in the order they were imported. */25 export const importedProjects: readonly ImportedProject[] = [26 imported(27 "anyhow",28 "https://github.com/dtolnay/anyhow",211 unmodified linesmodified:packages/agent-kit/src/docs/index.ts-9 removed
1-/**2- * The docs: five guides written for people doing one job, then the3- * reference, read from the sources that define it. Each page is pure4- * Markdown for the CLI's commands and the two hosts' URLs; the web draws5- * it at `/docs/<slug>` and serves the text at `/docs/<slug>.md`.6- */1 import { Option } from "effect";2 3 import { answerAnAsk } from "./answer-an-ask.ts";4 import { connectAnAgent } from "./connect-an-agent.ts";18 unmodified lines23 export type { DocEntry, DocPart, DocSlug } from "./entries.ts";24 25 export type { DocInput, DocPage } from "./page.ts";26 33-/** Every page, guides first, in the order the index lists them. */27 const sources: readonly DocSource[] = [28 startHere,29 answerAnAsk,30 runAProject,7 unmodified lines38 mcpPage,39 importedPage,40 ];41 49-/** Every page, written for `input`. */42 export const docPages = (input: DocInput): readonly DocPage[] =>43 sources.flatMap((source) =>44 Option.toArray(45 Option.map(docEntry(source.slug), (entry) =>1 unmodified line47 )48 )49 );50 59-/** The page at `slug`, written for `input`; none for a slug no page has. */51 export const docPage = (52 input: DocInput,53 slug: string54 ): Option.Option<DocPage> =>5 unmodified linesmodified:packages/agent-kit/src/docs/page.ts-12 removed
1-/**2- * One page of the docs, and what every page is written from: the CLI's3- * commands and the two hosts' URLs. A page is a title, a one-line summary4- * and its body; its Markdown opens with the title and the summary.5- */1 import { Brand } from "@repo/brand";2 3 import type { CommandDoc } from "../command-doc.ts";4 import { code, page } from "../text.ts";5 import type { DocEntry, DocSlug } from "./entries.ts";6 12-/** What every page is written from. */7 export interface DocInput {8 readonly commands: readonly CommandDoc[];9 readonly platformUrl: string;10 readonly webUrl: string;11 }12 19-/** One page as the web serves it. */13 export interface DocPage extends DocEntry {14 readonly markdown: string;15 }16 24-/** One page before it is written: its slug, and its body's lines from the input. */17 export interface DocSource {18 readonly slug: DocSlug;19 readonly body: (input: DocInput) => readonly string[];20 }21 30-/** `source` written for `input`, under what names it. */22 export const written = (23 entry: DocEntry,24 source: DocSource,25 input: DocInput7 unmodified lines33 ...source.body(input),34 ]),35 });36 46-/** A command as typed, in a code span: `<cli> claim <ask> --project <owner>/<name>`. */37 export const cli = (words: string) => code(`${Brand.cli} ${words}`);38 49-/** A block of shell commands. */39 export const shell = (...lines: readonly string[]) => [40 "```sh",41 ...lines,42 "```",43 ];44 56-/** A section's lines without its own `## ` heading, for a page that is that section. */45 export const withoutHeading = (lines: readonly string[]) => {46 const [first, blank, ...rest] = lines;47 48 return first?.startsWith("## ") === true && blank === "" ? rest : lines;1 unmodified linemodified:packages/agent-kit/src/docs/reference.ts-9 removed
1-/**2- * The reference: each page read from what defines it, never copied. The3- * commands from the CLI's one list, the refusals from the closed union,4- * git, landings and events from the text `/llms-full.txt` serves, the MCP5- * tools from the contracts served over MCP, and the imported projects from6- * the copy of the import plan.7- */1 import { Brand } from "@repo/brand";2 import {3 Contracts,4 Description,10 unmodified lines15 import { importedProjects } from "./imported.ts";16 import type { DocSource } from "./page.ts";17 import { withoutHeading } from "./page.ts";18 26-/** A command as typed: its words, then its positionals in angle brackets. */19 const usage = ({ path, positional }: CommandDoc) =>20 code(21 [Brand.cli, ...path, ...positional.map((name) => `<${name}>`)].join(" ")22 );35 unmodified lines58 body: () => withoutHeading(events()),59 slug: "events",60 };61 70-/** Each contract served over MCP: its tool name, what it does, and whether it only reads. */62 const mcpTools = () =>63 [...Contracts.requests.values()].flatMap(({ _tag, annotations }) =>64 Context.get(annotations, Surfaces).includes("mcp")65 ? [36 unmodified linesmodified:packages/agent-kit/src/docs/run-a-project.ts-5 removed
1-/**2- * The maintainer's guide: make a project, write how it takes changes in3- * its config folder, open asks, take proposals and drafts, spend Today's4- * decisions, finish an answer, land your own change and vouch.5- */1 import { Brand } from "@repo/brand";2 import { sourceHosts } from "@repo/protocol/ids";3 4 import { code } from "../text.ts";87 unmodified linesmodified:packages/agent-kit/src/docs/start-here.ts-4 removed
1-/**2- * The first guide: what the platform is, the four words a contributor3- * meets, the loop a change takes to `main`, and what a refusal looks like.4- */1 import { Brand } from "@repo/brand";2 3 import type { DocSource } from "./page.ts";4 import { cli } from "./page.ts";45 unmodified linesmodified:packages/agent-kit/src/agent-setup.ts-51 removed
1-/**2- * How an agent reaches the platform, set as a reference: a synopsis of the3- * CLI's commands; the channels it connects through (remote MCP for a client4- * that signs in over OAuth, MCP over stdio through the CLI, the CLI itself,5- * a sentence any agent can be handed, and the skills), each saying when to6- * use it and giving the snippets to copy; the endpoints an agent reads; the7- * limits a project's policy sets by default; and the refusals. The web draws8- * it as `/agents` and serves `agentSetupMarkdown` as `/agents.md`.9- *10- * Pure: the hosts hand in the CLI's commands as this package's one list11- * holds them and the two hosts' URLs. Each client's MCP JSON comes from12- * `mcpServersFor`, the builder the plugin bundles use, and every name from13- * `Brand`, the MCP server's name being `Brand.slug`.14- *15- * Client facts, as each client's docs give them: Claude Code adds a remote16- * server with `claude mcp add --transport http <name> <url>` and signs in17- * from `/mcp`; Cursor reads `.cursor/mcp.json`'s `mcpServers`, a remote18- * entry being its `url`; VS Code reads `.vscode/mcp.json`'s `servers`, a19- * remote entry being `{type: "http", url}`.20- */1 import { Brand } from "@repo/brand";2 import { PolicyInput } from "@repo/protocol/domain/policy";3 import { groups } from "@repo/protocol/refusal";4 import { Array as Arr, Schema } from "effect";4 unmodified lines9 import { span } from "./sections.ts";10 import { code, listed, page, printJson, table } from "./text.ts";11 12 export interface SetupSnippet {33- /** What the snippet is, or where it goes: a client, a file. */13 readonly label: string;14 readonly language: "sh" | "json" | "text";36- /** The text to copy, whole, with no trailing newline. */15 readonly text: string;16 }17 18 export interface SetupChannel {19 readonly title: string;42- /** One plain sentence, no Markdown: the agent this channel is for. */20 readonly useWhen: string;21 readonly snippets: readonly SetupSnippet[];22 }23 24 export interface SetupInput {48- /** Every CLI command, as `commandDocs` lists them. */25 readonly commands: readonly CommandDoc[];50- /** The platform's origin: its MCP endpoint and the CLI's sign-in. */26 readonly platformUrl: string;52- /** The web's origin: its Markdown, the CLI's downloads and the skills. */27 readonly webUrl: string;28 }29 56-/** Whether the CLI has the command whose words are `words`. */30 const has = (commands: readonly CommandDoc[], words: string) =>31 Arr.some(commands, ({ path }) => path.join(" ") === words);32 60-/** JSON as a snippet holds it: the generators' printing, without its final newline. */33 const json = (value: Parameters<typeof printJson>[0]) =>34 printJson(value).trimEnd();35 36 const remoteMcp = ({ platformUrl }: SetupInput): SetupChannel => ({79 unmodified lines116 title: "Skills",117 useWhen: `Your agent loads skills: each project's contribute skill is listed, with its digest, at ${webUrl}/.well-known/agent-skills/index.json.`,118 });119 148-/** Every channel, in the order the page shows them; stdio only when the CLI has `mcp`. */120 export const agentSetup = (input: SetupInput): readonly SetupChannel[] => [121 remoteMcp(input),122 ...(has(input.commands, "mcp") ? [stdioMcp()] : []),123 theCli(input),124 anyAgent(input),125 skills(input),126 ];127 157-// --- Synopsis -------------------------------------------------------------------158-159-/** One command as a synopsis gives it: how it is typed, and what it does. */128 export interface SynopsisLine {161- /** The CLI's name, its words, its arguments, then each flag it takes in brackets. */129 readonly usage: string;130 readonly summary: string;131 }132 166-/** Every command, one line each, in the catalog's order. */133 export const synopsis = (134 commands: readonly CommandDoc[]135 ): readonly SynopsisLine[] =>136 commands.map(({ flags, path, positional, summary }) => ({7 unmodified lines144 .map((flag) => `[${flag}]`),145 ].join(" "),146 }));147 182-// --- Endpoints ------------------------------------------------------------------183-184-/** One address an agent reads or calls. */148 export interface Endpoint {186- /** The address whole; `<…>` marks a part the reader fills in. */149 readonly url: string;150 readonly what: string;189- /** A plain GET in a browser shows it. */151 readonly readable: boolean;152 }153 193-/** Every address an agent reads, the web's first, then the platform's. */154 export const agentEndpoints = ({155 platformUrl,156 webUrl,157 }: Pick<SetupInput, "platformUrl" | "webUrl">): readonly Endpoint[] => [43 unmodified lines201 what: "Git over smart HTTP: clone a project, push an answer to your fork.",202 },203 ];204 245-// --- Limits ---------------------------------------------------------------------246-247-/** One limit and its value, as a person says them. */205 export interface Limit {206 readonly limit: string;207 readonly value: string;208 }209 253-/** What a policy that sets nothing takes: the defaults its schema fills in. */210 const policyDefaults = () =>211 Schema.decodeSync(212 Schema.Struct({213 budget: PolicyInput.fields.budget,1 unmodified line215 claims: PolicyInput.fields.claims,216 })217 )({});218 263-/**264- * The limits an agent meets: each project's policy may set its own, so the265- * values are the defaults; the platform's own rate limits stand in front.266- */219 export const agentLimits = (): readonly Limit[] => {220 const { budget, caps, claims } = policyDefaults();221 222 return [24 unmodified lines247 },248 ];249 };250 299-// --- Markdown -------------------------------------------------------------------300-251 const snippetLines = ({ label, language, text }: SetupSnippet) => [252 `${label}:`,253 "",254 `\`\`\`${language}`,50 unmodified lines305 ),306 "",307 ];308 359-/** The whole reference as one Markdown document: `/agents.md`. */309 export const agentSetupMarkdown = (input: SetupInput) =>310 page([311 "# For agents",312 "",10 unmodified linesmodified:packages/agent-kit/src/agents-block.ts-20 removed
1-/**2- * The AGENTS.md block: the brief every harness reads without installing3- * anything, between markers the platform owns. The first marker carries the4- * body's hash, so a hand-edited block is detectable; everything outside the5- * markers belongs to the project and is never touched.6- */1 import { Brand } from "@repo/brand";2 import type { Policy } from "@repo/protocol/domain/policy";3 import type { LandedSha, ProjectName } from "@repo/protocol/ids";4 import { Effect, Option } from "effect";2 unmodified lines7 import { contributeSkillName, contributeSkillPaths } from "./project-skill.ts";8 import { lanesOf, loopSteps, unfencedNorms } from "./sections.ts";9 import { code, listed, page } from "./text.ts";10 17-/** The block: its two marker lines and the text between them. */11 export interface AgentsBlock {12 readonly begin: string;13 readonly end: string;14 readonly body: string;41 unmodified lines56 ...unfencedNorms(policy.agents),57 ]);58 };59 67-/**68- * The block for a project's AGENTS.md, from its policy alone: the landing69- * changes nothing in it, so a landing that leaves the policy's text alone70- * leaves the block, and its hash, as they were.71- */60 export const agentsBlock = (input: {61 readonly project: ProjectName;62 readonly policy: Policy;63 readonly landed: LandedSha;8 unmodified lines72 }))73 );74 };75 88-/** The block as a file holds it: the markers on lines of their own. */76 const written = (block: AgentsBlock) =>77 `${block.begin}\n${block.body}${block.body.endsWith("\n") ? "" : "\n"}${block.end}`;78 92-/** Where an existing block starts and ends, whatever hash its first marker carries. */79 const locate = (80 existing: string,81 end: string82 ): Option.Option<{ readonly from: number; readonly to: number }> => {12 unmodified lines95 96 return marker ? Option.some({ from, to: to + end.length }) : Option.none();97 };98 113-/** What goes between a file's last text and an appended block: one blank line. */99 const separator = (existing: string) => {100 if (existing === "" || existing.endsWith("\n\n")) {101 return "";102 }103 104 return existing.endsWith("\n") ? "\n" : "\n\n";105 };106 122-/**123- * `existing` with the block in it: replacing the text from the first marker124- * to the last where a block is, appending it after a blank line where none125- * is. Every other byte stays as it was, and a second call changes nothing.126- */107 export const upsertAgentsBlock = (existing: string, block: AgentsBlock) =>108 Option.match(locate(existing, block.end), {109 onNone: () => `${existing}${separator(existing)}${written(block)}\n`,110 onSome: ({ from, to }) =>2 unmodified linesmodified:packages/agent-kit/src/command-doc.ts-37 removed
1-/**2- * One row per CLI command, the list the platform's skill, the CLI's MCP3- * prompt and the web's `llms.txt` all render from. Contract rows4- * come from each contract's annotations; the hand-written commands are5- * listed here, and `apps/cli/test/commands-doc.test.ts` holds the list to6- * the CLI.7- */1 import {2 Cli,3 Description,4 NeedsApproval,3 unmodified lines8 import type { Contracts } from "@repo/protocol/contracts";9 import { Array as Arr, Context, Order, Schema, SchemaAST } from "effect";10 11 export const CommandDoc = Schema.Struct({19- /** The contract it calls: always for a contract's row, sometimes for a local one. */12 contract: Schema.optionalKey(Schema.NonEmptyString),21- /** Every flag it takes, as typed: `--project`. */13 flags: Schema.Array(Schema.NonEmptyString),23- /** It runs only with `--yes`; `--dry-run` prints what it would send. */14 needsApproval: Schema.Boolean,25- /** The words after the CLI's name: `["env", "set"]`. */15 path: Schema.NonEmptyArray(Schema.NonEmptyString),27- /** The arguments it takes in order, by name. */16 positional: Schema.Array(Schema.NonEmptyString),17 readOnly: Schema.Boolean,18 source: Schema.Literals(["contract", "local"]),19 summary: Schema.NonEmptyString,20 });21 22 export type CommandDoc = typeof CommandDoc.Type;23 36-/**37- * The CLI's hand-written commands. `init` and `env set` stand in for the38- * contracts they call (`initProject`, `setEnv`), so those contracts get no39- * row of their own.40- */24 export const localCommandDocs: readonly CommandDoc[] = [25 {26 flags: [27 "--url",129 unmodified lines157 "Show your Today: the decisions to take, each with its evidence and a safe default; --tui opens it full-screen at a terminal.",158 },159 ];160 178-/**179- * The names of the local commands that call a contract: a contract whose180- * CLI name is one of them is that command, so it gets no row of its own.181- */161 const standIns = new Set(162 localCommandDocs.flatMap(({ contract, path }) =>163 contract === undefined ? [] : [path.join(" ")]164 )165 );166 188-/** A payload's field names, in the schema's order; none for a payload of no fields. */167 const fieldsOf = (ast: SchemaAST.AST) =>168 SchemaAST.isObjects(ast)169 ? ast.propertySignatures.map(({ name }) => String(name))170 : [];171 194-/**195- * One row per contract the CLI serves (its `Surfaces` include `cli`), in the196- * group's order, from its annotations: the `Cli` name split into words, its197- * positional fields, then every other payload field as a flag, `--json`,198- * `--yes` when it needs approval, and `--dry-run` unless it only reads. A199- * contract a local command calls under the same name is left to that200- * command's row.201- */172 export const contractCommandDocs = (173 group: typeof Contracts174 ): readonly CommandDoc[] =>175 [...group.requests.values()].flatMap((rpc) => {40 unmodified lines216 const byWords = Order.mapInput(Order.String, (doc: CommandDoc) =>217 doc.path.join(" ")218 );219 250-/**251- * Every command the CLI has, one row each, sorted by its words (so `ask`252- * and its subcommands come before `asks`): the contracts it projects and the253- * commands written by hand in it. The platform's skill, the CLI's MCP254- * prompt and the web's `llms.txt` all read this list;255- * `apps/cli/test/commands-doc.test.ts` holds it to the CLI's real tree.256- */220 export const commandDocs = (group: typeof Contracts): readonly CommandDoc[] =>221 Arr.sort([...contractCommandDocs(group), ...localCommandDocs], byWords);modified:packages/agent-kit/src/full-llms.ts-17 removed
1-/**2- * `/llms-full.txt`: what an agent needs beyond the index, in one file.3- * `frontLlms`' text, then every refusal of the closed union (every group,4- * from `refusalCatalog`), the CLI's exit codes, how git meets the platform, how a landing5- * happens (ADR 0014), one line per event a watcher hears (those four from6- * `llms-sections.ts`, which the docs show too), and the guides for the7- * moments an answer goes sideways.8- *9- * Pure, and every name comes from `Brand`; a guide names a command only10- * when the catalog has it.11- */1 import type { ProjectListing } from "@repo/protocol/domain/front-page";2 import { Option } from "effect";3 4 import type { CommandDoc } from "./command-doc.ts";9 unmodified lines14 import { code, page } from "./text.ts";15 16 type Commands = readonly CommandDoc[];17 29-// --- Guides ---------------------------------------------------------------------30-18 const guides = (commands: Commands, platformUrl: string) => [19 "## Guides",20 "",21 "### Recover from `StaleBase`",36 unmodified lines58 ` Claiming the ask again (${each}) returns the claim you hold, with its remote.`59 ).join("")}`,60 ];61 75-/**76- * `/llms-full.txt`: the index, then the refusals, exit codes, git,77- * landings, events and guides. The web serves it; the platform's `/` stays the index alone.78- */62 export const fullLlms = (input: {63 readonly commands: Commands;64 readonly projects: readonly ProjectListing[];65 readonly platformUrl: string;10 unmodified linesmodified:packages/agent-kit/src/generated-file.ts+2 added-48 removed
1-/**2- * A generated file, and how it says it was generated. A Markdown file opens3- * with Agent Skills frontmatter whose `metadata` names who manages it, the4- * landing it came from and the SHA-256 of its body, so a stale copy (its5- * body differs from the one the current policy gives) and a hand-edited copy6- * (its body no longer hashes to what it records) are both detectable.7- */1 import { Brand } from "@repo/brand";2 import { LandedSha } from "@repo/protocol/ids";3 import { Array as Arr, Effect, Option, Schema } from "effect";4 12-/** One file a generator makes: where it goes, and every byte of it. */5 export interface GeneratedFile {6 readonly path: string;7 readonly content: string;8 }9 18-/** What a managed file says about itself, and the body it says it of. */10 export interface Managed {20- /** The landing it was generated from; none for the platform's own files. */11 readonly landed: Option.Option<LandedSha>;22- /** `sha256:<64 hex>`, as its frontmatter records it. */12 readonly hash: string;13 readonly body: string;14 }15 1 unmodified line17 [...new Uint8Array(bytes)]18 .map((byte) => byte.toString(16).padStart(2, "0"))19 .join("");20 32-/**33- * `sha256:<64 hex>` of the text's UTF-8 bytes, through WebCrypto, which the34- * platform Worker and Node both have. SHA-256 of bytes in memory cannot fail35- * for a reason a caller could handle, so a failure is a defect.36- */21 export const contentHash = (text: string): Effect.Effect<string> =>22 Effect.tryPromise(() =>23 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))24 ).pipe(25 Effect.orDie,26 Effect.map((digest) => `sha256:${hex(digest)}`)27 );28 45-// Every value but the name is a YAML double-quoted string, written as JSON46-// writes one: a description has colons, and YAML would read a SHA made only47-// of digits as a number.29+// Values are JSON-quoted: a description has colons, and YAML would read a30+// SHA made only of digits as a number.31 const quoted = (value: string) => JSON.stringify(value);32 50-/**51- * A Markdown file with Agent Skills frontmatter: only the spec's `name`,52- * `description` and `metadata`, with `managed-by`, `landed` (when it came53- * from one) and `content-hash` (of `body`) under `metadata`.54- */33 export const frontmatter = (input: {34 readonly name: string;35 readonly description: string;36 readonly landed: Option.Option<LandedSha>;24 unmodified lines61 const decodeQuoted = Schema.decodeUnknownOption(62 Schema.fromJsonString(Schema.String)63 );64 87-/** A frontmatter value: a quoted one decoded, a plain one as it stands. */65 const valueOf = (raw: string) =>66 raw.startsWith('"') ? decodeQuoted(raw) : Option.some(raw);67 91-/** The `key: value` lines indented under `metadata:`, by key. */68 const metadataOf = (head: string) => {69 const lines = head.split("\n");70 const start = lines.indexOf("metadata:");71 15 unmodified lines87 };88 89 const decodeLanded = Schema.decodeUnknownOption(LandedSha);90 115-/** A Markdown file's frontmatter and the body after it; none without one. */91 const sections = (file: string) => {92 if (!file.startsWith(OPEN)) {93 return Option.none();94 }9 unmodified lines104 };105 106 const DESCRIPTION = "description: ";107 133-/**134- * The `description` a skill's frontmatter gives, quoted as `frontmatter`135- * writes it or plain as a hand-written skill may: none without the136- * frontmatter, or without a description in it. The skills index lists a137- * landed skill by it.138- */108 export const describedIn = (file: string): Option.Option<string> =>109 Option.flatMap(sections(file), ({ head }) =>110 Arr.findFirst(head.split("\n"), (line) =>111 line.startsWith(DESCRIPTION)3 unmodified lines115 Option.flatMap(valueOf)116 )117 );118 150-/**151- * What a file this platform manages says about itself: none for a file152- * without the frontmatter, or one someone else manages.153- */119 export const readManaged = (file: string): Option.Option<Managed> => {120 const split = sections(file);121 122 if (Option.isNone(split)) {16 unmodified lines139 ),140 });141 };142 178-/**179- * Whether the copy on disk differs from the file the current policy gives:180- * its body hashes to something other than what it records (edited by hand),181- * or what it records is not the current body's hash (generated from other182- * text). The landing alone never makes a copy stale: a landing that left183- * the text alone leaves the copy current. Some names the copy's own landing184- * and recorded hash. A copy without the frontmatter has no landing, and its185- * hash is the whole file's: it is current only when the current file has no186- * frontmatter either and the two are the same text, so a copy whose187- * frontmatter was taken off is stale.188- */143 export const isStale = (144 onDisk: string,145 current: GeneratedFile146 ): Effect.Effect<29 unmodified linesmodified:packages/agent-kit/src/hook-events.ts-12 removed
1-/**2- * The hook events the CLI answers: `<cli> hook <event> --json`. The hook3- * configs agent-kit generates call it with these names, and the4- * CLI's `hook` command parses the same ones.5- */1 import { Schema } from "effect";2 8-/** When a harness asks the gate's policy: at the session's start, before a tool runs, at Stop. */3 export const HookEvent = Schema.Literals([4 "session-start",5 "pre-tool-use",6 "stop",7 ]);8 9 export type HookEvent = typeof HookEvent.Type;10 17-/** The Claude Code hook event each one answers. */11 export const claudeEventOf = {12 "pre-tool-use": "PreToolUse",13 "session-start": "SessionStart",14 stop: "Stop",15 } as const satisfies Record<HookEvent, "SessionStart" | "PreToolUse" | "Stop">;16 24-/**25- * The tools whose use the `pre-tool-use` hook guards: every Claude Code tool26- * that writes a file. The generated hook config matches them, and the CLI's27- * hook decides on the same names.28- */17 export const guardedTools = [18 "Edit",19 "Write",20 "MultiEdit",2 unmodified linesmodified:packages/agent-kit/src/host-doc.ts+2 added-72 removed
1-/**2- * What an agent, or a person, reads first about a host, as plain Markdown3- * in the `llms.txt` shape (a title, a one-line summary, then sections of4- * links). `frontLlms` says what the platform is, how to install the CLI,5- * how to connect over MCP, how to find and take an ask, every command, and6- * which projects exist: the web serves it at `/llms.txt`, and the platform7- * at `/` for an agent, with no web app's pages named when it knows of none.8- * `projectLlms` is the web's `/<owner>/<name>/llms.txt`, with the project's open9- * asks, and `mcpCard` its `/.well-known/mcp.json`. With a web app,10- * `frontLlms` names `/llms-full.txt` (`full-llms.ts`), and `indexBanner`11- * sits under the title of every other Markdown answer the web serves, so a reader that lands12- * on one finds the rest.13- *14- * Pure: the hosts hand in what the platform lists and the CLI's commands15- * as this package's one list holds them, so no command is written here16- * by hand. A step names a command only when the catalog has it. Every17- * name comes from `Brand`.18- */1 import { Brand } from "@repo/brand";2 import type { AskListing } from "@repo/protocol/domain/ask";3 import type { ProjectListing } from "@repo/protocol/domain/front-page";4 import type { ProjectName } from "@repo/protocol/ids";6 unmodified lines11 type Command = CommandDoc;12 13 type Commands = readonly CommandDoc[];14 33-/** The MCP protocol the platform serves over HTTP. */15 export const MCP_PROTOCOL = "2026-07-28";16 36-/** Each posture as GLOSSARY.md names it. */17 const postureWords = {18 open: "Open",19 openCore: "Open core",20 openOnSchedule: "Open on schedule",5 unmodified lines26 27 const counted = (count: number, one: string) =>28 `${count} ${one}${count === 1 ? "" : "s"}`;29 50-/** The lines as one document, ending in a newline. */30 const page = (lines: readonly string[]) => `${lines.join("\n")}\n`;31 53-/** What a placeholder stands for in a command line, if the page knows it. */32 interface Known {33 readonly project?: string;34 }35 58-/** The command whose words are `words`, if the catalog has it. */36 const commandOf = (commands: Commands, words: string) =>37 Arr.findFirst(commands, ({ path }) => path.join(" ") === words);38 62-/**63- * A command as typed: the CLI's name, its words, its arguments, then64- * `flags` it takes, each with a value the page knows or a placeholder.65- */39 const usage = (40 command: Command,41 known: Known = {},42 flags: readonly ("ask" | "project")[] = []12 unmodified lines55 ),56 ].join(" ");57 };58 86-/** `words` as typed, with `flags`, when the catalog has the command. */59 export const typed = (60 commands: Commands,61 words: string,62 known: Known,2 unmodified lines65 Option.map(commandOf(commands, words), (command) =>66 code(usage(command, known, flags))67 );68 97-/** The sentence `make` writes around a typed command, or nothing without it. */69 export const withCommand = (70 command: Option.Option<string>,71 make: (typedCommand: string) => string72 ) => Option.toArray(Option.map(command, make));73 103-/**104- * How to take an ask, each step with the commands the catalog has: find,105- * read, claim, change and check, push and read the verdict. Numbered in106- * order, whatever steps the catalog leaves out.107- */74 const takeAnAsk = (commands: Commands, known: Known) => {75 const front = typed(commands, "front", known);76 const asks = typed(commands, "asks", known, ["project"]);77 35 unmodified lines113 "",114 ];115 };116 151-/** What a command row adds to its description. */117 const notes = ({ needsApproval, readOnly }: Command) => [118 ...(readOnly ? ["Only reads."] : []),119 ...(needsApproval ? [`Runs only with ${code("--yes")}.`] : []),120 ];121 157-/** Every command, one line each, in the catalog's order. */122 const commandList = (commands: Commands) => [123 "## Commands",124 "",125 ...commands.map(2 unmodified lines128 ),129 "",130 ];131 168-/** Where a project's page is on the web host. */132 const projectPage = (webUrl: string, project: string) => `${webUrl}/${project}`;133 171-/** What a project's line says of it: its posture and its open asks. */134 const projectFacts = (listing: ProjectListing) =>135 `${postureWords[listing.posture]}, ${counted(listing.openAsks, "open ask")}.`;136 175-/**176- * A project's line: a link to its Markdown on the web host, or, with no177- * web app, its clone URL on the platform.178- */137 const projectLine = (138 platformUrl: string,139 webUrl: Option.Option<string>,140 listing: ProjectListing4 unmodified lines145 onSome: (web) =>146 `- [${listing.project}](${projectPage(web, listing.project)}/llms.txt): ${projectFacts(listing)}`,147 });148 191-/**192- * The platform, the CLI, MCP, taking an ask, the commands and the193- * projects: the web's `/llms.txt`, and the platform's `/` for an agent.194- * Without `webUrl` it names only what the platform serves itself: the CLI195- * and the skills from the platform, each project by its clone URL, and no196- * page that only a web app serves.197- */149 export const frontLlms = (input: {150 readonly commands: Commands;151 readonly projects: readonly ProjectListing[];152 readonly platformUrl: string;153 readonly webUrl?: string;154 }) => {155 const { commands, platformUrl, projects } = input;156 const webUrl = Option.fromUndefinedOr(input.webUrl);206- // The CLI's downloads and the skills: the web forwards both to the platform.157 const served = Option.getOrElse(webUrl, () => platformUrl);158 159 return page([160 `# ${Brand.name}`,52 unmodified lines213 : projects.map((listing) => projectLine(platformUrl, webUrl, listing))),214 ]);215 };216 267-/** What an ask's line adds after its want: its kind and territory, then whether it can be taken. */217 const askNotes = (listing: AskListing) => [218 `Kind ${code(listing.kind)}, territory ${code(listing.territory)}.`,219 ...(listing.claimed ? ["Claimed."] : []),220 ...(listing.reserve === undefined ? [] : [`Held for ${listing.reserve}.`]),1 unmodified line222 ? []223 : [`Waits for ${listing.blockedBy.map(code).join(", ")}.`]),224 ];225 277-/** An ask's want as a sentence of its own, however it was punctuated. */226 const sentence = (text: string) => `${text.replace(/[.\s]+$/u, "")}.`;227 228 const askLine = (webUrl: string, project: string, listing: AskListing) =>229 `- [${listing.ask}](${projectPage(webUrl, project)}/asks/${listing.ask}.md): ${[sentence(listing.want), ...askNotes(listing)].join(" ")}`;230 283-/**284- * The line under the title of a Markdown answer the web serves: where the285- * index is, where the full text is, and, for a project's answer, the286- * project's own index. One blockquote, so a reader that lands on any page287- * finds the rest. It never comes first: an `llms.txt` opens with its `#`288- * heading.289- */231 export const indexBanner = (input: {232 readonly webUrl: string;233 readonly project?: ProjectName;234 }) => {1 unmodified line236 237 return `> For agents: the index is ${webUrl}/llms.txt, and everything beyond it (refusals, git, landings, events, guides) is ${webUrl}/llms-full.txt${project === undefined ? "" : `; this project's index is ${projectPage(webUrl, project)}/llms.txt`}.`;238 };239 299-/** `banner` under `text`'s `#` title, or on top of a text that has none. */240 export const underTitle = (text: string, banner: string) => {241 const end = text.indexOf("\n");242 243 return text.startsWith("# ") && end !== -1244 ? `${text.slice(0, end)}\n\n${banner}\n\n${text.slice(end).replace(/^\n+/u, "")}`245 : `${banner}\n\n${text}`;246 };247 308-/** `/<owner>/<name>/llms.txt`: the project, its posture, how to clone it, its open asks and how to take one. */248 export const projectLlms = (input: {249 readonly listing: ProjectListing;250 readonly asks: readonly AskListing[];251 readonly commands: Commands;23 unmodified lines275 ...takeAnAsk(commands, { project }).slice(0, -1),276 ]);277 };278 340-/**341- * `/<owner>/<name>/llms.txt` for a project the platform does not list. A name342- * that could not be a project's is not repeated back.343- */279 export const missingProjectLlms = (input: {280 readonly project: Option.Option<ProjectName>;281 readonly webUrl: string;282 }) =>5 unmodified lines288 onSome: (project) => `No project named ${code(project)}`,289 })} is on ${Brand.name}. Every project is listed at ${input.webUrl}/llms.txt.`,290 ]);291 357-/**358- * `/.well-known/mcp.json`: the platform's MCP endpoint, its transport and359- * protocol, and where a client learns to sign in. No settled standard says360- * this card's shape; it follows the MCP server card draft, and names its361- * authorization the way the platform's 401 does (RFC 9728's362- * `resource_metadata`).363- */292+// No settled standard gives this card's shape: it follows the MCP server card293+// draft, naming its authorization as RFC 9728's `resource_metadata`.294 export const mcpCard = (input: { readonly platformUrl: string }) => ({295 authentication: {296 required: true,297 resource_metadata: `${input.platformUrl}/.well-known/oauth-protected-resource`,10 unmodified linesmodified:packages/agent-kit/src/index.ts-6 removed
1-/**2- * Generated agent files from a project's policy: the contribute skill, the3- * AGENTS.md block, the harness plugins and their hooks, and the well-known4- * skills index. Each module is its own subpath too5- * (`@repo/agent-kit/hook-events`).6- */1 export { agentsBlock, upsertAgentsBlock } from "./agents-block.ts";2 3 export type { AgentsBlock } from "./agents-block.ts";4 30 unmodified linesmodified:packages/agent-kit/src/install.ts-5 removed
1-/**2- * The line that installs the CLI, from a web's origin (the web forwards the3- * CLI's downloads to the platform, as `llms.txt` says). One string, so every4- * page and document that gives it gives the same one.5- */1 export const installCommand = (webUrl: string) =>2 `curl -fsSL ${webUrl}/install.sh | sh`;modified:packages/agent-kit/src/llms-sections.ts-25 removed
1-/**2- * The sections of `/llms-full.txt` that the docs' reference shows too:3- * every refusal of the closed union, how git meets the platform, how a4- * landing happens (ADR 0014), and one line per event a watcher hears. Pure,5- * and every name comes from `Brand`. The refusals come from the union and6- * the events from a table the type holds to `ProjectEvent`, so a new tag7- * cannot be missing. Nothing here names a private repo, its files or its8- * readers (AGENTS.md principle 7): the gateway lines below are the ones9- * anyone outside one can meet.10- */1 import { Brand } from "@repo/brand";2 import type { ProjectEvent } from "@repo/protocol/domain/event";3 4 import { refusalCatalog } from "./refusals.ts";2 unmodified lines7 const cli = (...words: readonly string[]) => [Brand.cli, ...words].join(" ");8 9 const notesRef = `refs/notes/${Brand.slug}`;10 21-/** How an answer is pushed to a claim's fork: a function, so loading this module runs nothing. */11 export const pushAnswer = () => code(`git push ${Brand.slug} HEAD:main`);12 24-/** What the gateway says when git is not let in: `<reason>; sign in with <cli> login`. */13 const signIn = (reason: string) => `${reason}; sign in with ${cli("login")}`;14 27-// --- Refusals -----------------------------------------------------------------28-29-/** Every refusal of the closed union, with its group, retry, exit code, `next` and repair. */15 export const refusals = () => [16 "## Refusals",17 "",18 `Every refusal the platform gives, in every group of its closed union. Each has a \`_tag\`, \`retryable\` (whether trying the same thing again can help) and \`next\` (the command to run next), and no message: match on the tag. Git prints them on its \`remote:\` lines, ${code(cli("check"))} and ${code(cli("status"))} print them, an MCP tool returns them as JSON, and the verdict note holds them. The refusals about an answer's files arrive together, so one push hears about all of them.`,11 unmodified lines30 ),31 "",32 ];33 49-// --- Git here -------------------------------------------------------------------50-51-/** How git reaches the platform's repos, who reads and pushes each, and what it says when it refuses. */34 export const gitHere = (platformUrl: string) => [35 "## Git here",36 "",37 `Git reaches each repo at ${code(`${platformUrl}/<repo>.git`)} over smart HTTP and signs in with Basic auth. The password is your platform token, which ${code(cli("login"))} stores and hands to git through its credential helper. The username is an audit tag, ${code("audit;harness=<harness>")} (with ${code("&model=…")} and ${code("&session=…")} when the harness names them): it records which harness pushed and is never identity. The token alone says who you are.`,40 unmodified lines78 `- 404 ${code("not a git endpoint")}: the path is not one git asks for.`,79 "",80 ];81 100-// --- How a landing happens ----------------------------------------------------101-102-/** How a checked answer becomes a commit on `main`. */82 export const landing = () => [83 "## How a landing happens",84 "",85 "1. The platform checks the answer's merged tree: the ask's check and the project's lanes.",3 unmodified lines89 "5. A landing tried again finds its own commit on `main` by its `Request-Id` trailer and writes only what is missing, so it never makes a second commit.",90 "",91 ];92 114-// --- Events ---------------------------------------------------------------------115-116-/** What each event says happened, one line per tag of `ProjectEvent`. */93 const eventLines = {94 AskClosed: "An ask closed, with the landing that answered it.",95 AskOpened: "A new ask opened.",96 Claimed: "Someone claimed an ask.",10 unmodified lines107 Released: "A claim was released.",108 Warned: "A claim was warned that it lapses without a push.",109 } as const satisfies Record<ProjectEvent["_tag"], string>;110 135-/** One line per event a watcher of a project hears. */111 export const events = () => [112 "## Events",113 "",114 "A project's page follows its events as they happen (the `watch` contract). Each event carries `seq`, its place in the project's sequence, and `at`, its time; a watcher resumes after the last `seq` it saw.",4 unmodified linesmodified:packages/agent-kit/src/platform.ts+7 added-59 removed
1-/**2- * The platform's own skill and plugin: the platform's skill,3- * which the platform and the CLI serve as the MCP prompt `contribute`, the4- * Claude Code plugin with its three hooks, and the Agent Plugins bundle,5- * each as files at `skills/<slug>/` and `plugins/<slug>/`. The plugin is what6- * a person installs, so it is the only place executable hooks ship; a7- * project's own generated files are data.8- *9- * Both plugin manifests share one directory: Claude Code reads10- * `.claude-plugin/plugin.json`, `.mcp.json` and `hooks/hooks.json`, Agent11- * Plugins 1.0 reads `plugin.json` and `mcp.json`, and both read `skills/`.12- * No path is read by both, so neither manifest overrides the other.13- */1+// Claude Code reads `.claude-plugin/plugin.json`, `.mcp.json` and2+// `hooks/hooks.json`; Agent Plugins 1.0 reads `plugin.json` and `mcp.json`.3+// No path is read by both, so the two manifests share one directory.4 import { Brand } from "@repo/brand";5 import { Array as Arr, Effect, Option, Order } from "effect";6 7 import type { CommandDoc } from "./command-doc.ts";4 unmodified lines12 import { loopSteps, unfencedSection } from "./sections.ts";13 import { code, page, printJson, table } from "./text.ts";14 15 export interface PlatformInput {26- /** Every CLI command, as `commandDocs` lists them. */16 readonly commands: readonly CommandDoc[];28- /** The platform's origin, for its MCP endpoint; without it, MCP runs through the CLI. */17 readonly platformUrl?: string;18 }19 20 const SKILL = `skills/${Brand.slug}/SKILL.md`;21 22 const PLUGIN = `plugins/${Brand.slug}`;23 36-// --- The platform's skill ------------------------------------------------------37-24 const description = `Contribute to projects on ${Brand.name} with the \`${Brand.cli}\` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on ${Brand.name}, or when a push was refused with a refusal such as OutOfScope or StaleBase.`;25 26 const usage = ({ path, positional }: CommandDoc) =>27 code(56 unmodified lines84 ...refusalSection(),85 ...unfencedSection(),86 ]);87 102-/**103- * The platform's skill as the prompt `contribute` serves it: its name, its104- * description and its Markdown, made at once. The platform builds the105- * prompt where nothing may be awaited (its router, at module load), and106- * `SKILL.md`'s frontmatter hashes the body through WebCrypto, a promise.107- */88+// Synchronous: the platform builds the prompt at module load, where nothing89+// may be awaited, and `SKILL.md`'s hash is a WebCrypto promise.90 export const platformSkillParts = (input: PlatformInput) => ({91 body: platformBody(input),92 description,93 name: Brand.slug,1 unmodified line95 96 const skillFile = (input: PlatformInput) =>97 frontmatter({ ...platformSkillParts(input), landed: Option.none() });98 117-/** `skills/<slug>/SKILL.md`: the platform's skill, which comes from no landing. */99 export const platformSkill = (100 input: PlatformInput101 ): Effect.Effect<readonly GeneratedFile[]> =>102 skillFile(input).pipe(Effect.map((content) => [{ content, path: SKILL }]));103 123-// --- The MCP server, as each client's config names it ----------------------------124-125-/**126- * How each config spells the platform's MCP server: Claude Code's `.mcp.json`127- * (and VS Code's `servers`, the same entry), Agent Plugins 1.0's `mcp.json`,128- * and Cursor's `mcp.json`, whose remote entry is a bare `url` (its docs give129- * a `type` only for stdio).130- */104+// Cursor's remote entry is a bare `url`: its docs give a `type` only for stdio.105 const servers = {106 "agent-plugins": {107 remote: (url: string) => ({ type: "streamable-http", url }),108 stdio: { args: ["mcp"], command: Brand.cli, type: "stdio" },9 unmodified lines118 } as const;119 120 export type McpFlavour = keyof typeof servers;121 148-/**149- * The `mcpServers` object a client's config holds: the platform's `/mcp`150- * over HTTP, or `<cli> mcp` over stdio without a URL, under the brand's151- * slug. The plugin bundles and the Agents page (`agent-setup.ts`) both152- * build theirs here, so no client's snippet can drift from a bundle's.153- */122 export const mcpServersFor = (123 platformUrl: string | undefined,124 flavour: McpFlavour125 ) => ({2 unmodified lines128 ? servers[flavour].stdio129 : servers[flavour].remote(`${platformUrl}/mcp`),130 });131 164-// --- The Claude Code plugin ------------------------------------------------------165-132 const hookCommand = (event: HookEvent) => ({133 hooks: [{ command: `${Brand.cli} hook ${event} --json`, type: "command" }],134 });135 170-/**171- * `hooks/hooks.json`: before an edit, the scope guard; at the session's172- * start, the claimed ask's brief; at Stop, the verdict gate. Each runs173- * `<cli> hook <event> --json`, which fails open: hooks are early feedback,174- * and the gateway decides.175- */136+// Each hook fails open: hooks are early feedback, and the gateway decides.137 const hooksJson = () =>138 printJson({139 hooks: Object.fromEntries(140 HookEvent.literals.map((event) => [11 unmodified lines152 153 const homepage = (platformUrl: string | undefined) =>154 platformUrl === undefined ? {} : { homepage: platformUrl };155 195-/**196- * `plugins/<slug>/`: `.claude-plugin/plugin.json`, the platform's skill,197- * `.mcp.json` (the platform's `/mcp` over HTTP, or `<cli> mcp` without a198- * URL) and `hooks/hooks.json`.199- */156 export const claudePlugin = (157 input: PlatformInput158 ): Effect.Effect<readonly GeneratedFile[]> =>159 skillFile(input).pipe(16 unmodified lines176 { content: hooksJson(), path: `${PLUGIN}/hooks/hooks.json` },177 ])178 );179 224-// --- The Agent Plugins bundle ----------------------------------------------------225-180 const SCHEMAS = "https://agent-plugins.org/schemas/1.0.0";181 228-/**229- * `plugins/<slug>/plugin.json`, the same skill and `mcp.json`: the Agent230- * Plugins 1.0 package, whose manifests are closed (only `$schema` and the231- * listed fields) and carry no hooks, which that standard leaves to each232- * client.233- */182 export const agentPluginsBundle = (183 input: PlatformInput184 ): Effect.Effect<readonly GeneratedFile[]> =>185 skillFile(input).pipe(20 unmodified linesmodified:packages/agent-kit/src/project-skill.ts-19 removed
1-/**2- * A project's contribute skill: what a stranger's agent reads to answer one3- * of its asks, generated from the policy at a landing and nothing else. One4- * file, written to `.agents/skills/` and `.claude/skills/`, which between5- * them reach every harness that reads skills.6- */1 import { Brand } from "@repo/brand";2 import type { Policy } from "@repo/protocol/domain/policy";3 import { keyOf } from "@repo/protocol/ids";4 import type { LandedSha, ProjectName } from "@repo/protocol/ids";11 unmodified lines16 unfencedSection,17 } from "./sections.ts";18 import { code, page } from "./text.ts";19 26-/**27- * The skill's name: `<key>-contribute`, by the project's key28- * (`datekit-contribute`, `oscabriel__foo-contribute`), its folder's name too,29- * so the forty's skills keep their names and a name reads back to its30- * project (ADR 0032).31- */20 export const contributeSkillName = (project: ProjectName) =>21 `${keyOf(project)}-contribute`;22 35-/** Where the skill goes: the folders harnesses read project skills from, `.agents` first. */23 export const contributeSkillPaths = (project: ProjectName) => {24 const skill = `skills/${contributeSkillName(project)}/SKILL.md`;25 26 return [`.agents/${skill}`, `.claude/${skill}`] as const;27 };28 42-/** What the skill's frontmatter says it is for. */29 export const contributeDescription = (project: ProjectName) =>30 `Answer one of ${project}'s asks on ${Brand.name}: claim it, change only its territory, run \`${Brand.cli} check\`, push it to your fork, and read the verdict. Use when working on ${project}, or when a push to it was refused.`;31 46-/** The skill's body: the loop, then the rules from the policy, then what nothing checks yet. */32 export const contributeBody = (project: ProjectName, policy: Policy) =>33 page([34 `# Contribute to ${project}`,35 "",13 unmodified lines49 ...refusalSection(),50 ...unfencedSection(policy.agents),51 ]);52 68-/**69- * `.agents/skills/<key>-contribute/SKILL.md` and its `.claude/skills/`70- * copy, the same bytes, with frontmatter naming the landing it came from.71- */53 export const projectSkill = (input: {54 readonly project: ProjectName;55 readonly policy: Policy;56 readonly landed: LandedSha;11 unmodified linesmodified:packages/agent-kit/src/refusals.ts-29 removed
1-/**2- * The refusals an answer can meet, read from the closed union: each one's3- * tag, whether retrying can help and its `next` come from its schema, its4- * exit code from the CLI's (`exitCodeOfTag`), and what to do about it from5- * the table below, which the type holds to the union's groups (a refusal6- * added to one fails the typecheck until it has a line here).7- * `refusalCatalog` walks every group the same way, for `/llms-full.txt`,8- * with a second table for the refusals no answer meets.9- */1 import { Brand } from "@repo/brand";2 import { ExitCode, exitCodeOfTag, precedence } from "@repo/protocol/exit-code";3 import { groups } from "@repo/protocol/refusal";4 import { Exit, Predicate, SchemaAST } from "effect";5 6 import { code, table } from "./text.ts";7 17-/** The groups whose refusals an answer can meet, from claim to verdict. */8 const answerGroups = [9 "Push and claim",10 "Shape",11 "Merge",13 unmodified lines25 type AnswerTag = InstanceType<AnswerMember>["_tag"];26 27 type Tag = InstanceType<Member>["_tag"];28 39-/**40- * What to do on meeting it. A refusal whose `next` is set when it is raised41- * gives the command's form here, or what it names when no form fits.42- */29 interface Repair {30 readonly todo: string;31 readonly next?: string;32 readonly nextNames?: string;64 unmodified lines97 todo: "Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet.",98 },99 } as const satisfies Record<AnswerTag, Repair>;100 115-/**116- * What to do on meeting a refusal no answer meets: at an ask's opening, a117- * maintainer's own push, a decision, a lookup, setup or the env.118- */101 const elsewhere = {102 DecisionClosed: {103 todo: "Nothing to decide: it was taken already, or expired to its default.",104 },72 unmodified lines177 ...repairOf,178 ...Object.entries(elsewhere),179 ]);180 199-/** A field's value when the constructor fills it in, as it does a fixed `next`. */181 const constructorDefault = (ast: SchemaAST.AST) => {182 const fill = ast.context?.constructorDefault;183 184 return fill !== undefined &&3 unmodified lines188 ? fill.value189 : undefined;190 };191 211-/** One refusal an answer can meet, as the skills list it. */192 export interface AnswerRefusal {193 readonly tag: string;194 readonly retryable: boolean;215- /** The code the CLI exits with when it meets this refusal. */195 readonly exitCode: ExitCode;217- /** Its `next`, in Markdown: the command as a code span, or what it names. */196 readonly next: string;197 readonly todo: string;198 }199 6 unmodified lines206 ? (repair?.nextNames ?? "")207 : code(repair.next);208 };209 232-/** One member's row, from its schema and the repair `repairTable` gives it. */210 const rowOf = (211 member: Member,212 repairTable: ReadonlyMap<string, Repair>213 ): AnswerRefusal => {9 unmodified lines223 todo: repair?.todo ?? "",224 };225 };226 250-/** Every refusal an answer can meet, in the union's order. */227 export const answerRefusals: readonly AnswerRefusal[] = groups228 .flatMap((group): readonly Member[] =>229 answerGroups.some((answer) => answer === group.name) ? group.members : []230 )231 .map((member) => rowOf(member, repairOf));232 257-/** One refusal of the closed union, with the group the union files it under. */233 export interface CatalogRow extends AnswerRefusal {234 readonly group: string;235 }236 262-/** Every refusal of the closed union, every group, in the union's order. */237 export const refusalCatalog = (): readonly CatalogRow[] =>238 groups.flatMap((group) =>239 group.members.map((member: Member) => ({240 ...rowOf(member, everyRepairOf),241 group: group.name,242 }))243 );244 271-/** What each code the CLI exits with tells its caller, in the order a caller reads them. */245 const exitMeanings = {246 [ExitCode.ok]: "It did what it was asked.",247 [ExitCode.failed]: "Something else went wrong; stderr says what.",248 [ExitCode.usage]:9 unmodified lines258 [ExitCode.noPerm]:259 "Refused: you may not do this until you sign in, or someone lets you in.",260 } as const satisfies Record<ExitCode, string>;261 289-/** The CLI's exit codes, as `/llms-full.txt` lists them. */262 export const exitCodeSection = () => [263 "## Exit codes",264 "",265 `${code(Brand.cli)} exits with a code from sysexits(3), so a script or an agent can tell what to do next without reading stderr. A refusal's code follows from its \`retryable\`: 75 when trying again can help, else the code for what has to change, as the Refusals table lists it. A command that meets several refusals at once exits with the first of ${precedence.map(String).join(", ")} among them.`,4 unmodified lines270 ),271 "",272 ];273 302-/** The refusals section every skill carries. */274 export const refusalSection = () => [275 "## Refusals",276 "",277 `Instead of landing an answer, the platform answers with refusals. Git prints them on its \`remote:\` lines, \`${cli("check")}\` and \`${cli("status")}\` print them, and the verdict note holds them as JSON. Each one has a \`_tag\`, \`retryable\` (whether trying the same thing again can help) and \`next\` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them. The CLI exits with a refusal's code: 75 when trying again can help, and 65, 66 or 77 when something has to change first.`,13 unmodified linesmodified:packages/agent-kit/src/sections.ts-33 removed
1-/**2- * The sections the contribute skill, the AGENTS.md block and the platform's3- * own skill are made of, each from the policy or the brand alone. None4- * names the landing, so a landing that leaves the policy's text alone5- * leaves every generated body, and its hash, as it was.6- */1 import { Brand } from "@repo/brand";2 import { RatchetMeasure } from "@repo/protocol/domain/check";3 import type { AskKind, CheckKind, ClaimRule } from "@repo/protocol/domain/kind";4 import type { Policy } from "@repo/protocol/domain/policy";8 unmodified lines13 const remote = Brand.slug;14 15 const notesRef = `refs/notes/${Brand.slug}`;16 23-// --- The loop ----------------------------------------------------------------24-25-/**26- * The five steps every answer takes: read and claim, work, check, push,27- * read the verdict. The same in every generated file, so an agent that read28- * one knows them all.29- */17 export const loopSteps = () => [18 `1. Read the ask, then claim it: ${cli("ask", "<ask>")}, then ${cli("claim", "<ask>")}. The claim prints your fork's remote; add it with ${code(`git remote add ${remote} <remote>`)}.`,19 "2. Work inside the ask's territory until its check passes.",20 `3. Run ${cli("check")}. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.`,8 unmodified lines29 { ms: 60_000, one: "minute" },30 { ms: 1000, one: "second" },31 ] as const;32 46-/** A span as a person says it: `2 hours`, `1 day`, `90 minutes`. */33 export const span = (ms: number) => {34 const unit = unitsOfTime.find((each) => ms % each.ms === 0) ?? unitsOfTime[4];35 36 const count = Math.round(ms / unit.ms);37 38 return `${count} ${unit.one}${count === 1 ? "" : "s"}`;39 };40 55-/** What the project's policy says about holding a claim. */41 export const claimTerms = (policy: Policy) =>42 `A claim stays alive only while you push to it: after ${span(policy.claims.warnAfterMs)} without a push it is warned, and after ${span(policy.claims.lapseAfterMs)} it lapses. You may hold ${policy.caps.claimsPerPerson} ${policy.caps.claimsPerPerson === 1 ? "claim" : "claims"} at once in this project.`;43 59-// --- What an answer may change -------------------------------------------------60-44 const byName = <A>(name: (item: A) => string) =>45 Order.mapInput(Order.String, name);46 47 const judgeLines = (judge: Policy["judge"]) => [20 unmodified lines68 (ratchet) =>69 `- ${code(ratchet.name)}${ratchet.territory === undefined ? "" : ` in ${code(ratchet.territory)}`}: ${measureOf(ratchet.measure)}`70 );71 89-/**90- * The territory rule, the public files rule, the judge closure, the91- * weakening markers and the ratchets: each held by a refusal the gate92- * gives, which the section names.93- */72 export const changeSection = (policy: Policy) => {73 const { judge, modules, ratchets, weakening } = policy;74 75 const publicFiles = modules.some(55 unmodified lines131 "",132 ];133 };134 157-// --- The run block -------------------------------------------------------------158-159-/** The run block's lanes, by name. */135 export const lanesOf = (run: RunBlock) =>136 Arr.sort(137 Object.entries(run.checks),138 byName(([lane]: readonly [string, string]) => lane)18 unmodified lines157 ),158 "",159 ];160 186-// --- Ask kinds -----------------------------------------------------------------187-161 const checkKindText = (kind: CheckKind, run: RunBlock) =>162 ({163 lintToZero:164 "a lint rule's findings in the territory go to zero; the ask names the rule and the command that counts them.",54 unmodified lines219 byName((kind: AskKind) => kind.name)220 ).flatMap((kind) => kindLines(kind, policy)),221 ];222 250-// --- No fence yet ----------------------------------------------------------------251-252-/**253- * Norms the generated files state that nothing checks yet, listed as such254- * rather than as rules. Without a project, the default `agents` policy.255- */223 export const unfencedNorms = (agents: Policy["agents"] = "trailer") => [224 "- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.",225 ...(agents === "none"226 ? []13 unmodified linesmodified:packages/agent-kit/src/text.ts-14 removed
1-/**2- * The few ways generated text is written: Markdown pages, code spans and3- * table cells that survive any command a project writes, and JSON with4- * sorted keys, so no byte depends on the order a value was built in.5- */1 import { Array as Arr, Order, Predicate } from "effect";2 import type { Schema } from "effect";3 9-/** A Markdown page: its lines joined, ending in exactly one newline. */4 export const page = (lines: readonly string[]) =>5 `${lines.join("\n").replace(/\n+$/u, "")}\n`;6 13-/**14- * A code span around any text: a command with a backtick in it gets a15- * longer fence, padded with spaces as Markdown asks.16- */7 export const code = (text: string) => {8 const runs = text.match(/`+/gu) ?? [];9 const longest = Math.max(0, ...runs.map((run) => run.length));10 const fence = "`".repeat(longest + 1);2 unmodified lines13 ? `${fence}${text}${fence}`14 : `${fence} ${text} ${fence}`;15 };16 27-/** A table cell: a pipe in it would end the cell. */17 export const cell = (text: string) => text.replaceAll("|", String.raw`\|`);18 30-/** A Markdown table: a header row, its rule, then one row per entry. */19 export const table = (20 header: readonly string[],21 rows: readonly (readonly string[])[]22 ) => [1 unmodified line24 `| ${header.map(() => "---").join(" | ")} |`,25 ...rows.map((row) => `| ${row.map(cell).join(" | ")} |`),26 ];27 40-/** Words joined as a sentence lists them: `a`, `a and b`, `a, b and c`. */28 export const listed = (words: readonly string[]) =>29 words.length < 230 ? words.join("")31 : `${words.slice(0, -1).join(", ")} and ${words.at(-1) ?? ""}`;25 unmodified lines57 58 return value;59 };60 74-/** JSON as the generators write it: sorted keys, two-space indents, a final newline. */61 export const printJson = (value: Schema.Json) =>62 `${JSON.stringify(sortKeys(value), null, 2)}\n`;modified:packages/agent-kit/src/well-known.ts-14 removed
1-/**2- * `/.well-known/agent-skills/index.json`: the skills index the `skills` CLI3- * reads (discovery schema 0.2.0), so `npx skills add <platform>` finds every4- * project's contribute skill. Each entry names a skill, says what it is for,5- * where its `SKILL.md` is served and the SHA-256 of that file's bytes.6- */1 import { Array as Arr, Effect, Order } from "effect";2 3 import { contentHash } from "./generated-file.ts";4 import type { GeneratedFile } from "./generated-file.ts";5 import { printJson } from "./text.ts";6 13-/** One skill the index lists: its file's text, to digest, and where it is served. */7 export interface SkillEntry {8 readonly name: string;9 readonly description: string;10 readonly url: string;1 unmodified line12 }13 14 const DISCOVERY = "https://schemas.agentskills.io/discovery/0.2.0/schema.json";15 23-/** The most characters an entry's description may have. */16 const DESCRIBED = 1024;17 18 const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });19 28-/**29- * A description cut to the limit with an ellipsis, whole characters only:30- * at most 1024 UTF-16 units, so at most 1024 characters however a reader31- * counts them.32- */20 const cut = (description: string) => {21 if (description.length <= DESCRIBED) {22 return description;23 }12 unmodified lines36 };37 38 const byName = Order.mapInput(Order.String, (entry: SkillEntry) => entry.name);39 53-/** The index, its entries sorted by name. Its path is served from the platform's root. */40 export const wellKnownSkills = (41 entries: readonly SkillEntry[]42 ): Effect.Effect<GeneratedFile> =>43 Effect.forEach(Arr.sort(entries, byName), (entry) =>15 unmodified linesmodified:packages/agent-kit/test/agent-setup.test.ts-11 removed
1-/**2- * The Agents page's one source: how each agent connects (remote MCP, MCP3- * over stdio, the CLI, text to paste, skills), each channel with when to4- * use it and the snippets to copy. A pure function of the CLI's commands5- * and the two hosts' URLs; the web draws it as `/agents` and serves it as6- * `/agents.md`, and its MCP JSON is the object the plugin bundles carry.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import { groups } from "@repo/protocol/refusal";39 unmodified lines44 const commands: readonly CommandDoc[] = [...someCommands, login, mcp];45 46 const channels = agentSetup({ commands, platformUrl, webUrl });47 55-/** The channel titled `title`; fails the test without one. */48 const channel = (from: readonly SetupChannel[], title: string) =>49 Option.getOrThrow(Arr.findFirst(from, (each) => each.title === title));50 59-/** The snippet labelled `label` in the channel titled `title`. */51 const snippet = (title: string, label: string) =>52 Option.getOrThrow(53 Arr.findFirst(channel(channels, title).snippets, (each) =>54 each.label.startsWith(label)55 )56 );57 67-/** A JSON object's text, decoded. */58 const parsed = Schema.decodeUnknownSync(59 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))60 );61 72-/** The `.mcp.json` the Claude Code plugin carries for the same platform. */62 const pluginMcpJson = claudePlugin({ commands, platformUrl }).pipe(63 Effect.map((files) =>64 Option.getOrThrow(65 Arr.findFirst(files, ({ path }) => path.endsWith("/.mcp.json"))207 unmodified linesmodified:packages/agent-kit/test/agents-block.test.ts-1 removed
27 unmodified lines28 body: "## Contributing\n\nOld text,\nover two lines.\n",29 end,30 };31 32-/** The block as it sits in a file. */32 const written = ({ begin, body }: typeof block) => `${begin}\n${body}${end}`;33 34 describe(upsertAgentsBlock, () => {35 it("inserts the block at the end of an AGENTS.md without one", () => {84 unmodified linesmodified:packages/agent-kit/test/command-doc.test.ts-5 removed
103 unmodified lines104 ]);105 });106 });107 108-/** Each row that calls `tag`, by its words and where it comes from. */108 const calling = (docs: readonly CommandDoc[], tag: string) =>109 docs.flatMap((doc) =>110 doc.contract === tag ? [`${doc.path.join(" ")} (${doc.source})`] : []111 );112 114-// The one list the platform's skill, the CLI's MCP prompt and the web's115-// `llms.txt` read: every command once, in the order a person scans for one.113 describe(commandDocs, () => {114 const docs = commandDocs(Contracts);115 const words = docs.map(({ path }) => path.join(" "));116 54 unmodified lines171 "ask open",172 ]);173 });174 178- // `init` and `env set` do local work around the contract they call, so179- // their hand-written rows stand for those contracts.175 it("gives a contract a hand-written command calls no row of its own", () => {176 expect(calling(docs, "initProject")).toStrictEqual(["init (local)"]);177 expect(calling(docs, "setEnv")).toStrictEqual(["env set (local)"]);178 });1 unmodified linemodified:packages/agent-kit/test/docs.test.ts-9 removed
1-/**2- * The docs: guides written for people, then a reference read from the3- * sources that define it (the CLI's commands, the refusal union, the4- * events, the MCP tools and the import plan's copy). Every command a page5- * names is one the CLI has, with flags it takes, and every link between6- * pages names a page that exists.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Contracts, Surfaces } from "@repo/protocol/contracts";4 import type { ProjectEvent } from "@repo/protocol/domain/event";19 unmodified lines24 onNone: () => "",25 onSome: ({ markdown }) => markdown,26 });27 35-/** Every code span and shell line in `markdown` that runs the CLI, as its words. */28 const cliSpans = (markdown: string) =>29 [30 ...[...markdown.matchAll(/`(?<span>[^`\n]+)`/gu)].map(31 (found) => found.groups?.span ?? ""4 unmodified lines36 ? [span.slice(Brand.cli.length + 1).split(/\s+/u)]37 : []38 );39 48-/** The catalog's command these words run: the longest path they start with. */40 const commandOf = (words: readonly string[]) =>41 commands42 .filter(({ path }) => path.every((word, at) => words[at] === word))43 .toSorted((a, b) => b.path.length - a.path.length)[0];182 unmodified linesmodified:packages/agent-kit/test/fixtures.ts+1 added-13 removed
1-/**2- * A datekit-shaped project at one landed commit: two ask kinds, three asks,3- * two modules and the run block `{test: "bun test {path}", checks: {lint,4- * types, unit}}`. Decoded with the domain's own schema, so a fixture the5- * domain would refuse throws here.6- */1 import { Brand } from "@repo/brand";2 import { CheckSpec } from "@repo/protocol/domain/check";3 import { Command } from "@repo/protocol/domain/common";4 import type { AskKind } from "@repo/protocol/domain/kind";6 unmodified lines11 export const project = ProjectName.make("oscabriel/datekit");12 13 export const landed = LandedSha.make("a".repeat(40));14 21-/** A later landing, for a copy generated before it. */15 export const later = LandedSha.make("b".repeat(40));16 17 const encodeCheck = Schema.encodeSync(CheckSpec);18 121 unmodified lines140 };141 142 export const policy = Schema.decodeSync(Policy)(encoded);143 151-/** The same project after a landing that changed one lane of its run block. */144 export const policyWithNewLint = Schema.decodeSync(Policy)({145 ...encoded,146 run: {147 ...encoded.run,148 checks: { ...encoded.run.checks, lint: "bunx oxlint --deny-warnings" },149 },150 });151 160-/**161- * A few CLI commands as the generators take them: hand-written here, so a162- * contract's wording changing elsewhere leaves these golden files alone.163- */152+// Hand-written, so a contract's wording changing elsewhere leaves the golden files alone.153 export const commands: readonly CommandDoc[] = [154 {155 contract: "listAsks",156 flags: ["--project", "--json"],44 unmodified lines201 summary: "Run the gate's checks on your answer locally, before you push.",202 },203 ];204 216-/** Where the platform serves its routes in these tests. */205 export const platformUrl = `https://${Brand.domain}`;modified:packages/agent-kit/test/full-llms.test.ts-9 removed
1-/**2- * `/llms-full.txt`: what an agent needs beyond the index. `frontLlms`'3- * text, then every refusal of the closed union, how git meets the4- * platform, how a landing happens, every event a watcher hears, and the5- * guides for the moments an answer goes sideways. A pure function of the6- * CLI's commands, the listed projects and the two hosts' URLs.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import type { ProjectEvent } from "@repo/protocol/domain/event";11 unmodified lines16 const platformUrl = "https://platform-test.example.workers.dev";17 18 const webUrl = "https://web-test.example.workers.dev";19 27-/** A command row as the command list holds it. */20 const row = (21 path: readonly [string, ...string[]],22 summary: string,23 more: Partial<CommandDoc> = {}69 unmodified lines93 const text = fullLlms(input);94 95 const lines = text.split("\n");96 105-/** The lines of the section headed `## <title>`, up to the next `## `. */97 const section = (title: string) => {98 const start = lines.indexOf(`## ${title}`);99 const rest = lines.slice(start + 1);100 const end = rest.findIndex((line) => line.startsWith("## "));145 unmodified linesmodified:packages/agent-kit/test/generate.test.ts-7 removed
24 unmodified lines25 import { expectGolden, transcript } from "./golden.ts";26 27 const plugin = `plugins/${Brand.slug}`;28 29-/** The `name:` line of a file's frontmatter; none without one. */29 const frontmatterName = (content: string) =>30 Option.fromNullishOr(/^name: (?<name>.+)$/mu.exec(content)?.groups?.name);31 32 const skill = `${keyOf(project)}-contribute`;33 35-/** `sha256("hello\n")`, as every tool that hashes prints it. */34 const helloDigest =35 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";36 37 interface Case {40- /** Its golden file: `test/golden/<golden>.txt`. */38 readonly golden: string;39 readonly what: string;40 readonly paths: readonly string[];41 readonly run: Effect.Effect<readonly GeneratedFile[]>;100 unmodified lines142 const eventsOf = Schema.decodeUnknownSync(143 Schema.Struct({ hooks: Schema.Record(Schema.String, Schema.Unknown) })144 );145 149-/** A SKILL.md's frontmatter keys: top level, and under `metadata`. */146 const frontmatterKeys = (content: string) => {147 const [, head = ""] = content.split("---\n");148 const lines = head.split("\n");149 6 unmodified lines156 ),157 };158 };159 164-/** A Markdown file's body: everything after its frontmatter's closing line. */160 const bodyOf = (content: string) => {161 const close = content.indexOf("\n---\n", 3);162 163 return close === -1 ? content : content.slice(close + "\n---\n".length);164 };165 171-/** The hash a file's frontmatter records, read with a pattern of its own. */166 const recordedHash = (content: string) =>167 /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(content)?.groups168 ?.hash ?? "";169 176-/** The hook entry that runs `<cli> hook <event> --json`. */170 const hookCommand = (event: HookEvent) => [171 { command: `${Brand.cli} hook ${event} --json`, type: "command" },172 ];173 276 unmodified linesmodified:packages/agent-kit/test/golden.ts+2 added-18 removed
1-/**2- * Golden files for the generators: each generator's files in one3- * `test/golden/<name>.txt`, with the product's name as placeholders so no4- * golden file spells it (`brand:check`) and a renamed brand still matches.5- * A `content-hash` covers text that spells the name, so it changes with the6- * brand: the golden file holds `__HASH__` there, and the generator tests7- * hold each recorded hash to its body instead. `UPDATE_GOLDEN=1` rewrites8- * them; read the diff before committing it.9- */1+// Golden files hold the brand as placeholders (so `brand:check` passes) and2+// each content hash as `__HASH__`. `UPDATE_GOLDEN=1` rewrites them.3 import { expect } from "@effect/vitest";4 import { Brand } from "@repo/brand";5 import { Config, Effect, FileSystem } from "effect";6 12 unmodified lines19 const CLI = new RegExp(`(?<=^|[\`"])${escaped(Brand.cli)}(?= [a-z])`, "gmu");20 21 const SLUG = new RegExp(`(?<![A-Za-z])${escaped(Brand.slug)}(?![a-z])`, "gu");22 30-/** A golden file's text with its placeholders filled in from `Brand`. */23 export const branded = (golden: string) =>24 golden25 .replaceAll("__NAME__", Brand.name)26 .replaceAll("__CLI__", Brand.cli)2 unmodified lines29 // The hex of a frontmatter's `content-hash: "sha256:…"` or an AGENTS.md30 // marker's `content-hash: sha256:…`.31 const HASH = /(?<=content-hash: "?sha256:)[0-9a-f]{64}/gu;32 41-/** Generated text with each content hash as `__HASH__`. */33 const unhashed = (text: string) => text.replaceAll(HASH, "__HASH__");34 44-/** Generated text as a golden file holds it: the brand and hashes as placeholders. */35 const unbranded = (text: string) =>36 unhashed(text)37 .replaceAll(NAME, "__NAME__")38 .replaceAll(CLI, "__CLI__")39 .replaceAll(SLUG, "__SLUG__");40 51-/** Several files as one text: each under a `==> <path> <==` line. */41 export const transcript = (files: readonly GeneratedFile[]) =>42 files.map(({ content, path }) => `==> ${path} <==\n${content}`).join("\n");43 55-/**56- * Asserts that `actual`, with its content hashes as `__HASH__`, is57- * `test/golden/<name>.txt` with its brand placeholders filled in, byte for58- * byte. Under `UPDATE_GOLDEN=1` it writes the file.59- */44 export const expectGolden = (name: string, actual: string) =>45 Effect.gen(function* () {46 const fs = yield* FileSystem.FileSystem;47 const file = `${DIR}/${name}.txt`;23 unmodified linesmodified:packages/agent-kit/test/host-doc.test.ts-8 removed
1-/**2- * The host's own Markdown, `frontLlms`: what the web serves at `/llms.txt`3- * and the platform at `/` for an agent. A pure function of the CLI's4- * commands, the listed projects and the two hosts' URLs; with no web app5- * it points only at what the platform serves itself.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import type { ProjectListing } from "@repo/protocol/domain/front-page";12 unmodified lines17 const platformUrl = "https://platform-test.example.workers.dev";18 19 const webUrl = "https://web-test.example.workers.dev";20 27-/** A command row as the command list holds it. */21 const row = (22 path: readonly [string, ...string[]],23 summary: string,24 more: Partial<CommandDoc> = {}7 unmodified lines32 summary,33 ...more,34 });35 43-/** The web's own `llms.test.ts` catalog, so the golden file is its former output. */36 const commands: readonly CommandDoc[] = [37 row(38 ["ask"],39 "Show one ask in full, with its brief in Markdown for an answerer to read first.",180 unmodified linesmodified:packages/agent-kit/test/stale.test.ts-2 removed
15 unmodified lines16 policyWithNewLint,17 project,18 } from "./fixtures.ts";19 20-/** `sha256("hello\n")`, as every tool that hashes prints it. */20 const helloDigest =21 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";22 24-/** The hash a file's frontmatter records, read with a pattern of its own. */23 const recordedHash = (file: string) =>24 /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(file)?.groups25 ?.hash ?? "";26 244 unmodified linesmodified:packages/artifacts/src/repo-host/artifacts-api.ts+1 added-21 removed
1-/**2- * What the two adapters over Artifacts share, the Workers binding's3- * (`binding.ts`) and the REST API's (`rest.ts`): Artifacts' error codes and4- * their numbers, the codes an import refuses a source with, how a revision5- * is named, and the limits on a token's ttl and a log page. One table each,6- * so the two adapters can't drift apart.7- */1 import { Duration, Schema } from "effect";2 3 import { Revision } from "../repo-host.ts";4 12-/** Artifacts' names for its errors: `ArtifactsError.code` on the binding. */5 export const Code = Schema.Literals([6 "ALREADY_EXISTS",7 "NOT_FOUND",8 "CREATE_IN_PROGRESS",12 unmodified lines21 export type Code = typeof Code.Type;22 23 export const isCode = Schema.is(Code);24 33-/**34- * Each code by its number, from Artifacts' errors page: the REST API's35- * `errors[].code`, and the binding's `numericCode`. The page gives36- * `CREATE_IN_PROGRESS` no number.37- */25+/** Artifacts' errors page gives `CREATE_IN_PROGRESS` no number. */26 export const NUMBERED: ReadonlyMap<number, Code> = new Map<number, Code>([27 [10_100, "INVALID_INPUT"],28 [10_101, "INVALID_REPO_NAME"],29 [10_103, "INVALID_TTL"],7 unmodified lines37 [10_401, "UPSTREAM_UNAVAILABLE"],38 [10_402, "MEMORY_LIMIT"],39 ]);40 53-/**54- * The codes an import refuses its source with, as no repo to take: not git,55- * not public, not reachable, or too big.56- */41 export const NO_SOURCE = [42 "INVALID_INPUT",43 "INVALID_URL",44 "MEMORY_LIMIT",1 unmodified line46 "REMOTE_AUTH_REQUIRED",47 "UPSTREAM_UNAVAILABLE",48 ] as const satisfies readonly Code[];49 66-/** Artifacts' name for a revision: a short branch name or a commit id, never `refs/…`. */50 export const refOf = (at: Revision) =>51 Revision.$match(at, {52 Branch: ({ name }) => name,53 Commit: ({ sha }) => sha,54 });55 73-// Artifacts takes a token's ttl in whole seconds, from a minute to a year.56 const MIN_TTL_SECONDS = 60;57 58 const MAX_TTL_SECONDS = 31_536_000;59 78-/** A token's ttl as Artifacts takes it: whole seconds, clamped to a minute and a year. */60 export const secondsOf = (ttl: Duration.Duration) =>61 Math.min(62 Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),63 MAX_TTL_SECONDS64 );65 85-/** `log` reads at most this many commits per call. */66 export const LOG_PAGE = 1000;modified:packages/artifacts/src/repo-host/binding.ts+13 added-86 removed
1 /**2- * `RepoHost` over the Workers `Artifacts` binding: how the deployed platform3- * keeps its repos. The binding's surprises, found by probing it live, come back4- * typed:2+ * The binding's surprises, found by probing it live:3 *4 * - errors are read by `code`, and by message when there is none, as under5 * `wrangler dev` remote bindings;6 * - a fork that answers 500 is tried once more, and an already-exists or a7 * second 500 after that may be the fork the first made: it is, if it lists8 * `main`;9 * - reads name a branch by its short name and a commit by its id, never10 * `refs/…`, so `refs` and `push` go over git smart HTTP instead;13- * - a busy receive-pack is `HostBusy`;14- * - a call refused for Artifacts' rate limit (2,000 requests per 10 s per15- * repo) is asked again from 250 ms apart, doubling, at most four more16- * times; past that it fails as the call's own failure would.11+ * - a rate-limited call (2,000 requests per 10 s per repo) is retried.12 *18- * Refs and pushes use a token the adapter mints for the one call and revokes19- * after it; the token goes nowhere but the `Authorization` header of the20- * adapter's own requests. The day-long write token a create, a fork or an21- * import hands back is revoked at once: any write token can force-push22- * `main`, and no caller needs it. A repo still being23- * created is asked for again, from 250 ms apart, up to seven more times24- * (about 32 s); one still being imported up to sixteen (about 3 minutes),25- * each sleep at most 16 s. Every repo handle is disposed after use: after26- * each read, or, for reads in one `RepoSession`, once when the session27- * ends, so a view's many reads ask `get` for one handle.13+ * The write token a create, fork or import hands back is revoked at once:14+ * any write token can force-push `main`, and no caller needs it.15 */16 import {17 Data,18 DateTime,35 unmodified lines54 } from "./artifacts-api.ts";55 import type { Code } from "./artifacts-api.ts";56 import { listRefs, listTags, pushRefs } from "./smart-http.ts";57 71-/**72- * The codes a message names when the error carries none: Artifacts'73- * words, the fake's, and the code itself.74- */58 const MESSAGES = [59 [/not found/iu, "NOT_FOUND"],60 [/already exists/iu, "ALREADY_EXISTS"],61 [/fork[_ ]in[_ ]progress|still forking/iu, "FORK_IN_PROGRESS"],62 [/internal error/iu, "INTERNAL_ERROR"],63 ] as const satisfies readonly (readonly [RegExp, Code])[];64 82-/**83- * What a call to the binding threw, read once: its `code`, or the one its84- * message names when it has none, and the error itself as the cause.85- */65 class Thrown extends Data.TaggedError("Thrown")<{66 readonly code: Option.Option<Code>;67 readonly message: string;68 readonly error: unknown;69 }> {}70 92-/** A fork that answered `INTERNAL_ERROR`, which may still have made the repo. */71 class MaybeForked extends Data.TaggedError("MaybeForked")<{72 readonly thrown: Thrown;73 }> {}74 75 /**98- * How Artifacts words a refusal for its rate limit. ASSUMPTION: none has99- * been seen live and its error codes list none, so it is read from a code100- * or a message that names the limit, as an HTTP 429's "Too Many Requests"101- * does.76+ * ASSUMPTION: no rate-limit refusal has been seen live and its error codes77+ * list none, so it is read from a code or a message that names the limit.78 */79 const RATE_LIMITED = /rate[ _-]?limit|too[ _-]many[ _-]requests/iu;80 81 const isRateLimited = ({ error, message }: Thrown) =>1 unmodified line83 (Predicate.hasProperty(error, "code") &&84 Predicate.isString(error.code) &&85 RATE_LIMITED.test(error.code));86 111-/** From 250 ms apart, doubling, four more asks while the limit refuses. */87 const whileLimited = Schedule.exponential(Duration.millis(250)).pipe(88 Schedule.setInputType<Thrown>(),89 Schedule.while(90 ({ attempt: asked, input }) => asked <= 4 && isRateLimited(input)91 )92 );93 119-/**120- * A promise of the binding's, failing with what it threw, read; asked121- * again while Artifacts' rate limit refuses it.122- */94 const attempt = <A>(run: () => Promise<A>) =>95 Effect.tryPromise({96 catch: (error) => {97 const message = error instanceof Error ? error.message : String(error);14 unmodified lines112 (code: Code) =>113 (thrown: Thrown): boolean =>114 Option.contains(thrown.code, code);115 145-/**146- * An error the binding threw, as the port's: by `code` first, by message147- * when there is none. Anything else is a defect, with the error as its cause.148- */116 const fromArtifactsError = (117 name: RepoName,118 thrown: Thrown119 ): Effect.Effect<never, RepoNotFound | RepoExists | ForkInProgress> =>9 unmodified lines129 ),130 Match.orElse(({ error }) => Effect.die(error))131 );132 166-/** A call about the repo `name`, its errors read as the port's. */133 const call = <A>(name: RepoName, run: () => Promise<A>) =>134 attempt(run).pipe(135 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))136 );137 138 const asDefect = ({ error }: Thrown) => Effect.die(error);139 174-/** The port's reads and token calls fail only with `RepoNotFound`. */140 const onlyNotFound = <A, R>(141 effect: Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, R>142 ) =>143 effect.pipe(1 unmodified line145 );146 147 const main = RefName.make("refs/heads/main");148 184-/** How long a token minted for one call lives; it is revoked after the call. */149 const CALL_TOKEN_TTL = Duration.minutes(5);150 187-/** The codes `import` refuses a source with. */151 const IMPORT_REFUSALS: ReadonlySet<Code> = new Set(NO_SOURCE);152 153 const bytesOf = (blob: Blob) =>154 attempt(() => blob.arrayBuffer()).pipe(36 unmodified lines191 };192 })193 ).pipe(Effect.orDie);194 232-/**233- * How many times `get` is asked again while the repo is still being made:234- * a create about 32 s in all, and an import, which copies a whole history235- * and may outlast `import()` itself, about 3 minutes. Anything else is236- * never asked again.237- */195+/** An import copies a whole history and may outlast `import()` itself. */196 const asksWhileMaking = (thrown: Thrown) =>197 Match.value(thrown).pipe(198 Match.when(threw("CREATE_IN_PROGRESS"), () => 7),199 Match.when(threw("IMPORT_IN_PROGRESS"), () => 16),200 Match.orElse(() => 0)201 );202 245-/**246- * From 250 ms apart, doubling, each sleep at most 16 s: 250 ms … 16 s for a247- * create's seven asks (31.75 s), then 16 s apart for an import's nine more248- * (175.75 s in all).249- */203 const whileMaking = Schedule.min([204 Schedule.exponential(Duration.millis(250)),205 Schedule.spaced(Duration.seconds(16)),206 ]).pipe(207 Schedule.setInputType<Thrown>(),208 Schedule.while(({ attempt: asked, input }) => asked <= asksWhileMaking(input))209 );210 258-/** A handle to `name`, asked for again while the repo is still being made. */211 const handleOf = (binding: Artifacts, name: RepoName) =>212 attempt(() => binding.get(name)).pipe(213 Effect.retry(whileMaking),214 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))215 );216 265-/** Gives a handle back: the binding's handles are RPC stubs. */217+/** The binding's handles are RPC stubs, so each is disposed. */218 const disposeOf = (repo: ArtifactsRepo) =>219 Effect.sync(() => {220 repo[Symbol.dispose]();221 });222 271-/** `use` over a handle to `name`, disposed after, whatever `use` came to. */223 const withRepo = <A, E, R>(224 binding: Artifacts,225 name: RepoName,226 use: (repo: ArtifactsRepo) => Effect.Effect<A, E, R>4 unmodified lines231 )232 );233 234 /**284- * The repo `made` names, its initial write token revoked: nothing the285- * adapter's callers do needs it. A revoke that fails is logged, never the286- * call's failure: the repo was made, and the token went nowhere.235+ * The initial write token is revoked: no caller needs it. A failed revoke is236+ * logged, never the call's failure: the repo was made.237 */238 const withoutToken = (239 binding: Artifacts,240 made: { readonly remote: string; readonly token: string },10 unmodified lines251 ),252 Effect.as({ name, remote: made.remote })253 );254 305-/**306- * A token for one call, revoked when the scope closes, and the repo's307- * remote: what a smart-HTTP call to the repo needs.308- */255 const access = (name: RepoName, repo: ArtifactsRepo, scope: TokenScope) =>256 Effect.gen(function* () {257 const { remote } = yield* call(name, () => repo.info());258 13 unmodified lines272 return yield* listRefs(remote, token);273 })274 );275 330-/** The repo's tags over smart HTTP, peeled: the binding lists no refs. */276+/** Over smart HTTP: the binding lists no refs. */277 const tagsOf = (name: RepoName, repo: ArtifactsRepo) =>278 Effect.scoped(279 Effect.gen(function* () {280 const { remote, token } = yield* access(name, repo, "read");3 unmodified lines284 );285 286 /**287 * After a 500 and then an already-exists or a second 500, the fork may be342- * made: it is, if it lists `main`. Otherwise it is still being made, or343- * was undone; either way the caller tries again later.288+ * made: it is, if it lists `main`.289 */290 const confirmed = (binding: Artifacts, name: RepoName) =>291 withRepo(binding, name, (repo) =>292 Effect.gen(function* () {13 unmodified lines306 RepoNotFound: () => Effect.fail(new ForkInProgress({ name })),307 })308 );309 365-/**366- * One fork call. The base's absence names the base; any other refusal names367- * the target, and a 500 is `MaybeForked`, since it may have made the target.368- */310 const forkOnce = (binding: Artifacts, base: RepoName, name: RepoName) =>311 withRepo(binding, base, (repo) =>312 attempt(() => repo.fork(name)).pipe(313 Effect.catchTag("Thrown", (thrown) =>9 unmodified lines323 )324 )325 ).pipe(Effect.flatMap((made) => withoutToken(binding, made, name)));326 386-/**387- * Whether the repo holds `id` as a blob or a commit: `readBlob` answers388- * `null` for any other kind, and `readCommit` throws for a non-commit.389- */327+/** `readBlob` answers `null` for any other kind, and `readCommit` throws for a non-commit. */328 const blobOrCommit = (name: RepoName, repo: ArtifactsRepo, id: string) =>329 call(name, () => repo.readBlob(id)).pipe(330 Effect.flatMap((blob) =>331 blob === null15 unmodified lines347 attempt(() => repo.readTree(tree)).pipe(348 Effect.flatMap((found) =>349 found === null ? Effect.succeedNone : Effect.asSome(entriesOf(found))350 ),413- // A blob's or a commit's id names no tree, as on the other stores;414- // any other failure stays one.351 Effect.catchIf(threw("INTERNAL_ERROR"), ({ error }) =>352 blobOrCommit(name, repo, tree).pipe(353 Effect.flatMap((other) =>354 other ? Effect.succeedNone : Effect.die(error)96 unmodified lines451 // The service alone: the layer's whole context would carry its Scope, and452 // every call's finalizers would wait for the layer's end.453 const fetch = yield* Fetch;454 519- /**520- * A read of `name`'s, failing only with `RepoNotFound`: over the521- * session's handle to `name` when the read runs in a `RepoSession`,522- * else over a handle of its own.523- */455 const read = <A>(456 name: RepoName,457 use: (458 repo: ArtifactsRepo104 unmodified lines563 tags: (name) => read(name, (repo) => tagsOf(name, repo)),564 });565 });566 636-/**637- * Artifacts through the Workers binding, the platform's `RepoHost` in638- * production. Refs and pushes go over git smart HTTP through `Fetch`.639- */567 export const RepoHostBinding = {568 layer: (binding: Artifacts): Layer.Layer<RepoHost, never, Fetch> =>569 Layer.effect(RepoHost, make(binding)),570 };modified:packages/artifacts/src/repo-host/isogit-store.ts+2 added-27 removed
42 unmodified lines43 RepoName,44 RepoNotFound,45 } from "../repo-host.ts";46 47-/**48- * A bare repo's directory on a file system isomorphic-git reads and writes:49- * the shape a push takes its objects from, so every stored repo is a source50- * too.51- */47 export type GitDir = PushSource;48 54-/** A repo a store found by name: its directory and the lock its pushes take. */49 export interface StoredRepo {50 readonly dir: GitDir;51 readonly lock: Semaphore.Semaphore;52 }53 60-/** The ref every repo's HEAD names: Artifacts' default branch. */54 export const mainRef = "refs/heads/main";55 56 class GitFailure extends Data.TaggedError("GitFailure")<{57 readonly cause: unknown;1 unmodified line59 60 const git = <A>(run: () => Promise<A>) =>61 Effect.tryPromise({ catch: (cause) => new GitFailure({ cause }), try: run });62 70-/** `None` where isomorphic-git finds no such object, ref or file. */63 export const unlessMissing = <A>(64 run: () => Promise<A>65 ): Effect.Effect<Option.Option<A>> =>66 git(run).pipe(18 unmodified lines85 : Effect.die(`copying ${oid} produced ${written}`)86 )87 );88 97-/** A new, empty bare repo whose HEAD names `main`. */89 export const initBare = (repo: GitDir) =>90 git(() => init({ ...repo, bare: true, defaultBranch: "main" })).pipe(91 Effect.orDie92 );3 unmodified lines96 Effect.map(Option.map((sha) => CommitSha.make(sha)))97 );98 99 /**109- * The ref a remote's import takes when none is named: the branch its HEAD110- * names, or, when HEAD names a branch it lacks (a store made here names111- * `main`), its one branch, as a remote whose default is `master` has it.112- * Otherwise what HEAD names, even a branch it lacks; `None` only for a113- * detached HEAD.100+ * When HEAD names a branch the remote lacks (a store made here names `main`),101+ * its one branch, as a remote whose default is `master` has it.102 */103 export const defaultRefOf = (repo: GitDir) =>104 Effect.gen(function* () {105 const head = Option.filter(79 unmodified lines185 );186 yield* keep(oid, () => writeCommit({ ...into, commit }));187 });188 201-/**202- * A ref's target, objects first: an annotated tag after what it names203- * (a commit, or another tag), or else a commit and its history.204- */189 const copyTarget = (190 source: PushSource,191 into: GitDir,192 oid: string16 unmodified lines209 yield* copyTarget(source, into, tag.value.tag.object);210 yield* keep(oid, () => writeTag({ ...into, tag: tag.value.tag }));211 });212 229-/** Sets the new repo `into`'s `ref` to `source`'s `tip`, objects first. */213 export const seedRef = (214 source: PushSource,215 into: GitDir,216 ref: string,53 unmodified lines270 }))271 )272 );273 291-// isomorphic-git's entries carry `path` and `oid`; the port's, `name` and `sha`.274 const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));275 294-/**295- * The RepoHost methods that read a repo's objects and refs or push to it,296- * the same over every store whose repos are isomorphic-git directories:297- * `known` finds a repo's directory and lock by name. A push is a298- * compare-and-swap per ref under the repo's lock, never atomic across refs;299- * reads resolve short branch names and commit ids only.300- */276 export const objectsAndRefs = (277 known: (name: RepoName) => Effect.Effect<StoredRepo, RepoNotFound>278 ): Pick<279 RepoHost["Service"],133 unmodified linesmodified:packages/artifacts/src/repo-host/local.ts+5 added-37 removed
52 unmodified lines53 unlessMissing,54 } from "./isogit-store.ts";55 import type { GitDir } from "./isogit-store.ts";56 57-/** A promise from isomorphic-git or the file system that rejected. */57 class IoFailure extends Data.TaggedError("IoFailure")<{58 readonly cause: unknown;59 }> {}60 61 const io = <A>(run: () => Promise<A>) =>62 Effect.tryPromise({ catch: (cause) => new IoFailure({ cause }), try: run });63 65-/** Whether a file-system call failed with node's error `code`. */64 const failedWith = (code: "EEXIST" | "ENOENT") => (failure: IoFailure) =>65 failure.cause instanceof Error &&66 "code" in failure.cause &&67 failure.cause.code === code;68 71-/** Whether anything is at `path`. */69 const exists = (path: string) =>70 io(() => fs.promises.stat(path)).pipe(71 Effect.as(true),72 Effect.catchIf(failedWith("ENOENT"), () => Effect.succeed(false)),73 Effect.orDie74 );75 79-/** Deletes `path` and everything under it; whether there was anything. */76 const removeAll = (path: string) =>77 Effect.gen(function* () {78 const found = yield* exists(path);79 3 unmodified lines83 84 return found;85 });86 91-/** The remote an HTTP import fetches through, removed once it has. */87 const importRemote = "import";88 89 const branchOf = (ref: string) => ref.replace(/^refs\/heads\//u, "");90 96-/**97- * The tokens a repo has minted, kept beside its objects so that every layer98- * over the same root sees them. `minted` counts every token ever minted, so99- * no two get the same id.100- */91 const Tokens = Schema.fromJsonString(92 Schema.Struct({ live: Schema.Array(Schema.String), minted: Schema.Int })93 );94 22 unmodified lines117 ? Stream.fromAsyncIterable(body, (cause) => new IoFailure({ cause }))118 : Stream.fromIterable(body)119 ).pipe(Stream.runCollect, Effect.map(concat));120 131-/** One chunk as the async iterator isomorphic-git reads a response body from. */121 const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {122 const chunks = [bytes];123 124 const iterator: AsyncIterableIterator<Uint8Array> = {11 unmodified lines136 137 return iterator;138 };139 151-/**152- * isomorphic-git's HTTP client over a `Fetch`. isomorphic-git awaits a153- * promise, so each exchange runs as one; a `Fetch` failure rejects it as is.154- */140 const httpOver = (141 fetch: Fetch["Service"]["fetch"],142 context: Context.Context<never>143 ): HttpClient => ({26 unmodified lines170 })171 ),172 });173 189-/** Why a fetch from `url` brought nothing to import. */174 const fetchRefusal = (url: string, cause: unknown) =>175 Match.value(cause).pipe(176 Match.when(Schema.is(FetchFailed), (failed) => failed.reason),177 Match.when(Match.instanceOf(Error), (thrown) => thrown.message),39 unmodified lines217 218 return lock;219 });220 237- /** The repo's directory and lock, if the repo exists. */221 const known = (name: RepoName) =>222 Effect.gen(function* () {223 const dir = dirOf(name);224 3 unmodified lines228 229 return { dir, lock: yield* lockOf(name) };230 });231 249- /** A new, empty bare repo; making its directory is what claims the name. */232+ /** Making its directory is what claims the name. */233 const open = (name: RepoName) =>234 Effect.gen(function* () {235 const dir = dirOf(name);236 11 unmodified lines248 249 return dir;250 });251 269- /** A new repo `name` holding `source`'s `ref` at `tip`, copied as it stands. */252 const seed = (253 name: RepoName,254 source: PushSource,255 ref: string,4 unmodified lines260 261 return createdOf(name);262 });263 282- // Local disk's test-only meaning of a public remote: a bare repo on this283- // machine, copied object by object. Without a branch, it takes the one284- // the repo's HEAD names.264+ // Test-only meaning of a public remote: a bare repo on this machine.265 const importFile = (266 name: RepoName,267 url: string,268 branch: BranchName | undefined269 ) =>270 Effect.gen(function* () {271 const noRepo = new ImportRefused({ name, reason: `no repo at ${url}` });272 293- // A file URL that names another host is no path on this machine.273 const gitdir = yield* Effect.try({274 catch: () => noRepo,275 try: () => fileURLToPath(url),276 });5 unmodified lines282 if (Option.isNone(head)) {283 return yield* noRepo;284 }285 307- // Without a branch, what HEAD names, or the one branch when HEAD308- // names none it has (`main` on a repo whose only branch is309- // `master`). A detached HEAD with several branches names none.286 const named =287 branch === undefined288 ? yield* defaultRefOf({ fs, gitdir })289 : Option.some(`refs/heads/${branch}`);18 unmodified lines308 309 return yield* seed(name, { fs, gitdir }, ref, tip);310 });311 336- /** One branch of a smart-HTTP remote, fetched into the empty repo `gitdir`. */312 const fetchInto = (313 name: RepoName,314 gitdir: string,315 url: string,43 unmodified lines359 360 yield* io(() => writeRef({ fs, gitdir, ref, value: tip })).pipe(361 Effect.orDie362 );388- // No repo here has remotes or remote-tracking refs.363 yield* io(() =>364 deleteRemote({ fs, gitdir, remote: importRemote })365 ).pipe(Effect.orDie);366 yield* removeAll(`${gitdir}/refs/remotes`);367 368 return createdOf(name);369 });370 397- // A public remote over smart HTTP, through the `Fetch` this layer was398- // given. A failed import leaves no repo behind.371+ // A failed import leaves no repo behind.372 const importHttp = (373 name: RepoName,374 url: string,375 branch: BranchName | undefined3 unmodified lines379 Effect.onError(() => removeAll(gitdir).pipe(Effect.asVoid))380 )381 );382 410- /** The repo's tokens file, read and rewritten under the repo's lock. */383 const updateTokens = <A>(384 name: RepoName,385 change: (tokens: Tokens) => Effect.Effect<readonly [A, Tokens]>386 ) =>115 unmodified lines502 });503 504 /**505 * Artifacts on local disk, for tests that need real git over HTTP and for the534- * CLI's dev mode: each repo a bare git repo `<root>/<name>.git` with default535- * branch `main`, kept across layers over the same root. A push is a536- * compare-and-swap per ref with no atomicity across refs, as probes found537- * Artifacts. `remote(name)` is `<remoteBase>/<name>.git`, so a test can serve538- * `root` with `git http-backend` under that base and drive real git at it.539- * Tokens are recorded, never checked.506+ * CLI's dev mode. Pushes are a compare-and-swap per ref with no atomicity507+ * across refs, as probes found Artifacts. Tokens are recorded, never checked.508 */509 export const RepoHostLocal = {510 layer: (options: {511 readonly root: string;4 unmodified linesmodified:packages/artifacts/src/repo-host/memory-fs.ts-6 removed
1-/**2- * An in-memory file system: the part of `fs.promises` that isomorphic-git3- * calls (`docs/fs.md` in isomorphic-git), with node's error codes.4- */5-1 type ReadOptions = string | { readonly encoding?: string } | undefined;2 3 interface Stats {4 readonly mode: number;163 unmodified lines168 ? Promise.resolve(stats("dir", 0))169 : failure("ENOENT", path);170 };171 177- /** Deletes a directory and everything under it; not part of `fs`. */172 const removeTree = (raw: string) => {173 const root = normalize(raw);174 175 const inside = (path: string) =>27 unmodified linesmodified:packages/artifacts/src/repo-host/memory.ts+1 added-10 removed
27 unmodified lines28 remote: remoteOf(name),29 });30 31 interface Repo extends StoredRepo {32- /** Token ids still live; the memory store authenticates nothing. */32+ /** The memory store authenticates nothing. */33 readonly tokens: Set<string>;34 }35 36-/**37- * Artifacts in memory, as probes found it: each repo a bare git directory, a push38- * a compare-and-swap per ref with no atomicity across refs, and reads that39- * resolve short branch names and commit ids only.40- */36 const make = () => {37 const fs = memoryFs();38 const repos = new Map<RepoName, Repo>();39 let minted = 0;23 unmodified lines63 64 return repo;65 });66 72- /** A new repo `name` holding `from`'s `ref` at `tip`, copied as it stands. */67 const seed = (68 from: Repo,69 name: RepoName,70 ref: string,37 unmodified lines108 reason: `no repo at ${source.url}`,109 });110 }111 118- // Without a branch, the remote's default: what its HEAD names, or119- // its one branch, as `master` is on a remote that has only that.112 const named =113 source.branch === undefined114 ? yield* defaultRefOf(from.dir)115 : Option.some(`refs/heads/${source.branch}`);52 unmodified lines168 known(name).pipe(Effect.map((repo) => repo.tokens.delete(id))),169 });170 };171 180-/** A fresh, empty store each time the layer is built. */172 export const RepoHostMemory = Layer.sync(RepoHost, make);modified:packages/artifacts/src/repo-host/rest.ts+15 added-108 removed
1 /**2- * `RepoHost` over the Artifacts REST API, with a Cloudflare API token: for3- * code that runs outside a Worker, such as infra scripts and the seed4- * script. It passes the contract the binding passes, and types the same5- * surprises:2+ * Over the REST API, as probes and the docs found it:3 *4 * - a fork names its target (`{name, default_branch_only: true}`), which8- * cf's `artifacts namespaces repos fork` cannot do (cf #180);9- * - a fork that answers 500 (code 10400) is tried once more, and an10- * already-exists or a second 500 after that may be the fork the first11- * made: it is, if it lists `main`, as on the binding;12- * - `refs` and `push` have no REST route, so they go over git smart HTTP to13- * the repo's `remote` (`smart-http.ts`), with a repo token this layer mints.5+ * cf's `artifacts namespaces repos fork` cannot do;6+ * - a fork that answers 500 (code 10400) may still have made the repo, as on7+ * the binding;8+ * - `refs` and `push` have no REST route, so they go over git smart HTTP;9+ * - a token id resolves through an eventually consistent index, so revoking10+ * it within about a second of its mint can be 404.11 *15- * Every route is under `<base>/accounts/<accountId>/artifacts/namespaces/16- * <namespace>` and carries the API token as `Authorization: Bearer`, and17- * nowhere else. Each was confirmed with `bun run ops -- schema artifacts18- * namespaces <command>` (cf 1.0.0-beta.12, read-only), and against19- * Artifacts' REST docs (developers.cloudflare.com/artifacts/api/rest-api),20- * which spell bodies in snake case where cf's flags use kebab case:21- *22- * | Port | Route | `<command>` | Body or query |23- * | --- | --- | --- | --- |24- * | `create` | `POST /repos` | `repos create` | `{name}` |25- * | `remote`, and whether a repo exists | `GET /repos/{name}` | `repos get` | |26- * | `remove` | `DELETE /repos/{name}` | `repos delete` | |27- * | `fork` | `POST /repos/{base}/fork` | `repos fork` | `{name, default_branch_only: true}`: the docs and the probes send `name`; cf's schema lacks it (cf #180) |28- * | `importFrom` | `POST /repos/{name}/import` | `repos import` | `{url, branch?}` |29- * | `mintToken`, and the git calls' tokens | `POST /tokens` | `tokens create` | `{repo, scope, ttl}` |30- * | `revokeToken` | `DELETE /tokens/{id}` | `tokens revoke` | |31- * | `readCommit` | `GET /repos/{name}/commit/{hash}` | `repos commits get` | |32- * | `readTree` | `GET /repos/{name}/tree/{hash}` | `repos trees get` | |33- * | `readBlob` | `GET /repos/{name}/blob/{hash}` | `repos blobs get` | raw bytes back |34- * | `readFile` | `GET /repos/{name}/file` | `repos files get` | `?ref&path`; raw bytes back |35- * | `log` | `GET /repos/{name}/log` | `repos logs get` | `?ref&limit&offset` |36- *37- * cf's schema gives no reply shapes. From the docs: every JSON reply, and38- * every refusal, is Cloudflare's v4 envelope, `{success, errors: [{code,39- * message}], messages, result}`; blob and file replies are raw bytes; create,40- * fork, import and a repo's info carry `remote`; a minted token is `{id,41- * plaintext, scope, expires_at}`; a repo still being imported or forked42- * answers 409 (cf's generated client declares 409 for a repo's info and a43- * token's mint too); errors carry Artifacts' numeric codes (its errors44- * page), which the binding's `numericCode` matches (workers-types), and probes45- * saw 10201 and 10400 live. A refusal that names no code at all, such as a46- * proxy's, is read by its status: 404 is not found, 5xx internal. One that47- * names only Cloudflare's own codes (7000, an unknown route) is a defect.48- * ASSUMPTIONs, for a live run to settle:49- *50- * - a commit is the binding's metadata, spelled in snake case51- * (`tree_hash`) as the API's other fields are, or in camel case as the52- * binding's; a tree's `result` is the binding's entries, and a log's is a53- * list of commit metadata;54- * - a 404 from a read is the object's absence once the repo is found to55- * exist, and a tree read at another kind of object fails as the binding's56- * does (500), so the adapter asks whether it is a blob or a commit;57- * - a log page may hold fewer commits than asked before the history ends58- * (a server cap), so only an empty page ends it.59- *60- * A token id resolves through an eventually consistent index, so revoking it61- * within about a second of its mint can be 404 (cf's help for `tokens62- * revoke`): a 404 for a token this layer minted less than two seconds ago is63- * tried once more when they have passed. Git calls share one token per repo64- * and scope, minted on first use, minted again near its expiry, and revoked65- * when the layer closes. The day-long write token create, fork and import66- * return is dropped, as the binding drops it.12+ * ASSUMPTIONs, for a live run to settle: a commit's fields are snake case or13+ * camel case; a 404 from a read is the object's absence once the repo exists;14+ * a tree read at another kind of object is 500; and a log page may hold fewer15+ * commits than asked, so only an empty page ends it.16 */17 import { CommitSha } from "@repo/protocol/ids";18 import {19 Data,35 unmodified lines55 } from "./artifacts-api.ts";56 import type { Code } from "./artifacts-api.ts";57 import { listRefs, listTags, pushRefs } from "./smart-http.ts";58 110-/** A refusal that names no code at all, such as a proxy's, read by status. */59 const byStatus = (status: number): Option.Option<Code> =>60 Match.value(status).pipe(61 Match.when(404, () => Option.some<Code>("NOT_FOUND")),62 Match.when(2 unmodified lines65 ),66 Match.orElse(() => Option.none())67 );68 121-/** A reply that was no success: its status, the code it names, its messages. */69 class Refused extends Data.TaggedError("Refused")<{70 readonly status: number;71 readonly code: Option.Option<Code>;72 readonly message: string;73 }> {}74 128-/** A fork that answered 500, which may still have made the repo. */75 class MaybeForked extends Data.TaggedError("MaybeForked")<{76 readonly refused: Refused;77 }> {}78 5 unmodified lines84 85 const decodeFailure = Schema.decodeOption(Failure);86 87 /**142- * A refused reply read: by the first code Artifacts names, or by its status143- * when it names no code at all. One that names only codes Artifacts does not144- * own, such as Cloudflare's 7000 for a route it does not know, reads as no145- * code, so a wrong route, account or namespace is a defect and never passes146- * for a missing repo or object.88+ * A reply naming only codes Artifacts does not own (Cloudflare's 7000 for an89+ * unknown route) reads as no code, so a wrong route, account or namespace is90+ * a defect and never passes for a missing repo or object.91 */92 const refusedBy = (status: number, text: string) => {93 const problems = Option.match(decodeFailure(text), {94 onNone: () => [],17 unmodified lines112 (...codes: readonly Code[]) =>113 (refused: Refused): boolean =>114 Option.exists(refused.code, (code) => codes.includes(code));115 172-/** Cloudflare's v4 envelope around a success's `result`. */116 const Envelope = <S extends Schema.Top>(result: S) =>117 Schema.fromJsonString(118 Schema.Struct({ result, success: Schema.Literal(true) })119 );96 unmodified lines216 textOf(response).pipe(217 Effect.flatMap((text) => Effect.fail(refusedBy(response.status, text)))218 );219 277-/** A success's envelope, decoded at the boundary, or what refused it. */220 const decoded =221 <A>(codec: Schema.Codec<A, string>) =>222 (response: Response) =>223 response.ok2 unmodified lines226 Effect.orDie227 )228 : refusal(response);229 288-/** A success's raw bytes, or what refused it. */230 const bytesOf = (response: Response) =>231 response.ok232 ? Effect.promise(() => response.arrayBuffer()).pipe(233 Effect.map((buffer) => new Uint8Array(buffer))4 unmodified lines238 response.ok ? Effect.void : refusal(response);239 240 const main = RefName.make("refs/heads/main");241 301-/** How long a token for git calls lives, and how near its expiry it is replaced. */242 const CALL_TOKEN_TTL = Duration.minutes(30);243 244 const CALL_TOKEN_MARGIN = Duration.minutes(5);245 306-/** How long a token id may be unknown to the index after its mint. */246 const REVOKE_LAG = Duration.seconds(2);247 309-/** A token this layer minted and has not revoked. */248 interface Token {249 readonly name: RepoName;250 readonly at: DateTime.Utc;313- /** Minted for the layer's own git calls, and revoked when it closes. */251 readonly forCalls: boolean;252 }253 317-/** What a git call to a repo needs: its remote, and a token. */254 interface Access {255 readonly name: RepoName;256 readonly remote: string;257 readonly token: Redacted.Redacted;12 unmodified lines270 "FORK_IN_PROGRESS",271 "IMPORT_IN_PROGRESS",272 ] as const satisfies readonly Code[];273 338-/** What a create or an import refuses a name with: one taken, or being made. */274 const TAKEN = [275 "ALREADY_EXISTS",276 ...BEING_MADE,277 ] as const satisfies readonly Code[];24 unmodified lines302 const access = yield* Ref.make<ReadonlyMap<string, Access>>(new Map());303 304 const authorization = () => `Bearer ${Redacted.value(options.token)}`;305 371- /** One request to the API; one that got no response is a defect. */306 const send = (request: Request) => fetch.fetch(request).pipe(Effect.orDie);307 308 const httpGet = (path: string) =>309 send(37 unmodified lines347 method: "POST",348 })349 );350 417- /** A repo's remote; a 409 there is a repo still being made. */351 const infoOf = (name: RepoName) =>352 httpGet(repoPath(name)).pipe(353 Effect.flatMap(decoded(Remote)),354 Effect.map(({ result }) => result.remote),12 unmodified lines367 368 const remoteOf = (name: RepoName) =>369 infoOf(name).pipe(Effect.catchTag("ForkInProgress", Effect.die));370 438- /**439- * A read whose 404 is the object's absence once the repo is found to440- * exist; any other refusal is a defect.441- */371 const optional = <A>(name: RepoName, read: Effect.Effect<A, Refused>) =>372 read.pipe(373 Effect.asSome,374 Effect.catchTag("Refused", (refused) =>60 unmodified lines435 is("NOT_FOUND")(refused) ? Effect.succeed(false) : Effect.die(refused)436 )437 );438 510- /**511- * Revokes the token `id`, once more when the index may not know it yet;512- * whether it was revoked. The layer forgets the token either way.513- */439 const revoke = (id: string) =>440 Effect.gen(function* () {441 const token = (yield* Ref.get(minted)).get(id);442 const revoked = yield* revokeOnce(id);19 unmodified lines462 463 return again;464 });465 541- /** The remote and token a git call to `name` uses, minted on first use. */466 const accessOf = (name: RepoName, scope: TokenScope) =>467 Effect.gen(function* () {468 const key = `${scope}:${name}`;469 const now = yield* DateTime.now;46 unmodified lines516 );517 518 /**519 * After a 500 and then an already-exists or a second 500, the fork may be596- * made: it is, if it lists `main`. Otherwise it is still being made,597- * or was undone; either way the caller tries again later.520+ * made: it is, if it lists `main`.521 */522 const confirmed = (name: RepoName) =>523 Effect.gen(function* () {524 const { remote, token } = yield* accessOf(name, "read");10 unmodified lines535 ),536 Effect.provideService(Fetch, fetch)537 );538 616- /**617- * One fork request. The base's absence names the base; any other refusal618- * names the target, and a 500 is `MaybeForked`, since it may have made it.619- */539 const forkOnce = (from: RepoName, name: RepoName) =>540 httpPost(`${repoPath(from)}/fork`, {541 default_branch_only: true,542 name,18 unmodified lines561 )562 )563 );564 646- /** Whether the repo holds `id` as a blob or a commit, as a tree read refused it. */565 const blobOrCommit = (name: RepoName, id: ObjectId) =>566 optional(567 name,568 httpGet(`${repoPath(name)}/blob/${id}`).pipe(Effect.flatMap(bytesOf))22 unmodified lines591 Match.value(refused).pipe(592 Match.when(is("NOT_FOUND"), () =>593 remoteOf(name).pipe(Effect.as(Option.none()))594 ),677- // A blob's or a commit's id names no tree, as on the other stores;678- // any other failure stays one.595 Match.when(is("INTERNAL_ERROR"), () =>596 blobOrCommit(name, tree).pipe(597 Effect.flatMap((other) =>598 other ? Effect.succeedNone : Effect.die(refused)4 unmodified lines603 )604 )605 );606 691- /** One page of a log; a ref that names nothing logs nothing, as the binding's. */607 const page = (name: RepoName, ref: string, offset: number, limit: number) =>608 httpGet(609 `${repoPath(name)}/log?${new URLSearchParams({610 limit: String(limit),147 unmodified lines758 ),759 });760 });761 847-/**848- * Artifacts over its REST API, for scripts: the same `RepoHost`849- * the platform reaches through the binding. The API token is the caller's850- * (scripts get it from `varlock run`), and goes only into the851- * `Authorization` header of requests to the API. Delete only repos the852- * caller made with it.853- */762 export const RepoHostRest = {763 layer: (options: {764 readonly accountId: string;765 readonly namespace: string;766 readonly token: Redacted.Redacted;859- /** Defaults to `https://api.cloudflare.com/client/v4`. */767 readonly base?: string;768 }): Layer.Layer<RepoHost, never, Fetch> =>769 Layer.effect(RepoHost, make(options)),770 };modified:packages/artifacts/src/repo-host/smart-http.ts+10 added-54 removed
1-/**2- * Git smart HTTP over the `Fetch` port, for adapters whose store serves git3- * at a remote URL with a bearer token: `/binding` and `/rest`. It takes a4- * `remote` (`…/<repo>.git`, Artifacts' shape) and a token, and nothing about5- * how either was got.6- *7- * The token goes only into the `Authorization` header of requests to the8- * remote's own origin; everywhere else it stays `Redacted`.1+// The token goes only into the `Authorization` header of requests to the2+// remote's own origin; everywhere else it stays `Redacted`.9- */3 import { CommitSha } from "@repo/protocol/ids";4 import {5 Data,6 Effect,32 unmodified lines39 RepoNotFound,40 } from "../repo-host.ts";41 import type { PushSource, RefUpdate, Tag } from "../repo-host.ts";42 50-/** What isomorphic-git or a response body threw, before it is read. */43 class GitFailure extends Data.TaggedError("GitFailure")<{44 readonly cause: unknown;45 }> {}46 20 unmodified lines67 const decodeRef = Schema.decodeUnknownOption(RefName);68 69 const decodeSha = Schema.decodeUnknownOption(CommitSha);70 79-/** The repo a remote names: its last path segment, less `.git`. */71 const repoOf = (remote: string) =>72 Option.match(73 decodeRepo(74 (URL.canParse(remote) ? new URL(remote).pathname : remote)29 unmodified lines104 ? Stream.fromAsyncIterable(body, (cause) => new GitFailure({ cause }))105 : Stream.fromIterable(body)106 ).pipe(Stream.runCollect, Effect.map(concat));107 117-/** One chunk as the async iterator isomorphic-git reads a response body from. */108 const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {109 const chunks = [bytes];110 111 const iterator: AsyncIterableIterator<Uint8Array> = {11 unmodified lines123 124 return iterator;125 };126 137-/** The side-band 3 (fatal) messages in a reply's top-level packet lines. */127 const fatalMessages = (bytes: Uint8Array) => {128 const messages: string[] = [];129 const text = new TextDecoder();130 let at = 0;4 unmodified lines135 if (Number.isNaN(length)) {136 break;137 }138 150- // A flush (`0000`) or a delimiter carries no payload.139 if (length < 4) {140 at += 4;141 continue;142 }10 unmodified lines153 154 const isReceivePack = (url: string) =>155 new URL(url).pathname.endsWith("/git-receive-pack");156 169-/**170- * isomorphic-git's HTTP client over `Fetch`, for one repo. It adds the token171- * to requests to the remote's origin, and reads a 404 as `RepoNotFound` and a172- * busy receive-pack as `HostBusy`, failing the exchange with them, so the173- * promise isomorphic-git awaits rejects with the typed error itself.174- */157 const httpFor = (remote: string, token: Redacted.Redacted, name: RepoName) =>158 Effect.gen(function* () {159 const run = yield* FiberSet.makeRuntimePromise<Fetch>();160 const { origin } = new URL(remote);53 unmodified lines214 } satisfies HttpClient;215 });216 217 /**236- * Runs an isomorphic-git call. The typed errors the HTTP client failed with237- * come back as new values (isomorphic-git stamps a `caller` onto what it238- * rethrows); anything else it threw is a `GitFailure` for the caller to read.218+ * The typed errors come back as new values: isomorphic-git stamps a `caller`219+ * onto what it rethrows.220 */221 const git = <A>(run: (signal: AbortSignal) => Promise<A>) =>222 Effect.tryPromise({223 catch: (cause) =>7 unmodified lines231 ),232 try: run,233 });234 254-/** Every ref the remote lists, custom refs included; never `HEAD` or a peeled tag. */235 const refsAt = (remote: string, http: HttpClient) =>236 git(() => listServerRefs({ http, protocolVersion: 1, url: remote })).pipe(237 Effect.catchTags({238 GitFailure: ({ cause }) => Effect.die(cause),12 unmodified lines251 )252 )253 );254 275-/**276- * Every `refs/tags/*` the remote lists, each peeled to what it names: the277- * `^{}` line protocol v1 advertises after an annotated tag, else the tag's278- * own target.279- */255+/** Peeled by the `^{}` line protocol v1 advertises after an annotated tag, else the tag's own target. */256 const tagsAt = (remote: string, http: HttpClient) =>257 git(() =>258 listServerRefs({259 http,16 unmodified lines276 )277 )278 );279 304-/** Every tag the remote lists, peeled to its commit. */280 export const listTags = (281 remote: string,282 token: Redacted.Redacted283 ): Effect.Effect<readonly Tag[], RepoNotFound, Fetch> =>4 unmodified lines288 return yield* tagsAt(remote, yield* httpFor(remote, token, name));289 })290 );291 317-/**318- * Every ref the remote lists, as `ls-remote` lists them: what reads by name319- * cannot reach.320- */292 export const listRefs = (293 remote: string,294 token: Redacted.Redacted295 ): Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound, Fetch> =>7 unmodified lines303 304 const isMoved = (reason: string) =>305 MOVED.some((moved) => reason.includes(moved));306 336-/** Whether the store refused a push of `ref` because the ref moved. */307 const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>308 cause instanceof Errors.GitPushError &&309 isMoved(cause.data.result.refs[ref]?.error ?? "");310 311 /**342- * One ref's compare-and-swap. The push's own ref discovery is the check: if343- * the tip it finds is not `from`, the push stops there, before any pack is344- * built, so the old value the push names is the one checked, and the store345- * checks it again as it moves the ref. A ref that moved after the check is346- * `Stale` at the tip a fresh listing shows.347- *348- * The old value is the only check, as on every store: `to` need not descend349- * from `from` (Artifacts takes such an update). So isomorphic-git's350- * own fast-forward test is off (`force`), which also spares it walking the351- * history of `to` in a source that holds only the new objects.312+ * One ref's compare-and-swap: the push's own ref discovery is the check, so313+ * it stops before any pack is built if the tip is not `from`. `to` need not314+ * descend from `from` (Artifacts takes such an update), so isomorphic-git's315+ * fast-forward test is off (`force`).316 */317 const pushOne = (318 remote: string,319 http: HttpClient,62 unmodified lines382 return pushed;383 });384 385 /**422- * Pushes each update in order, one ref per push, since Artifacts has no423- * atomic push: each ref is updated or `Stale` on its own. Nothing is424- * retried; a `Stale` ref is the caller's to decide on. A busy store fails the386+ * One ref per push, since Artifacts has no atomic push. A busy store fails the387 * whole call with `HostBusy`, and refs before the busy one may have moved.388 */389 export const pushRefs = (input: {390 readonly remote: string;11 unmodified lines402 );403 })404 );405 444-/**445- * Fetches one ref of the remote into the repo `gitdir` in `fs` (made if446- * absent), `depth` commits deep when given; its tip, or `None` when the remote447- * has no such ref. The ref is a branch name or a full ref. The repo keeps the448- * objects and no ref, remote or tracking ref of the fetch's own.449- */406 export const fetchInto = (input: {407 readonly remote: string;408 readonly token: Redacted.Redacted;409 readonly fs: FsClient;65 unmodified linesmodified:packages/artifacts/src/fetch.ts-7 removed
1 import { Context, Schema } from "effect";2 import type { Effect } from "effect";3 4-/** An HTTP request that got no response: the network, DNS or TLS failed. */4 export class FetchFailed extends Schema.TaggedError<FetchFailed>()(5 "FetchFailed",6 { reason: Schema.String, url: Schema.String }7 ) {}8 10-/**11- * The one way a package makes an HTTP request, so none calls the global12- * `fetch`. A response of any status is a success; only a request that got no13- * response fails. The Worker's adapter wraps its `fetch`; tests serve an14- * in-process handler with `Fetch.of`.15- */9 export class Fetch extends Context.Service<10 Fetch,11 {12 readonly fetch: (request: Request) => Effect.Effect<Response, FetchFailed>;2 unmodified linesmodified:packages/artifacts/src/repo-host.ts+5 added-60 removed
10 unmodified lines11 } from "effect";12 import type { Array, DateTime, Duration, Redacted } from "effect";13 import type { FsClient } from "isomorphic-git";14 15-/** A repo's name in its namespace: the one `RepoName`, from the domain. */15 export { RepoName } from "@repo/protocol/ids";16 18-/** A short branch name such as `main` or `feature/x`, never `refs/…`. */17 export const BranchName = Schema.String.pipe(18 Schema.check(19 Schema.isPattern(20 /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u3 unmodified lines24 );25 26 export type BranchName = typeof BranchName.Type;27 30-/**31- * A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`,32- * `refs/tags/@changesets/cli@2.27.1` (a scoped package's tag; `@` and `+`33- * are git's as well).34- */28 export const RefName = Schema.String.pipe(29 Schema.check(30 Schema.isPattern(31 /^refs\/(?!.*\.\.)[A-Za-z0-9._@+-]+(?:\/[A-Za-z0-9._@+-]+)+$/u3 unmodified lines35 );36 37 export type RefName = typeof RefName.Type;38 46-/** A git object id: 40 lowercase hex digits. */39 export const ObjectId = Schema.String.pipe(40 Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),41 Schema.brand("ObjectId")42 );43 44 export type ObjectId = typeof ObjectId.Type;45 54-/**55- * One immediate child of a git tree, as `git ls-tree` lists it: `040000` and56- * `tree` for a folder, `160000` and `commit` for a submodule.57- */46 export const TreeEntry = Schema.Struct({47 mode: Schema.Literals(["100644", "100755", "120000", "040000", "160000"]),48 name: Schema.NonEmptyString,49 sha: ObjectId,1 unmodified line51 });52 53 export type TreeEntry = typeof TreeEntry.Type;54 67-/**68- * Where a read starts. Artifacts' binding resolves short branch names and69- * commit ids only, so these are the only two kinds.70- */55+/** Artifacts' binding resolves short branch names and commit ids only. */56 export type Revision = Data.TaggedEnum<{57 Branch: { readonly name: BranchName };58 Commit: { readonly sha: CommitSha };59 }>;1 unmodified line61 export const Revision = Data.taggedEnum<Revision>();62 63 const Person = Schema.Struct({ email: Schema.String, name: Schema.String });64 80-/** A commit, with when it was written and when committed, in Unix seconds. */65 export const Commit = Schema.Struct({66 author: Person,67 authoredAt: Schema.Int,68 committedAt: Schema.Int,5 unmodified lines74 });75 76 export type Commit = typeof Commit.Type;77 94-/** One tag: its full ref, and the commit it names, peeled. */78 export interface Tag {79 readonly name: RefName;80 readonly sha: CommitSha;81 }11 unmodified lines93 readonly name: RepoName;94 readonly remote: string;95 }96 114-/** A local git repo, read through isomorphic-git, that a push takes objects from. */97 export interface PushSource {98 readonly fs: FsClient;99 readonly gitdir: string;100 }101 120-/**121- * One ref's compare-and-swap. `from` is the tip the pusher expects; `None`122- * means the ref must not exist yet.123- */102 export interface RefUpdate {103 readonly ref: RefName;104 readonly from: Option.Option<CommitSha>;105 readonly to: CommitSha;15 unmodified lines121 export class RepoExists extends Schema.TaggedError<RepoExists>()("RepoExists", {122 name: RepoName,123 }) {}124 147-/** Artifacts is still forking this repo; retry. */125 export class ForkInProgress extends Schema.TaggedError<ForkInProgress>()(126 "ForkInProgress",127 { name: RepoName }128 ) {}129 153-/** The store would not import from that remote: not git, not public, or not reachable. */130 export class ImportRefused extends Schema.TaggedError<ImportRefused>()(131 "ImportRefused",132 { name: RepoName, reason: Schema.String }133 ) {}134 159-/** The store refused a whole push while busy with another; retry. */135 export class HostBusy extends Schema.TaggedError<HostBusy>()("HostBusy", {136 name: RepoName,137 }) {}138 164-/**165- * The git store the platform keeps repos in. The only way to Artifacts: every166- * other package reaches it through this port.167- */139 export class RepoHost extends Context.Service<140 RepoHost,141 {142 readonly create: (name: RepoName) => Effect.Effect<RepoCreated, RepoExists>;172- /**173- * A new repo holding one branch of a public remote: `branch`, or the174- * remote's default branch, under its own name.175- */143 readonly importFrom: (144 name: RepoName,145 source: { readonly url: string; readonly branch?: BranchName }146 ) => Effect.Effect<RepoCreated, RepoExists | ImportRefused>;180- /** Forks the default branch only, as Artifacts does by default. */147 readonly fork: (148 base: RepoName,149 name: RepoName150 ) => Effect.Effect<RepoCreated, RepoNotFound | RepoExists | ForkInProgress>;6 unmodified lines157 readonly revokeToken: (158 name: RepoName,159 id: string160 ) => Effect.Effect<boolean, RepoNotFound>;195- /** The git URL that pushes and fetches go to. */161 readonly remote: (name: RepoName) => Effect.Effect<string, RepoNotFound>;162 readonly readFile: (163 name: RepoName,164 at: Revision,2 unmodified lines167 readonly readCommit: (168 name: RepoName,169 sha: CommitSha170 ) => Effect.Effect<Option.Option<Commit>, RepoNotFound>;206- /** A tree's immediate children by the tree's id; `None` when no tree has it. */171 readonly readTree: (172 name: RepoName,173 tree: ObjectId174 ) => Effect.Effect<Option.Option<readonly TreeEntry[]>, RepoNotFound>;211- /** A blob's bytes by its id; `None` when no blob has it. */175 readonly readBlob: (176 name: RepoName,177 blob: ObjectId178 ) => Effect.Effect<Option.Option<Uint8Array>, RepoNotFound>;3 unmodified lines182 at: Revision,183 limit: number,184 offset?: number185 ) => Effect.Effect<readonly Commit[], RepoNotFound>;223- /** Every ref, as `ls-remote` lists them, custom refs included. */186 readonly refs: (187 name: RepoName188 ) => Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound>;189 /**228- * Every `refs/tags/*`, each peeled to the commit it names: an annotated229- * tag's ref names a tag object, which `readCommit` cannot read.230- * `refs` keeps what git lists.190+ * Each tag peeled to its commit: an annotated tag's ref names a tag191+ * object, which `readCommit` cannot read.192 */193 readonly tags: (194 name: RepoName195 ) => Effect.Effect<readonly Tag[], RepoNotFound>;4 unmodified lines200 ) => Effect.Effect<readonly RefOutcome[], RepoNotFound | HostBusy>;201 }202 >()("artifacts/RepoHost") {}203 243-/**244- * What the reads of one session may share: a host keeps what it opens on a245- * repo (the binding's handle) under `key` until the session ends, rather246- * than opening and closing it for each read. One opening at a time, and247- * only a finished value is kept, so no read waits on another's opening248- * past its own session.249- */204 export interface RepoSessionApi {205 readonly hold: <A, E>(206 key: string,207 open: Effect.Effect<A, E, Scope.Scope>208 ) => Effect.Effect<A, E>;209 }210 211 /**258- * The session reads run in, if any. A `Context.Reference` whose default is259- * none, so each read opens and closes what it needs, as a host without a260- * session does. It lives in one request's context, never in an isolate's261- * state: a Worker whose client goes away is cancelled where it stands, so262- * nothing a request holds may outlive it.212+ * Lives in one request's context, never in isolate state: a Worker whose213+ * client goes away is cancelled where it stands, so nothing may outlive it.214 */215 export const RepoSession = Context.Reference<Option.Option<RepoSessionApi>>(216 "artifacts/RepoSession",217 { defaultValue: Option.none }218 );219 269-/**270- * `effect` with its reads in one session: what a host holds for them is271- * released when `effect` ends, whatever it came to. Inside a session272- * already, `effect` joins it, so a view whose parts each ask for a273- * session still reads over one handle.274- */220 export const inRepoSession = <A, E, R>(221 effect: Effect.Effect<A, E, R>222 ): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>223 Effect.scoped(36 unmodified linesmodified:packages/artifacts/test/binding-live.test.ts+4 added-19 removed
1 /**2- * The binding against live Artifacts. Opt-in, never in `verify`: it runs only3- * with `LIVE_ARTIFACTS=1` and `LIVE_ARTIFACTS_HARNESS` naming, by absolute4- * path, a harness module outside this repo (live-harness code lives5- * outside it). The harness exports `live()`, which resolves to2+ * Opt-in, never in `verify`: runs only with `LIVE_ARTIFACTS=1` and3+ * `LIVE_ARTIFACTS_HARNESS` naming, by absolute path, a harness module outside4+ * this repo. The harness exports `live()`, which resolves to5 *6 * ```ts7 * {8 * namespace: string; // a namespace this build made1 unmodified line10 * fetch: (request: Request) => Promise<Response>;11 * dispose: () => Promise<void>; // the proxy's12 * }13 * ```15- *16- * Every repo name gets a fresh prefix per test, since the contract suite uses17- * fixed names, and every repo a test made is deleted when it ends. It never18- * runs against the `witness` namespace.14 */15 import { describe } from "@effect/vitest";16 import { Data, Effect, FiberSet, Layer, Predicate, Schema } from "effect";17 18 import { Fetch, FetchFailed } from "../src/fetch.ts";19 import { RepoHostBinding } from "../src/repo-host/binding.ts";20 import { describeRepoHost } from "./repo-host-contract.ts";21 27-/** The namespace another project owns. */22 const FORBIDDEN = "witness";23 24 const harnessPath = process.env.LIVE_ARTIFACTS_HARNESS;25 14 unmodified lines40 (input): input is (request: Request) => Promise<Response> =>41 Predicate.isFunction(input)42 );43 50-/** What the harness's module exports. */44 const HarnessModule = Schema.Struct({ live: Start });45 53-/** What `live()` resolves to. */46 const Harness = Schema.Struct({47 binding: Schema.declare(48 (input): input is Artifacts =>49 Predicate.hasProperty(input, "get") && Predicate.isFunction(input.get)16 unmodified lines66 class HarnessFailed extends Data.TaggedError("HarnessFailed")<{67 readonly reason: string;68 }> {}69 78-/** The harness's `live()`, run once per test and disposed after it. */70 const harness = (path: string) =>71 Effect.acquireRelease(72 Effect.gen(function* () {73 const module = yield* Effect.tryPromise({8 unmodified lines82 }).pipe(Effect.orDie),83 ({ dispose }) => Effect.tryPromise(() => dispose()).pipe(Effect.ignore)84 );85 95-/** A fresh prefix: the suite's fixed names, unique to this test. */86 const freshPrefix = () =>87 `live-${crypto88 .getRandomValues(new Uint32Array(2))89 .reduce((text, word) => text + word.toString(36), "")}-`;90 101-/**102- * The live binding with every name prefixed, and every repo made through it103- * deleted when the scope closes. Each method is forwarded by name: a binding104- * and its handles are RPC stubs, whose methods a spread would not copy.105- */91+/** Each method is forwarded by name: RPC stubs' methods are not copied by a spread. */92 const prefixed = (binding: Artifacts) =>93 Effect.gen(function* () {94 const prefix = freshPrefix();95 const run = yield* FiberSet.makeRuntimePromise();44 unmodified lines140 list: (options) => binding.list(options),141 } satisfies Artifacts;142 });143 158-/** The live store's `Fetch`: the harness's fetch, failing as no response. */144 const fetchOver = (send: Harness["fetch"]) =>145 Fetch.of({146 fetch: (request) =>147 Effect.tryPromise({25 unmodified linesmodified:packages/artifacts/test/binding.test.ts+3 added-28 removed
49 unmodified lines50 const main = RefName.make("refs/heads/main");51 52 const landed = RefName.make("refs/asked/landed");53 54-/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */54 const remoteBase = "https://artifacts.test/git/projects";55 57-/** A packet-line holding one side-band 3 (fatal) message. */56 const fatal = (message: string) => {57 const payload = new TextEncoder().encode(`\u0003${message}`);58 const length = (payload.length + 4).toString(16).padStart(4, "0");59 60 return new Uint8Array([...new TextEncoder().encode(length), ...payload]);61 };62 65-/** Artifacts' whole reply to a push it is too busy for: no report, no flush. */63 const busyReply = () =>64 new Response(fatal("artifacts_git_receive_pack_busy\n"), {65 headers: { "content-type": "application/x-git-receive-pack-result" },66 });67 71-/** What one request to the store carried, as the test's `Fetch` saw it. */68 interface Seen {69 readonly url: string;70 readonly authorization: string | null;71 }72 77-/** What a test may do to the next receive-pack call before git sees it. */73 type Intercept = (request: Request) => Effect.Effect<Option.Option<Response>>;74 80-/**81- * The binding over a fake Artifacts on local disk: a `RepoHostLocal` in a82- * temporary directory, wrapped by testkit's fake binding, whose remotes a83- * `Fetch` serves with real `git http-backend` over the same directory.84- * Every handle the binding opens is counted, and every token it mints is85- * recorded, so a test can check both came back.86- */75 const world = (76 options: FakeOptions & {77 readonly wrap?: (host: HostLike) => HostLike;90- /** How many of the first `get`s answer that the repo is still being made, and how. */78 readonly making?: {79 readonly code: "CREATE_IN_PROGRESS" | "IMPORT_IN_PROGRESS";80 readonly gets: number;81 };124 unmodified lines206 });207 208 type World = Effect.Success<ReturnType<typeof world>>;209 223-/** A test body over a fresh world, with the binding's `RepoHost` in scope. */210 const within = <A, E>(211 body: (212 world: World213 ) => Effect.Effect<19 unmodified lines233 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),234 }235 );236 251-/** A repo `name` with one commit on `main`, and the client that made it. */237 const seeded = (name: RepoName) =>238 Effect.gen(function* () {239 const repos = yield* RepoHost;240 const client = yield* gitClient(memoryFs());102 unmodified lines343 }344 )345 );346 362- // One side-band 3 packet and no report.347 it.live("reads a busy receive-pack as HostBusy, and moves nothing", () =>348 within(({ intercept }) =>349 Effect.gen(function* () {350 const repos = yield* RepoHost;25 unmodified lines376 })377 )378 );379 396- // git's receive-pack checks the old value the push names.380 it.live(381 "reports a ref that moved during the push as Stale at its new tip",382 () =>383 within(({ intercept, store }) =>100 unmodified lines484 })485 )486 );487 505- // Artifacts' `readTree` throws `INTERNAL_ERROR` for an object that is no506- // tree; the other stores read no tree there.488 it.live("reads no tree at a blob's id or a commit's id", () =>489 within(490 () =>491 Effect.gen(function* () {159 unmodified lines651 ({ plaintext }) => authorization === `Bearer ${plaintext}`652 )653 )654 ).toBeTruthy();674- // Revoked already: a second revoke finds nothing.655 expect(revoked.every((again) => !again)).toBeTruthy();656 })657 )658 );159 unmodified lines818 );819 });820 821 /**842- * `effect` run to its end on the TestClock: the clock moves on by the843- * longest sleep the binding takes between asks while the effect runs, so844- * a wait of minutes passes at once, whatever real I/O it does between.822+ * Runs `effect` on the TestClock, moving the clock by the binding's longest823+ * sleep while it runs, so a wait of minutes passes at once.824 */825 const onTestClock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>826 Effect.gen(function* () {827 const fiber = yield* Effect.forkChild(effect);5 unmodified lines833 834 return yield* Fiber.await(fiber);835 });836 858-/** How many tokens on `name` are still live, as the fake lists them. */837 const liveTokens = (fake: Artifacts, name: RepoName) =>838 Effect.acquireUseRelease(839 Effect.promise(() => fake.get(name)),840 (repo) =>11 unmodified lines852 853 describe("an import Artifacts is still copying", () => {854 const master = RefName.make("refs/heads/master");855 878- // A remote whose default branch is `master`, as anyhow's is: its HEAD879- // names `master`, and the import takes that branch under its own name.856 it.live(857 "imports a remote whose default branch is master without being told",858 () =>859 within(31 unmodified lines891 { defaultBranch: "master" }892 )893 );894 919- // Seven asks (about 32 s) were too few for a large import; the binding920- // now asks for about three minutes, so twelve busy answers pass.895+ // An import may be asked about for three minutes, so twelve busy answers pass.896 it.effect(897 "waits through twelve IMPORT_IN_PROGRESS answers, then revokes the import's token and reads it",898 () =>899 within(179 unmodified linesmodified:packages/artifacts/test/fake-rest.ts+4 added-60 removed
1 /**2- * An in-process fake of the Artifacts REST API over a `RepoHost` (in tests,3- * `RepoHostLocal`), for `/rest`'s tests. It serves the routes4- * `src/repo-host/rest.ts` lists, under5- * `<base>/accounts/<accountId>/artifacts/namespaces/<namespace>`, and answers6- * in Cloudflare's v4 envelope, `{success, errors: [{code, message}],7- * messages, result}`. A repo's `remote` is the host's, for a git server the8- * test runs there (`@repo/testkit/http-backend`).9- *10- * It keeps what Artifacts' REST docs and the probes say of the real API:11- *12- * - only `Authorization: Bearer <api token>` authenticates; anything else is13- * 401 (Cloudflare's code 10000);14- * - errors carry Artifacts' numeric codes (its errors page): 10200 not15- * found, 10201 already exists, 10303 fork in progress, 10100 invalid16- * input, 10103 invalid ttl, 10104 invalid url, 10400 internal;17- * - a fork names its target in the body, `{name, default_branch_only}`, a18- * field cf's schema lacks (cf #180); a body without `name` is refused;19- * - create, fork and import answer with the new repo's `remote` and a20- * day-long write token; a token's mint answers `{id, plaintext,21- * scope, expires_at}`; a delete answers 202;22- * - under load, a fork answers HTTP 500 with code 10400 after making the23- * repo, and a retry answers 409 with code 10201:24- * `{ forkFailures: n }`; `{ forkLost: true }` makes those forks make25- * nothing;26- * - revoking a token within about a second of its mint can be 404 (cf's27- * help for `tokens revoke`): `{ revokeLag: n }` makes the first `n`28- * revocations of each token 404;29- * - blobs and files are raw bytes; every other reply is JSON.30- *31- * And, as ASSUMPTIONs nobody has seen live, what the docs leave out:32- *33- * - commit metadata is the binding's, in snake case (`tree_hash`) as the34- * API's other fields are, or in camel case: `{ casing: "camel" }`;35- * - a tree or a log is the binding's list, as the envelope's `result`;36- * - a tree or a commit read at an object of another kind is 500 (10400), as37- * the binding throws `INTERNAL_ERROR` there;38- * - a ref is a short branch name or a commit id, as the binding's,39- * and a log at a ref that names nothing is 404.2+ * An in-process fake of the Artifacts REST API over a `RepoHost`. It keeps3+ * what Artifacts' REST docs and probes say of the real API; what the docs4+ * leave out (commit field casing, a wrong-kind read as 500, a log at a ref5+ * that names nothing as 404) is an ASSUMPTION nobody has seen live.6 */7 import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";8 import {9 Data,21 unmodified lines31 32 export interface FakeRestOptions {33 readonly accountId: string;34 readonly namespace: string;69- /** The API token it takes, as a bearer token. */35 readonly token: string;71- /** Defaults to `https://api.cloudflare.com/client/v4`. */36 readonly base?: string;73- /** How many fork calls answer 500 (code 10400), as under load. */37 readonly forkFailures?: number;75- /** Whether those forks make nothing; by default each makes the repo first. */38 readonly forkLost?: boolean;77- /** How commit metadata spells its fields; snake case by default. */39 readonly casing?: "camel" | "snake";79- /** How many revocations of each token answer 404 before one takes. */40 readonly revokeLag?: number;41 }42 83-/** Artifacts' error codes, from its errors page. */43 const Codes = {44 alreadyExists: 10_201,45 forkInProgress: 10_303,46 internal: 10_400,2 unmodified lines49 invalidUrl: 10_104,50 notFound: 10_200,51 } as const;52 94-/** Cloudflare's own codes for a bad API token and an unknown route. */53 const UNAUTHENTICATED = 10_000;54 55 const NO_ROUTE = 7000;56 21 unmodified lines78 79 const internal = () =>80 failed(500, Codes.internal, "An internal error occurred.");81 124-/** A reply decided before the host was asked: a refusal of the request itself. */82 class Answered extends Data.TaggedError("Answered")<{83 readonly response: Response;84 }> {}85 86 const invalid = (code: number, message: string) =>87 new Answered({ response: failed(400, code, message) });88 132-/** What a route's handler fails with: the host's errors, or a reply. */89 type Failure =90 | Answered91 | ForkInProgress92 | ImportRefused28 unmodified lines121 const decodeBranch = Schema.decodeUnknownOption(BranchName);122 123 const decodePath = Schema.decodeUnknownOption(RepoPath);124 169-/** A request's JSON body, decoded, or a 400. */125 const bodyOf = <A>(request: Request, codec: Schema.Codec<A, string>) =>126 Effect.promise(() => request.text()).pipe(127 Effect.flatMap(Schema.decodeEffect(codec)),128 Effect.mapError(() => invalid(Codes.invalidInput, "invalid request body"))10 unmodified lines139 Effect.fromOption(decodeObject(id)).pipe(140 Effect.mapError(() => invalid(Codes.invalidInput, `invalid hash: ${id}`))141 );142 188-/** A short branch name or a commit id; anything else names nothing. */143 const revisionOf = (ref: string): Option.Option<Revision> =>144 Option.match(decodeObject(ref), {145 onNone: () =>146 Option.map(decodeBranch(ref), (name) => Revision.Branch({ name })),14 unmodified lines161 Match.orElse(() => "blob")162 ),163 });164 211-/** Whether the repo holds `id` as an object of any kind. */165 const holds = (host: RepoHost["Service"], name: RepoName, id: ObjectId) =>166 Effect.all([167 host.readBlob(name, id),168 host.readTree(name, id),4 unmodified lines173 Option.isSome(blob) || Option.isSome(tree) || Option.isSome(commit)174 )175 );176 224-/** A repo's info, as `GET /repos/{name}` gives it. */177 const infoOf = (name: RepoName, remote: string) =>178 ok({179 created_at: "2026-10-07T00:00:00.000Z",180 default_branch: "main",6 unmodified lines187 source: null,188 updated_at: "2026-10-07T00:00:00.000Z",189 });190 239-/** Whose a token is, and how many more revocations of it miss. */191 interface Minted {192 readonly repo: RepoName;193 readonly misses: number;194 }195 245-/** A route's path parameters, the request, and its URL. */196 interface Call {197 readonly name: string;198 readonly id: string;199 readonly request: Request;1 unmodified line201 }202 203 type Handler = (call: Call) => Effect.Effect<Response, Failure>;204 255-/** The fake API over `host`: a handler for the test's `Fetch` to route to. */205 export const fakeRest = (206 host: RepoHost["Service"],207 options: FakeRestOptions208 ): Effect.Effect<(request: Request) => Effect.Effect<Response>> =>2 unmodified lines211 const prefix = `${apiBase}/accounts/${options.accountId}/artifacts/namespaces/${options.namespace}`;212 const forkFailures = yield* Ref.make(options.forkFailures ?? 0);213 const tokens = yield* Ref.make<ReadonlyMap<string, Minted>>(new Map());214 266- // The times the host read from the commit itself.215 const metadataOf = (commit: Commit) => {216 const fields = {217 author: commit.author,218 committer: commit.committer,36 unmodified lines255 scope,256 };257 });258 311- /** A new repo's reply, with its day-long write token. */259 const made = (name: RepoName, remote: string) =>260 mint(name, "write", DAY_SECONDS).pipe(261 Effect.map(({ plaintext }) => ({262 default_branch: "main",64 unmodified lines327 328 return ok(yield* made(name, remote));329 });330 384- /** A commit or a tree; another kind of object at the id is a 500. */331 const object =332 <A>(333 read: (334 name: RepoName,33 unmodified lines368 onSome: raw,369 });370 });371 426- /** A file at a ref that is a short branch name or a commit id. */372 const file: Handler = (call) =>373 Effect.gen(function* () {374 const name = yield* repoNamed(call.name);375 const at = revisionOf(call.url.searchParams.get("ref") ?? "");83 unmodified lines459 ["POST", /^\/tokens$/u, token],460 ["DELETE", /^\/tokens\/(?<id>[^/]+)$/u, revoke],461 ];462 518- /** The handler for a request, and the call it is given. */463 const routed = (request: Request) => {464 const url = new URL(request.url);465 const path = `${url.origin}${url.pathname}`;466 57 unmodified linesmodified:packages/artifacts/test/local.test.ts+1 added-7 removed
20 unmodified lines21 import { temporaryRoot } from "./temporary-root.ts";22 23 const main = RefName.make("refs/heads/main");24 25-/** No network: every request fails as an unreachable host's would. */25 const offline = Layer.succeed(26 Fetch,27 Fetch.of({28 fetch: (request) =>29 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),30 })31 );32 34-/** The store in `root`, whose remotes are its repos' own `file://` URLs. */33 const storeAt = (root: string) =>34 RepoHostLocal.layer({ remoteBase: `file://${root}`, root }).pipe(35 Layer.provide(offline)36 );37 40-/** A store in a new temporary directory, removed when the test ends. */38 const freshStore = Layer.unwrap(Effect.map(temporaryRoot, storeAt));39 43-/** Real `git http-backend` over `root` on a local port: its base URL. */40 const served = (root: string) =>41 Effect.gen(function* () {42 const spawner =43 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();29 unmodified lines73 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),74 });75 76 describe("bare repos on local disk", () => {81- // The issue's Check: what the adapter stores is a repo real git can clone82- // over smart HTTP, served by `git http-backend` from the same root.77+ // What the adapter stores is a repo real git can clone over smart HTTP.78 it.live(79 "serves a pushed file to a real git clone of its remote",80 () =>81 Effect.gen(function* () {139 unmodified lines221 expect(yield* repos.remove(name)).toBeFalsy();222 }).pipe(Effect.provide(freshStore))223 );224 230- // A file URL that names another machine is no path on this one.225 it.effect("refuses a file URL on another host, and makes no repo", () =>226 Effect.gen(function* () {227 const repos = yield* RepoHost;228 const name = RepoName.make("elsewhere");58 unmodified linesmodified:packages/artifacts/test/repo-host-contract.ts+1 added-22 removed
27 unmodified lines28 const path = RepoPath.make("src/a.ts");29 30 const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);31 32-/** No object in any repo here has this id. */32 const absent = ObjectId.make("0".repeat(40));33 35-/** When a commit was written, and when committed: two different instants. */34 const authored = 1_700_000_000;35 36 const committed = 1_700_000_500;37 40-/** The test client's repo, which a push takes objects from. */38 type Source = Parameters<RepoHost["Service"]["push"]>[1];39 43-/**44- * A commit on `parent`'s tree written by hand, so its author and committer45- * times differ (the test client stamps both alike).46- */40+/** Written by hand, so its author and committer times differ (the test client stamps both alike). */41 const timedCommit = (source: Source, parent: CommitSha) =>42 Effect.gen(function* () {43 const { commit } = yield* Effect.promise(() =>44 readCommit({ ...source, oid: parent })24 unmodified lines69 70 return CommitSha.make(oid);71 });72 79-/** When a commit was written and committed, as a store read it. */73 const times = (commit: Commit) => ({74 authoredAt: commit.authoredAt,75 committedAt: commit.committedAt,76 });77 85-/** An annotated tag object naming `commit`; its id, as a push sends it. */78 const annotatedTag = (source: Source, name: string, commit: CommitSha) =>79 Effect.map(80 Effect.promise(() =>81 writeTag({15 unmodified lines97 // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.98 (oid) => CommitSha.make(oid)99 );100 109-/** What an adapter's run of the suite adds to the shared cases. */101 export interface RepoHostSuite {111- /**112- * The URL `importFrom` reads the repo `name` from, as this adapter's113- * stand-in for a public remote. Without one, the import cases don't run.114- */102 readonly importUrl?: (103 name: RepoName104 ) => Effect.Effect<string, never, RepoHost>;105 /**4 unmodified lines110 */111 readonly danglingHead?: boolean;112 }113 127-/**128- * What every RepoHost adapter must do, written against the port. `/memory`,129- * `/local`, `/binding` (over testkit's fake Artifacts on `/local`) and130- * `/rest` (over a fake REST API on `/local`) run it on every `verify`;131- * `binding-live.test.ts` runs it against live Artifacts when asked.132- */114 export const describeRepoHost = (115 adapter: string,116 host: Layer.Layer<RepoHost>,117 suite: RepoHostSuite = {}435 unmodified lines553 ]);554 }).pipe(Effect.provide(host))555 );556 576- // A fork shares what it inherited and nothing a sibling577- // adds later.557 it.effect("keeps each fork's own commits to itself", () =>558 Effect.gen(function* () {559 const repos = yield* RepoHost;560 const client = yield* gitClient(memoryFs());130 unmodified linesmodified:packages/artifacts/test/rest.test.ts-18 removed
46 unmodified lines47 const namespace = "projects-test";48 49 const api = `https://api.cloudflare.com/client/v4/accounts/${accountId}/artifacts/namespaces/${namespace}`;50 51-/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */51 const remoteBase = `https://${accountId}.artifacts.test/git/${namespace}`;52 53 const apiToken = "cf-api-token-for-the-rest-tests";54 56-/** One request as the test's `Fetch` saw it, with its reply. */55 interface Seen {56 readonly method: string;57 readonly url: string;58 readonly headers: readonly (readonly [string, string])[];8 unmodified lines67 );68 69 const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));70 73-/** What a token's mint answered, as far as these tests read it. */71 const decodeMinted = Schema.decodeEffect(72 Schema.fromJsonString(73 Schema.Struct({74 result: Schema.Struct({ id: Schema.String, plaintext: Schema.String }),75 })76 )77 );78 82-/**83- * The REST adapter over a fake API on local disk: a `RepoHostLocal` in a84- * temporary directory, behind `fakeRest`, with its remotes served by real85- * `git http-backend` over the same directory. Every request and reply the86- * adapter's `Fetch` carries is recorded.87- */79 const world = (80 options: Omit<FakeRestOptions, "accountId" | "namespace" | "token"> = {}81 ) =>82 Effect.gen(function* () {72 unmodified lines155 });156 157 type World = Effect.Success<ReturnType<typeof world>>;158 168-/** The REST adapter over a `Fetch` that gives every request the same reply. */159 const answering = (reply: () => Response) =>160 RepoHostRest.layer({161 accountId,162 namespace,3 unmodified lines166 Layer.succeed(Fetch, Fetch.of({ fetch: () => Effect.sync(reply) }))167 )168 );169 180-/** A refusal in Cloudflare's v4 envelope. */170 const refused = (status: number, code: number, message: string) => () =>171 Response.json(172 { errors: [{ code, message }], messages: [], result: null, success: false },173 { status }174 );175 187-/** A test body over a fresh world, with the REST adapter's `RepoHost` in scope. */176 const within = <A, E>(177 body: (178 world: World179 ) => Effect.Effect<19 unmodified lines199 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),200 }201 );202 215-/** A repo `name` with one commit on `main`, and the client that made it. */203 const seeded = (name: RepoName) =>204 Effect.gen(function* () {205 const repos = yield* RepoHost;206 const client = yield* gitClient(memoryFs());8 unmodified lines215 216 return { client, first };217 });218 232-/** The requests to one REST route, by method and path under the namespace. */219 const requestsTo = (220 seen: Ref.Ref<readonly Seen[]>,221 method: string,222 path: string6 unmodified lines229 )230 )231 );232 247-/** A commit's tree, read from the client that wrote it. */233 const treeOf = (source: PushSource, oid: CommitSha) =>234 Effect.promise(() => readCommit({ ...source, oid })).pipe(235 Effect.map(({ commit }) => ObjectId.make(commit.tree))236 );421 unmodified lines658 { casing }659 )660 );661 677- // The binding throws `INTERNAL_ERROR` for a read of the wrong kind; the678- // fake's REST API answers 500 there (an ASSUMPTION), and the other stores679- // read no tree.662 it.live("reads no tree at a blob's id or a commit's id", () =>663 within(() =>664 Effect.gen(function* () {665 const repos = yield* RepoHost;17 unmodified linesmodified:packages/artifacts/test/revision.test.ts-1 removed
2 unmodified lines3 import { Schema } from "effect";4 5 import { BranchName, RepoName } from "../src/repo-host.ts";6 7-// One `RepoName` across the product: the port names repos with the domain's.7 describe("a repo name", () => {8 it("is the domain's RepoName", () => {9 expect(RepoName).toBe(Ids.RepoName);10 });16 unmodified linesmodified:packages/artifacts/test/temporary-root.ts-4 removed
1 import { NodeServices } from "@effect/platform-node";2 import { Effect, FileSystem } from "effect";3 4-/**5- * A new temporary directory for a store's root, removed with its contents6- * when the test's scope closes.7- */4 export const temporaryRoot = FileSystem.FileSystem.pipe(5 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "repo-host-" })),6 Effect.orDie,7 Effect.provide(NodeServices.layer)1 unmodified linemodified:packages/brand/src/index.ts-5 removed
1-/**2- * The product's name and every identifier made from it. Nothing outside this3- * package spells the name; `brand:check` holds that, and the acceptance script4- * renames the slug at random to prove it.5- */1 const slug = "myr";2 3 export const Brand = {4 cli: slug,12 unmodified linesmodified:packages/brand/src/leaks.ts-2 removed
5 unmodified lines6 }7 8 export interface BrandLeak {9 readonly path: string;10- /** 1-based; 0 when the path itself carries the name. */10 readonly line: number;11 readonly text: string;12 }13 46 unmodified lines60 61 return [...inPath, ...inContent];62 };63 65-/** Every place outside the brand package and prose that spells the name. */64 export const findLeaks = (files: Iterable<SourceFile>): readonly BrandLeak[] =>65 [...files].flatMap(leaksIn);modified:packages/brand/test/leaks.test.ts-2 removed
53 unmodified lines54 ])55 ).toStrictEqual([]);56 });57 58- // Nothing in the repo is written from the brand any more, so no folder59- // outside the brand package and prose may spell it.58 it("flags the name in a plugin's or a skill's JSON like any other file", () => {59 const content = `${Brand.cli} asks`;60 61 expect(86 unmodified linesmodified:packages/config/src/vitest.ts-1 removed
1 import { defineConfig } from "vitest/config";2 3-/** The one vitest setup every package uses: tests live in `test/`, run in Node. */3 export const preset = defineConfig({4 test: {5 include: ["test/**/*.test.ts"],6 },1 unmodified linemodified:packages/config/test/bootstrap.test.ts-7 removed
23 unmodified lines24 import { blankJsonc } from "../../../infra/jsonc.ts";25 import { resources, stages } from "../../../infra/stages.ts";26 import { repoRoot } from "./root.ts";27 28-/** A file under the repo root, as text. */28 const rootText = (file: string) =>29 Effect.gen(function* () {30 const fs = yield* FileSystem.FileSystem;31 const path = yield* Path.Path;32 33 return yield* fs.readFileString(path.join(yield* repoRoot, file));34 }).pipe(Effect.provide(NodeServices.layer));35 37-/** What this test reads of a stage's block in the platform's `wrangler.jsonc`. */36 const PlatformStage = Schema.Struct({37 artifacts: Schema.Array(38 Schema.Struct({ binding: Schema.String, namespace: Schema.String })39 ),27 unmodified lines67 name: Schema.String,68 })69 );70 73-/** `apps/<app>/wrangler.jsonc`, comments and trailing commas aside, decoded. */71 const wrangler = <S extends Schema.Top & { readonly DecodingServices: never }>(72 app: string,73 stage: S74 ) =>3 unmodified lines78 );79 80 const nothing: Existing = { d1: [], kv: [], namespaces: [], r2: [] };81 85-/** Every resource of `dev-oscabriel` and `demo` present, with ids. */82 const everything: Existing = {83 d1: [84 {85 id: "11111111-1111-4111-8111-111111111111",30 unmodified lines116 117 expect(platform.name).toBe("platform");118 expect(Object.keys(platform.env)).toStrictEqual([...stages]);119 124- // Each block as the table names it, and as wrangler.jsonc does.120 const named = stages.map((stage) => {121 const names = resources(stage);122 123 return {124 frontPage: names.frontPage,130- // The public namespace, then the private one the layers live in.125 namespaces: [names.projects, names.layers],126 onPush: [names.onPush, names.onPush],127 platform: names.platform,128 projects: [names.projects, names.projects],115 unmodified lines244 ]);245 });246 });247 254-/** The lines of `after` that differ from `before`'s, by line. */248 const changed = (before: string, after: string) => {249 const old = before.split("\n");250 251 return after329 unmodified linesmodified:packages/config/test/cartridge.test.ts+12 added-88 removed
1 /**2- * The visibility cartridge, read as data (README's cut line 5): its3- * paths exist, one marked line plugs it in, and nothing outside it reaches4- * into it, so removing it is a deletion. The cartridge is its manifest's5- * folders, the marked composition line (the line under the marker6- * comment, which goes with it), the two `@repo/visibility` dependency lines7- * and the `ARTIFACTS_PRIVATE` binding; everything else8- * depends only on the neutral ports (`@repo/project`'s `visibility-port.ts`9- * and `env-port.ts`, the platform's `layer-gate.ts`), whose defaults are10- * the platform without it.11- *12- * Imports are read from the source with comments and the insides of13- * strings, regexes and templates blanked, so an import spelled in a comment14- * or a string never counts, and every form does: static, `import type`,15- * re-exports and `import()`.2+ * The visibility cartridge is its manifest's folders, the marked composition3+ * line, the two `@repo/visibility` dependency lines and the4+ * `ARTIFACTS_PRIVATE` binding; everything else depends only on the neutral5+ * ports, whose defaults are the platform without it. Imports are read with6+ * comments and the insides of strings, regexes and templates blanked.7 */8 import { NodeServices } from "@effect/platform-node";9 import { describe, expect, it } from "@effect/vitest";10 import { Array, Effect, FileSystem, Option, Path, Schema } from "effect";11 import type { ChildProcessSpawner } from "effect/process";12 13 import { committable, readsAtOnce, repoRoot, textOf } from "./root.ts";14 24-/** The cartridge's folders, from the repo root; each ends with `/`, and each exists. */15 const MANIFEST = [16 "packages/visibility/",17 "packages/project/src/visibility/",18 "apps/platform/src/visibility/",19 "apps/platform/test/visibility/",20 ] as const;21 32-/**33- * Where tests of the cartridge's project side live: they go with it, so34- * they are its too, though none may be written yet.35- */22 const TEST_HOMES = ["packages/project/test/visibility/"] as const;23 38-/**39- * Tests outside its folders that run the cartridge's world as a process,40- * by its path rather than an import (the CLI's end-to-end `env set`:41- * apps never import apps), so no import reader sees them: they go42- * with it too.43- */24 const RUNS_ITS_WORLD = [25 "apps/cli/test/local/env-set-live.test.ts",46- // The seed's layer step, over the world the cartridge plugs into.26 "packages/config/test/seed-layer.test.ts",27 ] as const;28 50-/**51- * The examples' content that only a platform with the cartridge can seed:52- * datekit's maintainers layer. Without it the seed plans no layer.53- */29 const ITS_CONTENT = ["examples/datekit/layers/"] as const;30 31 /**57- * Every folder, and every file, that goes when the cartridge goes. Deleting58- * it also takes the lines that name it (deleting it in a scratch worktree59- * left verify green): the marked line in `cartridges.ts`; the two32+ * Every folder and file that goes when the cartridge goes. Deleting it also33+ * takes the lines that name it: the marked line in `cartridges.ts`; the two34 * `@repo/visibility` dependency lines; `ARTIFACTS_PRIVATE` and `MASTER_KEY`35 * in the platform's `wrangler.jsonc`, `.env.schema` and `platform.ts`, its62- * tests' fake env (`withPrivateNamespace` and its imports, and its use in63- * `serve-world.ts`), `bindings.test.ts`, `platform.test.ts` and64- * `env.test-d.ts`, then `bun run types`; the private namespace and65- * `MASTER_KEY` rows in `bootstrap.test.ts`; and datekit's three `Layer`66- * lines in `seed.test.ts`. Bootstrap still plans the stage's `layers-<s>`67- * namespace (`infra/stages.ts`), which nothing binds then.36+ * tests' fake env (`withPrivateNamespace` and its uses), `bindings.test.ts`,37+ * `platform.test.ts` and `env.test-d.ts`, then `bun run types`; the private38+ * namespace and `MASTER_KEY` rows in `bootstrap.test.ts`; and datekit's three39+ * `Layer` lines in `seed.test.ts`.40 */41 const CARTRIDGE = [42 ...MANIFEST,43 ...TEST_HOMES,44 ...RUNS_ITS_WORLD,45 ...ITS_CONTENT,46 ];47 76-/**77- * Where the line that plugs the cartridge in lives (`ports.ts` merges every78- * cartridge `cartridges.ts` names over the platform's ports), and the one79- * module it names.80- */48 const COMPOSITION = {49 file: "apps/platform/src/cartridges.ts",50 module: "./visibility/live.ts",51 };2 unmodified lines54 const MARKER = ["//", "cartridge:", "visibility"].join(" ");55 56 const PACKAGE = "@repo/visibility";57 91-/** The workspaces that depend on the package: the cartridge's implementations live in them. */58 const DEPENDENTS = [59 "apps/platform/package.json",60 "packages/project/package.json",61 ];62 97-/** The private namespace's binding, by its name, spelled so a search for it finds the allowed files below. */63+/** Spelled so a search for the binding's name finds only the allowed files below. */64 const BINDING = ["ARTIFACTS", "PRIVATE"].join("_");65 100-/**101- * The files outside the cartridge that may name the binding: the platform's102- * config, generated types and env decode, its tests' fake env and type103- * fences, principle 7's web fence, and these tests.104- */66 const NAMES_BINDING = new Set([67 "apps/platform/wrangler.jsonc",68 "apps/platform/worker-configuration.d.ts",69 "apps/platform/src/platform.ts",5 unmodified lines75 "packages/config/test/web-wiring.test.ts",76 "packages/config/test/cartridge.test.ts",77 ]);78 118-/** Prose and binary files: they wire nothing. */79 const NOT_WIRING = /\.(?:md|png|ico|svg|woff2?|ttf|otf|jpg|webp|gif|lockb)$/u;80 81 const isCartridge = (file: string) =>82 CARTRIDGE.some((folder) => file.startsWith(folder));83 84 const isSource = (file: string) => /\.tsx?$/u.test(file);85 126-// ------------------------------------------------------------ the repo127-128-/** Every committable file with its text, `filter` deciding which. */86 const filesWhere = (filter: (file: string) => boolean) =>87 Effect.flatMap(committable, (files) =>88 Effect.forEach(89 files.filter(filter),4 unmodified lines94 readsAtOnce95 )96 ).pipe(Effect.map(Array.getSomes));97 141-// --------------------------------------------------------- reading code142-143-/** Punctuation after which a `/` starts a regex rather than a division. */98 const BEFORE_REGEX = new Set("(,=:[!&|?{};+-*%<>~^");99 100 const KEYWORDS_BEFORE_REGEX = new Set([101 "await",15 unmodified lines117 const WORD = /[\w$]/u;118 119 const SPACE = /\s/u;120 167-/**168- * One pass over a file's source: `chars` ends with comments and the insides169- * of strings, regexes and templates blanked, keeping every offset.170- */121 interface Lexer {122 readonly chars: string[];123 readonly content: string;174- /** The brace depth outside each enclosing template's `${`, innermost last. */124 readonly outer: number[];176- /** Each string literal's contents, by the offset of its opening quote. */125 readonly strings: Map<number, string>;126 at: number;127 depth: number;128 inTemplate: boolean;181- /** The last code token read: a punctuation character or a word. */129 previous: string;130 }131 185-/** Blanks `[from, to)`, keeping line breaks. */132 const blank = (lexer: Lexer, from: number, to: number) => {133 for (let at = from; at < Math.min(to, lexer.chars.length); at += 1) {134 if (lexer.chars[at] !== "\n") {135 lexer.chars[at] = " ";136 }137 }138 };139 194-/** The offset of the `/` that closes the regex opening at `start`, or -1 when its line ends first. */140 const regexEnd = (content: string, start: number) => {141 let inClass = false;142 let at = start + 1;143 13 unmodified lines157 158 return -1;159 };160 216-/** A template's text, up to its closing backtick or its next `${`. */161 const templateText = (lexer: Lexer) => {162 const { content } = lexer;163 const start = lexer.at;164 18 unmodified lines183 lexer.at += 1;184 }185 };186 243-/** Each step reads one token of code if it starts at `at`, and says whether it did. */187 type Step = (lexer: Lexer) => boolean;188 189 const comment: Step = (lexer) => {190 const { at, content } = lexer;72 unmodified lines263 264 return true;265 };266 324-/** The `}` that closes a template's `${`. */267 const templateResume: Step = (lexer) => {268 if (269 lexer.content[lexer.at] !== "}" ||270 lexer.depth > 0 ||45 unmodified lines316 word,317 punctuation,318 ];319 378-/**379- * The source with comments, and the insides of strings, regexes and380- * templates, blanked, keeping every offset and line break, so import381- * syntax inside them is never read.382- */320 const mask = (content: string) => {321 const lexer: Lexer = {322 at: 0,323 chars: content.split(""),21 unmodified lines345 // `import "x"`, or a dynamic `import("x")` (`typeof import("x")` too).346 const IMPORT =347 /(?<![.\w$])(?:import|export)[\s{*][^;]*?\bfrom\s*["']|(?<![.\w$])import\s*["']|(?<![.\w$])import\s*\(\s*["']/gu;348 412-/** One import of a file: what it names, and the line it is on (1-based). */349 interface Import {350 readonly line: number;351 readonly specifier: string;352 }353 418-/** Every import, re-export and dynamic import in a file, in source order. */354 const importsOf = (content: string): readonly Import[] => {355 const { code, strings } = mask(content);356 357 return [...code.matchAll(IMPORT)].flatMap((match) => {5 unmodified lines363 : [{ line: content.slice(0, quote).split("\n").length, specifier }];364 });365 };366 432-// ------------------------------------------------------------ resolving433-434-/** `a/b/../c/./d` as `a/c/d`; none when it climbs out of the repo. */367 const normalize = (path: string): Option.Option<string> => {368 const parts: string[] = [];369 370 for (const part of path.split("/")) {28 unmodified lines399 const decodeManifest = Schema.decodeUnknownEffect(400 Schema.fromJsonString(Manifest)401 );402 471-/** A workspace: its folder (with `/`) and its manifest. */403 interface Workspace {404 readonly dir: string;405 readonly manifest: Manifest;406 }407 477-/** Every workspace package in the repo: the `package.json` files under `apps/` and `packages/`. */408 const workspaces = Effect.flatMap(409 filesWhere((file) => /^(?:apps|packages)\/[^/]+\/package\.json$/u.test(file)),410 (files) =>411 Effect.forEach(files, ({ content, file }) =>3 unmodified lines415 }))416 )417 );418 489-/** The file an `exports` subpath names, through a key or one `*` wildcard. */419 const exported = (420 workspace: Workspace,421 subpath: string422 ): Option.Option<string> => {25 unmodified lines448 (file) => normalize(`${workspace.dir}${file}`)449 );450 };451 523-/** The repo path an import reaches: a relative path, or a workspace package's export; none for anything else. */452 const resolved = (453 from: string,454 specifier: string,455 all: readonly Workspace[]11 unmodified lines467 ? Option.none()468 : exported(owner, specifier.slice(owner.manifest.name.length + 1));469 };470 543-/** Whether an import reaches into the cartridge: its package by name, or a path inside it. */471 const reachesCartridge = (472 from: string,473 specifier: string,474 all: readonly Workspace[]12 unmodified lines487 ...manifest.devDependencies,488 ...manifest.peerDependencies,489 });490 564-// ---------------------------------------------------------------- tests565-491 const provided = <A, E>(492 effect: Effect.Effect<493 A,494 E,121 unmodified lines616 617 const reaching = outside.flatMap(({ content, file }) => {618 const lines = content.split("\n");619 695- // `line` is 1-based, so the line above it is `lines[line - 2]`.620 return importsOf(content)621 .filter(622 ({ line, specifier }) =>623 !(lines[line - 2] ?? "").includes(MARKER) &&50 unmodified linesmodified:packages/config/test/created.test.ts-7 removed
1-/**2- * The ledger of throwaway resources: every namespace, repo or3- * project a smoke run, a swarm run or a `seed --as` copy makes on a stage is4- * written to `infra/created.jsonl`, so teardown acts only on what this5- * build made.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { DateTime, Effect, FileSystem, Path } from "effect";4 23 unmodified lines28 name: "swarm-r2",29 stage: "dev-oscabriel",30 };31 38-/** A fresh ledger file in a temp dir, for the scope of one test. */32 const tempLedger = Effect.gen(function* () {33 const fs = yield* FileSystem.FileSystem;34 const path = yield* Path.Path;35 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "ledger-701-" });78 unmodified linesmodified:packages/config/test/deploy.test.ts+2 added-17 removed
21 unmodified lines22 } from "../../../infra/deploy.ts";23 import { LockFile } from "../../../infra/recording.ts";24 import { repoRoot } from "./root.ts";25 26-/** One command the deploy spawned, with its folder relative to the repo root. */26 interface Spawned {27 readonly command: string;28 readonly args: readonly string[];29 readonly cwd: string;30 readonly env: Readonly<Record<string, string | undefined>>;31 }32 34-/**35- * A `ChildProcessSpawner` that runs nothing: it records each command and36- * answers with the exit code `exitOf` gives it.37- */33 const recording = (exitOf: (spawned: Spawned) => number) =>34 Effect.gen(function* () {35 const path = yield* Path.Path;36 const root = yield* repoRoot;35 unmodified lines72 spawned: Ref.get(spawned),73 };74 });75 81-/** `deploy(argv)` over a recording spawner: what it spawned, and how it ended. */76 const run = (77 argv: readonly string[],78 options: {79 readonly exitOf?: (spawned: Spawned) => number;4 unmodified lines84 const fs = yield* FileSystem.FileSystem;85 const path = yield* Path.Path;86 const fake = yield* recording(options.exitOf ?? (() => 0));87 94- // A lock nobody wrote, so a take being recorded on this machine95- // (`infra/.recording`) never decides these tests; recording.test.ts96- // holds the lock itself.88+ // A lock nobody wrote, so a local `infra/.recording` never decides these89+ // tests; recording.test.ts holds the lock itself.90 const unlocked = path.join(91 yield* fs.makeTempDirectoryScoped({ prefix: "deploy-unlocked-" }),92 ".recording"93 );11 unmodified lines105 106 return { result, spawned: yield* fake.spawned };107 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));108 116-/** A spawned command as one line: `apps/sandbox$ wrangler deploy --env x`. */109 const line = ({ args, command, cwd }: Spawned) =>110 `${cwd === "" ? "." : cwd}$ ${[command, ...args].join(" ")}`;111 112 describe("a deploy without a known stage", () => {66 unmodified lines179 Effect.provideService(Console.Console, quiet)180 );181 182 expect(Result.isSuccess(result)).toBeTruthy();191- // infra/workers-dev.json records the account's subdomain.183 expect(printed.at(-1)).toBe(184 "deploy dev-oscabriel: to offer Google sign-in, register https://platform-dev-oscabriel.oscargabriel.workers.dev/oauth/google/callback as the Google client's redirect URI (H4)"185 );186 })50 unmodified lines237 it.live("turns Wrangler's metrics off in every command it spawns", () =>238 Effect.gen(function* () {239 const { spawned } = yield* run(["--stage", "dev-oscabriel"]);240 250- // One per step: verify, sandbox, platform, web build, web, triggers,251- // smoke.241 expect(spawned.map(({ env }) => env.WRANGLER_SEND_METRICS)).toStrictEqual(242 ["false", "false", "false", "false", "false", "false", "false"]243 );244 })108 unmodified lines353 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))354 );355 });356 368-/**369- * The message a failed `deploy(argv)` carries: `runMain` prints a failure as370- * its tag and its message, and nothing else.371- */357 const messageOf = (358 argv: readonly string[],359 options: Parameters<typeof run>[1] = {}360 ) =>90 unmodified linesmodified:packages/config/test/docs-public.test.ts+3 added-33 removed
1-/**2- * The repo's own docs are the public record: AGENTS.md and GLOSSARY.md point3- * at nothing outside the repo, AGENTS.md says what holds today, and the4- * glossary defines the terms the code is written in. No file the repo would5- * commit cites the build's private plan or points into the maintainer's6- * gitignored working docs either, code comments included. File reads and7- * string checks only, beside one `git ls-files`.8- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Array, Effect, FileSystem, Option, Order, Path, Schema } from "effect";4 5 import { committable, readsAtOnce, repoRoot, textOf } from "./root.ts";6 15-/**16- * A pointer into the maintainer's working docs, which live in a gitignored17- * `.agents/` folder on the maintainer's machine: the decisions, the demo, the18- * stage record, the workflow docs, the issue tracker and the folder's README.19- * A bare `.agents/` is not one: a hosted project's skill lives under it.20- */7 const PRIVATE_FOLDERS = [8 ".agents/adr",9 ".agents/demo",10 ".agents/ops",1 unmodified line12 ".agents/scratch",13 ".agents/README",14 ] as const;15 30-/**31- * What a pointer to something only the maintainer can open looks like: a32- * home folder, the private research repo or the host that serves it, or the33- * maintainer's working docs.34- */16 const PRIVATE = [17 "~/",18 "/home/",19 "wanted-explainer",1 unmodified line21 ...PRIVATE_FOLDERS,22 ] as const;23 24 /**44- * What a reference into the build's private plan looks like, which a reader45- * with only the repo cannot follow: a section of its spec (`spec §8`, or a46- * wave's `W9 §14`), one of its decisions (`spec D6`, or a wave's `W9-D14`),47- * one of its issues by wave (`W3 313`), or the research synthesis it was48- * drawn from (`SYN`).25+ * A reference into the build's private plan: a section of its spec26+ * (`spec §8`, `W9 §14`), a decision (`spec D6`, `W9-D14`), an issue by wave27+ * (`W3 313`), or the research synthesis (`SYN`).28 */29 const PLAN_REFERENCES = [30 /\bspec §/u,31 /\bspec D\d/u,2 unmodified lines34 /\bW\d \d{3}\b/u,35 /\bSYN\b/u,36 ] as const;37 59-/** The files a reader opens as text: source, config, docs and scripts. */38 const TEXT_FILE =39 /(?:\.(?:css|html|json|jsonc|md|mjs|sh|sql|toml|ts|tsx|ya?ml)|(?:^|\/)(?:\.gitignore|\.env\.schema|[^/]*Dockerfile))$/u;40 41 /** This file, which spells the references out to find them. */42 const QUOTES_THE_REFERENCES = "packages/config/test/docs-public.test.ts";43 66-/** The plan references `text` makes, by their patterns. */44 const planReferencesIn = (text: string) =>45 PLAN_REFERENCES.flatMap((reference) =>46 reference.test(text) ? [reference.source] : []47 );4 unmodified lines52 */53 const NAMES_THE_PRIVATE_FOLDERS = (file: string) =>54 file.startsWith(".agents/") || file === ".gitignore";55 79-/** The private plan references and private folder pointers in `file`'s `text`. */56 const privateIn = (file: string, text: string) => [57 ...planReferencesIn(text),58 ...(NAMES_THE_PRIVATE_FOLDERS(file)59 ? []60 : PRIVATE_FOLDERS.filter((folder) => text.includes(folder))),61 ];62 87-/** Terms the code uses in public names, each of which GLOSSARY.md defines. */63 const TERMS = [64 "Claim fork",65 "Decision",66 "Family",12 unmodified lines79 const RootPackage = Schema.Struct({80 scripts: Schema.Record(Schema.String, Schema.String),81 });82 108-/** A file's text, by its path from the repo root. */83 const read = (relative: string) =>84 Effect.gen(function* () {85 const fs = yield* FileSystem.FileSystem;86 const path = yield* Path.Path;1 unmodified line88 89 return yield* fs.readFileString(path.join(root, relative));90 });91 118-/** Each file with its text. */92 const withText = (paths: readonly string[]) =>93 Effect.forEach(paths, (path) =>94 Effect.map(read(path), (text) => ({ path, text }))95 );96 124-/** Every public doc this test reads, with its text. */97 const publicDocs = withText(["AGENTS.md", "GLOSSARY.md"]);98 127-/** The lines of a `## <title>` section, up to the next heading of its level or above. */99 const sectionOf = (text: string, title: string): readonly string[] => {100 const lines = text.split("\n");101 const start = lines.indexOf(`## ${title}`);102 6 unmodified lines109 110 return end === -1 ? rest : rest.slice(0, end);111 };112 142-/** The command a list item opens with: `ops` in "- `ops -- <command>`: …". */113 const commandOf = (line: string) =>114 /^- `(?<name>[^`\s]+)/u.exec(line)?.groups?.name;115 116 describe("the repo's public docs", () => {85 unmodified linesmodified:packages/config/test/example-burrow.test.ts+3 added-30 removed
1-/**2- * The fence-shaped example: `examples/burrow` is a Bun3- * project of its own, and these cases run its own commands in its folder, as4- * its maintainers would. Its lint, run as its ratchet runs it, reports5- * exactly the six module-level `let`s the ratchet starts from, one in each6- * package's `src/`, as warnings; its caller count finds `legacyFetch` in all7- * six packages, in the JSON a migrate ask's count command prints; its other8- * lanes pass on main; and its lint rule's own fixture test passes.9- *10- * Each case installs first (`--frozen-lockfile`: burrow's devDependencies are11- * pinned to the root's, so Bun's cache serves them). The manifest's presence12- * is asserted before anything runs, so a missing project is a failed13- * assertion, not a spawn error.14- */1+// Each case installs first (`--frozen-lockfile`: burrow's devDependencies are2+// pinned to the root's, so Bun's cache serves them).3 import { NodeServices } from "@effect/platform-node";4 import { describe, expect, it } from "@effect/vitest";5 import { Effect, FileSystem, Path, Schema, Stream } from "effect";6 import { ChildProcess, ChildProcessSpawner } from "effect/process";1 unmodified line8 import { repoRoot } from "./root.ts";9 10 const example = "examples/burrow";11 24-/** The six workspace packages, each holding one module-level `let`. */12 const PACKAGES = [13 "auth",14 "billing",15 "catalog",1 unmodified line17 "notify",18 "search",19 ] as const;20 34-/**35- * What a migrate ask's count command prints (`CallerCount` in36- * `@repo/project/migrate`; `@repo/config` imports no workspace package, so37- * the shape is restated here).38- */21+/** `@repo/config` imports no workspace package, so `CallerCount`'s shape is restated here. */22 const CallerCount = Schema.Struct({23 byModule: Schema.Record(Schema.String, Schema.Int),24 total: Schema.Int,25 });26 44-/** The part of `oxlint --format json` these cases read. */27 const OxlintReport = Schema.Struct({28 diagnostics: Schema.Array(29 Schema.Struct({30 code: Schema.optionalKey(Schema.String),2 unmodified lines33 })34 ),35 });36 55-/** A command's exit code and what it printed. */37 interface Ran {38 readonly code: number;39 readonly stderr: string;40 readonly stdout: string;41 }42 62-/** Runs a command in burrow's folder and keeps its exit code and output. */43 const run = (command: string, args: readonly string[]) =>44 Effect.gen(function* () {45 const path = yield* Path.Path;46 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;14 unmodified lines61 62 return { code, stderr, stdout } satisfies Ran;63 }).pipe(Effect.scoped);64 85-/** Asserts burrow exists, then installs its pinned devDependencies. */65 const install = () =>66 Effect.gen(function* () {67 const fs = yield* FileSystem.FileSystem;68 const path = yield* Path.Path;3 unmodified lines72 yield* fs.exists(manifest),73 `${example}/package.json exists`74 ).toBeTruthy();75 97- // The whole run on a failure, so its stderr shows in the diff.76 expect(yield* run("bun", ["install", "--frozen-lockfile"])).toMatchObject({77 code: 0,78 });79 });80 103-/** The package a reported file sits in, from its `packages/<name>/src/` path. */81 const packageOf = (filename: string) =>82 /(?:^|\/)packages\/(?<name>[^/]+)\/src\//u.exec(filename)?.groups?.name;83 107-/** Long enough for a cold install; a warm one takes about a second. */84 const TIMEOUT = 180_000;85 86 describe("examples/burrow", () => {87 it.live(1 unmodified line89 () =>90 Effect.gen(function* () {91 yield* install();92 117- // The command burrow's ratchet runs (its config folder's `project.ts`).93 const lint = yield* run("bun", ["run", "lint", "--format", "json"]);94 95 const report = yield* Schema.decodeEffect(96 Schema.fromJsonString(OxlintReport)39 unmodified lines136 const counts = yield* Schema.decodeEffect(137 Schema.fromJsonString(CallerCount)138 )(count.stdout);139 165- // Every package has a caller, so the family has six children; the166- // calls in each package's src/, counted by hand.140 expect(counts).toStrictEqual({141 byModule: {142 "@burrow/auth": 2,143 "@burrow/billing": 2,40 unmodified linesmodified:packages/config/test/example-datekit.test.ts+3 added-39 removed
1-/**2- * The datekit example, run as the project it pretends to be:3- * `bun test` inside `examples/datekit` is red on main for exactly the three4- * tests its asks name as their checks, each by an assertion rather than a5- * load error (what red first in GLOSSARY.md asks of a check), and green for6- * every other test. Its run block holds on main too: every lane passes, and7- * each ask's check, run alone by the block's test command, is red by an8- * assertion. The example is a Bun project of its own, outside the9- * workspaces, so each command runs as a child process under10- * `sh -c`, the way the platform's Checker runs a project's commands, in a11- * copy of its public tree: every file git tracks but its layers (`layers/`,12- * pushed to the private namespace, never to main).13- */1+// The example is a Bun project outside the workspaces, so each command runs2+// as a child process under `sh -c`, as the Checker runs a project's commands,3+// in a copy of its public tree (every tracked file but `layers/`).4 import { NodeServices } from "@effect/platform-node";5 import { describe, expect, it } from "@effect/vitest";6 import { Effect, FileSystem, Path, Stream } from "effect";7 import { ChildProcess, ChildProcessSpawner } from "effect/process";8 9 import { Brand } from "../../brand/src/index.ts";10 import { repoRoot } from "./root.ts";11 22-/** The example, from the repo root. */12 const example = "examples/datekit";13 25-/** What one run of `bun test` printed, both streams, and how it ended. */14 interface BunRun {15 readonly exitCode: number;16 readonly output: string;17 }18 31-/** One test file's part of bun's report: the tests it failed, and its text. */19 interface FileReport {20 readonly failed: readonly string[];21 readonly file: string;22 readonly text: string;23 }24 38-/** Bun's report, read: each file it reported on, and its closing counts. */25 interface BunReport {26 readonly errors: number;27 readonly failed: number;28 readonly files: readonly FileReport[];29 readonly passed: number;44- /** How many tests bun ran, across how many files. */30 readonly ran: { readonly files: number; readonly tests: number };31 }32 33 const ANSI = new RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*m`, "gu");35 unmodified lines69 const LANES = /\bchecks:\s*\{(?<lanes>[^}]*)\}/u;70 71 const LANE = /(?<lane>\w+):\s*"(?<command>[^"]+)"/gu;72 88-/** A closing count bun prints (` 3 fail`), or 0 when it prints none. */73 const countOf = (output: string, word: string) =>74 Number(75 new RegExp(`^\\s*(?<count>\\d+) ${word}$`, "mu").exec(output)?.groups76 ?.count ?? "0"77 );78 95-/** The name a `(fail)` line gives, if the line is one. */79 const failedIn = (line: string) => {80 const name = FAILED_TEST.exec(line)?.groups?.name;81 82 return name === undefined ? [] : [name];83 };84 102-/** Reads bun's console report into its files and counts. */85 const readReport = (output: string): BunReport => {86 const lines = output.split("\n").map((line) => line.trim());87 88 const starts = lines.flatMap((line, at) =>31 unmodified lines120 121 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>122 bytes.pipe(Stream.decodeText(), Stream.mkString);123 142-/**143- * The example's public tree in a folder of its own, for as long as the144- * scope lasts: every file git tracks under it but its layers, as the seed145- * pushes main.146- */124 const publicTree = Effect.gen(function* () {125 const fs = yield* FileSystem.FileSystem;126 const path = yield* Path.Path;127 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;19 unmodified lines147 148 return dir;149 });150 174-/** Runs `command` in the example's public tree at `dir` under `sh -c`, as the Checker runs a lane. */151 const inTree = (dir: string, command: string) =>152 Effect.scoped(153 Effect.gen(function* () {154 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;13 unmodified lines168 } satisfies BunRun;169 })170 );171 196-/** The example's run block, read from its project file. */172 const runBlock = Effect.gen(function* () {173 const fs = yield* FileSystem.FileSystem;174 const path = yield* Path.Path;175 11 unmodified lines187 188 return { lanes, test: TEST_COMMAND.exec(source)?.groups?.command ?? "" };189 });190 216-/**217- * Each ask file in the example's config folder, and the check file it names;218- * none when the folder is missing.219- */191 const askChecks = Effect.gen(function* () {192 const fs = yield* FileSystem.FileSystem;193 const path = yield* Path.Path;194 const asks = path.join(yield* repoRoot, example, Brand.configDir, "asks");13 unmodified lines208 }))209 );210 });211 241-/** How a file failed: how many tests, whether by an assertion, whether it loaded. */212 const howFailed = ({ failed, file, text: part }: FileReport) => ({213 assertion: ASSERTION.test(part),214 file,215 loaded: !LOAD_ERRORS.some((pattern) => pattern.test(part)),7 unmodified lines223 it.live(224 "is red on main for exactly its three asks' checks, each by an assertion, and green elsewhere",225 () =>226 Effect.gen(function* () {257- // The example's own `package.json` test script.227 const run = yield* inTree(yield* publicTree, "bun test");228 const report = readReport(run.output);229 const checks = yield* askChecks;230 2 unmodified lines233 "format-ordinal.ask.ts",234 "parse-iso-week.ask.ts",235 ]);236 268- // The run fails, and only by the asks' checks: one test in each, by269- // an assertion, with nothing that failed to load.237 expect({238 errors: report.errors,239 exitedNonZero: run.exitCode !== 0,240 failed: report.failed,14 unmodified lines255 }))256 .toSorted(byFile),257 });258 292- // Every other test passes, across the four suites the library keeps293- // green (parse, format, add, diff) and the three checks.259 expect({260 files: report.ran.files,261 passedOrFailed: report.passed + report.failed,262 }).toStrictEqual({ files: 7, passedOrFailed: report.ran.tests });61 unmodified lines324 failing: [{ assertion: true, file, loaded: true, tests: 1 }],325 }))326 );327 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),363- // Four `bun test` runs over a small library, one after another.328 30_000329 );330 });modified:packages/config/test/import-examples.test.ts-17 removed
1-/**2- * `bun scripts/import-examples.ts`: the open-source repos the code browser3- * is previewed on, imported one at a time as the operator, skipped once a4- * platform lists them, recorded in the ledger as kept imports, on `demo`5- * as on a dev stage; and `--tags`' backfill, which pushes tags only and6- * never shows its token.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { ProjectExists } from "@repo/protocol/refusal";4 import {263 unmodified lines268 ]);269 });270 });271 279-/** A platform in memory: the projects it lists, and every call made to it. */272 const fakePlatform = (listed: readonly string[]) =>273 Effect.gen(function* () {274 const calls = yield* Ref.make<readonly string[]>([]);275 const have = new Set(listed.map(project));40 unmodified lines316 ),317 };318 });319 328-/** `importExamples(argv)` over `layer`, with the ledger in a temp folder: how it ended, and what it printed. */320 const ran = (321 argv: readonly string[],322 layer: Layer.Layer<ImportTarget | TagBackfill | Warmer>323 ) =>223 unmodified lines547 548 const ledgerFile = path.join(dir, "created.jsonl");549 const platform = yield* fakePlatform(["anyhow", "ky"]);550 560- // An earlier run imported anyhow; ky is someone else's project.551 yield* fs.writeFileString(552 ledgerFile,553 `${JSON.stringify({ at: "2026-10-08T20:00:00.000Z", by: "import", kind: "project", name: "anyhow", stage: "dev-oscabriel" })}\n`554 );22 unmodified lines577 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "importing-" });578 579 const ledgerFile = path.join(dir, "created.jsonl");580 591- // An earlier run imported anyhow and gum; the platform lists anyhow592- // and ky (someone else's project), and gum not yet.581 const platform = yield* fakePlatform(["anyhow", "ky"]);582 583 yield* fs.writeFileString(584 ledgerFile,87 unmodified lines672 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))673 );674 });675 688-/** A call the platform never answered, as an edge timeout leaves it. */676 class NoAnswer extends Data.TaggedError("NoAnswer")<{677 readonly after: string;678 }> {}679 693-/**694- * `initUntilAnswered` over calls that answer `answers` in turn, the clock695- * moved past its waits: how it ended, and how many calls it made.696- */680 const askedAgain = (681 answers: readonly Effect.Effect<682 { readonly landed?: string },683 NoAnswer | ProjectExists61 unmodified linesmodified:packages/config/test/imported-docs.test.ts-6 removed
1-/**2- * The docs' list of imported projects is a copy of the import script's3- * plan, kept in `@repo/agent-kit` (the web cannot import a script): each4- * project by its name and key, with its source, its licence and what it5- * is, in the plan's order.6- */1 import { describe, expect, it } from "@effect/vitest";2 3 import { examples } from "../../../scripts/lib/import/plan.ts";4 import { importedProjects } from "../../agent-kit/src/docs/imported.ts";14 unmodified linesmodified:packages/config/test/legacy-projects.test.ts+2 added-9 removed
1-/**2- * The projects made before owners keep the keys they were made with3- * (`packages/protocol/src/legacy.ts`): the protocol's table holds the two4- * examples, the operator's, and every import at its source path, each by5- * the key it has on the stages. The table is written by hand in the6- * protocol, so a Worker never imports a script; this holds it to its7- * sources, the examples' folders and the import plan.8- */1+// The protocol's table is written by hand, so a Worker never imports a2+// script; this holds it to its sources, the examples' folders and the import plan.3 import { describe, expect, it } from "@effect/vitest";4 5 import { examples } from "../../../scripts/lib/import/plan.ts";6 import { EXAMPLES } from "../../../scripts/seed.ts";7 import { legacyProjects } from "../../protocol/src/legacy.ts";8 15-/** Each example folder's project, in the operator's namespace. */9 const seeded = EXAMPLES.map((folder) => {10 const key = folder.slice(folder.lastIndexOf("/") + 1);11 12 return { key, name: `oscabriel/${key}` };15 unmodified linesmodified:packages/config/test/recording.test.ts-13 removed
1-/**2- * The deploy lock for recording days: `bun infra/recording.ts3- * on` writes `infra/.recording`, and while it is there `infra/deploy.ts`4- * refuses every deploy with `RecordingInProgress` before it spawns anything.5- * `off` is the only way out.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 ConfigProvider,18 unmodified lines23 RecordingUsage,24 } from "../../../infra/recording.ts";25 import { repoRoot } from "./root.ts";26 33-/**34- * A spawner that runs nothing and exits 0: each command it was asked for,35- * as `<folder>$ <command> <args>`, its folder relative to the repo root.36- */27 const spawning = Effect.gen(function* () {28 const path = yield* Path.Path;29 const root = yield* repoRoot;30 const lines = yield* Ref.make<readonly string[]>([]);32 unmodified lines63 spawned: Ref.get(lines),64 };65 });66 77-/** A temp root's lock file, `infra/.recording` under it, for one test's scope. */67 const tempLock = Effect.gen(function* () {68 const fs = yield* FileSystem.FileSystem;69 const path = yield* Path.Path;70 const root = yield* fs.makeTempDirectoryScoped({ prefix: "recording-806-" });2 unmodified lines73 74 return path.join(root, lockPath);75 });76 88-/** `deploy(argv)` with the lock at `lock`: how it ended, and what it spawned. */77 const deployed = (argv: readonly string[], lock: string) =>78 Effect.gen(function* () {79 const fake = yield* spawning;80 10 unmodified lines91 92 return { result, spawned: yield* fake.spawned };93 });94 107-/** What `recording(argv)` prints, with the lock at `lock`. */95 const printedBy = (argv: readonly string[], lock: string) =>96 Effect.gen(function* () {97 const printed: string[] = [];98 124 unmodified linesmodified:packages/config/test/release.test.ts-19 removed
1-/**2- * The release: the CLI's npm package says what it is from3- * `Brand` alone, a release builds for exactly two machines, only a person4- * publishes, and what goes to the platform's own release storage is what5- * the platform decodes and serves.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Array as Arr,37 unmodified lines42 import { layoutOf, runStep } from "../../../scripts/lib/release/steps.ts";43 import { Brand } from "../../brand/src/index.ts";44 import { repoRoot } from "./root.ts";45 52-/** What the test reads of a package manifest. */46 const PackageJson = Schema.fromJsonString(47 Schema.Struct({48 dependencies: Schema.optionalKey(49 Schema.Record(Schema.String, Schema.String)350 unmodified lines400 });401 });402 });403 411-/** A digest, as `sha256sum` prints one. */404 const digest = (fill: string) => fill.repeat(64);405 406 const first = {407 latest: "0.1.0",15 unmodified lines423 [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },424 [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },425 };426 435-/**436- * A spawner that runs nothing and exits 0: each command it was asked for,437- * as `<folder>$ <command> <args>`, its folder relative to the repo root.438- */427 const recordingSpawner = Effect.gen(function* () {428 const path = yield* Path.Path;429 const root = yield* repoRoot;430 const lines = yield* Ref.make<readonly string[]>([]);101 unmodified lines532 });533 });534 });535 548-/** A file's digest as `sha256sum` prints it. */536 const sha256 = (content: string) =>537 Effect.flatMap(Crypto.Crypto, (crypto) =>538 crypto.digest("SHA-256", new TextEncoder().encode(content))539 ).pipe(27 unmodified lines567 posix: true,568 });569 });570 584- /**585- * A machine to install on: a `curl` that serves `files` for the release's586- * URLs and fails any other, a home folder, and `sh` to run the script.587- */571 const install = (files: Readonly<Record<string, string>>) =>572 Effect.gen(function* () {573 const fs = yield* FileSystem.FileSystem;574 const path = yield* Path.Path;62 unmodified lines637 stderr,638 };639 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));640 658- /** A binary for each machine a release builds for, as a tiny script. */641 const binaries = Object.fromEntries(642 ["linux-x64", "darwin-arm64"].map((target) => [643 `${Brand.slug}-${target}`,644 `#!/bin/sh\necho ${target}\n`,645 ])646 );647 666- /** `SHA256SUMS` for the binaries, each digest as `digestOf` gives it. */648 const sums = <E, R>(649 digestOf: (content: string) => Effect.Effect<string, E, R>650 ) =>651 Effect.map(90 unmodified linesmodified:packages/config/test/root.ts+2 added-12 removed
1 import { Effect, FileSystem, Option, Path, Stream } from "effect";2 import { ChildProcess, ChildProcessSpawner } from "effect/process";3 4-/** The repo root. Vitest runs in the package's folder, two below it. */4 export const repoRoot = Effect.map(Path.Path, (path) =>5 path.resolve("..", "..")6 );7 9-/**10- * Every file git tracks or would track (ignored files left out), from the11- * repo root. A tracked file deleted but not yet staged is still listed:12- * `textOf` reads it as none.13- */8+/** A tracked file deleted but not yet staged is still listed: `textOf` reads it as none. */9 export const committable = Effect.gen(function* () {10 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;11 const cwd = yield* repoRoot;12 16 unmodified lines29 30 return listed.split("\n").filter((line) => line.length > 0);31 }).pipe(Effect.scoped);32 38-/**39- * How many of the repo's files a whole-repo scan reads at once. One at a40- * time, a scan of every source file waits on a thousand queued reads, which41- * under verify's parallel test run takes longer than a test's timeout.42- */33+/** One read at a time, a whole-repo scan outlasts a test's timeout under verify's parallel run. */34 export const readsAtOnce = { concurrency: 32 } as const;35 45-/** A file under the repo root, as text, if it is on disk. */36 export const textOf = (file: string) =>37 Effect.gen(function* () {38 const fs = yield* FileSystem.FileSystem;39 const path = yield* Path.Path;6 unmodified linesmodified:packages/config/test/scripts.test.ts-8 removed
1-/**2- * The demo-readiness scripts: a maintainer types `bun run swarm`,3- * `bun run seed`, `bun run release` or `bun run import-examples`, and each4- * runs one entry file that5- * exists, so the work that builds them fills an entry without touching a6- * root file.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Effect, FileSystem, Path, Schema } from "effect";4 2 unmodified lines7 const RootPackage = Schema.Struct({8 scripts: Schema.Record(Schema.String, Schema.String),9 });10 18-/** What `bun run <name>` runs, and whether its entry file is on disk. */11 const entryOf = (name: string) =>12 Effect.gen(function* () {13 const fs = yield* FileSystem.FileSystem;14 const path = yield* Path.Path;39 unmodified linesmodified:packages/config/test/seed-as.test.ts-9 removed
1-/**2- * `seed --as`: a fresh copy of an example under another project3- * name, so a live run (the swarm's rehearsal) can take a family nobody has4- * touched while the original stays fresh for the recording. A name some5- * project already has is refused, and a copy on a stage is written to the6- * throwaway ledger for teardown.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Console, DateTime, Effect, FileSystem, Layer, Path } from "effect";4 66 unmodified lines71 repo: `oscabriel__datekit-copy-2--${layer}`,72 }))73 );74 82- // A copy of a copy is still a copy of the example.75 expect(copy.copyOf).toBe("oscabriel/datekit");76 }).pipe(Effect.provide(NodeServices.layer))77 );78 });38 unmodified lines117 60_000118 );119 });120 129-/** What `main` prints, line by line. */121 const printedBy = (argv: readonly string[]) =>122 Effect.gen(function* () {123 const printed: string[] = [];124 121 unmodified linesmodified:packages/config/test/seed-layer.test.ts-39 removed
1-/**2- * datekit's maintainers layer and the seed's layer step: the3- * held-back checks datekit keeps in `layers/maintainers/`, each citing the4- * clause it enforces, and the seed pushing them to the private namespace5- * after the public project, never into the public tree.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Array,25 unmodified lines30 } from "../../protocol/src/domain/visibility.ts";31 import { Handle, keyOf, RepoName } from "../../protocol/src/ids.ts";32 import { repoRoot } from "./root.ts";33 40-/** The config folder's name, from the brand. */34 const config = Brand.configDir;35 43-/** Every file of datekit's maintainers layer, as the layer repo holds it. */36 const layerFiles = [37 `${config}/layer.json`,38 `${config}/layer.ts`,39 ".agents/maintainers/finish.md",56 unmodified lines96 }).pipe(Effect.provide(NodeServices.layer))97 );98 });99 108-// ------------------------------------------------------------- the layer109-100 const example = "examples/datekit";101 102 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>103 bytes.pipe(Stream.decodeText(), Stream.mkString);104 115-/** `command` run in `cwd`: how it ended, and both streams. */105 const run = (cwd: string, command: string, args: readonly string[]) =>106 Effect.scoped(107 Effect.gen(function* () {108 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;10 unmodified lines119 return { code: Number(code), output: `${stdout}\n${stderr}` };120 })121 );122 134-/** A file of the example, as text. */123 const exampleFile = (file: string) =>124 Effect.gen(function* () {125 const fs = yield* FileSystem.FileSystem;126 const path = yield* Path.Path;127 128 return yield* fs.readFileString(path.join(yield* repoRoot, example, file));129 });130 143-// Every import of the sdk by the name config files use.131 const SDK = new RegExp(`(["'])${Brand.cliPackage}/rules\\1`, "gu");132 146-/**147- * What a config module's default export is, as data: the module run by148- * bun with its sdk import pointed at the sdk's source, as the rules149- * evaluator's `/bun` adapter runs config code, then printed as JSON.150- */133 const defaultExportOf = (source: string) =>134 Effect.scoped(135 Effect.gen(function* () {136 const fs = yield* FileSystem.FileSystem;12 unmodified lines149 );150 151 const ran = yield* run(dir, "bun", ["main.ts"]);152 171- // What bun said shows only when it failed.153 expect({154 code: ran.code,155 said: ran.code === 0 ? "" : ran.output,156 }).toStrictEqual({ code: 0, said: "" });3 unmodified lines160 );161 })162 );163 183-/** The layer's file at `file`, as text. */164 const inLayer = (plan: SeedPlan, file: string) =>165 new TextDecoder().decode(166 plan.layers[0]?.files.find(({ path }) => path === file)?.content167 );168 189-/** datekit's plan, its maintainers layer, the manifest and the policy. */169 const datekit = Effect.gen(function* () {170 const plan = yield* planSeed(example);171 const layer = yield* Effect.fromNullishOr(plan.layers[0]);172 7 unmodified lines180 181 return { layer, manifest, plan, policy };182 });183 205-/** The lanes datekit's `project.ts` runs on every answer: the public checks, by name. */184 const publicLanes = Effect.gen(function* () {185 const { run: block } = yield* Schema.decodeUnknownEffect(186 Schema.Struct({187 run: Schema.Struct({4 unmodified lines192 193 return Object.entries(block.checks);194 });195 218-/** A heading's anchor, as a README link names it: `## Format patterns` is `format-patterns`. */196 const anchorOf = (heading: string) =>197 heading198 .toLowerCase()199 .replaceAll(/[^\w\s-]/gu, "")200 .trim()201 .replaceAll(/\s+/gu, "-");202 226-/** Each README section's text by its anchor: from its heading to the next. */203 const sectionsOf = (readme: string) => {204 const sections = new Map<string, string>();205 let current = "";206 113 unmodified lines320 );321 322 expect(unquoted).toStrictEqual([]);323 348- // Both kinds of source are cited.324 expect(325 Array.dedupe(326 manifest.checks.map(({ clause }) => clause.source)327 ).toSorted()29 unmodified lines357 30_000358 );359 });360 386-/** A folder holding `trees` one over another, each file at its path. */361 const treeOf = (...trees: readonly (readonly SeedFile[])[]) =>362 Effect.gen(function* () {363 const fs = yield* FileSystem.FileSystem;364 const path = yield* Path.Path;49 unmodified lines414 "test",415 `./checks/held-back/${area}`,416 ]);417 444- // Each lane as the Checker runs it: its command under `sh -c`.418 const failedLanes = yield* Effect.filter(lanes, ([, command]) =>419 Effect.map(420 run(bad, "sh", ["-c", command]),421 ({ code }) => code !== 018 unmodified lines440 60_000441 );442 });443 471-// ------------------------------------------------------------- the world472-473-/** A vouched contributor to datekit, who reads no layer. */444 const bram = Handle.make("bram");445 476-/** Paths a public tree must never hold: the layer's, or the example's folder of layers. */446 const isLayerPath = (path: string) =>447 ["layers/", "checks/held-back/", ".agents/maintainers/"].some((prefix) =>448 path.startsWith(prefix)449 );19 unmodified lines469 "OpenAsk oscabriel/datekit/parse-iso-week: done",470 "Layer datekit--maintainers: done",471 ]);472 504- // A maintainer's clone: the layer's files on main, and a branch505- // for each known-bad commit its manifest names.473 const refs = yield* Effect.flatMap(474 target.refsAt(layer.repo, plan.decider),475 Effect.fromOption476 );27 unmodified lines504 MAIN_REF,505 ].toSorted(),506 });507 541- // A contributor's clone of the layer is turned away, and the542- // public tree holds visibility.ts and nothing of the layer.508 const refused = yield* Effect.flip(target.refsAt(layer.repo, bram));509 510 const published = yield* target.pathsAt(511 project,12 unmodified lines524 layerPaths: [],525 visibility: true,526 });527 563- // The public ledger declares the layer and the posture its564- // config states. (Each area's counts are published when its565- // checks are admitted: 615.)528 const ledger = yield* Client.use((client) =>529 client.ledger({ project: plan.project })530 ).pipe(Effect.provide(target.clientFor(bram)));531 19 unmodified lines551 posture:552 "Open with sealed evidence · sealed checks in export, parser",553 });554 593- // A second run finds every step done and moves no ref.555 const again = yield* runSeed(plan);556 const after = yield* target.refsAt(layer.repo, plan.decider);557 558 expect({21 unmodified linesmodified:packages/config/test/seed.test.ts-11 removed
1-/**2- * The seed: what it plans to put on a platform for each example3- * project, read from the example's tracked files, and putting it there.4- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 ConfigProvider,24 unmodified lines29 } from "../../../scripts/seed.ts";30 import { Brand } from "../../brand/src/index.ts";31 import { repoRoot } from "./root.ts";32 37-/** The config folder's name, from the brand (`Brand.configDir`). */33 const config = Brand.configDir;34 40-/** A file of an example, as the test reads it from disk. */35 const onDisk = (example: string, path: string) =>36 Effect.gen(function* () {37 const fs = yield* FileSystem.FileSystem;38 const paths = yield* Path.Path;145 unmodified lines184 }).pipe(Effect.provide(NodeServices.layer))185 );186 });187 194-/** Each step as the command prints it. */188 const linesOf = (steps: readonly SeedStep[]) => steps.map(stepLine);189 190 describe(runSeed, () => {191 it.live(23 unmodified lines215 ]);216 217 const held = yield* seeded(plans);218 226- // Each project's asks, each with the asks it waits on.219 const asks = Object.fromEntries(220 held.map(({ asks: listed, project }) => [221 project,222 Object.fromEntries(60 unmodified lines283 const { failure, refs } = yield* Effect.gen(function* () {284 const stopped = yield* Effect.flip(runSeed(plan));285 const target = yield* SeedTarget;286 295- // No project was made: the gateway has no burrow to list refs of.287 const listed = yield* target.refsOf(plan.project).pipe(288 Effect.map((held) => `listed ${held.size} refs`),289 Effect.catch(({ reason }) => Effect.succeed(reason))290 );79 unmodified lines370 )371 );372 });373 383-/** What `main` prints, line by line, and how it ended. */374 const printedBy = (argv: readonly string[]) =>375 Effect.gen(function* () {376 const printed: string[] = [];377 81 unmodified lines459 decider: held?.decider,460 project: held?.project,461 ratchets: held?.ratchets,462 }).toStrictEqual({473- // The migrate ask's family: the parent, six children, the delete child.463 asks: 8,464 decider: "okafor",465 project: "oscabriel/burrow",466 ratchets: ["no-module-level-mutable-state"],59 unmodified linesmodified:packages/config/test/smoke-loop.test.ts+2 added-30 removed
1-/**2- * smoke's core loop: `bun scripts/smoke.ts --stage <s> --loop`3- * makes a throwaway project, opens an ask red first, claims it, pushes an4- * answer that reaches outside the ask's territory and hears `OutOfScope`5- * in git's own output, pushes the fix, and reads back its landing and its6- * verdict note, all through the CLI and git as a person would. Here it runs7- * against the Node world (`apps/platform/test/serve-world.ts`), reached8- * over HTTP and git as a stage is.9- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Effect,22 unmodified lines27 const decider = Handle.make("ines-v");28 29 const answerer = Handle.make("bram");30 40-/** Each person's token in the world: no secret, it never leaves this machine. */31 const tokens = {32 answerer: Redacted.make("bram-smoke-loop-world-token-0123456789abcdef"),33 decider: Redacted.make("ines-v-smoke-loop-world-token-0123456789abcd"),34 };35 46-/** A person in a trailer: their handle and the address the platform gives them. */36 const credited = (handle: string) =>37 `${handle} <${handle}@users.${Brand.domain}>`;38 50-/** All a byte stream says, as text. */39 const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>40 bytes.pipe(Stream.decodeText(), Stream.mkString);41 54-/** `git ls-remote <remote> <ref>` as anyone, with no credential at all. */42 const anonymousTip = (remote: string, ref: string) =>43 Effect.scoped(44 Effect.gen(function* () {45 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;119 unmodified lines165 240_000166 );167 });168 182-/**183- * A spawner that runs nothing: each command it was asked for, by name. Any184- * command fails, so a run that reached one could not pass by accident.185- */169+/** Any command fails, so a run that reached one could not pass by accident. */170 const refusing = Effect.gen(function* () {171 const asked = yield* Ref.make<readonly string[]>([]);172 173 const spawner = ChildProcessSpawner.make((command) =>24 unmodified lines198 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),199 };200 });201 218-/**219- * A platform scripted at the process boundary: `status` names the decider,220- * `projects` lists `listed`, git does what it is asked, and `init` makes221- * the project on the platform and then fails (as a push that answered 500222- * after the project was made did on a dev stage). What was spawned is kept, git by223- * its subcommand and the CLI by its command.224- */202+/** `init` makes the project and then fails, as a push that answered 500 after making it did. */203 const scripted = (listed: readonly string[]) =>204 Effect.gen(function* () {205 const asked = yield* Ref.make<readonly string[]>([]);206 229- // Each CLI command's `--json` envelope, as the CLI prints it.207 const replies = new Map([208 [209 "status",210 {32 unmodified lines243 const [program, args] = ChildProcess.isStandardCommand(command)244 ? [command.command, command.args]245 : ["a pipe", []];246 270- // The CLI runs as `bun <entry> <command> … --json`.247 const said =248 program === "bun" ? (args[1] ?? "") : `${program} ${args[0] ?? ""}`;249 250 yield* Ref.update(asked, (all) => [...all, said]);21 unmodified lines272 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),273 };274 });275 300-/**301- * The loop for run `r1` on the scripted platform, with the ledger in a file302- * of its own: how it ended, the CLI commands it ran, and the ledger's lines.303- */276 const loopOnScripted = (listed: readonly string[]) =>277 Effect.gen(function* () {278 const fs = yield* FileSystem.FileSystem;279 const path = yield* Path.Path;233 unmodified linesmodified:packages/config/test/smoke.test.ts+7 added-38 removed
18 unmodified lines19 SmokeFailed,20 webProbes,21 } from "../../../scripts/smoke.ts";22 23-/** What the fake platform answers one request with, after `delayMs` when given. */23 interface Reply {24 readonly status: number;25 readonly body?: string;26 readonly contentType?: string;27 readonly delayMs?: number;28 }29 31-/** A request as the fake platform sees it. */30 interface Seen {31 readonly method: string;32 readonly path: string;33 readonly authorized: boolean;34 readonly body: string;35 }36 39-/** A call as effect/rpc's HTTP protocol sends one, with JSON serialization. */37 const ListAsksCall = Schema.fromJsonString(38 Schema.Tuple([39 Schema.TaggedStruct("Request", {40 headers: Schema.Array(Schema.Unknown),4 unmodified lines45 ])46 );47 48 /**52- * The platform's `/rpc` reply to `body`: for an anonymous `listAsks` of a53- * project in `held`, its open asks (none); of any other, the bytes its54- * server sent for a project it doesn't hold (captured from55- * `apps/platform`'s `serve` before any project existed, the refusal's56- * `next` aside); a 400 for anything else.49+ * The bytes of another project's reply were captured from `apps/platform`'s50+ * `serve` before any project existed, the refusal's `next` aside.51 */52 const rpcReply = (body: string, held: readonly string[]): Reply =>53 Option.match(Schema.decodeOption(ListAsksCall)(body), {54 onNone: () => ({ status: 400 }),4 unmodified lines59 status: 200,60 }),61 });62 69-/** The platform as `healthy` below, holding only the projects `held` names: a stage not seeded holds none. */63 const holding =64 (held: readonly string[]) =>65 ({ authorized, body, method, path }: Seen): Reply => {66 if (method === "GET" && path === "/") {25 unmodified lines92 93 return { status: 404 };94 };95 103-/**104- * The platform as smoke expects to find it: healthy, OAuth's resource105- * metadata published, MCP closed to anyone without a credential, anonymous106- * reads open, the seeded example `oscabriel/datekit` held and no repo it doesn't107- * hold, and a `/` that names MCP and the CLI's installer.108- */96 const healthy = holding(["oscabriel/datekit"]);97 111-/**112- * A platform whose 401 gate is gone and whose stage is down: `/health` and113- * `/rpc` break, MCP opens to anyone, git's paths answer 200, and `/` is114- * gone.115- */98 const broken = (seen: Seen): Reply => {99 if (seen.path === "/") {100 return { status: 404 };101 }16 unmodified lines118 119 return healthy(seen);120 };121 140-/** `answer` served on an ephemeral local port, for the test's scope: its origin. */122 const fakePlatform = (answer: (seen: Seen) => Reply) =>123 Effect.gen(function* () {124 const app = Effect.gen(function* () {125 const request = yield* HttpServerRequest.HttpServerRequest;53 unmodified lines179 ).toBeTruthy();180 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))181 );182 202- // Live on dev-oscabriel: the first smoke after the first deploy got203- // a 500 from /health and a defect from the first Project DO call, and a204- // second run seconds later passed every probe.183+ // Seen live: the first smoke after a first deploy got a 500 from /health and184+ // a defect from the first Project DO call; a run seconds later passed.185 it.live(186 "asks again while a fresh deploy answers with a server error or a defect, and passes once it settles",187 () =>188 Effect.gen(function* () {37 unmodified lines226 it.live(227 "asks / again while the version before a deploy still answers it with 404, and passes once it settles",228 () =>229 Effect.gen(function* () {250- // a demo deploy that added `/`: smoke ran as the upload finished, and the230+ // A deploy that added `/`: smoke ran as the upload finished, and the231 // version before, which has no `/`, answered it once more with 404.232 const asked = { root: 0 };233 234 const origin = yield* fakePlatform((seen) => {62 unmodified lines297 }).pipe(Effect.provide(FetchHttpClient.layer))298 );299 });300 321-/**322- * The web as smoke expects to find it: its front page renders, its323- * `/llms.txt` answers with the Markdown it builds from the platform's324- * project list, which only a web that reaches the platform can, and so do325- * a seeded example's `llms.txt` and ask, and the agent skills' index.326- */301 const healthyWeb = ({ method, path }: Seen): Reply => {302 if (method === "GET" && path === "/") {303 return {304 body: '<!DOCTYPE html><html lang="en"><head></head><body></body></html>',155 unmodified lines460 });461 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))462 );463 490- // Live on dev-oscabriel: smoke ran 4 s after the web Worker's first491- // deploy, and its new workers.dev hostname answered 404 to both probes; a492- // run seconds later passed both.464+ // Seen live: smoke ran 4 s after the web Worker's first deploy, and its new465+ // workers.dev hostname answered 404; a run seconds later passed.466 it.live(467 "asks the web again while a first deploy's hostname answers 404, and passes once it settles",468 () =>469 Effect.gen(function* () {23 unmodified lines493 },494 probes: [...probes],495 });496 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)),524- // Five paths, each asked three times a second apart.497 30_000498 );499 500 it.live(154 unmodified lines655 Schema.is(SmokeFailed)(failed)656 ? failed.failures.map(({ probe }) => probe)657 : []658 ).toStrictEqual(["health"]);687- // `runMain` prints a failure as its tag and its message, and nothing else.659 expect(failed.message).toBe(`health failed at ${origin}`);660 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))661 );662 663 it.live("probes the web at --web-url, and only there, beside --url", () =>664 Effect.gen(function* () {665 const origin = yield* fakePlatform(healthy);695- // A web that answers, wrongly: JSON where a page and Markdown belong696- // (only the agent skills' index is JSON).666 const web = yield* fakePlatform(() => ({ body: "{}", status: 200 }));667 668 yield* main(["--stage", "dev-oscabriel", "--url", origin]);669 25 unmodified linesmodified:packages/config/test/swarm-herdr.test.ts+3 added-77 removed
1-/**2- * The swarm's herdr view: six contributors in six herdr panes and a counter3- * pane, for the video. The view decides only where a harness runs and how a4- * prompt reaches it; the verdict loop and its outcomes (from5- * `<cli> status --json`, never pane text) are `swarm-loop.test.ts`'s. The counter follows the6- * project's `watch` and counts claims, pushes and landings.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { AnswerView } from "@repo/protocol/domain/answer";4 import { ClaimView } from "@repo/protocol/domain/claim";59 unmodified lines64 );65 66 const sha = (digit: number) => CommitSha.make(String(digit).repeat(40));67 75-/** The `n`th event's place in the project's sequence, and its time. */68 const stamp = (n: number) => ({69 at: DateTime.makeUnsafe(70 `2026-10-08T12:${String(10 + n).padStart(2, "0")}:00.000Z`71 ),72 seq: 100 + n,73 });74 83-/**84- * A take's events: six claims, nine pushes (three agents pushed twice), four85- * landings, and events the counter does not count (a verdict, a released86- * claim, an ask that opened).87- */75 const takeEvents: readonly ProjectEvent[] = [76 ...children.map((ask, at) =>77 ProjectEvent.cases.Claimed.make({78 ...stamp(at),184 unmodified lines263 })264 );265 });266 280-/** The env names the CLI reads, spelled from the brand. */267 const SLUG = Brand.slug.toUpperCase();268 269 const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";270 271 const tokenOf = (handle: string) =>272 `${handle}-token-0123456789abcdef0123456789ab`;273 288-/** Whose token `env` carries, if anyone's. */274 const holderOf = (env: Readonly<Record<string, string | undefined>>) =>275 handles.find((handle) => env[`${SLUG}_TOKEN`] === tokenOf(handle));276 292-/** One command the fake world was asked to run. */277 interface Spawned {278 readonly command: string;279 readonly args: readonly string[];280 readonly env: Readonly<Record<string, string | undefined>>;281 }282 299-/** How a faked command ends: its exit code and what it printed. */283 interface Ending {284 readonly code?: number;285 readonly stdout?: string;286 readonly stderr?: string;287 }288 289 const bytes = (text: string) => Stream.make(new TextEncoder().encode(text));290 308-/**309- * A `ChildProcessSpawner` that runs nothing: it records each command and310- * ends it as `answer` says.311- */291 const fakeSpawner = (answer: (call: Spawned) => Effect.Effect<Ending>) =>292 Effect.gen(function* () {293 const spawned = yield* Ref.make<readonly Spawned[]>([]);294 34 unmodified lines329 spawned: Ref.get(spawned),330 };331 });332 354-/** A swarm fixture's text. */333 const fixture = (name: string) =>334 Effect.gen(function* () {335 const fs = yield* FileSystem.FileSystem;336 const path = yield* Path.Path;16 unmodified lines353 })354 )355 );356 379-/** `handle`'s answer to `ask`, the `n`th they pushed, with its outcome. */357 const answerOf = (358 handle: string,359 ask: AskId,360 n: number,7 unmodified lines368 });369 370 const landed = Outcome.cases.Landed.make({ sha: LandedSha.make(sha(9)) });371 395-/**396- * What `handle`'s `<cli> status --json` prints on its `call`th read: wren's397- * first answer is refused for leaving its territory and the next one lands;398- * everyone else's first answer lands.399- */372 const statusOf = (handle: string, call: number) => {373 const ask = children[handles.indexOf(handle)] ?? AskId.make("unknown");374 375 const refused = answerOf(15 unmodified lines391 v: 1,392 });393 };394 423-/** herdr's answer for a pane it made. */395 const paneJson = (pane: string) =>396 JSON.stringify({397 id: "cli:pane:split",398 result: { pane: { pane_id: pane, workspace_id: "w9" }, type: "pane_info" },399 });400 430-/** herdr's answer for an agent that is idle and ready for input. */401 const agentJson = (name: string, type: string) =>402 JSON.stringify({403 id: `cli:agent:${type}`,404 result: {7 unmodified lines412 type,413 },414 });415 446-/** What `<cli> claim <ask> --json` prints for `handle`. */416 const claimOf = (ask: string, handle: string) => {417 const fork = `burrow--${ask}--${handle}`;418 419 return JSON.stringify({17 unmodified lines437 v: 1,438 });439 };440 472-/**473- * The platform, git and herdr, faked for a whole `--view herdr` run: the474- * CLI's `asks`, `ask` and `claim` answer from the fixtures, each475- * contributor's `status` from `statusOf`, git and `mkfifo` succeed, herdr476- * makes panes `w9:p1`, `w9:p2`, … and every agent settles idle, and the477- * counter's `watch` hears nothing new. `replay` is how the counter's read478- * of where the project stands ends: an empty replay unless a test says.479- */441 const herdrWorld = (replay: Ending) =>442 Effect.gen(function* () {443 const panes = yield* Ref.make(1);444 const reads = yield* Ref.make(new Map<string, number>());65 unmodified lines510 if (call.command !== "curl") {511 return Effect.map(answer(call), (stdout) => ({ stdout }));512 }513 553- // The read of where the project stands is plain JSON; the follow hears nothing.514 return Effect.succeed(515 call.args.includes("content-type: application/json") ? replay : {}516 );517 });518 });519 560-/** `watch`'s plain JSON replay of a project that holds no event yet. */520 const emptyReplay: Ending = {521 stdout:522 '[{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',523 };524 566-/** What herdr puts in the env of a process in one of its panes. */525 const inAPane = { HERDR_ENV: "1" };526 569-/**570- * `main --view herdr` for every contributor over `herdrWorld`, from a herdr571- * pane unless `herdrEnv` says otherwise, the counter's read of the project572- * ending as `replay`, with `.swarm/` and the ledger in a temp dir.573- */527 const herdrRunWith = (528 herdrEnv: Readonly<Record<string, string>>,529 replay: Ending = emptyReplay530 ) =>43 unmodified lines574 ),575 Effect.result576 );577 625- // The TestClock's epoch names the run.578 const run = `${swarm}/19700101-000000`;579 const summary = `${run}/agents.json`;580 const wrensScript = `${run}/wren/pane-shell`;581 13 unmodified lines595 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));596 597 const herdrRun = herdrRunWith(inAPane);598 647-/** The herdr calls of a run, as argv. */599 const herdrCalls = (spawned: readonly Spawned[]) =>600 spawned.flatMap(({ args, command }) => (command === "herdr" ? [args] : []));601 651-/** The `agent <verb>` calls among `calls`, by the agent's name. */602 const agentCalls = (calls: readonly (readonly string[])[], verb: string) =>603 calls.flatMap((call) =>604 call[0] === "agent" && call[1] === verb605 ? [{ args: call, name: call[2] ?? "" }]606 : []607 );608 659-/** The pane each contributor's harness runs in: the layout's order over `w9:p1`, `w9:p2`, …. */609 const paneOf = new Map([610 ["wren", "w9:p1"],611 ["counter", "w9:p2"],612 ["marisol", "w9:p3"],97 unmodified lines710 .toSorted(byName)711 .map(({ args }) => args)712 );713 // wren's harness is Claude Code, started with the headless run's765- // safety flags: every tool allowed, no MCP server of the user's.714+ // safety flags: every tool allowed, no MCP server of the machine's own.715 expect(716 starts.find(({ name }) => name === "wren")?.args.slice(9)717 ).toStrictEqual([718 "--",140 unmodified lines859 })860 );861 });862 914-/** What herdr's detection text shows while Claude Code 2.1.293 asks whether to trust a new folder. */863 const trustQuestion = [864 " Accessing workspace:",865 "",866 " Quick safety check: Is this a project you created or one you trust?",1 unmodified line868 " ❯ No, exit",869 " Yes, I trust this folder",870 ].join("\n");871 924-/**925- * …and then whether to import the CLAUDE.md files above the clone, "No"926- * under the cursor (live, Enter left the clone's927- * `hasClaudeMdExternalIncludesApproved` false).928- */872+/** …and then whether to import the CLAUDE.md files above the clone, "No" under the cursor. */873 const importsQuestion = [874 " Allow external CLAUDE.md file imports?",875 "",876 " ❯ No, disable external imports",1 unmodified line878 ].join("\n");879 880 const [wren] = roster;881 938-/** wren's workspace for run `r1`. */882 const wrensWorkspace: AgentWorkspace = {883 clone: "/work/.swarm/r1/wren/clone",884 dir: "/work/.swarm/r1/wren",885 env: { [`${SLUG}_TOKEN`]: tokenOf("wren") },886 redacted: [`${SLUG}_TOKEN`],887 };888 946-/** The first of `queue`, taken off it unless it is the last. */889 const takeFrom = (queue: Ref.Ref<readonly string[]>) =>890 Ref.modify(queue, (all) => [891 all[0] ?? "",892 all.length > 1 ? all.slice(1) : all,893 ]);894 953-/**954- * wren's first attempt in herdr's pane `w9:p1`, where herdr finds Claude955- * Code blocked at startup: each `agent get` says the next of `states`956- * (`blocked` until the last), and each `agent read` shows the next of957- * `screens`. Files are kept in memory, so the TestClock moves as `clock`958- * says, deterministically.959- */895 const blockedStart = (input: {896 readonly states: readonly string[];897 readonly screens: readonly string[];898 readonly clock: Effect.Effect<void>;135 unmodified lines1034 })1035 );1036 });1037 1103-/**1104- * What dev-oscabriel's `/rpc` answered `watch` for burrow over plain JSON1105- * on 2026-10-08 (two of its eight events, the others cut): the frames at1106- * once, then the exit.1107- */1038 const replayed = [1039 '[{"_tag":"Chunk","requestId":"1","values":[',1040 '{"_tag":"AskOpened","at":"2026-10-08T05:21:35.148Z","seq":7,"ask":{"ask":"drop-legacy-fetch-burrow-notify","blockedBy":[],"claimed":false,"kind":"migrate","territory":"@burrow/notify","want":"@burrow/notify: 1 caller of legacyFetch → http.get"}},',1041 '{"_tag":"AskOpened","at":"2026-10-08T05:21:35.148Z","seq":8,"ask":{"ask":"drop-legacy-fetch-burrow-search","blockedBy":[],"claimed":false,"kind":"migrate","territory":"@burrow/search","want":"@burrow/search: 1 caller of legacyFetch → http.get"}}',1042 ']},{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',1043 ].join("");1044 1115-/**1116- * The framed stream's lines, as dev-oscabriel sends them over NDJSON: one1117- * frame per line. The first repeats an event the counter already heard1118- * (a claim, so a counter that heard it twice would say so).1119- */1045+/** The first frame repeats an event the counter already heard, so a double count would show. */1046 const streamed = [1047 '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:00:00.000Z","seq":8,"ask":"drop-legacy-fetch-burrow-billing","claimant":"tamsin"}]}',1048 '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:05:00.000Z","seq":9,"ask":"drop-legacy-fetch-burrow-auth","claimant":"wren"}]}',1049 `{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Pushed","at":"2026-10-08T12:06:00.000Z","seq":10,"ask":"drop-legacy-fetch-burrow-auth","head":"${"1".repeat(40)}"},{"_tag":"Released","at":"2026-10-08T12:07:00.000Z","seq":11,"ask":"drop-legacy-fetch-burrow-kit"}]}`,167 unmodified linesmodified:packages/config/test/swarm-loop.test.ts+3 added-37 removed
1-/**2- * The swarm's verdict loop: each contributor's harness started3- * headless on the brief, and every refusal their answer meets sent back into4- * the same session, at most three times. The loop reads outcomes only from5- * the contributor's `<cli> status --json`; a harness's output gives it the6- * session id, that the session settled, and the tokens it used.7- *8- * The harness output under `fixtures/swarm/harness-output/<harness>/` is9- * what each installed harness printed for one headless start and one resume10- * on 2026-10-08, its local paths replaced and the user's own setup (tool,11- * MCP, plugin and skill lists, pi's system prompt) left out.12- */1+// `fixtures/swarm/harness-output/<harness>/` is what each harness printed for2+// one headless start and one resume, its local paths replaced and the3+// machine's own setup (tool, MCP, plugin and skill lists) left out.4 import { NodeServices } from "@effect/platform-node";5 import { describe, expect, it } from "@effect/vitest";6 import { AnswerView } from "@repo/protocol/domain/answer";7 import { ClaimView } from "@repo/protocol/domain/claim";47 unmodified lines55 import type { AgentWorkspace } from "../../../scripts/lib/swarm/workspace.ts";56 import { Brand } from "../../brand/src/index.ts";57 import { repoRoot } from "./root.ts";58 68-/** The env names the CLI reads, spelled from the brand. */59 const SLUG = Brand.slug.toUpperCase();60 61 const token = "wren-token-0123456789abcdef0123456789abcdef";62 63 const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";64 65 const ask = AskId.make("drop-legacy-fetch-burrow-auth");66 77-/** A harness's recorded output: `start`, `resume`, or OpenCode's `refused-model`. */67 const recorded = (68 harness: Harness,69 run: "start" | "resume" | "refused-model"70 ) =>14 unmodified lines85 86 return text.split("\n").filter((line) => line !== "");87 }).pipe(Effect.provide(NodeServices.layer));88 100-/** Everything one recorded run's lines say, in order. */89 const heard = (driver: HarnessDriver, lines: readonly string[]) =>90 lines.flatMap(driver.parse);91 92 const sessionsIn = (events: readonly HarnessEvent[]) =>93 events.flatMap((event) =>94 HarnessEvent.$is("SessionStarted")(event) ? [event.id] : []95 );96 109-// The commits of four answers, and the landing of the last.97 const heads = ["1", "2", "3", "4"].map((digit) =>98 CommitSha.make(digit.repeat(40))99 );100 101 const landing = LandedSha.make(CommitSha.make("a".repeat(40)));102 116-/** One answer to the ask, `n` seconds after noon, with its outcome. */103 const answer = (n: number, outcome: Outcome): AnswerView => ({104 ask,105 at: DateTime.makeUnsafe(`2026-10-08T12:00:0${n}.000Z`),106 head: heads[n] ?? CommitSha.make("f".repeat(40)),43 unmodified lines150 })151 )152 );153 168-/** What `<cli> status --json` prints for wren with these answers. */154 const status = (...answers: readonly AnswerView[]) =>155 Schema.encodeSync(StatusJson)({156 command: "status",157 data: { answers, claims: [wrensClaim], handle: Handle.make("wren") },158 ok: true,159 v: 1,160 });161 177-/** One command the fake spawner was asked to run. */162 interface Spawned {163 readonly command: string;164 readonly args: readonly string[];165 readonly cwd: string | undefined;166 readonly env: Readonly<Record<string, string | undefined>>;167 readonly extendEnv: boolean | undefined;168 }169 186-/** How a scripted harness run goes: its stdout lines and exit code, or it never ends. */170 type HarnessRun =171 | { readonly lines: readonly string[]; readonly code?: number }172 | { readonly stalls: readonly string[] };173 174 const bytes = (text: string) => new TextEncoder().encode(text);175 193-/** A process handle that prints `stdout` and ends with `exitCode`. */176 const handleOf = (input: {177 readonly stdout: Stream.Stream<Uint8Array>;178 readonly exitCode: Effect.Effect<number>;179 }) =>10 unmodified lines190 stdout: input.stdout,191 unref: Effect.succeed(Effect.void),192 });193 212-/**213- * A `ChildProcessSpawner` that runs nothing. The workspace's CLI answers214- * `status` with the next of `statuses` (the last one again once they run215- * out); any other command is a harness, and plays the next of `harness`.216- */194 const fakeWorld = (script: {195 readonly harness: readonly HarnessRun[];196 readonly statuses: readonly string[];197 }) =>81 unmodified lines279 );280 }),281 });282 306-/** wren's workspace for run `r1`. */283 const dir = "/work/.swarm/r1/wren";284 285 const wrensWorkspace: AgentWorkspace = {286 clone: `${dir}/clone`,7 unmodified lines294 },295 redacted: [`${SLUG}_TOKEN`],296 };297 322-/** The swarm's own env: the user's HOME, and secrets no harness may see. */298 const swarmEnv = ConfigProvider.fromEnv({299 env: {300 CLAUDECODE: "1",301 CLOUDFLARE_API_TOKEN: "cf-secret",3 unmodified lines305 });306 307 const [wren, tamsin, ivo] = roster;308 334-/**335- * `runAgent` for `contributor` on burrow's auth child, over a fake world and336- * a file system in memory. It runs forked, so `clock` can move the TestClock337- * while it runs.338- */309 const agentRun = (input: {310 readonly harness: readonly HarnessRun[];311 readonly statuses: readonly string[];312 readonly contributor?: Assignment["contributor"];45 unmodified lines358 spawned: yield* world.spawned,359 };360 });361 392-/** The prompt a harness run carried: its last argument. */362 const promptOf = (run: Spawned | undefined) => run?.args.at(-1) ?? "";363 364 describe("the verdict loop", () => {365 it.effect(261 unmodified lines627 () =>628 Effect.gen(function* () {629 const start = yield* recorded("claude-code", "start");630 662- // The brief tells the agent to read status and push again, so one663- // session can push several answers before it settles.631 const { harnessRuns, result } = yield* agentRun({632 harness: [{ lines: start }],633 statuses: [634 status(168 unmodified lines803 })804 );805 });806 840-/** A workspace for the golden argv: `/work/.swarm/r1/<handle>`. */807 const goldenWorkspace = (handle: string): AgentWorkspace => ({808 clone: `/work/.swarm/r1/${handle}/clone`,809 dir: `/work/.swarm/r1/${handle}`,810 env: {},286 unmodified linesmodified:packages/config/test/swarm.test.ts+2 added-41 removed
1-/**2- * The swarm: its plan for a split family, its people, each3- * contributor's brief and workspace, and the run's summary file. The burrow4- * fixtures are what `<cli> asks` and `<cli> ask` printed for burrow's5- * `drop-legacy-fetch` family on the dev stage (2026-10-08).6- */1+// The burrow fixtures are what `<cli> asks` and `<cli> ask` printed for2+// burrow's `drop-legacy-fetch` family on a dev stage.3 import { NodeServices } from "@effect/platform-node";4 import { describe, expect, it } from "@effect/vitest";5 import { Ask, AskListing } from "@repo/protocol/domain/ask";6 import { ClaimView } from "@repo/protocol/domain/claim";47 unmodified lines54 const burrow = ProjectName.make("oscabriel/burrow");55 56 const ListedAsks = Envelope(Schema.Struct({ asks: Schema.Array(AskListing) }));57 62-/** What `<cli> claim <ask> --json` prints. */58 const Claimed = Envelope(Schema.Struct({ claim: ClaimView }));59 65-/** What `<cli> ask <ask> --json` prints, when it shows the ask. */60 const ShownAsk = Schema.Struct({61 command: Schema.Literal("ask"),62 data: Schema.Struct({ ask: Ask, brief: Schema.NonEmptyString }),63 ok: Schema.Literal(true),64 v: Schema.Literal(1),65 });66 73-/** A fixture's text. */67 const fixture = (name: string) =>68 Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;2 unmodified lines73 path.join("test", "fixtures", "swarm", name)74 );75 });76 84-/** burrow's open asks, as `<cli> asks --project burrow --json` listed them. */77 const burrowAsks = Effect.gen(function* () {78 const envelope = yield* Schema.decodeEffect(79 Schema.fromJsonString(ListedAsks)80 )(yield* fixture("list-asks.json"));272 unmodified lines353 expect(354 roster.flatMap(({ adapter, handle }) => (adapter ? [handle] : []))355 ).toStrictEqual(["pell"]);356 365- // An Anthropic id, OpenCode's GPT, an Amp mode, then pi's three.357 const models = [358 /^claude-/u,359 /^opencode-go\/gpt-/u,360 /^(?:low|medium|high|ultra)$/u,36 unmodified lines397 );398 });399 });400 410-/** The ask page `<cli> ask` printed for burrow's auth child. */401 const authPage = Effect.gen(function* () {402 const text = (yield* fixture("show-ask.json")).replaceAll(403 "{configDir}",404 Brand.configDir54 unmodified lines459 );460 });461 });462 473-/** One command a fake spawner was asked to run. */463 interface Spawned {464 readonly command: string;465 readonly args: readonly string[];466 readonly cwd: string | undefined;467 readonly env: Readonly<Record<string, string | undefined>>;468 }469 481-/**482- * A `ChildProcessSpawner` that runs nothing: it records each command and483- * answers with what `answer` gives it (exit 0 and no output by default).484- * `answer` also gets how many commands came before this one.485- */470 const fakeSpawner = (471 answer: (472 spawned: Spawned,473 before: number49 unmodified lines523 spawned: Ref.get(spawned),524 };525 });526 543-/** The env names the CLI reads, spelled from the brand. */527 const SLUG = Brand.slug.toUpperCase();528 529 const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";530 548-/** wren's claim of burrow's auth child, as `<cli> claim --json` gives it. */531 const wrensClaim = Schema.decodeSync(ClaimView)({532 ask: "drop-legacy-fetch-burrow-auth",533 base: "9998ebe62c2f282d148b1d806372484916cc2548",534 checkCommand: `${Brand.cli} check`,8 unmodified lines543 });544 545 const wrensToken = "wren-token-0123456789abcdef0123456789abcdef";546 565-/** What git prints when the gateway answers 404 for the fork: it is not made yet. */547 const forkNotMade = `remote: no repo ${wrensClaim.fork}548 fatal: repository '${wrensClaim.remote}/' not found549 `;550 570-/**571- * wren's workspace for run `r1`, below a temp dir, over a fake spawner572- * whose every clone exits `code`, or answers as `clone` says (given how573- * many clones came before it).574- */551 const wrensWorkspace = (552 code = 0,553 clone: (before: number) => {554 readonly code?: number;270 unmodified lines825 }).pipe(Effect.provide(NodeServices.layer))826 );827 });828 853-/** Why the flags `argv` make no run, or `accepted` when they make one. */829 const reasonOf = (argv: readonly string[]) =>830 optionsOf(argv).pipe(831 Effect.match({832 onFailure: ({ reason }) => reason,124 unmodified lines957 })958 );959 });960 986-/** What `main` prints, line by line, over a spawner that answers `asks` with the fixture. */961 const dryRun = (argv: readonly string[]) =>962 Effect.gen(function* () {963 const fs = yield* FileSystem.FileSystem;964 const swarm = yield* fs.makeTempDirectoryScoped();16 unmodified lines981 yield* main(argv).pipe(982 Effect.provide(fake.layer),983 Effect.provideService(SwarmDir, swarm),984 Effect.provideService(Console.Console, captured),1011- // No SESSION_TOKENS, nor any token: a dry run needs none.985 Effect.provideService(986 ConfigProvider.ConfigProvider,987 ConfigProvider.fromEnv({ env: {} })988 )153 unmodified lines1142 })1143 );1144 });1145 1173-/** A fictional person's token on the fake platform: never printed, never in an argv. */1146 const tokenOf = (handle: string) =>1147 `${handle}-token-0123456789abcdef0123456789ab`;1148 1177-/**1178- * `main` without `--dry-run`, over a fake platform: the CLI's `asks`, `ask`1179- * and `claim` answer from the fixtures, git succeeds, and `SESSION_TOKENS`1180- * holds `people`. The ledger and `.swarm/` are temp files. Any other command1181- * (a harness, a workspace's `status`) exits 1 unless `otherwise` answers it.1182- */1149 const fullRun = (1150 people: readonly string[],1185- /** The contributor whose claim the platform refuses with `AskFull`, if any. */1151 refused?: string,1152 otherwise?: (call: Spawned) => Option.Option<{1153 readonly code?: number;1154 readonly stdout?: string;108 unmodified lines1263 ),1264 Effect.result1265 );1266 1302- // The TestClock's epoch names the run.1267 const summary = `${swarm}/19700101-000000/agents.json`;1268 1269 return {1270 agents: (yield* fs.exists(summary))89 unmodified lines1360 ["marisol", 0, {}],1361 ["dagny", 0, {}],1362 ["pell", 0, {}],1363 ]);1400- // No claim, no fork: ivo's is never recorded for teardown.1364 expect(1365 ledger1366 .map(({ name }) => name.split("--").at(-1) ?? "")1367 .toSorted((one, other) => one.localeCompare(other))8 unmodified lines1376 const started = yield* fixture(1377 "harness-output/claude-code/start.jsonl"1378 ).pipe(Effect.provide(NodeServices.layer));1379 1417- // wren's Claude Code starts a session; the platform has no answer1418- // from wren yet, so the loop nudges once and asks status again.1380 const nothingYet = JSON.stringify({1381 command: "status",1382 data: { answers: [], claims: [], handle: "wren" },1383 ok: true,51 unmodified linesmodified:packages/config/test/teardown.test.ts+1 added-22 removed
1-/**2- * Teardown: `bun infra/teardown.ts` prints a plan, and only3- * `--apply` deletes it. The plan is the ledger's throwaways that the account4- * still lists, never a stage's own namespaces, never `witness`, never the5- * seeded examples, and never a name the ledger doesn't hold, whatever it is6- * called.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Console,33 unmodified lines38 const projects = "projects-dev-oscabriel";39 40 const layers = "layers-dev-oscabriel";41 49-/** One ledger line, made by `by` on the dev stage; a repo's names its namespace. */42 const made = (43 by: Created["by"],44 kind: Created["kind"],45 name: string,17 unmodified lines63 });64 65 const namespace = (name: string): Listed => ({ kind: "namespace", name });66 75-/** A smoke run's project and repos, and a `seed --as` swarm copy's. */67 const ledger: readonly Created[] = [68 made("smoke", "project", "smoke-r1"),69 made("smoke", "repo", "smoke-r1", projects),70 made("smoke", "repo", "smoke-r1--parse-year--bram", projects),7 unmodified lines78 ),79 made("seed", "repo", "datekit-805--maintainers", layers),80 ];81 91-/** What the account lists: every ledger repo, and much that isn't the ledger's. */82 const listed: readonly Listed[] = [83 repo("datekit"),84 repo("burrow"),85 repo("smoke-r1"),10 unmodified lines96 namespace("layers-demo"),97 namespace("witness"),98 ];99 110-/** Two imports of the preview repos, kept: each one's project and repo line. */100 const imports: readonly Created[] = [101 made("import", "project", "anyhow"),102 made("import", "repo", "anyhow", projects),103 made("import", "project", "ky"),159 unmodified lines263 ).toStrictEqual([]);264 });265 });266 278-/** A fresh ledger file in a temp dir, for the scope of one test. */267 const tempLedger = Effect.gen(function* () {268 const fs = yield* FileSystem.FileSystem;269 const path = yield* Path.Path;270 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "teardown-808-" });110 unmodified lines381 ]);382 });383 });384 397-/**398- * The account in memory: each namespace a memory `RepoHost` holding `repos`.399- * A namespace it doesn't hold, `witness` among them, dies when read.400- */385+/** A namespace it doesn't hold, `witness` among them, dies when read. */386 const memoryAccount = (repos: Readonly<Record<string, readonly string[]>>) =>387 Effect.gen(function* () {388 const read = yield* Ref.make<readonly string[]>([]);389 22 unmodified lines412 )413 )414 );415 431- /** Of `names`, those the namespace still holds. */416 const standing = (space: string, names: readonly string[]) =>417 Effect.gen(function* () {418 const host = yield* Effect.fromNullishOr(hosts.get(space)).pipe(419 Effect.orDie17 unmodified lines437 standing,438 };439 });440 457-/** A temp root with a ledger written from `entries` and no recording lock. */441 const tempRoot = (entries: readonly Created[]) =>442 Effect.gen(function* () {443 const fs = yield* FileSystem.FileSystem;444 const path = yield* Path.Path;6 unmodified lines451 452 return { ledgerFile, lock: path.join(dir, ".recording") };453 });454 472-/** `teardown(argv)` over `account`: how it ended, and what it printed. */455 const tornDown = (456 argv: readonly string[],457 account: TeardownAccount["Service"],458 files: { readonly ledgerFile: string; readonly lock: string }18 unmodified lines477 478 return { printed, result };479 });480 499-/** The dev stage's two namespaces as a smoke run, a swarm copy and the seed left them. */481 const devRepos = {482 [layers]: ["datekit--maintainers", "datekit-805--maintainers"],483 [projects]: [484 "datekit",6 unmodified lines491 "w3live-muyjz31t",492 ],493 };494 514-/** The ledger: `ledger` above, one repo already gone, and one in `witness`. */495 const devLedger: readonly Created[] = [496 ...ledger,497 made("smoke", "repo", "smoke-r0", projects),498 made("smoke", "repo", "smoke-r9", "witness"),132 unmodified lines631 it.live(632 "lists the kept imports apart, each once, never in the plan, and deletes none of them with --apply",633 () =>634 Effect.gen(function* () {655- // A `--tags` backfill records anyhow's repo a second time.635 const files = yield* tempRoot([636 ...devLedger,637 ...imports,638 {68 unmodified linesmodified:packages/config/test/verify.test.ts-2 removed
17 unmodified lines18 .scripts;19 });20 21 describe("verify", () => {22- // The gate guards the product's own behaviour: the lockfile, lint and23- // format, types, tests, the brand and the Workers' byte budgets.22 it.live("runs the product's checks, in order", () =>23 Effect.gen(function* () {24 const scripts = yield* rootScripts;25 28 unmodified linesmodified:packages/config/test/web-wiring.test.ts+4 added-23 removed
1-/**2- * The web Worker's wiring, read as data: it reaches the platform3- * only through the `PLATFORM` service binding and holds no storage binding of4- * any kind, in any stage (AGENTS.md principle 7); `#backend` picks the5- * in-process backend under `development` and the binding otherwise; the byte6- * alarm measures it; and the examples stay outside the workspaces.7- *8- * Each file's presence is asserted before it is read, so a missing file is a9- * failed assertion, not a load error.10- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Effect, FileSystem, Path, Schema } from "effect";4 7 unmodified lines12 } from "../../../infra/stages.ts";13 import { budgets, workers } from "../../../scripts/startup-budget.ts";14 import { repoRoot } from "./root.ts";15 26-/** A file under the repo root, as text, once its presence is asserted. */16 const presentText = (file: string) =>17 Effect.gen(function* () {18 const fs = yield* FileSystem.FileSystem;19 const path = yield* Path.Path;3 unmodified lines23 24 return yield* fs.readFileString(at);25 }).pipe(Effect.provide(NodeServices.layer));26 38-/** A JSON (or JSONC) file under the repo root, decoded by `schema`. */27 const presentJson = <S extends Schema.Top>(file: string, schema: S) =>28 Effect.flatMap(presentText(file), (text) =>29 Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(blankJsonc(text))30 );31 44-/** The binding kinds that would reach storage or run code: none in the web. */32 const STORAGE = [33 "artifacts",34 "d1_databases",35 "durable_objects",32 unmodified lines68 const RootManifest = Schema.Struct({69 workspaces: Schema.Struct({ packages: Schema.Array(Schema.String) }),70 });71 85-/**86- * Whether a workspace glob's parts match a folder's segments: `*` is one87- * segment, `**` any number of them.88- */72 const globMatches = (73 parts: readonly string[],74 segments: readonly string[]75 ): boolean => {67 unmodified lines143 }144 })145 );146 164- // ADR 0026: the edge keeps the web's answers only behind its entry, which165- // decides what may be kept; `vite dev` keeps nothing; and a kept page166- // never outlives its Worker version, whose hashed assets it names.147+ // The edge keeps the web's answers only behind its entry, which decides what148+ // may be kept; `vite dev` keeps nothing; and a kept page never outlives its149+ // Worker version, whose hashed assets it names.150 it.effect(151 "enters through src/server.ts, and turns Workers Cache on in each stage alone, per version",152 () =>153 Effect.gen(function* () {72 unmodified lines226 it("measures the web Worker", () => {227 expect(workers.map(({ dir }) => dir)).toContain("apps/web");228 });229 247- // Each Worker grows on its own, so each has limits of its own, about248- // 15% above its bundle as last measured (the platform's entry, its only249- // module, 1,679,675: both its limits at 1,900,000, 13% above).230+ // Each Worker has limits of its own, about 15% above its bundle as last measured.231 it("holds each Worker it measures to limits of its own", () => {232 expect(budgets).toStrictEqual({233 "apps/platform": { entry: 1_900_000, javascript: 1_900_000 },234 "apps/sandbox": { entry: 656_000, javascript: 656_000 },28 unmodified lines