Skip to content
Myr

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

84 files+128 added−1847 removed

modified:packages/agent-kit/src/docs/answer-an-ask.ts-5 removed
modified:packages/agent-kit/src/docs/connect-an-agent.ts-6 removed
modified: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 */1import { Option } from "effect";29/** A guide, written for a person doing one job, or a page of the reference. */3export type DocPart = "guide" | "reference";412/** What names a page, before it is written: enough for a list or a head. */5export interface DocEntry {6 readonly slug: string;7 readonly title: string;8 readonly summary: string;9 readonly part: DocPart;10}1120/** Every page as the index lists it, guides first. */12export const docEntries = [13 {14 part: "guide",15 slug: "start-here",
77 unmodified lines
93 title: "Imported projects",94 },95] as const satisfies readonly DocEntry[];96106/** A page's slug: the last segment of its address. */97export type DocSlug = (typeof docEntries)[number]["slug"];98109/** The page at `slug` as a list or a head names it; none for a slug no page has. */99export 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
modified:packages/agent-kit/src/docs/imported-note.ts-5 removed
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 */1import { ProjectKey, ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";2import { Option } from "effect";311/**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 */4export interface ImportedProject {5 readonly name: ProjectName;6 readonly key: ProjectKey;7 readonly url: string;
13 unmodified lines
21 name: ProjectName.make(`${Option.getOrThrow(sourceNamespaceOf(url))}/${key}`),22 url,23});2437/** Every imported project, in the order they were imported. */25export const importedProjects: readonly ImportedProject[] = [26 imported(27 "anyhow",28 "https://github.com/dtolnay/anyhow",
211 unmodified lines
modified: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 */1import { Option } from "effect";23import { answerAnAsk } from "./answer-an-ask.ts";4import { connectAnAgent } from "./connect-an-agent.ts";
18 unmodified lines
23export type { DocEntry, DocPart, DocSlug } from "./entries.ts";2425export type { DocInput, DocPage } from "./page.ts";2633/** Every page, guides first, in the order the index lists them. */27const sources: readonly DocSource[] = [28 startHere,29 answerAnAsk,30 runAProject,
7 unmodified lines
38 mcpPage,39 importedPage,40];4149/** Every page, written for `input`. */42export const docPages = (input: DocInput): readonly DocPage[] =>43 sources.flatMap((source) =>44 Option.toArray(45 Option.map(docEntry(source.slug), (entry) =>
1 unmodified line
47 )48 )49 );5059/** The page at `slug`, written for `input`; none for a slug no page has. */51export const docPage = (52 input: DocInput,53 slug: string54): Option.Option<DocPage> =>
5 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";23import type { CommandDoc } from "../command-doc.ts";4import { code, page } from "../text.ts";5import type { DocEntry, DocSlug } from "./entries.ts";612/** What every page is written from. */7export interface DocInput {8 readonly commands: readonly CommandDoc[];9 readonly platformUrl: string;10 readonly webUrl: string;11}1219/** One page as the web serves it. */13export interface DocPage extends DocEntry {14 readonly markdown: string;15}1624/** One page before it is written: its slug, and its body's lines from the input. */17export interface DocSource {18 readonly slug: DocSlug;19 readonly body: (input: DocInput) => readonly string[];20}2130/** `source` written for `input`, under what names it. */22export const written = (23 entry: DocEntry,24 source: DocSource,25 input: DocInput
7 unmodified lines
33 ...source.body(input),34 ]),35});3646/** A command as typed, in a code span: `<cli> claim <ask> --project <owner>/<name>`. */37export const cli = (words: string) => code(`${Brand.cli} ${words}`);3849/** A block of shell commands. */39export const shell = (...lines: readonly string[]) => [40 "```sh",41 ...lines,42 "```",43];4456/** A section's lines without its own `## ` heading, for a page that is that section. */45export const withoutHeading = (lines: readonly string[]) => {46 const [first, blank, ...rest] = lines;4748 return first?.startsWith("## ") === true && blank === "" ? rest : lines;
1 unmodified line
modified: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 */1import { Brand } from "@repo/brand";2import {3 Contracts,4 Description,
10 unmodified lines
15import { importedProjects } from "./imported.ts";16import type { DocSource } from "./page.ts";17import { withoutHeading } from "./page.ts";1826/** A command as typed: its words, then its positionals in angle brackets. */19const usage = ({ path, positional }: CommandDoc) =>20 code(21 [Brand.cli, ...path, ...positional.map((name) => `<${name}>`)].join(" ")22 );
35 unmodified lines
58 body: () => withoutHeading(events()),59 slug: "events",60};6170/** Each contract served over MCP: its tool name, what it does, and whether it only reads. */62const mcpTools = () =>63 [...Contracts.requests.values()].flatMap(({ _tag, annotations }) =>64 Context.get(annotations, Surfaces).includes("mcp")65 ? [
36 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import { sourceHosts } from "@repo/protocol/ids";34import { code } from "../text.ts";
87 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";23import type { DocSource } from "./page.ts";4import { cli } from "./page.ts";
45 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import { PolicyInput } from "@repo/protocol/domain/policy";3import { groups } from "@repo/protocol/refusal";4import { Array as Arr, Schema } from "effect";
4 unmodified lines
9import { span } from "./sections.ts";10import { code, listed, page, printJson, table } from "./text.ts";1112export 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}1718export 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}2324export 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}2956/** Whether the CLI has the command whose words are `words`. */30const has = (commands: readonly CommandDoc[], words: string) =>31 Arr.some(commands, ({ path }) => path.join(" ") === words);3260/** JSON as a snippet holds it: the generators' printing, without its final newline. */33const json = (value: Parameters<typeof printJson>[0]) =>34 printJson(value).trimEnd();3536const remoteMcp = ({ platformUrl }: SetupInput): SetupChannel => ({
79 unmodified lines
116 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});119148/** Every channel, in the order the page shows them; stdio only when the CLI has `mcp`. */120export 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];127157// --- Synopsis -------------------------------------------------------------------158159/** One command as a synopsis gives it: how it is typed, and what it does. */128export 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}132166/** Every command, one line each, in the catalog's order. */133export const synopsis = (134 commands: readonly CommandDoc[]135): readonly SynopsisLine[] =>136 commands.map(({ flags, path, positional, summary }) => ({
7 unmodified lines
144 .map((flag) => `[${flag}]`),145 ].join(" "),146 }));147182// --- Endpoints ------------------------------------------------------------------183184/** One address an agent reads or calls. */148export 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}153193/** Every address an agent reads, the web's first, then the platform's. */154export const agentEndpoints = ({155 platformUrl,156 webUrl,157}: Pick<SetupInput, "platformUrl" | "webUrl">): readonly Endpoint[] => [
43 unmodified lines
201 what: "Git over smart HTTP: clone a project, push an answer to your fork.",202 },203];204245// --- Limits ---------------------------------------------------------------------246247/** One limit and its value, as a person says them. */205export interface Limit {206 readonly limit: string;207 readonly value: string;208}209253/** What a policy that sets nothing takes: the defaults its schema fills in. */210const policyDefaults = () =>211 Schema.decodeSync(212 Schema.Struct({213 budget: PolicyInput.fields.budget,
1 unmodified line
215 claims: PolicyInput.fields.claims,216 })217 )({});218263/**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 */219export const agentLimits = (): readonly Limit[] => {220 const { budget, caps, claims } = policyDefaults();221222 return [
24 unmodified lines
247 },248 ];249};250299// --- Markdown -------------------------------------------------------------------300251const snippetLines = ({ label, language, text }: SetupSnippet) => [252 `${label}:`,253 "",254 `\`\`\`${language}`,
50 unmodified lines
305 ),306 "",307];308359/** The whole reference as one Markdown document: `/agents.md`. */309export const agentSetupMarkdown = (input: SetupInput) =>310 page([311 "# For agents",312 "",
10 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import type { Policy } from "@repo/protocol/domain/policy";3import type { LandedSha, ProjectName } from "@repo/protocol/ids";4import { Effect, Option } from "effect";
2 unmodified lines
7import { contributeSkillName, contributeSkillPaths } from "./project-skill.ts";8import { lanesOf, loopSteps, unfencedNorms } from "./sections.ts";9import { code, listed, page } from "./text.ts";1017/** The block: its two marker lines and the text between them. */11export interface AgentsBlock {12 readonly begin: string;13 readonly end: string;14 readonly body: string;
41 unmodified lines
56 ...unfencedNorms(policy.agents),57 ]);58};5967/**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 */60export const agentsBlock = (input: {61 readonly project: ProjectName;62 readonly policy: Policy;63 readonly landed: LandedSha;
8 unmodified lines
72 }))73 );74};7588/** The block as a file holds it: the markers on lines of their own. */76const written = (block: AgentsBlock) =>77 `${block.begin}\n${block.body}${block.body.endsWith("\n") ? "" : "\n"}${block.end}`;7892/** Where an existing block starts and ends, whatever hash its first marker carries. */79const locate = (80 existing: string,81 end: string82): Option.Option<{ readonly from: number; readonly to: number }> => {
12 unmodified lines
9596 return marker ? Option.some({ from, to: to + end.length }) : Option.none();97};98113/** What goes between a file's last text and an appended block: one blank line. */99const separator = (existing: string) => {100 if (existing === "" || existing.endsWith("\n\n")) {101 return "";102 }103104 return existing.endsWith("\n") ? "\n" : "\n\n";105};106122/**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 */107export 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 lines
modified: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 */1import {2 Cli,3 Description,4 NeedsApproval,
3 unmodified lines
8import type { Contracts } from "@repo/protocol/contracts";9import { Array as Arr, Context, Order, Schema, SchemaAST } from "effect";1011export 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});2122export type CommandDoc = typeof CommandDoc.Type;2336/**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 */24export const localCommandDocs: readonly CommandDoc[] = [25 {26 flags: [27 "--url",
129 unmodified lines
157 "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];160178/**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 */161const standIns = new Set(162 localCommandDocs.flatMap(({ contract, path }) =>163 contract === undefined ? [] : [path.join(" ")]164 )165);166188/** A payload's field names, in the schema's order; none for a payload of no fields. */167const fieldsOf = (ast: SchemaAST.AST) =>168 SchemaAST.isObjects(ast)169 ? ast.propertySignatures.map(({ name }) => String(name))170 : [];171194/**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 */172export const contractCommandDocs = (173 group: typeof Contracts174): readonly CommandDoc[] =>175 [...group.requests.values()].flatMap((rpc) => {
40 unmodified lines
216const byWords = Order.mapInput(Order.String, (doc: CommandDoc) =>217 doc.path.join(" ")218);219250/**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 */220export 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 */1import type { ProjectListing } from "@repo/protocol/domain/front-page";2import { Option } from "effect";34import type { CommandDoc } from "./command-doc.ts";
9 unmodified lines
14import { code, page } from "./text.ts";1516type Commands = readonly CommandDoc[];1729// --- Guides ---------------------------------------------------------------------3018const guides = (commands: Commands, platformUrl: string) => [19 "## Guides",20 "",21 "### Recover from `StaleBase`",
36 unmodified lines
58 ` Claiming the ask again (${each}) returns the claim you hold, with its remote.`59 ).join("")}`,60];6175/**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 */62export const fullLlms = (input: {63 readonly commands: Commands;64 readonly projects: readonly ProjectListing[];65 readonly platformUrl: string;
10 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import { LandedSha } from "@repo/protocol/ids";3import { Array as Arr, Effect, Option, Schema } from "effect";412/** One file a generator makes: where it goes, and every byte of it. */5export interface GeneratedFile {6 readonly path: string;7 readonly content: string;8}918/** What a managed file says about itself, and the body it says it of. */10export 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 line
17 [...new Uint8Array(bytes)]18 .map((byte) => byte.toString(16).padStart(2, "0"))19 .join("");2032/**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 */21export 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 );2845// 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.31const quoted = (value: string) => JSON.stringify(value);3250/**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 */33export const frontmatter = (input: {34 readonly name: string;35 readonly description: string;36 readonly landed: Option.Option<LandedSha>;
24 unmodified lines
61const decodeQuoted = Schema.decodeUnknownOption(62 Schema.fromJsonString(Schema.String)63);6487/** A frontmatter value: a quoted one decoded, a plain one as it stands. */65const valueOf = (raw: string) =>66 raw.startsWith('"') ? decodeQuoted(raw) : Option.some(raw);6791/** The `key: value` lines indented under `metadata:`, by key. */68const metadataOf = (head: string) => {69 const lines = head.split("\n");70 const start = lines.indexOf("metadata:");71
15 unmodified lines
87};8889const decodeLanded = Schema.decodeUnknownOption(LandedSha);90115/** A Markdown file's frontmatter and the body after it; none without one. */91const sections = (file: string) => {92 if (!file.startsWith(OPEN)) {93 return Option.none();94 }
9 unmodified lines
104};105106const DESCRIPTION = "description: ";107133/**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 */108export 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 lines
115 Option.flatMap(valueOf)116 )117 );118150/**151 * What a file this platform manages says about itself: none for a file152 * without the frontmatter, or one someone else manages.153 */119export const readManaged = (file: string): Option.Option<Managed> => {120 const split = sections(file);121122 if (Option.isNone(split)) {
16 unmodified lines
139 ),140 });141};142178/**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 */143export const isStale = (144 onDisk: string,145 current: GeneratedFile146): Effect.Effect<
29 unmodified lines
modified: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 */1import { Schema } from "effect";28/** When a harness asks the gate's policy: at the session's start, before a tool runs, at Stop. */3export const HookEvent = Schema.Literals([4 "session-start",5 "pre-tool-use",6 "stop",7]);89export type HookEvent = typeof HookEvent.Type;1017/** The Claude Code hook event each one answers. */11export const claudeEventOf = {12 "pre-tool-use": "PreToolUse",13 "session-start": "SessionStart",14 stop: "Stop",15} as const satisfies Record<HookEvent, "SessionStart" | "PreToolUse" | "Stop">;1624/**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 */17export const guardedTools = [18 "Edit",19 "Write",20 "MultiEdit",
2 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import type { AskListing } from "@repo/protocol/domain/ask";3import type { ProjectListing } from "@repo/protocol/domain/front-page";4import type { ProjectName } from "@repo/protocol/ids";
6 unmodified lines
11type Command = CommandDoc;1213type Commands = readonly CommandDoc[];1433/** The MCP protocol the platform serves over HTTP. */15export const MCP_PROTOCOL = "2026-07-28";1636/** Each posture as GLOSSARY.md names it. */17const postureWords = {18 open: "Open",19 openCore: "Open core",20 openOnSchedule: "Open on schedule",
5 unmodified lines
2627const counted = (count: number, one: string) =>28 `${count} ${one}${count === 1 ? "" : "s"}`;2950/** The lines as one document, ending in a newline. */30const page = (lines: readonly string[]) => `${lines.join("\n")}\n`;3153/** What a placeholder stands for in a command line, if the page knows it. */32interface Known {33 readonly project?: string;34}3558/** The command whose words are `words`, if the catalog has it. */36const commandOf = (commands: Commands, words: string) =>37 Arr.findFirst(commands, ({ path }) => path.join(" ") === words);3862/**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 */39const usage = (40 command: Command,41 known: Known = {},42 flags: readonly ("ask" | "project")[] = []
12 unmodified lines
55 ),56 ].join(" ");57};5886/** `words` as typed, with `flags`, when the catalog has the command. */59export const typed = (60 commands: Commands,61 words: string,62 known: Known,
2 unmodified lines
65 Option.map(commandOf(commands, words), (command) =>66 code(usage(command, known, flags))67 );6897/** The sentence `make` writes around a typed command, or nothing without it. */69export const withCommand = (70 command: Option.Option<string>,71 make: (typedCommand: string) => string72) => Option.toArray(Option.map(command, make));73103/**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 */74const takeAnAsk = (commands: Commands, known: Known) => {75 const front = typed(commands, "front", known);76 const asks = typed(commands, "asks", known, ["project"]);77
35 unmodified lines
113 "",114 ];115};116151/** What a command row adds to its description. */117const notes = ({ needsApproval, readOnly }: Command) => [118 ...(readOnly ? ["Only reads."] : []),119 ...(needsApproval ? [`Runs only with ${code("--yes")}.`] : []),120];121157/** Every command, one line each, in the catalog's order. */122const commandList = (commands: Commands) => [123 "## Commands",124 "",125 ...commands.map(
2 unmodified lines
128 ),129 "",130];131168/** Where a project's page is on the web host. */132const projectPage = (webUrl: string, project: string) => `${webUrl}/${project}`;133171/** What a project's line says of it: its posture and its open asks. */134const projectFacts = (listing: ProjectListing) =>135 `${postureWords[listing.posture]}, ${counted(listing.openAsks, "open ask")}.`;136175/**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 */137const projectLine = (138 platformUrl: string,139 webUrl: Option.Option<string>,140 listing: ProjectListing
4 unmodified lines
145 onSome: (web) =>146 `- [${listing.project}](${projectPage(web, listing.project)}/llms.txt): ${projectFacts(listing)}`,147 });148191/**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 */149export 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);158159 return page([160 `# ${Brand.name}`,
52 unmodified lines
213 : projects.map((listing) => projectLine(platformUrl, webUrl, listing))),214 ]);215};216267/** What an ask's line adds after its want: its kind and territory, then whether it can be taken. */217const 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 line
222 ? []223 : [`Waits for ${listing.blockedBy.map(code).join(", ")}.`]),224];225277/** An ask's want as a sentence of its own, however it was punctuated. */226const sentence = (text: string) => `${text.replace(/[.\s]+$/u, "")}.`;227228const askLine = (webUrl: string, project: string, listing: AskListing) =>229 `- [${listing.ask}](${projectPage(webUrl, project)}/asks/${listing.ask}.md): ${[sentence(listing.want), ...askNotes(listing)].join(" ")}`;230283/**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 */231export const indexBanner = (input: {232 readonly webUrl: string;233 readonly project?: ProjectName;234}) => {
1 unmodified line
236237 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};239299/** `banner` under `text`'s `#` title, or on top of a text that has none. */240export const underTitle = (text: string, banner: string) => {241 const end = text.indexOf("\n");242243 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};247308/** `/<owner>/<name>/llms.txt`: the project, its posture, how to clone it, its open asks and how to take one. */248export const projectLlms = (input: {249 readonly listing: ProjectListing;250 readonly asks: readonly AskListing[];251 readonly commands: Commands;
23 unmodified lines
275 ...takeAnAsk(commands, { project }).slice(0, -1),276 ]);277};278340/**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 */279export const missingProjectLlms = (input: {280 readonly project: Option.Option<ProjectName>;281 readonly webUrl: string;282}) =>
5 unmodified lines
288 onSome: (project) => `No project named ${code(project)}`,289 })} is on ${Brand.name}. Every project is listed at ${input.webUrl}/llms.txt.`,290 ]);291357/**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`.294export const mcpCard = (input: { readonly platformUrl: string }) => ({295 authentication: {296 required: true,297 resource_metadata: `${input.platformUrl}/.well-known/oauth-protected-resource`,
10 unmodified lines
modified: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 */1export { agentsBlock, upsertAgentsBlock } from "./agents-block.ts";23export type { AgentsBlock } from "./agents-block.ts";4
30 unmodified lines
modified: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 */1export 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 */1import { Brand } from "@repo/brand";2import type { ProjectEvent } from "@repo/protocol/domain/event";34import { refusalCatalog } from "./refusals.ts";
2 unmodified lines
7const cli = (...words: readonly string[]) => [Brand.cli, ...words].join(" ");89const notesRef = `refs/notes/${Brand.slug}`;1021/** How an answer is pushed to a claim's fork: a function, so loading this module runs nothing. */11export const pushAnswer = () => code(`git push ${Brand.slug} HEAD:main`);1224/** What the gateway says when git is not let in: `<reason>; sign in with <cli> login`. */13const signIn = (reason: string) => `${reason}; sign in with ${cli("login")}`;1427// --- Refusals -----------------------------------------------------------------2829/** Every refusal of the closed union, with its group, retry, exit code, `next` and repair. */15export 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 lines
30 ),31 "",32];3349// --- Git here -------------------------------------------------------------------5051/** How git reaches the platform's repos, who reads and pushes each, and what it says when it refuses. */34export 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 lines
78 `- 404 ${code("not a git endpoint")}: the path is not one git asks for.`,79 "",80];81100// --- How a landing happens ----------------------------------------------------101102/** How a checked answer becomes a commit on `main`. */82export 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 lines
89 "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];92114// --- Events ---------------------------------------------------------------------115116/** What each event says happened, one line per tag of `ProjectEvent`. */93const 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 lines
107 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>;110135/** One line per event a watcher of a project hears. */111export 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 lines
modified: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.4import { Brand } from "@repo/brand";5import { Array as Arr, Effect, Option, Order } from "effect";67import type { CommandDoc } from "./command-doc.ts";
4 unmodified lines
12import { loopSteps, unfencedSection } from "./sections.ts";13import { code, page, printJson, table } from "./text.ts";1415export 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}1920const SKILL = `skills/${Brand.slug}/SKILL.md`;2122const PLUGIN = `plugins/${Brand.slug}`;2336// --- The platform's skill ------------------------------------------------------3724const 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.`;2526const usage = ({ path, positional }: CommandDoc) =>27 code(
56 unmodified lines
84 ...refusalSection(),85 ...unfencedSection(),86 ]);87102/**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.90export const platformSkillParts = (input: PlatformInput) => ({91 body: platformBody(input),92 description,93 name: Brand.slug,
1 unmodified line
9596const skillFile = (input: PlatformInput) =>97 frontmatter({ ...platformSkillParts(input), landed: Option.none() });98117/** `skills/<slug>/SKILL.md`: the platform's skill, which comes from no landing. */99export const platformSkill = (100 input: PlatformInput101): Effect.Effect<readonly GeneratedFile[]> =>102 skillFile(input).pipe(Effect.map((content) => [{ content, path: SKILL }]));103123// --- The MCP server, as each client's config names it ----------------------------124125/**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.105const servers = {106 "agent-plugins": {107 remote: (url: string) => ({ type: "streamable-http", url }),108 stdio: { args: ["mcp"], command: Brand.cli, type: "stdio" },
9 unmodified lines
118} as const;119120export type McpFlavour = keyof typeof servers;121148/**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 */122export const mcpServersFor = (123 platformUrl: string | undefined,124 flavour: McpFlavour125) => ({
2 unmodified lines
128 ? servers[flavour].stdio129 : servers[flavour].remote(`${platformUrl}/mcp`),130});131164// --- The Claude Code plugin ------------------------------------------------------165132const hookCommand = (event: HookEvent) => ({133 hooks: [{ command: `${Brand.cli} hook ${event} --json`, type: "command" }],134});135170/**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.137const hooksJson = () =>138 printJson({139 hooks: Object.fromEntries(140 HookEvent.literals.map((event) => [
11 unmodified lines
152153const homepage = (platformUrl: string | undefined) =>154 platformUrl === undefined ? {} : { homepage: platformUrl };155195/**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 */156export const claudePlugin = (157 input: PlatformInput158): Effect.Effect<readonly GeneratedFile[]> =>159 skillFile(input).pipe(
16 unmodified lines
176 { content: hooksJson(), path: `${PLUGIN}/hooks/hooks.json` },177 ])178 );179224// --- The Agent Plugins bundle ----------------------------------------------------225180const SCHEMAS = "https://agent-plugins.org/schemas/1.0.0";181228/**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 */182export const agentPluginsBundle = (183 input: PlatformInput184): Effect.Effect<readonly GeneratedFile[]> =>185 skillFile(input).pipe(
20 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import type { Policy } from "@repo/protocol/domain/policy";3import { keyOf } from "@repo/protocol/ids";4import type { LandedSha, ProjectName } from "@repo/protocol/ids";
11 unmodified lines
16 unfencedSection,17} from "./sections.ts";18import { code, page } from "./text.ts";1926/**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 */20export const contributeSkillName = (project: ProjectName) =>21 `${keyOf(project)}-contribute`;2235/** Where the skill goes: the folders harnesses read project skills from, `.agents` first. */23export const contributeSkillPaths = (project: ProjectName) => {24 const skill = `skills/${contributeSkillName(project)}/SKILL.md`;2526 return [`.agents/${skill}`, `.claude/${skill}`] as const;27};2842/** What the skill's frontmatter says it is for. */29export 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.`;3146/** The skill's body: the loop, then the rules from the policy, then what nothing checks yet. */32export const contributeBody = (project: ProjectName, policy: Policy) =>33 page([34 `# Contribute to ${project}`,35 "",
13 unmodified lines
49 ...refusalSection(),50 ...unfencedSection(policy.agents),51 ]);5268/**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 */53export const projectSkill = (input: {54 readonly project: ProjectName;55 readonly policy: Policy;56 readonly landed: LandedSha;
11 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import { ExitCode, exitCodeOfTag, precedence } from "@repo/protocol/exit-code";3import { groups } from "@repo/protocol/refusal";4import { Exit, Predicate, SchemaAST } from "effect";56import { code, table } from "./text.ts";717/** The groups whose refusals an answer can meet, from claim to verdict. */8const answerGroups = [9 "Push and claim",10 "Shape",11 "Merge",
13 unmodified lines
25type AnswerTag = InstanceType<AnswerMember>["_tag"];2627type Tag = InstanceType<Member>["_tag"];2839/**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 */29interface Repair {30 readonly todo: string;31 readonly next?: string;32 readonly nextNames?: string;
64 unmodified lines
97 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>;100115/**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 */101const elsewhere = {102 DecisionClosed: {103 todo: "Nothing to decide: it was taken already, or expired to its default.",104 },
72 unmodified lines
177 ...repairOf,178 ...Object.entries(elsewhere),179]);180199/** A field's value when the constructor fills it in, as it does a fixed `next`. */181const constructorDefault = (ast: SchemaAST.AST) => {182 const fill = ast.context?.constructorDefault;183184 return fill !== undefined &&
3 unmodified lines
188 ? fill.value189 : undefined;190};191211/** One refusal an answer can meet, as the skills list it. */192export 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 lines
206 ? (repair?.nextNames ?? "")207 : code(repair.next);208};209232/** One member's row, from its schema and the repair `repairTable` gives it. */210const rowOf = (211 member: Member,212 repairTable: ReadonlyMap<string, Repair>213): AnswerRefusal => {
9 unmodified lines
223 todo: repair?.todo ?? "",224 };225};226250/** Every refusal an answer can meet, in the union's order. */227export 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));232257/** One refusal of the closed union, with the group the union files it under. */233export interface CatalogRow extends AnswerRefusal {234 readonly group: string;235}236262/** Every refusal of the closed union, every group, in the union's order. */237export const refusalCatalog = (): readonly CatalogRow[] =>238 groups.flatMap((group) =>239 group.members.map((member: Member) => ({240 ...rowOf(member, everyRepairOf),241 group: group.name,242 }))243 );244271/** What each code the CLI exits with tells its caller, in the order a caller reads them. */245const 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 lines
258 [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>;261289/** The CLI's exit codes, as `/llms-full.txt` lists them. */262export 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 lines
270 ),271 "",272];273302/** The refusals section every skill carries. */274export 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 lines
modified: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 */1import { Brand } from "@repo/brand";2import { RatchetMeasure } from "@repo/protocol/domain/check";3import type { AskKind, CheckKind, ClaimRule } from "@repo/protocol/domain/kind";4import type { Policy } from "@repo/protocol/domain/policy";
8 unmodified lines
13const remote = Brand.slug;1415const notesRef = `refs/notes/${Brand.slug}`;1623// --- The loop ----------------------------------------------------------------2425/**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 */17export 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 lines
29 { ms: 60_000, one: "minute" },30 { ms: 1000, one: "second" },31] as const;3246/** A span as a person says it: `2 hours`, `1 day`, `90 minutes`. */33export const span = (ms: number) => {34 const unit = unitsOfTime.find((each) => ms % each.ms === 0) ?? unitsOfTime[4];3536 const count = Math.round(ms / unit.ms);3738 return `${count} ${unit.one}${count === 1 ? "" : "s"}`;39};4055/** What the project's policy says about holding a claim. */41export 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.`;4359// --- What an answer may change -------------------------------------------------6044const byName = <A>(name: (item: A) => string) =>45 Order.mapInput(Order.String, name);4647const judgeLines = (judge: Policy["judge"]) => [
20 unmodified lines
68 (ratchet) =>69 `- ${code(ratchet.name)}${ratchet.territory === undefined ? "" : ` in ${code(ratchet.territory)}`}: ${measureOf(ratchet.measure)}`70 );7189/**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 */72export const changeSection = (policy: Policy) => {73 const { judge, modules, ratchets, weakening } = policy;7475 const publicFiles = modules.some(
55 unmodified lines
131 "",132 ];133};134157// --- The run block -------------------------------------------------------------158159/** The run block's lanes, by name. */135export const lanesOf = (run: RunBlock) =>136 Arr.sort(137 Object.entries(run.checks),138 byName(([lane]: readonly [string, string]) => lane)
18 unmodified lines
157 ),158 "",159];160186// --- Ask kinds -----------------------------------------------------------------187161const 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 lines
219 byName((kind: AskKind) => kind.name)220 ).flatMap((kind) => kindLines(kind, policy)),221 ];222250// --- No fence yet ----------------------------------------------------------------251252/**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 */223export 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 lines
modified: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 */1import { Array as Arr, Order, Predicate } from "effect";2import type { Schema } from "effect";39/** A Markdown page: its lines joined, ending in exactly one newline. */4export const page = (lines: readonly string[]) =>5 `${lines.join("\n").replace(/\n+$/u, "")}\n`;613/**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 */7export 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 lines
13 ? `${fence}${text}${fence}`14 : `${fence} ${text} ${fence}`;15};1627/** A table cell: a pipe in it would end the cell. */17export const cell = (text: string) => text.replaceAll("|", String.raw`\|`);1830/** A Markdown table: a header row, its rule, then one row per entry. */19export const table = (20 header: readonly string[],21 rows: readonly (readonly string[])[]22) => [
1 unmodified line
24 `| ${header.map(() => "---").join(" | ")} |`,25 ...rows.map((row) => `| ${row.map(cell).join(" | ")} |`),26];2740/** Words joined as a sentence lists them: `a`, `a and b`, `a, b and c`. */28export const listed = (words: readonly string[]) =>29 words.length < 230 ? words.join("")31 : `${words.slice(0, -1).join(", ")} and ${words.at(-1) ?? ""}`;
25 unmodified lines
5758 return value;59};6074/** JSON as the generators write it: sorted keys, two-space indents, a final newline. */61export 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 */1import { Array as Arr, Effect, Order } from "effect";23import { contentHash } from "./generated-file.ts";4import type { GeneratedFile } from "./generated-file.ts";5import { printJson } from "./text.ts";613/** One skill the index lists: its file's text, to digest, and where it is served. */7export interface SkillEntry {8 readonly name: string;9 readonly description: string;10 readonly url: string;
1 unmodified line
12}1314const DISCOVERY = "https://schemas.agentskills.io/discovery/0.2.0/schema.json";1523/** The most characters an entry's description may have. */16const DESCRIBED = 1024;1718const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });1928/**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 */20const cut = (description: string) => {21 if (description.length <= DESCRIBED) {22 return description;23 }
12 unmodified lines
36};3738const byName = Order.mapInput(Order.String, (entry: SkillEntry) => entry.name);3953/** The index, its entries sorted by name. Its path is served from the platform's root. */40export const wellKnownSkills = (41 entries: readonly SkillEntry[]42): Effect.Effect<GeneratedFile> =>43 Effect.forEach(Arr.sort(entries, byName), (entry) =>
15 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { groups } from "@repo/protocol/refusal";
39 unmodified lines
44const commands: readonly CommandDoc[] = [...someCommands, login, mcp];4546const channels = agentSetup({ commands, platformUrl, webUrl });4755/** The channel titled `title`; fails the test without one. */48const channel = (from: readonly SetupChannel[], title: string) =>49 Option.getOrThrow(Arr.findFirst(from, (each) => each.title === title));5059/** The snippet labelled `label` in the channel titled `title`. */51const snippet = (title: string, label: string) =>52 Option.getOrThrow(53 Arr.findFirst(channel(channels, title).snippets, (each) =>54 each.label.startsWith(label)55 )56 );5767/** A JSON object's text, decoded. */58const parsed = Schema.decodeUnknownSync(59 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))60);6172/** The `.mcp.json` the Claude Code plugin carries for the same platform. */62const pluginMcpJson = claudePlugin({ commands, platformUrl }).pipe(63 Effect.map((files) =>64 Option.getOrThrow(65 Arr.findFirst(files, ({ path }) => path.endsWith("/.mcp.json"))
207 unmodified lines
modified:packages/agent-kit/test/agents-block.test.ts-1 removed
27 unmodified lines
28 body: "## Contributing\n\nOld text,\nover two lines.\n",29 end,30};3132/** The block as it sits in a file. */32const written = ({ begin, body }: typeof block) => `${begin}\n${body}${end}`;3334describe(upsertAgentsBlock, () => {35 it("inserts the block at the end of an AGENTS.md without one", () => {
84 unmodified lines
modified:packages/agent-kit/test/command-doc.test.ts-5 removed
103 unmodified lines
104 ]);105 });106});107108/** Each row that calls `tag`, by its words and where it comes from. */108const calling = (docs: readonly CommandDoc[], tag: string) =>109 docs.flatMap((doc) =>110 doc.contract === tag ? [`${doc.path.join(" ")} (${doc.source})`] : []111 );112114// 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.113describe(commandDocs, () => {114 const docs = commandDocs(Contracts);115 const words = docs.map(({ path }) => path.join(" "));116
54 unmodified lines
171 "ask open",172 ]);173 });174178 // `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 line
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Contracts, Surfaces } from "@repo/protocol/contracts";4import type { ProjectEvent } from "@repo/protocol/domain/event";
19 unmodified lines
24 onNone: () => "",25 onSome: ({ markdown }) => markdown,26 });2735/** Every code span and shell line in `markdown` that runs the CLI, as its words. */28const cliSpans = (markdown: string) =>29 [30 ...[...markdown.matchAll(/`(?<span>[^`\n]+)`/gu)].map(31 (found) => found.groups?.span ?? ""
4 unmodified lines
36 ? [span.slice(Brand.cli.length + 1).split(/\s+/u)]37 : []38 );3948/** The catalog's command these words run: the longest path they start with. */40const 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 lines
modified: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 */1import { Brand } from "@repo/brand";2import { CheckSpec } from "@repo/protocol/domain/check";3import { Command } from "@repo/protocol/domain/common";4import type { AskKind } from "@repo/protocol/domain/kind";
6 unmodified lines
11export const project = ProjectName.make("oscabriel/datekit");1213export const landed = LandedSha.make("a".repeat(40));1421/** A later landing, for a copy generated before it. */15export const later = LandedSha.make("b".repeat(40));1617const encodeCheck = Schema.encodeSync(CheckSpec);18
121 unmodified lines
140};141142export const policy = Schema.decodeSync(Policy)(encoded);143151/** The same project after a landing that changed one lane of its run block. */144export const policyWithNewLint = Schema.decodeSync(Policy)({145 ...encoded,146 run: {147 ...encoded.run,148 checks: { ...encoded.run.checks, lint: "bunx oxlint --deny-warnings" },149 },150});151160/**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.153export const commands: readonly CommandDoc[] = [154 {155 contract: "listAsks",156 flags: ["--project", "--json"],
44 unmodified lines
201 summary: "Run the gate's checks on your answer locally, before you push.",202 },203];204216/** Where the platform serves its routes in these tests. */205export 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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import type { ProjectEvent } from "@repo/protocol/domain/event";
11 unmodified lines
16const platformUrl = "https://platform-test.example.workers.dev";1718const webUrl = "https://web-test.example.workers.dev";1927/** A command row as the command list holds it. */20const row = (21 path: readonly [string, ...string[]],22 summary: string,23 more: Partial<CommandDoc> = {}
69 unmodified lines
93const text = fullLlms(input);9495const lines = text.split("\n");96105/** The lines of the section headed `## <title>`, up to the next `## `. */97const 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 lines
modified:packages/agent-kit/test/generate.test.ts-7 removed
24 unmodified lines
25import { expectGolden, transcript } from "./golden.ts";2627const plugin = `plugins/${Brand.slug}`;2829/** The `name:` line of a file's frontmatter; none without one. */29const frontmatterName = (content: string) =>30 Option.fromNullishOr(/^name: (?<name>.+)$/mu.exec(content)?.groups?.name);3132const skill = `${keyOf(project)}-contribute`;3335/** `sha256("hello\n")`, as every tool that hashes prints it. */34const helloDigest =35 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";3637interface 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 lines
142const eventsOf = Schema.decodeUnknownSync(143 Schema.Struct({ hooks: Schema.Record(Schema.String, Schema.Unknown) })144);145149/** A SKILL.md's frontmatter keys: top level, and under `metadata`. */146const frontmatterKeys = (content: string) => {147 const [, head = ""] = content.split("---\n");148 const lines = head.split("\n");149
6 unmodified lines
156 ),157 };158};159164/** A Markdown file's body: everything after its frontmatter's closing line. */160const bodyOf = (content: string) => {161 const close = content.indexOf("\n---\n", 3);162163 return close === -1 ? content : content.slice(close + "\n---\n".length);164};165171/** The hash a file's frontmatter records, read with a pattern of its own. */166const recordedHash = (content: string) =>167 /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(content)?.groups168 ?.hash ?? "";169176/** The hook entry that runs `<cli> hook <event> --json`. */170const hookCommand = (event: HookEvent) => [171 { command: `${Brand.cli} hook ${event} --json`, type: "command" },172];173
276 unmodified lines
modified: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.3import { expect } from "@effect/vitest";4import { Brand } from "@repo/brand";5import { Config, Effect, FileSystem } from "effect";6
12 unmodified lines
19const CLI = new RegExp(`(?<=^|[\`"])${escaped(Brand.cli)}(?= [a-z])`, "gmu");2021const SLUG = new RegExp(`(?<![A-Za-z])${escaped(Brand.slug)}(?![a-z])`, "gu");2230/** A golden file's text with its placeholders filled in from `Brand`. */23export const branded = (golden: string) =>24 golden25 .replaceAll("__NAME__", Brand.name)26 .replaceAll("__CLI__", Brand.cli)
2 unmodified lines
29// The hex of a frontmatter's `content-hash: "sha256:…"` or an AGENTS.md30// marker's `content-hash: sha256:…`.31const HASH = /(?<=content-hash: "?sha256:)[0-9a-f]{64}/gu;3241/** Generated text with each content hash as `__HASH__`. */33const unhashed = (text: string) => text.replaceAll(HASH, "__HASH__");3444/** Generated text as a golden file holds it: the brand and hashes as placeholders. */35const unbranded = (text: string) =>36 unhashed(text)37 .replaceAll(NAME, "__NAME__")38 .replaceAll(CLI, "__CLI__")39 .replaceAll(SLUG, "__SLUG__");4051/** Several files as one text: each under a `==> <path> <==` line. */41export const transcript = (files: readonly GeneratedFile[]) =>42 files.map(({ content, path }) => `==> ${path} <==\n${content}`).join("\n");4355/**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 */44export const expectGolden = (name: string, actual: string) =>45 Effect.gen(function* () {46 const fs = yield* FileSystem.FileSystem;47 const file = `${DIR}/${name}.txt`;
23 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import type { ProjectListing } from "@repo/protocol/domain/front-page";
12 unmodified lines
17const platformUrl = "https://platform-test.example.workers.dev";1819const webUrl = "https://web-test.example.workers.dev";2027/** A command row as the command list holds it. */21const row = (22 path: readonly [string, ...string[]],23 summary: string,24 more: Partial<CommandDoc> = {}
7 unmodified lines
32 summary,33 ...more,34});3543/** The web's own `llms.test.ts` catalog, so the golden file is its former output. */36const 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 lines
modified:packages/agent-kit/test/stale.test.ts-2 removed
15 unmodified lines
16 policyWithNewLint,17 project,18} from "./fixtures.ts";1920/** `sha256("hello\n")`, as every tool that hashes prints it. */20const helloDigest =21 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";2224/** The hash a file's frontmatter records, read with a pattern of its own. */23const recordedHash = (file: string) =>24 /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(file)?.groups25 ?.hash ?? "";26
244 unmodified lines
modified: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 */1import { Duration, Schema } from "effect";23import { Revision } from "../repo-host.ts";412/** Artifacts' names for its errors: `ArtifactsError.code` on the binding. */5export const Code = Schema.Literals([6 "ALREADY_EXISTS",7 "NOT_FOUND",8 "CREATE_IN_PROGRESS",
12 unmodified lines
21export type Code = typeof Code.Type;2223export const isCode = Schema.is(Code);2433/**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. */26export 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 lines
37 [10_401, "UPSTREAM_UNAVAILABLE"],38 [10_402, "MEMORY_LIMIT"],39]);4053/**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 */41export const NO_SOURCE = [42 "INVALID_INPUT",43 "INVALID_URL",44 "MEMORY_LIMIT",
1 unmodified line
46 "REMOTE_AUTH_REQUIRED",47 "UPSTREAM_UNAVAILABLE",48] as const satisfies readonly Code[];4966/** Artifacts' name for a revision: a short branch name or a commit id, never `refs/…`. */50export const refOf = (at: Revision) =>51 Revision.$match(at, {52 Branch: ({ name }) => name,53 Commit: ({ sha }) => sha,54 });5573// Artifacts takes a token's ttl in whole seconds, from a minute to a year.56const MIN_TTL_SECONDS = 60;5758const MAX_TTL_SECONDS = 31_536_000;5978/** A token's ttl as Artifacts takes it: whole seconds, clamped to a minute and a year. */60export const secondsOf = (ttl: Duration.Duration) =>61 Math.min(62 Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),63 MAX_TTL_SECONDS64 );6585/** `log` reads at most this many commits per call. */66export 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 */16import {17 Data,18 DateTime,
35 unmodified lines
54} from "./artifacts-api.ts";55import type { Code } from "./artifacts-api.ts";56import { listRefs, listTags, pushRefs } from "./smart-http.ts";5771/**72 * The codes a message names when the error carries none: Artifacts'73 * words, the fake's, and the code itself.74 */58const 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])[];6482/**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 */65class Thrown extends Data.TaggedError("Thrown")<{66 readonly code: Option.Option<Code>;67 readonly message: string;68 readonly error: unknown;69}> {}7092/** A fork that answered `INTERNAL_ERROR`, which may still have made the repo. */71class MaybeForked extends Data.TaggedError("MaybeForked")<{72 readonly thrown: Thrown;73}> {}7475/**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 */79const RATE_LIMITED = /rate[ _-]?limit|too[ _-]many[ _-]requests/iu;8081const isRateLimited = ({ error, message }: Thrown) =>
1 unmodified line
83 (Predicate.hasProperty(error, "code") &&84 Predicate.isString(error.code) &&85 RATE_LIMITED.test(error.code));86111/** From 250 ms apart, doubling, four more asks while the limit refuses. */87const whileLimited = Schedule.exponential(Duration.millis(250)).pipe(88 Schedule.setInputType<Thrown>(),89 Schedule.while(90 ({ attempt: asked, input }) => asked <= 4 && isRateLimited(input)91 )92);93119/**120 * A promise of the binding's, failing with what it threw, read; asked121 * again while Artifacts' rate limit refuses it.122 */94const attempt = <A>(run: () => Promise<A>) =>95 Effect.tryPromise({96 catch: (error) => {97 const message = error instanceof Error ? error.message : String(error);
14 unmodified lines
112 (code: Code) =>113 (thrown: Thrown): boolean =>114 Option.contains(thrown.code, code);115145/**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 */116const fromArtifactsError = (117 name: RepoName,118 thrown: Thrown119): Effect.Effect<never, RepoNotFound | RepoExists | ForkInProgress> =>
9 unmodified lines
129 ),130 Match.orElse(({ error }) => Effect.die(error))131 );132166/** A call about the repo `name`, its errors read as the port's. */133const call = <A>(name: RepoName, run: () => Promise<A>) =>134 attempt(run).pipe(135 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))136 );137138const asDefect = ({ error }: Thrown) => Effect.die(error);139174/** The port's reads and token calls fail only with `RepoNotFound`. */140const onlyNotFound = <A, R>(141 effect: Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, R>142) =>143 effect.pipe(
1 unmodified line
145 );146147const main = RefName.make("refs/heads/main");148184/** How long a token minted for one call lives; it is revoked after the call. */149const CALL_TOKEN_TTL = Duration.minutes(5);150187/** The codes `import` refuses a source with. */151const IMPORT_REFUSALS: ReadonlySet<Code> = new Set(NO_SOURCE);152153const bytesOf = (blob: Blob) =>154 attempt(() => blob.arrayBuffer()).pipe(
36 unmodified lines
191 };192 })193 ).pipe(Effect.orDie);194232/**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. */196const 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 );202245/**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 */203const 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);210258/** A handle to `name`, asked for again while the repo is still being made. */211const handleOf = (binding: Artifacts, name: RepoName) =>212 attempt(() => binding.get(name)).pipe(213 Effect.retry(whileMaking),214 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))215 );216265/** Gives a handle back: the binding's handles are RPC stubs. */217/** The binding's handles are RPC stubs, so each is disposed. */218const disposeOf = (repo: ArtifactsRepo) =>219 Effect.sync(() => {220 repo[Symbol.dispose]();221 });222271/** `use` over a handle to `name`, disposed after, whatever `use` came to. */223const withRepo = <A, E, R>(224 binding: Artifacts,225 name: RepoName,226 use: (repo: ArtifactsRepo) => Effect.Effect<A, E, R>
4 unmodified lines
231 )232 );233234/**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 */238const withoutToken = (239 binding: Artifacts,240 made: { readonly remote: string; readonly token: string },
10 unmodified lines
251 ),252 Effect.as({ name, remote: made.remote })253 );254305/**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 */255const access = (name: RepoName, repo: ArtifactsRepo, scope: TokenScope) =>256 Effect.gen(function* () {257 const { remote } = yield* call(name, () => repo.info());258
13 unmodified lines
272 return yield* listRefs(remote, token);273 })274 );275330/** The repo's tags over smart HTTP, peeled: the binding lists no refs. */276/** Over smart HTTP: the binding lists no refs. */277const tagsOf = (name: RepoName, repo: ArtifactsRepo) =>278 Effect.scoped(279 Effect.gen(function* () {280 const { remote, token } = yield* access(name, repo, "read");
3 unmodified lines
284 );285286/**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 */290const confirmed = (binding: Artifacts, name: RepoName) =>291 withRepo(binding, name, (repo) =>292 Effect.gen(function* () {
13 unmodified lines
306 RepoNotFound: () => Effect.fail(new ForkInProgress({ name })),307 })308 );309365/**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 */310const 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 lines
323 )324 )325 ).pipe(Effect.flatMap((made) => withoutToken(binding, made, name)));326386/**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. */328const blobOrCommit = (name: RepoName, repo: ArtifactsRepo, id: string) =>329 call(name, () => repo.readBlob(id)).pipe(330 Effect.flatMap((blob) =>331 blob === null
15 unmodified lines
347 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 lines
451 // 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;454519 /**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: ArtifactsRepo
104 unmodified lines
563 tags: (name) => read(name, (repo) => tagsOf(name, repo)),564 });565 });566636/**637 * Artifacts through the Workers binding, the platform's `RepoHost` in638 * production. Refs and pushes go over git smart HTTP through `Fetch`.639 */567export 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 lines
43 RepoName,44 RepoNotFound,45} from "../repo-host.ts";4647/**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 */47export type GitDir = PushSource;4854/** A repo a store found by name: its directory and the lock its pushes take. */49export interface StoredRepo {50 readonly dir: GitDir;51 readonly lock: Semaphore.Semaphore;52}5360/** The ref every repo's HEAD names: Artifacts' default branch. */54export const mainRef = "refs/heads/main";5556class GitFailure extends Data.TaggedError("GitFailure")<{57 readonly cause: unknown;
1 unmodified line
5960const git = <A>(run: () => Promise<A>) =>61 Effect.tryPromise({ catch: (cause) => new GitFailure({ cause }), try: run });6270/** `None` where isomorphic-git finds no such object, ref or file. */63export const unlessMissing = <A>(64 run: () => Promise<A>65): Effect.Effect<Option.Option<A>> =>66 git(run).pipe(
18 unmodified lines
85 : Effect.die(`copying ${oid} produced ${written}`)86 )87 );8897/** A new, empty bare repo whose HEAD names `main`. */89export const initBare = (repo: GitDir) =>90 git(() => init({ ...repo, bare: true, defaultBranch: "main" })).pipe(91 Effect.orDie92 );
3 unmodified lines
96 Effect.map(Option.map((sha) => CommitSha.make(sha)))97 );9899/**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 */103export const defaultRefOf = (repo: GitDir) =>104 Effect.gen(function* () {105 const head = Option.filter(
79 unmodified lines
185 );186 yield* keep(oid, () => writeCommit({ ...into, commit }));187 });188201/**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 */189const copyTarget = (190 source: PushSource,191 into: GitDir,192 oid: string
16 unmodified lines
209 yield* copyTarget(source, into, tag.value.tag.object);210 yield* keep(oid, () => writeTag({ ...into, tag: tag.value.tag }));211 });212229/** Sets the new repo `into`'s `ref` to `source`'s `tip`, objects first. */213export const seedRef = (214 source: PushSource,215 into: GitDir,216 ref: string,
53 unmodified lines
270 }))271 )272 );273291// isomorphic-git's entries carry `path` and `oid`; the port's, `name` and `sha`.274const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));275294/**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 */276export const objectsAndRefs = (277 known: (name: RepoName) => Effect.Effect<StoredRepo, RepoNotFound>278): Pick<279 RepoHost["Service"],
133 unmodified lines
modified:packages/artifacts/src/repo-host/local.ts+5 added-37 removed
52 unmodified lines
53 unlessMissing,54} from "./isogit-store.ts";55import type { GitDir } from "./isogit-store.ts";5657/** A promise from isomorphic-git or the file system that rejected. */57class IoFailure extends Data.TaggedError("IoFailure")<{58 readonly cause: unknown;59}> {}6061const io = <A>(run: () => Promise<A>) =>62 Effect.tryPromise({ catch: (cause) => new IoFailure({ cause }), try: run });6365/** Whether a file-system call failed with node's error `code`. */64const failedWith = (code: "EEXIST" | "ENOENT") => (failure: IoFailure) =>65 failure.cause instanceof Error &&66 "code" in failure.cause &&67 failure.cause.code === code;6871/** Whether anything is at `path`. */69const 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 );7579/** Deletes `path` and everything under it; whether there was anything. */76const removeAll = (path: string) =>77 Effect.gen(function* () {78 const found = yield* exists(path);79
3 unmodified lines
8384 return found;85 });8691/** The remote an HTTP import fetches through, removed once it has. */87const importRemote = "import";8889const branchOf = (ref: string) => ref.replace(/^refs\/heads\//u, "");9096/**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 */91const Tokens = Schema.fromJsonString(92 Schema.Struct({ live: Schema.Array(Schema.String), minted: Schema.Int })93);94
22 unmodified lines
117 ? Stream.fromAsyncIterable(body, (cause) => new IoFailure({ cause }))118 : Stream.fromIterable(body)119 ).pipe(Stream.runCollect, Effect.map(concat));120131/** One chunk as the async iterator isomorphic-git reads a response body from. */121const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {122 const chunks = [bytes];123124 const iterator: AsyncIterableIterator<Uint8Array> = {
11 unmodified lines
136137 return iterator;138};139151/**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 */140const httpOver = (141 fetch: Fetch["Service"]["fetch"],142 context: Context.Context<never>143): HttpClient => ({
26 unmodified lines
170 })171 ),172});173189/** Why a fetch from `url` brought nothing to import. */174const 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 lines
217218 return lock;219 });220237 /** 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 lines
228229 return { dir, lock: yield* lockOf(name) };230 });231249 /** 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 lines
248249 return dir;250 });251269 /** 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 lines
260261 return createdOf(name);262 });263282 // 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}` });272293 // 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 lines
282 if (Option.isNone(head)) {283 return yield* noRepo;284 }285307 // 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 lines
308309 return yield* seed(name, { fs, gitdir }, ref, tip);310 });311336 /** 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 lines
359360 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`);367368 return createdOf(name);369 });370397 // 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 | undefined
3 unmodified lines
379 Effect.onError(() => removeAll(gitdir).pipe(Effect.asVoid))380 )381 );382410 /** 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 lines
502 });503504/**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 */509export const RepoHostLocal = {510 layer: (options: {511 readonly root: string;
4 unmodified lines
modified: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 */51type ReadOptions = string | { readonly encoding?: string } | undefined;23interface Stats {4 readonly mode: number;
163 unmodified lines
168 ? Promise.resolve(stats("dir", 0))169 : failure("ENOENT", path);170 };171177 /** Deletes a directory and everything under it; not part of `fs`. */172 const removeTree = (raw: string) => {173 const root = normalize(raw);174175 const inside = (path: string) =>
27 unmodified lines
modified:packages/artifacts/src/repo-host/memory.ts+1 added-10 removed
27 unmodified lines
28 remote: remoteOf(name),29});3031interface 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}3536/**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 */36const make = () => {37 const fs = memoryFs();38 const repos = new Map<RepoName, Repo>();39 let minted = 0;
23 unmodified lines
6364 return repo;65 });6672 /** 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 lines
108 reason: `no repo at ${source.url}`,109 });110 }111118 // 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 lines
168 known(name).pipe(Effect.map((repo) => repo.tokens.delete(id))),169 });170};171180/** A fresh, empty store each time the layer is built. */172export 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 */17import { CommitSha } from "@repo/protocol/ids";18import {19 Data,
35 unmodified lines
55} from "./artifacts-api.ts";56import type { Code } from "./artifacts-api.ts";57import { listRefs, listTags, pushRefs } from "./smart-http.ts";58110/** A refusal that names no code at all, such as a proxy's, read by status. */59const 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 lines
65 ),66 Match.orElse(() => Option.none())67 );68121/** A reply that was no success: its status, the code it names, its messages. */69class Refused extends Data.TaggedError("Refused")<{70 readonly status: number;71 readonly code: Option.Option<Code>;72 readonly message: string;73}> {}74128/** A fork that answered 500, which may still have made the repo. */75class MaybeForked extends Data.TaggedError("MaybeForked")<{76 readonly refused: Refused;77}> {}78
5 unmodified lines
8485const decodeFailure = Schema.decodeOption(Failure);8687/**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 */92const refusedBy = (status: number, text: string) => {93 const problems = Option.match(decodeFailure(text), {94 onNone: () => [],
17 unmodified lines
112 (...codes: readonly Code[]) =>113 (refused: Refused): boolean =>114 Option.exists(refused.code, (code) => codes.includes(code));115172/** Cloudflare's v4 envelope around a success's `result`. */116const Envelope = <S extends Schema.Top>(result: S) =>117 Schema.fromJsonString(118 Schema.Struct({ result, success: Schema.Literal(true) })119 );
96 unmodified lines
216 textOf(response).pipe(217 Effect.flatMap((text) => Effect.fail(refusedBy(response.status, text)))218 );219277/** A success's envelope, decoded at the boundary, or what refused it. */220const decoded =221 <A>(codec: Schema.Codec<A, string>) =>222 (response: Response) =>223 response.ok
2 unmodified lines
226 Effect.orDie227 )228 : refusal(response);229288/** A success's raw bytes, or what refused it. */230const bytesOf = (response: Response) =>231 response.ok232 ? Effect.promise(() => response.arrayBuffer()).pipe(233 Effect.map((buffer) => new Uint8Array(buffer))
4 unmodified lines
238 response.ok ? Effect.void : refusal(response);239240const main = RefName.make("refs/heads/main");241301/** How long a token for git calls lives, and how near its expiry it is replaced. */242const CALL_TOKEN_TTL = Duration.minutes(30);243244const CALL_TOKEN_MARGIN = Duration.minutes(5);245306/** How long a token id may be unknown to the index after its mint. */246const REVOKE_LAG = Duration.seconds(2);247309/** A token this layer minted and has not revoked. */248interface 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}253317/** What a git call to a repo needs: its remote, and a token. */254interface Access {255 readonly name: RepoName;256 readonly remote: string;257 readonly token: Redacted.Redacted;
12 unmodified lines
270 "FORK_IN_PROGRESS",271 "IMPORT_IN_PROGRESS",272] as const satisfies readonly Code[];273338/** What a create or an import refuses a name with: one taken, or being made. */274const TAKEN = [275 "ALREADY_EXISTS",276 ...BEING_MADE,277] as const satisfies readonly Code[];
24 unmodified lines
302 const access = yield* Ref.make<ReadonlyMap<string, Access>>(new Map());303304 const authorization = () => `Bearer ${Redacted.value(options.token)}`;305371 /** One request to the API; one that got no response is a defect. */306 const send = (request: Request) => fetch.fetch(request).pipe(Effect.orDie);307308 const httpGet = (path: string) =>309 send(
37 unmodified lines
347 method: "POST",348 })349 );350417 /** 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 lines
367368 const remoteOf = (name: RepoName) =>369 infoOf(name).pipe(Effect.catchTag("ForkInProgress", Effect.die));370438 /**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 lines
435 is("NOT_FOUND")(refused) ? Effect.succeed(false) : Effect.die(refused)436 )437 );438510 /**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 lines
462463 return again;464 });465541 /** 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 lines
516 );517518 /**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 lines
535 ),536 Effect.provideService(Fetch, fetch)537 );538616 /**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 lines
561 )562 )563 );564646 /** 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 lines
591 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 lines
603 )604 )605 );606691 /** 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 lines
758 ),759 });760 });761847/**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 */762export 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 */3import { CommitSha } from "@repo/protocol/ids";4import {5 Data,6 Effect,
32 unmodified lines
39 RepoNotFound,40} from "../repo-host.ts";41import type { PushSource, RefUpdate, Tag } from "../repo-host.ts";4250/** What isomorphic-git or a response body threw, before it is read. */43class GitFailure extends Data.TaggedError("GitFailure")<{44 readonly cause: unknown;45}> {}46
20 unmodified lines
67const decodeRef = Schema.decodeUnknownOption(RefName);6869const decodeSha = Schema.decodeUnknownOption(CommitSha);7079/** The repo a remote names: its last path segment, less `.git`. */71const repoOf = (remote: string) =>72 Option.match(73 decodeRepo(74 (URL.canParse(remote) ? new URL(remote).pathname : remote)
29 unmodified lines
104 ? Stream.fromAsyncIterable(body, (cause) => new GitFailure({ cause }))105 : Stream.fromIterable(body)106 ).pipe(Stream.runCollect, Effect.map(concat));107117/** One chunk as the async iterator isomorphic-git reads a response body from. */108const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {109 const chunks = [bytes];110111 const iterator: AsyncIterableIterator<Uint8Array> = {
11 unmodified lines
123124 return iterator;125};126137/** The side-band 3 (fatal) messages in a reply's top-level packet lines. */127const fatalMessages = (bytes: Uint8Array) => {128 const messages: string[] = [];129 const text = new TextDecoder();130 let at = 0;
4 unmodified lines
135 if (Number.isNaN(length)) {136 break;137 }138150 // A flush (`0000`) or a delimiter carries no payload.139 if (length < 4) {140 at += 4;141 continue;142 }
10 unmodified lines
153154const isReceivePack = (url: string) =>155 new URL(url).pathname.endsWith("/git-receive-pack");156169/**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 */157const 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 lines
214 } satisfies HttpClient;215 });216217/**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 */221const git = <A>(run: (signal: AbortSignal) => Promise<A>) =>222 Effect.tryPromise({223 catch: (cause) =>
7 unmodified lines
231 ),232 try: run,233 });234254/** Every ref the remote lists, custom refs included; never `HEAD` or a peeled tag. */235const 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 lines
251 )252 )253 );254275/**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. */256const tagsAt = (remote: string, http: HttpClient) =>257 git(() =>258 listServerRefs({259 http,
16 unmodified lines
276 )277 )278 );279304/** Every tag the remote lists, peeled to its commit. */280export const listTags = (281 remote: string,282 token: Redacted.Redacted283): Effect.Effect<readonly Tag[], RepoNotFound, Fetch> =>
4 unmodified lines
288 return yield* tagsAt(remote, yield* httpFor(remote, token, name));289 })290 );291317/**318 * Every ref the remote lists, as `ls-remote` lists them: what reads by name319 * cannot reach.320 */292export const listRefs = (293 remote: string,294 token: Redacted.Redacted295): Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound, Fetch> =>
7 unmodified lines
303304const isMoved = (reason: string) =>305 MOVED.some((moved) => reason.includes(moved));306336/** Whether the store refused a push of `ref` because the ref moved. */307const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>308 cause instanceof Errors.GitPushError &&309 isMoved(cause.data.result.refs[ref]?.error ?? "");310311/**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 */317const pushOne = (318 remote: string,319 http: HttpClient,
62 unmodified lines
382 return pushed;383 });384385/**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 */389export const pushRefs = (input: {390 readonly remote: string;
11 unmodified lines
402 );403 })404 );405444/**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 */406export const fetchInto = (input: {407 readonly remote: string;408 readonly token: Redacted.Redacted;409 readonly fs: FsClient;
65 unmodified lines
modified:packages/artifacts/src/fetch.ts-7 removed
1import { Context, Schema } from "effect";2import type { Effect } from "effect";34/** An HTTP request that got no response: the network, DNS or TLS failed. */4export class FetchFailed extends Schema.TaggedError<FetchFailed>()(5 "FetchFailed",6 { reason: Schema.String, url: Schema.String }7) {}810/**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 */9export class Fetch extends Context.Service<10 Fetch,11 {12 readonly fetch: (request: Request) => Effect.Effect<Response, FetchFailed>;
2 unmodified lines
modified:packages/artifacts/src/repo-host.ts+5 added-60 removed
10 unmodified lines
11} from "effect";12import type { Array, DateTime, Duration, Redacted } from "effect";13import type { FsClient } from "isomorphic-git";1415/** A repo's name in its namespace: the one `RepoName`, from the domain. */15export { RepoName } from "@repo/protocol/ids";1618/** A short branch name such as `main` or `feature/x`, never `refs/…`. */17export const BranchName = Schema.String.pipe(18 Schema.check(19 Schema.isPattern(20 /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u
3 unmodified lines
24);2526export type BranchName = typeof BranchName.Type;2730/**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 */28export const RefName = Schema.String.pipe(29 Schema.check(30 Schema.isPattern(31 /^refs\/(?!.*\.\.)[A-Za-z0-9._@+-]+(?:\/[A-Za-z0-9._@+-]+)+$/u
3 unmodified lines
35);3637export type RefName = typeof RefName.Type;3846/** A git object id: 40 lowercase hex digits. */39export const ObjectId = Schema.String.pipe(40 Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),41 Schema.brand("ObjectId")42);4344export type ObjectId = typeof ObjectId.Type;4554/**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 */46export const TreeEntry = Schema.Struct({47 mode: Schema.Literals(["100644", "100755", "120000", "040000", "160000"]),48 name: Schema.NonEmptyString,49 sha: ObjectId,
1 unmodified line
51});5253export type TreeEntry = typeof TreeEntry.Type;5467/**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. */56export type Revision = Data.TaggedEnum<{57 Branch: { readonly name: BranchName };58 Commit: { readonly sha: CommitSha };59}>;
1 unmodified line
61export const Revision = Data.taggedEnum<Revision>();6263const Person = Schema.Struct({ email: Schema.String, name: Schema.String });6480/** A commit, with when it was written and when committed, in Unix seconds. */65export const Commit = Schema.Struct({66 author: Person,67 authoredAt: Schema.Int,68 committedAt: Schema.Int,
5 unmodified lines
74});7576export type Commit = typeof Commit.Type;7794/** One tag: its full ref, and the commit it names, peeled. */78export interface Tag {79 readonly name: RefName;80 readonly sha: CommitSha;81}
11 unmodified lines
93 readonly name: RepoName;94 readonly remote: string;95}96114/** A local git repo, read through isomorphic-git, that a push takes objects from. */97export interface PushSource {98 readonly fs: FsClient;99 readonly gitdir: string;100}101120/**121 * One ref's compare-and-swap. `from` is the tip the pusher expects; `None`122 * means the ref must not exist yet.123 */102export interface RefUpdate {103 readonly ref: RefName;104 readonly from: Option.Option<CommitSha>;105 readonly to: CommitSha;
15 unmodified lines
121export class RepoExists extends Schema.TaggedError<RepoExists>()("RepoExists", {122 name: RepoName,123}) {}124147/** Artifacts is still forking this repo; retry. */125export class ForkInProgress extends Schema.TaggedError<ForkInProgress>()(126 "ForkInProgress",127 { name: RepoName }128) {}129153/** The store would not import from that remote: not git, not public, or not reachable. */130export class ImportRefused extends Schema.TaggedError<ImportRefused>()(131 "ImportRefused",132 { name: RepoName, reason: Schema.String }133) {}134159/** The store refused a whole push while busy with another; retry. */135export class HostBusy extends Schema.TaggedError<HostBusy>()("HostBusy", {136 name: RepoName,137}) {}138164/**165 * The git store the platform keeps repos in. The only way to Artifacts: every166 * other package reaches it through this port.167 */139export 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 lines
157 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 lines
167 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 lines
182 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 lines
200 ) => Effect.Effect<readonly RefOutcome[], RepoNotFound | HostBusy>;201 }202>()("artifacts/RepoHost") {}203243/**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 */204export interface RepoSessionApi {205 readonly hold: <A, E>(206 key: string,207 open: Effect.Effect<A, E, Scope.Scope>208 ) => Effect.Effect<A, E>;209}210211/**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 */215export const RepoSession = Context.Reference<Option.Option<RepoSessionApi>>(216 "artifacts/RepoSession",217 { defaultValue: Option.none }218);219269/**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 */220export 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 lines
modified: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 made
1 unmodified line
10 * 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 */15import { describe } from "@effect/vitest";16import { Data, Effect, FiberSet, Layer, Predicate, Schema } from "effect";1718import { Fetch, FetchFailed } from "../src/fetch.ts";19import { RepoHostBinding } from "../src/repo-host/binding.ts";20import { describeRepoHost } from "./repo-host-contract.ts";2127/** The namespace another project owns. */22const FORBIDDEN = "witness";2324const harnessPath = process.env.LIVE_ARTIFACTS_HARNESS;25
14 unmodified lines
40 (input): input is (request: Request) => Promise<Response> =>41 Predicate.isFunction(input)42);4350/** What the harness's module exports. */44const HarnessModule = Schema.Struct({ live: Start });4553/** What `live()` resolves to. */46const Harness = Schema.Struct({47 binding: Schema.declare(48 (input): input is Artifacts =>49 Predicate.hasProperty(input, "get") && Predicate.isFunction(input.get)
16 unmodified lines
66class HarnessFailed extends Data.TaggedError("HarnessFailed")<{67 readonly reason: string;68}> {}6978/** The harness's `live()`, run once per test and disposed after it. */70const harness = (path: string) =>71 Effect.acquireRelease(72 Effect.gen(function* () {73 const module = yield* Effect.tryPromise({
8 unmodified lines
82 }).pipe(Effect.orDie),83 ({ dispose }) => Effect.tryPromise(() => dispose()).pipe(Effect.ignore)84 );8595/** A fresh prefix: the suite's fixed names, unique to this test. */86const freshPrefix = () =>87 `live-${crypto88 .getRandomValues(new Uint32Array(2))89 .reduce((text, word) => text + word.toString(36), "")}-`;90101/**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. */92const prefixed = (binding: Artifacts) =>93 Effect.gen(function* () {94 const prefix = freshPrefix();95 const run = yield* FiberSet.makeRuntimePromise();
44 unmodified lines
140 list: (options) => binding.list(options),141 } satisfies Artifacts;142 });143158/** The live store's `Fetch`: the harness's fetch, failing as no response. */144const fetchOver = (send: Harness["fetch"]) =>145 Fetch.of({146 fetch: (request) =>147 Effect.tryPromise({
25 unmodified lines
modified:packages/artifacts/test/binding.test.ts+3 added-28 removed
49 unmodified lines
50const main = RefName.make("refs/heads/main");5152const landed = RefName.make("refs/asked/landed");5354/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */54const remoteBase = "https://artifacts.test/git/projects";5557/** A packet-line holding one side-band 3 (fatal) message. */56const fatal = (message: string) => {57 const payload = new TextEncoder().encode(`\u0003${message}`);58 const length = (payload.length + 4).toString(16).padStart(4, "0");5960 return new Uint8Array([...new TextEncoder().encode(length), ...payload]);61};6265/** Artifacts' whole reply to a push it is too busy for: no report, no flush. */63const busyReply = () =>64 new Response(fatal("artifacts_git_receive_pack_busy\n"), {65 headers: { "content-type": "application/x-git-receive-pack-result" },66 });6771/** What one request to the store carried, as the test's `Fetch` saw it. */68interface Seen {69 readonly url: string;70 readonly authorization: string | null;71}7277/** What a test may do to the next receive-pack call before git sees it. */73type Intercept = (request: Request) => Effect.Effect<Option.Option<Response>>;7480/**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 */75const 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 lines
206 });207208type World = Effect.Success<ReturnType<typeof world>>;209223/** A test body over a fresh world, with the binding's `RepoHost` in scope. */210const within = <A, E>(211 body: (212 world: World213 ) => Effect.Effect<
19 unmodified lines
233 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),234 }235);236251/** A repo `name` with one commit on `main`, and the client that made it. */237const seeded = (name: RepoName) =>238 Effect.gen(function* () {239 const repos = yield* RepoHost;240 const client = yield* gitClient(memoryFs());
102 unmodified lines
343 }344 )345 );346362 // 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 lines
376 })377 )378 );379396 // 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 lines
484 })485 )486 );487505 // 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 lines
651 ({ 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 lines
818 );819});820821/**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 */825const onTestClock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>826 Effect.gen(function* () {827 const fiber = yield* Effect.forkChild(effect);
5 unmodified lines
833834 return yield* Fiber.await(fiber);835 });836858/** How many tokens on `name` are still live, as the fake lists them. */837const liveTokens = (fake: Artifacts, name: RepoName) =>838 Effect.acquireUseRelease(839 Effect.promise(() => fake.get(name)),840 (repo) =>
11 unmodified lines
852853describe("an import Artifacts is still copying", () => {854 const master = RefName.make("refs/heads/master");855878 // 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 lines
891 { defaultBranch: "master" }892 )893 );894919 // 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 lines
modified: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 */7import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";8import {9 Data,
21 unmodified lines
3132export 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}4283/** Artifacts' error codes, from its errors page. */43const Codes = {44 alreadyExists: 10_201,45 forkInProgress: 10_303,46 internal: 10_400,
2 unmodified lines
49 invalidUrl: 10_104,50 notFound: 10_200,51} as const;5294/** Cloudflare's own codes for a bad API token and an unknown route. */53const UNAUTHENTICATED = 10_000;5455const NO_ROUTE = 7000;56
21 unmodified lines
7879const internal = () =>80 failed(500, Codes.internal, "An internal error occurred.");81124/** A reply decided before the host was asked: a refusal of the request itself. */82class Answered extends Data.TaggedError("Answered")<{83 readonly response: Response;84}> {}8586const invalid = (code: number, message: string) =>87 new Answered({ response: failed(400, code, message) });88132/** What a route's handler fails with: the host's errors, or a reply. */89type Failure =90 | Answered91 | ForkInProgress92 | ImportRefused
28 unmodified lines
121const decodeBranch = Schema.decodeUnknownOption(BranchName);122123const decodePath = Schema.decodeUnknownOption(RepoPath);124169/** A request's JSON body, decoded, or a 400. */125const 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 lines
139 Effect.fromOption(decodeObject(id)).pipe(140 Effect.mapError(() => invalid(Codes.invalidInput, `invalid hash: ${id}`))141 );142188/** A short branch name or a commit id; anything else names nothing. */143const revisionOf = (ref: string): Option.Option<Revision> =>144 Option.match(decodeObject(ref), {145 onNone: () =>146 Option.map(decodeBranch(ref), (name) => Revision.Branch({ name })),
14 unmodified lines
161 Match.orElse(() => "blob")162 ),163});164211/** Whether the repo holds `id` as an object of any kind. */165const holds = (host: RepoHost["Service"], name: RepoName, id: ObjectId) =>166 Effect.all([167 host.readBlob(name, id),168 host.readTree(name, id),
4 unmodified lines
173 Option.isSome(blob) || Option.isSome(tree) || Option.isSome(commit)174 )175 );176224/** A repo's info, as `GET /repos/{name}` gives it. */177const infoOf = (name: RepoName, remote: string) =>178 ok({179 created_at: "2026-10-07T00:00:00.000Z",180 default_branch: "main",
6 unmodified lines
187 source: null,188 updated_at: "2026-10-07T00:00:00.000Z",189 });190239/** Whose a token is, and how many more revocations of it miss. */191interface Minted {192 readonly repo: RepoName;193 readonly misses: number;194}195245/** A route's path parameters, the request, and its URL. */196interface Call {197 readonly name: string;198 readonly id: string;199 readonly request: Request;
1 unmodified line
201}202203type Handler = (call: Call) => Effect.Effect<Response, Failure>;204255/** The fake API over `host`: a handler for the test's `Fetch` to route to. */205export const fakeRest = (206 host: RepoHost["Service"],207 options: FakeRestOptions208): Effect.Effect<(request: Request) => Effect.Effect<Response>> =>
2 unmodified lines
211 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());214266 // 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 lines
255 scope,256 };257 });258311 /** 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 lines
327328 return ok(yield* made(name, remote));329 });330384 /** 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 lines
368 onSome: raw,369 });370 });371426 /** 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 lines
459 ["POST", /^\/tokens$/u, token],460 ["DELETE", /^\/tokens\/(?<id>[^/]+)$/u, revoke],461 ];462518 /** 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 lines
modified:packages/artifacts/test/local.test.ts+1 added-7 removed
20 unmodified lines
21import { temporaryRoot } from "./temporary-root.ts";2223const main = RefName.make("refs/heads/main");2425/** No network: every request fails as an unreachable host's would. */25const offline = Layer.succeed(26 Fetch,27 Fetch.of({28 fetch: (request) =>29 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),30 })31);3234/** The store in `root`, whose remotes are its repos' own `file://` URLs. */33const storeAt = (root: string) =>34 RepoHostLocal.layer({ remoteBase: `file://${root}`, root }).pipe(35 Layer.provide(offline)36 );3740/** A store in a new temporary directory, removed when the test ends. */38const freshStore = Layer.unwrap(Effect.map(temporaryRoot, storeAt));3943/** Real `git http-backend` over `root` on a local port: its base URL. */40const served = (root: string) =>41 Effect.gen(function* () {42 const spawner =43 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();
29 unmodified lines
73 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),74});7576describe("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 lines
221 expect(yield* repos.remove(name)).toBeFalsy();222 }).pipe(Effect.provide(freshStore))223 );224230 // 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 lines
modified:packages/artifacts/test/repo-host-contract.ts+1 added-22 removed
27 unmodified lines
28const path = RepoPath.make("src/a.ts");2930const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);3132/** No object in any repo here has this id. */32const absent = ObjectId.make("0".repeat(40));3335/** When a commit was written, and when committed: two different instants. */34const authored = 1_700_000_000;3536const committed = 1_700_000_500;3740/** The test client's repo, which a push takes objects from. */38type Source = Parameters<RepoHost["Service"]["push"]>[1];3943/**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). */41const timedCommit = (source: Source, parent: CommitSha) =>42 Effect.gen(function* () {43 const { commit } = yield* Effect.promise(() =>44 readCommit({ ...source, oid: parent })
24 unmodified lines
6970 return CommitSha.make(oid);71 });7279/** When a commit was written and committed, as a store read it. */73const times = (commit: Commit) => ({74 authoredAt: commit.authoredAt,75 committedAt: commit.committedAt,76});7785/** An annotated tag object naming `commit`; its id, as a push sends it. */78const annotatedTag = (source: Source, name: string, commit: CommitSha) =>79 Effect.map(80 Effect.promise(() =>81 writeTag({
15 unmodified lines
97 // 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 );100109/** What an adapter's run of the suite adds to the shared cases. */101export 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 lines
110 */111 readonly danglingHead?: boolean;112}113127/**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 */114export const describeRepoHost = (115 adapter: string,116 host: Layer.Layer<RepoHost>,117 suite: RepoHostSuite = {}
435 unmodified lines
553 ]);554 }).pipe(Effect.provide(host))555 );556576 // 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 lines
modified:packages/artifacts/test/rest.test.ts-18 removed
46 unmodified lines
47const namespace = "projects-test";4849const api = `https://api.cloudflare.com/client/v4/accounts/${accountId}/artifacts/namespaces/${namespace}`;5051/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */51const remoteBase = `https://${accountId}.artifacts.test/git/${namespace}`;5253const apiToken = "cf-api-token-for-the-rest-tests";5456/** One request as the test's `Fetch` saw it, with its reply. */55interface Seen {56 readonly method: string;57 readonly url: string;58 readonly headers: readonly (readonly [string, string])[];
8 unmodified lines
67 );6869const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));7073/** What a token's mint answered, as far as these tests read it. */71const decodeMinted = Schema.decodeEffect(72 Schema.fromJsonString(73 Schema.Struct({74 result: Schema.Struct({ id: Schema.String, plaintext: Schema.String }),75 })76 )77);7882/**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 */79const world = (80 options: Omit<FakeRestOptions, "accountId" | "namespace" | "token"> = {}81) =>82 Effect.gen(function* () {
72 unmodified lines
155 });156157type World = Effect.Success<ReturnType<typeof world>>;158168/** The REST adapter over a `Fetch` that gives every request the same reply. */159const answering = (reply: () => Response) =>160 RepoHostRest.layer({161 accountId,162 namespace,
3 unmodified lines
166 Layer.succeed(Fetch, Fetch.of({ fetch: () => Effect.sync(reply) }))167 )168 );169180/** A refusal in Cloudflare's v4 envelope. */170const refused = (status: number, code: number, message: string) => () =>171 Response.json(172 { errors: [{ code, message }], messages: [], result: null, success: false },173 { status }174 );175187/** A test body over a fresh world, with the REST adapter's `RepoHost` in scope. */176const within = <A, E>(177 body: (178 world: World179 ) => Effect.Effect<
19 unmodified lines
199 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),200 }201);202215/** A repo `name` with one commit on `main`, and the client that made it. */203const seeded = (name: RepoName) =>204 Effect.gen(function* () {205 const repos = yield* RepoHost;206 const client = yield* gitClient(memoryFs());
8 unmodified lines
215216 return { client, first };217 });218232/** The requests to one REST route, by method and path under the namespace. */219const requestsTo = (220 seen: Ref.Ref<readonly Seen[]>,221 method: string,222 path: string
6 unmodified lines
229 )230 )231 );232247/** A commit's tree, read from the client that wrote it. */233const treeOf = (source: PushSource, oid: CommitSha) =>234 Effect.promise(() => readCommit({ ...source, oid })).pipe(235 Effect.map(({ commit }) => ObjectId.make(commit.tree))236 );
421 unmodified lines
658 { casing }659 )660 );661677 // 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 lines
modified:packages/artifacts/test/revision.test.ts-1 removed
2 unmodified lines
3import { Schema } from "effect";45import { BranchName, RepoName } from "../src/repo-host.ts";67// One `RepoName` across the product: the port names repos with the domain's.7describe("a repo name", () => {8 it("is the domain's RepoName", () => {9 expect(RepoName).toBe(Ids.RepoName);10 });
16 unmodified lines
modified:packages/artifacts/test/temporary-root.ts-4 removed
1import { NodeServices } from "@effect/platform-node";2import { Effect, FileSystem } from "effect";34/**5 * A new temporary directory for a store's root, removed with its contents6 * when the test's scope closes.7 */4export const temporaryRoot = FileSystem.FileSystem.pipe(5 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "repo-host-" })),6 Effect.orDie,7 Effect.provide(NodeServices.layer)
1 unmodified line
modified: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 */1const slug = "myr";23export const Brand = {4 cli: slug,
12 unmodified lines
modified:packages/brand/src/leaks.ts-2 removed
5 unmodified lines
6}78export 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 lines
6061 return [...inPath, ...inContent];62};6365/** Every place outside the brand package and prose that spells the name. */64export const findLeaks = (files: Iterable<SourceFile>): readonly BrandLeak[] =>65 [...files].flatMap(leaksIn);
modified:packages/brand/test/leaks.test.ts-2 removed
53 unmodified lines
54 ])55 ).toStrictEqual([]);56 });5758 // 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`;6061 expect(
86 unmodified lines
modified:packages/config/src/vitest.ts-1 removed
1import { defineConfig } from "vitest/config";23/** The one vitest setup every package uses: tests live in `test/`, run in Node. */3export const preset = defineConfig({4 test: {5 include: ["test/**/*.test.ts"],6 },
1 unmodified line
modified:packages/config/test/bootstrap.test.ts-7 removed
23 unmodified lines
24import { blankJsonc } from "../../../infra/jsonc.ts";25import { resources, stages } from "../../../infra/stages.ts";26import { repoRoot } from "./root.ts";2728/** A file under the repo root, as text. */28const rootText = (file: string) =>29 Effect.gen(function* () {30 const fs = yield* FileSystem.FileSystem;31 const path = yield* Path.Path;3233 return yield* fs.readFileString(path.join(yield* repoRoot, file));34 }).pipe(Effect.provide(NodeServices.layer));3537/** What this test reads of a stage's block in the platform's `wrangler.jsonc`. */36const PlatformStage = Schema.Struct({37 artifacts: Schema.Array(38 Schema.Struct({ binding: Schema.String, namespace: Schema.String })39 ),
27 unmodified lines
67 name: Schema.String,68 })69 );7073/** `apps/<app>/wrangler.jsonc`, comments and trailing commas aside, decoded. */71const wrangler = <S extends Schema.Top & { readonly DecodingServices: never }>(72 app: string,73 stage: S74) =>
3 unmodified lines
78 );7980const nothing: Existing = { d1: [], kv: [], namespaces: [], r2: [] };8185/** Every resource of `dev-oscabriel` and `demo` present, with ids. */82const everything: Existing = {83 d1: [84 {85 id: "11111111-1111-4111-8111-111111111111",
30 unmodified lines
116117 expect(platform.name).toBe("platform");118 expect(Object.keys(platform.env)).toStrictEqual([...stages]);119124 // Each block as the table names it, and as wrangler.jsonc does.120 const named = stages.map((stage) => {121 const names = resources(stage);122123 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 lines
244 ]);245 });246});247254/** The lines of `after` that differ from `before`'s, by line. */248const changed = (before: string, after: string) => {249 const old = before.split("\n");250251 return after
329 unmodified lines
modified: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 */8import { NodeServices } from "@effect/platform-node";9import { describe, expect, it } from "@effect/vitest";10import { Array, Effect, FileSystem, Option, Path, Schema } from "effect";11import type { ChildProcessSpawner } from "effect/process";1213import { committable, readsAtOnce, repoRoot, textOf } from "./root.ts";1424/** The cartridge's folders, from the repo root; each ends with `/`, and each exists. */15const MANIFEST = [16 "packages/visibility/",17 "packages/project/src/visibility/",18 "apps/platform/src/visibility/",19 "apps/platform/test/visibility/",20] as const;2132/**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 */22const TEST_HOMES = ["packages/project/test/visibility/"] as const;2338/**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 */24const 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;2850/**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 */29const ITS_CONTENT = ["examples/datekit/layers/"] as const;3031/**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 */41const CARTRIDGE = [42 ...MANIFEST,43 ...TEST_HOMES,44 ...RUNS_ITS_WORLD,45 ...ITS_CONTENT,46];4776/**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 */48const COMPOSITION = {49 file: "apps/platform/src/cartridges.ts",50 module: "./visibility/live.ts",51};
2 unmodified lines
54const MARKER = ["//", "cartridge:", "visibility"].join(" ");5556const PACKAGE = "@repo/visibility";5791/** The workspaces that depend on the package: the cartridge's implementations live in them. */58const DEPENDENTS = [59 "apps/platform/package.json",60 "packages/project/package.json",61];6297/** 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. */64const BINDING = ["ARTIFACTS", "PRIVATE"].join("_");65100/**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 */66const NAMES_BINDING = new Set([67 "apps/platform/wrangler.jsonc",68 "apps/platform/worker-configuration.d.ts",69 "apps/platform/src/platform.ts",
5 unmodified lines
75 "packages/config/test/web-wiring.test.ts",76 "packages/config/test/cartridge.test.ts",77]);78118/** Prose and binary files: they wire nothing. */79const NOT_WIRING = /\.(?:md|png|ico|svg|woff2?|ttf|otf|jpg|webp|gif|lockb)$/u;8081const isCartridge = (file: string) =>82 CARTRIDGE.some((folder) => file.startsWith(folder));8384const isSource = (file: string) => /\.tsx?$/u.test(file);85126// ------------------------------------------------------------ the repo127128/** Every committable file with its text, `filter` deciding which. */86const filesWhere = (filter: (file: string) => boolean) =>87 Effect.flatMap(committable, (files) =>88 Effect.forEach(89 files.filter(filter),
4 unmodified lines
94 readsAtOnce95 )96 ).pipe(Effect.map(Array.getSomes));97141// --------------------------------------------------------- reading code142143/** Punctuation after which a `/` starts a regex rather than a division. */98const BEFORE_REGEX = new Set("(,=:[!&|?{};+-*%<>~^");99100const KEYWORDS_BEFORE_REGEX = new Set([101 "await",
15 unmodified lines
117const WORD = /[\w$]/u;118119const SPACE = /\s/u;120167/**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 */121interface 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}131185/** Blanks `[from, to)`, keeping line breaks. */132const 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};139194/** The offset of the `/` that closes the regex opening at `start`, or -1 when its line ends first. */140const regexEnd = (content: string, start: number) => {141 let inClass = false;142 let at = start + 1;143
13 unmodified lines
157158 return -1;159};160216/** A template's text, up to its closing backtick or its next `${`. */161const templateText = (lexer: Lexer) => {162 const { content } = lexer;163 const start = lexer.at;164
18 unmodified lines
183 lexer.at += 1;184 }185};186243/** Each step reads one token of code if it starts at `at`, and says whether it did. */187type Step = (lexer: Lexer) => boolean;188189const comment: Step = (lexer) => {190 const { at, content } = lexer;
72 unmodified lines
263264 return true;265};266324/** The `}` that closes a template's `${`. */267const templateResume: Step = (lexer) => {268 if (269 lexer.content[lexer.at] !== "}" ||270 lexer.depth > 0 ||
45 unmodified lines
316 word,317 punctuation,318];319378/**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 */320const mask = (content: string) => {321 const lexer: Lexer = {322 at: 0,323 chars: content.split(""),
21 unmodified lines
345// `import "x"`, or a dynamic `import("x")` (`typeof import("x")` too).346const IMPORT =347 /(?<![.\w$])(?:import|export)[\s{*][^;]*?\bfrom\s*["']|(?<![.\w$])import\s*["']|(?<![.\w$])import\s*\(\s*["']/gu;348412/** One import of a file: what it names, and the line it is on (1-based). */349interface Import {350 readonly line: number;351 readonly specifier: string;352}353418/** Every import, re-export and dynamic import in a file, in source order. */354const importsOf = (content: string): readonly Import[] => {355 const { code, strings } = mask(content);356357 return [...code.matchAll(IMPORT)].flatMap((match) => {
5 unmodified lines
363 : [{ line: content.slice(0, quote).split("\n").length, specifier }];364 });365};366432// ------------------------------------------------------------ resolving433434/** `a/b/../c/./d` as `a/c/d`; none when it climbs out of the repo. */367const normalize = (path: string): Option.Option<string> => {368 const parts: string[] = [];369370 for (const part of path.split("/")) {
28 unmodified lines
399const decodeManifest = Schema.decodeUnknownEffect(400 Schema.fromJsonString(Manifest)401);402471/** A workspace: its folder (with `/`) and its manifest. */403interface Workspace {404 readonly dir: string;405 readonly manifest: Manifest;406}407477/** Every workspace package in the repo: the `package.json` files under `apps/` and `packages/`. */408const workspaces = Effect.flatMap(409 filesWhere((file) => /^(?:apps|packages)\/[^/]+\/package\.json$/u.test(file)),410 (files) =>411 Effect.forEach(files, ({ content, file }) =>
3 unmodified lines
415 }))416 )417);418489/** The file an `exports` subpath names, through a key or one `*` wildcard. */419const exported = (420 workspace: Workspace,421 subpath: string422): Option.Option<string> => {
25 unmodified lines
448 (file) => normalize(`${workspace.dir}${file}`)449 );450};451523/** The repo path an import reaches: a relative path, or a workspace package's export; none for anything else. */452const resolved = (453 from: string,454 specifier: string,455 all: readonly Workspace[]
11 unmodified lines
467 ? Option.none()468 : exported(owner, specifier.slice(owner.manifest.name.length + 1));469};470543/** Whether an import reaches into the cartridge: its package by name, or a path inside it. */471const reachesCartridge = (472 from: string,473 specifier: string,474 all: readonly Workspace[]
12 unmodified lines
487 ...manifest.devDependencies,488 ...manifest.peerDependencies,489 });490564// ---------------------------------------------------------------- tests565491const provided = <A, E>(492 effect: Effect.Effect<493 A,494 E,
121 unmodified lines
616617 const reaching = outside.flatMap(({ content, file }) => {618 const lines = content.split("\n");619695 // `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 lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { DateTime, Effect, FileSystem, Path } from "effect";4
23 unmodified lines
28 name: "swarm-r2",29 stage: "dev-oscabriel",30};3138/** A fresh ledger file in a temp dir, for the scope of one test. */32const 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 lines
modified:packages/config/test/deploy.test.ts+2 added-17 removed
21 unmodified lines
22} from "../../../infra/deploy.ts";23import { LockFile } from "../../../infra/recording.ts";24import { repoRoot } from "./root.ts";2526/** One command the deploy spawned, with its folder relative to the repo root. */26interface Spawned {27 readonly command: string;28 readonly args: readonly string[];29 readonly cwd: string;30 readonly env: Readonly<Record<string, string | undefined>>;31}3234/**35 * A `ChildProcessSpawner` that runs nothing: it records each command and36 * answers with the exit code `exitOf` gives it.37 */33const recording = (exitOf: (spawned: Spawned) => number) =>34 Effect.gen(function* () {35 const path = yield* Path.Path;36 const root = yield* repoRoot;
35 unmodified lines
72 spawned: Ref.get(spawned),73 };74 });7581/** `deploy(argv)` over a recording spawner: what it spawned, and how it ended. */76const run = (77 argv: readonly string[],78 options: {79 readonly exitOf?: (spawned: Spawned) => number;
4 unmodified lines
84 const fs = yield* FileSystem.FileSystem;85 const path = yield* Path.Path;86 const fake = yield* recording(options.exitOf ?? (() => 0));8794 // 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 lines
105106 return { result, spawned: yield* fake.spawned };107 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));108116/** A spawned command as one line: `apps/sandbox$ wrangler deploy --env x`. */109const line = ({ args, command, cwd }: Spawned) =>110 `${cwd === "" ? "." : cwd}$ ${[command, ...args].join(" ")}`;111112describe("a deploy without a known stage", () => {
66 unmodified lines
179 Effect.provideService(Console.Console, quiet)180 );181182 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 lines
237 it.live("turns Wrangler's metrics off in every command it spawns", () =>238 Effect.gen(function* () {239 const { spawned } = yield* run(["--stage", "dev-oscabriel"]);240250 // 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 lines
353 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))354 );355});356368/**369 * The message a failed `deploy(argv)` carries: `runMain` prints a failure as370 * its tag and its message, and nothing else.371 */357const messageOf = (358 argv: readonly string[],359 options: Parameters<typeof run>[1] = {}360) =>
90 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Array, Effect, FileSystem, Option, Order, Path, Schema } from "effect";45import { committable, readsAtOnce, repoRoot, textOf } from "./root.ts";615/**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 */7const PRIVATE_FOLDERS = [8 ".agents/adr",9 ".agents/demo",10 ".agents/ops",
1 unmodified line
12 ".agents/scratch",13 ".agents/README",14] as const;1530/**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 */16const PRIVATE = [17 "~/",18 "/home/",19 "wanted-explainer",
1 unmodified line
21 ...PRIVATE_FOLDERS,22] as const;2324/**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 */29const PLAN_REFERENCES = [30 /\bspec §/u,31 /\bspec D\d/u,
2 unmodified lines
34 /\bW\d \d{3}\b/u,35 /\bSYN\b/u,36] as const;3759/** The files a reader opens as text: source, config, docs and scripts. */38const TEXT_FILE =39 /(?:\.(?:css|html|json|jsonc|md|mjs|sh|sql|toml|ts|tsx|ya?ml)|(?:^|\/)(?:\.gitignore|\.env\.schema|[^/]*Dockerfile))$/u;4041/** This file, which spells the references out to find them. */42const QUOTES_THE_REFERENCES = "packages/config/test/docs-public.test.ts";4366/** The plan references `text` makes, by their patterns. */44const planReferencesIn = (text: string) =>45 PLAN_REFERENCES.flatMap((reference) =>46 reference.test(text) ? [reference.source] : []47 );
4 unmodified lines
52 */53const NAMES_THE_PRIVATE_FOLDERS = (file: string) =>54 file.startsWith(".agents/") || file === ".gitignore";5579/** The private plan references and private folder pointers in `file`'s `text`. */56const privateIn = (file: string, text: string) => [57 ...planReferencesIn(text),58 ...(NAMES_THE_PRIVATE_FOLDERS(file)59 ? []60 : PRIVATE_FOLDERS.filter((folder) => text.includes(folder))),61];6287/** Terms the code uses in public names, each of which GLOSSARY.md defines. */63const TERMS = [64 "Claim fork",65 "Decision",66 "Family",
12 unmodified lines
79const RootPackage = Schema.Struct({80 scripts: Schema.Record(Schema.String, Schema.String),81});82108/** A file's text, by its path from the repo root. */83const read = (relative: string) =>84 Effect.gen(function* () {85 const fs = yield* FileSystem.FileSystem;86 const path = yield* Path.Path;
1 unmodified line
8889 return yield* fs.readFileString(path.join(root, relative));90 });91118/** Each file with its text. */92const withText = (paths: readonly string[]) =>93 Effect.forEach(paths, (path) =>94 Effect.map(read(path), (text) => ({ path, text }))95 );96124/** Every public doc this test reads, with its text. */97const publicDocs = withText(["AGENTS.md", "GLOSSARY.md"]);98127/** The lines of a `## <title>` section, up to the next heading of its level or above. */99const sectionOf = (text: string, title: string): readonly string[] => {100 const lines = text.split("\n");101 const start = lines.indexOf(`## ${title}`);102
6 unmodified lines
109110 return end === -1 ? rest : rest.slice(0, end);111};112142/** The command a list item opens with: `ops` in "- `ops -- <command>`: …". */113const commandOf = (line: string) =>114 /^- `(?<name>[^`\s]+)/u.exec(line)?.groups?.name;115116describe("the repo's public docs", () => {
85 unmodified lines
modified: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).3import { NodeServices } from "@effect/platform-node";4import { describe, expect, it } from "@effect/vitest";5import { Effect, FileSystem, Path, Schema, Stream } from "effect";6import { ChildProcess, ChildProcessSpawner } from "effect/process";
1 unmodified line
8import { repoRoot } from "./root.ts";910const example = "examples/burrow";1124/** The six workspace packages, each holding one module-level `let`. */12const PACKAGES = [13 "auth",14 "billing",15 "catalog",
1 unmodified line
17 "notify",18 "search",19] as const;2034/**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. */22const CallerCount = Schema.Struct({23 byModule: Schema.Record(Schema.String, Schema.Int),24 total: Schema.Int,25});2644/** The part of `oxlint --format json` these cases read. */27const OxlintReport = Schema.Struct({28 diagnostics: Schema.Array(29 Schema.Struct({30 code: Schema.optionalKey(Schema.String),
2 unmodified lines
33 })34 ),35});3655/** A command's exit code and what it printed. */37interface Ran {38 readonly code: number;39 readonly stderr: string;40 readonly stdout: string;41}4262/** Runs a command in burrow's folder and keeps its exit code and output. */43const run = (command: string, args: readonly string[]) =>44 Effect.gen(function* () {45 const path = yield* Path.Path;46 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
14 unmodified lines
6162 return { code, stderr, stdout } satisfies Ran;63 }).pipe(Effect.scoped);6485/** Asserts burrow exists, then installs its pinned devDependencies. */65const install = () =>66 Effect.gen(function* () {67 const fs = yield* FileSystem.FileSystem;68 const path = yield* Path.Path;
3 unmodified lines
72 yield* fs.exists(manifest),73 `${example}/package.json exists`74 ).toBeTruthy();7597 // 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 });80103/** The package a reported file sits in, from its `packages/<name>/src/` path. */81const packageOf = (filename: string) =>82 /(?:^|\/)packages\/(?<name>[^/]+)\/src\//u.exec(filename)?.groups?.name;83107/** Long enough for a cold install; a warm one takes about a second. */84const TIMEOUT = 180_000;8586describe("examples/burrow", () => {87 it.live(
1 unmodified line
89 () =>90 Effect.gen(function* () {91 yield* install();92117 // The command burrow's ratchet runs (its config folder's `project.ts`).93 const lint = yield* run("bun", ["run", "lint", "--format", "json"]);9495 const report = yield* Schema.decodeEffect(96 Schema.fromJsonString(OxlintReport)
39 unmodified lines
136 const counts = yield* Schema.decodeEffect(137 Schema.fromJsonString(CallerCount)138 )(count.stdout);139165 // 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 lines
modified: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/`).4import { NodeServices } from "@effect/platform-node";5import { describe, expect, it } from "@effect/vitest";6import { Effect, FileSystem, Path, Stream } from "effect";7import { ChildProcess, ChildProcessSpawner } from "effect/process";89import { Brand } from "../../brand/src/index.ts";10import { repoRoot } from "./root.ts";1122/** The example, from the repo root. */12const example = "examples/datekit";1325/** What one run of `bun test` printed, both streams, and how it ended. */14interface BunRun {15 readonly exitCode: number;16 readonly output: string;17}1831/** One test file's part of bun's report: the tests it failed, and its text. */19interface FileReport {20 readonly failed: readonly string[];21 readonly file: string;22 readonly text: string;23}2438/** Bun's report, read: each file it reported on, and its closing counts. */25interface 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}3233const ANSI = new RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*m`, "gu");
35 unmodified lines
69const LANES = /\bchecks:\s*\{(?<lanes>[^}]*)\}/u;7071const LANE = /(?<lane>\w+):\s*"(?<command>[^"]+)"/gu;7288/** A closing count bun prints (` 3 fail`), or 0 when it prints none. */73const countOf = (output: string, word: string) =>74 Number(75 new RegExp(`^\\s*(?<count>\\d+) ${word}$`, "mu").exec(output)?.groups76 ?.count ?? "0"77 );7895/** The name a `(fail)` line gives, if the line is one. */79const failedIn = (line: string) => {80 const name = FAILED_TEST.exec(line)?.groups?.name;8182 return name === undefined ? [] : [name];83};84102/** Reads bun's console report into its files and counts. */85const readReport = (output: string): BunReport => {86 const lines = output.split("\n").map((line) => line.trim());8788 const starts = lines.flatMap((line, at) =>
31 unmodified lines
120121const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>122 bytes.pipe(Stream.decodeText(), Stream.mkString);123142/**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 */124const publicTree = Effect.gen(function* () {125 const fs = yield* FileSystem.FileSystem;126 const path = yield* Path.Path;127 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
19 unmodified lines
147148 return dir;149});150174/** Runs `command` in the example's public tree at `dir` under `sh -c`, as the Checker runs a lane. */151const inTree = (dir: string, command: string) =>152 Effect.scoped(153 Effect.gen(function* () {154 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
13 unmodified lines
168 } satisfies BunRun;169 })170 );171196/** The example's run block, read from its project file. */172const runBlock = Effect.gen(function* () {173 const fs = yield* FileSystem.FileSystem;174 const path = yield* Path.Path;175
11 unmodified lines
187188 return { lanes, test: TEST_COMMAND.exec(source)?.groups?.command ?? "" };189});190216/**217 * Each ask file in the example's config folder, and the check file it names;218 * none when the folder is missing.219 */191const 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 lines
208 }))209 );210});211241/** How a file failed: how many tests, whether by an assertion, whether it loaded. */212const howFailed = ({ failed, file, text: part }: FileReport) => ({213 assertion: ASSERTION.test(part),214 file,215 loaded: !LOAD_ERRORS.some((pattern) => pattern.test(part)),
7 unmodified lines
223 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 lines
233 "format-ordinal.ask.ts",234 "parse-iso-week.ask.ts",235 ]);236268 // 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 lines
255 }))256 .toSorted(byFile),257 });258292 // 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 lines
324 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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { ProjectExists } from "@repo/protocol/refusal";4import {
263 unmodified lines
268 ]);269 });270});271279/** A platform in memory: the projects it lists, and every call made to it. */272const 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 lines
316 ),317 };318 });319328/** `importExamples(argv)` over `layer`, with the ledger in a temp folder: how it ended, and what it printed. */320const ran = (321 argv: readonly string[],322 layer: Layer.Layer<ImportTarget | TagBackfill | Warmer>323) =>
223 unmodified lines
547548 const ledgerFile = path.join(dir, "created.jsonl");549 const platform = yield* fakePlatform(["anyhow", "ky"]);550560 // 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 lines
577 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "importing-" });578579 const ledgerFile = path.join(dir, "created.jsonl");580591 // 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"]);582583 yield* fs.writeFileString(584 ledgerFile,
87 unmodified lines
672 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))673 );674});675688/** A call the platform never answered, as an edge timeout leaves it. */676class NoAnswer extends Data.TaggedError("NoAnswer")<{677 readonly after: string;678}> {}679693/**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 */680const askedAgain = (681 answers: readonly Effect.Effect<682 { readonly landed?: string },683 NoAnswer | ProjectExists
61 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";23import { examples } from "../../../scripts/lib/import/plan.ts";4import { importedProjects } from "../../agent-kit/src/docs/imported.ts";
14 unmodified lines
modified: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.3import { describe, expect, it } from "@effect/vitest";45import { examples } from "../../../scripts/lib/import/plan.ts";6import { EXAMPLES } from "../../../scripts/seed.ts";7import { legacyProjects } from "../../protocol/src/legacy.ts";815/** Each example folder's project, in the operator's namespace. */9const seeded = EXAMPLES.map((folder) => {10 const key = folder.slice(folder.lastIndexOf("/") + 1);1112 return { key, name: `oscabriel/${key}` };
15 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 ConfigProvider,
18 unmodified lines
23 RecordingUsage,24} from "../../../infra/recording.ts";25import { repoRoot } from "./root.ts";2633/**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 */27const 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 lines
63 spawned: Ref.get(lines),64 };65});6677/** A temp root's lock file, `infra/.recording` under it, for one test's scope. */67const 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 lines
7374 return path.join(root, lockPath);75});7688/** `deploy(argv)` with the lock at `lock`: how it ended, and what it spawned. */77const deployed = (argv: readonly string[], lock: string) =>78 Effect.gen(function* () {79 const fake = yield* spawning;80
10 unmodified lines
9192 return { result, spawned: yield* fake.spawned };93 });94107/** What `recording(argv)` prints, with the lock at `lock`. */95const printedBy = (argv: readonly string[], lock: string) =>96 Effect.gen(function* () {97 const printed: string[] = [];98
124 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 Array as Arr,
37 unmodified lines
42import { layoutOf, runStep } from "../../../scripts/lib/release/steps.ts";43import { Brand } from "../../brand/src/index.ts";44import { repoRoot } from "./root.ts";4552/** What the test reads of a package manifest. */46const PackageJson = Schema.fromJsonString(47 Schema.Struct({48 dependencies: Schema.optionalKey(49 Schema.Record(Schema.String, Schema.String)
350 unmodified lines
400 });401 });402});403411/** A digest, as `sha256sum` prints one. */404const digest = (fill: string) => fill.repeat(64);405406const first = {407 latest: "0.1.0",
15 unmodified lines
423 [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },424 [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },425};426435/**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 */427const 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 lines
532 });533 });534});535548/** A file's digest as `sha256sum` prints it. */536const sha256 = (content: string) =>537 Effect.flatMap(Crypto.Crypto, (crypto) =>538 crypto.digest("SHA-256", new TextEncoder().encode(content))539 ).pipe(
27 unmodified lines
567 posix: true,568 });569 });570584 /**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 lines
637 stderr,638 };639 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));640658 /** 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 );647666 /** `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 lines
modified:packages/config/test/root.ts+2 added-12 removed
1import { Effect, FileSystem, Option, Path, Stream } from "effect";2import { ChildProcess, ChildProcessSpawner } from "effect/process";34/** The repo root. Vitest runs in the package's folder, two below it. */4export const repoRoot = Effect.map(Path.Path, (path) =>5 path.resolve("..", "..")6);79/**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. */9export const committable = Effect.gen(function* () {10 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;11 const cwd = yield* repoRoot;12
16 unmodified lines
2930 return listed.split("\n").filter((line) => line.length > 0);31}).pipe(Effect.scoped);3238/**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. */34export const readsAtOnce = { concurrency: 32 } as const;3545/** A file under the repo root, as text, if it is on disk. */36export const textOf = (file: string) =>37 Effect.gen(function* () {38 const fs = yield* FileSystem.FileSystem;39 const path = yield* Path.Path;
6 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Effect, FileSystem, Path, Schema } from "effect";4
2 unmodified lines
7const RootPackage = Schema.Struct({8 scripts: Schema.Record(Schema.String, Schema.String),9});1018/** What `bun run <name>` runs, and whether its entry file is on disk. */11const entryOf = (name: string) =>12 Effect.gen(function* () {13 const fs = yield* FileSystem.FileSystem;14 const path = yield* Path.Path;
39 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Console, DateTime, Effect, FileSystem, Layer, Path } from "effect";4
66 unmodified lines
71 repo: `oscabriel__datekit-copy-2--${layer}`,72 }))73 );7482 // 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 lines
117 60_000118 );119});120129/** What `main` prints, line by line. */121const printedBy = (argv: readonly string[]) =>122 Effect.gen(function* () {123 const printed: string[] = [];124
121 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 Array,
25 unmodified lines
30} from "../../protocol/src/domain/visibility.ts";31import { Handle, keyOf, RepoName } from "../../protocol/src/ids.ts";32import { repoRoot } from "./root.ts";3340/** The config folder's name, from the brand. */34const config = Brand.configDir;3543/** Every file of datekit's maintainers layer, as the layer repo holds it. */36const layerFiles = [37 `${config}/layer.json`,38 `${config}/layer.ts`,39 ".agents/maintainers/finish.md",
56 unmodified lines
96 }).pipe(Effect.provide(NodeServices.layer))97 );98});99108// ------------------------------------------------------------- the layer109100const example = "examples/datekit";101102const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>103 bytes.pipe(Stream.decodeText(), Stream.mkString);104115/** `command` run in `cwd`: how it ended, and both streams. */105const run = (cwd: string, command: string, args: readonly string[]) =>106 Effect.scoped(107 Effect.gen(function* () {108 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
10 unmodified lines
119 return { code: Number(code), output: `${stdout}\n${stderr}` };120 })121 );122134/** A file of the example, as text. */123const exampleFile = (file: string) =>124 Effect.gen(function* () {125 const fs = yield* FileSystem.FileSystem;126 const path = yield* Path.Path;127128 return yield* fs.readFileString(path.join(yield* repoRoot, example, file));129 });130143// Every import of the sdk by the name config files use.131const SDK = new RegExp(`(["'])${Brand.cliPackage}/rules\\1`, "gu");132146/**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 */133const defaultExportOf = (source: string) =>134 Effect.scoped(135 Effect.gen(function* () {136 const fs = yield* FileSystem.FileSystem;
12 unmodified lines
149 );150151 const ran = yield* run(dir, "bun", ["main.ts"]);152171 // 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 lines
160 );161 })162 );163183/** The layer's file at `file`, as text. */164const inLayer = (plan: SeedPlan, file: string) =>165 new TextDecoder().decode(166 plan.layers[0]?.files.find(({ path }) => path === file)?.content167 );168189/** datekit's plan, its maintainers layer, the manifest and the policy. */169const datekit = Effect.gen(function* () {170 const plan = yield* planSeed(example);171 const layer = yield* Effect.fromNullishOr(plan.layers[0]);172
7 unmodified lines
180181 return { layer, manifest, plan, policy };182});183205/** The lanes datekit's `project.ts` runs on every answer: the public checks, by name. */184const publicLanes = Effect.gen(function* () {185 const { run: block } = yield* Schema.decodeUnknownEffect(186 Schema.Struct({187 run: Schema.Struct({
4 unmodified lines
192193 return Object.entries(block.checks);194});195218/** A heading's anchor, as a README link names it: `## Format patterns` is `format-patterns`. */196const anchorOf = (heading: string) =>197 heading198 .toLowerCase()199 .replaceAll(/[^\w\s-]/gu, "")200 .trim()201 .replaceAll(/\s+/gu, "-");202226/** Each README section's text by its anchor: from its heading to the next. */203const sectionsOf = (readme: string) => {204 const sections = new Map<string, string>();205 let current = "";206
113 unmodified lines
320 );321322 expect(unquoted).toStrictEqual([]);323348 // Both kinds of source are cited.324 expect(325 Array.dedupe(326 manifest.checks.map(({ clause }) => clause.source)327 ).toSorted()
29 unmodified lines
357 30_000358 );359});360386/** A folder holding `trees` one over another, each file at its path. */361const treeOf = (...trees: readonly (readonly SeedFile[])[]) =>362 Effect.gen(function* () {363 const fs = yield* FileSystem.FileSystem;364 const path = yield* Path.Path;
49 unmodified lines
414 "test",415 `./checks/held-back/${area}`,416 ]);417444 // 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 !== 0
18 unmodified lines
440 60_000441 );442});443471// ------------------------------------------------------------- the world472473/** A vouched contributor to datekit, who reads no layer. */444const bram = Handle.make("bram");445476/** Paths a public tree must never hold: the layer's, or the example's folder of layers. */446const isLayerPath = (path: string) =>447 ["layers/", "checks/held-back/", ".agents/maintainers/"].some((prefix) =>448 path.startsWith(prefix)449 );
19 unmodified lines
469 "OpenAsk oscabriel/datekit/parse-iso-week: done",470 "Layer datekit--maintainers: done",471 ]);472504 // 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 lines
504 MAIN_REF,505 ].toSorted(),506 });507541 // 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));509510 const published = yield* target.pathsAt(511 project,
12 unmodified lines
524 layerPaths: [],525 visibility: true,526 });527563 // 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 lines
551 posture:552 "Open with sealed evidence · sealed checks in export, parser",553 });554593 // 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);557558 expect({
21 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 ConfigProvider,
24 unmodified lines
29} from "../../../scripts/seed.ts";30import { Brand } from "../../brand/src/index.ts";31import { repoRoot } from "./root.ts";3237/** The config folder's name, from the brand (`Brand.configDir`). */33const config = Brand.configDir;3440/** A file of an example, as the test reads it from disk. */35const onDisk = (example: string, path: string) =>36 Effect.gen(function* () {37 const fs = yield* FileSystem.FileSystem;38 const paths = yield* Path.Path;
145 unmodified lines
184 }).pipe(Effect.provide(NodeServices.layer))185 );186});187194/** Each step as the command prints it. */188const linesOf = (steps: readonly SeedStep[]) => steps.map(stepLine);189190describe(runSeed, () => {191 it.live(
23 unmodified lines
215 ]);216217 const held = yield* seeded(plans);218226 // 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 lines
283 const { failure, refs } = yield* Effect.gen(function* () {284 const stopped = yield* Effect.flip(runSeed(plan));285 const target = yield* SeedTarget;286295 // 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 lines
370 )371 );372});373383/** What `main` prints, line by line, and how it ended. */374const printedBy = (argv: readonly string[]) =>375 Effect.gen(function* () {376 const printed: string[] = [];377
81 unmodified lines
459 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 lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 Effect,
22 unmodified lines
27const decider = Handle.make("ines-v");2829const answerer = Handle.make("bram");3040/** Each person's token in the world: no secret, it never leaves this machine. */31const tokens = {32 answerer: Redacted.make("bram-smoke-loop-world-token-0123456789abcdef"),33 decider: Redacted.make("ines-v-smoke-loop-world-token-0123456789abcd"),34};3546/** A person in a trailer: their handle and the address the platform gives them. */36const credited = (handle: string) =>37 `${handle} <${handle}@users.${Brand.domain}>`;3850/** All a byte stream says, as text. */39const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>40 bytes.pipe(Stream.decodeText(), Stream.mkString);4154/** `git ls-remote <remote> <ref>` as anyone, with no credential at all. */42const anonymousTip = (remote: string, ref: string) =>43 Effect.scoped(44 Effect.gen(function* () {45 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
119 unmodified lines
165 240_000166 );167});168182/**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. */170const refusing = Effect.gen(function* () {171 const asked = yield* Ref.make<readonly string[]>([]);172173 const spawner = ChildProcessSpawner.make((command) =>
24 unmodified lines
198 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),199 };200});201218/**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. */203const scripted = (listed: readonly string[]) =>204 Effect.gen(function* () {205 const asked = yield* Ref.make<readonly string[]>([]);206229 // Each CLI command's `--json` envelope, as the CLI prints it.207 const replies = new Map([208 [209 "status",210 {
32 unmodified lines
243 const [program, args] = ChildProcess.isStandardCommand(command)244 ? [command.command, command.args]245 : ["a pipe", []];246270 // The CLI runs as `bun <entry> <command> … --json`.247 const said =248 program === "bun" ? (args[1] ?? "") : `${program} ${args[0] ?? ""}`;249250 yield* Ref.update(asked, (all) => [...all, said]);
21 unmodified lines
272 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),273 };274 });275300/**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 */276const loopOnScripted = (listed: readonly string[]) =>277 Effect.gen(function* () {278 const fs = yield* FileSystem.FileSystem;279 const path = yield* Path.Path;
233 unmodified lines
modified:packages/config/test/smoke.test.ts+7 added-38 removed
18 unmodified lines
19 SmokeFailed,20 webProbes,21} from "../../../scripts/smoke.ts";2223/** What the fake platform answers one request with, after `delayMs` when given. */23interface Reply {24 readonly status: number;25 readonly body?: string;26 readonly contentType?: string;27 readonly delayMs?: number;28}2931/** A request as the fake platform sees it. */30interface Seen {31 readonly method: string;32 readonly path: string;33 readonly authorized: boolean;34 readonly body: string;35}3639/** A call as effect/rpc's HTTP protocol sends one, with JSON serialization. */37const ListAsksCall = Schema.fromJsonString(38 Schema.Tuple([39 Schema.TaggedStruct("Request", {40 headers: Schema.Array(Schema.Unknown),
4 unmodified lines
45 ])46);4748/**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 */52const rpcReply = (body: string, held: readonly string[]): Reply =>53 Option.match(Schema.decodeOption(ListAsksCall)(body), {54 onNone: () => ({ status: 400 }),
4 unmodified lines
59 status: 200,60 }),61 });6269/** The platform as `healthy` below, holding only the projects `held` names: a stage not seeded holds none. */63const holding =64 (held: readonly string[]) =>65 ({ authorized, body, method, path }: Seen): Reply => {66 if (method === "GET" && path === "/") {
25 unmodified lines
9293 return { status: 404 };94 };95103/**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 */96const healthy = holding(["oscabriel/datekit"]);97111/**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 */98const broken = (seen: Seen): Reply => {99 if (seen.path === "/") {100 return { status: 404 };101 }
16 unmodified lines
118119 return healthy(seen);120};121140/** `answer` served on an ephemeral local port, for the test's scope: its origin. */122const fakePlatform = (answer: (seen: Seen) => Reply) =>123 Effect.gen(function* () {124 const app = Effect.gen(function* () {125 const request = yield* HttpServerRequest.HttpServerRequest;
53 unmodified lines
179 ).toBeTruthy();180 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))181 );182202 // 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 lines
226 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 };233234 const origin = yield* fakePlatform((seen) => {
62 unmodified lines
297 }).pipe(Effect.provide(FetchHttpClient.layer))298 );299});300321/**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 */301const 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 lines
460 });461 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))462 );463490 // 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 lines
493 },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 );499500 it.live(
154 unmodified lines
655 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 );662663 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 }));667668 yield* main(["--stage", "dev-oscabriel", "--url", origin]);669
25 unmodified lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { AnswerView } from "@repo/protocol/domain/answer";4import { ClaimView } from "@repo/protocol/domain/claim";
59 unmodified lines
64);6566const sha = (digit: number) => CommitSha.make(String(digit).repeat(40));6775/** The `n`th event's place in the project's sequence, and its time. */68const 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});7483/**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 */75const takeEvents: readonly ProjectEvent[] = [76 ...children.map((ask, at) =>77 ProjectEvent.cases.Claimed.make({78 ...stamp(at),
184 unmodified lines
263 })264 );265});266280/** The env names the CLI reads, spelled from the brand. */267const SLUG = Brand.slug.toUpperCase();268269const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";270271const tokenOf = (handle: string) =>272 `${handle}-token-0123456789abcdef0123456789ab`;273288/** Whose token `env` carries, if anyone's. */274const holderOf = (env: Readonly<Record<string, string | undefined>>) =>275 handles.find((handle) => env[`${SLUG}_TOKEN`] === tokenOf(handle));276292/** One command the fake world was asked to run. */277interface Spawned {278 readonly command: string;279 readonly args: readonly string[];280 readonly env: Readonly<Record<string, string | undefined>>;281}282299/** How a faked command ends: its exit code and what it printed. */283interface Ending {284 readonly code?: number;285 readonly stdout?: string;286 readonly stderr?: string;287}288289const bytes = (text: string) => Stream.make(new TextEncoder().encode(text));290308/**309 * A `ChildProcessSpawner` that runs nothing: it records each command and310 * ends it as `answer` says.311 */291const fakeSpawner = (answer: (call: Spawned) => Effect.Effect<Ending>) =>292 Effect.gen(function* () {293 const spawned = yield* Ref.make<readonly Spawned[]>([]);294
34 unmodified lines
329 spawned: Ref.get(spawned),330 };331 });332354/** A swarm fixture's text. */333const fixture = (name: string) =>334 Effect.gen(function* () {335 const fs = yield* FileSystem.FileSystem;336 const path = yield* Path.Path;
16 unmodified lines
353 })354 )355);356379/** `handle`'s answer to `ask`, the `n`th they pushed, with its outcome. */357const answerOf = (358 handle: string,359 ask: AskId,360 n: number,
7 unmodified lines
368});369370const landed = Outcome.cases.Landed.make({ sha: LandedSha.make(sha(9)) });371395/**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 */372const statusOf = (handle: string, call: number) => {373 const ask = children[handles.indexOf(handle)] ?? AskId.make("unknown");374375 const refused = answerOf(
15 unmodified lines
391 v: 1,392 });393};394423/** herdr's answer for a pane it made. */395const paneJson = (pane: string) =>396 JSON.stringify({397 id: "cli:pane:split",398 result: { pane: { pane_id: pane, workspace_id: "w9" }, type: "pane_info" },399 });400430/** herdr's answer for an agent that is idle and ready for input. */401const agentJson = (name: string, type: string) =>402 JSON.stringify({403 id: `cli:agent:${type}`,404 result: {
7 unmodified lines
412 type,413 },414 });415446/** What `<cli> claim <ask> --json` prints for `handle`. */416const claimOf = (ask: string, handle: string) => {417 const fork = `burrow--${ask}--${handle}`;418419 return JSON.stringify({
17 unmodified lines
437 v: 1,438 });439};440472/**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 */441const 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 lines
510 if (call.command !== "curl") {511 return Effect.map(answer(call), (stdout) => ({ stdout }));512 }513553 // 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 });519560/** `watch`'s plain JSON replay of a project that holds no event yet. */520const emptyReplay: Ending = {521 stdout:522 '[{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',523};524566/** What herdr puts in the env of a process in one of its panes. */525const inAPane = { HERDR_ENV: "1" };526569/**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 */527const herdrRunWith = (528 herdrEnv: Readonly<Record<string, string>>,529 replay: Ending = emptyReplay530) =>
43 unmodified lines
574 ),575 Effect.result576 );577625 // 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 lines
595 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));596597const herdrRun = herdrRunWith(inAPane);598647/** The herdr calls of a run, as argv. */599const herdrCalls = (spawned: readonly Spawned[]) =>600 spawned.flatMap(({ args, command }) => (command === "herdr" ? [args] : []));601651/** The `agent <verb>` calls among `calls`, by the agent's name. */602const 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 );608659/** The pane each contributor's harness runs in: the layout's order over `w9:p1`, `w9:p2`, …. */609const paneOf = new Map([610 ["wren", "w9:p1"],611 ["counter", "w9:p2"],612 ["marisol", "w9:p3"],
97 unmodified lines
710 .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 lines
859 })860 );861});862914/** What herdr's detection text shows while Claude Code 2.1.293 asks whether to trust a new folder. */863const trustQuestion = [864 " Accessing workspace:",865 "",866 " Quick safety check: Is this a project you created or one you trust?",
1 unmodified line
868 " ❯ No, exit",869 " Yes, I trust this folder",870].join("\n");871924/**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. */873const importsQuestion = [874 " Allow external CLAUDE.md file imports?",875 "",876 " ❯ No, disable external imports",
1 unmodified line
878].join("\n");879880const [wren] = roster;881938/** wren's workspace for run `r1`. */882const 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};888946/** The first of `queue`, taken off it unless it is the last. */889const takeFrom = (queue: Ref.Ref<readonly string[]>) =>890 Ref.modify(queue, (all) => [891 all[0] ?? "",892 all.length > 1 ? all.slice(1) : all,893 ]);894953/**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 */895const blockedStart = (input: {896 readonly states: readonly string[];897 readonly screens: readonly string[];898 readonly clock: Effect.Effect<void>;
135 unmodified lines
1034 })1035 );1036});10371103/**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 */1038const 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("");10441115/**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. */1046const 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 lines
modified: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.4import { NodeServices } from "@effect/platform-node";5import { describe, expect, it } from "@effect/vitest";6import { AnswerView } from "@repo/protocol/domain/answer";7import { ClaimView } from "@repo/protocol/domain/claim";
47 unmodified lines
55import type { AgentWorkspace } from "../../../scripts/lib/swarm/workspace.ts";56import { Brand } from "../../brand/src/index.ts";57import { repoRoot } from "./root.ts";5868/** The env names the CLI reads, spelled from the brand. */59const SLUG = Brand.slug.toUpperCase();6061const token = "wren-token-0123456789abcdef0123456789abcdef";6263const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";6465const ask = AskId.make("drop-legacy-fetch-burrow-auth");6677/** A harness's recorded output: `start`, `resume`, or OpenCode's `refused-model`. */67const recorded = (68 harness: Harness,69 run: "start" | "resume" | "refused-model"70) =>
14 unmodified lines
8586 return text.split("\n").filter((line) => line !== "");87 }).pipe(Effect.provide(NodeServices.layer));88100/** Everything one recorded run's lines say, in order. */89const heard = (driver: HarnessDriver, lines: readonly string[]) =>90 lines.flatMap(driver.parse);9192const sessionsIn = (events: readonly HarnessEvent[]) =>93 events.flatMap((event) =>94 HarnessEvent.$is("SessionStarted")(event) ? [event.id] : []95 );96109// The commits of four answers, and the landing of the last.97const heads = ["1", "2", "3", "4"].map((digit) =>98 CommitSha.make(digit.repeat(40))99);100101const landing = LandedSha.make(CommitSha.make("a".repeat(40)));102116/** One answer to the ask, `n` seconds after noon, with its outcome. */103const 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 lines
150 })151 )152);153168/** What `<cli> status --json` prints for wren with these answers. */154const 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 });161177/** One command the fake spawner was asked to run. */162interface 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}169186/** How a scripted harness run goes: its stdout lines and exit code, or it never ends. */170type HarnessRun =171 | { readonly lines: readonly string[]; readonly code?: number }172 | { readonly stalls: readonly string[] };173174const bytes = (text: string) => new TextEncoder().encode(text);175193/** A process handle that prints `stdout` and ends with `exitCode`. */176const handleOf = (input: {177 readonly stdout: Stream.Stream<Uint8Array>;178 readonly exitCode: Effect.Effect<number>;179}) =>
10 unmodified lines
190 stdout: input.stdout,191 unref: Effect.succeed(Effect.void),192 });193212/**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 */194const fakeWorld = (script: {195 readonly harness: readonly HarnessRun[];196 readonly statuses: readonly string[];197}) =>
81 unmodified lines
279 );280 }),281 });282306/** wren's workspace for run `r1`. */283const dir = "/work/.swarm/r1/wren";284285const wrensWorkspace: AgentWorkspace = {286 clone: `${dir}/clone`,
7 unmodified lines
294 },295 redacted: [`${SLUG}_TOKEN`],296};297322/** The swarm's own env: the user's HOME, and secrets no harness may see. */298const swarmEnv = ConfigProvider.fromEnv({299 env: {300 CLAUDECODE: "1",301 CLOUDFLARE_API_TOKEN: "cf-secret",
3 unmodified lines
305});306307const [wren, tamsin, ivo] = roster;308334/**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 */309const agentRun = (input: {310 readonly harness: readonly HarnessRun[];311 readonly statuses: readonly string[];312 readonly contributor?: Assignment["contributor"];
45 unmodified lines
358 spawned: yield* world.spawned,359 };360 });361392/** The prompt a harness run carried: its last argument. */362const promptOf = (run: Spawned | undefined) => run?.args.at(-1) ?? "";363364describe("the verdict loop", () => {365 it.effect(
261 unmodified lines
627 () =>628 Effect.gen(function* () {629 const start = yield* recorded("claude-code", "start");630662 // 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 lines
803 })804 );805});806840/** A workspace for the golden argv: `/work/.swarm/r1/<handle>`. */807const goldenWorkspace = (handle: string): AgentWorkspace => ({808 clone: `/work/.swarm/r1/${handle}/clone`,809 dir: `/work/.swarm/r1/${handle}`,810 env: {},
286 unmodified lines
modified: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.3import { NodeServices } from "@effect/platform-node";4import { describe, expect, it } from "@effect/vitest";5import { Ask, AskListing } from "@repo/protocol/domain/ask";6import { ClaimView } from "@repo/protocol/domain/claim";
47 unmodified lines
54const burrow = ProjectName.make("oscabriel/burrow");5556const ListedAsks = Envelope(Schema.Struct({ asks: Schema.Array(AskListing) }));5762/** What `<cli> claim <ask> --json` prints. */58const Claimed = Envelope(Schema.Struct({ claim: ClaimView }));5965/** What `<cli> ask <ask> --json` prints, when it shows the ask. */60const 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});6673/** A fixture's text. */67const fixture = (name: string) =>68 Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;
2 unmodified lines
73 path.join("test", "fixtures", "swarm", name)74 );75 });7684/** burrow's open asks, as `<cli> asks --project burrow --json` listed them. */77const burrowAsks = Effect.gen(function* () {78 const envelope = yield* Schema.decodeEffect(79 Schema.fromJsonString(ListedAsks)80 )(yield* fixture("list-asks.json"));
272 unmodified lines
353 expect(354 roster.flatMap(({ adapter, handle }) => (adapter ? [handle] : []))355 ).toStrictEqual(["pell"]);356365 // 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 lines
397 );398 });399});400410/** The ask page `<cli> ask` printed for burrow's auth child. */401const authPage = Effect.gen(function* () {402 const text = (yield* fixture("show-ask.json")).replaceAll(403 "{configDir}",404 Brand.configDir
54 unmodified lines
459 );460 });461});462473/** One command a fake spawner was asked to run. */463interface Spawned {464 readonly command: string;465 readonly args: readonly string[];466 readonly cwd: string | undefined;467 readonly env: Readonly<Record<string, string | undefined>>;468}469481/**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 */470const fakeSpawner = (471 answer: (472 spawned: Spawned,473 before: number
49 unmodified lines
523 spawned: Ref.get(spawned),524 };525 });526543/** The env names the CLI reads, spelled from the brand. */527const SLUG = Brand.slug.toUpperCase();528529const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";530548/** wren's claim of burrow's auth child, as `<cli> claim --json` gives it. */531const wrensClaim = Schema.decodeSync(ClaimView)({532 ask: "drop-legacy-fetch-burrow-auth",533 base: "9998ebe62c2f282d148b1d806372484916cc2548",534 checkCommand: `${Brand.cli} check`,
8 unmodified lines
543});544545const wrensToken = "wren-token-0123456789abcdef0123456789abcdef";546565/** What git prints when the gateway answers 404 for the fork: it is not made yet. */547const forkNotMade = `remote: no repo ${wrensClaim.fork}548fatal: repository '${wrensClaim.remote}/' not found549`;550570/**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 */551const wrensWorkspace = (552 code = 0,553 clone: (before: number) => {554 readonly code?: number;
270 unmodified lines
825 }).pipe(Effect.provide(NodeServices.layer))826 );827});828853/** Why the flags `argv` make no run, or `accepted` when they make one. */829const reasonOf = (argv: readonly string[]) =>830 optionsOf(argv).pipe(831 Effect.match({832 onFailure: ({ reason }) => reason,
124 unmodified lines
957 })958 );959});960986/** What `main` prints, line by line, over a spawner that answers `asks` with the fixture. */961const dryRun = (argv: readonly string[]) =>962 Effect.gen(function* () {963 const fs = yield* FileSystem.FileSystem;964 const swarm = yield* fs.makeTempDirectoryScoped();
16 unmodified lines
981 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 lines
1142 })1143 );1144});11451173/** A fictional person's token on the fake platform: never printed, never in an argv. */1146const tokenOf = (handle: string) =>1147 `${handle}-token-0123456789abcdef0123456789ab`;11481177/**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 */1149const 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 lines
1263 ),1264 Effect.result1265 );12661302 // The TestClock's epoch names the run.1267 const summary = `${swarm}/19700101-000000/agents.json`;12681269 return {1270 agents: (yield* fs.exists(summary))
89 unmodified lines
1360 ["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 lines
1376 const started = yield* fixture(1377 "harness-output/claude-code/start.jsonl"1378 ).pipe(Effect.provide(NodeServices.layer));13791417 // 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 lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 Console,
33 unmodified lines
38const projects = "projects-dev-oscabriel";3940const layers = "layers-dev-oscabriel";4149/** One ledger line, made by `by` on the dev stage; a repo's names its namespace. */42const made = (43 by: Created["by"],44 kind: Created["kind"],45 name: string,
17 unmodified lines
63});6465const namespace = (name: string): Listed => ({ kind: "namespace", name });6675/** A smoke run's project and repos, and a `seed --as` swarm copy's. */67const 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 lines
78 ),79 made("seed", "repo", "datekit-805--maintainers", layers),80];8191/** What the account lists: every ledger repo, and much that isn't the ledger's. */82const listed: readonly Listed[] = [83 repo("datekit"),84 repo("burrow"),85 repo("smoke-r1"),
10 unmodified lines
96 namespace("layers-demo"),97 namespace("witness"),98];99110/** Two imports of the preview repos, kept: each one's project and repo line. */100const imports: readonly Created[] = [101 made("import", "project", "anyhow"),102 made("import", "repo", "anyhow", projects),103 made("import", "project", "ky"),
159 unmodified lines
263 ).toStrictEqual([]);264 });265});266278/** A fresh ledger file in a temp dir, for the scope of one test. */267const 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 lines
381 ]);382 });383});384397/**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. */386const memoryAccount = (repos: Readonly<Record<string, readonly string[]>>) =>387 Effect.gen(function* () {388 const read = yield* Ref.make<readonly string[]>([]);389
22 unmodified lines
412 )413 )414 );415431 /** 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.orDie
17 unmodified lines
437 standing,438 };439 });440457/** A temp root with a ledger written from `entries` and no recording lock. */441const tempRoot = (entries: readonly Created[]) =>442 Effect.gen(function* () {443 const fs = yield* FileSystem.FileSystem;444 const path = yield* Path.Path;
6 unmodified lines
451452 return { ledgerFile, lock: path.join(dir, ".recording") };453 });454472/** `teardown(argv)` over `account`: how it ended, and what it printed. */455const tornDown = (456 argv: readonly string[],457 account: TeardownAccount["Service"],458 files: { readonly ledgerFile: string; readonly lock: string }
18 unmodified lines
477478 return { printed, result };479 });480499/** The dev stage's two namespaces as a smoke run, a swarm copy and the seed left them. */481const devRepos = {482 [layers]: ["datekit--maintainers", "datekit-805--maintainers"],483 [projects]: [484 "datekit",
6 unmodified lines
491 "w3live-muyjz31t",492 ],493};494514/** The ledger: `ledger` above, one repo already gone, and one in `witness`. */495const devLedger: readonly Created[] = [496 ...ledger,497 made("smoke", "repo", "smoke-r0", projects),498 made("smoke", "repo", "smoke-r9", "witness"),
132 unmodified lines
631 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 lines
modified:packages/config/test/verify.test.ts-2 removed
17 unmodified lines
18 .scripts;19});2021describe("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 lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Effect, FileSystem, Path, Schema } from "effect";4
7 unmodified lines
12} from "../../../infra/stages.ts";13import { budgets, workers } from "../../../scripts/startup-budget.ts";14import { repoRoot } from "./root.ts";1526/** A file under the repo root, as text, once its presence is asserted. */16const presentText = (file: string) =>17 Effect.gen(function* () {18 const fs = yield* FileSystem.FileSystem;19 const path = yield* Path.Path;
3 unmodified lines
2324 return yield* fs.readFileString(at);25 }).pipe(Effect.provide(NodeServices.layer));2638/** A JSON (or JSONC) file under the repo root, decoded by `schema`. */27const presentJson = <S extends Schema.Top>(file: string, schema: S) =>28 Effect.flatMap(presentText(file), (text) =>29 Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(blankJsonc(text))30 );3144/** The binding kinds that would reach storage or run code: none in the web. */32const STORAGE = [33 "artifacts",34 "d1_databases",35 "durable_objects",
32 unmodified lines
68const RootManifest = Schema.Struct({69 workspaces: Schema.Struct({ packages: Schema.Array(Schema.String) }),70});7185/**86 * Whether a workspace glob's parts match a folder's segments: `*` is one87 * segment, `**` any number of them.88 */72const globMatches = (73 parts: readonly string[],74 segments: readonly string[]75): boolean => {
67 unmodified lines
143 }144 })145 );146164 // 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 lines
226 it("measures the web Worker", () => {227 expect(workers.map(({ dir }) => dir)).toContain("apps/web");228 });229247 // 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