Skip to content
Myr

Merge build/comments-packages-rest into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents e4c407e, 6273b84 · Browse files · 212 files+211 added−2706 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

212 files+211 added−2706 removed

  • tests:+67 added−981 removed
  • other:+144 added−1725 removed

212 files+211 added−2706 removed

This commit is too large to show whole: its files are listed by path, without their changes.

modified:packages/agent-kit/src/docs/answer-an-ask.ts-5 removed
1/**2 * The contributor's guide: install and sign in, find an ask, claim it,3 * answer it in git, check it before the push, push, read the verdict, and4 * what to do when it is refused.5 */1import { Brand } from "@repo/brand";23import { installCommand } from "../install.ts";4import { code } from "../text.ts";
58 unmodified lines
modified:packages/agent-kit/src/docs/connect-an-agent.ts-6 removed
1/**2 * The agent guide: the ways an agent reaches the platform, each pointing3 * to the For agents page that holds the exact setup, and the rules that4 * hold for any agent.5 */61import { code } from "../text.ts";2import type { DocSource } from "./page.ts";3import { cli } from "./page.ts";4
23 unmodified lines
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
1/**2 * The visibility guide: layers and their audiences, held-back checks and3 * what an answerer learns of them, the posture and the ledger anyone can4 * read, and the env shape with its write-only values.5 */1import { Brand } from "@repo/brand";23import { code } from "../text.ts";4import type { DocSource } from "./page.ts";
51 unmodified lines
modified:packages/agent-kit/src/docs/imported-note.ts-5 removed
1/**2 * What an imported project is, in the words the docs' Imported projects3 * page, the project's own page and the CLI's `policy` share. A module of4 * its own, so a page that says it does not carry the imported list.5 */1export const IMPORTED_NOTE =2 "a copy of a public repo, read-only here and not run by its maintainers";
modified:packages/agent-kit/src/docs/imported.ts-13 removed
1/**2 * The open-source projects imported onto the platform for reading, each a3 * copy of a public repo under its own licence, read-only here and not run4 * by its maintainers. A copy of the import script's plan, which a test in5 * `packages/config` holds equal to it, so the docs can name each one's6 * source and licence.7 */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
modified:packages/drafting/src/draft-runs/canned.ts-10 removed
1/**2 * The draft the worlds without a model give every proposal drafted in them3 * (the web's dev world, the platform's Node world): an ask for a reader of4 * ordinal dates in `src/parse.ts`, whose test fails on main by its5 * assertion wherever that file has none, in datekit and in smoke's6 * throwaway project alike. So `bun run dev` and `smoke --loop --draft`7 * show a draft end to end, offline.8 */1import { AskId, RepoPath } from "@repo/protocol/ids";2import { Array } from "effect";3import type { Layer } from "effect";4
1 unmodified line
6import type { Drafter } from "../drafter.ts";7import { DrafterMemory } from "../drafter/memory.ts";8import type { DraftsAsked } from "../drafter/memory.ts";918/** How many drafts a world gives before its drafter's script runs out. */10const CANNED_DRAFTS = 64;1112export const cannedDraft = {13 current: "src/parse.ts reads no ordinal date.",
17 unmodified lines
31 },32 want: "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.",33} satisfies DraftedAsk;3444/** The memory drafter, scripted with the canned draft for every attempt a world makes. */35export const cannedDrafter: Layer.Layer<Drafter | DraftsAsked> = DrafterMemory(36 Array.replicate(cannedDraft, CANNED_DRAFTS)37);
modified:packages/drafting/src/draft-runs/inline.ts+3 added-22 removed
1/**2 * `DraftRuns` in process, for tests and the worlds that run without a3 * Workflow engine (the web's dev world, the platform's Node world): `start`4 * runs the round's program (`runDraft`) at once, to its settling, as5 * `@repo/project`'s `AnswerRunsInline` runs an answer's steps. Each step runs6 * once, its failures retried as its retries say, without waiting; nothing7 * is recorded, since nothing replays. A round already under way is not8 * started twice, and a run that dies is logged: the proposal stays9 * drafting, and its proposer may draft it again.10 *11 * The run reaches the project through `Projects`, which is built over the12 * project services that start runs: so the runs take their ports when a13 * round starts (`draftRunsInline`), and `withDraftRunsInline` ties the knot14 * for a `Projects` layer, handing its runs the `Projects` it builds.2 * `Projects` is built over the project services that start runs, so the runs3 * take their ports when a round starts, and `withDraftRunsInline` ties the4 * knot, handing its runs the `Projects` it builds.5 */6import type { RepoHost } from "@repo/artifacts/repo-host";7import { DraftRuns } from "@repo/project/draft-runs";8import type { DraftParams } from "@repo/project/draft-runs";
3 unmodified lines
12import type { Drafter } from "../drafter.ts";13import { runDraft } from "../run.ts";14import type { DraftSteps } from "../run.ts";1526/** What a round runs on. */16export type InlinePorts = Projects | Drafter | RepoHost;1729/** Steps run once each, in process: a failure retried as its retries say, at once. */18const inlineSteps: DraftSteps = {19 step: (_name, _schema, effect, retry) =>20 Effect.retry(effect, { times: retry?.limit ?? 0 }),21};2235/** One round's key: its project, proposal and round. */23const keyOf = ({ project, proposal, round }: DraftParams) =>24 `${project}/${proposal}/${round}`;2539/** `DraftRuns` that run each round in process, on the ports `portsOf` gives when it starts. */26export const draftRunsInline = (27 portsOf: Effect.Effect<Context.Context<InlinePorts>>28): Layer.Layer<never> =>29 Layer.effect(
35 unmodified lines
65 };66 })67 );6883/**84 * `projects` with in-process draft runs: every project service it builds85 * starts its rounds through `draftRunsInline`, which reaches the projects86 * through the `Projects` this layer builds.87 */69export const withDraftRunsInline = <E, R>(70 projects: Layer.Layer<Projects, E, R>71): Layer.Layer<Projects, E, R | Drafter | RepoHost> =>72 Layer.effectContext(
14 unmodified lines
modified:packages/drafting/src/drafter/binding.ts+8 added-41 removed
1/**2 * The `Drafter` over Workers AI, through the platform's `AI` binding3 * (ADR 0018): one chat call that asks for JSON matching `DraftedAsk`'s JSON4 * Schema. Workers AI can't promise the model keeps to the schema, so the5 * reply is decoded with Effect Schema whatever the model claims6 * (principle 2). Nothing here logs: a prompt carries the project's files.7 */1// Workers AI can't promise the model keeps to the schema, so the reply is2// decoded whatever the model claims. Nothing here logs: a prompt carries the3// project's files.4import { Effect, Hash, Layer, Predicate, Schema } from "effect";5import type { JsonSchema } from "effect";67import { DraftedAsk, DraftedReply, DraftFailed } from "../drafted.ts";
1 unmodified line
9import { Drafter } from "../drafter.ts";10import { systemPrompt, userPrompt } from "../prompt.ts";1112/**17 * The slice of the Workers `Ai` binding the drafter calls: `run` with a18 * model named by a var, so the generated type's fallback overload. The19 * generated `Ai` is held to it by a type test, so tests pass a fake.13 * `run` with a model named by a var, so the generated type's fallback14 * overload. A type test holds the generated `Ai` to it, so tests pass a fake.15 */16export interface AiLike {17 readonly run: (model: string, inputs: ChatInputs) => Promise<object>;18}1925/** One chat message. */20export interface ChatMessage {21 readonly content: string;22 readonly role: "system" | "user";23}2431/**32 * How hard a reasoning model thinks before it answers, in the key a Workers33 * AI chat call takes it (glm-5.3: max, high or low; gpt-oss-120b: low,34 * medium or high; `@cloudflare/workers-types` 5.20261006.1).35 */25export interface ReasoningInputs {26 readonly reasoning_effort: "low";27}2840/**41 * What the drafter sends: the messages, the JSON Schema the reply must42 * match, the sampling it asks for, and the model's own settings43 * (`modelSettings`). A type alias, not an interface, so it fits the44 * binding's open `Record` of inputs.45 */29/** A type alias, not an interface, so it fits the binding's open `Record` of inputs. */30export type ChatInputs = Partial<ReasoningInputs> & {31 readonly max_completion_tokens: number;32 readonly messages: readonly ChatMessage[];33 readonly response_format: {
3 unmodified lines
37 readonly seed: number;38 readonly temperature: number;39};4057/** What a model is asked with beyond the prompt: its output cap, and how hard it reasons. */41export interface ModelSettings {42 readonly max_completion_tokens: number;60 /** The model's own reasoning input, sent as it stands; none sends nothing. */43 readonly reasoning?: ReasoningInputs;44}4564/** What a model not in `MODEL_SETTINGS` is asked with: `DRAFT_MODEL`'s settings. */46const DEFAULT_SETTINGS: ModelSettings = { max_completion_tokens: 12_000 };4748/**68 * The fallback models reason before they answer, and spent 12,000 tokens69 * doing so on the drafting prompt before the JSON was done. Each70 * gets more room and a low effort, in the key its Workers AI input schema71 * takes for a chat call (`ReasoningInputs`).49 * The fallback models spent 12,000 tokens reasoning on the drafting prompt50 * before the JSON was done, so each gets more room and a low effort.51 */52const FALLBACK_SETTINGS: ModelSettings = {53 max_completion_tokens: 32_000,54 reasoning: { reasoning_effort: "low" },55};5678/** Settings by Workers AI model id; `DRAFT_MODEL` (kimi-k2.7-code) takes the defaults. */57const MODEL_SETTINGS: ReadonlyMap<string, ModelSettings> = new Map([58 ["@cf/moonshotai/kimi-k2.7-code", DEFAULT_SETTINGS],59 ["@cf/zai-org/glm-5.3", FALLBACK_SETTINGS],60 ["@cf/openai/gpt-oss-120b", FALLBACK_SETTINGS],61]);6285/** What `model` is asked with beyond the prompt; the defaults for a model not listed. */63export const modelSettings = (model: string): ModelSettings =>64 MODEL_SETTINGS.get(model) ?? DEFAULT_SETTINGS;6589/** `DraftedAsk` as JSON Schema, for `response_format`: an object root, no `$ref`. */66const responseSchema = (() => {67 const { definitions, schema } = Schema.toJsonSchemaDocument(DraftedAsk);6869 return Object.keys(definitions).length === 070 ? schema71 : { ...schema, $defs: definitions };72})();7398/** What a chat reply carries: OpenAI's `choices`, or Workers AI's own `response`. */74const Reply = Schema.Union([75 Schema.Struct({76 choices: Schema.NonEmptyArray(77 Schema.Struct({ message: Schema.Struct({ content: Schema.String }) })
10 unmodified lines
88const decodeReply = Schema.decodeUnknownEffect(Reply);8990const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));91117/** A reply's fields, where one sentence may stand for a list of them. */92const decodeDrafted = Schema.decodeUnknownEffect(DraftedReply);93120/** A reply wrapped in one Markdown code fence, unwrapped. */94const unfenced = (text: string) =>95 /^\s*```[\w-]*[^\S\n]*\n(?<body>[\s\S]*?)\n?```\s*$/u.exec(text)?.groups96 ?.body ?? text;9798const failed = (reason: DraftFailed["reason"]) => new DraftFailed({ reason });99127/**128 * The draft a decoded reply holds: its text unfenced and parsed, or the129 * object Workers AI already parsed from it, then decoded as `DraftedAsk`.130 */100const draftedOf = (101 reply: typeof Reply.Type102): Effect.Effect<DraftedAsk, DraftFailed> => {103 const content =
8 unmodified lines
112 (parsed) => Effect.mapError(decodeDrafted(parsed), () => failed("schema"))113 );114};115147/** Why a call to the binding threw, from its text: Workers AI names its errors by code. */116const reasonOf = (thrown: string): DraftFailed["reason"] => {117 if (/\b(?:429|3040)\b|rate.?limit/iu.test(thrown)) {118 return "rate-limited";119 }
8 unmodified lines
128 `${input.context.project}:${input.context.at}:${input.attempt}:${input.want}`129 )130 );131164/** The drafter over `ai`, asking `model` (the platform's `DRAFT_MODEL`) with its settings. */132export const DrafterWorkersAi = (133 ai: AiLike,134 model: string135): Layer.Layer<Drafter> => {
46 unmodified lines
modified:packages/drafting/src/drafter/memory.ts-8 removed
1/**2 * The `Drafter` in memory: each call takes the next answer from a script3 * (a drafted ask, or the failure to give), and every input is kept for the4 * test to read (`DraftsAsked`). A call past the script's end is the test's5 * defect.6 */1import { Context, Effect, Layer, Ref, Schema } from "effect";23import { DraftFailed } from "../drafted.ts";4import type { DraftedAsk, DraftInput } from "../drafted.ts";5import { Drafter } from "../drafter.ts";67const isFailure = Schema.is(DraftFailed);815/** What the memory drafter was asked, in order. */9export class DraftsAsked extends Context.Service<10 DraftsAsked,11 { readonly inputs: Effect.Effect<readonly DraftInput[]> }12>()("drafting/DraftsAsked") {}1321/** A drafter that answers `script` in order, one entry per call. */14export const DrafterMemory = (15 script: readonly (DraftedAsk | DraftFailed)[]16): Layer.Layer<Drafter | DraftsAsked> =>17 Layer.effectContext(
24 unmodified lines
modified:packages/drafting/src/context.ts+5 added-28 removed
1/**2 * What the drafter reads: files picked from the project's canonical tree at3 * the landed commit, deterministically, within a byte budget (ADR 0018).4 * The caller hands the tree and a reader over the canonical repo only, so5 * no layer's repo can be read here; a path that looks like a layer's or a6 * held-back check's is refused anyway, as is an env file.2 * A path that looks like a layer's or a held-back check's is refused even3 * though the caller hands a reader over the canonical repo only.4 *5 * The order is the priority: an existing ask with its test as a style6 * example (first, so no long README can spend the budget it needs), the7 * root READMEs, the root manifest, the project module, then the11 * territory's files (or, with none given, the source files whose path12 * shares the most words with the want, at most 12), each source with its13 * sibling tests, and last every other README. Each file is cut at 40 KB,14 * and the rest of the budget cuts the next one, both with a marker.8 * territory's files (or the source files whose path shares the most words9 * with the want), each source with its sibling tests, and last every other10 * README.11 */12import { Brand } from "@repo/brand";13import type { ConfigFile } from "@repo/protocol/domain/common";14import { RepoPath } from "@repo/protocol/ids";15import { Array, Effect, Option, Order, Schema, pipe } from "effect";1621/** The bytes the model reads in all, about 50k tokens. */17const defaultBudget = 200 * 1024;1824/** The most of one file the model reads. */19const perFile = 40 * 1024;2027/** Room kept for a cut file's marker. */21const markerRoom = 64;2230/** Source files ranked by the want, when no territory is given. */23const rankedFiles = 12;2425const manifests = new Set([26 "Cargo.toml",
70 unmodified lines
9798 return name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : "";99};100109/** A layer's file, a held-back check, or an env file: never read. */101const isWithheld = (path: string) =>102 path.startsWith(`${Brand.configDir}/layers/`) ||103 segmentsOf(path).some(104 (segment) =>
18 unmodified lines
123 path.startsWith(askFolder) &&124 path.endsWith(askSuffix) &&125 !path.slice(askFolder.length).includes("/");126136/** A file's name without its extensions: `add.test.ts` is `add`. */127const stemOf = (path: string) => baseName(path).split(".")[0] ?? "";128139/** A word and its camel-case parts, lower-cased: `addMonths` → addmonths, add, months. */129const wordsOf = (text: string): readonly string[] =>130 text131 .split(/[^A-Za-z0-9]+/u)132 .flatMap((word) =>
7 unmodified lines
140 ]141 )142 .filter((word) => word.length >= 3 && !stopWords.has(word));143155/** How many of the want's words a path shares, its extension left out. */144const overlap = (want: ReadonlySet<string>, path: string) =>145 Array.dedupe(146 wordsOf(path.slice(0, path.length - extensionOf(path).length))147 ).filter((word) => want.has(word)).length;
2 unmodified lines
150 readonly path: string;151 readonly score: number;152}153166/** Most shared words first, then by path. */154const byScore = Order.combine(155 Order.mapInput(Order.flip(Order.Number), ({ score }: Ranked) => score),156 Order.mapInput(Order.String, ({ path }: Ranked) => path)157);158172/** The source files whose path shares a word with the want, most first, at most `rankedFiles`. */159const ranked = (paths: readonly string[], want: ReadonlySet<string>) =>160 paths161 .flatMap((path): Ranked[] => {162 const score = isSource(path) ? overlap(want, path) : 0;
3 unmodified lines
166 .toSorted(byScore)167 .slice(0, rankedFiles)168 .map(({ path }) => path);169184/** The tests beside a source file: the same stem with a test suffix, anywhere. */170const siblingTests = (tree: readonly string[], source: string) => {171 const stem = stemOf(source);172173 return tree.filter(
5 unmodified lines
179};180181const decodeLiteral = Schema.decodeOption(Schema.fromJsonString(Schema.String));182198/** The test file an ask file names in its `path`, when it names one. */183const askTestPath = (source: string): Option.Option<string> =>184 pipe(185 Option.fromNullishOr(186 /\bpath:\s*(?<literal>"(?:[^"\\\n]|\\.)*")/u.exec(source)?.groups?.literal187 ),188 Option.flatMap(decodeLiteral)189 );190207/** The folder the picked style example's test sits in: the project's ask-test folder. */191export const askTestFolderOf = (192 files: readonly ConfigFile[]193): Option.Option<string> =>194 pipe(
5 unmodified lines
200const encoder = new TextEncoder();201202const decoder = new TextDecoder();203221/** `content` cut to at most `room` bytes and its marker, or none when nothing fits. */204const cut = (content: string, room: number): Option.Option<string> => {205 const bytes = encoder.encode(content);206207 if (bytes.length <= Math.min(room, perFile)) {
8 unmodified lines
216 `${decoder.decode(bytes.slice(0, shown)).replace(/�$/u, "")}\n[cut: the first ${shown} of ${bytes.length} bytes]\n`217 );218};219238/**239 * The files the model reads for a want, in the order above, each read once240 * through `read` and the whole within `budget` bytes. The same tree, in any241 * order, and the same want give the same files.242 */220export const pickFiles = (221 tree: readonly RepoPath[],222 input: { readonly want: string; readonly territory?: readonly RepoPath[] },223 read: (path: RepoPath) => Effect.Effect<string>,
78 unmodified lines
modified:packages/drafting/src/drafted.ts+6 added-39 removed
1/**2 * What drafting reads and writes. The model returns `DraftedAsk`, fields3 * only: code renders the ask file from them, so only the test file is the4 * model's own text. `DraftContext` is what it reads, from the canonical5 * repo at the landed commit (never a layer's), and `DraftInput` one6 * attempt's question. `DraftFailed` stays inside the run: it is no public7 * refusal.8 */1/** `DraftFailed` stays inside the run: it is no public refusal. */2import { Brand } from "@repo/brand";3import { AtLeastOne } from "@repo/protocol/domain/common";4import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";5import { Schema, SchemaTransformation } from "effect";614/** A string the model writes, bounded so no reply fills the Worker. */7/** Bounded so no reply fills the Worker. */8const Text = Schema.NonEmptyString.check(Schema.isMaxLength(4000));917/** A path in the tree as git names it: relative, with no empty, `.` or `..` segment. */10const TreePath = RepoPath.check(11 Schema.makeFilter(12 (path: string) =>13 path
7 unmodified lines
21 )22);2324/**33 * Where the drafted test goes: anywhere in the tree but the config folder,34 * which only code writes. The test is the model's own text, so a test path35 * there would land model text as an ask file or the project's policy.25 * Anywhere in the tree but the config folder: the test is the model's own26 * text, so a test path there would land model text as an ask file or policy.27 */28const TestPath = TreePath.check(29 Schema.makeFilter(30 (path: string) =>
3 unmodified lines
34 { expected: `a path outside ${Brand.configDir}/` }35 )36);3747/** One ask, drafted: only `fix` asks are drafted. */38export const DraftedAsk = Schema.Struct({39 context: Schema.optionalKey(Schema.Array(Text)),40 current: Schema.optionalKey(Text),51 /** Becomes `<config>/asks/<id>.ask.ts`. */41 id: AskId,42 kind: Schema.Literal("fix"),43 outOfScope: Schema.optionalKey(Schema.Array(Text)),44 /** Shown to the decider as evidence; never landed. */45 rationale: Schema.String.check(Schema.isMaxLength(4000)),57 /** The files an answer may change. */46 territory: Schema.NonEmptyArray(TreePath),59 /** The ask's check: a test that fails on main by an assertion. */47 test: Schema.Struct({48 path: TestPath,49 source: Schema.NonEmptyString.check(Schema.isMaxLength(100_000)),50 }),64 /** One testable sentence. */51 want: Text,52});5354export type DraftedAsk = typeof DraftedAsk.Type;5556/**71 * Sentences as a model may send them: a list, or one sentence alone, which72 * decodes as a list of one. Workers AI does not hold a model to the JSON73 * Schema it is asked for: kimi-k2.7-code sent `context` and `outOfScope` as74 * strings on every attempt, live on dev-oscabriel.57 * A list, or one sentence alone, which decodes as a list of one: Workers AI58 * does not hold a model to the JSON Schema it is asked for.59 */60const Sentences = Schema.Union([61 Schema.Array(Text),62 Text.pipe(
6 unmodified lines
69 )70 ),71]);7289/**90 * A model's reply, decoded into a `DraftedAsk`: the same fields, but a91 * list of sentences may come as one sentence. The model is still asked for92 * `DraftedAsk`'s JSON Schema.93 */73export const DraftedReply = Schema.Struct({74 ...DraftedAsk.fields,75 context: Schema.optionalKey(Sentences),76 outOfScope: Schema.optionalKey(Sentences),77});78100/** One file the drafter reads, as text. */79export const ContextFile = Schema.Struct({80 content: Schema.String,81 path: RepoPath,82});8384export type ContextFile = typeof ContextFile.Type;85108/**109 * What a draft reads: the project's public policy as a short digest, and110 * the files picked from its canonical tree at the landed commit.111 */86export const DraftContext = Schema.Struct({87 at: LandedSha,88 files: Schema.Array(ContextFile),89 policy: Schema.String,
1 unmodified line
91});9293export type DraftContext = typeof DraftContext.Type;94121/** One attempt's question: the want, what it reads, and what went wrong before. */95export const DraftInput = Schema.Struct({96 attempt: AtLeastOne,97 context: DraftContext,125 /** The last attempt's refusal and its output's tail, for the next to mend. */98 feedback: Schema.optionalKey(Schema.String),127 /** A decider's or the proposer's note on what to do differently. */99 note: Schema.optionalKey(Schema.String),100 territory: Schema.optionalKey(Schema.NonEmptyString),101 want: Schema.NonEmptyString,102});103104export type DraftInput = typeof DraftInput.Type;105135/**136 * The model gave no draft: its reply was no JSON, or not the schema's, it137 * was rate-limited, or it failed.138 */106export class DraftFailed extends Schema.TaggedError<DraftFailed>()(107 "DraftFailed",108 {109 reason: Schema.Literals([
7 unmodified lines
modified:packages/drafting/src/drafter.ts-6 removed
1/**2 * The `Drafter` port: the platform's agent that drafts an ask from a want.3 * Adapters: `/memory` (a scripted queue, for tests and the web's dev world)4 * and `/binding` (Workers AI through the `AI` binding).5 */1import { Context } from "effect";2import type { Effect } from "effect";34import type { DraftFailed, DraftedAsk, DraftInput } from "./drafted.ts";56export class Drafter extends Context.Service<7 Drafter,8 {14 /** One attempt: the drafted ask's fields, or why the model gave none. */9 readonly draft: (10 input: DraftInput11 ) => Effect.Effect<DraftedAsk, DraftFailed>;12 }
1 unmodified line
modified:packages/drafting/src/prompt.ts+2 added-27 removed
1/**2 * What the platform's agent is told. The system prompt holds the rules of a3 * good draft and a digest of the project's public policy; the user prompt4 * holds the want, the files picked for it and, from attempt 2 on, what went5 * wrong with the last attempt.6 *7 * The digest is built from a `PublicPolicy`, and reads only its kinds,8 * modules, run block and deciders, so no layer, held-back check or reason9 * from `visibility` can reach a prompt. The product's name comes from10 * `Brand`.11 */1// The policy digest reads only a `PublicPolicy`'s kinds, modules, run block2// and deciders, so no layer, held-back check or reason can reach a prompt.3import { Brand } from "@repo/brand";4import type { PublicPolicy } from "@repo/protocol/domain/policy";5import type { Refusal } from "@repo/protocol/refusal";6import { explain } from "@repo/protocol/render";7import { Option } from "effect";89import type { DraftInput } from "./drafted.ts";1020/** The most of a failing run's output an attempt is shown: its last 4 KB. */11const tailBytes = 4 * 1024;1223/** Why the last attempt's draft did not open: the gate's refusal, its diagnosis and the run's output. */13export interface Feedback {25 /** The red-first diagnosis: `Passed`, `LoadError`, `Weak` and the like. */14 readonly diagnosis: string;27 /** The failing run's output; only its tail is shown. */15 readonly excerpt: string;16 readonly refusal: Refusal;17}1832/**33 * The project's public policy, as the system prompt states it: its ask34 * kinds, its modules, its run block, its deciders, and the folder its ask35 * tests sit in (from the picked style example, `askTestFolderOf`).36 */19export const policyDigest = (20 policy: PublicPolicy,21 askTests: Option.Option<string>22): string =>
15 unmodified lines
38 onSome: (folder) => `Ask tests go in: ${folder}/`,39 }),40 ].join("\n");4160/** The rules of a draft, then the project's policy digest. */42export const systemPrompt = (digest: string): string =>43 [44 `You draft one ask for a project hosted on ${Brand.name}. An ask is a file in which a project states one change it wants: a behavioural want, a territory, and a test that fails on main today.`,45 "",
22 unmodified lines
68const encoder = new TextEncoder();6970const decoder = new TextDecoder();7191/** The last `tailBytes` of a run's output, starting on a whole line where one fits. */72const tailOf = (output: string) => {73 const bytes = encoder.encode(output);7475 if (bytes.length <= tailBytes) {
6 unmodified lines
8283 return tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : tail;84};85106/**107 * The last attempt's failure as the next one reads it: the refusal as108 * `protocol/render` gives it, the diagnosis, and the output's tail.109 */86export const feedbackText = (feedback: Feedback): string =>87 [88 ...explain([feedback.refusal]),89 `diagnosis: ${feedback.diagnosis}`,90 "output (its end):",91 tailOf(feedback.excerpt),92 ].join("\n");93118/** One attempt's question: the want, what to change, the files, and the last failure. */94export const userPrompt = (input: DraftInput): string =>95 [96 `Project: ${input.context.project}, at ${input.context.at}.`,97 `Want: ${input.want}`,
21 unmodified lines
modified:packages/drafting/src/render.ts+3 added-16 removed
1/**2 * The ask file, written by code from a draft's fields (ADR 0018): the model3 * never writes the `.ask.ts` source, so it cannot put code there. Every4 * string it gave enters the file through `JSON.stringify`, as a string5 * literal, and a field it left out (or gave empty) is left out. Only the6 * test file is the model's own text.7 */1// The model never writes the `.ask.ts` source: every string it gave enters the2// file through `JSON.stringify`, as a string literal. Only the test file is3// the model's own text.4import { Brand } from "@repo/brand";5import type { ConfigFile } from "@repo/protocol/domain/common";6import { RepoPath } from "@repo/protocol/ids";7
2 unmodified lines
10const text = (value: string) => JSON.stringify(value);1112const list = (values: readonly string[]) => `[${values.map(text).join(", ")}]`;1318/** Each drafted kind's handle in the rules package: drafts are `fix` asks only, for now. */14const kindHandle = { fix: "kinds.fix" } as const satisfies Record<15 DraftedAsk["kind"],16 string17>;1824/**25 * The `.ask.ts` source for a draft: the rules import by the CLI package's26 * name, then `kinds.fix.ask({ … })` with its keys sorted.27 */19export const renderAskFile = (drafted: DraftedAsk): string => {20 const fields: readonly (readonly [string, string | undefined])[] = [21 [22 "context",
27 unmodified lines
50 "",51 ].join("\n");52};5363/**64 * A draft as a proposal's files: its ask file under the config folder's65 * `asks/`, named by its id (what `askIdOf` reads back), then its test.66 */54export const draftedFiles = (55 drafted: DraftedAsk56): readonly [ConfigFile, ConfigFile] => [57 {
5 unmodified lines
modified:packages/drafting/src/run.ts+1 added-43 removed
1/**2 * One draft run, as a program over named steps (ADR 0018): the platform's3 * `Answer` Workflow runs it with durable steps (`apps/platform`'s4 * `workflows/draft-steps.ts`), and `draft-runs/inline.ts` runs it in5 * process, so both reach the same end.2 * Each step's value is recorded, so a replay never asks the model again.3 *7 * - `context`: the project's open proposal (`draftContext`), and the files8 * the drafter reads, picked from the canonical repo at the landed commit9 * and read there (never a layer's repo). The step records them, so a10 * replay reads nothing. A project with no `fix` kind settles at once,11 * `Failed{IncompleteBrief}`, with no model call.12 * - for each attempt n, at most `DRAFT_ROUNDS`: `draft-<n>`, the model's13 * draft, recorded as `DraftedAsk`, so a replay never asks the model14 * again; then `rehearse-<n>`, its files rehearsed as `accept` would open15 * them (`rehearseOpen`). `Red` ends the round; `Refused` becomes the next16 * attempt's feedback (the refusal as `protocol/render` says it, the17 * diagnosis and the output's tail). A draft the model could not give is18 * a spent attempt, except `rate-limited`, which the step retries.19 * - `settle`: the round's end, told to the project (`draftSettled`), which20 * ignores a round no longer current.21 *4 * A step whose retries are spent is kept failed by the engine and thrown5 * again, unrun, in every replay, where its typed failure is gone: so what6 * the program makes of it is recorded as a value in a step of its own7 * (`<step>:gave-up`), which every replay reads back.
13 unmodified lines
21import { Drafter } from "./drafter.ts";22import { feedbackText, policyDigest } from "./prompt.ts";23import { draftedFiles } from "./render.ts";2443/** How often, and how far apart, a failed step runs again before it is spent. */25export interface StepRetry {26 readonly limit: number;27 readonly delayMs: number;28 readonly backoff: "constant" | "linear" | "exponential";29}3050/**51 * The steps a run takes: each named, its value recorded by `schema`, and52 * run once per run (a replay reads the record back). A failure is retried53 * per `retry`, and once spent fails the step.54 */31export interface DraftSteps {32 readonly step: <A, I, E, R>(33 name: string,34 schema: Schema.Codec<A, I>,
1 unmodified line
36 retry?: StepRetry37 ) => Effect.Effect<A, E, R>;38}3964/**65 * The model the drafter asks, as a settled round names it (`drafted by`,66 * and the accepted landing's `Assisted-by:`). The platform gives its67 * `DRAFT_MODEL`; a world with the memory drafter keeps the default.68 */40export const DraftModel = Context.Reference<string>("drafting/DraftModel", {41 defaultValue: () => "memory",42});4373/** A rate-limited model is asked again, further apart each time. */44export const rateLimitedRetry: StepRetry = {45 backoff: "exponential",46 delayMs: 15_000,47 limit: 4,48};4980/** A Checker that could not run, or a main that moved, is rehearsed again. */50export const blockedRetry: StepRetry = {51 backoff: "exponential",52 delayMs: 60_000,53 limit: 3,54};5587/** What `context` records: what the attempts read, or why the round has none. */56const Prepared = Schema.TaggedUnion({89 /** The proposal is closed or gone: nothing to draft or settle. */57 Gone: {},91 /** The project has no `fix` kind, the only kind drafted. */58 NoFix: {},59 Ready: {60 context: DraftContext,61 territory: Schema.optionalKey(Schema.NonEmptyString),
2 unmodified lines
64});6566type Prepared = typeof Prepared.Type;67102/** What `draft-<n>` records: the model's draft, or why it gave none. */68const Attempted = Schema.TaggedUnion({69 Drafted: { drafted: DraftedAsk },70 Spent: { reason: DraftFailed.fields.reason },71});7273type Attempted = typeof Attempted.Type;74110/** The kind a draft is: drafts are `fix` asks only, for now (ADR 0018). */75const draftedKind = "fix";76113/** A proposal's territory as the paths whose files the drafter reads. */77const territoryPaths = (territory: string | undefined) =>78 (territory ?? "")79 .split(/[\s,]+/u)80 .map((path) => path.replace(/(?:\/\*\*)?\/*$/u, ""))
1 unmodified line
82 .map((path) => RepoPath.make(path));8384const decoder = new TextDecoder();85123/** `{ [key]: value }` when `value` is there, else no key at all. */86const field = <K extends string, A>(87 key: K,88 value: Option.Option<A>89): Partial<Record<K, A>> =>
1 unmodified line
91 onNone: () => ({}),92 onSome: (present) => Record.singleton(key, present),93 });94133/** What the next attempt is told when the model gave no draft. */95const spentText = (reason: string) =>96 `Your reply gave no draft (${reason}): answer with one JSON object that matches the schema, and nothing else.`;97137/** The refusal a round that never rehearsed ends with: no draft, and why. */98const noDraft = (reason: string): Refusal =>99 new IncompleteBrief({ missing: [`a draft (${reason})`] });100141/** Runs one round of a proposal's draft to its settling, over `steps`. */101export const runDraft = (102 params: DraftParams,103 steps: DraftSteps104): Effect.Effect<void, never, Projects | Drafter | RepoHost> =>
64 unmodified lines
169 Effect.catchTag("UnknownProject", () => Effect.succeed(false))170 )171 );172214 /** Up to `DRAFT_ROUNDS` attempts, each fed the last one's failure. */173 const attempts = (174 ready: Extract<Prepared, { readonly _tag: "Ready" }>175 ): Effect.Effect<DraftResult> =>176 Effect.gen(function* () {
151 unmodified lines
modified:packages/drafting/test/binding.test.ts+2 added-9 removed
1/**2 * The Workers AI drafter, over a fake `Ai` that records its call: what it3 * asks the model for, and how each kind of reply or failure comes back.4 */1import { describe, expect, expectTypeOf, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";4import { Effect, Schema } from "effect";
37 unmodified lines
42 readonly inputs: ChatInputs;43 readonly model: string;44}4550/** What the fake binding does: answer with a reply, or throw. */46type Outcome = { readonly reply: object } | { readonly thrown: Error };4753/** A fake binding that gives `outcome` and keeps every call. */48const fakeAi = (outcome: Outcome) => {49 const calls: Call[] = [];5051 const ai: AiLike = {
21 unmodified lines
73const thrown = (message: string): Outcome => ({ thrown: new Error(message) });7475const failure = (reason: DraftFailed["reason"]) => new DraftFailed({ reason });7683/** The one call a draft makes, as the fake recorded it. */77const callOf = Effect.gen(function* () {78 const { ai, calls } = fakeAi(chat(json));7980 yield* Drafter.use(({ draft }) => draft(input)).pipe(
116 unmodified lines
197 it.effect(198 "takes one sentence where the schema asks for a list of them, as a list of one",199 () =>200 Effect.gen(function* () {208 // kimi-k2.7-code on dev-oscabriel answered every attempt with209 // `context` and `outOfScope` as strings, whatever the JSON Schema said.201 // Seen live: kimi-k2.7-code answered every attempt with `context` and202 // `outOfScope` as strings, whatever the JSON Schema said.203 const reply = JSON.stringify({204 ...encoded,205 context: "An ordinal date is YYYY-DDD.",206 outOfScope: "Changing parse.",
74 unmodified lines
modified:packages/drafting/test/context.test.ts-5 removed
1/**2 * What the model reads: `pickFiles` over a project's canonical tree, the3 * same every time, within its byte budget, and never a layer's path.4 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { RepoPath } from "@repo/protocol/ids";4import { Effect, Option } from "effect";
4 unmodified lines
910const askSource = (id: string) =>11 `export default kinds.fix.ask({\n path: "test/asks/${id}.test.ts",\n want: "w",\n});\n`;1217/** A datekit-shaped tree, with what each file holds. */13const files = {14 ".github/workflows/ci.yml": "steps: []\n",15 "README.md": "# datekit\n",16 [askFile("add-months-clamp")]: askSource("add-months-clamp"),
164 unmodified lines
modified:packages/drafting/test/prompt.test.ts-6 removed
1/**2 * What the model is told: a system prompt from the project's public policy3 * (never its layers), and a user prompt that carries, from attempt 2 on,4 * the last attempt's refusal and the tail of its output.5 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import type { Policy } from "@repo/protocol/domain/policy";4import { VisibilityPolicy } from "@repo/protocol/domain/visibility";
11 unmodified lines
16} from "../src/prompt.ts";1718const { policy } = aProject();1925/** Layer facts no prompt may carry. */20const visibility = Schema.decodeSync(VisibilityPolicy)({21 checks: {22 areas: { export: "src/sealed-area/**" },23 attempts: { perClaim: 3, perPersonPerAreaPerWeek: 5 },
99 unmodified lines
modified:packages/drafting/test/render.test.ts-10 removed
1/**2 * The ask file is written by code from the drafted fields: rendered, then3 * evaluated by the rules' `/bun` adapter beside datekit's own config folder,4 * it states the same ask as the hand-written file, and every string the5 * model gave stays data.6 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { FinishersFromChecks } from "@repo/project/project";
12 unmodified lines
17const at = LandedSha.make("a".repeat(40));1819const askFile = (id: string) => `${Brand.configDir}/asks/${id}.ask.ts`;2027/** datekit's config folder, as the Lander bundles it, keyed by repo path. */21const datekitModules = Effect.gen(function* () {22 const fs = yield* FileSystem.FileSystem;23 const path = yield* Path.Path;24 const root = yield* path.fromFileUrl(exampleUrl);
12 unmodified lines
3738 return modules;39});4048/** The asks a bundle of datekit's folder evaluates to, encoded, by id. */41const asksOf = (modules: Readonly<Record<string, string>>) =>42 Effect.gen(function* () {43 const evaluator = yield* RulesEvaluator;44
33 unmodified lines
78 path: RepoPath.make(`test/asks/${id}.test.ts`),79 source: 'import { expect, it } from "bun:test";\n',80});8190/** `format-ordinal.ask.ts`'s fields, as a drafter would give them. */82const formatOrdinal: DraftedAsk = {83 current: "The 11th, 12th and 13th of a month print as 11st, 12nd and 13rd.",84 id: AskId.make("format-ordinal"),85 kind: "fix",
9 unmodified lines
95 test: test("format-ordinal"),96 want: "The Do token of format prints the day of the month as an English ordinal: 1st, 2nd, 3rd and 4th, 11th, 12th and 13th, then 21st, 22nd, 23rd and 31st.",97};98108/** `add-months-clamp.ask.ts`'s fields: every brief field a draft may give. */99const addMonthsClamp: DraftedAsk = {100 context: [101 "addYears adds twelve months, so it follows: February 29 plus a year becomes February 28.",102 ],
111 unmodified lines
modified:packages/drafting/test/run.test.ts-5 removed
1/**2 * The draft run's program over a fake step runner: the steps it names, and3 * what it settles, with the project and the drafter faked at their ports.4 */1import { describe, expect, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import { DraftResult } from "@repo/project/draft-runs";4import type { DraftContextData } from "@repo/project/draft-runs";
13 unmodified lines
18const scenario = aProject();1920const proposal = ProposalId.make("prop-000001");2126/** The scenario's policy as anyone reads it, with no `fix` kind. */22const withoutFix = Schema.decodeSync(PublicPolicy)(23 Schema.encodeSync(PublicPolicy)({24 ...Struct.omit(scenario.policy, ["asks", "functions", "visibility"]),25 kinds: scenario.policy.kinds.filter(({ name }) => name !== "fix"),
78 unmodified lines
modified:packages/gate/src/stages/parse.ts+2 added-13 removed
1/**2 * Stage 0, parse: who may push what. It reads only the push's target, the3 * pusher, the policy and the claim, so it is free; the first rule a push4 * breaks is its one refusal.5 */1import type { Policy } from "@repo/protocol/domain/policy";2import { sameHandle } from "@repo/protocol/ids";3import type { Handle } from "@repo/protocol/ids";4import { Principal } from "@repo/protocol/principal";
22 unmodified lines
27const isPusher = (facts: PushFacts, handle: Handle) =>28 Option.exists(handleOf(facts.pusher), (pusher) => sameHandle(pusher, handle));2930/**36 * Where a person stands by the vouch file: a line names them vouched or37 * denounced, and a denouncement on any line wins, as the project service38 * reads the file (`attention/vouch.ts`). Deciders vouch for others, so a39 * decider with no line is vouched.31 * A denouncement on any line wins, as the project service reads the file.32 * Deciders vouch for others, so a decider with no line is vouched.33 */34const standingOf = (policy: Policy, handle: Handle) => {35 const lines = policy.vouches.filter((vouch) =>36 sameHandle(vouch.handle, handle)
13 unmodified lines
5051 return decides ? "vouched" : "unknown";52};5361/** Where a person's work goes on a fork: its branches, never another ref. */54const branchPrefix = "refs/heads/";5556/**57 * Main moves only by a landing: no push reaches a canonical ref.
37 unmodified lines
95 ? Option.some(new NotVouched({}))96 : Option.none();97 });98107/** The rules for a push to a claim's fork, in order. */99const claimFork = (100 facts: PushFacts,101 fork: Data.TaggedEnum.Value<PushTarget, "ClaimFork">102): Option.Option<Refusal> => {
8 unmodified lines
111 if (Option.isNone(open)) {112 return Option.some(new NoAsk({}));113 }114124 // The fork is named for its claimant, who must hold the ask's claim.115 const held = Option.filter(116 facts.claim,117 (claim) =>118 claim.ask === fork.ask &&
25 unmodified lines
144 : Option.none();145146const rules: readonly Rule[] = [directPush, trust, claims];147158/** Parse: the first rule the push breaks, or nothing. */148export const parse: Stage<never> = {149 accumulate: false,150 name: "parse",151 run: (facts) =>
4 unmodified lines
modified:packages/gate/src/stages/shape.ts+6 added-52 removed
1/**2 * Stage 1, shape: what the push's changes do, read from the change list and3 * the added lines alone. It accumulates, so one push hears about every4 * problem at once, in the order of the refusal union's Shape group.5 *6 * The stage's value is `scan` (lint keeps "shape" out of symbol names); its7 * `name` is the stage's, `shape`.1// The stage's value is `scan` (lint keeps "shape" out of symbol names); its2// `name` is `shape`.8 */3import type { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec } from "@repo/protocol/domain/check";5import { RepoPath } from "@repo/protocol/ids";6import {
12 unmodified lines
19import { importSpecifiers, reachedInternals as reachInto } from "../imports.ts";20import { markersOf, scanMarkers } from "../markers.ts";21import type { Stage } from "../stage.ts";2229/** The one JSON pointer the gate is told about: whether the scripts changed. */23const SCRIPTS = "package.json#/scripts";2432/** The ask's own files: its file in the config folder, and its check's file. */25const ownFiles = (ask: Ask): ReadonlySet<string> =>26 new Set([27 ask.file,28 ...(CheckSpec.guards.RedThenGreen(ask.check) ? [ask.check.path] : []),29 ]);3039/** Each path once, in a fixed order, if there are any. */31const someOf = (32 paths: Iterable<RepoPath>33): Option.Option<Array.NonEmptyReadonlyArray<RepoPath>> => {34 const each = [...new Set(paths)].toSorted();
2 unmodified lines
37 ? Option.some(each)38 : Option.none();39};4050/**51 * Whether a path judges the push. An answer may not touch its ask's own52 * files, which judge it; a decider opening the ask writes them.53 */41const judges = (facts: PushFacts) => (path: RepoPath) => {42 const own = Option.exists(facts.ask, (ask) => ownFiles(ask).has(path));4344 return facts.opensAsk && own45 ? false46 : own || matchAny(facts.policy.judge.paths, path);47};4862/**63 * Whether a path is the push's to change: inside the ask's territory, or one64 * of the ask's own files when a decider opens it. With no ask (a decider's65 * own landing) there is no territory to leave.66 */49const inScope = (facts: PushFacts) => (path: RepoPath) =>50 Option.match(facts.ask, {51 onNone: () => true,52 onSome: (ask) =>53 matchAny(ask.territory.paths, path) ||54 (facts.opensAsk && ownFiles(ask).has(path)),55 });5675/** Changed paths outside the territory. A judged path is TouchedJudge's to name. */57const outOfScope = (facts: PushFacts): readonly Refusal[] => {58 const judged = judges(facts);59 const allowed = inScope(facts);60
9 unmodified lines
70 }71 );72};7393/** Changed paths in the judge closure, and the scripts pointer when it moved. */74const touchedJudge = (facts: PushFacts): readonly Refusal[] => {75 const scripts =76 facts.scriptsChanged && facts.policy.judge.pointers.includes(SCRIPTS)77 ? [RepoPath.make(SCRIPTS)]
10 unmodified lines
88 }89 );90};91112/** Every marker added with no reason; a reasoned one is an escape, for `escapeDecisions`. */92const weakened = (facts: PushFacts): readonly Refusal[] =>93 scanMarkers(facts.addedLines, markersOf(facts.policy)).flatMap(94 ({ line, marker, path, reason }) =>95 Option.isNone(reason)96 ? [new Weakened({ at: { line, path }, weakening: { marker } })]97 : []98 );99121/** Whether a layer's path set holds `path`: the path itself, or a folder above it. */100const inLayers =101 (layerPaths: ReadonlySet<RepoPath>) =>102 (path: RepoPath): boolean => {103 const held: ReadonlySet<string> = layerPaths;
2 unmodified lines
106 return parts.some((_, end) => held.has(parts.slice(0, end + 1).join("/")));107 };108109/**132 * The no-write-down guard by path, the one rule stage 1133 * and the visibility cartridge's landing guard share: added or134 * changed paths a layer holds, as the path itself or under a folder the set135 * names. A deletion writes nothing. The refusal is no oracle on which paths136 * are a layer's: to a pusher who cannot read the layers it names every path137 * they added or modified, all of them their own; only a reader hears which138 * collide.139 *140 * `pusherCanRead` vouches for every layer whose paths are in `layerPaths`:141 * true only when the pusher reads all of them, so reading one layer never142 * names another's paths.110 * The refusal is no oracle on which paths are a layer's: to a pusher who111 * cannot read the layers it names every path they added or modified; only a112 * reader hears which collide. `pusherCanRead` must hold for every layer in113 * `layerPaths`, so reading one layer never names another's paths.114 */115export const layerPathRefusal = (input: {116 readonly changes: readonly Pick<Change, "path" | "status">[];117 readonly layerPaths: ReadonlySet<RepoPath>;
12 unmodified lines
130 (paths) => new PrivatePathInPublicTree({ paths })131 );132};133163/** Stage 1's guard by path, over the push's facts (`canReadLayers`). */134const privatePaths = (facts: PushFacts): readonly Refusal[] =>135 Option.toArray(136 layerPathRefusal({137 changes: facts.changes,
1 unmodified line
139 pusherCanRead: facts.canReadLayers === true,140 })141 );142173// The files whose imports are read: JavaScript and TypeScript sources.143const SCRIPT = /\.[cm]?[jt]sx?$/u;144176/**177 * Each run of consecutive added lines as one text, with the number of the178 * line before it, so an import over several lines is read whole.179 */145const runsOf = (lines: readonly AddedLine[]) => {146 // Consecutive lines keep the same difference from their place in order.147 const placed = lines148 .toSorted((one, other) => one.line - other.line)
8 unmodified lines
157 )158 : [];159};160196/**197 * Imports the answer adds to a script inside its territory that reach into198 * another module's internals, each on its line. A push that answers no ask199 * (a decider's own landing) is not judged.200 */161const reachedInternals = (facts: PushFacts): readonly Refusal[] =>162 Option.match(facts.ask, {163 onNone: () => [],164 onSome: ({ territory }) =>
25 unmodified lines
190 )191 ),192 });193234// The Shape group's tags, in union order.194const unionOrder: readonly string[] =195 groups196 .find((group) => group.name === "Shape")197 ?.members.map((member) => member.identifier) ?? [];198240/** Union group order, then path, then line. */199const byUnionOrder = Order.combineAll<Refusal>([200 Order.mapInput(Order.Number, (refusal) => unionOrder.indexOf(refusal._tag)),201 Order.mapInput(Order.String, (refusal) => refusal.at?.path ?? ""),202 Order.mapInput(Order.Number, (refusal) => refusal.at?.line ?? 0),203]);204247/**248 * Stage 1: every problem the push's changes have, in the union's Shape249 * order, then by path, then by line.250 */205export const scan: Stage<never> = {206 accumulate: true,207 name: "shape",208 run: (facts) =>
10 unmodified lines
modified:packages/gate/src/classify.ts+5 added-14 removed
1/**2 * Classifying a failing lane: the gate never charges an answerer3 * for its own trouble, nor for a main that moved underneath them. Only a4 * lane that passes on main and fails on the merged tree, in a file the2 * Only a lane that passes on main and fails on the merged tree, in a file the3 * answer changed or in none it can name, is the answer's failure.4 */5import type { LaneResult } from "@repo/protocol/domain/answer";6import type { CommitSha, LaneName, RepoPath } from "@repo/protocol/ids";
4 unmodified lines
11 VerifierBlocked,12} from "@repo/protocol/refusal";13import { Option } from "effect";1417/** What the platform saw of one lane on main, on the merged tree and on a fresh run. */15export interface LaneEvidence {16 readonly lane: LaneName;17 readonly onMain: LaneResult["result"];18 readonly onMerged: LaneResult["result"];22 /** The lane's fresh run on the same merged tree, once one has run. */19 readonly rerun: Option.Option<LaneResult["result"]>;24 /** The files the failure points at, when the lane's output names any. */20 readonly failingPaths: readonly RepoPath[];21 readonly logRef: string;27 /** The command that reproduces the lane: a refusal's `next`. */22 readonly command: string;29 /** Whether this is the run block's `doctor`, which checks the checker itself. */23 readonly isDoctor: boolean;24}2533/** Whether a result is the platform's own trouble, not the code's: a flake, or a checker that never started. */26const isTrouble = (result: LaneResult["result"]) =>27 result === "flaked" || result === "blocked";2829/**38 * How a lane's failure counts, or `None` when the lane passed on the merged39 * tree. A lane red on main too is `VerifierBlocked`. A checker that never40 * started on a tree whose main passes earns one fresh run (`Flake`); an41 * identical second failure means it was never a flake, so it counts as the42 * answer's. A failure only outside the diff is `StaleBase`.30 * A lane red on main too is `VerifierBlocked`. A checker that never started31 * on a tree whose main passes earns one fresh run (`Flake`); an identical32 * second failure means it was never a flake, so it counts as the answer's. A33 * failure only outside the diff is `StaleBase`.34 */35export const classifyFailure = (36 evidence: LaneEvidence,37 changedPaths: ReadonlySet<RepoPath>,
39 unmodified lines
modified:packages/gate/src/escapes.ts+2 added-35 removed
1/**2 * Reasoned escapes: a marker with a reason after ` -- ` is not refused but3 * counted against its territory's escape ratchet. The4 * ratchet is incremental, with no command: its count moves by the reasoned5 * markers an answer adds minus those it removes. An answer that would take a6 * territory past its baseline waits for a decider, one `Waiver` per reasoned7 * marker it adds there, instead of landing or being refused.8 *9 * This is a pure function beside the stages, not a stage: a waiting answer10 * is not refused, so the caller (the Project DO, when an answer's checks11 * report) opens the decisions.2 * A pure function beside the stages, not a stage: a waiting answer is not3 * refused, so the caller (the Project DO) opens the decisions.4 */5import type { Ask } from "@repo/protocol/domain/ask";6import { DecisionSubject } from "@repo/protocol/domain/decision";7import type { Policy } from "@repo/protocol/domain/policy";
5 unmodified lines
13import { matchAny } from "./glob.ts";14import { markersOf, scanMarkers } from "./markers.ts";15import type { MarkerHit } from "./markers.ts";1625/** A `Waiver` decision's subject. */17export type Waiver = Extract<DecisionSubject, { readonly _tag: "Waiver" }>;1828/** An answer asking a decider to raise one ratchet in one territory, and why. */19export interface RaiseRequest {20 readonly ratchet: RatchetName;21 readonly territory: string;22 readonly reason: string;23}2435/**36 * The escape ratchet of `territory`: `escapes-` and the territory's name in37 * lowercase words joined by `-` (`@datekit/parse` is `escapes-datekit-parse`);38 * a territory with no such words, the root's `.`, is `escapes-root`.39 */25export const escapeRatchet = (territory: string): RatchetName =>26 RatchetName.make(27 `escapes-${28 territory
3 unmodified lines
32 .join("-") || "root"33 }`34 );3551/** A marker hit whose line gives a reason. */36interface Escape extends MarkerHit {37 readonly given: string;38}39
7 unmodified lines
47 onSome: (given) => [{ ...hit, given }],48 })49 );5067/**68 * The territory a path counts against: the first module holding it, or the69 * ask's territory for a path no module holds (a root manifest the ask may70 * change).71 */51export const territoryOf = (policy: Policy, ask: Ask, path: RepoPath) =>52 policy.modules.find((module) => matchAny(module.paths, path))?.module ??53 ask.territory.module;5476/**77 * One `Waiver` per reasoned marker the push adds, in each territory whose78 * escape count after the push (its count on main, plus the reasoned markers79 * added there, less those removed) exceeds its baseline; ordered by path,80 * then line. A push that answers no ask has nothing to wait on.81 */55export const escapeDecisions = (facts: PushFacts): readonly Waiver[] =>56 Option.match(facts.ask, {57 onNone: () => [],58 onSome: (ask) => {
27 unmodified lines
86 );87 },88 });89117/**118 * The raises a push's `waivers` ask a decider for: a reasoned escape in a119 * territory explains a raise of every declared ratchet there, for its120 * reason. The Project DO judges an answer's counts with them, and121 * `<cli> check` does the same before the push.122 */90export const explainedRaises = (91 policy: Policy,92 ask: Ask,93 waivers: readonly Waiver[]
8 unmodified lines
modified:packages/gate/src/facts.ts+1 added-34 removed
1/**2 * What the gate knows about one push: the facts its stages decide over. The3 * gate never reads a repo or computes a diff; its callers (the project4 * service, the CLI's local check) gather these and hand them in.5 */1import type { Ask } from "@repo/protocol/domain/ask";2import type { ClaimView } from "@repo/protocol/domain/claim";3import type { RefNameText } from "@repo/protocol/domain/common";4import type { Policy } from "@repo/protocol/domain/policy";
11 unmodified lines
16import type { Principal } from "@repo/protocol/principal";17import { Data } from "effect";18import type { Option } from "effect";1925/** One path an answer changes, with its blob before and after. */20export interface Change {21 readonly path: RepoPath;22 readonly status: "added" | "modified" | "deleted";23 readonly before?: BlobSha;24 readonly after?: BlobSha;25}2633/** One line an answer adds to a file, by its 1-based number in the new file. */27export interface AddedLine {28 readonly line: number;29 readonly text: string;30}3139/**40 * Where a push goes, read from the repo's name: the canonical41 * repo `<project>`, a claim's fork `<project>--<ask>--<handle>`, a person's42 * working fork `<project>--me--<handle>`, or a layer's repo43 * `<project>--<layer>`.44 */32export type PushTarget = Data.TaggedEnum<{33 Canonical: { readonly project: ProjectName };34 ClaimFork: {35 readonly project: ProjectName;
3 unmodified lines
39 Layer: { readonly project: ProjectName; readonly layer: LayerName };40 WorkingFork: { readonly project: ProjectName; readonly owner: Handle };41}>;4256/** Constructors and matchers for `PushTarget`. */43export const PushTarget = Data.taggedEnum<PushTarget>();4459/** Everything the gate's stages decide one push over. */45export interface PushFacts {61 /** The policy at the landed SHA: the only place rules are read from. */46 readonly policy: Policy;63 /** The ask the push answers (or opens), if one is open. */47 readonly ask: Option.Option<Ask>;65 /** The claim on that ask, whoever holds it. */48 readonly claim: Option.Option<ClaimView>;49 readonly pusher: Principal;50 readonly target: PushTarget;51 readonly ref: RefNameText;
1 unmodified line
53 readonly head: CommitSha;54 readonly landed: LandedSha;55 readonly changes: readonly Change[];56 readonly addedLines: ReadonlyMap<RepoPath, readonly AddedLine[]>;75 /** Whether `package.json#/scripts` differs; the caller compares the two JSON pointers. */57 readonly scriptsChanged: boolean;77 /**78 * Paths that belong to a layer, which no public tree may carry (empty without79 * the visibility cartridge): files, or folders whose every path is the80 * layer's.81 */58 readonly layerPaths: ReadonlySet<RepoPath>;59 /**60 * Whether the pusher reads the layers `layerPaths` holds. Only a61 * reader hears which of their paths collide with a layer; anyone else
1 unmodified line
63 * every layer in the set: true only when the pusher reads all of them, so64 * reading one layer never names another's paths. Absent, they read none.65 */66 readonly canReadLayers?: boolean;91 /** How many live claims the pusher holds, for `CapReached`. */67 readonly claimsHeld: number;93 /**94 * Whether the push opens `ask` (a decider's `openAsk`) rather than answers95 * it. Only then are the ask's own file and check file the push's to write.96 */68 /** Only when the push opens the ask are its own file and check file the push's to write. */69 readonly opensAsk: boolean;98 /**99 * Each ratchet's baseline, from the project's `ratchets` rows: the most a100 * count may be. A territory's escape ratchet is named by `escapeRatchet`.101 * Absent, or with no row for a ratchet, the baseline is 0.102 */70 readonly ratchetBaselines?: ReadonlyMap<RatchetName, number>;71 /**72 * The lines a push removes, by their 1-based number in the old file, so a73 * removed escape offsets an added one. Absent, a push removes none, which
11 unmodified lines
modified:packages/gate/src/gate.ts+2 added-9 removed
1/**2 * The gate: a push's stages, run in order of cost. It stops after the first3 * stage that refuses, so a push never pays for a stage past its cheapest4 * problem (ADR 0006).2 * Stops after the first stage that refuses, so a push never pays for a stage3 * past its cheapest problem.4 */5import type { Refusal } from "@repo/protocol/refusal";6import { Array, Effect, Option } from "effect";7
1 unmodified line
9import type { Stage } from "./stage.ts";10import { parse } from "./stages/parse.ts";11import { scan } from "./stages/shape.ts";1214/**15 * Runs `stages` over the push in order, and answers with the refusals of the16 * first stage that has any: all of them when it accumulates, its first17 * otherwise. `None` means the push may go on to merge and checks.18 */13export const runGate = <R>(14 stages: readonly Stage<R>[],15 facts: PushFacts16): Effect.Effect<
14 unmodified lines
3132 return Option.none();33 });3441/** Stages 0 and 1: what the gateway and `submitAnswer` run before answering a push. */35export const pushStages: readonly Stage<never>[] = [parse, scan];
modified:packages/gate/src/glob.ts+4 added-16 removed
1/**2 * Path globs as the config folder writes them, read as `.gitignore` reads3 * them: `**` crosses folders, `*` and `?` stay inside one, a glob with a `/`4 * before its end is anchored at the repo's root (a leading `/` only anchors),5 * a glob with none matches a file's name at any depth (`vitest.config.*` is6 * every package's config, so none escapes the judge closure), and a trailing7 * `/` means everything under the folder.8 *9 * The gate keeps its own small matcher rather than importing `@repo/checks`'10 * (the gate takes no checks dependency); both read the same11 * globs.2 * Globs read as `.gitignore` reads them: a glob with a `/` before its end is3 * anchored at the root, and one with none matches a file's name at any depth.4 * The gate keeps its own matcher rather than importing `@repo/checks`' (it5 * takes no checks dependency); both read the same globs.6 */78// The characters a RegExp reads as syntax, which a glob means literally.9const SYNTAX = new Set("\\^$.|+()[]{}");1017/** The RegExp source for one glob, anchored at both ends. */11const sourceOf = (glob: string) => {12 let source = "";13 let at = 0;14
41 unmodified lines
5657 return glob.slice(0, -1).includes("/") ? folder : `**/${folder}`;58};5967/** Whether `path` matches `glob`. */60export const matchGlob = (glob: string, path: string): boolean =>61 new RegExp(sourceOf(anchored(glob)), "u").test(path);6271/**72 * Whether `path` is in the set `globs` describe: some glob matches it and no73 * `!`-glob takes it back out (`.env.*` with `!.env.*.local`).74 */63export const matchAny = (globs: readonly string[], path: string): boolean =>64 globs.some((glob) => !glob.startsWith("!") && matchGlob(glob, path)) &&65 !globs.some((glob) => glob.startsWith("!") && matchGlob(glob.slice(1), path));
modified:packages/gate/src/imports.ts+4 added-53 removed
1/**2 * Imports read from text, for `ReachedInternals`: stage 1 reads the module3 * specifiers an answer adds and judges each against the modules' public4 * files, with no compiler and no file system. Full resolution (path aliases,5 * `exports` conditions, a re-export that leaks an internal) is stage 3's,6 * through `tsc`.7 */1// Stage 1 reads imports from text, with no compiler and no file system. Full2// resolution (path aliases, `exports` conditions, re-exports) is stage 3's.3import type { Policy } from "@repo/protocol/domain/policy";4import type { RepoPath } from "@repo/protocol/ids";5import { Array, Option } from "effect";67import { matchAny } from "./glob.ts";814/** One module specifier a text imports, and the 1-based line it sits on. */9export interface ImportSpecifier {10 readonly specifier: string;11 readonly line: number;12}
9 unmodified lines
22const KEYWORD_BEFORE_REGEX =23 /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/u;2425/**32 * `text` with its comments blanked, and the contents of its strings,33 * templates and regular expressions filled with `_`, so what is left to read34 * is code and the bare delimiters of its strings. Lines and offsets stay35 * where they were. A line whose code opens with `*` reads as the inside of a36 * block comment: an answer's added lines can start after the comment opened.26 * A line whose code opens with `*` reads as the inside of a block comment: an27 * answer's added lines can start after the comment opened.28 */29const maskOf = (text: string): string => {30 let out = "";31 let mode: Mode = "code";32 let quote = "";33 let inClass = false;43 // The last of the code read so far, its whitespace kept: what a `/` follows.34 let tail = "";45 // Whether the current line holds nothing but whitespace so far.35 let blankLine = true;47 // Each open `${`, with how many braces are open inside it.36 const expressions: number[] = [];3738 const emit = (chars: string, as: "blank" | "fill") => {39 for (const char of chars) {
11 unmodified lines
51 tail = (tail + chars).slice(-32);52 blankLine = chars.endsWith("\n") || (blankLine && chars.trim() === "");53 };5467 /** Ends the current mode on `char`, which stays as code. */55 const close = (char: string) => {56 mode = "code";57 keep(char);58 };5973 // Each step reads the character at hand (and the next, for pairs) in its74 // mode, and answers with how many characters it read.60 const inComment = (char: string) => {61 if (char === "\n") {62 mode = "code";63 }
71 unmodified lines
135136 return 1;137 };138154 /** Whether a `/` here opens a regular expression rather than divides. */139 const opensRegex = () => {140 const before = tail.trimEnd();141142 return (
2 unmodified lines
145 KEYWORD_BEFORE_REGEX.test(before)146 );147 };148165 /** What a character of code opens: a string, a template, a regular expression, or nothing. */149 const opened = (char: string): Mode => {150 if (char === '"' || char === "'") {151 quote = char;152
12 unmodified lines
165166 return "code";167 };168186 /** Counts braces inside a template's `${`; its closing one resumes the template. */169 const brace = (char: string) => {170 const open = expressions.pop();171172 if (open === undefined) {
62 unmodified lines
235 /(?<![\w$.])import\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,236 /(?<![\w$.])require\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,237];238257/**258 * Every module specifier `text` imports: static imports and re-exports259 * (`… from "x"`, over any number of lines), side-effect imports, dynamic260 * `import("x")` and `require("x")` (their specifier a string or a template261 * with no substitution), each on the line its specifier sits on, in the262 * order they appear. Comments, strings, templates and regular expressions263 * import nothing.264 */239export const importSpecifiers = (text: string): readonly ImportSpecifier[] => {240 const masked = maskOf(text);241242 return FORMS.flatMap((form) =>
12 unmodified lines
255 .toSorted((one, other) => one.start - other.start)256 .map(({ line, specifier }) => ({ line, specifier }));257};258285// A specifier relative to the importing file: `./x`, `../x`, `.` or `..`.259const RELATIVE = /^\.\.?(?:\/|$)/u;260288// The folders a package subpath may not name: they hold a module's insides.261const INSIDES = new Set(["src", "test", "internal"]);262263type Module = Policy["modules"][number];264265const moduleOf = (modules: Policy["modules"], path: string) =>266 Array.findFirst(modules, (module) => matchAny(module.paths, path));267296/** `from`'s folder joined with a relative specifier; none when it leaves the repo. */268const resolve = (from: string, specifier: string): Option.Option<string> => {269 const parts = from.split("/").slice(0, -1);270271 for (const part of specifier.split("/")) {
10 unmodified lines
282283 return Option.some(parts.join("/"));284};285315/** A module file's path with its extension and a trailing `/index` dropped. */286const bare = (path: string) =>287 path.replace(/\.[cm]?[jt]sx?$/u, "").replace(/\/index$/u, "");288319/** The folders a module's globs name: `packages/b/**` is `packages/b`. */289const rootsOf = (module: Module) =>290 module.paths.map((glob) =>291 glob.replace(/^\//u, "").replace(/\/(?:\*\*)?$/u, "")292 );293325/**326 * Whether `target` is a file of `module` that it does not export. A folder327 * import of the module's root goes through its manifest, so it is public; a328 * module that lists no public files is not judged.329 */294const isInternal = (module: Module, target: string) =>295 module.publicFiles !== undefined &&296 !rootsOf(module).includes(target) &&297 !module.publicFiles.some((file) => bare(file) === bare(target));298335/** The module a relative specifier lands in, when it is internal there. */299const relative = (300 from: string,301 specifier: string,302 modules: Policy["modules"]
3 unmodified lines
306 isInternal(module, target)307 )308 );309347/**348 * The module a package specifier names, when its subpath names a folder that349 * holds the module's insides: `@scope/b/src/internal`. Only the project's own350 * modules are judged; a dependency's insides are its own business.351 */310const subpath = (specifier: string, modules: Policy["modules"]) => {311 const segments = specifier.split("/");312 const length = specifier.startsWith("@") ? 2 : 1;313 const name = segments.slice(0, length).join("/");
2 unmodified lines
316 ? Array.findFirst(modules, (module) => module.module === name)317 : Option.none();318};319362/**363 * Whether an import of `specifier` from `from` reaches into another module's364 * internals: a relative import that lands on a file of another module that365 * the module does not export, or a package subpath of another module that366 * names its `src`, `test` or `internal` folder. Imports inside the importing367 * file's own module are its own.368 */320export const reachedInternals = (input: {321 readonly from: RepoPath;322 readonly specifier: string;323 readonly modules: Policy["modules"];
14 unmodified lines
modified:packages/gate/src/markers.ts+2 added-16 removed
1/**2 * Weakening markers: text an answer adds that turns a check off. A marker3 * with no reason after ` -- ` is refused at shape; one with a reason is an4 * escape, counted against its territory's escape ratchet.5 */1import type { Policy } from "@repo/protocol/domain/policy";2import type { RepoPath } from "@repo/protocol/ids";3import { Option, Order } from "effect";45import type { PushFacts } from "./facts.ts";612/** One marker, and the kind of check it turns off. */7export interface Marker {8 readonly text: string;9 readonly family:10 | "test"
5 unmodified lines
16 | "rust"17 | "go";18}1926/** The markers every project starts with; a project may add more. */20export const defaultMarkers: readonly Marker[] = [21 { family: "test", text: ".skip(" },22 { family: "test", text: ".only(" },23 { family: "test", text: ".todo(" },
11 unmodified lines
35 { family: "coverage", text: "istanbul ignore" },36 { family: "coverage", text: "c8 ignore" },37];3846/** The defaults and the markers the project adds, each once. */39export const markersOf = (policy: Policy): readonly string[] => [40 ...new Set([41 ...defaultMarkers.map((marker) => marker.text),42 ...policy.weakening.markers,43 ]),44];4554/** One marker on one line, with the reason written after it, if any. */46export interface MarkerHit {47 readonly path: RepoPath;48 readonly line: number;49 readonly marker: string;50 readonly reason: Option.Option<string>;51}5262// The ` -- ` that starts a reason after an escape directive.53const REASON_MARK = /\s--(?=\s|$)/u;5465// What closes a comment after its reason: `*/`, `-->`.55const CLOSER = /\s*(?:\*\/|-->)\s*$/u;5668/** The reason written after a marker on its line, if there is one. */57const reasonIn = (rest: string): Option.Option<string> => {58 const mark = REASON_MARK.exec(rest);5960 if (mark === null) {
8 unmodified lines
69 return reason === "" ? Option.none() : Option.some(reason);70};7172/**85 * Every marker in `markers` that a line holds, once per line, ordered by86 * path, then line. A marker is plain text: it is found in any file, a string87 * in a README included; a project decides by adding to or trimming its list.88 * The lines are an answer's added lines, or its removed ones.73 * A marker is plain text: it is found in any file, a README included; a74 * project decides by adding to or trimming its list.75 */76export const scanMarkers = (77 lines: PushFacts["addedLines"],78 markers: readonly string[]
23 unmodified lines
modified:packages/gate/src/stage.ts-5 removed
2 unmodified lines
3import type { Effect } from "effect";45import type { PushFacts } from "./facts.ts";67/**8 * One stage of the gate: a decision over a push's facts that answers with9 * refusals, or none. An accumulating stage reports every refusal it finds; any10 * other stage stops the gate at its first.11 */7export interface Stage<R> {8 readonly name: StageName;9 readonly accumulate: boolean;10 readonly run: (
3 unmodified lines
modified:packages/gate/src/verdict.ts-13 removed
1/**2 * The verdict: the record of one check run on an answer, which the platform3 * keeps with the landing and writes as a note on the answer's head. It takes4 * `now` from its caller and reads no clock (principle 8).5 */1import type {2 HeldBackResult,3 LaneResult,4 Verdict,
5 unmodified lines
10import type { DateTime } from "effect";1112import type { PushFacts } from "./facts.ts";1319/** What one check run found, and where it got to. */14export interface VerdictInput {15 readonly facts: PushFacts;22 /** The merged tree the checks ran on. */16 readonly tree: TreeSha;17 readonly patchId: PatchId;18 readonly checkVersion: CheckVersion;26 /** The furthest stage the answer reached. */19 readonly stage: StageName;20 readonly lanes: readonly LaneResult[];21 readonly heldBack: readonly HeldBackResult[];22 readonly outcome: Outcome;23 readonly now: DateTime.Utc;24}2534/**35 * The verdict on the answer `facts` describe. A verdict is about an answer to36 * an ask, so a push that answers none (a decider's own landing) has none:37 * `NoAsk`.38 */26export const verdictOf = (input: VerdictInput): Result.Result<Verdict, NoAsk> =>27 Option.match(input.facts.ask, {28 onNone: () => Result.fail(new NoAsk({})),29 onSome: (ask) =>
16 unmodified lines
modified:packages/gate/test/classify.test.ts-4 removed
17 unmodified lines
18const week = RepoPath.make("packages/parse/src/week.ts");1920const pad = RepoPath.make("packages/format/src/pad.ts");2122/** The answer changed `week.ts` only. */22const changed: ReadonlySet<RepoPath> = new Set([week]);2325/** The unit lane, green on main and red on the merged tree in `week.ts`. */24const red: LaneEvidence = {25 command: "bun run test",26 failingPaths: [week],27 isDoctor: false,
3 unmodified lines
31 onMerged: "failed",32 rerun: Option.none(),33};3437// The classification table: the platform never charges the answerer for its own38// trouble, nor for a main that moved underneath them.35const rows: readonly {36 readonly name: string;37 readonly evidence: LaneEvidence;38 readonly refusal: Option.Option<Refusal>;
97 unmodified lines
modified:packages/gate/test/escapes.test.ts-1 removed
23 unmodified lines
24const generated = "/* eslint-disable no-console -- generated tables */";2526const parseEscapes = RatchetName.make("escapes-datekit-parse");2728/** The `Waiver` for the escape `marker` with `reason` at `path:line`. */28const waiver = (path: string, line: number, marker: string, reason: string) =>29 DecisionSubject.cases.Waiver.make({30 ask: ask.id,31 at: { line, path: RepoPath.make(path) },
164 unmodified lines
modified:packages/gate/test/facts.ts-21 removed
1/**2 * A push's facts for the gate's tests. One project, `datekit`, has two3 * modules, `parse` and `format`. Its ask `iso-week` has `parse` (and the root4 * manifest, for a dependency bump) as its territory, and bob holds a live5 * claim on it. By default bob pushes one change inside the territory to his6 * claim's fork, which every stage lets through; each test overrides only what7 * it is about: `testFacts({ changes: modified("docs/guide.md") })`.8 */1import { Ask } from "@repo/protocol/domain/ask";2import { CheckSpec } from "@repo/protocol/domain/check";3import { ClaimView } from "@repo/protocol/domain/claim";4import { RefNameText } from "@repo/protocol/domain/common";
11 unmodified lines
16const { vouch } = Schema.decodeSync(17 Schema.Struct({ vouch: PolicyInput.fields.vouch })18)({});1928/** The config folder's name, as `Brand.configDir` spells it. */20export const configDir = vouch.file.slice(0, vouch.file.indexOf("/"));2131/** A decider for every path, who is in no line of the vouch file. */22export const alice = Handle.make("alice");2334/** Vouched for, and the holder of the claim on `iso-week`. */24export const bob = Handle.make("bob");2537/** Vouched for, with no claim. */26export const carol = Handle.make("carol");2740/** In no line of the vouch file. */28export const dana = Handle.make("dana");2943/** Denounced by the vouch file. */30export const mallory = Handle.make("mallory");3132export const base = CommitSha.make("1111111111111111111111111111111111111111");33
35 unmodified lines
69 state: "claimed",70 territory: { ...parseModule, paths: ["packages/parse/**", "/package.json"] },71} as const;7287/** The ask bob answers. */73export const ask = Schema.decodeSync(Ask)(askWire);7490/** Bob's live claim on `iso-week`. */75export const claim = Schema.decodeSync(ClaimView)({76 ask: askWire.id,77 base,78 checkCommand: `bun test ${checkPath}`,
6 unmodified lines
85 state: "live",86 warnsAt: "2026-10-07T14:00:00.000Z",87});88105/** The policy at the landed SHA. */89export const policy = Schema.decodeSync(Policy)({90 agents: "trailer",91 asks: [askWire],92 at: landedSha,
41 unmodified lines
134 ],135 weakening: { markers: [] },136});137155/** The paths, each changed in place. */138export const modified = (...paths: readonly string[]): readonly Change[] =>139 paths.map((path) => ({ path: RepoPath.make(path), status: "modified" }));140159/** The lines a push adds, as `[path, line, text]`, grouped by path. */141export const addedLines = (142 ...lines: readonly (readonly [string, number, string])[]143): ReadonlyMap<RepoPath, readonly AddedLine[]> => {144 const byPath = new Map<RepoPath, AddedLine[]>();
6 unmodified lines
151152 return byPath;153};154174/** Bob's clean push to his claim's fork, with `overrides` applied. */155export const testFacts = (overrides: Partial<PushFacts> = {}): PushFacts => ({156 addedLines: addedLines([157 "packages/parse/src/week.ts",158 3,
19 unmodified lines
178 }),179 ...overrides,180});181202/** Refusals as they cross the wire, so a test compares their fields. */182export const wire = (refusals: readonly Refusal[]) =>183 refusals.map((refusal) => Schema.encodeSync(Refusal)(refusal));
modified:packages/gate/test/gate.test.ts-2 removed
6 unmodified lines
7import { pushStages, runGate } from "../src/gate.ts";8import type { Stage } from "../src/stage.ts";9import { ask, modified, testFacts, wire } from "./facts.ts";1011/** What the gate answered, as it crosses the wire; `None` stays `None`. */11const wired = (answer: Option.Option<readonly Refusal[]>) =>12 Option.map(answer, wire);1315/** A stage that answers every push with `refusals`. */14const always = (15 accumulate: boolean,16 refusals: readonly Refusal[]17): Stage<never> => ({
75 unmodified lines
modified:packages/gate/test/glob.test.ts-1 removed
1import { describe, expect, it } from "@effect/vitest";23import { matchAny, matchGlob } from "../src/glob.ts";45// Each row is a glob, a path, and whether `.gitignore`'s rules match them.5const rows: readonly (readonly [string, string, boolean])[] = [6 ["vitest.config.*", "vitest.config.ts", true],7 ["vitest.config.*", "packages/parse/vitest.config.ts", true],8 [".github/workflows/**", ".github/workflows/ci.yml", true],
32 unmodified lines
modified:packages/gate/test/imports.test.ts-1 removed
3 unmodified lines
4import { Option, Schema } from "effect";56import { importSpecifiers, reachedInternals } from "../src/imports.ts";78/** The text of `lines`, one per line. */8const text = (...lines: readonly string[]) => lines.join("\n");910describe(importSpecifiers, () => {11 it.each([
225 unmodified lines
modified:packages/gate/test/markers.test.ts-1 removed
5 unmodified lines
6import { addedLines, policy } from "./facts.ts";78const texts = defaultMarkers.map((marker) => marker.text);910// One added line per default marker, as each tool writes it.10const lines: readonly (readonly [string, string])[] = [11 [".skip(", ' it.skip("parses week 53", () => {'],12 [".only(", ' describe.only("weeks", () => {'],13 [".todo(", ' it.todo("parses week 54");'],
108 unmodified lines
modified:packages/gate/test/parse.test.ts-5 removed
28 unmodified lines
29 testFacts,30 wire,31} from "./facts.ts";3233/** Dana's own live claim on the ask, and her push to its fork. */33const danasPush = (mode: PushFacts["policy"]["vouch"]["mode"]) =>34 testFacts({35 claim: Option.some({ ...claim, claimant: dana }),36 policy: { ...policy, vouch: { ...policy.vouch, mode } },
4 unmodified lines
41 project: ask.project,42 }),43 });4446/** Dana's push to her own working fork (`<project>--me--dana`). */45const danasWorkingForkPush = (mode: PushFacts["policy"]["vouch"]["mode"]) =>46 testFacts({47 ask: Option.none(),48 claim: Option.none(),
5 unmodified lines
54const main = RefNameText.make("refs/heads/main");5556const tag = RefNameText.make("refs/tags/v1");5760// Each row is one push; parse answers with at most one refusal, the first61// rule the push breaks.58const rows: readonly {59 readonly name: string;60 readonly facts: PushFacts;61 readonly refusals: readonly Refusal[];
158 unmodified lines
220 }),221 name: "a push to a layer's repo, which W6 opens to its writers",222 refusals: [new DirectPush({ ref: main })],223 },228 // A fork takes branches only: every other ref is the platform's or no one's.224 {225 facts: testFacts({ ref: tag }),226 name: "the claimant's push of a tag to their claim's fork",227 refusals: [new DirectPush({ ref: tag })],
34 unmodified lines
modified:packages/gate/test/shape.test.ts-10 removed
36 unmodified lines
37const week = "packages/parse/src/week.ts";3839const weekTest = "packages/parse/test/week.test.ts";4041/** The path set of a layer holding `each`: files, or folders. */41const layerHolds = (...each: readonly string[]): ReadonlySet<RepoPath> =>42 new Set(each.map((path) => RepoPath.make(path)));4345/** A push that changes `files` and adds `lines` to them. */44const push = (45 files: readonly string[],46 lines: readonly (readonly [string, number, string])[] = [],47 overrides: Partial<PushFacts> = {}
3 unmodified lines
51 changes: modified(...files),52 ...overrides,53 });5457/** One push with every problem shape knows. */55const everyProblem = push(56 [week, "docs/guide.md", ".github/workflows/ci.yml"],57 [58 [week, 1, 'export { pad } from "../../format/src/pad";'],
6 unmodified lines
65// The language service reads its directive anywhere in a source file, so66// the marker is joined at run time.67const effectDiagnostics = ["@effect", "-diagnostics"].join("");6872// Two modules, `a` and `b`; the ask's territory is `a`, and the judge73// closure also holds the lint config.69const [moduleA, moduleB] = Schema.decodeSync(70 Schema.Tuple([Territory, Territory])71)([72 {
11 unmodified lines
84const x = "packages/a/src/x.ts";8586const xTest = "packages/a/test/x.test.ts";8793/** A push answering an ask in module `a`. */88const pushToA = (89 files: readonly string[],90 lines: readonly (readonly [string, number, string])[] = []91) =>
8 unmodified lines
100 modules: [moduleA, moduleB],101 },102 });103110// Every default marker, as a tool writes it on an added line.104const markerLines: readonly (readonly [string, string])[] = [105 [".skip(", ' it.skip("parses week 53", () => {'],106 [".only(", ' describe.only("weeks", () => {'],107 [".todo(", ' it.todo("parses week 54");'],
13 unmodified lines
121];122123const pad = "../../format/src/pad.ts";124132/** ReachedInternals for an import of `to` on line `line` of `week`. */125const reachedFromWeek = (line: number, to: string) =>126 new ReachedInternals({ at: at(week, line), from: RepoPath.make(week), to });127136// Each row is one push. Shape reports every problem the push has, in the137// order of the refusal union's Shape group.128const rows: readonly {129 readonly name: string;130 readonly facts: PushFacts;131 readonly refusals: readonly Refusal[];
398 unmodified lines
modified:packages/git/src/upstream/repo-host.ts+1 added-9 removed
13 unmodified lines
1415import { Exchange, Upstream, UpstreamFailure } from "../upstream.ts";16import type { Service } from "../upstream.ts";1718/** How long a token the upstream mints is asked to last. */18const TOKEN_TTL = Duration.hours(1);1920/** A token is dropped this long before it expires, so none expires mid-exchange. */21const MARGIN = Duration.minutes(1);2224/** Tokens kept at once, one per (repo, scope). */23const CAPACITY = 1024;2425class TokenKey extends Data.Class<{26 readonly repo: RepoName;27 readonly scope: TokenScope;28}> {}2932/** A clone or fetch reads; only a push writes. */30const scopeOf = (service: Service): TokenScope =>31 service === "git-receive-pack" ? "write" : "read";3233/**
27 unmodified lines
61 },62 });63};6468/**69 * The production `Upstream`: each exchange goes to the repo's own remote in70 * the store, with a token the store minted for the exchange's scope. Tokens71 * are cached per (repo, scope) until a minute before they expire, in a cache72 * made when the layer is built: one per isolate in a Worker.73 */65/** Tokens are cached per (repo, scope) in a cache made when the layer is built: one per isolate. */66export const UpstreamRepoHost: Layer.Layer<Upstream, never, RepoHost | Fetch> =67 Layer.effect(68 Upstream,69 Effect.gen(function* () {
49 unmodified lines
modified:packages/git/src/blame.ts+1 added-26 removed
1/**2 * First-parent blame, pure: given one file's versions newest first (one3 * per first-parent commit that changed its blob), each line of the newest4 * goes to the oldest version that still holds it unchanged, found by a5 * line diff (`line-diff.ts`) between each version and the one before it.2 * Lines the oldest version given still holds go to it: the caller knows7 * whether that version brought them or the walk stopped there. A caller8 * that reads versions one at a time folds them with `traceBack`, so only9 * two are held at once.3 * whether that version brought them or the walk stopped there.4 */5import type { WhyRange } from "@repo/protocol/domain/code";6import type { CommitSha } from "@repo/protocol/ids";78import { Edit, lineDiff } from "./line-diff.ts";916/** One version of a file: the commit that made it, and its text. */10export interface Version {11 readonly sha: CommitSha;12 readonly text: string;13}1422/** Why each line is there, and whether any went to the oldest version given. */15export interface Blame {16 readonly ranges: readonly WhyRange[];17 readonly reachedEnd: boolean;18}1928/** A text's lines, without the empty one after a final newline. */20export const linesOf = (text: string): readonly string[] => {21 if (text === "") {22 return [];23 }
6 unmodified lines
3031 return lines;32};3343/** Where each line of `after` sits in `before`, or -1 for a line `before` lacks. */34const originsOf = (before: readonly string[], after: readonly string[]) => {35 const origins = new Int32Array(after.length).fill(-1);3637 for (const edit of lineDiff(before, after)) {
6 unmodified lines
4445 return origins;46};4758/** Each line's version as ranges of consecutive lines, numbered from 1. */48const rangesOf = (owners: readonly CommitSha[]): readonly WhyRange[] => {49 const ranges: WhyRange[] = [];5051 for (const [index, sha] of owners.entries()) {
9 unmodified lines
6162 return ranges;63};6476/**77 * A blame under way: the newest version's lines each given a version, or78 * still open at a line of the version reached so far.79 */65export interface Tracing {81 /** Each line's version, or null while it is open. */66 readonly owners: readonly (CommitSha | null)[];83 /** Each open line of the newest, by where it sits in `lines`. */67 readonly open: ReadonlyMap<number, number>;68 readonly lines: readonly string[];69 readonly sha: CommitSha;70}7189/** A blame of `newest`, every line open. */72export const blameFrom = (newest: Version): Tracing => {73 const lines = linesOf(newest.text);7475 return {
3 unmodified lines
79 sha: newest.sha,80 };81};82101/** Whether every line has its version, so no older one need be read. */83export const isSettled = (tracing: Tracing) => tracing.open.size === 0;84104/**105 * `tracing` taken back to `older`, the version before the one it reached:106 * each open line `older` lacks goes to the version reached.107 */85export const traceBack = (tracing: Tracing, older: Version): Tracing => {86 const lines = linesOf(older.text);87 const origins = originsOf(lines, tracing.lines);88 const owners = [...tracing.owners];
11 unmodified lines
100101 return { lines, open, owners, sha: older.sha };102};103127/** Why each line is there, the open lines going to the version reached. */104export const settle = (tracing: Tracing): Blame => ({105 ranges: rangesOf(tracing.owners.map((owner) => owner ?? tracing.sha)),106 reachedEnd: tracing.open.size > 0,107});108133/** Why each line of the newest of `versions` (newest first) is there. */109export const blame = (versions: readonly Version[]): Blame => {110 const [newest, ...older] = versions;111112 if (newest === undefined) {
15 unmodified lines
modified:packages/git/src/custody.ts+2 added-11 removed
2 unmodified lines
3import type { Refusal } from "@repo/protocol/refusal";4import { Context } from "effect";5import type { Array, Effect, Option } from "effect";67/** One ref in a push: `None` for `from` creates it, for `to` deletes it. */7export interface Command {8 readonly ref: RefName;9 readonly from: Option.Option<CommitSha>;10 readonly to: Option.Option<CommitSha>;11}1214/**15 * Who may push what. A push lands whole or not at all at the gateway: any16 * refusal turns every ref in it away, and each refusal reaches the pusher in17 * git's own output.18 */13/** A push lands whole or not at all at the gateway: any refusal turns every ref away. */14export class Custody extends Context.Service<15 Custody,16 {22 /** Before anything reaches the upstream; a refusal forwards nothing. */17 readonly admit: (18 repo: RepoName,19 commands: Array.NonEmptyReadonlyArray<Command>20 ) => Effect.Effect<readonly Refusal[]>;27 /**28 * After the upstream took the push, such as stage 0–1 over the29 * answerer's fork; a refusal reaches the pusher though the fork keeps it.30 */21 /** A refusal here reaches the pusher though the upstream already took the push. */22 readonly review: (23 repo: RepoName,24 commands: Array.NonEmptyReadonlyArray<Command>25 ) => Effect.Effect<readonly Refusal[]>;
2 unmodified lines
modified:packages/git/src/gateway.ts+2 added-34 removed
24 unmodified lines
25// or without `.git`, then the endpoint.26const ROUTE =27 /^\/(?<name>[A-Za-z0-9._-]+?(?:\/[A-Za-z0-9._-]+?){0,2})(?:\.git)?\/(?<endpoint>info\/refs|git-upload-pack|git-receive-pack)$/u;2829/** One of the three endpoints of git's smart HTTP. */29export type GitEndpoint = "info/refs" | "git-upload-pack" | "git-receive-pack";3032/** What a smart HTTP path names: the address as spelled, its repo, and the endpoint. */31export interface GitRoute {32 readonly endpoint: GitEndpoint;35 /** The address as the path spelled it, for a message. */33 readonly name: string;37 /** The repo the address names (ADR 0032); none for an address no project can have. */34 readonly repo: Option.Option<RepoName>;35}3641/**42 * The repo a smart HTTP path names, and the endpoint it asks for; `None`43 * for any other path.44 */37export const gitRoute = (pathname: string): Option.Option<GitRoute> =>38 Option.flatMap(39 Option.fromNullishOr(ROUTE.exec(pathname)?.groups),40 ({ endpoint, name }) =>
30 unmodified lines
7172 return picked;73};7483/**84 * Passes bytes and fails the stream on anything else: the Workers types leave85 * a request body's chunk type open.86 */75/** The Workers types leave a request body's chunk type open. */76const bytes = () =>77 new TransformStream<unknown, Uint8Array>({78 transform: (chunk, controller) => {79 if (chunk instanceof Uint8Array) {
5 unmodified lines
85 }86 },87 });88100/** A POST's body, the only kind of request with one here. */89const bodyOf = (request: Request) =>90 request.method === "POST" && request.body !== null91 ? Option.some(request.body.pipeThrough(bytes()))92 : Option.none();93106/** A plain-text reply, which git prints as the reason a request failed. */94export const plain = (95 status: number,96 text: string,97 headers: Readonly<Record<string, string>> = {}
2 unmodified lines
100 headers: { "content-type": "text/plain; charset=utf-8", ...headers },101 status,102 });103117/** The upstream's reply as the client gets it: status, type and body, uncached. */104const relay = (response: Response) =>105 new Response(response.body, {106 headers: {107 "cache-control": "no-cache",
21 unmodified lines
129130const busy = (messages: readonly Uint8Array[]) =>131 messages.some((message) => new TextDecoder().decode(message).includes(BUSY));132147/** Where each ref in the upstream points now. */133const tipsOf = (repo: RepoName) =>134 Effect.gen(function* () {135 const response = yield* (yield* Upstream).exchange(136 repo,
11 unmodified lines
148 readAdvertisement(new Uint8Array(advertisement))149 );150 }).pipe(Effect.orElseSucceed(() => new Map<string, CommitSha>()));151167/**168 * The upstream's refusals in the closed union: a ref that moved under the169 * push is `StaleBase`, from the base the pusher named to where the ref is now.170 */152const translate = (153 repo: RepoName,154 commands: readonly Command[],155 refs: readonly RefStatus[]
25 unmodified lines
181 })182 );183 });184204/**205 * The upstream's reply to a push, as the pusher gets it. When every ref206 * landed, custody reviews the push and may still turn it away. A reply that207 * is not a report passes on as it came.208 */185const answer = (186 repo: RepoName,187 opening: Opening,188 commands: Array.NonEmptyReadonlyArray<Command>,
78 unmodified lines
267 )268 : result(reply);269 });270295/**296 * A push: custody admits it or it goes no further. A refused push is read to297 * its end and answered here; the upstream never sees it.298 */271const push = (272 repo: RepoName,273 headers: Headers,274 body: ReadableStream<Uint8Array>
39 unmodified lines
314 Effect.succeed(plain(400, reason))315 )316 );317346/**347 * The platform's git endpoint, speaking git's smart HTTP: `info/refs`,348 * `git-upload-pack` (protocol v2 passes straight through) and349 * `git-receive-pack`. Packs stream through and are never held whole.350 */318/** Packs stream through and are never held whole. */319export const gateway = (320 request: Request321): Effect.Effect<Response, never, Upstream | Custody> =>322 Effect.gen(function* () {
50 unmodified lines
modified:packages/git/src/line-diff.ts+4 added-31 removed
1/**2 * A line diff with no dependency: the whole edit script from one file's3 * lines to another's, as runs of equal, deleted and inserted lines. The4 * shortest script is Myers' O(ND) diff over the lines left once the shared5 * head and tail are set aside; past `MAX_EDITS` edits it stops looking for6 * the shortest, and the script keeps only the lines found once in each7 * file, in order (git's patience anchors, matched greedily).8 *9 * Positions are 0-based: an edit starts at `oldStart` in the old lines and10 * `newStart` in the new, and in a run of changes the deletions come first.2 * Myers' O(ND) diff over the lines left once the shared head and tail are set3 * aside; past `MAX_EDITS` edits it keeps only the lines found once in each4 * file, in order (git's patience anchors, matched greedily). Positions are5 * 0-based, and in a run of changes the deletions come first.6 */7import { Data, Option } from "effect";814/** `count` lines from `oldStart` in the old lines and `newStart` in the new. */9interface Span {10 readonly oldStart: number;11 readonly newStart: number;12 readonly count: number;13}1421/** One run of an edit script: lines both files share, or lines one alone holds. */15export type Edit = Data.TaggedEnum<{16 Delete: Span;17 Equal: Span;18 Insert: Span;19}>;2021export const Edit = Data.taggedEnum<Edit>();2230/** One line's step through the script. */23type Step = Edit["_tag"];2433// Past this many edits the diff stops looking for the shortest script.25const MAX_EDITS = 1024;2627const at = (values: Int32Array, index: number) => values[index] ?? 0;28
38 unmodified lines
6768 return steps.toReversed();69};7080/** A shortest edit script from `previous` to `next`, or none past `MAX_EDITS`. */71const myers = (72 previous: readonly string[],73 next: readonly string[]74): Option.Option<readonly Step[]> => {
34 unmodified lines
109110 return Option.none();111};112123/** How many times each line occurs in `lines`. */113const countsOf = (lines: readonly string[]) => {114 const counts = new Map<string, number>();115116 for (const line of lines) {
2 unmodified lines
119120 return counts;121};122134/**135 * A script for a rewrite too large for the shortest: the lines found once136 * in each file are kept, in order, each matched after the last; every other137 * line is deleted or inserted.138 */123const anchored = (124 previous: readonly string[],125 next: readonly string[]126): readonly Step[] => {
33 unmodified lines
160161 return steps;162};163180/** The steps of a script, as runs: in each run of changes, deletions first. */164const runsOf = (steps: readonly Step[]): readonly Edit[] => {165 const edits: Edit[] = [];166 let oldStart = 0;167 let newStart = 0;
42 unmodified lines
210211 return edits;212};213231/** How many lines from each end `previous` and `next` share. */214export const sharedEnds = (215 previous: readonly string[],216 next: readonly string[]217) => {
19 unmodified lines
237238 return { head, tail };239};240259/** `middle` with the shared head and tail around it. */241const framed = (242 ends: { readonly head: number; readonly tail: number },243 middle: readonly Step[]244): readonly Step[] => [
1 unmodified line
246 ...middle,247 ...Array.from({ length: ends.tail }, (): Step => "Equal"),248];249269/**270 * A shortest edit script from `before` to `after`, or none when it takes271 * more than `MAX_EDITS` edits past the shared head and tail.272 */250export const shortestDiff = (251 before: readonly string[],252 after: readonly string[]253): Option.Option<readonly Edit[]> => {
7 unmodified lines
261 (middle) => runsOf(framed(ends, middle))262 );263};264288/**289 * The edit script from `before` to `after`: the shortest, or, for a rewrite290 * past `MAX_EDITS` edits, one that keeps the lines found once in each file.291 */265export const lineDiff = (266 before: readonly string[],267 after: readonly string[]268): readonly Edit[] =>
13 unmodified lines
modified:packages/git/src/notes.ts+2 added-20 removed
11 unmodified lines
12import { DateTime, Effect, Option, Schema } from "effect";1314import { committerLine } from "./trailers.ts";1516/**17 * Where verdicts live as git notes: one JSON note per commit, read18 * with `git notes --ref=<slug> show <commit>`.19 */16export const notesRef = RefName.make(`refs/notes/${Brand.slug}`);1722/** A verdict to write as the note on `target`, on top of the notes at `notesParent` in `repo`. */18export interface NoteInput {19 readonly repo: RepoName;20 readonly notesParent: Option.Option<CommitSha>;21 readonly target: CommitSha;22 readonly verdict: Verdict;23 readonly now: DateTime.Utc;24}2531/**32 * A git directory in memory that a push takes objects from: a `PushSource`33 * whose file system is `memoryFs`, so a reader gets its typed API.34 */26export interface ScratchSource extends PushSource {27 readonly fs: MemoryFs;28}29
20 unmodified lines
5051const bytesOfHex = (id: string) =>52 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));5363/** git's zlib stream, as a loose object holds it. */54const deflate = (bytes: Uint8Array) =>55 Effect.promise(() =>56 new Response(57 // A copy on its own `ArrayBuffer`: Node's `Blob` types refuse a view
55 unmodified lines
113 input.message,114 ].join("\n")115 );116127/**128 * A bare git directory in memory that a push takes objects from: loose,129 * zlib-deflated objects named by the SHA-1 of their header and content.130 */117const scratch = () =>118 Effect.gen(function* () {119 const fs = memoryFs();120 const gitdir = "/notes.git";
45 unmodified lines
166 source: { fs, gitdir } satisfies ScratchSource,167 };168 });169184/** The notes tree's entries at `parent`, read through the port; none for the first note. */170const notesAt = (repo: RepoName, parent: Option.Option<CommitSha>) =>171 Option.match(parent, {172 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),173 onSome: (sha) =>
17 unmodified lines
191192const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));193194/**210 * The notes commit that puts `verdict` on `target`, in git's own notes211 * layout: a fanout-free tree with one blob per annotated commit, named by its212 * SHA, holding the verdict as JSON. The tree keeps every note under213 * `notesParent` (read through the port), and the platform commits it at214 * `now`. The new blob, tree and commit sit in a scratch git directory in195 * git's own notes layout: a fanout-free tree with one blob per annotated196 * commit, named by its SHA. The new objects sit in a scratch git directory in197 * memory, which `RepoHost.push` takes them from; the earlier notes' objects198 * are referenced by id and are already in `repo`.199 */200export const noteCommit = (
41 unmodified lines
modified:packages/git/src/patch-id.ts+3 added-5 removed
7 unmodified lines
8 .map((byte) => byte.toString(16).padStart(2, "0"))9 .join("");1011/**12 * An answer's patch id: SHA-256 over its change set as sorted13 * `path\0before\0after\n` lines, an absent blob as the empty string. It14 * ignores order and moves exactly when a blob the answer touches moves. It15 * is the platform's own id, not `git patch-id`, so a Worker computes it with16 * WebCrypto and no diff.12 * SHA-256 over sorted `path\0before\0after\n` lines, an absent blob as the13 * empty string. Not `git patch-id`, so a Worker computes it with WebCrypto and14 * no diff.15 */16export const patchId = (changes: readonly Change[]): Effect.Effect<PatchId> => {17 const lines = Array.sort(18 changes.map(
9 unmodified lines
modified:packages/git/src/pkt-line.ts+2 added-12 removed
20 unmodified lines
21};2223export const utf8 = (text: string) => encoder.encode(text);2425/** One pkt-line around `payload`. */25export const pkt = (payload: Uint8Array) =>26 concat([27 encoder.encode((payload.length + 4).toString(16).padStart(4, "0")),28 payload,29 ]);3032/** A data line's payload, or `Flush`. */31export type Packet = Uint8Array | "Flush";3235/**36 * The packet that starts at `at`, with where the next one starts; `None` if37 * the bytes stop before the packet does.38 */33export const packetAt = (34 bytes: Uint8Array,35 at: number36): Option.Option<{ readonly packet: Packet; readonly next: number }> => {
21 unmodified lines
58 packet: bytes.subarray(at + 4, at + length),59 });60};6168/** Every packet in `bytes`, which must hold whole packets only. */62export const packets = (bytes: Uint8Array) => {63 const found: Packet[] = [];64 let at = 0;65
13 unmodified lines
7980const LENGTH = /^[0-9a-f]{4}$/u;8182/**90 * The text lines of a request in pkt-line framing, newline dropped, for a91 * reader that only looks: protocol v2's delimiter (`0001`) and response92 * end (`0002`) carry no line, nor does a flush, and reading stops where93 * the framing breaks, keeping the lines before it. `packets` is the strict94 * reader.83 * Lenient: delimiter, response-end and flush packets carry no line, and84 * reading stops where the framing breaks. `packets` is the strict reader.85 */86export const textLines = (bytes: Uint8Array): readonly string[] => {87 const decoder = new TextDecoder();88 const lines: string[] = [];
21 unmodified lines
modified:packages/git/src/receive-pack.ts+2 added-24 removed
1/**2 * The receive-pack side of git's smart HTTP (gitprotocol-pack): the command3 * list that opens a push, and the report-status that answers it.4 */1import { RefName } from "@repo/artifacts/repo-host";2import { CommitSha } from "@repo/protocol/ids";3import type { Refusal } from "@repo/protocol/refusal";4import { explain, headline } from "@repo/protocol/render";
1 unmodified line
67import type { Command } from "./custody.ts";8import { FLUSH, concat, packetAt, packets, pkt, utf8 } from "./pkt-line.ts";914/** The request is not a receive-pack request git would send. */10export class Malformed extends Data.TaggedError("Malformed")<{11 readonly reason: string;12}> {}13
6 unmodified lines
20 hex === ZERO ? Option.none() : Option.some(CommitSha.make(hex));2122const isRefName = Schema.is(RefName);2329/** The opening of a push, and every byte read to find it. */24export interface Opening {25 readonly commands: readonly Command[];26 readonly capabilities: ReadonlySet<string>;27 readonly read: Uint8Array;
45 unmodified lines
73 catch: () => new Malformed({ reason: "the push could not be read" }),74 try: () => reader.read(),75 });7683/**84 * Reads a push's command list, up to its flush, from the request body, then85 * lets the body go: the pack that follows stays unread in it. An empty list86 * is git's probe before a large push.87 */77/** The pack that follows stays unread in the body. An empty list is git's probe before a large push. */78export const readOpening = (body: ReadableStream<Uint8Array>) =>79 Effect.gen(function* () {80 const reader = body.getReader();81 const lines: string[] = [];
38 unmodified lines
120 evaluate: () => body,121 onError: () => new Malformed({ reason: "the push could not be read" }),122 });123134/** Reads the rest of a body and drops it, so the client finishes sending. */124/** So the client finishes sending. */125export const drain = (body: ReadableStream<Uint8Array>) =>126 Stream.runDrain(rest(body)).pipe(Effect.ignore);127138/** The bytes already read, then the rest of the body, as one stream. */128export const resume = (read: Uint8Array, body: ReadableStream<Uint8Array>) =>129 Stream.toReadableStream(Stream.concat(Stream.succeed(read), rest(body)));130131// The largest payload a side-band packet carries, by the client's capability.
17 unmodified lines
149150 return parts;151};152164/** One ref's line in a report: `None` if it landed, else git's reason. */153export interface RefStatus {154 readonly ref: string;155 readonly ng: Option.Option<string>;156}157170/** The upstream's answer to a push, out of its side band. */158export interface UpstreamReport {172 /** Side-band messages, which git prints as `remote:` lines. */159 readonly messages: readonly Uint8Array[];174 /** `ok`, or why the pack did not unpack; `None` if no report came. */160 readonly unpack: Option.Option<string>;161 readonly refs: readonly RefStatus[];162}163
1 unmodified line
165 new TextDecoder().decode(bytes).replace(/\n$/u, "");166167const STATUS = /^(?<verdict>ok|ng) (?<ref>\S+)(?: (?<reason>.*))?$/u;168184/** Reads the upstream's reply to a push; throws if it is not pkt-lines. */169export const readReport = (170 capabilities: ReadonlySet<string>,171 reply: Uint8Array172): UpstreamReport => {
37 unmodified lines
210211 return { messages, refs, unpack };212};213230/**231 * The reply a pusher gets: side-band messages, then every refusal explained,232 * as `remote:` lines; then `ok` or `ng <ref> <reason>` for every ref.233 */214export const writeReport = (215 capabilities: ReadonlySet<string>,216 messages: readonly Uint8Array[],217 refusals: readonly Refusal[],
36 unmodified lines
254};255256const ADVERTISED = /^(?<oid>[0-9a-f]{40}) (?<ref>[^\0\n ]+)/u;257278/** The refs in a ref advertisement (`info/refs`) and the commit each names. */258export const readAdvertisement = (advertisement: Uint8Array) =>259 new Map(260 packets(advertisement).flatMap((packet) => {261 const fields =
4 unmodified lines
266 : [[fields.ref, CommitSha.make(fields.oid)] as const];267 })268 );269291/** Every ref turned away for the same refusals. */270export const refuseAll = (271 commands: readonly Command[],272 refusals: Array.NonEmptyReadonlyArray<Refusal>273): RefStatus[] =>
1 unmodified line
modified:packages/git/src/trailers.ts+1 added-32 removed
9 unmodified lines
10 RequestId,11} from "@repo/protocol/ids";12import { Array, Option, Order, Schema } from "effect";1314/** One `Key: value` line of a commit message's trailer block. */14export interface Trailer {15 readonly key: string;16 readonly value: string;17}1820/** A git identity: the name and email of an author or committer line. */19export interface GitIdentity {20 readonly name: string;21 readonly email: string;22}2326/** The accountable person, as a landing's author: their handle at the platform's users domain. */24export const authorLine = (handle: Handle): GitIdentity => ({25 email: `${handle}@users.${Brand.domain}`,26 name: handle,27});2832/** The platform, which commits every landing. */29export const committerLine: GitIdentity = {30 email: `platform@${Brand.domain}`,31 name: Brand.name,32};3338/** What a landing commit's message is made of; every trailer comes from the platform's own rows. */34export interface LandingMessage {35 readonly subject: string;36 readonly body?: string;37 readonly credits: readonly Credit[];
3 unmodified lines
41 readonly verdict?: {42 readonly patchId: PatchId;43 readonly checkVersion: CheckVersion;44 };50 /** The `Held-back:` value, such as `export 7/7 @ sha256:…`, without its key. */45 readonly heldBack?: string;46 readonly requestId?: RequestId;47}48
6 unmodified lines
5556// git's scissors line: it and everything below it are not the message.57const SCISSORS = "# ------------------------ >8 ------------------------";5865/**66 * Whether git reads `line` as the end of a commit message: a `---` divider67 * (then a blank or the line's end) or the scissors line.68 */59const endsMessage = (line: string) =>60 line.startsWith(SCISSORS) ||61 (line.startsWith("---") && (line.length === 3 || isSpace(line.slice(3))));62
19 unmodified lines
82 `${oneLine(harness)}${model === undefined ? "" : `:${oneLine(model)}`} (${verified ? "verified" : "claimed"})`;8384const roleOrder = (role: CreditRole) => CreditRole.literals.indexOf(role);8596/**97 * Credits in the order of `CreditRole`, people within a role in the order98 * given, each (role, person) once: the same rows always make the same message.99 */86const ordered = (credits: readonly Credit[]) =>87 Array.dedupeWith(88 Array.sortWith(credits, ({ role }) => roleOrder(role), Order.Number),89 (one: Credit, other: Credit) =>90 one.role === other.role && one.handle === other.handle91 );92107/**108 * A landing commit's message: the subject, the body, then one trailer block109 * that credits each person by role, discloses each agent as `Assisted-by`,110 * and cites the ask, the verdict, the held-back result and the request.111 */93export const formatLanding = (input: LandingMessage): string => {94 const trailers: readonly Trailer[] = [95 ...ordered(input.credits).map(({ handle, role }) => ({96 key: role,
160 unmodified lines
257258 return Option.none();259};260280/** A value with its continuation lines folded to single spaces. */261const unfold = (value: string) =>262 value263 .replaceAll(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/gu, "")264 .replaceAll(/\n[ \t\n\v\f\r]*/gu, " ")265 .replaceAll(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/gu, "");266287/**288 * A message's trailers in order, as `git interpret-trailers --parse` reads289 * them: keys and values trimmed, continuation lines unfolded, lines that are290 * not trailers left out.291 */267export const parseTrailers = (message: string): readonly Trailer[] => {268 const lines = logLines(message);269270 return Option.match(blockStart(lines), {271 onNone: () => [],272 onSome: (start) => {298 // Each item is one trailer with its continuation lines, or another line.273 const items: string[] = [];274 let open = false;275276 for (const line of lines.slice(start)) {
65 unmodified lines
342 model === undefined ? { harness, verified } : { harness, model, verified }343 );344};345372/** The people a landing credits, and the agents it discloses. */346export interface LandingCredits {347 readonly credits: readonly Credit[];348 readonly assisted: readonly AgentTrailer[];349}350378/**379 * Who a landing credits, and which agents it discloses. Only trailers the380 * platform writes count: a credit names a platform handle by `authorLine`,381 * and `Assisted-by` is never credit.382 */351/** Only trailers the platform writes count, and `Assisted-by` is never credit. */352export const creditsOf = (message: string): LandingCredits => {353 const trailers = parseTrailers(message);354355 return {
4 unmodified lines
modified:packages/git/src/tree-diff.ts+2 added-29 removed
4 unmodified lines
5import { Array, Effect, Option, Order, Semaphore } from "effect";67import { Edit, sharedEnds, shortestDiff } from "./line-diff.ts";89/**10 * One file an answer changed, with its blob ids before and after. The same11 * shape as the gate's `Change` (`@repo/gate/facts`), which git cannot import.12 */9/** The same shape as the gate's `Change` (`@repo/gate/facts`), which git cannot import. */10export interface Change {11 readonly path: RepoPath;12 readonly status: "added" | "modified" | "deleted";13 readonly before?: BlobSha;14 readonly after?: BlobSha;15}1620/** A line a change added, numbered from 1 in the new file. */17export interface AddedLine {18 readonly line: number;19 readonly text: string;20}
97 unmodified lines
118119 return changed.flat();120 });121126/**127 * The files that differ between two trees of `repo`, read through the128 * `RepoHost` port alone: it walks both roots and descends only into subtrees129 * whose ids differ, since the store has no diff of its own. At most eight130 * trees are read at once.131 */122/** Descends only into subtrees whose ids differ: the store has no diff of its own. */123export const treeDiff = (124 repo: RepoName,125 base: TreeSha,126 head: TreeSha
17 unmodified lines
144145 return lines;146};147157/**158 * Lines of `next` with no partner in `previous`, matched by count: the159 * fallback for a rewrite too large for the shortest script.160 */148const unmatched = (previous: readonly string[], next: readonly string[]) => {149 const left = new Map<string, number>();150151 for (const line of previous) {
8 unmodified lines
160 return count > 0 ? [] : [index];161 });162};163177/**178 * The lines of `next` that are not in `previous`, numbered from 1: the179 * insertions of the shortest edit script (`line-diff.ts`), or, for a180 * rewrite too large for it, the lines with no partner by count.181 */164const added = (165 previous: readonly string[],166 next: readonly string[]167): readonly AddedLine[] =>
13 unmodified lines
181 : []182 ),183 }).map((index) => ({ line: index + 1, text: next[index] ?? "" }));184203/**204 * A file's lines; none for a binary blob, or for a submodule's pointer, whose205 * id names a commit in another repo, so the store has no blob by it.206 */185const textOf = (repo: RepoName, blob: BlobSha | undefined) =>186 blob === undefined187 ? Effect.succeedSome<readonly string[]>([])188 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(
7 unmodified lines
196// Changes diffed at once, each reading its two blobs together: eight store197// calls, and no more than four files' text held at a time.198const CHANGES = { concurrency: STORE_CALLS / 2 } as const;199222/**223 * The lines each added or modified file gained, by a line diff of its blobs.224 * A binary blob (a NUL in its first 8 KiB) and a submodule's pointer report225 * no lines. At most eight blobs are read at once.226 */200export const addedLines = (201 repo: RepoName,202 changes: readonly Change[]203): Effect.Effect<
26 unmodified lines
modified:packages/git/src/upload-pack.ts+2 added-11 removed
1/**2 * What a clone's or fetch's upload-pack request asks of a repo3 * (gitprotocol-pack, gitprotocol-v2), read from its pkt-lines for a log of4 * who read what: whether it reads content, and the first commit it wants.5 * Lines it can't make out still read, with no commit named, so a log built6 * on it errs toward a read.7 */1// A request it can't make out still reads, with no commit named, so a read2// log built on it errs toward a read.3import { CommitSha } from "@repo/protocol/ids";4import { Array, Option, Schema } from "effect";56import { textLines } from "./pkt-line.ts";713/** What one upload-pack request reads of a repo. */8export interface UploadRequest {15 /** Anything but protocol v2's `ls-refs`, which lists refs and reads no content. */9 readonly reads: boolean;17 /** The first commit it wants, if a line names one. */10 readonly want: Option.Option<CommitSha>;11}1213const WANT = /^want (?<oid>[0-9a-f]{40})(?: |$)/u;1415const asCommit = Schema.decodeOption(CommitSha);1625/** The request `bytes` hold, as git wrote it (inflated, if it was gzipped). */17export const readUpload = (bytes: Uint8Array): UploadRequest => {18 const lines = textLines(bytes);1920 return {
9 unmodified lines
modified:packages/git/src/upstream.ts+1 added-12 removed
1 unmodified line
2import type { RepoNotFound } from "@repo/artifacts/repo-host";3import { Context, Data, Schema } from "effect";4import type { Effect } from "effect";56/** The two git services the gateway carries. */6export type Service = "git-upload-pack" | "git-receive-pack";79/**10 * One smart-HTTP exchange with the git server behind the gateway: a ref11 * advertisement (`GET info/refs?service=…`) or a service call (`POST12 * <service>`). The headers are the gateway's own pick of the client's; the13 * client's credentials are never among them.14 */8/** The client's credentials are never among the headers. */9export type Exchange = Data.TaggedEnum<{10 Advertise: { readonly service: Service; readonly headers: Headers };11 Call: {12 readonly service: Service;
3 unmodified lines
16}>;1718export const Exchange = Data.taggedEnum<Exchange>();1926/** The git server behind the gateway did not answer. */20export class UpstreamFailure extends Schema.TaggedError<UpstreamFailure>()(21 "UpstreamFailure",22 { reason: Schema.String, repo: RepoName }23) {}2432/**33 * The git server the gateway forwards to, holding the platform's credentials:34 * Artifacts in production, `git http-backend` in tests.35 */25export class Upstream extends Context.Service<26 Upstream,27 {28 readonly exchange: (
5 unmodified lines
modified:packages/git/test/blame.test.ts-5 removed
1/**2 * First-parent blame over a file's versions, newest first: each line of3 * the newest goes to the oldest version that still holds it unchanged, as4 * contiguous ranges of lines numbered from 1.5 */1import { describe, expect, it } from "@effect/vitest";2import { CommitSha } from "@repo/protocol/ids";34import { blame } from "../src/blame.ts";
54 unmodified lines
modified:packages/git/test/gateway.test.ts-11 removed
8 unmodified lines
9import { Custody } from "../src/custody.ts";10import { gitRoute } from "../src/gateway.ts";11import { admitAll, commit, world } from "./world.ts";1213/** Custody that refuses, before forwarding, any push touching `ref`. */13const refusing = (ref: string, refusals: readonly Refusal[]) =>14 Custody.of({15 admit: (_repo, commands) =>16 Effect.succeed(
1 unmodified line
18 ),19 review: () => Effect.succeed([]),20 });2123/**24 * Artifacts' whole reply to a push it is too busy to take, as a probe recorded25 * it: one side-band 3 (fatal) packet, then the end of the response.26 */22const artifactsBusy = () =>23 new Response("0024\u0003artifacts_git_receive_pack_busy", {24 headers: { "content-type": "application/x-git-receive-pack-result" },25 });2632/**33 * The lines git printed from the server's side band, less the spaces git pads34 * them with to clear a progress line.35 */27const remoteLines = (stderr: string) =>28 stderr29 .split("\n")30 .filter((line) => line.startsWith("remote: "))
1 unmodified line
3233// A credential the client sends; the gateway must keep it from the upstream.34const asClient = ["-c", "http.extraHeader=Authorization: Bearer client-secret"];3545/** Text that compresses poorly, from a fixed seed (Park and Miller's generator). */36const noise = (length: number) => {37 const digits: string[] = [];38 let state = 20_261_006;39
201 unmodified lines
241 );242 expect(pushed.stderr).toContain(243 " ! [remote rejected] HEAD -> answer (OutOfScope)"244 );255 // The answerer's fork keeps what the upstream took.245 expect(yield* gitOk(upstream, "rev-parse", "answer")).toBe(answer);246 }).pipe(Effect.provide(NodeServices.layer)),247 20_000248 );
141 unmodified lines
modified:packages/git/test/line-diff.test.ts-6 removed
1/**2 * The line diff: a whole edit script from one file's lines to another's,3 * the shortest one Myers' diff finds, as runs of equal, deleted and4 * inserted lines that, applied to the old lines, rebuild the new.5 */1import { describe, expect, it } from "@effect/vitest";23import { Edit, lineDiff } from "../src/line-diff.ts";45const lines = (text: string) => (text === "" ? [] : text.split(" "));612/** `before` with `edits` applied, the inserted lines taken from `after`. */7const apply = (8 before: readonly string[],9 after: readonly string[],10 edits: readonly Edit[]
79 unmodified lines
modified:packages/git/test/notes.test.tsnot shown

Its text is not shown, modified.

modified:packages/git/test/trailers.test.tsnot shown

Its text is not shown, modified.

modified:packages/git/test/tree-diff.test.tsnot shown

Its text is not shown, modified.

modified:packages/git/test/upload-pack.test.tsnot shown

Its text is not shown, modified.

modified:packages/git/test/upstream.test.tsnot shown

Its text is not shown, modified.

modified:packages/git/test/world.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/rules-evaluator/bun-main.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/rules-evaluator/bun-prelude.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/rules-evaluator/bun.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/rules-evaluator/json.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/rules-evaluator/worker.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/config-folder.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/defaults.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/entry.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/finish.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/prelude.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/rules-evaluator.tsnot shown

Its text is not shown, modified.

modified:packages/rules/src/vouch.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/fixtures/cm/asks/iso-week.ask.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/fixtures/cm/asks/leap-year.ask.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/fixtures/cm/project.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/fixtures/sdk-stub.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/evaluate.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/example-burrow.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/example-datekit.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/fake-loader.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/finish.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/prelude.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/replay.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/vouch.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/worker.test.tsnot shown

Its text is not shown, modified.

modified:packages/rules/test/world.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/check.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/checked.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/functions.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/index.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/kind.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/project.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/run.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/territory.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/src/visibility.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/test/sdk.test.tsnot shown

Its text is not shown, modified.

modified:packages/sdk/test/visibility.test.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/clock.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/fake-artifacts-binding.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/git-client.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/git.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/golden.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/http-backend.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/scenarios.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/untouchable.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/test/fake-artifacts-binding.test.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/test/golden.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/env-schema/env-spec.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/env-schema/memory.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/vault/webcrypto.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/commitment.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/env-schema.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/env-shape.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/guards.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/index.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/layer-repos.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/leak-scan.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/ledger.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/posture.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/proxy.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/src/vault.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/fixtures/env/cases.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/fixtures/env/raw.d.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/env-shape.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/env-spec-adapter.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/guards.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/leak-scan.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/posture.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/proxy.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/smoke.test.tsnot shown

Its text is not shown, modified.

modified:packages/visibility/test/vault.test.tsnot shown

Its text is not shown, modified.