Merge build/comments-packages-rest into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
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
Provenance
- Commit
38cd503- Tree
de932cd- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
e4c407e- Parent 2
6273b84
212 files changed+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- */1 import { Brand } from "@repo/brand";2 3 import { installCommand } from "../install.ts";4 import { code } from "../text.ts";58 unmodified linesmodified: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- */6-1 import { code } from "../text.ts";2 import type { DocSource } from "./page.ts";3 import { cli } from "./page.ts";4 23 unmodified linesmodified:packages/agent-kit/src/docs/entries.ts-11 removed
1-/**2- * What names each page of the docs: its title, its one-line summary and3- * whether it is a guide or the reference, in the order the index lists4- * them. Apart from the pages' text, so a route's head and its not-found5- * read it without carrying every page into the first load.6- */1 import { Option } from "effect";2 9-/** A guide, written for a person doing one job, or a page of the reference. */3 export type DocPart = "guide" | "reference";4 12-/** What names a page, before it is written: enough for a list or a head. */5 export interface DocEntry {6 readonly slug: string;7 readonly title: string;8 readonly summary: string;9 readonly part: DocPart;10 }11 20-/** Every page as the index lists it, guides first. */12 export const docEntries = [13 {14 part: "guide",15 slug: "start-here",77 unmodified lines93 title: "Imported projects",94 },95 ] as const satisfies readonly DocEntry[];96 106-/** A page's slug: the last segment of its address. */97 export type DocSlug = (typeof docEntries)[number]["slug"];98 109-/** The page at `slug` as a list or a head names it; none for a slug no page has. */99 export const docEntry = (slug: string): Option.Option<DocEntry> =>100 Option.fromUndefinedOr(docEntries.find((entry) => entry.slug === slug));modified:packages/agent-kit/src/docs/held-back-checks.ts-5 removed
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- */1 import { Brand } from "@repo/brand";2 3 import { code } from "../text.ts";4 import type { DocSource } from "./page.ts";51 unmodified linesmodified: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- */1 export 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- */1 import { ProjectKey, ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";2 import { Option } from "effect";3 11-/**12- * One imported project: its name here, after its source namespace13- * (`github.com/pallets/click`), the key it was imported under (`click`),14- * its source, its licence, and what it is.15- */4 export interface ImportedProject {5 readonly name: ProjectName;6 readonly key: ProjectKey;7 readonly url: string;13 unmodified lines21 name: ProjectName.make(`${Option.getOrThrow(sourceNamespaceOf(url))}/${key}`),22 url,23 });24 37-/** Every imported project, in the order they were imported. */25 export const importedProjects: readonly ImportedProject[] = [26 imported(27 "anyhow",28 "https://github.com/dtolnay/anyhow",211 unmodified linesmodified:packages/agent-kit/src/docs/index.ts-9 removed
1-/**2- * The docs: five guides written for people doing one job, then the3- * reference, read from the sources that define it. Each page is pure4- * Markdown for the CLI's commands and the two hosts' URLs; the web draws5- * it at `/docs/<slug>` and serves the text at `/docs/<slug>.md`.6- */1 import { Option } from "effect";2 3 import { answerAnAsk } from "./answer-an-ask.ts";4 import { connectAnAgent } from "./connect-an-agent.ts";18 unmodified lines23 export type { DocEntry, DocPart, DocSlug } from "./entries.ts";24 25 export type { DocInput, DocPage } from "./page.ts";26 33-/** Every page, guides first, in the order the index lists them. */27 const sources: readonly DocSource[] = [28 startHere,29 answerAnAsk,30 runAProject,7 unmodified lines38 mcpPage,39 importedPage,40 ];41 49-/** Every page, written for `input`. */42 export const docPages = (input: DocInput): readonly DocPage[] =>43 sources.flatMap((source) =>44 Option.toArray(45 Option.map(docEntry(source.slug), (entry) =>1 unmodified line47 )48 )49 );50 59-/** The page at `slug`, written for `input`; none for a slug no page has. */51 export const docPage = (52 input: DocInput,53 slug: string54 ): Option.Option<DocPage> =>5 unmodified linesmodified:packages/agent-kit/src/docs/page.ts-12 removed
1-/**2- * One page of the docs, and what every page is written from: the CLI's3- * commands and the two hosts' URLs. A page is a title, a one-line summary4- * and its body; its Markdown opens with the title and the summary.5- */1 import { Brand } from "@repo/brand";2 3 import type { CommandDoc } from "../command-doc.ts";4 import { code, page } from "../text.ts";5 import type { DocEntry, DocSlug } from "./entries.ts";6 12-/** What every page is written from. */7 export interface DocInput {8 readonly commands: readonly CommandDoc[];9 readonly platformUrl: string;10 readonly webUrl: string;11 }12 19-/** One page as the web serves it. */13 export interface DocPage extends DocEntry {14 readonly markdown: string;15 }16 24-/** One page before it is written: its slug, and its body's lines from the input. */17 export interface DocSource {18 readonly slug: DocSlug;19 readonly body: (input: DocInput) => readonly string[];20 }21 30-/** `source` written for `input`, under what names it. */22 export const written = (23 entry: DocEntry,24 source: DocSource,25 input: DocInput7 unmodified lines33 ...source.body(input),34 ]),35 });36 46-/** A command as typed, in a code span: `<cli> claim <ask> --project <owner>/<name>`. */37 export const cli = (words: string) => code(`${Brand.cli} ${words}`);38 49-/** A block of shell commands. */39 export const shell = (...lines: readonly string[]) => [40 "```sh",41 ...lines,42 "```",43 ];44 56-/** A section's lines without its own `## ` heading, for a page that is that section. */45 export const withoutHeading = (lines: readonly string[]) => {46 const [first, blank, ...rest] = lines;47 48 return first?.startsWith("## ") === true && blank === "" ? rest : lines;1 unmodified linemodified:packages/agent-kit/src/docs/reference.ts-9 removed
1-/**2- * The reference: each page read from what defines it, never copied. The3- * commands from the CLI's one list, the refusals from the closed union,4- * git, landings and events from the text `/llms-full.txt` serves, the MCP5- * tools from the contracts served over MCP, and the imported projects from6- * the copy of the import plan.7- */1 import { Brand } from "@repo/brand";2 import {3 Contracts,4 Description,10 unmodified lines15 import { importedProjects } from "./imported.ts";16 import type { DocSource } from "./page.ts";17 import { withoutHeading } from "./page.ts";18 26-/** A command as typed: its words, then its positionals in angle brackets. */19 const usage = ({ path, positional }: CommandDoc) =>20 code(21 [Brand.cli, ...path, ...positional.map((name) => `<${name}>`)].join(" ")22 );35 unmodified lines58 body: () => withoutHeading(events()),59 slug: "events",60 };61 70-/** Each contract served over MCP: its tool name, what it does, and whether it only reads. */62 const mcpTools = () =>63 [...Contracts.requests.values()].flatMap(({ _tag, annotations }) =>64 Context.get(annotations, Surfaces).includes("mcp")65 ? [36 unmodified linesmodified:packages/agent-kit/src/docs/run-a-project.ts-5 removed
1-/**2- * The maintainer's guide: make a project, write how it takes changes in3- * its config folder, open asks, take proposals and drafts, spend Today's4- * decisions, finish an answer, land your own change and vouch.5- */1 import { Brand } from "@repo/brand";2 import { sourceHosts } from "@repo/protocol/ids";3 4 import { code } from "../text.ts";87 unmodified linesmodified:packages/agent-kit/src/docs/start-here.ts-4 removed
1-/**2- * The first guide: what the platform is, the four words a contributor3- * meets, the loop a change takes to `main`, and what a refusal looks like.4- */1 import { Brand } from "@repo/brand";2 3 import type { DocSource } from "./page.ts";4 import { cli } from "./page.ts";45 unmodified linesmodified:packages/agent-kit/src/agent-setup.ts-51 removed
1-/**2- * How an agent reaches the platform, set as a reference: a synopsis of the3- * CLI's commands; the channels it connects through (remote MCP for a client4- * that signs in over OAuth, MCP over stdio through the CLI, the CLI itself,5- * a sentence any agent can be handed, and the skills), each saying when to6- * use it and giving the snippets to copy; the endpoints an agent reads; the7- * limits a project's policy sets by default; and the refusals. The web draws8- * it as `/agents` and serves `agentSetupMarkdown` as `/agents.md`.9- *10- * Pure: the hosts hand in the CLI's commands as this package's one list11- * holds them and the two hosts' URLs. Each client's MCP JSON comes from12- * `mcpServersFor`, the builder the plugin bundles use, and every name from13- * `Brand`, the MCP server's name being `Brand.slug`.14- *15- * Client facts, as each client's docs give them: Claude Code adds a remote16- * server with `claude mcp add --transport http <name> <url>` and signs in17- * from `/mcp`; Cursor reads `.cursor/mcp.json`'s `mcpServers`, a remote18- * entry being its `url`; VS Code reads `.vscode/mcp.json`'s `servers`, a19- * remote entry being `{type: "http", url}`.20- */1 import { Brand } from "@repo/brand";2 import { PolicyInput } from "@repo/protocol/domain/policy";3 import { groups } from "@repo/protocol/refusal";4 import { Array as Arr, Schema } from "effect";4 unmodified lines9 import { span } from "./sections.ts";10 import { code, listed, page, printJson, table } from "./text.ts";11 12 export interface SetupSnippet {33- /** What the snippet is, or where it goes: a client, a file. */13 readonly label: string;14 readonly language: "sh" | "json" | "text";36- /** The text to copy, whole, with no trailing newline. */15 readonly text: string;16 }17 18 export interface SetupChannel {19 readonly title: string;42- /** One plain sentence, no Markdown: the agent this channel is for. */20 readonly useWhen: string;21 readonly snippets: readonly SetupSnippet[];22 }23 24 export interface SetupInput {48- /** Every CLI command, as `commandDocs` lists them. */25 readonly commands: readonly CommandDoc[];50- /** The platform's origin: its MCP endpoint and the CLI's sign-in. */26 readonly platformUrl: string;52- /** The web's origin: its Markdown, the CLI's downloads and the skills. */27 readonly webUrl: string;28 }29 56-/** Whether the CLI has the command whose words are `words`. */30 const has = (commands: readonly CommandDoc[], words: string) =>31 Arr.some(commands, ({ path }) => path.join(" ") === words);32 60-/** JSON as a snippet holds it: the generators' printing, without its final newline. */33 const json = (value: Parameters<typeof printJson>[0]) =>34 printJson(value).trimEnd();35 36 const remoteMcp = ({ platformUrl }: SetupInput): SetupChannel => ({79 unmodified lines116 title: "Skills",117 useWhen: `Your agent loads skills: each project's contribute skill is listed, with its digest, at ${webUrl}/.well-known/agent-skills/index.json.`,118 });119 148-/** Every channel, in the order the page shows them; stdio only when the CLI has `mcp`. */120 export const agentSetup = (input: SetupInput): readonly SetupChannel[] => [121 remoteMcp(input),122 ...(has(input.commands, "mcp") ? [stdioMcp()] : []),123 theCli(input),124 anyAgent(input),125 skills(input),126 ];127 157-// --- Synopsis -------------------------------------------------------------------158-159-/** One command as a synopsis gives it: how it is typed, and what it does. */128 export interface SynopsisLine {161- /** The CLI's name, its words, its arguments, then each flag it takes in brackets. */129 readonly usage: string;130 readonly summary: string;131 }132 166-/** Every command, one line each, in the catalog's order. */133 export const synopsis = (134 commands: readonly CommandDoc[]135 ): readonly SynopsisLine[] =>136 commands.map(({ flags, path, positional, summary }) => ({7 unmodified lines144 .map((flag) => `[${flag}]`),145 ].join(" "),146 }));147 182-// --- Endpoints ------------------------------------------------------------------183-184-/** One address an agent reads or calls. */148 export interface Endpoint {186- /** The address whole; `<…>` marks a part the reader fills in. */149 readonly url: string;150 readonly what: string;189- /** A plain GET in a browser shows it. */151 readonly readable: boolean;152 }153 193-/** Every address an agent reads, the web's first, then the platform's. */154 export const agentEndpoints = ({155 platformUrl,156 webUrl,157 }: Pick<SetupInput, "platformUrl" | "webUrl">): readonly Endpoint[] => [43 unmodified lines201 what: "Git over smart HTTP: clone a project, push an answer to your fork.",202 },203 ];204 245-// --- Limits ---------------------------------------------------------------------246-247-/** One limit and its value, as a person says them. */205 export interface Limit {206 readonly limit: string;207 readonly value: string;208 }209 253-/** What a policy that sets nothing takes: the defaults its schema fills in. */210 const policyDefaults = () =>211 Schema.decodeSync(212 Schema.Struct({213 budget: PolicyInput.fields.budget,1 unmodified line215 claims: PolicyInput.fields.claims,216 })217 )({});218 263-/**264- * The limits an agent meets: each project's policy may set its own, so the265- * values are the defaults; the platform's own rate limits stand in front.266- */219 export const agentLimits = (): readonly Limit[] => {220 const { budget, caps, claims } = policyDefaults();221 222 return [24 unmodified lines247 },248 ];249 };250 299-// --- Markdown -------------------------------------------------------------------300-251 const snippetLines = ({ label, language, text }: SetupSnippet) => [252 `${label}:`,253 "",254 `\`\`\`${language}`,50 unmodified lines305 ),306 "",307 ];308 359-/** The whole reference as one Markdown document: `/agents.md`. */309 export const agentSetupMarkdown = (input: SetupInput) =>310 page([311 "# For agents",312 "",10 unmodified linesmodified:packages/agent-kit/src/agents-block.ts-20 removed
1-/**2- * The AGENTS.md block: the brief every harness reads without installing3- * anything, between markers the platform owns. The first marker carries the4- * body's hash, so a hand-edited block is detectable; everything outside the5- * markers belongs to the project and is never touched.6- */1 import { Brand } from "@repo/brand";2 import type { Policy } from "@repo/protocol/domain/policy";3 import type { LandedSha, ProjectName } from "@repo/protocol/ids";4 import { Effect, Option } from "effect";2 unmodified lines7 import { contributeSkillName, contributeSkillPaths } from "./project-skill.ts";8 import { lanesOf, loopSteps, unfencedNorms } from "./sections.ts";9 import { code, listed, page } from "./text.ts";10 17-/** The block: its two marker lines and the text between them. */11 export interface AgentsBlock {12 readonly begin: string;13 readonly end: string;14 readonly body: string;41 unmodified lines56 ...unfencedNorms(policy.agents),57 ]);58 };59 67-/**68- * The block for a project's AGENTS.md, from its policy alone: the landing69- * changes nothing in it, so a landing that leaves the policy's text alone70- * leaves the block, and its hash, as they were.71- */60 export const agentsBlock = (input: {61 readonly project: ProjectName;62 readonly policy: Policy;63 readonly landed: LandedSha;8 unmodified lines72 }))73 );74 };75 88-/** The block as a file holds it: the markers on lines of their own. */76 const written = (block: AgentsBlock) =>77 `${block.begin}\n${block.body}${block.body.endsWith("\n") ? "" : "\n"}${block.end}`;78 92-/** Where an existing block starts and ends, whatever hash its first marker carries. */79 const locate = (80 existing: string,81 end: string82 ): Option.Option<{ readonly from: number; readonly to: number }> => {12 unmodified lines95 96 return marker ? Option.some({ from, to: to + end.length }) : Option.none();97 };98 113-/** What goes between a file's last text and an appended block: one blank line. */99 const separator = (existing: string) => {100 if (existing === "" || existing.endsWith("\n\n")) {101 return "";102 }103 104 return existing.endsWith("\n") ? "\n" : "\n\n";105 };106 122-/**123- * `existing` with the block in it: replacing the text from the first marker124- * to the last where a block is, appending it after a blank line where none125- * is. Every other byte stays as it was, and a second call changes nothing.126- */107 export const upsertAgentsBlock = (existing: string, block: AgentsBlock) =>108 Option.match(locate(existing, block.end), {109 onNone: () => `${existing}${separator(existing)}${written(block)}\n`,110 onSome: ({ from, to }) =>2 unmodified linesmodified:packages/agent-kit/src/command-doc.ts-37 removed
1-/**2- * One row per CLI command, the list the platform's skill, the CLI's MCP3- * prompt and the web's `llms.txt` all render from. Contract rows4- * come from each contract's annotations; the hand-written commands are5- * listed here, and `apps/cli/test/commands-doc.test.ts` holds the list to6- * the CLI.7- */1 import {2 Cli,3 Description,4 NeedsApproval,3 unmodified lines8 import type { Contracts } from "@repo/protocol/contracts";9 import { Array as Arr, Context, Order, Schema, SchemaAST } from "effect";10 11 export const CommandDoc = Schema.Struct({19- /** The contract it calls: always for a contract's row, sometimes for a local one. */12 contract: Schema.optionalKey(Schema.NonEmptyString),21- /** Every flag it takes, as typed: `--project`. */13 flags: Schema.Array(Schema.NonEmptyString),23- /** It runs only with `--yes`; `--dry-run` prints what it would send. */14 needsApproval: Schema.Boolean,25- /** The words after the CLI's name: `["env", "set"]`. */15 path: Schema.NonEmptyArray(Schema.NonEmptyString),27- /** The arguments it takes in order, by name. */16 positional: Schema.Array(Schema.NonEmptyString),17 readOnly: Schema.Boolean,18 source: Schema.Literals(["contract", "local"]),19 summary: Schema.NonEmptyString,20 });21 22 export type CommandDoc = typeof CommandDoc.Type;23 36-/**37- * The CLI's hand-written commands. `init` and `env set` stand in for the38- * contracts they call (`initProject`, `setEnv`), so those contracts get no39- * row of their own.40- */24 export const localCommandDocs: readonly CommandDoc[] = [25 {26 flags: [27 "--url",129 unmodified lines157 "Show your Today: the decisions to take, each with its evidence and a safe default; --tui opens it full-screen at a terminal.",158 },159 ];160 178-/**179- * The names of the local commands that call a contract: a contract whose180- * CLI name is one of them is that command, so it gets no row of its own.181- */161 const standIns = new Set(162 localCommandDocs.flatMap(({ contract, path }) =>163 contract === undefined ? [] : [path.join(" ")]164 )165 );166 188-/** A payload's field names, in the schema's order; none for a payload of no fields. */167 const fieldsOf = (ast: SchemaAST.AST) =>168 SchemaAST.isObjects(ast)169 ? ast.propertySignatures.map(({ name }) => String(name))170 : [];171 194-/**195- * One row per contract the CLI serves (its `Surfaces` include `cli`), in the196- * group's order, from its annotations: the `Cli` name split into words, its197- * positional fields, then every other payload field as a flag, `--json`,198- * `--yes` when it needs approval, and `--dry-run` unless it only reads. A199- * contract a local command calls under the same name is left to that200- * command's row.201- */172 export const contractCommandDocs = (173 group: typeof Contracts174 ): readonly CommandDoc[] =>175 [...group.requests.values()].flatMap((rpc) => {40 unmodified lines216 const byWords = Order.mapInput(Order.String, (doc: CommandDoc) =>217 doc.path.join(" ")218 );219 250-/**251- * Every command the CLI has, one row each, sorted by its words (so `ask`252- * and its subcommands come before `asks`): the contracts it projects and the253- * commands written by hand in it. The platform's skill, the CLI's MCP254- * prompt and the web's `llms.txt` all read this list;255- * `apps/cli/test/commands-doc.test.ts` holds it to the CLI's real tree.256- */220 export const commandDocs = (group: typeof Contracts): readonly CommandDoc[] =>221 Arr.sort([...contractCommandDocs(group), ...localCommandDocs], byWords);modified:packages/agent-kit/src/full-llms.ts-17 removed
1-/**2- * `/llms-full.txt`: what an agent needs beyond the index, in one file.3- * `frontLlms`' text, then every refusal of the closed union (every group,4- * from `refusalCatalog`), the CLI's exit codes, how git meets the platform, how a landing5- * happens (ADR 0014), one line per event a watcher hears (those four from6- * `llms-sections.ts`, which the docs show too), and the guides for the7- * moments an answer goes sideways.8- *9- * Pure, and every name comes from `Brand`; a guide names a command only10- * when the catalog has it.11- */1 import type { ProjectListing } from "@repo/protocol/domain/front-page";2 import { Option } from "effect";3 4 import type { CommandDoc } from "./command-doc.ts";9 unmodified lines14 import { code, page } from "./text.ts";15 16 type Commands = readonly CommandDoc[];17 29-// --- Guides ---------------------------------------------------------------------30-18 const guides = (commands: Commands, platformUrl: string) => [19 "## Guides",20 "",21 "### Recover from `StaleBase`",36 unmodified lines58 ` Claiming the ask again (${each}) returns the claim you hold, with its remote.`59 ).join("")}`,60 ];61 75-/**76- * `/llms-full.txt`: the index, then the refusals, exit codes, git,77- * landings, events and guides. The web serves it; the platform's `/` stays the index alone.78- */62 export const fullLlms = (input: {63 readonly commands: Commands;64 readonly projects: readonly ProjectListing[];65 readonly platformUrl: string;10 unmodified linesmodified:packages/agent-kit/src/generated-file.ts+2 added-48 removed
1-/**2- * A generated file, and how it says it was generated. A Markdown file opens3- * with Agent Skills frontmatter whose `metadata` names who manages it, the4- * landing it came from and the SHA-256 of its body, so a stale copy (its5- * body differs from the one the current policy gives) and a hand-edited copy6- * (its body no longer hashes to what it records) are both detectable.7- */1 import { Brand } from "@repo/brand";2 import { LandedSha } from "@repo/protocol/ids";3 import { Array as Arr, Effect, Option, Schema } from "effect";4 12-/** One file a generator makes: where it goes, and every byte of it. */5 export interface GeneratedFile {6 readonly path: string;7 readonly content: string;8 }9 18-/** What a managed file says about itself, and the body it says it of. */10 export interface Managed {20- /** The landing it was generated from; none for the platform's own files. */11 readonly landed: Option.Option<LandedSha>;22- /** `sha256:<64 hex>`, as its frontmatter records it. */12 readonly hash: string;13 readonly body: string;14 }15 1 unmodified line17 [...new Uint8Array(bytes)]18 .map((byte) => byte.toString(16).padStart(2, "0"))19 .join("");20 32-/**33- * `sha256:<64 hex>` of the text's UTF-8 bytes, through WebCrypto, which the34- * platform Worker and Node both have. SHA-256 of bytes in memory cannot fail35- * for a reason a caller could handle, so a failure is a defect.36- */21 export const contentHash = (text: string): Effect.Effect<string> =>22 Effect.tryPromise(() =>23 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))24 ).pipe(25 Effect.orDie,26 Effect.map((digest) => `sha256:${hex(digest)}`)27 );28 45-// Every value but the name is a YAML double-quoted string, written as JSON46-// writes one: a description has colons, and YAML would read a SHA made only47-// of digits as a number.29+// Values are JSON-quoted: a description has colons, and YAML would read a30+// SHA made only of digits as a number.31 const quoted = (value: string) => JSON.stringify(value);32 50-/**51- * A Markdown file with Agent Skills frontmatter: only the spec's `name`,52- * `description` and `metadata`, with `managed-by`, `landed` (when it came53- * from one) and `content-hash` (of `body`) under `metadata`.54- */33 export const frontmatter = (input: {34 readonly name: string;35 readonly description: string;36 readonly landed: Option.Option<LandedSha>;24 unmodified lines61 const decodeQuoted = Schema.decodeUnknownOption(62 Schema.fromJsonString(Schema.String)63 );64 87-/** A frontmatter value: a quoted one decoded, a plain one as it stands. */65 const valueOf = (raw: string) =>66 raw.startsWith('"') ? decodeQuoted(raw) : Option.some(raw);67 91-/** The `key: value` lines indented under `metadata:`, by key. */68 const metadataOf = (head: string) => {69 const lines = head.split("\n");70 const start = lines.indexOf("metadata:");71 15 unmodified lines87 };88 89 const decodeLanded = Schema.decodeUnknownOption(LandedSha);90 115-/** A Markdown file's frontmatter and the body after it; none without one. */91 const sections = (file: string) => {92 if (!file.startsWith(OPEN)) {93 return Option.none();94 }9 unmodified lines104 };105 106 const DESCRIPTION = "description: ";107 133-/**134- * The `description` a skill's frontmatter gives, quoted as `frontmatter`135- * writes it or plain as a hand-written skill may: none without the136- * frontmatter, or without a description in it. The skills index lists a137- * landed skill by it.138- */108 export const describedIn = (file: string): Option.Option<string> =>109 Option.flatMap(sections(file), ({ head }) =>110 Arr.findFirst(head.split("\n"), (line) =>111 line.startsWith(DESCRIPTION)3 unmodified lines115 Option.flatMap(valueOf)116 )117 );118 150-/**151- * What a file this platform manages says about itself: none for a file152- * without the frontmatter, or one someone else manages.153- */119 export const readManaged = (file: string): Option.Option<Managed> => {120 const split = sections(file);121 122 if (Option.isNone(split)) {16 unmodified lines139 ),140 });141 };142 178-/**179- * Whether the copy on disk differs from the file the current policy gives:180- * its body hashes to something other than what it records (edited by hand),181- * or what it records is not the current body's hash (generated from other182- * text). The landing alone never makes a copy stale: a landing that left183- * the text alone leaves the copy current. Some names the copy's own landing184- * and recorded hash. A copy without the frontmatter has no landing, and its185- * hash is the whole file's: it is current only when the current file has no186- * frontmatter either and the two are the same text, so a copy whose187- * frontmatter was taken off is stale.188- */143 export const isStale = (144 onDisk: string,145 current: GeneratedFile146 ): Effect.Effect<29 unmodified linesmodified:packages/agent-kit/src/hook-events.ts-12 removed
1-/**2- * The hook events the CLI answers: `<cli> hook <event> --json`. The hook3- * configs agent-kit generates call it with these names, and the4- * CLI's `hook` command parses the same ones.5- */1 import { Schema } from "effect";2 8-/** When a harness asks the gate's policy: at the session's start, before a tool runs, at Stop. */3 export const HookEvent = Schema.Literals([4 "session-start",5 "pre-tool-use",6 "stop",7 ]);8 9 export type HookEvent = typeof HookEvent.Type;10 17-/** The Claude Code hook event each one answers. */11 export const claudeEventOf = {12 "pre-tool-use": "PreToolUse",13 "session-start": "SessionStart",14 stop: "Stop",15 } as const satisfies Record<HookEvent, "SessionStart" | "PreToolUse" | "Stop">;16 24-/**25- * The tools whose use the `pre-tool-use` hook guards: every Claude Code tool26- * that writes a file. The generated hook config matches them, and the CLI's27- * hook decides on the same names.28- */17 export const guardedTools = [18 "Edit",19 "Write",20 "MultiEdit",2 unmodified linesmodified:packages/agent-kit/src/host-doc.ts+2 added-72 removed
1-/**2- * What an agent, or a person, reads first about a host, as plain Markdown3- * in the `llms.txt` shape (a title, a one-line summary, then sections of4- * links). `frontLlms` says what the platform is, how to install the CLI,5- * how to connect over MCP, how to find and take an ask, every command, and6- * which projects exist: the web serves it at `/llms.txt`, and the platform7- * at `/` for an agent, with no web app's pages named when it knows of none.8- * `projectLlms` is the web's `/<owner>/<name>/llms.txt`, with the project's open9- * asks, and `mcpCard` its `/.well-known/mcp.json`. With a web app,10- * `frontLlms` names `/llms-full.txt` (`full-llms.ts`), and `indexBanner`11- * sits under the title of every other Markdown answer the web serves, so a reader that lands12- * on one finds the rest.13- *14- * Pure: the hosts hand in what the platform lists and the CLI's commands15- * as this package's one list holds them, so no command is written here16- * by hand. A step names a command only when the catalog has it. Every17- * name comes from `Brand`.18- */1 import { Brand } from "@repo/brand";2 import type { AskListing } from "@repo/protocol/domain/ask";3 import type { ProjectListing } from "@repo/protocol/domain/front-page";4 import type { ProjectName } from "@repo/protocol/ids";6 unmodified lines11 type Command = CommandDoc;12 13 type Commands = readonly CommandDoc[];14 33-/** The MCP protocol the platform serves over HTTP. */15 export const MCP_PROTOCOL = "2026-07-28";16 36-/** Each posture as GLOSSARY.md names it. */17 const postureWords = {18 open: "Open",19 openCore: "Open core",20 openOnSchedule: "Open on schedule",5 unmodified lines26 27 const counted = (count: number, one: string) =>28 `${count} ${one}${count === 1 ? "" : "s"}`;29 50-/** The lines as one document, ending in a newline. */30 const page = (lines: readonly string[]) => `${lines.join("\n")}\n`;31 53-/** What a placeholder stands for in a command line, if the page knows it. */32 interface Known {33 readonly project?: string;34 }35 58-/** The command whose words are `words`, if the catalog has it. */36 const commandOf = (commands: Commands, words: string) =>37 Arr.findFirst(commands, ({ path }) => path.join(" ") === words);38 62-/**63- * A command as typed: the CLI's name, its words, its arguments, then64- * `flags` it takes, each with a value the page knows or a placeholder.65- */39 const usage = (40 command: Command,41 known: Known = {},42 flags: readonly ("ask" | "project")[] = []12 unmodified lines55 ),56 ].join(" ");57 };58 86-/** `words` as typed, with `flags`, when the catalog has the command. */59 export const typed = (60 commands: Commands,61 words: string,62 known: Known,2 unmodified lines65 Option.map(commandOf(commands, words), (command) =>66 code(usage(command, known, flags))67 );68 97-/** The sentence `make` writes around a typed command, or nothing without it. */69 export const withCommand = (70 command: Option.Option<string>,71 make: (typedCommand: string) => string72 ) => Option.toArray(Option.map(command, make));73 103-/**104- * How to take an ask, each step with the commands the catalog has: find,105- * read, claim, change and check, push and read the verdict. Numbered in106- * order, whatever steps the catalog leaves out.107- */74 const takeAnAsk = (commands: Commands, known: Known) => {75 const front = typed(commands, "front", known);76 const asks = typed(commands, "asks", known, ["project"]);77 35 unmodified lines113 "",114 ];115 };116 151-/** What a command row adds to its description. */117 const notes = ({ needsApproval, readOnly }: Command) => [118 ...(readOnly ? ["Only reads."] : []),119 ...(needsApproval ? [`Runs only with ${code("--yes")}.`] : []),120 ];121 157-/** Every command, one line each, in the catalog's order. */122 const commandList = (commands: Commands) => [123 "## Commands",124 "",125 ...commands.map(2 unmodified lines128 ),129 "",130 ];131 168-/** Where a project's page is on the web host. */132 const projectPage = (webUrl: string, project: string) => `${webUrl}/${project}`;133 171-/** What a project's line says of it: its posture and its open asks. */134 const projectFacts = (listing: ProjectListing) =>135 `${postureWords[listing.posture]}, ${counted(listing.openAsks, "open ask")}.`;136 175-/**176- * A project's line: a link to its Markdown on the web host, or, with no177- * web app, its clone URL on the platform.178- */137 const projectLine = (138 platformUrl: string,139 webUrl: Option.Option<string>,140 listing: ProjectListing4 unmodified lines145 onSome: (web) =>146 `- [${listing.project}](${projectPage(web, listing.project)}/llms.txt): ${projectFacts(listing)}`,147 });148 191-/**192- * The platform, the CLI, MCP, taking an ask, the commands and the193- * projects: the web's `/llms.txt`, and the platform's `/` for an agent.194- * Without `webUrl` it names only what the platform serves itself: the CLI195- * and the skills from the platform, each project by its clone URL, and no196- * page that only a web app serves.197- */149 export const frontLlms = (input: {150 readonly commands: Commands;151 readonly projects: readonly ProjectListing[];152 readonly platformUrl: string;153 readonly webUrl?: string;154 }) => {155 const { commands, platformUrl, projects } = input;156 const webUrl = Option.fromUndefinedOr(input.webUrl);206- // The CLI's downloads and the skills: the web forwards both to the platform.157 const served = Option.getOrElse(webUrl, () => platformUrl);158 159 return page([160 `# ${Brand.name}`,52 unmodified lines213 : projects.map((listing) => projectLine(platformUrl, webUrl, listing))),214 ]);215 };216 267-/** What an ask's line adds after its want: its kind and territory, then whether it can be taken. */217 const askNotes = (listing: AskListing) => [218 `Kind ${code(listing.kind)}, territory ${code(listing.territory)}.`,219 ...(listing.claimed ? ["Claimed."] : []),220 ...(listing.reserve === undefined ? [] : [`Held for ${listing.reserve}.`]),1 unmodified line222 ? []223 : [`Waits for ${listing.blockedBy.map(code).join(", ")}.`]),224 ];225 277-/** An ask's want as a sentence of its own, however it was punctuated. */226 const sentence = (text: string) => `${text.replace(/[.\s]+$/u, "")}.`;227 228 const askLine = (webUrl: string, project: string, listing: AskListing) =>229 `- [${listing.ask}](${projectPage(webUrl, project)}/asks/${listing.ask}.md): ${[sentence(listing.want), ...askNotes(listing)].join(" ")}`;230 283-/**284- * The line under the title of a Markdown answer the web serves: where the285- * index is, where the full text is, and, for a project's answer, the286- * project's own index. One blockquote, so a reader that lands on any page287- * finds the rest. It never comes first: an `llms.txt` opens with its `#`288- * heading.289- */231 export const indexBanner = (input: {232 readonly webUrl: string;233 readonly project?: ProjectName;234 }) => {1 unmodified line236 237 return `> For agents: the index is ${webUrl}/llms.txt, and everything beyond it (refusals, git, landings, events, guides) is ${webUrl}/llms-full.txt${project === undefined ? "" : `; this project's index is ${projectPage(webUrl, project)}/llms.txt`}.`;238 };239 299-/** `banner` under `text`'s `#` title, or on top of a text that has none. */240 export const underTitle = (text: string, banner: string) => {241 const end = text.indexOf("\n");242 243 return text.startsWith("# ") && end !== -1244 ? `${text.slice(0, end)}\n\n${banner}\n\n${text.slice(end).replace(/^\n+/u, "")}`245 : `${banner}\n\n${text}`;246 };247 308-/** `/<owner>/<name>/llms.txt`: the project, its posture, how to clone it, its open asks and how to take one. */248 export const projectLlms = (input: {249 readonly listing: ProjectListing;250 readonly asks: readonly AskListing[];251 readonly commands: Commands;23 unmodified lines275 ...takeAnAsk(commands, { project }).slice(0, -1),276 ]);277 };278 340-/**341- * `/<owner>/<name>/llms.txt` for a project the platform does not list. A name342- * that could not be a project's is not repeated back.343- */279 export const missingProjectLlms = (input: {280 readonly project: Option.Option<ProjectName>;281 readonly webUrl: string;282 }) =>5 unmodified lines288 onSome: (project) => `No project named ${code(project)}`,289 })} is on ${Brand.name}. Every project is listed at ${input.webUrl}/llms.txt.`,290 ]);291 357-/**358- * `/.well-known/mcp.json`: the platform's MCP endpoint, its transport and359- * protocol, and where a client learns to sign in. No settled standard says360- * this card's shape; it follows the MCP server card draft, and names its361- * authorization the way the platform's 401 does (RFC 9728's362- * `resource_metadata`).363- */292+// No settled standard gives this card's shape: it follows the MCP server card293+// draft, naming its authorization as RFC 9728's `resource_metadata`.294 export const mcpCard = (input: { readonly platformUrl: string }) => ({295 authentication: {296 required: true,297 resource_metadata: `${input.platformUrl}/.well-known/oauth-protected-resource`,10 unmodified linesmodified:packages/agent-kit/src/index.ts-6 removed
1-/**2- * Generated agent files from a project's policy: the contribute skill, the3- * AGENTS.md block, the harness plugins and their hooks, and the well-known4- * skills index. Each module is its own subpath too5- * (`@repo/agent-kit/hook-events`).6- */1 export { agentsBlock, upsertAgentsBlock } from "./agents-block.ts";2 3 export type { AgentsBlock } from "./agents-block.ts";4 30 unmodified linesmodified:packages/agent-kit/src/install.ts-5 removed
1-/**2- * The line that installs the CLI, from a web's origin (the web forwards the3- * CLI's downloads to the platform, as `llms.txt` says). One string, so every4- * page and document that gives it gives the same one.5- */1 export const installCommand = (webUrl: string) =>2 `curl -fsSL ${webUrl}/install.sh | sh`;modified:packages/agent-kit/src/llms-sections.ts-25 removed
1-/**2- * The sections of `/llms-full.txt` that the docs' reference shows too:3- * every refusal of the closed union, how git meets the platform, how a4- * landing happens (ADR 0014), and one line per event a watcher hears. Pure,5- * and every name comes from `Brand`. The refusals come from the union and6- * the events from a table the type holds to `ProjectEvent`, so a new tag7- * cannot be missing. Nothing here names a private repo, its files or its8- * readers (AGENTS.md principle 7): the gateway lines below are the ones9- * anyone outside one can meet.10- */1 import { Brand } from "@repo/brand";2 import type { ProjectEvent } from "@repo/protocol/domain/event";3 4 import { refusalCatalog } from "./refusals.ts";2 unmodified lines7 const cli = (...words: readonly string[]) => [Brand.cli, ...words].join(" ");8 9 const notesRef = `refs/notes/${Brand.slug}`;10 21-/** How an answer is pushed to a claim's fork: a function, so loading this module runs nothing. */11 export const pushAnswer = () => code(`git push ${Brand.slug} HEAD:main`);12 24-/** What the gateway says when git is not let in: `<reason>; sign in with <cli> login`. */13 const signIn = (reason: string) => `${reason}; sign in with ${cli("login")}`;14 27-// --- Refusals -----------------------------------------------------------------28-29-/** Every refusal of the closed union, with its group, retry, exit code, `next` and repair. */15 export const refusals = () => [16 "## Refusals",17 "",18 `Every refusal the platform gives, in every group of its closed union. Each has a \`_tag\`, \`retryable\` (whether trying the same thing again can help) and \`next\` (the command to run next), and no message: match on the tag. Git prints them on its \`remote:\` lines, ${code(cli("check"))} and ${code(cli("status"))} print them, an MCP tool returns them as JSON, and the verdict note holds them. The refusals about an answer's files arrive together, so one push hears about all of them.`,11 unmodified lines30 ),31 "",32 ];33 49-// --- Git here -------------------------------------------------------------------50-51-/** How git reaches the platform's repos, who reads and pushes each, and what it says when it refuses. */34 export const gitHere = (platformUrl: string) => [35 "## Git here",36 "",37 `Git reaches each repo at ${code(`${platformUrl}/<repo>.git`)} over smart HTTP and signs in with Basic auth. The password is your platform token, which ${code(cli("login"))} stores and hands to git through its credential helper. The username is an audit tag, ${code("audit;harness=<harness>")} (with ${code("&model=…")} and ${code("&session=…")} when the harness names them): it records which harness pushed and is never identity. The token alone says who you are.`,40 unmodified lines78 `- 404 ${code("not a git endpoint")}: the path is not one git asks for.`,79 "",80 ];81 100-// --- How a landing happens ----------------------------------------------------101-102-/** How a checked answer becomes a commit on `main`. */82 export const landing = () => [83 "## How a landing happens",84 "",85 "1. The platform checks the answer's merged tree: the ask's check and the project's lanes.",3 unmodified lines89 "5. A landing tried again finds its own commit on `main` by its `Request-Id` trailer and writes only what is missing, so it never makes a second commit.",90 "",91 ];92 114-// --- Events ---------------------------------------------------------------------115-116-/** What each event says happened, one line per tag of `ProjectEvent`. */93 const eventLines = {94 AskClosed: "An ask closed, with the landing that answered it.",95 AskOpened: "A new ask opened.",96 Claimed: "Someone claimed an ask.",10 unmodified lines107 Released: "A claim was released.",108 Warned: "A claim was warned that it lapses without a push.",109 } as const satisfies Record<ProjectEvent["_tag"], string>;110 135-/** One line per event a watcher of a project hears. */111 export const events = () => [112 "## Events",113 "",114 "A project's page follows its events as they happen (the `watch` contract). Each event carries `seq`, its place in the project's sequence, and `at`, its time; a watcher resumes after the last `seq` it saw.",4 unmodified linesmodified:packages/agent-kit/src/platform.ts+7 added-59 removed
1-/**2- * The platform's own skill and plugin: the platform's skill,3- * which the platform and the CLI serve as the MCP prompt `contribute`, the4- * Claude Code plugin with its three hooks, and the Agent Plugins bundle,5- * each as files at `skills/<slug>/` and `plugins/<slug>/`. The plugin is what6- * a person installs, so it is the only place executable hooks ship; a7- * project's own generated files are data.8- *9- * Both plugin manifests share one directory: Claude Code reads10- * `.claude-plugin/plugin.json`, `.mcp.json` and `hooks/hooks.json`, Agent11- * Plugins 1.0 reads `plugin.json` and `mcp.json`, and both read `skills/`.12- * No path is read by both, so neither manifest overrides the other.13- */1+// Claude Code reads `.claude-plugin/plugin.json`, `.mcp.json` and2+// `hooks/hooks.json`; Agent Plugins 1.0 reads `plugin.json` and `mcp.json`.3+// No path is read by both, so the two manifests share one directory.4 import { Brand } from "@repo/brand";5 import { Array as Arr, Effect, Option, Order } from "effect";6 7 import type { CommandDoc } from "./command-doc.ts";4 unmodified lines12 import { loopSteps, unfencedSection } from "./sections.ts";13 import { code, page, printJson, table } from "./text.ts";14 15 export interface PlatformInput {26- /** Every CLI command, as `commandDocs` lists them. */16 readonly commands: readonly CommandDoc[];28- /** The platform's origin, for its MCP endpoint; without it, MCP runs through the CLI. */17 readonly platformUrl?: string;18 }19 20 const SKILL = `skills/${Brand.slug}/SKILL.md`;21 22 const PLUGIN = `plugins/${Brand.slug}`;23 36-// --- The platform's skill ------------------------------------------------------37-24 const description = `Contribute to projects on ${Brand.name} with the \`${Brand.cli}\` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on ${Brand.name}, or when a push was refused with a refusal such as OutOfScope or StaleBase.`;25 26 const usage = ({ path, positional }: CommandDoc) =>27 code(56 unmodified lines84 ...refusalSection(),85 ...unfencedSection(),86 ]);87 102-/**103- * The platform's skill as the prompt `contribute` serves it: its name, its104- * description and its Markdown, made at once. The platform builds the105- * prompt where nothing may be awaited (its router, at module load), and106- * `SKILL.md`'s frontmatter hashes the body through WebCrypto, a promise.107- */88+// Synchronous: the platform builds the prompt at module load, where nothing89+// may be awaited, and `SKILL.md`'s hash is a WebCrypto promise.90 export const platformSkillParts = (input: PlatformInput) => ({91 body: platformBody(input),92 description,93 name: Brand.slug,1 unmodified line95 96 const skillFile = (input: PlatformInput) =>97 frontmatter({ ...platformSkillParts(input), landed: Option.none() });98 117-/** `skills/<slug>/SKILL.md`: the platform's skill, which comes from no landing. */99 export const platformSkill = (100 input: PlatformInput101 ): Effect.Effect<readonly GeneratedFile[]> =>102 skillFile(input).pipe(Effect.map((content) => [{ content, path: SKILL }]));103 123-// --- The MCP server, as each client's config names it ----------------------------124-125-/**126- * How each config spells the platform's MCP server: Claude Code's `.mcp.json`127- * (and VS Code's `servers`, the same entry), Agent Plugins 1.0's `mcp.json`,128- * and Cursor's `mcp.json`, whose remote entry is a bare `url` (its docs give129- * a `type` only for stdio).130- */104+// Cursor's remote entry is a bare `url`: its docs give a `type` only for stdio.105 const servers = {106 "agent-plugins": {107 remote: (url: string) => ({ type: "streamable-http", url }),108 stdio: { args: ["mcp"], command: Brand.cli, type: "stdio" },9 unmodified lines118 } as const;119 120 export type McpFlavour = keyof typeof servers;121 148-/**149- * The `mcpServers` object a client's config holds: the platform's `/mcp`150- * over HTTP, or `<cli> mcp` over stdio without a URL, under the brand's151- * slug. The plugin bundles and the Agents page (`agent-setup.ts`) both152- * build theirs here, so no client's snippet can drift from a bundle's.153- */122 export const mcpServersFor = (123 platformUrl: string | undefined,124 flavour: McpFlavour125 ) => ({2 unmodified lines128 ? servers[flavour].stdio129 : servers[flavour].remote(`${platformUrl}/mcp`),130 });131 164-// --- The Claude Code plugin ------------------------------------------------------165-132 const hookCommand = (event: HookEvent) => ({133 hooks: [{ command: `${Brand.cli} hook ${event} --json`, type: "command" }],134 });135 170-/**171- * `hooks/hooks.json`: before an edit, the scope guard; at the session's172- * start, the claimed ask's brief; at Stop, the verdict gate. Each runs173- * `<cli> hook <event> --json`, which fails open: hooks are early feedback,174- * and the gateway decides.175- */136+// Each hook fails open: hooks are early feedback, and the gateway decides.137 const hooksJson = () =>138 printJson({139 hooks: Object.fromEntries(140 HookEvent.literals.map((event) => [11 unmodified lines152 153 const homepage = (platformUrl: string | undefined) =>154 platformUrl === undefined ? {} : { homepage: platformUrl };155 195-/**196- * `plugins/<slug>/`: `.claude-plugin/plugin.json`, the platform's skill,197- * `.mcp.json` (the platform's `/mcp` over HTTP, or `<cli> mcp` without a198- * URL) and `hooks/hooks.json`.199- */156 export const claudePlugin = (157 input: PlatformInput158 ): Effect.Effect<readonly GeneratedFile[]> =>159 skillFile(input).pipe(16 unmodified lines176 { content: hooksJson(), path: `${PLUGIN}/hooks/hooks.json` },177 ])178 );179 224-// --- The Agent Plugins bundle ----------------------------------------------------225-180 const SCHEMAS = "https://agent-plugins.org/schemas/1.0.0";181 228-/**229- * `plugins/<slug>/plugin.json`, the same skill and `mcp.json`: the Agent230- * Plugins 1.0 package, whose manifests are closed (only `$schema` and the231- * listed fields) and carry no hooks, which that standard leaves to each232- * client.233- */182 export const agentPluginsBundle = (183 input: PlatformInput184 ): Effect.Effect<readonly GeneratedFile[]> =>185 skillFile(input).pipe(20 unmodified linesmodified:packages/agent-kit/src/project-skill.ts-19 removed
1-/**2- * A project's contribute skill: what a stranger's agent reads to answer one3- * of its asks, generated from the policy at a landing and nothing else. One4- * file, written to `.agents/skills/` and `.claude/skills/`, which between5- * them reach every harness that reads skills.6- */1 import { Brand } from "@repo/brand";2 import type { Policy } from "@repo/protocol/domain/policy";3 import { keyOf } from "@repo/protocol/ids";4 import type { LandedSha, ProjectName } from "@repo/protocol/ids";11 unmodified lines16 unfencedSection,17 } from "./sections.ts";18 import { code, page } from "./text.ts";19 26-/**27- * The skill's name: `<key>-contribute`, by the project's key28- * (`datekit-contribute`, `oscabriel__foo-contribute`), its folder's name too,29- * so the forty's skills keep their names and a name reads back to its30- * project (ADR 0032).31- */20 export const contributeSkillName = (project: ProjectName) =>21 `${keyOf(project)}-contribute`;22 35-/** Where the skill goes: the folders harnesses read project skills from, `.agents` first. */23 export const contributeSkillPaths = (project: ProjectName) => {24 const skill = `skills/${contributeSkillName(project)}/SKILL.md`;25 26 return [`.agents/${skill}`, `.claude/${skill}`] as const;27 };28 42-/** What the skill's frontmatter says it is for. */29 export const contributeDescription = (project: ProjectName) =>30 `Answer one of ${project}'s asks on ${Brand.name}: claim it, change only its territory, run \`${Brand.cli} check\`, push it to your fork, and read the verdict. Use when working on ${project}, or when a push to it was refused.`;31 46-/** The skill's body: the loop, then the rules from the policy, then what nothing checks yet. */32 export const contributeBody = (project: ProjectName, policy: Policy) =>33 page([34 `# Contribute to ${project}`,35 "",13 unmodified lines49 ...refusalSection(),50 ...unfencedSection(policy.agents),51 ]);52 68-/**69- * `.agents/skills/<key>-contribute/SKILL.md` and its `.claude/skills/`70- * copy, the same bytes, with frontmatter naming the landing it came from.71- */53 export const projectSkill = (input: {54 readonly project: ProjectName;55 readonly policy: Policy;56 readonly landed: LandedSha;11 unmodified linesmodified:packages/agent-kit/src/refusals.ts-29 removed
1-/**2- * The refusals an answer can meet, read from the closed union: each one's3- * tag, whether retrying can help and its `next` come from its schema, its4- * exit code from the CLI's (`exitCodeOfTag`), and what to do about it from5- * the table below, which the type holds to the union's groups (a refusal6- * added to one fails the typecheck until it has a line here).7- * `refusalCatalog` walks every group the same way, for `/llms-full.txt`,8- * with a second table for the refusals no answer meets.9- */1 import { Brand } from "@repo/brand";2 import { ExitCode, exitCodeOfTag, precedence } from "@repo/protocol/exit-code";3 import { groups } from "@repo/protocol/refusal";4 import { Exit, Predicate, SchemaAST } from "effect";5 6 import { code, table } from "./text.ts";7 17-/** The groups whose refusals an answer can meet, from claim to verdict. */8 const answerGroups = [9 "Push and claim",10 "Shape",11 "Merge",13 unmodified lines25 type AnswerTag = InstanceType<AnswerMember>["_tag"];26 27 type Tag = InstanceType<Member>["_tag"];28 39-/**40- * What to do on meeting it. A refusal whose `next` is set when it is raised41- * gives the command's form here, or what it names when no form fits.42- */29 interface Repair {30 readonly todo: string;31 readonly next?: string;32 readonly nextNames?: string;64 unmodified lines97 todo: "Take the marker out; a marker without a reason may get one after ` -- ` for a decider to weigh, but one a decider declined stays out; never raise a ratchet.",98 },99 } as const satisfies Record<AnswerTag, Repair>;100 115-/**116- * What to do on meeting a refusal no answer meets: at an ask's opening, a117- * maintainer's own push, a decision, a lookup, setup or the env.118- */101 const elsewhere = {102 DecisionClosed: {103 todo: "Nothing to decide: it was taken already, or expired to its default.",104 },72 unmodified lines177 ...repairOf,178 ...Object.entries(elsewhere),179 ]);180 199-/** A field's value when the constructor fills it in, as it does a fixed `next`. */181 const constructorDefault = (ast: SchemaAST.AST) => {182 const fill = ast.context?.constructorDefault;183 184 return fill !== undefined &&3 unmodified lines188 ? fill.value189 : undefined;190 };191 211-/** One refusal an answer can meet, as the skills list it. */192 export interface AnswerRefusal {193 readonly tag: string;194 readonly retryable: boolean;215- /** The code the CLI exits with when it meets this refusal. */195 readonly exitCode: ExitCode;217- /** Its `next`, in Markdown: the command as a code span, or what it names. */196 readonly next: string;197 readonly todo: string;198 }199 6 unmodified lines206 ? (repair?.nextNames ?? "")207 : code(repair.next);208 };209 232-/** One member's row, from its schema and the repair `repairTable` gives it. */210 const rowOf = (211 member: Member,212 repairTable: ReadonlyMap<string, Repair>213 ): AnswerRefusal => {9 unmodified lines223 todo: repair?.todo ?? "",224 };225 };226 250-/** Every refusal an answer can meet, in the union's order. */227 export const answerRefusals: readonly AnswerRefusal[] = groups228 .flatMap((group): readonly Member[] =>229 answerGroups.some((answer) => answer === group.name) ? group.members : []230 )231 .map((member) => rowOf(member, repairOf));232 257-/** One refusal of the closed union, with the group the union files it under. */233 export interface CatalogRow extends AnswerRefusal {234 readonly group: string;235 }236 262-/** Every refusal of the closed union, every group, in the union's order. */237 export const refusalCatalog = (): readonly CatalogRow[] =>238 groups.flatMap((group) =>239 group.members.map((member: Member) => ({240 ...rowOf(member, everyRepairOf),241 group: group.name,242 }))243 );244 271-/** What each code the CLI exits with tells its caller, in the order a caller reads them. */245 const exitMeanings = {246 [ExitCode.ok]: "It did what it was asked.",247 [ExitCode.failed]: "Something else went wrong; stderr says what.",248 [ExitCode.usage]:9 unmodified lines258 [ExitCode.noPerm]:259 "Refused: you may not do this until you sign in, or someone lets you in.",260 } as const satisfies Record<ExitCode, string>;261 289-/** The CLI's exit codes, as `/llms-full.txt` lists them. */262 export const exitCodeSection = () => [263 "## Exit codes",264 "",265 `${code(Brand.cli)} exits with a code from sysexits(3), so a script or an agent can tell what to do next without reading stderr. A refusal's code follows from its \`retryable\`: 75 when trying again can help, else the code for what has to change, as the Refusals table lists it. A command that meets several refusals at once exits with the first of ${precedence.map(String).join(", ")} among them.`,4 unmodified lines270 ),271 "",272 ];273 302-/** The refusals section every skill carries. */274 export const refusalSection = () => [275 "## Refusals",276 "",277 `Instead of landing an answer, the platform answers with refusals. Git prints them on its \`remote:\` lines, \`${cli("check")}\` and \`${cli("status")}\` print them, and the verdict note holds them as JSON. Each one has a \`_tag\`, \`retryable\` (whether trying the same thing again can help) and \`next\` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them. The CLI exits with a refusal's code: 75 when trying again can help, and 65, 66 or 77 when something has to change first.`,13 unmodified linesmodified:packages/agent-kit/src/sections.ts-33 removed
1-/**2- * The sections the contribute skill, the AGENTS.md block and the platform's3- * own skill are made of, each from the policy or the brand alone. None4- * names the landing, so a landing that leaves the policy's text alone5- * leaves every generated body, and its hash, as it was.6- */1 import { Brand } from "@repo/brand";2 import { RatchetMeasure } from "@repo/protocol/domain/check";3 import type { AskKind, CheckKind, ClaimRule } from "@repo/protocol/domain/kind";4 import type { Policy } from "@repo/protocol/domain/policy";8 unmodified lines13 const remote = Brand.slug;14 15 const notesRef = `refs/notes/${Brand.slug}`;16 23-// --- The loop ----------------------------------------------------------------24-25-/**26- * The five steps every answer takes: read and claim, work, check, push,27- * read the verdict. The same in every generated file, so an agent that read28- * one knows them all.29- */17 export const loopSteps = () => [18 `1. Read the ask, then claim it: ${cli("ask", "<ask>")}, then ${cli("claim", "<ask>")}. The claim prints your fork's remote; add it with ${code(`git remote add ${remote} <remote>`)}.`,19 "2. Work inside the ask's territory until its check passes.",20 `3. Run ${cli("check")}. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.`,8 unmodified lines29 { ms: 60_000, one: "minute" },30 { ms: 1000, one: "second" },31 ] as const;32 46-/** A span as a person says it: `2 hours`, `1 day`, `90 minutes`. */33 export const span = (ms: number) => {34 const unit = unitsOfTime.find((each) => ms % each.ms === 0) ?? unitsOfTime[4];35 36 const count = Math.round(ms / unit.ms);37 38 return `${count} ${unit.one}${count === 1 ? "" : "s"}`;39 };40 55-/** What the project's policy says about holding a claim. */41 export const claimTerms = (policy: Policy) =>42 `A claim stays alive only while you push to it: after ${span(policy.claims.warnAfterMs)} without a push it is warned, and after ${span(policy.claims.lapseAfterMs)} it lapses. You may hold ${policy.caps.claimsPerPerson} ${policy.caps.claimsPerPerson === 1 ? "claim" : "claims"} at once in this project.`;43 59-// --- What an answer may change -------------------------------------------------60-44 const byName = <A>(name: (item: A) => string) =>45 Order.mapInput(Order.String, name);46 47 const judgeLines = (judge: Policy["judge"]) => [20 unmodified lines68 (ratchet) =>69 `- ${code(ratchet.name)}${ratchet.territory === undefined ? "" : ` in ${code(ratchet.territory)}`}: ${measureOf(ratchet.measure)}`70 );71 89-/**90- * The territory rule, the public files rule, the judge closure, the91- * weakening markers and the ratchets: each held by a refusal the gate92- * gives, which the section names.93- */72 export const changeSection = (policy: Policy) => {73 const { judge, modules, ratchets, weakening } = policy;74 75 const publicFiles = modules.some(55 unmodified lines131 "",132 ];133 };134 157-// --- The run block -------------------------------------------------------------158-159-/** The run block's lanes, by name. */135 export const lanesOf = (run: RunBlock) =>136 Arr.sort(137 Object.entries(run.checks),138 byName(([lane]: readonly [string, string]) => lane)18 unmodified lines157 ),158 "",159 ];160 186-// --- Ask kinds -----------------------------------------------------------------187-161 const checkKindText = (kind: CheckKind, run: RunBlock) =>162 ({163 lintToZero:164 "a lint rule's findings in the territory go to zero; the ask names the rule and the command that counts them.",54 unmodified lines219 byName((kind: AskKind) => kind.name)220 ).flatMap((kind) => kindLines(kind, policy)),221 ];222 250-// --- No fence yet ----------------------------------------------------------------251-252-/**253- * Norms the generated files state that nothing checks yet, listed as such254- * rather than as rules. Without a project, the default `agents` policy.255- */223 export const unfencedNorms = (agents: Policy["agents"] = "trailer") => [224 "- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.",225 ...(agents === "none"226 ? []13 unmodified linesmodified:packages/agent-kit/src/text.ts-14 removed
1-/**2- * The few ways generated text is written: Markdown pages, code spans and3- * table cells that survive any command a project writes, and JSON with4- * sorted keys, so no byte depends on the order a value was built in.5- */1 import { Array as Arr, Order, Predicate } from "effect";2 import type { Schema } from "effect";3 9-/** A Markdown page: its lines joined, ending in exactly one newline. */4 export const page = (lines: readonly string[]) =>5 `${lines.join("\n").replace(/\n+$/u, "")}\n`;6 13-/**14- * A code span around any text: a command with a backtick in it gets a15- * longer fence, padded with spaces as Markdown asks.16- */7 export const code = (text: string) => {8 const runs = text.match(/`+/gu) ?? [];9 const longest = Math.max(0, ...runs.map((run) => run.length));10 const fence = "`".repeat(longest + 1);2 unmodified lines13 ? `${fence}${text}${fence}`14 : `${fence} ${text} ${fence}`;15 };16 27-/** A table cell: a pipe in it would end the cell. */17 export const cell = (text: string) => text.replaceAll("|", String.raw`\|`);18 30-/** A Markdown table: a header row, its rule, then one row per entry. */19 export const table = (20 header: readonly string[],21 rows: readonly (readonly string[])[]22 ) => [1 unmodified line24 `| ${header.map(() => "---").join(" | ")} |`,25 ...rows.map((row) => `| ${row.map(cell).join(" | ")} |`),26 ];27 40-/** Words joined as a sentence lists them: `a`, `a and b`, `a, b and c`. */28 export const listed = (words: readonly string[]) =>29 words.length < 230 ? words.join("")31 : `${words.slice(0, -1).join(", ")} and ${words.at(-1) ?? ""}`;25 unmodified lines57 58 return value;59 };60 74-/** JSON as the generators write it: sorted keys, two-space indents, a final newline. */61 export const printJson = (value: Schema.Json) =>62 `${JSON.stringify(sortKeys(value), null, 2)}\n`;modified:packages/agent-kit/src/well-known.ts-14 removed
1-/**2- * `/.well-known/agent-skills/index.json`: the skills index the `skills` CLI3- * reads (discovery schema 0.2.0), so `npx skills add <platform>` finds every4- * project's contribute skill. Each entry names a skill, says what it is for,5- * where its `SKILL.md` is served and the SHA-256 of that file's bytes.6- */1 import { Array as Arr, Effect, Order } from "effect";2 3 import { contentHash } from "./generated-file.ts";4 import type { GeneratedFile } from "./generated-file.ts";5 import { printJson } from "./text.ts";6 13-/** One skill the index lists: its file's text, to digest, and where it is served. */7 export interface SkillEntry {8 readonly name: string;9 readonly description: string;10 readonly url: string;1 unmodified line12 }13 14 const DISCOVERY = "https://schemas.agentskills.io/discovery/0.2.0/schema.json";15 23-/** The most characters an entry's description may have. */16 const DESCRIBED = 1024;17 18 const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });19 28-/**29- * A description cut to the limit with an ellipsis, whole characters only:30- * at most 1024 UTF-16 units, so at most 1024 characters however a reader31- * counts them.32- */20 const cut = (description: string) => {21 if (description.length <= DESCRIBED) {22 return description;23 }12 unmodified lines36 };37 38 const byName = Order.mapInput(Order.String, (entry: SkillEntry) => entry.name);39 53-/** The index, its entries sorted by name. Its path is served from the platform's root. */40 export const wellKnownSkills = (41 entries: readonly SkillEntry[]42 ): Effect.Effect<GeneratedFile> =>43 Effect.forEach(Arr.sort(entries, byName), (entry) =>15 unmodified linesmodified:packages/agent-kit/test/agent-setup.test.ts-11 removed
1-/**2- * The Agents page's one source: how each agent connects (remote MCP, MCP3- * over stdio, the CLI, text to paste, skills), each channel with when to4- * use it and the snippets to copy. A pure function of the CLI's commands5- * and the two hosts' URLs; the web draws it as `/agents` and serves it as6- * `/agents.md`, and its MCP JSON is the object the plugin bundles carry.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import { groups } from "@repo/protocol/refusal";39 unmodified lines44 const commands: readonly CommandDoc[] = [...someCommands, login, mcp];45 46 const channels = agentSetup({ commands, platformUrl, webUrl });47 55-/** The channel titled `title`; fails the test without one. */48 const channel = (from: readonly SetupChannel[], title: string) =>49 Option.getOrThrow(Arr.findFirst(from, (each) => each.title === title));50 59-/** The snippet labelled `label` in the channel titled `title`. */51 const snippet = (title: string, label: string) =>52 Option.getOrThrow(53 Arr.findFirst(channel(channels, title).snippets, (each) =>54 each.label.startsWith(label)55 )56 );57 67-/** A JSON object's text, decoded. */58 const parsed = Schema.decodeUnknownSync(59 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))60 );61 72-/** The `.mcp.json` the Claude Code plugin carries for the same platform. */62 const pluginMcpJson = claudePlugin({ commands, platformUrl }).pipe(63 Effect.map((files) =>64 Option.getOrThrow(65 Arr.findFirst(files, ({ path }) => path.endsWith("/.mcp.json"))207 unmodified linesmodified:packages/agent-kit/test/agents-block.test.ts-1 removed
27 unmodified lines28 body: "## Contributing\n\nOld text,\nover two lines.\n",29 end,30 };31 32-/** The block as it sits in a file. */32 const written = ({ begin, body }: typeof block) => `${begin}\n${body}${end}`;33 34 describe(upsertAgentsBlock, () => {35 it("inserts the block at the end of an AGENTS.md without one", () => {84 unmodified linesmodified:packages/agent-kit/test/command-doc.test.ts-5 removed
103 unmodified lines104 ]);105 });106 });107 108-/** Each row that calls `tag`, by its words and where it comes from. */108 const calling = (docs: readonly CommandDoc[], tag: string) =>109 docs.flatMap((doc) =>110 doc.contract === tag ? [`${doc.path.join(" ")} (${doc.source})`] : []111 );112 114-// The one list the platform's skill, the CLI's MCP prompt and the web's115-// `llms.txt` read: every command once, in the order a person scans for one.113 describe(commandDocs, () => {114 const docs = commandDocs(Contracts);115 const words = docs.map(({ path }) => path.join(" "));116 54 unmodified lines171 "ask open",172 ]);173 });174 178- // `init` and `env set` do local work around the contract they call, so179- // their hand-written rows stand for those contracts.175 it("gives a contract a hand-written command calls no row of its own", () => {176 expect(calling(docs, "initProject")).toStrictEqual(["init (local)"]);177 expect(calling(docs, "setEnv")).toStrictEqual(["env set (local)"]);178 });1 unmodified linemodified:packages/agent-kit/test/docs.test.ts-9 removed
1-/**2- * The docs: guides written for people, then a reference read from the3- * sources that define it (the CLI's commands, the refusal union, the4- * events, the MCP tools and the import plan's copy). Every command a page5- * names is one the CLI has, with flags it takes, and every link between6- * pages names a page that exists.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Contracts, Surfaces } from "@repo/protocol/contracts";4 import type { ProjectEvent } from "@repo/protocol/domain/event";19 unmodified lines24 onNone: () => "",25 onSome: ({ markdown }) => markdown,26 });27 35-/** Every code span and shell line in `markdown` that runs the CLI, as its words. */28 const cliSpans = (markdown: string) =>29 [30 ...[...markdown.matchAll(/`(?<span>[^`\n]+)`/gu)].map(31 (found) => found.groups?.span ?? ""4 unmodified lines36 ? [span.slice(Brand.cli.length + 1).split(/\s+/u)]37 : []38 );39 48-/** The catalog's command these words run: the longest path they start with. */40 const commandOf = (words: readonly string[]) =>41 commands42 .filter(({ path }) => path.every((word, at) => words[at] === word))43 .toSorted((a, b) => b.path.length - a.path.length)[0];182 unmodified linesmodified:packages/agent-kit/test/fixtures.ts+1 added-13 removed
1-/**2- * A datekit-shaped project at one landed commit: two ask kinds, three asks,3- * two modules and the run block `{test: "bun test {path}", checks: {lint,4- * types, unit}}`. Decoded with the domain's own schema, so a fixture the5- * domain would refuse throws here.6- */1 import { Brand } from "@repo/brand";2 import { CheckSpec } from "@repo/protocol/domain/check";3 import { Command } from "@repo/protocol/domain/common";4 import type { AskKind } from "@repo/protocol/domain/kind";6 unmodified lines11 export const project = ProjectName.make("oscabriel/datekit");12 13 export const landed = LandedSha.make("a".repeat(40));14 21-/** A later landing, for a copy generated before it. */15 export const later = LandedSha.make("b".repeat(40));16 17 const encodeCheck = Schema.encodeSync(CheckSpec);18 121 unmodified lines140 };141 142 export const policy = Schema.decodeSync(Policy)(encoded);143 151-/** The same project after a landing that changed one lane of its run block. */144 export const policyWithNewLint = Schema.decodeSync(Policy)({145 ...encoded,146 run: {147 ...encoded.run,148 checks: { ...encoded.run.checks, lint: "bunx oxlint --deny-warnings" },149 },150 });151 160-/**161- * A few CLI commands as the generators take them: hand-written here, so a162- * contract's wording changing elsewhere leaves these golden files alone.163- */152+// Hand-written, so a contract's wording changing elsewhere leaves the golden files alone.153 export const commands: readonly CommandDoc[] = [154 {155 contract: "listAsks",156 flags: ["--project", "--json"],44 unmodified lines201 summary: "Run the gate's checks on your answer locally, before you push.",202 },203 ];204 216-/** Where the platform serves its routes in these tests. */205 export const platformUrl = `https://${Brand.domain}`;modified:packages/agent-kit/test/full-llms.test.ts-9 removed
1-/**2- * `/llms-full.txt`: what an agent needs beyond the index. `frontLlms`'3- * text, then every refusal of the closed union, how git meets the4- * platform, how a landing happens, every event a watcher hears, and the5- * guides for the moments an answer goes sideways. A pure function of the6- * CLI's commands, the listed projects and the two hosts' URLs.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import type { ProjectEvent } from "@repo/protocol/domain/event";11 unmodified lines16 const platformUrl = "https://platform-test.example.workers.dev";17 18 const webUrl = "https://web-test.example.workers.dev";19 27-/** A command row as the command list holds it. */20 const row = (21 path: readonly [string, ...string[]],22 summary: string,23 more: Partial<CommandDoc> = {}69 unmodified lines93 const text = fullLlms(input);94 95 const lines = text.split("\n");96 105-/** The lines of the section headed `## <title>`, up to the next `## `. */97 const section = (title: string) => {98 const start = lines.indexOf(`## ${title}`);99 const rest = lines.slice(start + 1);100 const end = rest.findIndex((line) => line.startsWith("## "));145 unmodified linesmodified:packages/agent-kit/test/generate.test.ts-7 removed
24 unmodified lines25 import { expectGolden, transcript } from "./golden.ts";26 27 const plugin = `plugins/${Brand.slug}`;28 29-/** The `name:` line of a file's frontmatter; none without one. */29 const frontmatterName = (content: string) =>30 Option.fromNullishOr(/^name: (?<name>.+)$/mu.exec(content)?.groups?.name);31 32 const skill = `${keyOf(project)}-contribute`;33 35-/** `sha256("hello\n")`, as every tool that hashes prints it. */34 const helloDigest =35 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";36 37 interface Case {40- /** Its golden file: `test/golden/<golden>.txt`. */38 readonly golden: string;39 readonly what: string;40 readonly paths: readonly string[];41 readonly run: Effect.Effect<readonly GeneratedFile[]>;100 unmodified lines142 const eventsOf = Schema.decodeUnknownSync(143 Schema.Struct({ hooks: Schema.Record(Schema.String, Schema.Unknown) })144 );145 149-/** A SKILL.md's frontmatter keys: top level, and under `metadata`. */146 const frontmatterKeys = (content: string) => {147 const [, head = ""] = content.split("---\n");148 const lines = head.split("\n");149 6 unmodified lines156 ),157 };158 };159 164-/** A Markdown file's body: everything after its frontmatter's closing line. */160 const bodyOf = (content: string) => {161 const close = content.indexOf("\n---\n", 3);162 163 return close === -1 ? content : content.slice(close + "\n---\n".length);164 };165 171-/** The hash a file's frontmatter records, read with a pattern of its own. */166 const recordedHash = (content: string) =>167 /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(content)?.groups168 ?.hash ?? "";169 176-/** The hook entry that runs `<cli> hook <event> --json`. */170 const hookCommand = (event: HookEvent) => [171 { command: `${Brand.cli} hook ${event} --json`, type: "command" },172 ];173 276 unmodified linesmodified:packages/agent-kit/test/golden.ts+2 added-18 removed
1-/**2- * Golden files for the generators: each generator's files in one3- * `test/golden/<name>.txt`, with the product's name as placeholders so no4- * golden file spells it (`brand:check`) and a renamed brand still matches.5- * A `content-hash` covers text that spells the name, so it changes with the6- * brand: the golden file holds `__HASH__` there, and the generator tests7- * hold each recorded hash to its body instead. `UPDATE_GOLDEN=1` rewrites8- * them; read the diff before committing it.9- */1+// Golden files hold the brand as placeholders (so `brand:check` passes) and2+// each content hash as `__HASH__`. `UPDATE_GOLDEN=1` rewrites them.3 import { expect } from "@effect/vitest";4 import { Brand } from "@repo/brand";5 import { Config, Effect, FileSystem } from "effect";6 12 unmodified lines19 const CLI = new RegExp(`(?<=^|[\`"])${escaped(Brand.cli)}(?= [a-z])`, "gmu");20 21 const SLUG = new RegExp(`(?<![A-Za-z])${escaped(Brand.slug)}(?![a-z])`, "gu");22 30-/** A golden file's text with its placeholders filled in from `Brand`. */23 export const branded = (golden: string) =>24 golden25 .replaceAll("__NAME__", Brand.name)26 .replaceAll("__CLI__", Brand.cli)2 unmodified lines29 // The hex of a frontmatter's `content-hash: "sha256:…"` or an AGENTS.md30 // marker's `content-hash: sha256:…`.31 const HASH = /(?<=content-hash: "?sha256:)[0-9a-f]{64}/gu;32 41-/** Generated text with each content hash as `__HASH__`. */33 const unhashed = (text: string) => text.replaceAll(HASH, "__HASH__");34 44-/** Generated text as a golden file holds it: the brand and hashes as placeholders. */35 const unbranded = (text: string) =>36 unhashed(text)37 .replaceAll(NAME, "__NAME__")38 .replaceAll(CLI, "__CLI__")39 .replaceAll(SLUG, "__SLUG__");40 51-/** Several files as one text: each under a `==> <path> <==` line. */41 export const transcript = (files: readonly GeneratedFile[]) =>42 files.map(({ content, path }) => `==> ${path} <==\n${content}`).join("\n");43 55-/**56- * Asserts that `actual`, with its content hashes as `__HASH__`, is57- * `test/golden/<name>.txt` with its brand placeholders filled in, byte for58- * byte. Under `UPDATE_GOLDEN=1` it writes the file.59- */44 export const expectGolden = (name: string, actual: string) =>45 Effect.gen(function* () {46 const fs = yield* FileSystem.FileSystem;47 const file = `${DIR}/${name}.txt`;23 unmodified linesmodified:packages/agent-kit/test/host-doc.test.ts-8 removed
1-/**2- * The host's own Markdown, `frontLlms`: what the web serves at `/llms.txt`3- * and the platform at `/` for an agent. A pure function of the CLI's4- * commands, the listed projects and the two hosts' URLs; with no web app5- * it points only at what the platform serves itself.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import type { ProjectListing } from "@repo/protocol/domain/front-page";12 unmodified lines17 const platformUrl = "https://platform-test.example.workers.dev";18 19 const webUrl = "https://web-test.example.workers.dev";20 27-/** A command row as the command list holds it. */21 const row = (22 path: readonly [string, ...string[]],23 summary: string,24 more: Partial<CommandDoc> = {}7 unmodified lines32 summary,33 ...more,34 });35 43-/** The web's own `llms.test.ts` catalog, so the golden file is its former output. */36 const commands: readonly CommandDoc[] = [37 row(38 ["ask"],39 "Show one ask in full, with its brief in Markdown for an answerer to read first.",180 unmodified linesmodified:packages/agent-kit/test/stale.test.ts-2 removed
15 unmodified lines16 policyWithNewLint,17 project,18 } from "./fixtures.ts";19 20-/** `sha256("hello\n")`, as every tool that hashes prints it. */20 const helloDigest =21 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";22 24-/** The hash a file's frontmatter records, read with a pattern of its own. */23 const recordedHash = (file: string) =>24 /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(file)?.groups25 ?.hash ?? "";26 244 unmodified linesmodified:packages/artifacts/src/repo-host/artifacts-api.ts+1 added-21 removed
1-/**2- * What the two adapters over Artifacts share, the Workers binding's3- * (`binding.ts`) and the REST API's (`rest.ts`): Artifacts' error codes and4- * their numbers, the codes an import refuses a source with, how a revision5- * is named, and the limits on a token's ttl and a log page. One table each,6- * so the two adapters can't drift apart.7- */1 import { Duration, Schema } from "effect";2 3 import { Revision } from "../repo-host.ts";4 12-/** Artifacts' names for its errors: `ArtifactsError.code` on the binding. */5 export const Code = Schema.Literals([6 "ALREADY_EXISTS",7 "NOT_FOUND",8 "CREATE_IN_PROGRESS",12 unmodified lines21 export type Code = typeof Code.Type;22 23 export const isCode = Schema.is(Code);24 33-/**34- * Each code by its number, from Artifacts' errors page: the REST API's35- * `errors[].code`, and the binding's `numericCode`. The page gives36- * `CREATE_IN_PROGRESS` no number.37- */25+/** Artifacts' errors page gives `CREATE_IN_PROGRESS` no number. */26 export const NUMBERED: ReadonlyMap<number, Code> = new Map<number, Code>([27 [10_100, "INVALID_INPUT"],28 [10_101, "INVALID_REPO_NAME"],29 [10_103, "INVALID_TTL"],7 unmodified lines37 [10_401, "UPSTREAM_UNAVAILABLE"],38 [10_402, "MEMORY_LIMIT"],39 ]);40 53-/**54- * The codes an import refuses its source with, as no repo to take: not git,55- * not public, not reachable, or too big.56- */41 export const NO_SOURCE = [42 "INVALID_INPUT",43 "INVALID_URL",44 "MEMORY_LIMIT",1 unmodified line46 "REMOTE_AUTH_REQUIRED",47 "UPSTREAM_UNAVAILABLE",48 ] as const satisfies readonly Code[];49 66-/** Artifacts' name for a revision: a short branch name or a commit id, never `refs/…`. */50 export const refOf = (at: Revision) =>51 Revision.$match(at, {52 Branch: ({ name }) => name,53 Commit: ({ sha }) => sha,54 });55 73-// Artifacts takes a token's ttl in whole seconds, from a minute to a year.56 const MIN_TTL_SECONDS = 60;57 58 const MAX_TTL_SECONDS = 31_536_000;59 78-/** A token's ttl as Artifacts takes it: whole seconds, clamped to a minute and a year. */60 export const secondsOf = (ttl: Duration.Duration) =>61 Math.min(62 Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),63 MAX_TTL_SECONDS64 );65 85-/** `log` reads at most this many commits per call. */66 export const LOG_PAGE = 1000;modified:packages/artifacts/src/repo-host/binding.ts+13 added-86 removed
1 /**2- * `RepoHost` over the Workers `Artifacts` binding: how the deployed platform3- * keeps its repos. The binding's surprises, found by probing it live, come back4- * typed:2+ * The binding's surprises, found by probing it live:3 *4 * - errors are read by `code`, and by message when there is none, as under5 * `wrangler dev` remote bindings;6 * - a fork that answers 500 is tried once more, and an already-exists or a7 * second 500 after that may be the fork the first made: it is, if it lists8 * `main`;9 * - reads name a branch by its short name and a commit by its id, never10 * `refs/…`, so `refs` and `push` go over git smart HTTP instead;13- * - a busy receive-pack is `HostBusy`;14- * - a call refused for Artifacts' rate limit (2,000 requests per 10 s per15- * repo) is asked again from 250 ms apart, doubling, at most four more16- * times; past that it fails as the call's own failure would.11+ * - a rate-limited call (2,000 requests per 10 s per repo) is retried.12 *18- * Refs and pushes use a token the adapter mints for the one call and revokes19- * after it; the token goes nowhere but the `Authorization` header of the20- * adapter's own requests. The day-long write token a create, a fork or an21- * import hands back is revoked at once: any write token can force-push22- * `main`, and no caller needs it. A repo still being23- * created is asked for again, from 250 ms apart, up to seven more times24- * (about 32 s); one still being imported up to sixteen (about 3 minutes),25- * each sleep at most 16 s. Every repo handle is disposed after use: after26- * each read, or, for reads in one `RepoSession`, once when the session27- * ends, so a view's many reads ask `get` for one handle.13+ * The write token a create, fork or import hands back is revoked at once:14+ * any write token can force-push `main`, and no caller needs it.15 */16 import {17 Data,18 DateTime,35 unmodified lines54 } from "./artifacts-api.ts";55 import type { Code } from "./artifacts-api.ts";56 import { listRefs, listTags, pushRefs } from "./smart-http.ts";57 71-/**72- * The codes a message names when the error carries none: Artifacts'73- * words, the fake's, and the code itself.74- */58 const MESSAGES = [59 [/not found/iu, "NOT_FOUND"],60 [/already exists/iu, "ALREADY_EXISTS"],61 [/fork[_ ]in[_ ]progress|still forking/iu, "FORK_IN_PROGRESS"],62 [/internal error/iu, "INTERNAL_ERROR"],63 ] as const satisfies readonly (readonly [RegExp, Code])[];64 82-/**83- * What a call to the binding threw, read once: its `code`, or the one its84- * message names when it has none, and the error itself as the cause.85- */65 class Thrown extends Data.TaggedError("Thrown")<{66 readonly code: Option.Option<Code>;67 readonly message: string;68 readonly error: unknown;69 }> {}70 92-/** A fork that answered `INTERNAL_ERROR`, which may still have made the repo. */71 class MaybeForked extends Data.TaggedError("MaybeForked")<{72 readonly thrown: Thrown;73 }> {}74 75 /**98- * How Artifacts words a refusal for its rate limit. ASSUMPTION: none has99- * been seen live and its error codes list none, so it is read from a code100- * or a message that names the limit, as an HTTP 429's "Too Many Requests"101- * does.76+ * ASSUMPTION: no rate-limit refusal has been seen live and its error codes77+ * list none, so it is read from a code or a message that names the limit.78 */79 const RATE_LIMITED = /rate[ _-]?limit|too[ _-]many[ _-]requests/iu;80 81 const isRateLimited = ({ error, message }: Thrown) =>1 unmodified line83 (Predicate.hasProperty(error, "code") &&84 Predicate.isString(error.code) &&85 RATE_LIMITED.test(error.code));86 111-/** From 250 ms apart, doubling, four more asks while the limit refuses. */87 const whileLimited = Schedule.exponential(Duration.millis(250)).pipe(88 Schedule.setInputType<Thrown>(),89 Schedule.while(90 ({ attempt: asked, input }) => asked <= 4 && isRateLimited(input)91 )92 );93 119-/**120- * A promise of the binding's, failing with what it threw, read; asked121- * again while Artifacts' rate limit refuses it.122- */94 const attempt = <A>(run: () => Promise<A>) =>95 Effect.tryPromise({96 catch: (error) => {97 const message = error instanceof Error ? error.message : String(error);14 unmodified lines112 (code: Code) =>113 (thrown: Thrown): boolean =>114 Option.contains(thrown.code, code);115 145-/**146- * An error the binding threw, as the port's: by `code` first, by message147- * when there is none. Anything else is a defect, with the error as its cause.148- */116 const fromArtifactsError = (117 name: RepoName,118 thrown: Thrown119 ): Effect.Effect<never, RepoNotFound | RepoExists | ForkInProgress> =>9 unmodified lines129 ),130 Match.orElse(({ error }) => Effect.die(error))131 );132 166-/** A call about the repo `name`, its errors read as the port's. */133 const call = <A>(name: RepoName, run: () => Promise<A>) =>134 attempt(run).pipe(135 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))136 );137 138 const asDefect = ({ error }: Thrown) => Effect.die(error);139 174-/** The port's reads and token calls fail only with `RepoNotFound`. */140 const onlyNotFound = <A, R>(141 effect: Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, R>142 ) =>143 effect.pipe(1 unmodified line145 );146 147 const main = RefName.make("refs/heads/main");148 184-/** How long a token minted for one call lives; it is revoked after the call. */149 const CALL_TOKEN_TTL = Duration.minutes(5);150 187-/** The codes `import` refuses a source with. */151 const IMPORT_REFUSALS: ReadonlySet<Code> = new Set(NO_SOURCE);152 153 const bytesOf = (blob: Blob) =>154 attempt(() => blob.arrayBuffer()).pipe(36 unmodified lines191 };192 })193 ).pipe(Effect.orDie);194 232-/**233- * How many times `get` is asked again while the repo is still being made:234- * a create about 32 s in all, and an import, which copies a whole history235- * and may outlast `import()` itself, about 3 minutes. Anything else is236- * never asked again.237- */195+/** An import copies a whole history and may outlast `import()` itself. */196 const asksWhileMaking = (thrown: Thrown) =>197 Match.value(thrown).pipe(198 Match.when(threw("CREATE_IN_PROGRESS"), () => 7),199 Match.when(threw("IMPORT_IN_PROGRESS"), () => 16),200 Match.orElse(() => 0)201 );202 245-/**246- * From 250 ms apart, doubling, each sleep at most 16 s: 250 ms … 16 s for a247- * create's seven asks (31.75 s), then 16 s apart for an import's nine more248- * (175.75 s in all).249- */203 const whileMaking = Schedule.min([204 Schedule.exponential(Duration.millis(250)),205 Schedule.spaced(Duration.seconds(16)),206 ]).pipe(207 Schedule.setInputType<Thrown>(),208 Schedule.while(({ attempt: asked, input }) => asked <= asksWhileMaking(input))209 );210 258-/** A handle to `name`, asked for again while the repo is still being made. */211 const handleOf = (binding: Artifacts, name: RepoName) =>212 attempt(() => binding.get(name)).pipe(213 Effect.retry(whileMaking),214 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))215 );216 265-/** Gives a handle back: the binding's handles are RPC stubs. */217+/** The binding's handles are RPC stubs, so each is disposed. */218 const disposeOf = (repo: ArtifactsRepo) =>219 Effect.sync(() => {220 repo[Symbol.dispose]();221 });222 271-/** `use` over a handle to `name`, disposed after, whatever `use` came to. */223 const withRepo = <A, E, R>(224 binding: Artifacts,225 name: RepoName,226 use: (repo: ArtifactsRepo) => Effect.Effect<A, E, R>4 unmodified lines231 )232 );233 234 /**284- * The repo `made` names, its initial write token revoked: nothing the285- * adapter's callers do needs it. A revoke that fails is logged, never the286- * call's failure: the repo was made, and the token went nowhere.235+ * The initial write token is revoked: no caller needs it. A failed revoke is236+ * logged, never the call's failure: the repo was made.237 */238 const withoutToken = (239 binding: Artifacts,240 made: { readonly remote: string; readonly token: string },10 unmodified lines251 ),252 Effect.as({ name, remote: made.remote })253 );254 305-/**306- * A token for one call, revoked when the scope closes, and the repo's307- * remote: what a smart-HTTP call to the repo needs.308- */255 const access = (name: RepoName, repo: ArtifactsRepo, scope: TokenScope) =>256 Effect.gen(function* () {257 const { remote } = yield* call(name, () => repo.info());258 13 unmodified lines272 return yield* listRefs(remote, token);273 })274 );275 330-/** The repo's tags over smart HTTP, peeled: the binding lists no refs. */276+/** Over smart HTTP: the binding lists no refs. */277 const tagsOf = (name: RepoName, repo: ArtifactsRepo) =>278 Effect.scoped(279 Effect.gen(function* () {280 const { remote, token } = yield* access(name, repo, "read");3 unmodified lines284 );285 286 /**287 * After a 500 and then an already-exists or a second 500, the fork may be342- * made: it is, if it lists `main`. Otherwise it is still being made, or343- * was undone; either way the caller tries again later.288+ * made: it is, if it lists `main`.289 */290 const confirmed = (binding: Artifacts, name: RepoName) =>291 withRepo(binding, name, (repo) =>292 Effect.gen(function* () {13 unmodified lines306 RepoNotFound: () => Effect.fail(new ForkInProgress({ name })),307 })308 );309 365-/**366- * One fork call. The base's absence names the base; any other refusal names367- * the target, and a 500 is `MaybeForked`, since it may have made the target.368- */310 const forkOnce = (binding: Artifacts, base: RepoName, name: RepoName) =>311 withRepo(binding, base, (repo) =>312 attempt(() => repo.fork(name)).pipe(313 Effect.catchTag("Thrown", (thrown) =>9 unmodified lines323 )324 )325 ).pipe(Effect.flatMap((made) => withoutToken(binding, made, name)));326 386-/**387- * Whether the repo holds `id` as a blob or a commit: `readBlob` answers388- * `null` for any other kind, and `readCommit` throws for a non-commit.389- */327+/** `readBlob` answers `null` for any other kind, and `readCommit` throws for a non-commit. */328 const blobOrCommit = (name: RepoName, repo: ArtifactsRepo, id: string) =>329 call(name, () => repo.readBlob(id)).pipe(330 Effect.flatMap((blob) =>331 blob === null15 unmodified lines347 attempt(() => repo.readTree(tree)).pipe(348 Effect.flatMap((found) =>349 found === null ? Effect.succeedNone : Effect.asSome(entriesOf(found))350 ),413- // A blob's or a commit's id names no tree, as on the other stores;414- // any other failure stays one.351 Effect.catchIf(threw("INTERNAL_ERROR"), ({ error }) =>352 blobOrCommit(name, repo, tree).pipe(353 Effect.flatMap((other) =>354 other ? Effect.succeedNone : Effect.die(error)96 unmodified lines451 // The service alone: the layer's whole context would carry its Scope, and452 // every call's finalizers would wait for the layer's end.453 const fetch = yield* Fetch;454 519- /**520- * A read of `name`'s, failing only with `RepoNotFound`: over the521- * session's handle to `name` when the read runs in a `RepoSession`,522- * else over a handle of its own.523- */455 const read = <A>(456 name: RepoName,457 use: (458 repo: ArtifactsRepo104 unmodified lines563 tags: (name) => read(name, (repo) => tagsOf(name, repo)),564 });565 });566 636-/**637- * Artifacts through the Workers binding, the platform's `RepoHost` in638- * production. Refs and pushes go over git smart HTTP through `Fetch`.639- */567 export const RepoHostBinding = {568 layer: (binding: Artifacts): Layer.Layer<RepoHost, never, Fetch> =>569 Layer.effect(RepoHost, make(binding)),570 };modified:packages/artifacts/src/repo-host/isogit-store.ts+2 added-27 removed
42 unmodified lines43 RepoName,44 RepoNotFound,45 } from "../repo-host.ts";46 47-/**48- * A bare repo's directory on a file system isomorphic-git reads and writes:49- * the shape a push takes its objects from, so every stored repo is a source50- * too.51- */47 export type GitDir = PushSource;48 54-/** A repo a store found by name: its directory and the lock its pushes take. */49 export interface StoredRepo {50 readonly dir: GitDir;51 readonly lock: Semaphore.Semaphore;52 }53 60-/** The ref every repo's HEAD names: Artifacts' default branch. */54 export const mainRef = "refs/heads/main";55 56 class GitFailure extends Data.TaggedError("GitFailure")<{57 readonly cause: unknown;1 unmodified line59 60 const git = <A>(run: () => Promise<A>) =>61 Effect.tryPromise({ catch: (cause) => new GitFailure({ cause }), try: run });62 70-/** `None` where isomorphic-git finds no such object, ref or file. */63 export const unlessMissing = <A>(64 run: () => Promise<A>65 ): Effect.Effect<Option.Option<A>> =>66 git(run).pipe(18 unmodified lines85 : Effect.die(`copying ${oid} produced ${written}`)86 )87 );88 97-/** A new, empty bare repo whose HEAD names `main`. */89 export const initBare = (repo: GitDir) =>90 git(() => init({ ...repo, bare: true, defaultBranch: "main" })).pipe(91 Effect.orDie92 );3 unmodified lines96 Effect.map(Option.map((sha) => CommitSha.make(sha)))97 );98 99 /**109- * The ref a remote's import takes when none is named: the branch its HEAD110- * names, or, when HEAD names a branch it lacks (a store made here names111- * `main`), its one branch, as a remote whose default is `master` has it.112- * Otherwise what HEAD names, even a branch it lacks; `None` only for a113- * detached HEAD.100+ * When HEAD names a branch the remote lacks (a store made here names `main`),101+ * its one branch, as a remote whose default is `master` has it.102 */103 export const defaultRefOf = (repo: GitDir) =>104 Effect.gen(function* () {105 const head = Option.filter(79 unmodified lines185 );186 yield* keep(oid, () => writeCommit({ ...into, commit }));187 });188 201-/**202- * A ref's target, objects first: an annotated tag after what it names203- * (a commit, or another tag), or else a commit and its history.204- */189 const copyTarget = (190 source: PushSource,191 into: GitDir,192 oid: string16 unmodified lines209 yield* copyTarget(source, into, tag.value.tag.object);210 yield* keep(oid, () => writeTag({ ...into, tag: tag.value.tag }));211 });212 229-/** Sets the new repo `into`'s `ref` to `source`'s `tip`, objects first. */213 export const seedRef = (214 source: PushSource,215 into: GitDir,216 ref: string,53 unmodified lines270 }))271 )272 );273 291-// isomorphic-git's entries carry `path` and `oid`; the port's, `name` and `sha`.274 const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));275 294-/**295- * The RepoHost methods that read a repo's objects and refs or push to it,296- * the same over every store whose repos are isomorphic-git directories:297- * `known` finds a repo's directory and lock by name. A push is a298- * compare-and-swap per ref under the repo's lock, never atomic across refs;299- * reads resolve short branch names and commit ids only.300- */276 export const objectsAndRefs = (277 known: (name: RepoName) => Effect.Effect<StoredRepo, RepoNotFound>278 ): Pick<279 RepoHost["Service"],133 unmodified linesmodified:packages/artifacts/src/repo-host/local.ts+5 added-37 removed
52 unmodified lines53 unlessMissing,54 } from "./isogit-store.ts";55 import type { GitDir } from "./isogit-store.ts";56 57-/** A promise from isomorphic-git or the file system that rejected. */57 class IoFailure extends Data.TaggedError("IoFailure")<{58 readonly cause: unknown;59 }> {}60 61 const io = <A>(run: () => Promise<A>) =>62 Effect.tryPromise({ catch: (cause) => new IoFailure({ cause }), try: run });63 65-/** Whether a file-system call failed with node's error `code`. */64 const failedWith = (code: "EEXIST" | "ENOENT") => (failure: IoFailure) =>65 failure.cause instanceof Error &&66 "code" in failure.cause &&67 failure.cause.code === code;68 71-/** Whether anything is at `path`. */69 const exists = (path: string) =>70 io(() => fs.promises.stat(path)).pipe(71 Effect.as(true),72 Effect.catchIf(failedWith("ENOENT"), () => Effect.succeed(false)),73 Effect.orDie74 );75 79-/** Deletes `path` and everything under it; whether there was anything. */76 const removeAll = (path: string) =>77 Effect.gen(function* () {78 const found = yield* exists(path);79 3 unmodified lines83 84 return found;85 });86 91-/** The remote an HTTP import fetches through, removed once it has. */87 const importRemote = "import";88 89 const branchOf = (ref: string) => ref.replace(/^refs\/heads\//u, "");90 96-/**97- * The tokens a repo has minted, kept beside its objects so that every layer98- * over the same root sees them. `minted` counts every token ever minted, so99- * no two get the same id.100- */91 const Tokens = Schema.fromJsonString(92 Schema.Struct({ live: Schema.Array(Schema.String), minted: Schema.Int })93 );94 22 unmodified lines117 ? Stream.fromAsyncIterable(body, (cause) => new IoFailure({ cause }))118 : Stream.fromIterable(body)119 ).pipe(Stream.runCollect, Effect.map(concat));120 131-/** One chunk as the async iterator isomorphic-git reads a response body from. */121 const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {122 const chunks = [bytes];123 124 const iterator: AsyncIterableIterator<Uint8Array> = {11 unmodified lines136 137 return iterator;138 };139 151-/**152- * isomorphic-git's HTTP client over a `Fetch`. isomorphic-git awaits a153- * promise, so each exchange runs as one; a `Fetch` failure rejects it as is.154- */140 const httpOver = (141 fetch: Fetch["Service"]["fetch"],142 context: Context.Context<never>143 ): HttpClient => ({26 unmodified lines170 })171 ),172 });173 189-/** Why a fetch from `url` brought nothing to import. */174 const fetchRefusal = (url: string, cause: unknown) =>175 Match.value(cause).pipe(176 Match.when(Schema.is(FetchFailed), (failed) => failed.reason),177 Match.when(Match.instanceOf(Error), (thrown) => thrown.message),39 unmodified lines217 218 return lock;219 });220 237- /** The repo's directory and lock, if the repo exists. */221 const known = (name: RepoName) =>222 Effect.gen(function* () {223 const dir = dirOf(name);224 3 unmodified lines228 229 return { dir, lock: yield* lockOf(name) };230 });231 249- /** A new, empty bare repo; making its directory is what claims the name. */232+ /** Making its directory is what claims the name. */233 const open = (name: RepoName) =>234 Effect.gen(function* () {235 const dir = dirOf(name);236 11 unmodified lines248 249 return dir;250 });251 269- /** A new repo `name` holding `source`'s `ref` at `tip`, copied as it stands. */252 const seed = (253 name: RepoName,254 source: PushSource,255 ref: string,4 unmodified lines260 261 return createdOf(name);262 });263 282- // Local disk's test-only meaning of a public remote: a bare repo on this283- // machine, copied object by object. Without a branch, it takes the one284- // the repo's HEAD names.264+ // Test-only meaning of a public remote: a bare repo on this machine.265 const importFile = (266 name: RepoName,267 url: string,268 branch: BranchName | undefined269 ) =>270 Effect.gen(function* () {271 const noRepo = new ImportRefused({ name, reason: `no repo at ${url}` });272 293- // A file URL that names another host is no path on this machine.273 const gitdir = yield* Effect.try({274 catch: () => noRepo,275 try: () => fileURLToPath(url),276 });5 unmodified lines282 if (Option.isNone(head)) {283 return yield* noRepo;284 }285 307- // Without a branch, what HEAD names, or the one branch when HEAD308- // names none it has (`main` on a repo whose only branch is309- // `master`). A detached HEAD with several branches names none.286 const named =287 branch === undefined288 ? yield* defaultRefOf({ fs, gitdir })289 : Option.some(`refs/heads/${branch}`);18 unmodified lines308 309 return yield* seed(name, { fs, gitdir }, ref, tip);310 });311 336- /** One branch of a smart-HTTP remote, fetched into the empty repo `gitdir`. */312 const fetchInto = (313 name: RepoName,314 gitdir: string,315 url: string,43 unmodified lines359 360 yield* io(() => writeRef({ fs, gitdir, ref, value: tip })).pipe(361 Effect.orDie362 );388- // No repo here has remotes or remote-tracking refs.363 yield* io(() =>364 deleteRemote({ fs, gitdir, remote: importRemote })365 ).pipe(Effect.orDie);366 yield* removeAll(`${gitdir}/refs/remotes`);367 368 return createdOf(name);369 });370 397- // A public remote over smart HTTP, through the `Fetch` this layer was398- // given. A failed import leaves no repo behind.371+ // A failed import leaves no repo behind.372 const importHttp = (373 name: RepoName,374 url: string,375 branch: BranchName | undefined3 unmodified lines379 Effect.onError(() => removeAll(gitdir).pipe(Effect.asVoid))380 )381 );382 410- /** The repo's tokens file, read and rewritten under the repo's lock. */383 const updateTokens = <A>(384 name: RepoName,385 change: (tokens: Tokens) => Effect.Effect<readonly [A, Tokens]>386 ) =>115 unmodified lines502 });503 504 /**505 * Artifacts on local disk, for tests that need real git over HTTP and for the534- * CLI's dev mode: each repo a bare git repo `<root>/<name>.git` with default535- * branch `main`, kept across layers over the same root. A push is a536- * compare-and-swap per ref with no atomicity across refs, as probes found537- * Artifacts. `remote(name)` is `<remoteBase>/<name>.git`, so a test can serve538- * `root` with `git http-backend` under that base and drive real git at it.539- * Tokens are recorded, never checked.506+ * CLI's dev mode. Pushes are a compare-and-swap per ref with no atomicity507+ * across refs, as probes found Artifacts. Tokens are recorded, never checked.508 */509 export const RepoHostLocal = {510 layer: (options: {511 readonly root: string;4 unmodified linesmodified:packages/artifacts/src/repo-host/memory-fs.ts-6 removed
1-/**2- * An in-memory file system: the part of `fs.promises` that isomorphic-git3- * calls (`docs/fs.md` in isomorphic-git), with node's error codes.4- */5-1 type ReadOptions = string | { readonly encoding?: string } | undefined;2 3 interface Stats {4 readonly mode: number;163 unmodified lines168 ? Promise.resolve(stats("dir", 0))169 : failure("ENOENT", path);170 };171 177- /** Deletes a directory and everything under it; not part of `fs`. */172 const removeTree = (raw: string) => {173 const root = normalize(raw);174 175 const inside = (path: string) =>27 unmodified linesmodified:packages/artifacts/src/repo-host/memory.ts+1 added-10 removed
27 unmodified lines28 remote: remoteOf(name),29 });30 31 interface Repo extends StoredRepo {32- /** Token ids still live; the memory store authenticates nothing. */32+ /** The memory store authenticates nothing. */33 readonly tokens: Set<string>;34 }35 36-/**37- * Artifacts in memory, as probes found it: each repo a bare git directory, a push38- * a compare-and-swap per ref with no atomicity across refs, and reads that39- * resolve short branch names and commit ids only.40- */36 const make = () => {37 const fs = memoryFs();38 const repos = new Map<RepoName, Repo>();39 let minted = 0;23 unmodified lines63 64 return repo;65 });66 72- /** A new repo `name` holding `from`'s `ref` at `tip`, copied as it stands. */67 const seed = (68 from: Repo,69 name: RepoName,70 ref: string,37 unmodified lines108 reason: `no repo at ${source.url}`,109 });110 }111 118- // Without a branch, the remote's default: what its HEAD names, or119- // its one branch, as `master` is on a remote that has only that.112 const named =113 source.branch === undefined114 ? yield* defaultRefOf(from.dir)115 : Option.some(`refs/heads/${source.branch}`);52 unmodified lines168 known(name).pipe(Effect.map((repo) => repo.tokens.delete(id))),169 });170 };171 180-/** A fresh, empty store each time the layer is built. */172 export const RepoHostMemory = Layer.sync(RepoHost, make);modified:packages/artifacts/src/repo-host/rest.ts+15 added-108 removed
1 /**2- * `RepoHost` over the Artifacts REST API, with a Cloudflare API token: for3- * code that runs outside a Worker, such as infra scripts and the seed4- * script. It passes the contract the binding passes, and types the same5- * surprises:2+ * Over the REST API, as probes and the docs found it:3 *4 * - a fork names its target (`{name, default_branch_only: true}`), which8- * cf's `artifacts namespaces repos fork` cannot do (cf #180);9- * - a fork that answers 500 (code 10400) is tried once more, and an10- * already-exists or a second 500 after that may be the fork the first11- * made: it is, if it lists `main`, as on the binding;12- * - `refs` and `push` have no REST route, so they go over git smart HTTP to13- * the repo's `remote` (`smart-http.ts`), with a repo token this layer mints.5+ * cf's `artifacts namespaces repos fork` cannot do;6+ * - a fork that answers 500 (code 10400) may still have made the repo, as on7+ * the binding;8+ * - `refs` and `push` have no REST route, so they go over git smart HTTP;9+ * - a token id resolves through an eventually consistent index, so revoking10+ * it within about a second of its mint can be 404.11 *15- * Every route is under `<base>/accounts/<accountId>/artifacts/namespaces/16- * <namespace>` and carries the API token as `Authorization: Bearer`, and17- * nowhere else. Each was confirmed with `bun run ops -- schema artifacts18- * namespaces <command>` (cf 1.0.0-beta.12, read-only), and against19- * Artifacts' REST docs (developers.cloudflare.com/artifacts/api/rest-api),20- * which spell bodies in snake case where cf's flags use kebab case:21- *22- * | Port | Route | `<command>` | Body or query |23- * | --- | --- | --- | --- |24- * | `create` | `POST /repos` | `repos create` | `{name}` |25- * | `remote`, and whether a repo exists | `GET /repos/{name}` | `repos get` | |26- * | `remove` | `DELETE /repos/{name}` | `repos delete` | |27- * | `fork` | `POST /repos/{base}/fork` | `repos fork` | `{name, default_branch_only: true}`: the docs and the probes send `name`; cf's schema lacks it (cf #180) |28- * | `importFrom` | `POST /repos/{name}/import` | `repos import` | `{url, branch?}` |29- * | `mintToken`, and the git calls' tokens | `POST /tokens` | `tokens create` | `{repo, scope, ttl}` |30- * | `revokeToken` | `DELETE /tokens/{id}` | `tokens revoke` | |31- * | `readCommit` | `GET /repos/{name}/commit/{hash}` | `repos commits get` | |32- * | `readTree` | `GET /repos/{name}/tree/{hash}` | `repos trees get` | |33- * | `readBlob` | `GET /repos/{name}/blob/{hash}` | `repos blobs get` | raw bytes back |34- * | `readFile` | `GET /repos/{name}/file` | `repos files get` | `?ref&path`; raw bytes back |35- * | `log` | `GET /repos/{name}/log` | `repos logs get` | `?ref&limit&offset` |36- *37- * cf's schema gives no reply shapes. From the docs: every JSON reply, and38- * every refusal, is Cloudflare's v4 envelope, `{success, errors: [{code,39- * message}], messages, result}`; blob and file replies are raw bytes; create,40- * fork, import and a repo's info carry `remote`; a minted token is `{id,41- * plaintext, scope, expires_at}`; a repo still being imported or forked42- * answers 409 (cf's generated client declares 409 for a repo's info and a43- * token's mint too); errors carry Artifacts' numeric codes (its errors44- * page), which the binding's `numericCode` matches (workers-types), and probes45- * saw 10201 and 10400 live. A refusal that names no code at all, such as a46- * proxy's, is read by its status: 404 is not found, 5xx internal. One that47- * names only Cloudflare's own codes (7000, an unknown route) is a defect.48- * ASSUMPTIONs, for a live run to settle:49- *50- * - a commit is the binding's metadata, spelled in snake case51- * (`tree_hash`) as the API's other fields are, or in camel case as the52- * binding's; a tree's `result` is the binding's entries, and a log's is a53- * list of commit metadata;54- * - a 404 from a read is the object's absence once the repo is found to55- * exist, and a tree read at another kind of object fails as the binding's56- * does (500), so the adapter asks whether it is a blob or a commit;57- * - a log page may hold fewer commits than asked before the history ends58- * (a server cap), so only an empty page ends it.59- *60- * A token id resolves through an eventually consistent index, so revoking it61- * within about a second of its mint can be 404 (cf's help for `tokens62- * revoke`): a 404 for a token this layer minted less than two seconds ago is63- * tried once more when they have passed. Git calls share one token per repo64- * and scope, minted on first use, minted again near its expiry, and revoked65- * when the layer closes. The day-long write token create, fork and import66- * return is dropped, as the binding drops it.12+ * ASSUMPTIONs, for a live run to settle: a commit's fields are snake case or13+ * camel case; a 404 from a read is the object's absence once the repo exists;14+ * a tree read at another kind of object is 500; and a log page may hold fewer15+ * commits than asked, so only an empty page ends it.16 */17 import { CommitSha } from "@repo/protocol/ids";18 import {19 Data,35 unmodified lines55 } from "./artifacts-api.ts";56 import type { Code } from "./artifacts-api.ts";57 import { listRefs, listTags, pushRefs } from "./smart-http.ts";58 110-/** A refusal that names no code at all, such as a proxy's, read by status. */59 const byStatus = (status: number): Option.Option<Code> =>60 Match.value(status).pipe(61 Match.when(404, () => Option.some<Code>("NOT_FOUND")),62 Match.when(2 unmodified lines65 ),66 Match.orElse(() => Option.none())67 );68 121-/** A reply that was no success: its status, the code it names, its messages. */69 class Refused extends Data.TaggedError("Refused")<{70 readonly status: number;71 readonly code: Option.Option<Code>;72 readonly message: string;73 }> {}74 128-/** A fork that answered 500, which may still have made the repo. */75 class MaybeForked extends Data.TaggedError("MaybeForked")<{76 readonly refused: Refused;77 }> {}78 5 unmodified lines84 85 const decodeFailure = Schema.decodeOption(Failure);86 87 /**142- * A refused reply read: by the first code Artifacts names, or by its status143- * when it names no code at all. One that names only codes Artifacts does not144- * own, such as Cloudflare's 7000 for a route it does not know, reads as no145- * code, so a wrong route, account or namespace is a defect and never passes146- * for a missing repo or object.88+ * A reply naming only codes Artifacts does not own (Cloudflare's 7000 for an89+ * unknown route) reads as no code, so a wrong route, account or namespace is90+ * a defect and never passes for a missing repo or object.91 */92 const refusedBy = (status: number, text: string) => {93 const problems = Option.match(decodeFailure(text), {94 onNone: () => [],17 unmodified lines112 (...codes: readonly Code[]) =>113 (refused: Refused): boolean =>114 Option.exists(refused.code, (code) => codes.includes(code));115 172-/** Cloudflare's v4 envelope around a success's `result`. */116 const Envelope = <S extends Schema.Top>(result: S) =>117 Schema.fromJsonString(118 Schema.Struct({ result, success: Schema.Literal(true) })119 );96 unmodified lines216 textOf(response).pipe(217 Effect.flatMap((text) => Effect.fail(refusedBy(response.status, text)))218 );219 277-/** A success's envelope, decoded at the boundary, or what refused it. */220 const decoded =221 <A>(codec: Schema.Codec<A, string>) =>222 (response: Response) =>223 response.ok2 unmodified lines226 Effect.orDie227 )228 : refusal(response);229 288-/** A success's raw bytes, or what refused it. */230 const bytesOf = (response: Response) =>231 response.ok232 ? Effect.promise(() => response.arrayBuffer()).pipe(233 Effect.map((buffer) => new Uint8Array(buffer))4 unmodified lines238 response.ok ? Effect.void : refusal(response);239 240 const main = RefName.make("refs/heads/main");241 301-/** How long a token for git calls lives, and how near its expiry it is replaced. */242 const CALL_TOKEN_TTL = Duration.minutes(30);243 244 const CALL_TOKEN_MARGIN = Duration.minutes(5);245 306-/** How long a token id may be unknown to the index after its mint. */246 const REVOKE_LAG = Duration.seconds(2);247 309-/** A token this layer minted and has not revoked. */248 interface Token {249 readonly name: RepoName;250 readonly at: DateTime.Utc;313- /** Minted for the layer's own git calls, and revoked when it closes. */251 readonly forCalls: boolean;252 }253 317-/** What a git call to a repo needs: its remote, and a token. */254 interface Access {255 readonly name: RepoName;256 readonly remote: string;257 readonly token: Redacted.Redacted;12 unmodified lines270 "FORK_IN_PROGRESS",271 "IMPORT_IN_PROGRESS",272 ] as const satisfies readonly Code[];273 338-/** What a create or an import refuses a name with: one taken, or being made. */274 const TAKEN = [275 "ALREADY_EXISTS",276 ...BEING_MADE,277 ] as const satisfies readonly Code[];24 unmodified lines302 const access = yield* Ref.make<ReadonlyMap<string, Access>>(new Map());303 304 const authorization = () => `Bearer ${Redacted.value(options.token)}`;305 371- /** One request to the API; one that got no response is a defect. */306 const send = (request: Request) => fetch.fetch(request).pipe(Effect.orDie);307 308 const httpGet = (path: string) =>309 send(37 unmodified lines347 method: "POST",348 })349 );350 417- /** A repo's remote; a 409 there is a repo still being made. */351 const infoOf = (name: RepoName) =>352 httpGet(repoPath(name)).pipe(353 Effect.flatMap(decoded(Remote)),354 Effect.map(({ result }) => result.remote),12 unmodified lines367 368 const remoteOf = (name: RepoName) =>369 infoOf(name).pipe(Effect.catchTag("ForkInProgress", Effect.die));370 438- /**439- * A read whose 404 is the object's absence once the repo is found to440- * exist; any other refusal is a defect.441- */371 const optional = <A>(name: RepoName, read: Effect.Effect<A, Refused>) =>372 read.pipe(373 Effect.asSome,374 Effect.catchTag("Refused", (refused) =>60 unmodified lines435 is("NOT_FOUND")(refused) ? Effect.succeed(false) : Effect.die(refused)436 )437 );438 510- /**511- * Revokes the token `id`, once more when the index may not know it yet;512- * whether it was revoked. The layer forgets the token either way.513- */439 const revoke = (id: string) =>440 Effect.gen(function* () {441 const token = (yield* Ref.get(minted)).get(id);442 const revoked = yield* revokeOnce(id);19 unmodified lines462 463 return again;464 });465 541- /** The remote and token a git call to `name` uses, minted on first use. */466 const accessOf = (name: RepoName, scope: TokenScope) =>467 Effect.gen(function* () {468 const key = `${scope}:${name}`;469 const now = yield* DateTime.now;46 unmodified lines516 );517 518 /**519 * After a 500 and then an already-exists or a second 500, the fork may be596- * made: it is, if it lists `main`. Otherwise it is still being made,597- * or was undone; either way the caller tries again later.520+ * made: it is, if it lists `main`.521 */522 const confirmed = (name: RepoName) =>523 Effect.gen(function* () {524 const { remote, token } = yield* accessOf(name, "read");10 unmodified lines535 ),536 Effect.provideService(Fetch, fetch)537 );538 616- /**617- * One fork request. The base's absence names the base; any other refusal618- * names the target, and a 500 is `MaybeForked`, since it may have made it.619- */539 const forkOnce = (from: RepoName, name: RepoName) =>540 httpPost(`${repoPath(from)}/fork`, {541 default_branch_only: true,542 name,18 unmodified lines561 )562 )563 );564 646- /** Whether the repo holds `id` as a blob or a commit, as a tree read refused it. */565 const blobOrCommit = (name: RepoName, id: ObjectId) =>566 optional(567 name,568 httpGet(`${repoPath(name)}/blob/${id}`).pipe(Effect.flatMap(bytesOf))22 unmodified lines591 Match.value(refused).pipe(592 Match.when(is("NOT_FOUND"), () =>593 remoteOf(name).pipe(Effect.as(Option.none()))594 ),677- // A blob's or a commit's id names no tree, as on the other stores;678- // any other failure stays one.595 Match.when(is("INTERNAL_ERROR"), () =>596 blobOrCommit(name, tree).pipe(597 Effect.flatMap((other) =>598 other ? Effect.succeedNone : Effect.die(refused)4 unmodified lines603 )604 )605 );606 691- /** One page of a log; a ref that names nothing logs nothing, as the binding's. */607 const page = (name: RepoName, ref: string, offset: number, limit: number) =>608 httpGet(609 `${repoPath(name)}/log?${new URLSearchParams({610 limit: String(limit),147 unmodified lines758 ),759 });760 });761 847-/**848- * Artifacts over its REST API, for scripts: the same `RepoHost`849- * the platform reaches through the binding. The API token is the caller's850- * (scripts get it from `varlock run`), and goes only into the851- * `Authorization` header of requests to the API. Delete only repos the852- * caller made with it.853- */762 export const RepoHostRest = {763 layer: (options: {764 readonly accountId: string;765 readonly namespace: string;766 readonly token: Redacted.Redacted;859- /** Defaults to `https://api.cloudflare.com/client/v4`. */767 readonly base?: string;768 }): Layer.Layer<RepoHost, never, Fetch> =>769 Layer.effect(RepoHost, make(options)),770 };modified:packages/artifacts/src/repo-host/smart-http.ts+10 added-54 removed
1-/**2- * Git smart HTTP over the `Fetch` port, for adapters whose store serves git3- * at a remote URL with a bearer token: `/binding` and `/rest`. It takes a4- * `remote` (`…/<repo>.git`, Artifacts' shape) and a token, and nothing about5- * how either was got.6- *7- * The token goes only into the `Authorization` header of requests to the8- * remote's own origin; everywhere else it stays `Redacted`.1+// The token goes only into the `Authorization` header of requests to the2+// remote's own origin; everywhere else it stays `Redacted`.9- */3 import { CommitSha } from "@repo/protocol/ids";4 import {5 Data,6 Effect,32 unmodified lines39 RepoNotFound,40 } from "../repo-host.ts";41 import type { PushSource, RefUpdate, Tag } from "../repo-host.ts";42 50-/** What isomorphic-git or a response body threw, before it is read. */43 class GitFailure extends Data.TaggedError("GitFailure")<{44 readonly cause: unknown;45 }> {}46 20 unmodified lines67 const decodeRef = Schema.decodeUnknownOption(RefName);68 69 const decodeSha = Schema.decodeUnknownOption(CommitSha);70 79-/** The repo a remote names: its last path segment, less `.git`. */71 const repoOf = (remote: string) =>72 Option.match(73 decodeRepo(74 (URL.canParse(remote) ? new URL(remote).pathname : remote)29 unmodified lines104 ? Stream.fromAsyncIterable(body, (cause) => new GitFailure({ cause }))105 : Stream.fromIterable(body)106 ).pipe(Stream.runCollect, Effect.map(concat));107 117-/** One chunk as the async iterator isomorphic-git reads a response body from. */108 const once = (bytes: Uint8Array): AsyncIterableIterator<Uint8Array> => {109 const chunks = [bytes];110 111 const iterator: AsyncIterableIterator<Uint8Array> = {11 unmodified lines123 124 return iterator;125 };126 137-/** The side-band 3 (fatal) messages in a reply's top-level packet lines. */127 const fatalMessages = (bytes: Uint8Array) => {128 const messages: string[] = [];129 const text = new TextDecoder();130 let at = 0;4 unmodified lines135 if (Number.isNaN(length)) {136 break;137 }138 150- // A flush (`0000`) or a delimiter carries no payload.139 if (length < 4) {140 at += 4;141 continue;142 }10 unmodified lines153 154 const isReceivePack = (url: string) =>155 new URL(url).pathname.endsWith("/git-receive-pack");156 169-/**170- * isomorphic-git's HTTP client over `Fetch`, for one repo. It adds the token171- * to requests to the remote's origin, and reads a 404 as `RepoNotFound` and a172- * busy receive-pack as `HostBusy`, failing the exchange with them, so the173- * promise isomorphic-git awaits rejects with the typed error itself.174- */157 const httpFor = (remote: string, token: Redacted.Redacted, name: RepoName) =>158 Effect.gen(function* () {159 const run = yield* FiberSet.makeRuntimePromise<Fetch>();160 const { origin } = new URL(remote);53 unmodified lines214 } satisfies HttpClient;215 });216 217 /**236- * Runs an isomorphic-git call. The typed errors the HTTP client failed with237- * come back as new values (isomorphic-git stamps a `caller` onto what it238- * rethrows); anything else it threw is a `GitFailure` for the caller to read.218+ * The typed errors come back as new values: isomorphic-git stamps a `caller`219+ * onto what it rethrows.220 */221 const git = <A>(run: (signal: AbortSignal) => Promise<A>) =>222 Effect.tryPromise({223 catch: (cause) =>7 unmodified lines231 ),232 try: run,233 });234 254-/** Every ref the remote lists, custom refs included; never `HEAD` or a peeled tag. */235 const refsAt = (remote: string, http: HttpClient) =>236 git(() => listServerRefs({ http, protocolVersion: 1, url: remote })).pipe(237 Effect.catchTags({238 GitFailure: ({ cause }) => Effect.die(cause),12 unmodified lines251 )252 )253 );254 275-/**276- * Every `refs/tags/*` the remote lists, each peeled to what it names: the277- * `^{}` line protocol v1 advertises after an annotated tag, else the tag's278- * own target.279- */255+/** Peeled by the `^{}` line protocol v1 advertises after an annotated tag, else the tag's own target. */256 const tagsAt = (remote: string, http: HttpClient) =>257 git(() =>258 listServerRefs({259 http,16 unmodified lines276 )277 )278 );279 304-/** Every tag the remote lists, peeled to its commit. */280 export const listTags = (281 remote: string,282 token: Redacted.Redacted283 ): Effect.Effect<readonly Tag[], RepoNotFound, Fetch> =>4 unmodified lines288 return yield* tagsAt(remote, yield* httpFor(remote, token, name));289 })290 );291 317-/**318- * Every ref the remote lists, as `ls-remote` lists them: what reads by name319- * cannot reach.320- */292 export const listRefs = (293 remote: string,294 token: Redacted.Redacted295 ): Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound, Fetch> =>7 unmodified lines303 304 const isMoved = (reason: string) =>305 MOVED.some((moved) => reason.includes(moved));306 336-/** Whether the store refused a push of `ref` because the ref moved. */307 const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>308 cause instanceof Errors.GitPushError &&309 isMoved(cause.data.result.refs[ref]?.error ?? "");310 311 /**342- * One ref's compare-and-swap. The push's own ref discovery is the check: if343- * the tip it finds is not `from`, the push stops there, before any pack is344- * built, so the old value the push names is the one checked, and the store345- * checks it again as it moves the ref. A ref that moved after the check is346- * `Stale` at the tip a fresh listing shows.347- *348- * The old value is the only check, as on every store: `to` need not descend349- * from `from` (Artifacts takes such an update). So isomorphic-git's350- * own fast-forward test is off (`force`), which also spares it walking the351- * history of `to` in a source that holds only the new objects.312+ * One ref's compare-and-swap: the push's own ref discovery is the check, so313+ * it stops before any pack is built if the tip is not `from`. `to` need not314+ * descend from `from` (Artifacts takes such an update), so isomorphic-git's315+ * fast-forward test is off (`force`).316 */317 const pushOne = (318 remote: string,319 http: HttpClient,62 unmodified lines382 return pushed;383 });384 385 /**422- * Pushes each update in order, one ref per push, since Artifacts has no423- * atomic push: each ref is updated or `Stale` on its own. Nothing is424- * retried; a `Stale` ref is the caller's to decide on. A busy store fails the386+ * One ref per push, since Artifacts has no atomic push. A busy store fails the387 * whole call with `HostBusy`, and refs before the busy one may have moved.388 */389 export const pushRefs = (input: {390 readonly remote: string;11 unmodified lines402 );403 })404 );405 444-/**445- * Fetches one ref of the remote into the repo `gitdir` in `fs` (made if446- * absent), `depth` commits deep when given; its tip, or `None` when the remote447- * has no such ref. The ref is a branch name or a full ref. The repo keeps the448- * objects and no ref, remote or tracking ref of the fetch's own.449- */406 export const fetchInto = (input: {407 readonly remote: string;408 readonly token: Redacted.Redacted;409 readonly fs: FsClient;65 unmodified linesmodified:packages/artifacts/src/fetch.ts-7 removed
1 import { Context, Schema } from "effect";2 import type { Effect } from "effect";3 4-/** An HTTP request that got no response: the network, DNS or TLS failed. */4 export class FetchFailed extends Schema.TaggedError<FetchFailed>()(5 "FetchFailed",6 { reason: Schema.String, url: Schema.String }7 ) {}8 10-/**11- * The one way a package makes an HTTP request, so none calls the global12- * `fetch`. A response of any status is a success; only a request that got no13- * response fails. The Worker's adapter wraps its `fetch`; tests serve an14- * in-process handler with `Fetch.of`.15- */9 export class Fetch extends Context.Service<10 Fetch,11 {12 readonly fetch: (request: Request) => Effect.Effect<Response, FetchFailed>;2 unmodified linesmodified:packages/artifacts/src/repo-host.ts+5 added-60 removed
10 unmodified lines11 } from "effect";12 import type { Array, DateTime, Duration, Redacted } from "effect";13 import type { FsClient } from "isomorphic-git";14 15-/** A repo's name in its namespace: the one `RepoName`, from the domain. */15 export { RepoName } from "@repo/protocol/ids";16 18-/** A short branch name such as `main` or `feature/x`, never `refs/…`. */17 export const BranchName = Schema.String.pipe(18 Schema.check(19 Schema.isPattern(20 /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u3 unmodified lines24 );25 26 export type BranchName = typeof BranchName.Type;27 30-/**31- * A full ref name: `refs/heads/main`, `refs/asked/landed`, `refs/notes/commits`,32- * `refs/tags/@changesets/cli@2.27.1` (a scoped package's tag; `@` and `+`33- * are git's as well).34- */28 export const RefName = Schema.String.pipe(29 Schema.check(30 Schema.isPattern(31 /^refs\/(?!.*\.\.)[A-Za-z0-9._@+-]+(?:\/[A-Za-z0-9._@+-]+)+$/u3 unmodified lines35 );36 37 export type RefName = typeof RefName.Type;38 46-/** A git object id: 40 lowercase hex digits. */39 export const ObjectId = Schema.String.pipe(40 Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),41 Schema.brand("ObjectId")42 );43 44 export type ObjectId = typeof ObjectId.Type;45 54-/**55- * One immediate child of a git tree, as `git ls-tree` lists it: `040000` and56- * `tree` for a folder, `160000` and `commit` for a submodule.57- */46 export const TreeEntry = Schema.Struct({47 mode: Schema.Literals(["100644", "100755", "120000", "040000", "160000"]),48 name: Schema.NonEmptyString,49 sha: ObjectId,1 unmodified line51 });52 53 export type TreeEntry = typeof TreeEntry.Type;54 67-/**68- * Where a read starts. Artifacts' binding resolves short branch names and69- * commit ids only, so these are the only two kinds.70- */55+/** Artifacts' binding resolves short branch names and commit ids only. */56 export type Revision = Data.TaggedEnum<{57 Branch: { readonly name: BranchName };58 Commit: { readonly sha: CommitSha };59 }>;1 unmodified line61 export const Revision = Data.taggedEnum<Revision>();62 63 const Person = Schema.Struct({ email: Schema.String, name: Schema.String });64 80-/** A commit, with when it was written and when committed, in Unix seconds. */65 export const Commit = Schema.Struct({66 author: Person,67 authoredAt: Schema.Int,68 committedAt: Schema.Int,5 unmodified lines74 });75 76 export type Commit = typeof Commit.Type;77 94-/** One tag: its full ref, and the commit it names, peeled. */78 export interface Tag {79 readonly name: RefName;80 readonly sha: CommitSha;81 }11 unmodified lines93 readonly name: RepoName;94 readonly remote: string;95 }96 114-/** A local git repo, read through isomorphic-git, that a push takes objects from. */97 export interface PushSource {98 readonly fs: FsClient;99 readonly gitdir: string;100 }101 120-/**121- * One ref's compare-and-swap. `from` is the tip the pusher expects; `None`122- * means the ref must not exist yet.123- */102 export interface RefUpdate {103 readonly ref: RefName;104 readonly from: Option.Option<CommitSha>;105 readonly to: CommitSha;15 unmodified lines121 export class RepoExists extends Schema.TaggedError<RepoExists>()("RepoExists", {122 name: RepoName,123 }) {}124 147-/** Artifacts is still forking this repo; retry. */125 export class ForkInProgress extends Schema.TaggedError<ForkInProgress>()(126 "ForkInProgress",127 { name: RepoName }128 ) {}129 153-/** The store would not import from that remote: not git, not public, or not reachable. */130 export class ImportRefused extends Schema.TaggedError<ImportRefused>()(131 "ImportRefused",132 { name: RepoName, reason: Schema.String }133 ) {}134 159-/** The store refused a whole push while busy with another; retry. */135 export class HostBusy extends Schema.TaggedError<HostBusy>()("HostBusy", {136 name: RepoName,137 }) {}138 164-/**165- * The git store the platform keeps repos in. The only way to Artifacts: every166- * other package reaches it through this port.167- */139 export class RepoHost extends Context.Service<140 RepoHost,141 {142 readonly create: (name: RepoName) => Effect.Effect<RepoCreated, RepoExists>;172- /**173- * A new repo holding one branch of a public remote: `branch`, or the174- * remote's default branch, under its own name.175- */143 readonly importFrom: (144 name: RepoName,145 source: { readonly url: string; readonly branch?: BranchName }146 ) => Effect.Effect<RepoCreated, RepoExists | ImportRefused>;180- /** Forks the default branch only, as Artifacts does by default. */147 readonly fork: (148 base: RepoName,149 name: RepoName150 ) => Effect.Effect<RepoCreated, RepoNotFound | RepoExists | ForkInProgress>;6 unmodified lines157 readonly revokeToken: (158 name: RepoName,159 id: string160 ) => Effect.Effect<boolean, RepoNotFound>;195- /** The git URL that pushes and fetches go to. */161 readonly remote: (name: RepoName) => Effect.Effect<string, RepoNotFound>;162 readonly readFile: (163 name: RepoName,164 at: Revision,2 unmodified lines167 readonly readCommit: (168 name: RepoName,169 sha: CommitSha170 ) => Effect.Effect<Option.Option<Commit>, RepoNotFound>;206- /** A tree's immediate children by the tree's id; `None` when no tree has it. */171 readonly readTree: (172 name: RepoName,173 tree: ObjectId174 ) => Effect.Effect<Option.Option<readonly TreeEntry[]>, RepoNotFound>;211- /** A blob's bytes by its id; `None` when no blob has it. */175 readonly readBlob: (176 name: RepoName,177 blob: ObjectId178 ) => Effect.Effect<Option.Option<Uint8Array>, RepoNotFound>;3 unmodified lines182 at: Revision,183 limit: number,184 offset?: number185 ) => Effect.Effect<readonly Commit[], RepoNotFound>;223- /** Every ref, as `ls-remote` lists them, custom refs included. */186 readonly refs: (187 name: RepoName188 ) => Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound>;189 /**228- * Every `refs/tags/*`, each peeled to the commit it names: an annotated229- * tag's ref names a tag object, which `readCommit` cannot read.230- * `refs` keeps what git lists.190+ * Each tag peeled to its commit: an annotated tag's ref names a tag191+ * object, which `readCommit` cannot read.192 */193 readonly tags: (194 name: RepoName195 ) => Effect.Effect<readonly Tag[], RepoNotFound>;4 unmodified lines200 ) => Effect.Effect<readonly RefOutcome[], RepoNotFound | HostBusy>;201 }202 >()("artifacts/RepoHost") {}203 243-/**244- * What the reads of one session may share: a host keeps what it opens on a245- * repo (the binding's handle) under `key` until the session ends, rather246- * than opening and closing it for each read. One opening at a time, and247- * only a finished value is kept, so no read waits on another's opening248- * past its own session.249- */204 export interface RepoSessionApi {205 readonly hold: <A, E>(206 key: string,207 open: Effect.Effect<A, E, Scope.Scope>208 ) => Effect.Effect<A, E>;209 }210 211 /**258- * The session reads run in, if any. A `Context.Reference` whose default is259- * none, so each read opens and closes what it needs, as a host without a260- * session does. It lives in one request's context, never in an isolate's261- * state: a Worker whose client goes away is cancelled where it stands, so262- * nothing a request holds may outlive it.212+ * Lives in one request's context, never in isolate state: a Worker whose213+ * client goes away is cancelled where it stands, so nothing may outlive it.214 */215 export const RepoSession = Context.Reference<Option.Option<RepoSessionApi>>(216 "artifacts/RepoSession",217 { defaultValue: Option.none }218 );219 269-/**270- * `effect` with its reads in one session: what a host holds for them is271- * released when `effect` ends, whatever it came to. Inside a session272- * already, `effect` joins it, so a view whose parts each ask for a273- * session still reads over one handle.274- */220 export const inRepoSession = <A, E, R>(221 effect: Effect.Effect<A, E, R>222 ): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>223 Effect.scoped(36 unmodified linesmodified:packages/artifacts/test/binding-live.test.ts+4 added-19 removed
1 /**2- * The binding against live Artifacts. Opt-in, never in `verify`: it runs only3- * with `LIVE_ARTIFACTS=1` and `LIVE_ARTIFACTS_HARNESS` naming, by absolute4- * path, a harness module outside this repo (live-harness code lives5- * outside it). The harness exports `live()`, which resolves to2+ * Opt-in, never in `verify`: runs only with `LIVE_ARTIFACTS=1` and3+ * `LIVE_ARTIFACTS_HARNESS` naming, by absolute path, a harness module outside4+ * this repo. The harness exports `live()`, which resolves to5 *6 * ```ts7 * {8 * namespace: string; // a namespace this build made1 unmodified line10 * fetch: (request: Request) => Promise<Response>;11 * dispose: () => Promise<void>; // the proxy's12 * }13 * ```15- *16- * Every repo name gets a fresh prefix per test, since the contract suite uses17- * fixed names, and every repo a test made is deleted when it ends. It never18- * runs against the `witness` namespace.14 */15 import { describe } from "@effect/vitest";16 import { Data, Effect, FiberSet, Layer, Predicate, Schema } from "effect";17 18 import { Fetch, FetchFailed } from "../src/fetch.ts";19 import { RepoHostBinding } from "../src/repo-host/binding.ts";20 import { describeRepoHost } from "./repo-host-contract.ts";21 27-/** The namespace another project owns. */22 const FORBIDDEN = "witness";23 24 const harnessPath = process.env.LIVE_ARTIFACTS_HARNESS;25 14 unmodified lines40 (input): input is (request: Request) => Promise<Response> =>41 Predicate.isFunction(input)42 );43 50-/** What the harness's module exports. */44 const HarnessModule = Schema.Struct({ live: Start });45 53-/** What `live()` resolves to. */46 const Harness = Schema.Struct({47 binding: Schema.declare(48 (input): input is Artifacts =>49 Predicate.hasProperty(input, "get") && Predicate.isFunction(input.get)16 unmodified lines66 class HarnessFailed extends Data.TaggedError("HarnessFailed")<{67 readonly reason: string;68 }> {}69 78-/** The harness's `live()`, run once per test and disposed after it. */70 const harness = (path: string) =>71 Effect.acquireRelease(72 Effect.gen(function* () {73 const module = yield* Effect.tryPromise({8 unmodified lines82 }).pipe(Effect.orDie),83 ({ dispose }) => Effect.tryPromise(() => dispose()).pipe(Effect.ignore)84 );85 95-/** A fresh prefix: the suite's fixed names, unique to this test. */86 const freshPrefix = () =>87 `live-${crypto88 .getRandomValues(new Uint32Array(2))89 .reduce((text, word) => text + word.toString(36), "")}-`;90 101-/**102- * The live binding with every name prefixed, and every repo made through it103- * deleted when the scope closes. Each method is forwarded by name: a binding104- * and its handles are RPC stubs, whose methods a spread would not copy.105- */91+/** Each method is forwarded by name: RPC stubs' methods are not copied by a spread. */92 const prefixed = (binding: Artifacts) =>93 Effect.gen(function* () {94 const prefix = freshPrefix();95 const run = yield* FiberSet.makeRuntimePromise();44 unmodified lines140 list: (options) => binding.list(options),141 } satisfies Artifacts;142 });143 158-/** The live store's `Fetch`: the harness's fetch, failing as no response. */144 const fetchOver = (send: Harness["fetch"]) =>145 Fetch.of({146 fetch: (request) =>147 Effect.tryPromise({25 unmodified linesmodified:packages/artifacts/test/binding.test.ts+3 added-28 removed
49 unmodified lines50 const main = RefName.make("refs/heads/main");51 52 const landed = RefName.make("refs/asked/landed");53 54-/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */54 const remoteBase = "https://artifacts.test/git/projects";55 57-/** A packet-line holding one side-band 3 (fatal) message. */56 const fatal = (message: string) => {57 const payload = new TextEncoder().encode(`\u0003${message}`);58 const length = (payload.length + 4).toString(16).padStart(4, "0");59 60 return new Uint8Array([...new TextEncoder().encode(length), ...payload]);61 };62 65-/** Artifacts' whole reply to a push it is too busy for: no report, no flush. */63 const busyReply = () =>64 new Response(fatal("artifacts_git_receive_pack_busy\n"), {65 headers: { "content-type": "application/x-git-receive-pack-result" },66 });67 71-/** What one request to the store carried, as the test's `Fetch` saw it. */68 interface Seen {69 readonly url: string;70 readonly authorization: string | null;71 }72 77-/** What a test may do to the next receive-pack call before git sees it. */73 type Intercept = (request: Request) => Effect.Effect<Option.Option<Response>>;74 80-/**81- * The binding over a fake Artifacts on local disk: a `RepoHostLocal` in a82- * temporary directory, wrapped by testkit's fake binding, whose remotes a83- * `Fetch` serves with real `git http-backend` over the same directory.84- * Every handle the binding opens is counted, and every token it mints is85- * recorded, so a test can check both came back.86- */75 const world = (76 options: FakeOptions & {77 readonly wrap?: (host: HostLike) => HostLike;90- /** How many of the first `get`s answer that the repo is still being made, and how. */78 readonly making?: {79 readonly code: "CREATE_IN_PROGRESS" | "IMPORT_IN_PROGRESS";80 readonly gets: number;81 };124 unmodified lines206 });207 208 type World = Effect.Success<ReturnType<typeof world>>;209 223-/** A test body over a fresh world, with the binding's `RepoHost` in scope. */210 const within = <A, E>(211 body: (212 world: World213 ) => Effect.Effect<19 unmodified lines233 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),234 }235 );236 251-/** A repo `name` with one commit on `main`, and the client that made it. */237 const seeded = (name: RepoName) =>238 Effect.gen(function* () {239 const repos = yield* RepoHost;240 const client = yield* gitClient(memoryFs());102 unmodified lines343 }344 )345 );346 362- // One side-band 3 packet and no report.347 it.live("reads a busy receive-pack as HostBusy, and moves nothing", () =>348 within(({ intercept }) =>349 Effect.gen(function* () {350 const repos = yield* RepoHost;25 unmodified lines376 })377 )378 );379 396- // git's receive-pack checks the old value the push names.380 it.live(381 "reports a ref that moved during the push as Stale at its new tip",382 () =>383 within(({ intercept, store }) =>100 unmodified lines484 })485 )486 );487 505- // Artifacts' `readTree` throws `INTERNAL_ERROR` for an object that is no506- // tree; the other stores read no tree there.488 it.live("reads no tree at a blob's id or a commit's id", () =>489 within(490 () =>491 Effect.gen(function* () {159 unmodified lines651 ({ plaintext }) => authorization === `Bearer ${plaintext}`652 )653 )654 ).toBeTruthy();674- // Revoked already: a second revoke finds nothing.655 expect(revoked.every((again) => !again)).toBeTruthy();656 })657 )658 );159 unmodified lines818 );819 });820 821 /**842- * `effect` run to its end on the TestClock: the clock moves on by the843- * longest sleep the binding takes between asks while the effect runs, so844- * a wait of minutes passes at once, whatever real I/O it does between.822+ * Runs `effect` on the TestClock, moving the clock by the binding's longest823+ * sleep while it runs, so a wait of minutes passes at once.824 */825 const onTestClock = <A, E, R>(effect: Effect.Effect<A, E, R>) =>826 Effect.gen(function* () {827 const fiber = yield* Effect.forkChild(effect);5 unmodified lines833 834 return yield* Fiber.await(fiber);835 });836 858-/** How many tokens on `name` are still live, as the fake lists them. */837 const liveTokens = (fake: Artifacts, name: RepoName) =>838 Effect.acquireUseRelease(839 Effect.promise(() => fake.get(name)),840 (repo) =>11 unmodified lines852 853 describe("an import Artifacts is still copying", () => {854 const master = RefName.make("refs/heads/master");855 878- // A remote whose default branch is `master`, as anyhow's is: its HEAD879- // names `master`, and the import takes that branch under its own name.856 it.live(857 "imports a remote whose default branch is master without being told",858 () =>859 within(31 unmodified lines891 { defaultBranch: "master" }892 )893 );894 919- // Seven asks (about 32 s) were too few for a large import; the binding920- // now asks for about three minutes, so twelve busy answers pass.895+ // An import may be asked about for three minutes, so twelve busy answers pass.896 it.effect(897 "waits through twelve IMPORT_IN_PROGRESS answers, then revokes the import's token and reads it",898 () =>899 within(179 unmodified linesmodified:packages/artifacts/test/fake-rest.ts+4 added-60 removed
1 /**2- * An in-process fake of the Artifacts REST API over a `RepoHost` (in tests,3- * `RepoHostLocal`), for `/rest`'s tests. It serves the routes4- * `src/repo-host/rest.ts` lists, under5- * `<base>/accounts/<accountId>/artifacts/namespaces/<namespace>`, and answers6- * in Cloudflare's v4 envelope, `{success, errors: [{code, message}],7- * messages, result}`. A repo's `remote` is the host's, for a git server the8- * test runs there (`@repo/testkit/http-backend`).9- *10- * It keeps what Artifacts' REST docs and the probes say of the real API:11- *12- * - only `Authorization: Bearer <api token>` authenticates; anything else is13- * 401 (Cloudflare's code 10000);14- * - errors carry Artifacts' numeric codes (its errors page): 10200 not15- * found, 10201 already exists, 10303 fork in progress, 10100 invalid16- * input, 10103 invalid ttl, 10104 invalid url, 10400 internal;17- * - a fork names its target in the body, `{name, default_branch_only}`, a18- * field cf's schema lacks (cf #180); a body without `name` is refused;19- * - create, fork and import answer with the new repo's `remote` and a20- * day-long write token; a token's mint answers `{id, plaintext,21- * scope, expires_at}`; a delete answers 202;22- * - under load, a fork answers HTTP 500 with code 10400 after making the23- * repo, and a retry answers 409 with code 10201:24- * `{ forkFailures: n }`; `{ forkLost: true }` makes those forks make25- * nothing;26- * - revoking a token within about a second of its mint can be 404 (cf's27- * help for `tokens revoke`): `{ revokeLag: n }` makes the first `n`28- * revocations of each token 404;29- * - blobs and files are raw bytes; every other reply is JSON.30- *31- * And, as ASSUMPTIONs nobody has seen live, what the docs leave out:32- *33- * - commit metadata is the binding's, in snake case (`tree_hash`) as the34- * API's other fields are, or in camel case: `{ casing: "camel" }`;35- * - a tree or a log is the binding's list, as the envelope's `result`;36- * - a tree or a commit read at an object of another kind is 500 (10400), as37- * the binding throws `INTERNAL_ERROR` there;38- * - a ref is a short branch name or a commit id, as the binding's,39- * and a log at a ref that names nothing is 404.2+ * An in-process fake of the Artifacts REST API over a `RepoHost`. It keeps3+ * what Artifacts' REST docs and probes say of the real API; what the docs4+ * leave out (commit field casing, a wrong-kind read as 500, a log at a ref5+ * that names nothing as 404) is an ASSUMPTION nobody has seen live.6 */7 import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";8 import {9 Data,21 unmodified lines31 32 export interface FakeRestOptions {33 readonly accountId: string;34 readonly namespace: string;69- /** The API token it takes, as a bearer token. */35 readonly token: string;71- /** Defaults to `https://api.cloudflare.com/client/v4`. */36 readonly base?: string;73- /** How many fork calls answer 500 (code 10400), as under load. */37 readonly forkFailures?: number;75- /** Whether those forks make nothing; by default each makes the repo first. */38 readonly forkLost?: boolean;77- /** How commit metadata spells its fields; snake case by default. */39 readonly casing?: "camel" | "snake";79- /** How many revocations of each token answer 404 before one takes. */40 readonly revokeLag?: number;41 }42 83-/** Artifacts' error codes, from its errors page. */43 const Codes = {44 alreadyExists: 10_201,45 forkInProgress: 10_303,46 internal: 10_400,2 unmodified lines49 invalidUrl: 10_104,50 notFound: 10_200,51 } as const;52 94-/** Cloudflare's own codes for a bad API token and an unknown route. */53 const UNAUTHENTICATED = 10_000;54 55 const NO_ROUTE = 7000;56 21 unmodified lines78 79 const internal = () =>80 failed(500, Codes.internal, "An internal error occurred.");81 124-/** A reply decided before the host was asked: a refusal of the request itself. */82 class Answered extends Data.TaggedError("Answered")<{83 readonly response: Response;84 }> {}85 86 const invalid = (code: number, message: string) =>87 new Answered({ response: failed(400, code, message) });88 132-/** What a route's handler fails with: the host's errors, or a reply. */89 type Failure =90 | Answered91 | ForkInProgress92 | ImportRefused28 unmodified lines121 const decodeBranch = Schema.decodeUnknownOption(BranchName);122 123 const decodePath = Schema.decodeUnknownOption(RepoPath);124 169-/** A request's JSON body, decoded, or a 400. */125 const bodyOf = <A>(request: Request, codec: Schema.Codec<A, string>) =>126 Effect.promise(() => request.text()).pipe(127 Effect.flatMap(Schema.decodeEffect(codec)),128 Effect.mapError(() => invalid(Codes.invalidInput, "invalid request body"))10 unmodified lines139 Effect.fromOption(decodeObject(id)).pipe(140 Effect.mapError(() => invalid(Codes.invalidInput, `invalid hash: ${id}`))141 );142 188-/** A short branch name or a commit id; anything else names nothing. */143 const revisionOf = (ref: string): Option.Option<Revision> =>144 Option.match(decodeObject(ref), {145 onNone: () =>146 Option.map(decodeBranch(ref), (name) => Revision.Branch({ name })),14 unmodified lines161 Match.orElse(() => "blob")162 ),163 });164 211-/** Whether the repo holds `id` as an object of any kind. */165 const holds = (host: RepoHost["Service"], name: RepoName, id: ObjectId) =>166 Effect.all([167 host.readBlob(name, id),168 host.readTree(name, id),4 unmodified lines173 Option.isSome(blob) || Option.isSome(tree) || Option.isSome(commit)174 )175 );176 224-/** A repo's info, as `GET /repos/{name}` gives it. */177 const infoOf = (name: RepoName, remote: string) =>178 ok({179 created_at: "2026-10-07T00:00:00.000Z",180 default_branch: "main",6 unmodified lines187 source: null,188 updated_at: "2026-10-07T00:00:00.000Z",189 });190 239-/** Whose a token is, and how many more revocations of it miss. */191 interface Minted {192 readonly repo: RepoName;193 readonly misses: number;194 }195 245-/** A route's path parameters, the request, and its URL. */196 interface Call {197 readonly name: string;198 readonly id: string;199 readonly request: Request;1 unmodified line201 }202 203 type Handler = (call: Call) => Effect.Effect<Response, Failure>;204 255-/** The fake API over `host`: a handler for the test's `Fetch` to route to. */205 export const fakeRest = (206 host: RepoHost["Service"],207 options: FakeRestOptions208 ): Effect.Effect<(request: Request) => Effect.Effect<Response>> =>2 unmodified lines211 const prefix = `${apiBase}/accounts/${options.accountId}/artifacts/namespaces/${options.namespace}`;212 const forkFailures = yield* Ref.make(options.forkFailures ?? 0);213 const tokens = yield* Ref.make<ReadonlyMap<string, Minted>>(new Map());214 266- // The times the host read from the commit itself.215 const metadataOf = (commit: Commit) => {216 const fields = {217 author: commit.author,218 committer: commit.committer,36 unmodified lines255 scope,256 };257 });258 311- /** A new repo's reply, with its day-long write token. */259 const made = (name: RepoName, remote: string) =>260 mint(name, "write", DAY_SECONDS).pipe(261 Effect.map(({ plaintext }) => ({262 default_branch: "main",64 unmodified lines327 328 return ok(yield* made(name, remote));329 });330 384- /** A commit or a tree; another kind of object at the id is a 500. */331 const object =332 <A>(333 read: (334 name: RepoName,33 unmodified lines368 onSome: raw,369 });370 });371 426- /** A file at a ref that is a short branch name or a commit id. */372 const file: Handler = (call) =>373 Effect.gen(function* () {374 const name = yield* repoNamed(call.name);375 const at = revisionOf(call.url.searchParams.get("ref") ?? "");83 unmodified lines459 ["POST", /^\/tokens$/u, token],460 ["DELETE", /^\/tokens\/(?<id>[^/]+)$/u, revoke],461 ];462 518- /** The handler for a request, and the call it is given. */463 const routed = (request: Request) => {464 const url = new URL(request.url);465 const path = `${url.origin}${url.pathname}`;466 57 unmodified linesmodified:packages/artifacts/test/local.test.ts+1 added-7 removed
20 unmodified lines21 import { temporaryRoot } from "./temporary-root.ts";22 23 const main = RefName.make("refs/heads/main");24 25-/** No network: every request fails as an unreachable host's would. */25 const offline = Layer.succeed(26 Fetch,27 Fetch.of({28 fetch: (request) =>29 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),30 })31 );32 34-/** The store in `root`, whose remotes are its repos' own `file://` URLs. */33 const storeAt = (root: string) =>34 RepoHostLocal.layer({ remoteBase: `file://${root}`, root }).pipe(35 Layer.provide(offline)36 );37 40-/** A store in a new temporary directory, removed when the test ends. */38 const freshStore = Layer.unwrap(Effect.map(temporaryRoot, storeAt));39 43-/** Real `git http-backend` over `root` on a local port: its base URL. */40 const served = (root: string) =>41 Effect.gen(function* () {42 const spawner =43 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();29 unmodified lines73 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),74 });75 76 describe("bare repos on local disk", () => {81- // The issue's Check: what the adapter stores is a repo real git can clone82- // over smart HTTP, served by `git http-backend` from the same root.77+ // What the adapter stores is a repo real git can clone over smart HTTP.78 it.live(79 "serves a pushed file to a real git clone of its remote",80 () =>81 Effect.gen(function* () {139 unmodified lines221 expect(yield* repos.remove(name)).toBeFalsy();222 }).pipe(Effect.provide(freshStore))223 );224 230- // A file URL that names another machine is no path on this one.225 it.effect("refuses a file URL on another host, and makes no repo", () =>226 Effect.gen(function* () {227 const repos = yield* RepoHost;228 const name = RepoName.make("elsewhere");58 unmodified linesmodified:packages/artifacts/test/repo-host-contract.ts+1 added-22 removed
27 unmodified lines28 const path = RepoPath.make("src/a.ts");29 30 const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes);31 32-/** No object in any repo here has this id. */32 const absent = ObjectId.make("0".repeat(40));33 35-/** When a commit was written, and when committed: two different instants. */34 const authored = 1_700_000_000;35 36 const committed = 1_700_000_500;37 40-/** The test client's repo, which a push takes objects from. */38 type Source = Parameters<RepoHost["Service"]["push"]>[1];39 43-/**44- * A commit on `parent`'s tree written by hand, so its author and committer45- * times differ (the test client stamps both alike).46- */40+/** Written by hand, so its author and committer times differ (the test client stamps both alike). */41 const timedCommit = (source: Source, parent: CommitSha) =>42 Effect.gen(function* () {43 const { commit } = yield* Effect.promise(() =>44 readCommit({ ...source, oid: parent })24 unmodified lines69 70 return CommitSha.make(oid);71 });72 79-/** When a commit was written and committed, as a store read it. */73 const times = (commit: Commit) => ({74 authoredAt: commit.authoredAt,75 committedAt: commit.committedAt,76 });77 85-/** An annotated tag object naming `commit`; its id, as a push sends it. */78 const annotatedTag = (source: Source, name: string, commit: CommitSha) =>79 Effect.map(80 Effect.promise(() =>81 writeTag({15 unmodified lines97 // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.98 (oid) => CommitSha.make(oid)99 );100 109-/** What an adapter's run of the suite adds to the shared cases. */101 export interface RepoHostSuite {111- /**112- * The URL `importFrom` reads the repo `name` from, as this adapter's113- * stand-in for a public remote. Without one, the import cases don't run.114- */102 readonly importUrl?: (103 name: RepoName104 ) => Effect.Effect<string, never, RepoHost>;105 /**4 unmodified lines110 */111 readonly danglingHead?: boolean;112 }113 127-/**128- * What every RepoHost adapter must do, written against the port. `/memory`,129- * `/local`, `/binding` (over testkit's fake Artifacts on `/local`) and130- * `/rest` (over a fake REST API on `/local`) run it on every `verify`;131- * `binding-live.test.ts` runs it against live Artifacts when asked.132- */114 export const describeRepoHost = (115 adapter: string,116 host: Layer.Layer<RepoHost>,117 suite: RepoHostSuite = {}435 unmodified lines553 ]);554 }).pipe(Effect.provide(host))555 );556 576- // A fork shares what it inherited and nothing a sibling577- // adds later.557 it.effect("keeps each fork's own commits to itself", () =>558 Effect.gen(function* () {559 const repos = yield* RepoHost;560 const client = yield* gitClient(memoryFs());130 unmodified linesmodified:packages/artifacts/test/rest.test.ts-18 removed
46 unmodified lines47 const namespace = "projects-test";48 49 const api = `https://api.cloudflare.com/client/v4/accounts/${accountId}/artifacts/namespaces/${namespace}`;50 51-/** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */51 const remoteBase = `https://${accountId}.artifacts.test/git/${namespace}`;52 53 const apiToken = "cf-api-token-for-the-rest-tests";54 56-/** One request as the test's `Fetch` saw it, with its reply. */55 interface Seen {56 readonly method: string;57 readonly url: string;58 readonly headers: readonly (readonly [string, string])[];8 unmodified lines67 );68 69 const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));70 73-/** What a token's mint answered, as far as these tests read it. */71 const decodeMinted = Schema.decodeEffect(72 Schema.fromJsonString(73 Schema.Struct({74 result: Schema.Struct({ id: Schema.String, plaintext: Schema.String }),75 })76 )77 );78 82-/**83- * The REST adapter over a fake API on local disk: a `RepoHostLocal` in a84- * temporary directory, behind `fakeRest`, with its remotes served by real85- * `git http-backend` over the same directory. Every request and reply the86- * adapter's `Fetch` carries is recorded.87- */79 const world = (80 options: Omit<FakeRestOptions, "accountId" | "namespace" | "token"> = {}81 ) =>82 Effect.gen(function* () {72 unmodified lines155 });156 157 type World = Effect.Success<ReturnType<typeof world>>;158 168-/** The REST adapter over a `Fetch` that gives every request the same reply. */159 const answering = (reply: () => Response) =>160 RepoHostRest.layer({161 accountId,162 namespace,3 unmodified lines166 Layer.succeed(Fetch, Fetch.of({ fetch: () => Effect.sync(reply) }))167 )168 );169 180-/** A refusal in Cloudflare's v4 envelope. */170 const refused = (status: number, code: number, message: string) => () =>171 Response.json(172 { errors: [{ code, message }], messages: [], result: null, success: false },173 { status }174 );175 187-/** A test body over a fresh world, with the REST adapter's `RepoHost` in scope. */176 const within = <A, E>(177 body: (178 world: World179 ) => Effect.Effect<19 unmodified lines199 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),200 }201 );202 215-/** A repo `name` with one commit on `main`, and the client that made it. */203 const seeded = (name: RepoName) =>204 Effect.gen(function* () {205 const repos = yield* RepoHost;206 const client = yield* gitClient(memoryFs());8 unmodified lines215 216 return { client, first };217 });218 232-/** The requests to one REST route, by method and path under the namespace. */219 const requestsTo = (220 seen: Ref.Ref<readonly Seen[]>,221 method: string,222 path: string6 unmodified lines229 )230 )231 );232 247-/** A commit's tree, read from the client that wrote it. */233 const treeOf = (source: PushSource, oid: CommitSha) =>234 Effect.promise(() => readCommit({ ...source, oid })).pipe(235 Effect.map(({ commit }) => ObjectId.make(commit.tree))236 );421 unmodified lines658 { casing }659 )660 );661 677- // The binding throws `INTERNAL_ERROR` for a read of the wrong kind; the678- // fake's REST API answers 500 there (an ASSUMPTION), and the other stores679- // read no tree.662 it.live("reads no tree at a blob's id or a commit's id", () =>663 within(() =>664 Effect.gen(function* () {665 const repos = yield* RepoHost;17 unmodified linesmodified:packages/artifacts/test/revision.test.ts-1 removed
2 unmodified lines3 import { Schema } from "effect";4 5 import { BranchName, RepoName } from "../src/repo-host.ts";6 7-// One `RepoName` across the product: the port names repos with the domain's.7 describe("a repo name", () => {8 it("is the domain's RepoName", () => {9 expect(RepoName).toBe(Ids.RepoName);10 });16 unmodified linesmodified:packages/artifacts/test/temporary-root.ts-4 removed
1 import { NodeServices } from "@effect/platform-node";2 import { Effect, FileSystem } from "effect";3 4-/**5- * A new temporary directory for a store's root, removed with its contents6- * when the test's scope closes.7- */4 export const temporaryRoot = FileSystem.FileSystem.pipe(5 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "repo-host-" })),6 Effect.orDie,7 Effect.provide(NodeServices.layer)1 unmodified linemodified:packages/brand/src/index.ts-5 removed
1-/**2- * The product's name and every identifier made from it. Nothing outside this3- * package spells the name; `brand:check` holds that, and the acceptance script4- * renames the slug at random to prove it.5- */1 const slug = "myr";2 3 export const Brand = {4 cli: slug,12 unmodified linesmodified:packages/brand/src/leaks.ts-2 removed
5 unmodified lines6 }7 8 export interface BrandLeak {9 readonly path: string;10- /** 1-based; 0 when the path itself carries the name. */10 readonly line: number;11 readonly text: string;12 }13 46 unmodified lines60 61 return [...inPath, ...inContent];62 };63 65-/** Every place outside the brand package and prose that spells the name. */64 export const findLeaks = (files: Iterable<SourceFile>): readonly BrandLeak[] =>65 [...files].flatMap(leaksIn);modified:packages/brand/test/leaks.test.ts-2 removed
53 unmodified lines54 ])55 ).toStrictEqual([]);56 });57 58- // Nothing in the repo is written from the brand any more, so no folder59- // outside the brand package and prose may spell it.58 it("flags the name in a plugin's or a skill's JSON like any other file", () => {59 const content = `${Brand.cli} asks`;60 61 expect(86 unmodified linesmodified:packages/config/src/vitest.ts-1 removed
1 import { defineConfig } from "vitest/config";2 3-/** The one vitest setup every package uses: tests live in `test/`, run in Node. */3 export const preset = defineConfig({4 test: {5 include: ["test/**/*.test.ts"],6 },1 unmodified linemodified:packages/config/test/bootstrap.test.ts-7 removed
23 unmodified lines24 import { blankJsonc } from "../../../infra/jsonc.ts";25 import { resources, stages } from "../../../infra/stages.ts";26 import { repoRoot } from "./root.ts";27 28-/** A file under the repo root, as text. */28 const rootText = (file: string) =>29 Effect.gen(function* () {30 const fs = yield* FileSystem.FileSystem;31 const path = yield* Path.Path;32 33 return yield* fs.readFileString(path.join(yield* repoRoot, file));34 }).pipe(Effect.provide(NodeServices.layer));35 37-/** What this test reads of a stage's block in the platform's `wrangler.jsonc`. */36 const PlatformStage = Schema.Struct({37 artifacts: Schema.Array(38 Schema.Struct({ binding: Schema.String, namespace: Schema.String })39 ),27 unmodified lines67 name: Schema.String,68 })69 );70 73-/** `apps/<app>/wrangler.jsonc`, comments and trailing commas aside, decoded. */71 const wrangler = <S extends Schema.Top & { readonly DecodingServices: never }>(72 app: string,73 stage: S74 ) =>3 unmodified lines78 );79 80 const nothing: Existing = { d1: [], kv: [], namespaces: [], r2: [] };81 85-/** Every resource of `dev-oscabriel` and `demo` present, with ids. */82 const everything: Existing = {83 d1: [84 {85 id: "11111111-1111-4111-8111-111111111111",30 unmodified lines116 117 expect(platform.name).toBe("platform");118 expect(Object.keys(platform.env)).toStrictEqual([...stages]);119 124- // Each block as the table names it, and as wrangler.jsonc does.120 const named = stages.map((stage) => {121 const names = resources(stage);122 123 return {124 frontPage: names.frontPage,130- // The public namespace, then the private one the layers live in.125 namespaces: [names.projects, names.layers],126 onPush: [names.onPush, names.onPush],127 platform: names.platform,128 projects: [names.projects, names.projects],115 unmodified lines244 ]);245 });246 });247 254-/** The lines of `after` that differ from `before`'s, by line. */248 const changed = (before: string, after: string) => {249 const old = before.split("\n");250 251 return after329 unmodified linesmodified:packages/config/test/cartridge.test.ts+12 added-88 removed
1 /**2- * The visibility cartridge, read as data (README's cut line 5): its3- * paths exist, one marked line plugs it in, and nothing outside it reaches4- * into it, so removing it is a deletion. The cartridge is its manifest's5- * folders, the marked composition line (the line under the marker6- * comment, which goes with it), the two `@repo/visibility` dependency lines7- * and the `ARTIFACTS_PRIVATE` binding; everything else8- * depends only on the neutral ports (`@repo/project`'s `visibility-port.ts`9- * and `env-port.ts`, the platform's `layer-gate.ts`), whose defaults are10- * the platform without it.11- *12- * Imports are read from the source with comments and the insides of13- * strings, regexes and templates blanked, so an import spelled in a comment14- * or a string never counts, and every form does: static, `import type`,15- * re-exports and `import()`.2+ * The visibility cartridge is its manifest's folders, the marked composition3+ * line, the two `@repo/visibility` dependency lines and the4+ * `ARTIFACTS_PRIVATE` binding; everything else depends only on the neutral5+ * ports, whose defaults are the platform without it. Imports are read with6+ * comments and the insides of strings, regexes and templates blanked.7 */8 import { NodeServices } from "@effect/platform-node";9 import { describe, expect, it } from "@effect/vitest";10 import { Array, Effect, FileSystem, Option, Path, Schema } from "effect";11 import type { ChildProcessSpawner } from "effect/process";12 13 import { committable, readsAtOnce, repoRoot, textOf } from "./root.ts";14 24-/** The cartridge's folders, from the repo root; each ends with `/`, and each exists. */15 const MANIFEST = [16 "packages/visibility/",17 "packages/project/src/visibility/",18 "apps/platform/src/visibility/",19 "apps/platform/test/visibility/",20 ] as const;21 32-/**33- * Where tests of the cartridge's project side live: they go with it, so34- * they are its too, though none may be written yet.35- */22 const TEST_HOMES = ["packages/project/test/visibility/"] as const;23 38-/**39- * Tests outside its folders that run the cartridge's world as a process,40- * by its path rather than an import (the CLI's end-to-end `env set`:41- * apps never import apps), so no import reader sees them: they go42- * with it too.43- */24 const RUNS_ITS_WORLD = [25 "apps/cli/test/local/env-set-live.test.ts",46- // The seed's layer step, over the world the cartridge plugs into.26 "packages/config/test/seed-layer.test.ts",27 ] as const;28 50-/**51- * The examples' content that only a platform with the cartridge can seed:52- * datekit's maintainers layer. Without it the seed plans no layer.53- */29 const ITS_CONTENT = ["examples/datekit/layers/"] as const;30 31 /**57- * Every folder, and every file, that goes when the cartridge goes. Deleting58- * it also takes the lines that name it (deleting it in a scratch worktree59- * left verify green): the marked line in `cartridges.ts`; the two32+ * Every folder and file that goes when the cartridge goes. Deleting it also33+ * takes the lines that name it: the marked line in `cartridges.ts`; the two34 * `@repo/visibility` dependency lines; `ARTIFACTS_PRIVATE` and `MASTER_KEY`35 * in the platform's `wrangler.jsonc`, `.env.schema` and `platform.ts`, its62- * tests' fake env (`withPrivateNamespace` and its imports, and its use in63- * `serve-world.ts`), `bindings.test.ts`, `platform.test.ts` and64- * `env.test-d.ts`, then `bun run types`; the private namespace and65- * `MASTER_KEY` rows in `bootstrap.test.ts`; and datekit's three `Layer`66- * lines in `seed.test.ts`. Bootstrap still plans the stage's `layers-<s>`67- * namespace (`infra/stages.ts`), which nothing binds then.36+ * tests' fake env (`withPrivateNamespace` and its uses), `bindings.test.ts`,37+ * `platform.test.ts` and `env.test-d.ts`, then `bun run types`; the private38+ * namespace and `MASTER_KEY` rows in `bootstrap.test.ts`; and datekit's three39+ * `Layer` lines in `seed.test.ts`.40 */41 const CARTRIDGE = [42 ...MANIFEST,43 ...TEST_HOMES,44 ...RUNS_ITS_WORLD,45 ...ITS_CONTENT,46 ];47 76-/**77- * Where the line that plugs the cartridge in lives (`ports.ts` merges every78- * cartridge `cartridges.ts` names over the platform's ports), and the one79- * module it names.80- */48 const COMPOSITION = {49 file: "apps/platform/src/cartridges.ts",50 module: "./visibility/live.ts",51 };2 unmodified lines54 const MARKER = ["//", "cartridge:", "visibility"].join(" ");55 56 const PACKAGE = "@repo/visibility";57 91-/** The workspaces that depend on the package: the cartridge's implementations live in them. */58 const DEPENDENTS = [59 "apps/platform/package.json",60 "packages/project/package.json",61 ];62 97-/** The private namespace's binding, by its name, spelled so a search for it finds the allowed files below. */63+/** Spelled so a search for the binding's name finds only the allowed files below. */64 const BINDING = ["ARTIFACTS", "PRIVATE"].join("_");65 100-/**101- * The files outside the cartridge that may name the binding: the platform's102- * config, generated types and env decode, its tests' fake env and type103- * fences, principle 7's web fence, and these tests.104- */66 const NAMES_BINDING = new Set([67 "apps/platform/wrangler.jsonc",68 "apps/platform/worker-configuration.d.ts",69 "apps/platform/src/platform.ts",5 unmodified lines75 "packages/config/test/web-wiring.test.ts",76 "packages/config/test/cartridge.test.ts",77 ]);78 118-/** Prose and binary files: they wire nothing. */79 const NOT_WIRING = /\.(?:md|png|ico|svg|woff2?|ttf|otf|jpg|webp|gif|lockb)$/u;80 81 const isCartridge = (file: string) =>82 CARTRIDGE.some((folder) => file.startsWith(folder));83 84 const isSource = (file: string) => /\.tsx?$/u.test(file);85 126-// ------------------------------------------------------------ the repo127-128-/** Every committable file with its text, `filter` deciding which. */86 const filesWhere = (filter: (file: string) => boolean) =>87 Effect.flatMap(committable, (files) =>88 Effect.forEach(89 files.filter(filter),4 unmodified lines94 readsAtOnce95 )96 ).pipe(Effect.map(Array.getSomes));97 141-// --------------------------------------------------------- reading code142-143-/** Punctuation after which a `/` starts a regex rather than a division. */98 const BEFORE_REGEX = new Set("(,=:[!&|?{};+-*%<>~^");99 100 const KEYWORDS_BEFORE_REGEX = new Set([101 "await",15 unmodified lines117 const WORD = /[\w$]/u;118 119 const SPACE = /\s/u;120 167-/**168- * One pass over a file's source: `chars` ends with comments and the insides169- * of strings, regexes and templates blanked, keeping every offset.170- */121 interface Lexer {122 readonly chars: string[];123 readonly content: string;174- /** The brace depth outside each enclosing template's `${`, innermost last. */124 readonly outer: number[];176- /** Each string literal's contents, by the offset of its opening quote. */125 readonly strings: Map<number, string>;126 at: number;127 depth: number;128 inTemplate: boolean;181- /** The last code token read: a punctuation character or a word. */129 previous: string;130 }131 185-/** Blanks `[from, to)`, keeping line breaks. */132 const blank = (lexer: Lexer, from: number, to: number) => {133 for (let at = from; at < Math.min(to, lexer.chars.length); at += 1) {134 if (lexer.chars[at] !== "\n") {135 lexer.chars[at] = " ";136 }137 }138 };139 194-/** The offset of the `/` that closes the regex opening at `start`, or -1 when its line ends first. */140 const regexEnd = (content: string, start: number) => {141 let inClass = false;142 let at = start + 1;143 13 unmodified lines157 158 return -1;159 };160 216-/** A template's text, up to its closing backtick or its next `${`. */161 const templateText = (lexer: Lexer) => {162 const { content } = lexer;163 const start = lexer.at;164 18 unmodified lines183 lexer.at += 1;184 }185 };186 243-/** Each step reads one token of code if it starts at `at`, and says whether it did. */187 type Step = (lexer: Lexer) => boolean;188 189 const comment: Step = (lexer) => {190 const { at, content } = lexer;72 unmodified lines263 264 return true;265 };266 324-/** The `}` that closes a template's `${`. */267 const templateResume: Step = (lexer) => {268 if (269 lexer.content[lexer.at] !== "}" ||270 lexer.depth > 0 ||45 unmodified lines316 word,317 punctuation,318 ];319 378-/**379- * The source with comments, and the insides of strings, regexes and380- * templates, blanked, keeping every offset and line break, so import381- * syntax inside them is never read.382- */320 const mask = (content: string) => {321 const lexer: Lexer = {322 at: 0,323 chars: content.split(""),21 unmodified lines345 // `import "x"`, or a dynamic `import("x")` (`typeof import("x")` too).346 const IMPORT =347 /(?<![.\w$])(?:import|export)[\s{*][^;]*?\bfrom\s*["']|(?<![.\w$])import\s*["']|(?<![.\w$])import\s*\(\s*["']/gu;348 412-/** One import of a file: what it names, and the line it is on (1-based). */349 interface Import {350 readonly line: number;351 readonly specifier: string;352 }353 418-/** Every import, re-export and dynamic import in a file, in source order. */354 const importsOf = (content: string): readonly Import[] => {355 const { code, strings } = mask(content);356 357 return [...code.matchAll(IMPORT)].flatMap((match) => {5 unmodified lines363 : [{ line: content.slice(0, quote).split("\n").length, specifier }];364 });365 };366 432-// ------------------------------------------------------------ resolving433-434-/** `a/b/../c/./d` as `a/c/d`; none when it climbs out of the repo. */367 const normalize = (path: string): Option.Option<string> => {368 const parts: string[] = [];369 370 for (const part of path.split("/")) {28 unmodified lines399 const decodeManifest = Schema.decodeUnknownEffect(400 Schema.fromJsonString(Manifest)401 );402 471-/** A workspace: its folder (with `/`) and its manifest. */403 interface Workspace {404 readonly dir: string;405 readonly manifest: Manifest;406 }407 477-/** Every workspace package in the repo: the `package.json` files under `apps/` and `packages/`. */408 const workspaces = Effect.flatMap(409 filesWhere((file) => /^(?:apps|packages)\/[^/]+\/package\.json$/u.test(file)),410 (files) =>411 Effect.forEach(files, ({ content, file }) =>3 unmodified lines415 }))416 )417 );418 489-/** The file an `exports` subpath names, through a key or one `*` wildcard. */419 const exported = (420 workspace: Workspace,421 subpath: string422 ): Option.Option<string> => {25 unmodified lines448 (file) => normalize(`${workspace.dir}${file}`)449 );450 };451 523-/** The repo path an import reaches: a relative path, or a workspace package's export; none for anything else. */452 const resolved = (453 from: string,454 specifier: string,455 all: readonly Workspace[]11 unmodified lines467 ? Option.none()468 : exported(owner, specifier.slice(owner.manifest.name.length + 1));469 };470 543-/** Whether an import reaches into the cartridge: its package by name, or a path inside it. */471 const reachesCartridge = (472 from: string,473 specifier: string,474 all: readonly Workspace[]12 unmodified lines487 ...manifest.devDependencies,488 ...manifest.peerDependencies,489 });490 564-// ---------------------------------------------------------------- tests565-491 const provided = <A, E>(492 effect: Effect.Effect<493 A,494 E,121 unmodified lines616 617 const reaching = outside.flatMap(({ content, file }) => {618 const lines = content.split("\n");619 695- // `line` is 1-based, so the line above it is `lines[line - 2]`.620 return importsOf(content)621 .filter(622 ({ line, specifier }) =>623 !(lines[line - 2] ?? "").includes(MARKER) &&50 unmodified linesmodified:packages/config/test/created.test.ts-7 removed
1-/**2- * The ledger of throwaway resources: every namespace, repo or3- * project a smoke run, a swarm run or a `seed --as` copy makes on a stage is4- * written to `infra/created.jsonl`, so teardown acts only on what this5- * build made.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { DateTime, Effect, FileSystem, Path } from "effect";4 23 unmodified lines28 name: "swarm-r2",29 stage: "dev-oscabriel",30 };31 38-/** A fresh ledger file in a temp dir, for the scope of one test. */32 const tempLedger = Effect.gen(function* () {33 const fs = yield* FileSystem.FileSystem;34 const path = yield* Path.Path;35 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "ledger-701-" });78 unmodified linesmodified:packages/config/test/deploy.test.ts+2 added-17 removed
21 unmodified lines22 } from "../../../infra/deploy.ts";23 import { LockFile } from "../../../infra/recording.ts";24 import { repoRoot } from "./root.ts";25 26-/** One command the deploy spawned, with its folder relative to the repo root. */26 interface Spawned {27 readonly command: string;28 readonly args: readonly string[];29 readonly cwd: string;30 readonly env: Readonly<Record<string, string | undefined>>;31 }32 34-/**35- * A `ChildProcessSpawner` that runs nothing: it records each command and36- * answers with the exit code `exitOf` gives it.37- */33 const recording = (exitOf: (spawned: Spawned) => number) =>34 Effect.gen(function* () {35 const path = yield* Path.Path;36 const root = yield* repoRoot;35 unmodified lines72 spawned: Ref.get(spawned),73 };74 });75 81-/** `deploy(argv)` over a recording spawner: what it spawned, and how it ended. */76 const run = (77 argv: readonly string[],78 options: {79 readonly exitOf?: (spawned: Spawned) => number;4 unmodified lines84 const fs = yield* FileSystem.FileSystem;85 const path = yield* Path.Path;86 const fake = yield* recording(options.exitOf ?? (() => 0));87 94- // A lock nobody wrote, so a take being recorded on this machine95- // (`infra/.recording`) never decides these tests; recording.test.ts96- // holds the lock itself.88+ // A lock nobody wrote, so a local `infra/.recording` never decides these89+ // tests; recording.test.ts holds the lock itself.90 const unlocked = path.join(91 yield* fs.makeTempDirectoryScoped({ prefix: "deploy-unlocked-" }),92 ".recording"93 );11 unmodified lines105 106 return { result, spawned: yield* fake.spawned };107 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));108 116-/** A spawned command as one line: `apps/sandbox$ wrangler deploy --env x`. */109 const line = ({ args, command, cwd }: Spawned) =>110 `${cwd === "" ? "." : cwd}$ ${[command, ...args].join(" ")}`;111 112 describe("a deploy without a known stage", () => {66 unmodified lines179 Effect.provideService(Console.Console, quiet)180 );181 182 expect(Result.isSuccess(result)).toBeTruthy();191- // infra/workers-dev.json records the account's subdomain.183 expect(printed.at(-1)).toBe(184 "deploy dev-oscabriel: to offer Google sign-in, register https://platform-dev-oscabriel.oscargabriel.workers.dev/oauth/google/callback as the Google client's redirect URI (H4)"185 );186 })50 unmodified lines237 it.live("turns Wrangler's metrics off in every command it spawns", () =>238 Effect.gen(function* () {239 const { spawned } = yield* run(["--stage", "dev-oscabriel"]);240 250- // One per step: verify, sandbox, platform, web build, web, triggers,251- // smoke.241 expect(spawned.map(({ env }) => env.WRANGLER_SEND_METRICS)).toStrictEqual(242 ["false", "false", "false", "false", "false", "false", "false"]243 );244 })108 unmodified lines353 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))354 );355 });356 368-/**369- * The message a failed `deploy(argv)` carries: `runMain` prints a failure as370- * its tag and its message, and nothing else.371- */357 const messageOf = (358 argv: readonly string[],359 options: Parameters<typeof run>[1] = {}360 ) =>90 unmodified linesmodified:packages/config/test/docs-public.test.ts+3 added-33 removed
1-/**2- * The repo's own docs are the public record: AGENTS.md and GLOSSARY.md point3- * at nothing outside the repo, AGENTS.md says what holds today, and the4- * glossary defines the terms the code is written in. No file the repo would5- * commit cites the build's private plan or points into the maintainer's6- * gitignored working docs either, code comments included. File reads and7- * string checks only, beside one `git ls-files`.8- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Array, Effect, FileSystem, Option, Order, Path, Schema } from "effect";4 5 import { committable, readsAtOnce, repoRoot, textOf } from "./root.ts";6 15-/**16- * A pointer into the maintainer's working docs, which live in a gitignored17- * `.agents/` folder on the maintainer's machine: the decisions, the demo, the18- * stage record, the workflow docs, the issue tracker and the folder's README.19- * A bare `.agents/` is not one: a hosted project's skill lives under it.20- */7 const PRIVATE_FOLDERS = [8 ".agents/adr",9 ".agents/demo",10 ".agents/ops",1 unmodified line12 ".agents/scratch",13 ".agents/README",14 ] as const;15 30-/**31- * What a pointer to something only the maintainer can open looks like: a32- * home folder, the private research repo or the host that serves it, or the33- * maintainer's working docs.34- */16 const PRIVATE = [17 "~/",18 "/home/",19 "wanted-explainer",1 unmodified line21 ...PRIVATE_FOLDERS,22 ] as const;23 24 /**44- * What a reference into the build's private plan looks like, which a reader45- * with only the repo cannot follow: a section of its spec (`spec §8`, or a46- * wave's `W9 §14`), one of its decisions (`spec D6`, or a wave's `W9-D14`),47- * one of its issues by wave (`W3 313`), or the research synthesis it was48- * drawn from (`SYN`).25+ * A reference into the build's private plan: a section of its spec26+ * (`spec §8`, `W9 §14`), a decision (`spec D6`, `W9-D14`), an issue by wave27+ * (`W3 313`), or the research synthesis (`SYN`).28 */29 const PLAN_REFERENCES = [30 /\bspec §/u,31 /\bspec D\d/u,2 unmodified lines34 /\bW\d \d{3}\b/u,35 /\bSYN\b/u,36 ] as const;37 59-/** The files a reader opens as text: source, config, docs and scripts. */38 const TEXT_FILE =39 /(?:\.(?:css|html|json|jsonc|md|mjs|sh|sql|toml|ts|tsx|ya?ml)|(?:^|\/)(?:\.gitignore|\.env\.schema|[^/]*Dockerfile))$/u;40 41 /** This file, which spells the references out to find them. */42 const QUOTES_THE_REFERENCES = "packages/config/test/docs-public.test.ts";43 66-/** The plan references `text` makes, by their patterns. */44 const planReferencesIn = (text: string) =>45 PLAN_REFERENCES.flatMap((reference) =>46 reference.test(text) ? [reference.source] : []47 );4 unmodified lines52 */53 const NAMES_THE_PRIVATE_FOLDERS = (file: string) =>54 file.startsWith(".agents/") || file === ".gitignore";55 79-/** The private plan references and private folder pointers in `file`'s `text`. */56 const privateIn = (file: string, text: string) => [57 ...planReferencesIn(text),58 ...(NAMES_THE_PRIVATE_FOLDERS(file)59 ? []60 : PRIVATE_FOLDERS.filter((folder) => text.includes(folder))),61 ];62 87-/** Terms the code uses in public names, each of which GLOSSARY.md defines. */63 const TERMS = [64 "Claim fork",65 "Decision",66 "Family",12 unmodified lines79 const RootPackage = Schema.Struct({80 scripts: Schema.Record(Schema.String, Schema.String),81 });82 108-/** A file's text, by its path from the repo root. */83 const read = (relative: string) =>84 Effect.gen(function* () {85 const fs = yield* FileSystem.FileSystem;86 const path = yield* Path.Path;1 unmodified line88 89 return yield* fs.readFileString(path.join(root, relative));90 });91 118-/** Each file with its text. */92 const withText = (paths: readonly string[]) =>93 Effect.forEach(paths, (path) =>94 Effect.map(read(path), (text) => ({ path, text }))95 );96 124-/** Every public doc this test reads, with its text. */97 const publicDocs = withText(["AGENTS.md", "GLOSSARY.md"]);98 127-/** The lines of a `## <title>` section, up to the next heading of its level or above. */99 const sectionOf = (text: string, title: string): readonly string[] => {100 const lines = text.split("\n");101 const start = lines.indexOf(`## ${title}`);102 6 unmodified lines109 110 return end === -1 ? rest : rest.slice(0, end);111 };112 142-/** The command a list item opens with: `ops` in "- `ops -- <command>`: …". */113 const commandOf = (line: string) =>114 /^- `(?<name>[^`\s]+)/u.exec(line)?.groups?.name;115 116 describe("the repo's public docs", () => {85 unmodified linesmodified:packages/config/test/example-burrow.test.ts+3 added-30 removed
1-/**2- * The fence-shaped example: `examples/burrow` is a Bun3- * project of its own, and these cases run its own commands in its folder, as4- * its maintainers would. Its lint, run as its ratchet runs it, reports5- * exactly the six module-level `let`s the ratchet starts from, one in each6- * package's `src/`, as warnings; its caller count finds `legacyFetch` in all7- * six packages, in the JSON a migrate ask's count command prints; its other8- * lanes pass on main; and its lint rule's own fixture test passes.9- *10- * Each case installs first (`--frozen-lockfile`: burrow's devDependencies are11- * pinned to the root's, so Bun's cache serves them). The manifest's presence12- * is asserted before anything runs, so a missing project is a failed13- * assertion, not a spawn error.14- */1+// Each case installs first (`--frozen-lockfile`: burrow's devDependencies are2+// pinned to the root's, so Bun's cache serves them).3 import { NodeServices } from "@effect/platform-node";4 import { describe, expect, it } from "@effect/vitest";5 import { Effect, FileSystem, Path, Schema, Stream } from "effect";6 import { ChildProcess, ChildProcessSpawner } from "effect/process";1 unmodified line8 import { repoRoot } from "./root.ts";9 10 const example = "examples/burrow";11 24-/** The six workspace packages, each holding one module-level `let`. */12 const PACKAGES = [13 "auth",14 "billing",15 "catalog",1 unmodified line17 "notify",18 "search",19 ] as const;20 34-/**35- * What a migrate ask's count command prints (`CallerCount` in36- * `@repo/project/migrate`; `@repo/config` imports no workspace package, so37- * the shape is restated here).38- */21+/** `@repo/config` imports no workspace package, so `CallerCount`'s shape is restated here. */22 const CallerCount = Schema.Struct({23 byModule: Schema.Record(Schema.String, Schema.Int),24 total: Schema.Int,25 });26 44-/** The part of `oxlint --format json` these cases read. */27 const OxlintReport = Schema.Struct({28 diagnostics: Schema.Array(29 Schema.Struct({30 code: Schema.optionalKey(Schema.String),2 unmodified lines33 })34 ),35 });36 55-/** A command's exit code and what it printed. */37 interface Ran {38 readonly code: number;39 readonly stderr: string;40 readonly stdout: string;41 }42 62-/** Runs a command in burrow's folder and keeps its exit code and output. */43 const run = (command: string, args: readonly string[]) =>44 Effect.gen(function* () {45 const path = yield* Path.Path;46 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;14 unmodified lines61 62 return { code, stderr, stdout } satisfies Ran;63 }).pipe(Effect.scoped);64 85-/** Asserts burrow exists, then installs its pinned devDependencies. */65 const install = () =>66 Effect.gen(function* () {67 const fs = yield* FileSystem.FileSystem;68 const path = yield* Path.Path;3 unmodified lines72 yield* fs.exists(manifest),73 `${example}/package.json exists`74 ).toBeTruthy();75 97- // The whole run on a failure, so its stderr shows in the diff.76 expect(yield* run("bun", ["install", "--frozen-lockfile"])).toMatchObject({77 code: 0,78 });79 });80 103-/** The package a reported file sits in, from its `packages/<name>/src/` path. */81 const packageOf = (filename: string) =>82 /(?:^|\/)packages\/(?<name>[^/]+)\/src\//u.exec(filename)?.groups?.name;83 107-/** Long enough for a cold install; a warm one takes about a second. */84 const TIMEOUT = 180_000;85 86 describe("examples/burrow", () => {87 it.live(1 unmodified line89 () =>90 Effect.gen(function* () {91 yield* install();92 117- // The command burrow's ratchet runs (its config folder's `project.ts`).93 const lint = yield* run("bun", ["run", "lint", "--format", "json"]);94 95 const report = yield* Schema.decodeEffect(96 Schema.fromJsonString(OxlintReport)39 unmodified lines136 const counts = yield* Schema.decodeEffect(137 Schema.fromJsonString(CallerCount)138 )(count.stdout);139 165- // Every package has a caller, so the family has six children; the166- // calls in each package's src/, counted by hand.140 expect(counts).toStrictEqual({141 byModule: {142 "@burrow/auth": 2,143 "@burrow/billing": 2,40 unmodified linesmodified:packages/config/test/example-datekit.test.ts+3 added-39 removed
1-/**2- * The datekit example, run as the project it pretends to be:3- * `bun test` inside `examples/datekit` is red on main for exactly the three4- * tests its asks name as their checks, each by an assertion rather than a5- * load error (what red first in GLOSSARY.md asks of a check), and green for6- * every other test. Its run block holds on main too: every lane passes, and7- * each ask's check, run alone by the block's test command, is red by an8- * assertion. The example is a Bun project of its own, outside the9- * workspaces, so each command runs as a child process under10- * `sh -c`, the way the platform's Checker runs a project's commands, in a11- * copy of its public tree: every file git tracks but its layers (`layers/`,12- * pushed to the private namespace, never to main).13- */1+// The example is a Bun project outside the workspaces, so each command runs2+// as a child process under `sh -c`, as the Checker runs a project's commands,3+// in a copy of its public tree (every tracked file but `layers/`).4 import { NodeServices } from "@effect/platform-node";5 import { describe, expect, it } from "@effect/vitest";6 import { Effect, FileSystem, Path, Stream } from "effect";7 import { ChildProcess, ChildProcessSpawner } from "effect/process";8 9 import { Brand } from "../../brand/src/index.ts";10 import { repoRoot } from "./root.ts";11 22-/** The example, from the repo root. */12 const example = "examples/datekit";13 25-/** What one run of `bun test` printed, both streams, and how it ended. */14 interface BunRun {15 readonly exitCode: number;16 readonly output: string;17 }18 31-/** One test file's part of bun's report: the tests it failed, and its text. */19 interface FileReport {20 readonly failed: readonly string[];21 readonly file: string;22 readonly text: string;23 }24 38-/** Bun's report, read: each file it reported on, and its closing counts. */25 interface BunReport {26 readonly errors: number;27 readonly failed: number;28 readonly files: readonly FileReport[];29 readonly passed: number;44- /** How many tests bun ran, across how many files. */30 readonly ran: { readonly files: number; readonly tests: number };31 }32 33 const ANSI = new RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*m`, "gu");35 unmodified lines69 const LANES = /\bchecks:\s*\{(?<lanes>[^}]*)\}/u;70 71 const LANE = /(?<lane>\w+):\s*"(?<command>[^"]+)"/gu;72 88-/** A closing count bun prints (` 3 fail`), or 0 when it prints none. */73 const countOf = (output: string, word: string) =>74 Number(75 new RegExp(`^\\s*(?<count>\\d+) ${word}$`, "mu").exec(output)?.groups76 ?.count ?? "0"77 );78 95-/** The name a `(fail)` line gives, if the line is one. */79 const failedIn = (line: string) => {80 const name = FAILED_TEST.exec(line)?.groups?.name;81 82 return name === undefined ? [] : [name];83 };84 102-/** Reads bun's console report into its files and counts. */85 const readReport = (output: string): BunReport => {86 const lines = output.split("\n").map((line) => line.trim());87 88 const starts = lines.flatMap((line, at) =>31 unmodified lines120 121 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>122 bytes.pipe(Stream.decodeText(), Stream.mkString);123 142-/**143- * The example's public tree in a folder of its own, for as long as the144- * scope lasts: every file git tracks under it but its layers, as the seed145- * pushes main.146- */124 const publicTree = Effect.gen(function* () {125 const fs = yield* FileSystem.FileSystem;126 const path = yield* Path.Path;127 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;19 unmodified lines147 148 return dir;149 });150 174-/** Runs `command` in the example's public tree at `dir` under `sh -c`, as the Checker runs a lane. */151 const inTree = (dir: string, command: string) =>152 Effect.scoped(153 Effect.gen(function* () {154 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;13 unmodified lines168 } satisfies BunRun;169 })170 );171 196-/** The example's run block, read from its project file. */172 const runBlock = Effect.gen(function* () {173 const fs = yield* FileSystem.FileSystem;174 const path = yield* Path.Path;175 11 unmodified lines187 188 return { lanes, test: TEST_COMMAND.exec(source)?.groups?.command ?? "" };189 });190 216-/**217- * Each ask file in the example's config folder, and the check file it names;218- * none when the folder is missing.219- */191 const askChecks = Effect.gen(function* () {192 const fs = yield* FileSystem.FileSystem;193 const path = yield* Path.Path;194 const asks = path.join(yield* repoRoot, example, Brand.configDir, "asks");13 unmodified lines208 }))209 );210 });211 241-/** How a file failed: how many tests, whether by an assertion, whether it loaded. */212 const howFailed = ({ failed, file, text: part }: FileReport) => ({213 assertion: ASSERTION.test(part),214 file,215 loaded: !LOAD_ERRORS.some((pattern) => pattern.test(part)),7 unmodified lines223 it.live(224 "is red on main for exactly its three asks' checks, each by an assertion, and green elsewhere",225 () =>226 Effect.gen(function* () {257- // The example's own `package.json` test script.227 const run = yield* inTree(yield* publicTree, "bun test");228 const report = readReport(run.output);229 const checks = yield* askChecks;230 2 unmodified lines233 "format-ordinal.ask.ts",234 "parse-iso-week.ask.ts",235 ]);236 268- // The run fails, and only by the asks' checks: one test in each, by269- // an assertion, with nothing that failed to load.237 expect({238 errors: report.errors,239 exitedNonZero: run.exitCode !== 0,240 failed: report.failed,14 unmodified lines255 }))256 .toSorted(byFile),257 });258 292- // Every other test passes, across the four suites the library keeps293- // green (parse, format, add, diff) and the three checks.259 expect({260 files: report.ran.files,261 passedOrFailed: report.passed + report.failed,262 }).toStrictEqual({ files: 7, passedOrFailed: report.ran.tests });61 unmodified lines324 failing: [{ assertion: true, file, loaded: true, tests: 1 }],325 }))326 );327 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),363- // Four `bun test` runs over a small library, one after another.328 30_000329 );330 });modified:packages/config/test/import-examples.test.ts-17 removed
1-/**2- * `bun scripts/import-examples.ts`: the open-source repos the code browser3- * is previewed on, imported one at a time as the operator, skipped once a4- * platform lists them, recorded in the ledger as kept imports, on `demo`5- * as on a dev stage; and `--tags`' backfill, which pushes tags only and6- * never shows its token.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { ProjectExists } from "@repo/protocol/refusal";4 import {263 unmodified lines268 ]);269 });270 });271 279-/** A platform in memory: the projects it lists, and every call made to it. */272 const fakePlatform = (listed: readonly string[]) =>273 Effect.gen(function* () {274 const calls = yield* Ref.make<readonly string[]>([]);275 const have = new Set(listed.map(project));40 unmodified lines316 ),317 };318 });319 328-/** `importExamples(argv)` over `layer`, with the ledger in a temp folder: how it ended, and what it printed. */320 const ran = (321 argv: readonly string[],322 layer: Layer.Layer<ImportTarget | TagBackfill | Warmer>323 ) =>223 unmodified lines547 548 const ledgerFile = path.join(dir, "created.jsonl");549 const platform = yield* fakePlatform(["anyhow", "ky"]);550 560- // An earlier run imported anyhow; ky is someone else's project.551 yield* fs.writeFileString(552 ledgerFile,553 `${JSON.stringify({ at: "2026-10-08T20:00:00.000Z", by: "import", kind: "project", name: "anyhow", stage: "dev-oscabriel" })}\n`554 );22 unmodified lines577 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "importing-" });578 579 const ledgerFile = path.join(dir, "created.jsonl");580 591- // An earlier run imported anyhow and gum; the platform lists anyhow592- // and ky (someone else's project), and gum not yet.581 const platform = yield* fakePlatform(["anyhow", "ky"]);582 583 yield* fs.writeFileString(584 ledgerFile,87 unmodified lines672 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))673 );674 });675 688-/** A call the platform never answered, as an edge timeout leaves it. */676 class NoAnswer extends Data.TaggedError("NoAnswer")<{677 readonly after: string;678 }> {}679 693-/**694- * `initUntilAnswered` over calls that answer `answers` in turn, the clock695- * moved past its waits: how it ended, and how many calls it made.696- */680 const askedAgain = (681 answers: readonly Effect.Effect<682 { readonly landed?: string },683 NoAnswer | ProjectExists61 unmodified linesmodified:packages/config/test/imported-docs.test.ts-6 removed
1-/**2- * The docs' list of imported projects is a copy of the import script's3- * plan, kept in `@repo/agent-kit` (the web cannot import a script): each4- * project by its name and key, with its source, its licence and what it5- * is, in the plan's order.6- */1 import { describe, expect, it } from "@effect/vitest";2 3 import { examples } from "../../../scripts/lib/import/plan.ts";4 import { importedProjects } from "../../agent-kit/src/docs/imported.ts";14 unmodified linesmodified:packages/config/test/legacy-projects.test.ts+2 added-9 removed
1-/**2- * The projects made before owners keep the keys they were made with3- * (`packages/protocol/src/legacy.ts`): the protocol's table holds the two4- * examples, the operator's, and every import at its source path, each by5- * the key it has on the stages. The table is written by hand in the6- * protocol, so a Worker never imports a script; this holds it to its7- * sources, the examples' folders and the import plan.8- */1+// The protocol's table is written by hand, so a Worker never imports a2+// script; this holds it to its sources, the examples' folders and the import plan.3 import { describe, expect, it } from "@effect/vitest";4 5 import { examples } from "../../../scripts/lib/import/plan.ts";6 import { EXAMPLES } from "../../../scripts/seed.ts";7 import { legacyProjects } from "../../protocol/src/legacy.ts";8 15-/** Each example folder's project, in the operator's namespace. */9 const seeded = EXAMPLES.map((folder) => {10 const key = folder.slice(folder.lastIndexOf("/") + 1);11 12 return { key, name: `oscabriel/${key}` };15 unmodified linesmodified:packages/config/test/recording.test.ts-13 removed
1-/**2- * The deploy lock for recording days: `bun infra/recording.ts3- * on` writes `infra/.recording`, and while it is there `infra/deploy.ts`4- * refuses every deploy with `RecordingInProgress` before it spawns anything.5- * `off` is the only way out.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 ConfigProvider,18 unmodified lines23 RecordingUsage,24 } from "../../../infra/recording.ts";25 import { repoRoot } from "./root.ts";26 33-/**34- * A spawner that runs nothing and exits 0: each command it was asked for,35- * as `<folder>$ <command> <args>`, its folder relative to the repo root.36- */27 const spawning = Effect.gen(function* () {28 const path = yield* Path.Path;29 const root = yield* repoRoot;30 const lines = yield* Ref.make<readonly string[]>([]);32 unmodified lines63 spawned: Ref.get(lines),64 };65 });66 77-/** A temp root's lock file, `infra/.recording` under it, for one test's scope. */67 const tempLock = Effect.gen(function* () {68 const fs = yield* FileSystem.FileSystem;69 const path = yield* Path.Path;70 const root = yield* fs.makeTempDirectoryScoped({ prefix: "recording-806-" });2 unmodified lines73 74 return path.join(root, lockPath);75 });76 88-/** `deploy(argv)` with the lock at `lock`: how it ended, and what it spawned. */77 const deployed = (argv: readonly string[], lock: string) =>78 Effect.gen(function* () {79 const fake = yield* spawning;80 10 unmodified lines91 92 return { result, spawned: yield* fake.spawned };93 });94 107-/** What `recording(argv)` prints, with the lock at `lock`. */95 const printedBy = (argv: readonly string[], lock: string) =>96 Effect.gen(function* () {97 const printed: string[] = [];98 124 unmodified linesmodified:packages/config/test/release.test.ts-19 removed
1-/**2- * The release: the CLI's npm package says what it is from3- * `Brand` alone, a release builds for exactly two machines, only a person4- * publishes, and what goes to the platform's own release storage is what5- * the platform decodes and serves.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Array as Arr,37 unmodified lines42 import { layoutOf, runStep } from "../../../scripts/lib/release/steps.ts";43 import { Brand } from "../../brand/src/index.ts";44 import { repoRoot } from "./root.ts";45 52-/** What the test reads of a package manifest. */46 const PackageJson = Schema.fromJsonString(47 Schema.Struct({48 dependencies: Schema.optionalKey(49 Schema.Record(Schema.String, Schema.String)350 unmodified lines400 });401 });402 });403 411-/** A digest, as `sha256sum` prints one. */404 const digest = (fill: string) => fill.repeat(64);405 406 const first = {407 latest: "0.1.0",15 unmodified lines423 [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },424 [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },425 };426 435-/**436- * A spawner that runs nothing and exits 0: each command it was asked for,437- * as `<folder>$ <command> <args>`, its folder relative to the repo root.438- */427 const recordingSpawner = Effect.gen(function* () {428 const path = yield* Path.Path;429 const root = yield* repoRoot;430 const lines = yield* Ref.make<readonly string[]>([]);101 unmodified lines532 });533 });534 });535 548-/** A file's digest as `sha256sum` prints it. */536 const sha256 = (content: string) =>537 Effect.flatMap(Crypto.Crypto, (crypto) =>538 crypto.digest("SHA-256", new TextEncoder().encode(content))539 ).pipe(27 unmodified lines567 posix: true,568 });569 });570 584- /**585- * A machine to install on: a `curl` that serves `files` for the release's586- * URLs and fails any other, a home folder, and `sh` to run the script.587- */571 const install = (files: Readonly<Record<string, string>>) =>572 Effect.gen(function* () {573 const fs = yield* FileSystem.FileSystem;574 const path = yield* Path.Path;62 unmodified lines637 stderr,638 };639 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));640 658- /** A binary for each machine a release builds for, as a tiny script. */641 const binaries = Object.fromEntries(642 ["linux-x64", "darwin-arm64"].map((target) => [643 `${Brand.slug}-${target}`,644 `#!/bin/sh\necho ${target}\n`,645 ])646 );647 666- /** `SHA256SUMS` for the binaries, each digest as `digestOf` gives it. */648 const sums = <E, R>(649 digestOf: (content: string) => Effect.Effect<string, E, R>650 ) =>651 Effect.map(90 unmodified linesmodified:packages/config/test/root.ts+2 added-12 removed
1 import { Effect, FileSystem, Option, Path, Stream } from "effect";2 import { ChildProcess, ChildProcessSpawner } from "effect/process";3 4-/** The repo root. Vitest runs in the package's folder, two below it. */4 export const repoRoot = Effect.map(Path.Path, (path) =>5 path.resolve("..", "..")6 );7 9-/**10- * Every file git tracks or would track (ignored files left out), from the11- * repo root. A tracked file deleted but not yet staged is still listed:12- * `textOf` reads it as none.13- */8+/** A tracked file deleted but not yet staged is still listed: `textOf` reads it as none. */9 export const committable = Effect.gen(function* () {10 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;11 const cwd = yield* repoRoot;12 16 unmodified lines29 30 return listed.split("\n").filter((line) => line.length > 0);31 }).pipe(Effect.scoped);32 38-/**39- * How many of the repo's files a whole-repo scan reads at once. One at a40- * time, a scan of every source file waits on a thousand queued reads, which41- * under verify's parallel test run takes longer than a test's timeout.42- */33+/** One read at a time, a whole-repo scan outlasts a test's timeout under verify's parallel run. */34 export const readsAtOnce = { concurrency: 32 } as const;35 45-/** A file under the repo root, as text, if it is on disk. */36 export const textOf = (file: string) =>37 Effect.gen(function* () {38 const fs = yield* FileSystem.FileSystem;39 const path = yield* Path.Path;6 unmodified linesmodified:packages/config/test/scripts.test.ts-8 removed
1-/**2- * The demo-readiness scripts: a maintainer types `bun run swarm`,3- * `bun run seed`, `bun run release` or `bun run import-examples`, and each4- * runs one entry file that5- * exists, so the work that builds them fills an entry without touching a6- * root file.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Effect, FileSystem, Path, Schema } from "effect";4 2 unmodified lines7 const RootPackage = Schema.Struct({8 scripts: Schema.Record(Schema.String, Schema.String),9 });10 18-/** What `bun run <name>` runs, and whether its entry file is on disk. */11 const entryOf = (name: string) =>12 Effect.gen(function* () {13 const fs = yield* FileSystem.FileSystem;14 const path = yield* Path.Path;39 unmodified linesmodified:packages/config/test/seed-as.test.ts-9 removed
1-/**2- * `seed --as`: a fresh copy of an example under another project3- * name, so a live run (the swarm's rehearsal) can take a family nobody has4- * touched while the original stays fresh for the recording. A name some5- * project already has is refused, and a copy on a stage is written to the6- * throwaway ledger for teardown.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Console, DateTime, Effect, FileSystem, Layer, Path } from "effect";4 66 unmodified lines71 repo: `oscabriel__datekit-copy-2--${layer}`,72 }))73 );74 82- // A copy of a copy is still a copy of the example.75 expect(copy.copyOf).toBe("oscabriel/datekit");76 }).pipe(Effect.provide(NodeServices.layer))77 );78 });38 unmodified lines117 60_000118 );119 });120 129-/** What `main` prints, line by line. */121 const printedBy = (argv: readonly string[]) =>122 Effect.gen(function* () {123 const printed: string[] = [];124 121 unmodified linesmodified:packages/config/test/seed-layer.test.ts-39 removed
1-/**2- * datekit's maintainers layer and the seed's layer step: the3- * held-back checks datekit keeps in `layers/maintainers/`, each citing the4- * clause it enforces, and the seed pushing them to the private namespace5- * after the public project, never into the public tree.6- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Array,25 unmodified lines30 } from "../../protocol/src/domain/visibility.ts";31 import { Handle, keyOf, RepoName } from "../../protocol/src/ids.ts";32 import { repoRoot } from "./root.ts";33 40-/** The config folder's name, from the brand. */34 const config = Brand.configDir;35 43-/** Every file of datekit's maintainers layer, as the layer repo holds it. */36 const layerFiles = [37 `${config}/layer.json`,38 `${config}/layer.ts`,39 ".agents/maintainers/finish.md",56 unmodified lines96 }).pipe(Effect.provide(NodeServices.layer))97 );98 });99 108-// ------------------------------------------------------------- the layer109-100 const example = "examples/datekit";101 102 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>103 bytes.pipe(Stream.decodeText(), Stream.mkString);104 115-/** `command` run in `cwd`: how it ended, and both streams. */105 const run = (cwd: string, command: string, args: readonly string[]) =>106 Effect.scoped(107 Effect.gen(function* () {108 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;10 unmodified lines119 return { code: Number(code), output: `${stdout}\n${stderr}` };120 })121 );122 134-/** A file of the example, as text. */123 const exampleFile = (file: string) =>124 Effect.gen(function* () {125 const fs = yield* FileSystem.FileSystem;126 const path = yield* Path.Path;127 128 return yield* fs.readFileString(path.join(yield* repoRoot, example, file));129 });130 143-// Every import of the sdk by the name config files use.131 const SDK = new RegExp(`(["'])${Brand.cliPackage}/rules\\1`, "gu");132 146-/**147- * What a config module's default export is, as data: the module run by148- * bun with its sdk import pointed at the sdk's source, as the rules149- * evaluator's `/bun` adapter runs config code, then printed as JSON.150- */133 const defaultExportOf = (source: string) =>134 Effect.scoped(135 Effect.gen(function* () {136 const fs = yield* FileSystem.FileSystem;12 unmodified lines149 );150 151 const ran = yield* run(dir, "bun", ["main.ts"]);152 171- // What bun said shows only when it failed.153 expect({154 code: ran.code,155 said: ran.code === 0 ? "" : ran.output,156 }).toStrictEqual({ code: 0, said: "" });3 unmodified lines160 );161 })162 );163 183-/** The layer's file at `file`, as text. */164 const inLayer = (plan: SeedPlan, file: string) =>165 new TextDecoder().decode(166 plan.layers[0]?.files.find(({ path }) => path === file)?.content167 );168 189-/** datekit's plan, its maintainers layer, the manifest and the policy. */169 const datekit = Effect.gen(function* () {170 const plan = yield* planSeed(example);171 const layer = yield* Effect.fromNullishOr(plan.layers[0]);172 7 unmodified lines180 181 return { layer, manifest, plan, policy };182 });183 205-/** The lanes datekit's `project.ts` runs on every answer: the public checks, by name. */184 const publicLanes = Effect.gen(function* () {185 const { run: block } = yield* Schema.decodeUnknownEffect(186 Schema.Struct({187 run: Schema.Struct({4 unmodified lines192 193 return Object.entries(block.checks);194 });195 218-/** A heading's anchor, as a README link names it: `## Format patterns` is `format-patterns`. */196 const anchorOf = (heading: string) =>197 heading198 .toLowerCase()199 .replaceAll(/[^\w\s-]/gu, "")200 .trim()201 .replaceAll(/\s+/gu, "-");202 226-/** Each README section's text by its anchor: from its heading to the next. */203 const sectionsOf = (readme: string) => {204 const sections = new Map<string, string>();205 let current = "";206 113 unmodified lines320 );321 322 expect(unquoted).toStrictEqual([]);323 348- // Both kinds of source are cited.324 expect(325 Array.dedupe(326 manifest.checks.map(({ clause }) => clause.source)327 ).toSorted()29 unmodified lines357 30_000358 );359 });360 386-/** A folder holding `trees` one over another, each file at its path. */361 const treeOf = (...trees: readonly (readonly SeedFile[])[]) =>362 Effect.gen(function* () {363 const fs = yield* FileSystem.FileSystem;364 const path = yield* Path.Path;49 unmodified lines414 "test",415 `./checks/held-back/${area}`,416 ]);417 444- // Each lane as the Checker runs it: its command under `sh -c`.418 const failedLanes = yield* Effect.filter(lanes, ([, command]) =>419 Effect.map(420 run(bad, "sh", ["-c", command]),421 ({ code }) => code !== 018 unmodified lines440 60_000441 );442 });443 471-// ------------------------------------------------------------- the world472-473-/** A vouched contributor to datekit, who reads no layer. */444 const bram = Handle.make("bram");445 476-/** Paths a public tree must never hold: the layer's, or the example's folder of layers. */446 const isLayerPath = (path: string) =>447 ["layers/", "checks/held-back/", ".agents/maintainers/"].some((prefix) =>448 path.startsWith(prefix)449 );19 unmodified lines469 "OpenAsk oscabriel/datekit/parse-iso-week: done",470 "Layer datekit--maintainers: done",471 ]);472 504- // A maintainer's clone: the layer's files on main, and a branch505- // for each known-bad commit its manifest names.473 const refs = yield* Effect.flatMap(474 target.refsAt(layer.repo, plan.decider),475 Effect.fromOption476 );27 unmodified lines504 MAIN_REF,505 ].toSorted(),506 });507 541- // A contributor's clone of the layer is turned away, and the542- // public tree holds visibility.ts and nothing of the layer.508 const refused = yield* Effect.flip(target.refsAt(layer.repo, bram));509 510 const published = yield* target.pathsAt(511 project,12 unmodified lines524 layerPaths: [],525 visibility: true,526 });527 563- // The public ledger declares the layer and the posture its564- // config states. (Each area's counts are published when its565- // checks are admitted: 615.)528 const ledger = yield* Client.use((client) =>529 client.ledger({ project: plan.project })530 ).pipe(Effect.provide(target.clientFor(bram)));531 19 unmodified lines551 posture:552 "Open with sealed evidence · sealed checks in export, parser",553 });554 593- // A second run finds every step done and moves no ref.555 const again = yield* runSeed(plan);556 const after = yield* target.refsAt(layer.repo, plan.decider);557 558 expect({21 unmodified linesmodified:packages/config/test/seed.test.ts-11 removed
1-/**2- * The seed: what it plans to put on a platform for each example3- * project, read from the example's tracked files, and putting it there.4- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 ConfigProvider,24 unmodified lines29 } from "../../../scripts/seed.ts";30 import { Brand } from "../../brand/src/index.ts";31 import { repoRoot } from "./root.ts";32 37-/** The config folder's name, from the brand (`Brand.configDir`). */33 const config = Brand.configDir;34 40-/** A file of an example, as the test reads it from disk. */35 const onDisk = (example: string, path: string) =>36 Effect.gen(function* () {37 const fs = yield* FileSystem.FileSystem;38 const paths = yield* Path.Path;145 unmodified lines184 }).pipe(Effect.provide(NodeServices.layer))185 );186 });187 194-/** Each step as the command prints it. */188 const linesOf = (steps: readonly SeedStep[]) => steps.map(stepLine);189 190 describe(runSeed, () => {191 it.live(23 unmodified lines215 ]);216 217 const held = yield* seeded(plans);218 226- // Each project's asks, each with the asks it waits on.219 const asks = Object.fromEntries(220 held.map(({ asks: listed, project }) => [221 project,222 Object.fromEntries(60 unmodified lines283 const { failure, refs } = yield* Effect.gen(function* () {284 const stopped = yield* Effect.flip(runSeed(plan));285 const target = yield* SeedTarget;286 295- // No project was made: the gateway has no burrow to list refs of.287 const listed = yield* target.refsOf(plan.project).pipe(288 Effect.map((held) => `listed ${held.size} refs`),289 Effect.catch(({ reason }) => Effect.succeed(reason))290 );79 unmodified lines370 )371 );372 });373 383-/** What `main` prints, line by line, and how it ended. */374 const printedBy = (argv: readonly string[]) =>375 Effect.gen(function* () {376 const printed: string[] = [];377 81 unmodified lines459 decider: held?.decider,460 project: held?.project,461 ratchets: held?.ratchets,462 }).toStrictEqual({473- // The migrate ask's family: the parent, six children, the delete child.463 asks: 8,464 decider: "okafor",465 project: "oscabriel/burrow",466 ratchets: ["no-module-level-mutable-state"],59 unmodified linesmodified:packages/config/test/smoke-loop.test.ts+2 added-30 removed
1-/**2- * smoke's core loop: `bun scripts/smoke.ts --stage <s> --loop`3- * makes a throwaway project, opens an ask red first, claims it, pushes an4- * answer that reaches outside the ask's territory and hears `OutOfScope`5- * in git's own output, pushes the fix, and reads back its landing and its6- * verdict note, all through the CLI and git as a person would. Here it runs7- * against the Node world (`apps/platform/test/serve-world.ts`), reached8- * over HTTP and git as a stage is.9- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Effect,22 unmodified lines27 const decider = Handle.make("ines-v");28 29 const answerer = Handle.make("bram");30 40-/** Each person's token in the world: no secret, it never leaves this machine. */31 const tokens = {32 answerer: Redacted.make("bram-smoke-loop-world-token-0123456789abcdef"),33 decider: Redacted.make("ines-v-smoke-loop-world-token-0123456789abcd"),34 };35 46-/** A person in a trailer: their handle and the address the platform gives them. */36 const credited = (handle: string) =>37 `${handle} <${handle}@users.${Brand.domain}>`;38 50-/** All a byte stream says, as text. */39 const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>40 bytes.pipe(Stream.decodeText(), Stream.mkString);41 54-/** `git ls-remote <remote> <ref>` as anyone, with no credential at all. */42 const anonymousTip = (remote: string, ref: string) =>43 Effect.scoped(44 Effect.gen(function* () {45 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;119 unmodified lines165 240_000166 );167 });168 182-/**183- * A spawner that runs nothing: each command it was asked for, by name. Any184- * command fails, so a run that reached one could not pass by accident.185- */169+/** Any command fails, so a run that reached one could not pass by accident. */170 const refusing = Effect.gen(function* () {171 const asked = yield* Ref.make<readonly string[]>([]);172 173 const spawner = ChildProcessSpawner.make((command) =>24 unmodified lines198 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),199 };200 });201 218-/**219- * A platform scripted at the process boundary: `status` names the decider,220- * `projects` lists `listed`, git does what it is asked, and `init` makes221- * the project on the platform and then fails (as a push that answered 500222- * after the project was made did on a dev stage). What was spawned is kept, git by223- * its subcommand and the CLI by its command.224- */202+/** `init` makes the project and then fails, as a push that answered 500 after making it did. */203 const scripted = (listed: readonly string[]) =>204 Effect.gen(function* () {205 const asked = yield* Ref.make<readonly string[]>([]);206 229- // Each CLI command's `--json` envelope, as the CLI prints it.207 const replies = new Map([208 [209 "status",210 {32 unmodified lines243 const [program, args] = ChildProcess.isStandardCommand(command)244 ? [command.command, command.args]245 : ["a pipe", []];246 270- // The CLI runs as `bun <entry> <command> … --json`.247 const said =248 program === "bun" ? (args[1] ?? "") : `${program} ${args[0] ?? ""}`;249 250 yield* Ref.update(asked, (all) => [...all, said]);21 unmodified lines272 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),273 };274 });275 300-/**301- * The loop for run `r1` on the scripted platform, with the ledger in a file302- * of its own: how it ended, the CLI commands it ran, and the ledger's lines.303- */276 const loopOnScripted = (listed: readonly string[]) =>277 Effect.gen(function* () {278 const fs = yield* FileSystem.FileSystem;279 const path = yield* Path.Path;233 unmodified linesmodified:packages/config/test/smoke.test.ts+7 added-38 removed
18 unmodified lines19 SmokeFailed,20 webProbes,21 } from "../../../scripts/smoke.ts";22 23-/** What the fake platform answers one request with, after `delayMs` when given. */23 interface Reply {24 readonly status: number;25 readonly body?: string;26 readonly contentType?: string;27 readonly delayMs?: number;28 }29 31-/** A request as the fake platform sees it. */30 interface Seen {31 readonly method: string;32 readonly path: string;33 readonly authorized: boolean;34 readonly body: string;35 }36 39-/** A call as effect/rpc's HTTP protocol sends one, with JSON serialization. */37 const ListAsksCall = Schema.fromJsonString(38 Schema.Tuple([39 Schema.TaggedStruct("Request", {40 headers: Schema.Array(Schema.Unknown),4 unmodified lines45 ])46 );47 48 /**52- * The platform's `/rpc` reply to `body`: for an anonymous `listAsks` of a53- * project in `held`, its open asks (none); of any other, the bytes its54- * server sent for a project it doesn't hold (captured from55- * `apps/platform`'s `serve` before any project existed, the refusal's56- * `next` aside); a 400 for anything else.49+ * The bytes of another project's reply were captured from `apps/platform`'s50+ * `serve` before any project existed, the refusal's `next` aside.51 */52 const rpcReply = (body: string, held: readonly string[]): Reply =>53 Option.match(Schema.decodeOption(ListAsksCall)(body), {54 onNone: () => ({ status: 400 }),4 unmodified lines59 status: 200,60 }),61 });62 69-/** The platform as `healthy` below, holding only the projects `held` names: a stage not seeded holds none. */63 const holding =64 (held: readonly string[]) =>65 ({ authorized, body, method, path }: Seen): Reply => {66 if (method === "GET" && path === "/") {25 unmodified lines92 93 return { status: 404 };94 };95 103-/**104- * The platform as smoke expects to find it: healthy, OAuth's resource105- * metadata published, MCP closed to anyone without a credential, anonymous106- * reads open, the seeded example `oscabriel/datekit` held and no repo it doesn't107- * hold, and a `/` that names MCP and the CLI's installer.108- */96 const healthy = holding(["oscabriel/datekit"]);97 111-/**112- * A platform whose 401 gate is gone and whose stage is down: `/health` and113- * `/rpc` break, MCP opens to anyone, git's paths answer 200, and `/` is114- * gone.115- */98 const broken = (seen: Seen): Reply => {99 if (seen.path === "/") {100 return { status: 404 };101 }16 unmodified lines118 119 return healthy(seen);120 };121 140-/** `answer` served on an ephemeral local port, for the test's scope: its origin. */122 const fakePlatform = (answer: (seen: Seen) => Reply) =>123 Effect.gen(function* () {124 const app = Effect.gen(function* () {125 const request = yield* HttpServerRequest.HttpServerRequest;53 unmodified lines179 ).toBeTruthy();180 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))181 );182 202- // Live on dev-oscabriel: the first smoke after the first deploy got203- // a 500 from /health and a defect from the first Project DO call, and a204- // second run seconds later passed every probe.183+ // Seen live: the first smoke after a first deploy got a 500 from /health and184+ // a defect from the first Project DO call; a run seconds later passed.185 it.live(186 "asks again while a fresh deploy answers with a server error or a defect, and passes once it settles",187 () =>188 Effect.gen(function* () {37 unmodified lines226 it.live(227 "asks / again while the version before a deploy still answers it with 404, and passes once it settles",228 () =>229 Effect.gen(function* () {250- // a demo deploy that added `/`: smoke ran as the upload finished, and the230+ // A deploy that added `/`: smoke ran as the upload finished, and the231 // version before, which has no `/`, answered it once more with 404.232 const asked = { root: 0 };233 234 const origin = yield* fakePlatform((seen) => {62 unmodified lines297 }).pipe(Effect.provide(FetchHttpClient.layer))298 );299 });300 321-/**322- * The web as smoke expects to find it: its front page renders, its323- * `/llms.txt` answers with the Markdown it builds from the platform's324- * project list, which only a web that reaches the platform can, and so do325- * a seeded example's `llms.txt` and ask, and the agent skills' index.326- */301 const healthyWeb = ({ method, path }: Seen): Reply => {302 if (method === "GET" && path === "/") {303 return {304 body: '<!DOCTYPE html><html lang="en"><head></head><body></body></html>',155 unmodified lines460 });461 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))462 );463 490- // Live on dev-oscabriel: smoke ran 4 s after the web Worker's first491- // deploy, and its new workers.dev hostname answered 404 to both probes; a492- // run seconds later passed both.464+ // Seen live: smoke ran 4 s after the web Worker's first deploy, and its new465+ // workers.dev hostname answered 404; a run seconds later passed.466 it.live(467 "asks the web again while a first deploy's hostname answers 404, and passes once it settles",468 () =>469 Effect.gen(function* () {23 unmodified lines493 },494 probes: [...probes],495 });496 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)),524- // Five paths, each asked three times a second apart.497 30_000498 );499 500 it.live(154 unmodified lines655 Schema.is(SmokeFailed)(failed)656 ? failed.failures.map(({ probe }) => probe)657 : []658 ).toStrictEqual(["health"]);687- // `runMain` prints a failure as its tag and its message, and nothing else.659 expect(failed.message).toBe(`health failed at ${origin}`);660 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))661 );662 663 it.live("probes the web at --web-url, and only there, beside --url", () =>664 Effect.gen(function* () {665 const origin = yield* fakePlatform(healthy);695- // A web that answers, wrongly: JSON where a page and Markdown belong696- // (only the agent skills' index is JSON).666 const web = yield* fakePlatform(() => ({ body: "{}", status: 200 }));667 668 yield* main(["--stage", "dev-oscabriel", "--url", origin]);669 25 unmodified linesmodified:packages/config/test/swarm-herdr.test.ts+3 added-77 removed
1-/**2- * The swarm's herdr view: six contributors in six herdr panes and a counter3- * pane, for the video. The view decides only where a harness runs and how a4- * prompt reaches it; the verdict loop and its outcomes (from5- * `<cli> status --json`, never pane text) are `swarm-loop.test.ts`'s. The counter follows the6- * project's `watch` and counts claims, pushes and landings.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { AnswerView } from "@repo/protocol/domain/answer";4 import { ClaimView } from "@repo/protocol/domain/claim";59 unmodified lines64 );65 66 const sha = (digit: number) => CommitSha.make(String(digit).repeat(40));67 75-/** The `n`th event's place in the project's sequence, and its time. */68 const stamp = (n: number) => ({69 at: DateTime.makeUnsafe(70 `2026-10-08T12:${String(10 + n).padStart(2, "0")}:00.000Z`71 ),72 seq: 100 + n,73 });74 83-/**84- * A take's events: six claims, nine pushes (three agents pushed twice), four85- * landings, and events the counter does not count (a verdict, a released86- * claim, an ask that opened).87- */75 const takeEvents: readonly ProjectEvent[] = [76 ...children.map((ask, at) =>77 ProjectEvent.cases.Claimed.make({78 ...stamp(at),184 unmodified lines263 })264 );265 });266 280-/** The env names the CLI reads, spelled from the brand. */267 const SLUG = Brand.slug.toUpperCase();268 269 const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";270 271 const tokenOf = (handle: string) =>272 `${handle}-token-0123456789abcdef0123456789ab`;273 288-/** Whose token `env` carries, if anyone's. */274 const holderOf = (env: Readonly<Record<string, string | undefined>>) =>275 handles.find((handle) => env[`${SLUG}_TOKEN`] === tokenOf(handle));276 292-/** One command the fake world was asked to run. */277 interface Spawned {278 readonly command: string;279 readonly args: readonly string[];280 readonly env: Readonly<Record<string, string | undefined>>;281 }282 299-/** How a faked command ends: its exit code and what it printed. */283 interface Ending {284 readonly code?: number;285 readonly stdout?: string;286 readonly stderr?: string;287 }288 289 const bytes = (text: string) => Stream.make(new TextEncoder().encode(text));290 308-/**309- * A `ChildProcessSpawner` that runs nothing: it records each command and310- * ends it as `answer` says.311- */291 const fakeSpawner = (answer: (call: Spawned) => Effect.Effect<Ending>) =>292 Effect.gen(function* () {293 const spawned = yield* Ref.make<readonly Spawned[]>([]);294 34 unmodified lines329 spawned: Ref.get(spawned),330 };331 });332 354-/** A swarm fixture's text. */333 const fixture = (name: string) =>334 Effect.gen(function* () {335 const fs = yield* FileSystem.FileSystem;336 const path = yield* Path.Path;16 unmodified lines353 })354 )355 );356 379-/** `handle`'s answer to `ask`, the `n`th they pushed, with its outcome. */357 const answerOf = (358 handle: string,359 ask: AskId,360 n: number,7 unmodified lines368 });369 370 const landed = Outcome.cases.Landed.make({ sha: LandedSha.make(sha(9)) });371 395-/**396- * What `handle`'s `<cli> status --json` prints on its `call`th read: wren's397- * first answer is refused for leaving its territory and the next one lands;398- * everyone else's first answer lands.399- */372 const statusOf = (handle: string, call: number) => {373 const ask = children[handles.indexOf(handle)] ?? AskId.make("unknown");374 375 const refused = answerOf(15 unmodified lines391 v: 1,392 });393 };394 423-/** herdr's answer for a pane it made. */395 const paneJson = (pane: string) =>396 JSON.stringify({397 id: "cli:pane:split",398 result: { pane: { pane_id: pane, workspace_id: "w9" }, type: "pane_info" },399 });400 430-/** herdr's answer for an agent that is idle and ready for input. */401 const agentJson = (name: string, type: string) =>402 JSON.stringify({403 id: `cli:agent:${type}`,404 result: {7 unmodified lines412 type,413 },414 });415 446-/** What `<cli> claim <ask> --json` prints for `handle`. */416 const claimOf = (ask: string, handle: string) => {417 const fork = `burrow--${ask}--${handle}`;418 419 return JSON.stringify({17 unmodified lines437 v: 1,438 });439 };440 472-/**473- * The platform, git and herdr, faked for a whole `--view herdr` run: the474- * CLI's `asks`, `ask` and `claim` answer from the fixtures, each475- * contributor's `status` from `statusOf`, git and `mkfifo` succeed, herdr476- * makes panes `w9:p1`, `w9:p2`, … and every agent settles idle, and the477- * counter's `watch` hears nothing new. `replay` is how the counter's read478- * of where the project stands ends: an empty replay unless a test says.479- */441 const herdrWorld = (replay: Ending) =>442 Effect.gen(function* () {443 const panes = yield* Ref.make(1);444 const reads = yield* Ref.make(new Map<string, number>());65 unmodified lines510 if (call.command !== "curl") {511 return Effect.map(answer(call), (stdout) => ({ stdout }));512 }513 553- // The read of where the project stands is plain JSON; the follow hears nothing.514 return Effect.succeed(515 call.args.includes("content-type: application/json") ? replay : {}516 );517 });518 });519 560-/** `watch`'s plain JSON replay of a project that holds no event yet. */520 const emptyReplay: Ending = {521 stdout:522 '[{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',523 };524 566-/** What herdr puts in the env of a process in one of its panes. */525 const inAPane = { HERDR_ENV: "1" };526 569-/**570- * `main --view herdr` for every contributor over `herdrWorld`, from a herdr571- * pane unless `herdrEnv` says otherwise, the counter's read of the project572- * ending as `replay`, with `.swarm/` and the ledger in a temp dir.573- */527 const herdrRunWith = (528 herdrEnv: Readonly<Record<string, string>>,529 replay: Ending = emptyReplay530 ) =>43 unmodified lines574 ),575 Effect.result576 );577 625- // The TestClock's epoch names the run.578 const run = `${swarm}/19700101-000000`;579 const summary = `${run}/agents.json`;580 const wrensScript = `${run}/wren/pane-shell`;581 13 unmodified lines595 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));596 597 const herdrRun = herdrRunWith(inAPane);598 647-/** The herdr calls of a run, as argv. */599 const herdrCalls = (spawned: readonly Spawned[]) =>600 spawned.flatMap(({ args, command }) => (command === "herdr" ? [args] : []));601 651-/** The `agent <verb>` calls among `calls`, by the agent's name. */602 const agentCalls = (calls: readonly (readonly string[])[], verb: string) =>603 calls.flatMap((call) =>604 call[0] === "agent" && call[1] === verb605 ? [{ args: call, name: call[2] ?? "" }]606 : []607 );608 659-/** The pane each contributor's harness runs in: the layout's order over `w9:p1`, `w9:p2`, …. */609 const paneOf = new Map([610 ["wren", "w9:p1"],611 ["counter", "w9:p2"],612 ["marisol", "w9:p3"],97 unmodified lines710 .toSorted(byName)711 .map(({ args }) => args)712 );713 // wren's harness is Claude Code, started with the headless run's765- // safety flags: every tool allowed, no MCP server of the user's.714+ // safety flags: every tool allowed, no MCP server of the machine's own.715 expect(716 starts.find(({ name }) => name === "wren")?.args.slice(9)717 ).toStrictEqual([718 "--",140 unmodified lines859 })860 );861 });862 914-/** What herdr's detection text shows while Claude Code 2.1.293 asks whether to trust a new folder. */863 const trustQuestion = [864 " Accessing workspace:",865 "",866 " Quick safety check: Is this a project you created or one you trust?",1 unmodified line868 " ❯ No, exit",869 " Yes, I trust this folder",870 ].join("\n");871 924-/**925- * …and then whether to import the CLAUDE.md files above the clone, "No"926- * under the cursor (live, Enter left the clone's927- * `hasClaudeMdExternalIncludesApproved` false).928- */872+/** …and then whether to import the CLAUDE.md files above the clone, "No" under the cursor. */873 const importsQuestion = [874 " Allow external CLAUDE.md file imports?",875 "",876 " ❯ No, disable external imports",1 unmodified line878 ].join("\n");879 880 const [wren] = roster;881 938-/** wren's workspace for run `r1`. */882 const wrensWorkspace: AgentWorkspace = {883 clone: "/work/.swarm/r1/wren/clone",884 dir: "/work/.swarm/r1/wren",885 env: { [`${SLUG}_TOKEN`]: tokenOf("wren") },886 redacted: [`${SLUG}_TOKEN`],887 };888 946-/** The first of `queue`, taken off it unless it is the last. */889 const takeFrom = (queue: Ref.Ref<readonly string[]>) =>890 Ref.modify(queue, (all) => [891 all[0] ?? "",892 all.length > 1 ? all.slice(1) : all,893 ]);894 953-/**954- * wren's first attempt in herdr's pane `w9:p1`, where herdr finds Claude955- * Code blocked at startup: each `agent get` says the next of `states`956- * (`blocked` until the last), and each `agent read` shows the next of957- * `screens`. Files are kept in memory, so the TestClock moves as `clock`958- * says, deterministically.959- */895 const blockedStart = (input: {896 readonly states: readonly string[];897 readonly screens: readonly string[];898 readonly clock: Effect.Effect<void>;135 unmodified lines1034 })1035 );1036 });1037 1103-/**1104- * What dev-oscabriel's `/rpc` answered `watch` for burrow over plain JSON1105- * on 2026-10-08 (two of its eight events, the others cut): the frames at1106- * once, then the exit.1107- */1038 const replayed = [1039 '[{"_tag":"Chunk","requestId":"1","values":[',1040 '{"_tag":"AskOpened","at":"2026-10-08T05:21:35.148Z","seq":7,"ask":{"ask":"drop-legacy-fetch-burrow-notify","blockedBy":[],"claimed":false,"kind":"migrate","territory":"@burrow/notify","want":"@burrow/notify: 1 caller of legacyFetch → http.get"}},',1041 '{"_tag":"AskOpened","at":"2026-10-08T05:21:35.148Z","seq":8,"ask":{"ask":"drop-legacy-fetch-burrow-search","blockedBy":[],"claimed":false,"kind":"migrate","territory":"@burrow/search","want":"@burrow/search: 1 caller of legacyFetch → http.get"}}',1042 ']},{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',1043 ].join("");1044 1115-/**1116- * The framed stream's lines, as dev-oscabriel sends them over NDJSON: one1117- * frame per line. The first repeats an event the counter already heard1118- * (a claim, so a counter that heard it twice would say so).1119- */1045+/** The first frame repeats an event the counter already heard, so a double count would show. */1046 const streamed = [1047 '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:00:00.000Z","seq":8,"ask":"drop-legacy-fetch-burrow-billing","claimant":"tamsin"}]}',1048 '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:05:00.000Z","seq":9,"ask":"drop-legacy-fetch-burrow-auth","claimant":"wren"}]}',1049 `{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Pushed","at":"2026-10-08T12:06:00.000Z","seq":10,"ask":"drop-legacy-fetch-burrow-auth","head":"${"1".repeat(40)}"},{"_tag":"Released","at":"2026-10-08T12:07:00.000Z","seq":11,"ask":"drop-legacy-fetch-burrow-kit"}]}`,167 unmodified linesmodified:packages/config/test/swarm-loop.test.ts+3 added-37 removed
1-/**2- * The swarm's verdict loop: each contributor's harness started3- * headless on the brief, and every refusal their answer meets sent back into4- * the same session, at most three times. The loop reads outcomes only from5- * the contributor's `<cli> status --json`; a harness's output gives it the6- * session id, that the session settled, and the tokens it used.7- *8- * The harness output under `fixtures/swarm/harness-output/<harness>/` is9- * what each installed harness printed for one headless start and one resume10- * on 2026-10-08, its local paths replaced and the user's own setup (tool,11- * MCP, plugin and skill lists, pi's system prompt) left out.12- */1+// `fixtures/swarm/harness-output/<harness>/` is what each harness printed for2+// one headless start and one resume, its local paths replaced and the3+// machine's own setup (tool, MCP, plugin and skill lists) left out.4 import { NodeServices } from "@effect/platform-node";5 import { describe, expect, it } from "@effect/vitest";6 import { AnswerView } from "@repo/protocol/domain/answer";7 import { ClaimView } from "@repo/protocol/domain/claim";47 unmodified lines55 import type { AgentWorkspace } from "../../../scripts/lib/swarm/workspace.ts";56 import { Brand } from "../../brand/src/index.ts";57 import { repoRoot } from "./root.ts";58 68-/** The env names the CLI reads, spelled from the brand. */59 const SLUG = Brand.slug.toUpperCase();60 61 const token = "wren-token-0123456789abcdef0123456789abcdef";62 63 const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";64 65 const ask = AskId.make("drop-legacy-fetch-burrow-auth");66 77-/** A harness's recorded output: `start`, `resume`, or OpenCode's `refused-model`. */67 const recorded = (68 harness: Harness,69 run: "start" | "resume" | "refused-model"70 ) =>14 unmodified lines85 86 return text.split("\n").filter((line) => line !== "");87 }).pipe(Effect.provide(NodeServices.layer));88 100-/** Everything one recorded run's lines say, in order. */89 const heard = (driver: HarnessDriver, lines: readonly string[]) =>90 lines.flatMap(driver.parse);91 92 const sessionsIn = (events: readonly HarnessEvent[]) =>93 events.flatMap((event) =>94 HarnessEvent.$is("SessionStarted")(event) ? [event.id] : []95 );96 109-// The commits of four answers, and the landing of the last.97 const heads = ["1", "2", "3", "4"].map((digit) =>98 CommitSha.make(digit.repeat(40))99 );100 101 const landing = LandedSha.make(CommitSha.make("a".repeat(40)));102 116-/** One answer to the ask, `n` seconds after noon, with its outcome. */103 const answer = (n: number, outcome: Outcome): AnswerView => ({104 ask,105 at: DateTime.makeUnsafe(`2026-10-08T12:00:0${n}.000Z`),106 head: heads[n] ?? CommitSha.make("f".repeat(40)),43 unmodified lines150 })151 )152 );153 168-/** What `<cli> status --json` prints for wren with these answers. */154 const status = (...answers: readonly AnswerView[]) =>155 Schema.encodeSync(StatusJson)({156 command: "status",157 data: { answers, claims: [wrensClaim], handle: Handle.make("wren") },158 ok: true,159 v: 1,160 });161 177-/** One command the fake spawner was asked to run. */162 interface Spawned {163 readonly command: string;164 readonly args: readonly string[];165 readonly cwd: string | undefined;166 readonly env: Readonly<Record<string, string | undefined>>;167 readonly extendEnv: boolean | undefined;168 }169 186-/** How a scripted harness run goes: its stdout lines and exit code, or it never ends. */170 type HarnessRun =171 | { readonly lines: readonly string[]; readonly code?: number }172 | { readonly stalls: readonly string[] };173 174 const bytes = (text: string) => new TextEncoder().encode(text);175 193-/** A process handle that prints `stdout` and ends with `exitCode`. */176 const handleOf = (input: {177 readonly stdout: Stream.Stream<Uint8Array>;178 readonly exitCode: Effect.Effect<number>;179 }) =>10 unmodified lines190 stdout: input.stdout,191 unref: Effect.succeed(Effect.void),192 });193 212-/**213- * A `ChildProcessSpawner` that runs nothing. The workspace's CLI answers214- * `status` with the next of `statuses` (the last one again once they run215- * out); any other command is a harness, and plays the next of `harness`.216- */194 const fakeWorld = (script: {195 readonly harness: readonly HarnessRun[];196 readonly statuses: readonly string[];197 }) =>81 unmodified lines279 );280 }),281 });282 306-/** wren's workspace for run `r1`. */283 const dir = "/work/.swarm/r1/wren";284 285 const wrensWorkspace: AgentWorkspace = {286 clone: `${dir}/clone`,7 unmodified lines294 },295 redacted: [`${SLUG}_TOKEN`],296 };297 322-/** The swarm's own env: the user's HOME, and secrets no harness may see. */298 const swarmEnv = ConfigProvider.fromEnv({299 env: {300 CLAUDECODE: "1",301 CLOUDFLARE_API_TOKEN: "cf-secret",3 unmodified lines305 });306 307 const [wren, tamsin, ivo] = roster;308 334-/**335- * `runAgent` for `contributor` on burrow's auth child, over a fake world and336- * a file system in memory. It runs forked, so `clock` can move the TestClock337- * while it runs.338- */309 const agentRun = (input: {310 readonly harness: readonly HarnessRun[];311 readonly statuses: readonly string[];312 readonly contributor?: Assignment["contributor"];45 unmodified lines358 spawned: yield* world.spawned,359 };360 });361 392-/** The prompt a harness run carried: its last argument. */362 const promptOf = (run: Spawned | undefined) => run?.args.at(-1) ?? "";363 364 describe("the verdict loop", () => {365 it.effect(261 unmodified lines627 () =>628 Effect.gen(function* () {629 const start = yield* recorded("claude-code", "start");630 662- // The brief tells the agent to read status and push again, so one663- // session can push several answers before it settles.631 const { harnessRuns, result } = yield* agentRun({632 harness: [{ lines: start }],633 statuses: [634 status(168 unmodified lines803 })804 );805 });806 840-/** A workspace for the golden argv: `/work/.swarm/r1/<handle>`. */807 const goldenWorkspace = (handle: string): AgentWorkspace => ({808 clone: `/work/.swarm/r1/${handle}/clone`,809 dir: `/work/.swarm/r1/${handle}`,810 env: {},286 unmodified linesmodified:packages/config/test/swarm.test.ts+2 added-41 removed
1-/**2- * The swarm: its plan for a split family, its people, each3- * contributor's brief and workspace, and the run's summary file. The burrow4- * fixtures are what `<cli> asks` and `<cli> ask` printed for burrow's5- * `drop-legacy-fetch` family on the dev stage (2026-10-08).6- */1+// The burrow fixtures are what `<cli> asks` and `<cli> ask` printed for2+// burrow's `drop-legacy-fetch` family on a dev stage.3 import { NodeServices } from "@effect/platform-node";4 import { describe, expect, it } from "@effect/vitest";5 import { Ask, AskListing } from "@repo/protocol/domain/ask";6 import { ClaimView } from "@repo/protocol/domain/claim";47 unmodified lines54 const burrow = ProjectName.make("oscabriel/burrow");55 56 const ListedAsks = Envelope(Schema.Struct({ asks: Schema.Array(AskListing) }));57 62-/** What `<cli> claim <ask> --json` prints. */58 const Claimed = Envelope(Schema.Struct({ claim: ClaimView }));59 65-/** What `<cli> ask <ask> --json` prints, when it shows the ask. */60 const ShownAsk = Schema.Struct({61 command: Schema.Literal("ask"),62 data: Schema.Struct({ ask: Ask, brief: Schema.NonEmptyString }),63 ok: Schema.Literal(true),64 v: Schema.Literal(1),65 });66 73-/** A fixture's text. */67 const fixture = (name: string) =>68 Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;2 unmodified lines73 path.join("test", "fixtures", "swarm", name)74 );75 });76 84-/** burrow's open asks, as `<cli> asks --project burrow --json` listed them. */77 const burrowAsks = Effect.gen(function* () {78 const envelope = yield* Schema.decodeEffect(79 Schema.fromJsonString(ListedAsks)80 )(yield* fixture("list-asks.json"));272 unmodified lines353 expect(354 roster.flatMap(({ adapter, handle }) => (adapter ? [handle] : []))355 ).toStrictEqual(["pell"]);356 365- // An Anthropic id, OpenCode's GPT, an Amp mode, then pi's three.357 const models = [358 /^claude-/u,359 /^opencode-go\/gpt-/u,360 /^(?:low|medium|high|ultra)$/u,36 unmodified lines397 );398 });399 });400 410-/** The ask page `<cli> ask` printed for burrow's auth child. */401 const authPage = Effect.gen(function* () {402 const text = (yield* fixture("show-ask.json")).replaceAll(403 "{configDir}",404 Brand.configDir54 unmodified lines459 );460 });461 });462 473-/** One command a fake spawner was asked to run. */463 interface Spawned {464 readonly command: string;465 readonly args: readonly string[];466 readonly cwd: string | undefined;467 readonly env: Readonly<Record<string, string | undefined>>;468 }469 481-/**482- * A `ChildProcessSpawner` that runs nothing: it records each command and483- * answers with what `answer` gives it (exit 0 and no output by default).484- * `answer` also gets how many commands came before this one.485- */470 const fakeSpawner = (471 answer: (472 spawned: Spawned,473 before: number49 unmodified lines523 spawned: Ref.get(spawned),524 };525 });526 543-/** The env names the CLI reads, spelled from the brand. */527 const SLUG = Brand.slug.toUpperCase();528 529 const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";530 548-/** wren's claim of burrow's auth child, as `<cli> claim --json` gives it. */531 const wrensClaim = Schema.decodeSync(ClaimView)({532 ask: "drop-legacy-fetch-burrow-auth",533 base: "9998ebe62c2f282d148b1d806372484916cc2548",534 checkCommand: `${Brand.cli} check`,8 unmodified lines543 });544 545 const wrensToken = "wren-token-0123456789abcdef0123456789abcdef";546 565-/** What git prints when the gateway answers 404 for the fork: it is not made yet. */547 const forkNotMade = `remote: no repo ${wrensClaim.fork}548 fatal: repository '${wrensClaim.remote}/' not found549 `;550 570-/**571- * wren's workspace for run `r1`, below a temp dir, over a fake spawner572- * whose every clone exits `code`, or answers as `clone` says (given how573- * many clones came before it).574- */551 const wrensWorkspace = (552 code = 0,553 clone: (before: number) => {554 readonly code?: number;270 unmodified lines825 }).pipe(Effect.provide(NodeServices.layer))826 );827 });828 853-/** Why the flags `argv` make no run, or `accepted` when they make one. */829 const reasonOf = (argv: readonly string[]) =>830 optionsOf(argv).pipe(831 Effect.match({832 onFailure: ({ reason }) => reason,124 unmodified lines957 })958 );959 });960 986-/** What `main` prints, line by line, over a spawner that answers `asks` with the fixture. */961 const dryRun = (argv: readonly string[]) =>962 Effect.gen(function* () {963 const fs = yield* FileSystem.FileSystem;964 const swarm = yield* fs.makeTempDirectoryScoped();16 unmodified lines981 yield* main(argv).pipe(982 Effect.provide(fake.layer),983 Effect.provideService(SwarmDir, swarm),984 Effect.provideService(Console.Console, captured),1011- // No SESSION_TOKENS, nor any token: a dry run needs none.985 Effect.provideService(986 ConfigProvider.ConfigProvider,987 ConfigProvider.fromEnv({ env: {} })988 )153 unmodified lines1142 })1143 );1144 });1145 1173-/** A fictional person's token on the fake platform: never printed, never in an argv. */1146 const tokenOf = (handle: string) =>1147 `${handle}-token-0123456789abcdef0123456789ab`;1148 1177-/**1178- * `main` without `--dry-run`, over a fake platform: the CLI's `asks`, `ask`1179- * and `claim` answer from the fixtures, git succeeds, and `SESSION_TOKENS`1180- * holds `people`. The ledger and `.swarm/` are temp files. Any other command1181- * (a harness, a workspace's `status`) exits 1 unless `otherwise` answers it.1182- */1149 const fullRun = (1150 people: readonly string[],1185- /** The contributor whose claim the platform refuses with `AskFull`, if any. */1151 refused?: string,1152 otherwise?: (call: Spawned) => Option.Option<{1153 readonly code?: number;1154 readonly stdout?: string;108 unmodified lines1263 ),1264 Effect.result1265 );1266 1302- // The TestClock's epoch names the run.1267 const summary = `${swarm}/19700101-000000/agents.json`;1268 1269 return {1270 agents: (yield* fs.exists(summary))89 unmodified lines1360 ["marisol", 0, {}],1361 ["dagny", 0, {}],1362 ["pell", 0, {}],1363 ]);1400- // No claim, no fork: ivo's is never recorded for teardown.1364 expect(1365 ledger1366 .map(({ name }) => name.split("--").at(-1) ?? "")1367 .toSorted((one, other) => one.localeCompare(other))8 unmodified lines1376 const started = yield* fixture(1377 "harness-output/claude-code/start.jsonl"1378 ).pipe(Effect.provide(NodeServices.layer));1379 1417- // wren's Claude Code starts a session; the platform has no answer1418- // from wren yet, so the loop nudges once and asks status again.1380 const nothingYet = JSON.stringify({1381 command: "status",1382 data: { answers: [], claims: [], handle: "wren" },1383 ok: true,51 unmodified linesmodified:packages/config/test/teardown.test.ts+1 added-22 removed
1-/**2- * Teardown: `bun infra/teardown.ts` prints a plan, and only3- * `--apply` deletes it. The plan is the ledger's throwaways that the account4- * still lists, never a stage's own namespaces, never `witness`, never the5- * seeded examples, and never a name the ledger doesn't hold, whatever it is6- * called.7- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import {4 Console,33 unmodified lines38 const projects = "projects-dev-oscabriel";39 40 const layers = "layers-dev-oscabriel";41 49-/** One ledger line, made by `by` on the dev stage; a repo's names its namespace. */42 const made = (43 by: Created["by"],44 kind: Created["kind"],45 name: string,17 unmodified lines63 });64 65 const namespace = (name: string): Listed => ({ kind: "namespace", name });66 75-/** A smoke run's project and repos, and a `seed --as` swarm copy's. */67 const ledger: readonly Created[] = [68 made("smoke", "project", "smoke-r1"),69 made("smoke", "repo", "smoke-r1", projects),70 made("smoke", "repo", "smoke-r1--parse-year--bram", projects),7 unmodified lines78 ),79 made("seed", "repo", "datekit-805--maintainers", layers),80 ];81 91-/** What the account lists: every ledger repo, and much that isn't the ledger's. */82 const listed: readonly Listed[] = [83 repo("datekit"),84 repo("burrow"),85 repo("smoke-r1"),10 unmodified lines96 namespace("layers-demo"),97 namespace("witness"),98 ];99 110-/** Two imports of the preview repos, kept: each one's project and repo line. */100 const imports: readonly Created[] = [101 made("import", "project", "anyhow"),102 made("import", "repo", "anyhow", projects),103 made("import", "project", "ky"),159 unmodified lines263 ).toStrictEqual([]);264 });265 });266 278-/** A fresh ledger file in a temp dir, for the scope of one test. */267 const tempLedger = Effect.gen(function* () {268 const fs = yield* FileSystem.FileSystem;269 const path = yield* Path.Path;270 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "teardown-808-" });110 unmodified lines381 ]);382 });383 });384 397-/**398- * The account in memory: each namespace a memory `RepoHost` holding `repos`.399- * A namespace it doesn't hold, `witness` among them, dies when read.400- */385+/** A namespace it doesn't hold, `witness` among them, dies when read. */386 const memoryAccount = (repos: Readonly<Record<string, readonly string[]>>) =>387 Effect.gen(function* () {388 const read = yield* Ref.make<readonly string[]>([]);389 22 unmodified lines412 )413 )414 );415 431- /** Of `names`, those the namespace still holds. */416 const standing = (space: string, names: readonly string[]) =>417 Effect.gen(function* () {418 const host = yield* Effect.fromNullishOr(hosts.get(space)).pipe(419 Effect.orDie17 unmodified lines437 standing,438 };439 });440 457-/** A temp root with a ledger written from `entries` and no recording lock. */441 const tempRoot = (entries: readonly Created[]) =>442 Effect.gen(function* () {443 const fs = yield* FileSystem.FileSystem;444 const path = yield* Path.Path;6 unmodified lines451 452 return { ledgerFile, lock: path.join(dir, ".recording") };453 });454 472-/** `teardown(argv)` over `account`: how it ended, and what it printed. */455 const tornDown = (456 argv: readonly string[],457 account: TeardownAccount["Service"],458 files: { readonly ledgerFile: string; readonly lock: string }18 unmodified lines477 478 return { printed, result };479 });480 499-/** The dev stage's two namespaces as a smoke run, a swarm copy and the seed left them. */481 const devRepos = {482 [layers]: ["datekit--maintainers", "datekit-805--maintainers"],483 [projects]: [484 "datekit",6 unmodified lines491 "w3live-muyjz31t",492 ],493 };494 514-/** The ledger: `ledger` above, one repo already gone, and one in `witness`. */495 const devLedger: readonly Created[] = [496 ...ledger,497 made("smoke", "repo", "smoke-r0", projects),498 made("smoke", "repo", "smoke-r9", "witness"),132 unmodified lines631 it.live(632 "lists the kept imports apart, each once, never in the plan, and deletes none of them with --apply",633 () =>634 Effect.gen(function* () {655- // A `--tags` backfill records anyhow's repo a second time.635 const files = yield* tempRoot([636 ...devLedger,637 ...imports,638 {68 unmodified linesmodified:packages/config/test/verify.test.ts-2 removed
17 unmodified lines18 .scripts;19 });20 21 describe("verify", () => {22- // The gate guards the product's own behaviour: the lockfile, lint and23- // format, types, tests, the brand and the Workers' byte budgets.22 it.live("runs the product's checks, in order", () =>23 Effect.gen(function* () {24 const scripts = yield* rootScripts;25 28 unmodified linesmodified:packages/config/test/web-wiring.test.ts+4 added-23 removed
1-/**2- * The web Worker's wiring, read as data: it reaches the platform3- * only through the `PLATFORM` service binding and holds no storage binding of4- * any kind, in any stage (AGENTS.md principle 7); `#backend` picks the5- * in-process backend under `development` and the binding otherwise; the byte6- * alarm measures it; and the examples stay outside the workspaces.7- *8- * Each file's presence is asserted before it is read, so a missing file is a9- * failed assertion, not a load error.10- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Effect, FileSystem, Path, Schema } from "effect";4 7 unmodified lines12 } from "../../../infra/stages.ts";13 import { budgets, workers } from "../../../scripts/startup-budget.ts";14 import { repoRoot } from "./root.ts";15 26-/** A file under the repo root, as text, once its presence is asserted. */16 const presentText = (file: string) =>17 Effect.gen(function* () {18 const fs = yield* FileSystem.FileSystem;19 const path = yield* Path.Path;3 unmodified lines23 24 return yield* fs.readFileString(at);25 }).pipe(Effect.provide(NodeServices.layer));26 38-/** A JSON (or JSONC) file under the repo root, decoded by `schema`. */27 const presentJson = <S extends Schema.Top>(file: string, schema: S) =>28 Effect.flatMap(presentText(file), (text) =>29 Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(blankJsonc(text))30 );31 44-/** The binding kinds that would reach storage or run code: none in the web. */32 const STORAGE = [33 "artifacts",34 "d1_databases",35 "durable_objects",32 unmodified lines68 const RootManifest = Schema.Struct({69 workspaces: Schema.Struct({ packages: Schema.Array(Schema.String) }),70 });71 85-/**86- * Whether a workspace glob's parts match a folder's segments: `*` is one87- * segment, `**` any number of them.88- */72 const globMatches = (73 parts: readonly string[],74 segments: readonly string[]75 ): boolean => {67 unmodified lines143 }144 })145 );146 164- // ADR 0026: the edge keeps the web's answers only behind its entry, which165- // decides what may be kept; `vite dev` keeps nothing; and a kept page166- // never outlives its Worker version, whose hashed assets it names.147+ // The edge keeps the web's answers only behind its entry, which decides what148+ // may be kept; `vite dev` keeps nothing; and a kept page never outlives its149+ // Worker version, whose hashed assets it names.150 it.effect(151 "enters through src/server.ts, and turns Workers Cache on in each stage alone, per version",152 () =>153 Effect.gen(function* () {72 unmodified lines226 it("measures the web Worker", () => {227 expect(workers.map(({ dir }) => dir)).toContain("apps/web");228 });229 247- // Each Worker grows on its own, so each has limits of its own, about248- // 15% above its bundle as last measured (the platform's entry, its only249- // module, 1,679,675: both its limits at 1,900,000, 13% above).230+ // Each Worker has limits of its own, about 15% above its bundle as last measured.231 it("holds each Worker it measures to limits of its own", () => {232 expect(budgets).toStrictEqual({233 "apps/platform": { entry: 1_900_000, javascript: 1_900_000 },234 "apps/sandbox": { entry: 656_000, javascript: 656_000 },28 unmodified linesmodified: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- */1 import { AskId, RepoPath } from "@repo/protocol/ids";2 import { Array } from "effect";3 import type { Layer } from "effect";4 1 unmodified line6 import type { Drafter } from "../drafter.ts";7 import { DrafterMemory } from "../drafter/memory.ts";8 import type { DraftsAsked } from "../drafter/memory.ts";9 18-/** How many drafts a world gives before its drafter's script runs out. */10 const CANNED_DRAFTS = 64;11 12 export const cannedDraft = {13 current: "src/parse.ts reads no ordinal date.",17 unmodified lines31 },32 want: "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.",33 } satisfies DraftedAsk;34 44-/** The memory drafter, scripted with the canned draft for every attempt a world makes. */35 export 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 */6 import type { RepoHost } from "@repo/artifacts/repo-host";7 import { DraftRuns } from "@repo/project/draft-runs";8 import type { DraftParams } from "@repo/project/draft-runs";3 unmodified lines12 import type { Drafter } from "../drafter.ts";13 import { runDraft } from "../run.ts";14 import type { DraftSteps } from "../run.ts";15 26-/** What a round runs on. */16 export type InlinePorts = Projects | Drafter | RepoHost;17 29-/** Steps run once each, in process: a failure retried as its retries say, at once. */18 const inlineSteps: DraftSteps = {19 step: (_name, _schema, effect, retry) =>20 Effect.retry(effect, { times: retry?.limit ?? 0 }),21 };22 35-/** One round's key: its project, proposal and round. */23 const keyOf = ({ project, proposal, round }: DraftParams) =>24 `${project}/${proposal}/${round}`;25 39-/** `DraftRuns` that run each round in process, on the ports `portsOf` gives when it starts. */26 export const draftRunsInline = (27 portsOf: Effect.Effect<Context.Context<InlinePorts>>28 ): Layer.Layer<never> =>29 Layer.effect(35 unmodified lines65 };66 })67 );68 83-/**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- */69 export const withDraftRunsInline = <E, R>(70 projects: Layer.Layer<Projects, E, R>71 ): Layer.Layer<Projects, E, R | Drafter | RepoHost> =>72 Layer.effectContext(14 unmodified linesmodified: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.4 import { Effect, Hash, Layer, Predicate, Schema } from "effect";5 import type { JsonSchema } from "effect";6 7 import { DraftedAsk, DraftedReply, DraftFailed } from "../drafted.ts";1 unmodified line9 import { Drafter } from "../drafter.ts";10 import { systemPrompt, userPrompt } from "../prompt.ts";11 12 /**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 */16 export interface AiLike {17 readonly run: (model: string, inputs: ChatInputs) => Promise<object>;18 }19 25-/** One chat message. */20 export interface ChatMessage {21 readonly content: string;22 readonly role: "system" | "user";23 }24 31-/**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- */25 export interface ReasoningInputs {26 readonly reasoning_effort: "low";27 }28 40-/**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. */30 export type ChatInputs = Partial<ReasoningInputs> & {31 readonly max_completion_tokens: number;32 readonly messages: readonly ChatMessage[];33 readonly response_format: {3 unmodified lines37 readonly seed: number;38 readonly temperature: number;39 };40 57-/** What a model is asked with beyond the prompt: its output cap, and how hard it reasons. */41 export 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 }45 64-/** What a model not in `MODEL_SETTINGS` is asked with: `DRAFT_MODEL`'s settings. */46 const DEFAULT_SETTINGS: ModelSettings = { max_completion_tokens: 12_000 };47 48 /**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 */52 const FALLBACK_SETTINGS: ModelSettings = {53 max_completion_tokens: 32_000,54 reasoning: { reasoning_effort: "low" },55 };56 78-/** Settings by Workers AI model id; `DRAFT_MODEL` (kimi-k2.7-code) takes the defaults. */57 const 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 ]);62 85-/** What `model` is asked with beyond the prompt; the defaults for a model not listed. */63 export const modelSettings = (model: string): ModelSettings =>64 MODEL_SETTINGS.get(model) ?? DEFAULT_SETTINGS;65 89-/** `DraftedAsk` as JSON Schema, for `response_format`: an object root, no `$ref`. */66 const responseSchema = (() => {67 const { definitions, schema } = Schema.toJsonSchemaDocument(DraftedAsk);68 69 return Object.keys(definitions).length === 070 ? schema71 : { ...schema, $defs: definitions };72 })();73 98-/** What a chat reply carries: OpenAI's `choices`, or Workers AI's own `response`. */74 const Reply = Schema.Union([75 Schema.Struct({76 choices: Schema.NonEmptyArray(77 Schema.Struct({ message: Schema.Struct({ content: Schema.String }) })10 unmodified lines88 const decodeReply = Schema.decodeUnknownEffect(Reply);89 90 const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));91 117-/** A reply's fields, where one sentence may stand for a list of them. */92 const decodeDrafted = Schema.decodeUnknownEffect(DraftedReply);93 120-/** A reply wrapped in one Markdown code fence, unwrapped. */94 const unfenced = (text: string) =>95 /^\s*```[\w-]*[^\S\n]*\n(?<body>[\s\S]*?)\n?```\s*$/u.exec(text)?.groups96 ?.body ?? text;97 98 const failed = (reason: DraftFailed["reason"]) => new DraftFailed({ reason });99 127-/**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- */100 const draftedOf = (101 reply: typeof Reply.Type102 ): Effect.Effect<DraftedAsk, DraftFailed> => {103 const content =8 unmodified lines112 (parsed) => Effect.mapError(decodeDrafted(parsed), () => failed("schema"))113 );114 };115 147-/** Why a call to the binding threw, from its text: Workers AI names its errors by code. */116 const reasonOf = (thrown: string): DraftFailed["reason"] => {117 if (/\b(?:429|3040)\b|rate.?limit/iu.test(thrown)) {118 return "rate-limited";119 }8 unmodified lines128 `${input.context.project}:${input.context.at}:${input.attempt}:${input.want}`129 )130 );131 164-/** The drafter over `ai`, asking `model` (the platform's `DRAFT_MODEL`) with its settings. */132 export const DrafterWorkersAi = (133 ai: AiLike,134 model: string135 ): Layer.Layer<Drafter> => {46 unmodified linesmodified: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- */1 import { Context, Effect, Layer, Ref, Schema } from "effect";2 3 import { DraftFailed } from "../drafted.ts";4 import type { DraftedAsk, DraftInput } from "../drafted.ts";5 import { Drafter } from "../drafter.ts";6 7 const isFailure = Schema.is(DraftFailed);8 15-/** What the memory drafter was asked, in order. */9 export class DraftsAsked extends Context.Service<10 DraftsAsked,11 { readonly inputs: Effect.Effect<readonly DraftInput[]> }12 >()("drafting/DraftsAsked") {}13 21-/** A drafter that answers `script` in order, one entry per call. */14 export const DrafterMemory = (15 script: readonly (DraftedAsk | DraftFailed)[]16 ): Layer.Layer<Drafter | DraftsAsked> =>17 Layer.effectContext(24 unmodified linesmodified: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 */12 import { Brand } from "@repo/brand";13 import type { ConfigFile } from "@repo/protocol/domain/common";14 import { RepoPath } from "@repo/protocol/ids";15 import { Array, Effect, Option, Order, Schema, pipe } from "effect";16 21-/** The bytes the model reads in all, about 50k tokens. */17 const defaultBudget = 200 * 1024;18 24-/** The most of one file the model reads. */19 const perFile = 40 * 1024;20 27-/** Room kept for a cut file's marker. */21 const markerRoom = 64;22 30-/** Source files ranked by the want, when no territory is given. */23 const rankedFiles = 12;24 25 const manifests = new Set([26 "Cargo.toml",70 unmodified lines97 98 return name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : "";99 };100 109-/** A layer's file, a held-back check, or an env file: never read. */101 const isWithheld = (path: string) =>102 path.startsWith(`${Brand.configDir}/layers/`) ||103 segmentsOf(path).some(104 (segment) =>18 unmodified lines123 path.startsWith(askFolder) &&124 path.endsWith(askSuffix) &&125 !path.slice(askFolder.length).includes("/");126 136-/** A file's name without its extensions: `add.test.ts` is `add`. */127 const stemOf = (path: string) => baseName(path).split(".")[0] ?? "";128 139-/** A word and its camel-case parts, lower-cased: `addMonths` → addmonths, add, months. */129 const wordsOf = (text: string): readonly string[] =>130 text131 .split(/[^A-Za-z0-9]+/u)132 .flatMap((word) =>7 unmodified lines140 ]141 )142 .filter((word) => word.length >= 3 && !stopWords.has(word));143 155-/** How many of the want's words a path shares, its extension left out. */144 const 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 lines150 readonly path: string;151 readonly score: number;152 }153 166-/** Most shared words first, then by path. */154 const byScore = Order.combine(155 Order.mapInput(Order.flip(Order.Number), ({ score }: Ranked) => score),156 Order.mapInput(Order.String, ({ path }: Ranked) => path)157 );158 172-/** The source files whose path shares a word with the want, most first, at most `rankedFiles`. */159 const ranked = (paths: readonly string[], want: ReadonlySet<string>) =>160 paths161 .flatMap((path): Ranked[] => {162 const score = isSource(path) ? overlap(want, path) : 0;3 unmodified lines166 .toSorted(byScore)167 .slice(0, rankedFiles)168 .map(({ path }) => path);169 184-/** The tests beside a source file: the same stem with a test suffix, anywhere. */170 const siblingTests = (tree: readonly string[], source: string) => {171 const stem = stemOf(source);172 173 return tree.filter(5 unmodified lines179 };180 181 const decodeLiteral = Schema.decodeOption(Schema.fromJsonString(Schema.String));182 198-/** The test file an ask file names in its `path`, when it names one. */183 const 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 );190 207-/** The folder the picked style example's test sits in: the project's ask-test folder. */191 export const askTestFolderOf = (192 files: readonly ConfigFile[]193 ): Option.Option<string> =>194 pipe(5 unmodified lines200 const encoder = new TextEncoder();201 202 const decoder = new TextDecoder();203 221-/** `content` cut to at most `room` bytes and its marker, or none when nothing fits. */204 const cut = (content: string, room: number): Option.Option<string> => {205 const bytes = encoder.encode(content);206 207 if (bytes.length <= Math.min(room, perFile)) {8 unmodified lines216 `${decoder.decode(bytes.slice(0, shown)).replace(/�$/u, "")}\n[cut: the first ${shown} of ${bytes.length} bytes]\n`217 );218 };219 238-/**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- */220 export const pickFiles = (221 tree: readonly RepoPath[],222 input: { readonly want: string; readonly territory?: readonly RepoPath[] },223 read: (path: RepoPath) => Effect.Effect<string>,78 unmodified linesmodified: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. */2 import { Brand } from "@repo/brand";3 import { AtLeastOne } from "@repo/protocol/domain/common";4 import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";5 import { Schema, SchemaTransformation } from "effect";6 14-/** A string the model writes, bounded so no reply fills the Worker. */7+/** Bounded so no reply fills the Worker. */8 const Text = Schema.NonEmptyString.check(Schema.isMaxLength(4000));9 17-/** A path in the tree as git names it: relative, with no empty, `.` or `..` segment. */10 const TreePath = RepoPath.check(11 Schema.makeFilter(12 (path: string) =>13 path7 unmodified lines21 )22 );23 24 /**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 */28 const TestPath = TreePath.check(29 Schema.makeFilter(30 (path: string) =>3 unmodified lines34 { expected: `a path outside ${Brand.configDir}/` }35 )36 );37 47-/** One ask, drafted: only `fix` asks are drafted. */38 export 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 });53 54 export type DraftedAsk = typeof DraftedAsk.Type;55 56 /**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 */60 const Sentences = Schema.Union([61 Schema.Array(Text),62 Text.pipe(6 unmodified lines69 )70 ),71 ]);72 89-/**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- */73 export const DraftedReply = Schema.Struct({74 ...DraftedAsk.fields,75 context: Schema.optionalKey(Sentences),76 outOfScope: Schema.optionalKey(Sentences),77 });78 100-/** One file the drafter reads, as text. */79 export const ContextFile = Schema.Struct({80 content: Schema.String,81 path: RepoPath,82 });83 84 export type ContextFile = typeof ContextFile.Type;85 108-/**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- */86 export const DraftContext = Schema.Struct({87 at: LandedSha,88 files: Schema.Array(ContextFile),89 policy: Schema.String,1 unmodified line91 });92 93 export type DraftContext = typeof DraftContext.Type;94 121-/** One attempt's question: the want, what it reads, and what went wrong before. */95 export 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 });103 104 export type DraftInput = typeof DraftInput.Type;105 135-/**136- * The model gave no draft: its reply was no JSON, or not the schema's, it137- * was rate-limited, or it failed.138- */106 export class DraftFailed extends Schema.TaggedError<DraftFailed>()(107 "DraftFailed",108 {109 reason: Schema.Literals([7 unmodified linesmodified: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- */1 import { Context } from "effect";2 import type { Effect } from "effect";3 4 import type { DraftFailed, DraftedAsk, DraftInput } from "./drafted.ts";5 6 export 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 linemodified: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.3 import { Brand } from "@repo/brand";4 import type { PublicPolicy } from "@repo/protocol/domain/policy";5 import type { Refusal } from "@repo/protocol/refusal";6 import { explain } from "@repo/protocol/render";7 import { Option } from "effect";8 9 import type { DraftInput } from "./drafted.ts";10 20-/** The most of a failing run's output an attempt is shown: its last 4 KB. */11 const tailBytes = 4 * 1024;12 23-/** Why the last attempt's draft did not open: the gate's refusal, its diagnosis and the run's output. */13 export 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 }18 32-/**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- */19 export const policyDigest = (20 policy: PublicPolicy,21 askTests: Option.Option<string>22 ): string =>15 unmodified lines38 onSome: (folder) => `Ask tests go in: ${folder}/`,39 }),40 ].join("\n");41 60-/** The rules of a draft, then the project's policy digest. */42 export 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 lines68 const encoder = new TextEncoder();69 70 const decoder = new TextDecoder();71 91-/** The last `tailBytes` of a run's output, starting on a whole line where one fits. */72 const tailOf = (output: string) => {73 const bytes = encoder.encode(output);74 75 if (bytes.length <= tailBytes) {6 unmodified lines82 83 return tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : tail;84 };85 106-/**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- */86 export 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");93 118-/** One attempt's question: the want, what to change, the files, and the last failure. */94 export const userPrompt = (input: DraftInput): string =>95 [96 `Project: ${input.context.project}, at ${input.context.at}.`,97 `Want: ${input.want}`,21 unmodified linesmodified: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.4 import { Brand } from "@repo/brand";5 import type { ConfigFile } from "@repo/protocol/domain/common";6 import { RepoPath } from "@repo/protocol/ids";7 2 unmodified lines10 const text = (value: string) => JSON.stringify(value);11 12 const list = (values: readonly string[]) => `[${values.map(text).join(", ")}]`;13 18-/** Each drafted kind's handle in the rules package: drafts are `fix` asks only, for now. */14 const kindHandle = { fix: "kinds.fix" } as const satisfies Record<15 DraftedAsk["kind"],16 string17 >;18 24-/**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- */19 export const renderAskFile = (drafted: DraftedAsk): string => {20 const fields: readonly (readonly [string, string | undefined])[] = [21 [22 "context",27 unmodified lines50 "",51 ].join("\n");52 };53 63-/**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- */54 export const draftedFiles = (55 drafted: DraftedAsk56 ): readonly [ConfigFile, ConfigFile] => [57 {5 unmodified linesmodified: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 lines21 import { Drafter } from "./drafter.ts";22 import { feedbackText, policyDigest } from "./prompt.ts";23 import { draftedFiles } from "./render.ts";24 43-/** How often, and how far apart, a failed step runs again before it is spent. */25 export interface StepRetry {26 readonly limit: number;27 readonly delayMs: number;28 readonly backoff: "constant" | "linear" | "exponential";29 }30 50-/**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- */31 export interface DraftSteps {32 readonly step: <A, I, E, R>(33 name: string,34 schema: Schema.Codec<A, I>,1 unmodified line36 retry?: StepRetry37 ) => Effect.Effect<A, E, R>;38 }39 64-/**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- */40 export const DraftModel = Context.Reference<string>("drafting/DraftModel", {41 defaultValue: () => "memory",42 });43 73-/** A rate-limited model is asked again, further apart each time. */44 export const rateLimitedRetry: StepRetry = {45 backoff: "exponential",46 delayMs: 15_000,47 limit: 4,48 };49 80-/** A Checker that could not run, or a main that moved, is rehearsed again. */50 export const blockedRetry: StepRetry = {51 backoff: "exponential",52 delayMs: 60_000,53 limit: 3,54 };55 87-/** What `context` records: what the attempts read, or why the round has none. */56 const 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 lines64 });65 66 type Prepared = typeof Prepared.Type;67 102-/** What `draft-<n>` records: the model's draft, or why it gave none. */68 const Attempted = Schema.TaggedUnion({69 Drafted: { drafted: DraftedAsk },70 Spent: { reason: DraftFailed.fields.reason },71 });72 73 type Attempted = typeof Attempted.Type;74 110-/** The kind a draft is: drafts are `fix` asks only, for now (ADR 0018). */75 const draftedKind = "fix";76 113-/** A proposal's territory as the paths whose files the drafter reads. */77 const territoryPaths = (territory: string | undefined) =>78 (territory ?? "")79 .split(/[\s,]+/u)80 .map((path) => path.replace(/(?:\/\*\*)?\/*$/u, ""))1 unmodified line82 .map((path) => RepoPath.make(path));83 84 const decoder = new TextDecoder();85 123-/** `{ [key]: value }` when `value` is there, else no key at all. */86 const field = <K extends string, A>(87 key: K,88 value: Option.Option<A>89 ): Partial<Record<K, A>> =>1 unmodified line91 onNone: () => ({}),92 onSome: (present) => Record.singleton(key, present),93 });94 133-/** What the next attempt is told when the model gave no draft. */95 const spentText = (reason: string) =>96 `Your reply gave no draft (${reason}): answer with one JSON object that matches the schema, and nothing else.`;97 137-/** The refusal a round that never rehearsed ends with: no draft, and why. */98 const noDraft = (reason: string): Refusal =>99 new IncompleteBrief({ missing: [`a draft (${reason})`] });100 141-/** Runs one round of a proposal's draft to its settling, over `steps`. */101 export const runDraft = (102 params: DraftParams,103 steps: DraftSteps104 ): Effect.Effect<void, never, Projects | Drafter | RepoHost> =>64 unmodified lines169 Effect.catchTag("UnknownProject", () => Effect.succeed(false))170 )171 );172 214- /** 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 linesmodified: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- */1 import { describe, expect, expectTypeOf, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";4 import { Effect, Schema } from "effect";37 unmodified lines42 readonly inputs: ChatInputs;43 readonly model: string;44 }45 50-/** What the fake binding does: answer with a reply, or throw. */46 type Outcome = { readonly reply: object } | { readonly thrown: Error };47 53-/** A fake binding that gives `outcome` and keeps every call. */48 const fakeAi = (outcome: Outcome) => {49 const calls: Call[] = [];50 51 const ai: AiLike = {21 unmodified lines73 const thrown = (message: string): Outcome => ({ thrown: new Error(message) });74 75 const failure = (reason: DraftFailed["reason"]) => new DraftFailed({ reason });76 83-/** The one call a draft makes, as the fake recorded it. */77 const callOf = Effect.gen(function* () {78 const { ai, calls } = fakeAi(chat(json));79 80 yield* Drafter.use(({ draft }) => draft(input)).pipe(116 unmodified lines197 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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { RepoPath } from "@repo/protocol/ids";4 import { Effect, Option } from "effect";4 unmodified lines9 10 const askSource = (id: string) =>11 `export default kinds.fix.ask({\n path: "test/asks/${id}.test.ts",\n want: "w",\n});\n`;12 17-/** A datekit-shaped tree, with what each file holds. */13 const files = {14 ".github/workflows/ci.yml": "steps: []\n",15 "README.md": "# datekit\n",16 [askFile("add-months-clamp")]: askSource("add-months-clamp"),164 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import type { Policy } from "@repo/protocol/domain/policy";4 import { VisibilityPolicy } from "@repo/protocol/domain/visibility";11 unmodified lines16 } from "../src/prompt.ts";17 18 const { policy } = aProject();19 25-/** Layer facts no prompt may carry. */20 const visibility = Schema.decodeSync(VisibilityPolicy)({21 checks: {22 areas: { export: "src/sealed-area/**" },23 attempts: { perClaim: 3, perPersonPerAreaPerWeek: 5 },99 unmodified linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import { FinishersFromChecks } from "@repo/project/project";12 unmodified lines17 const at = LandedSha.make("a".repeat(40));18 19 const askFile = (id: string) => `${Brand.configDir}/asks/${id}.ask.ts`;20 27-/** datekit's config folder, as the Lander bundles it, keyed by repo path. */21 const 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 lines37 38 return modules;39 });40 48-/** The asks a bundle of datekit's folder evaluates to, encoded, by id. */41 const asksOf = (modules: Readonly<Record<string, string>>) =>42 Effect.gen(function* () {43 const evaluator = yield* RulesEvaluator;44 33 unmodified lines78 path: RepoPath.make(`test/asks/${id}.test.ts`),79 source: 'import { expect, it } from "bun:test";\n',80 });81 90-/** `format-ordinal.ask.ts`'s fields, as a drafter would give them. */82 const 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 lines95 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 };98 108-/** `add-months-clamp.ask.ts`'s fields: every brief field a draft may give. */99 const addMonthsClamp: DraftedAsk = {100 context: [101 "addYears adds twelve months, so it follows: February 29 plus a year becomes February 28.",102 ],111 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { DraftResult } from "@repo/project/draft-runs";4 import type { DraftContextData } from "@repo/project/draft-runs";13 unmodified lines18 const scenario = aProject();19 20 const proposal = ProposalId.make("prop-000001");21 26-/** The scenario's policy as anyone reads it, with no `fix` kind. */22 const 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 linesmodified: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- */1 import type { Policy } from "@repo/protocol/domain/policy";2 import { sameHandle } from "@repo/protocol/ids";3 import type { Handle } from "@repo/protocol/ids";4 import { Principal } from "@repo/protocol/principal";22 unmodified lines27 const isPusher = (facts: PushFacts, handle: Handle) =>28 Option.exists(handleOf(facts.pusher), (pusher) => sameHandle(pusher, handle));29 30 /**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 */34 const standingOf = (policy: Policy, handle: Handle) => {35 const lines = policy.vouches.filter((vouch) =>36 sameHandle(vouch.handle, handle)13 unmodified lines50 51 return decides ? "vouched" : "unknown";52 };53 61-/** Where a person's work goes on a fork: its branches, never another ref. */54 const branchPrefix = "refs/heads/";55 56 /**57 * Main moves only by a landing: no push reaches a canonical ref.37 unmodified lines95 ? Option.some(new NotVouched({}))96 : Option.none();97 });98 107-/** The rules for a push to a claim's fork, in order. */99 const claimFork = (100 facts: PushFacts,101 fork: Data.TaggedEnum.Value<PushTarget, "ClaimFork">102 ): Option.Option<Refusal> => {8 unmodified lines111 if (Option.isNone(open)) {112 return Option.some(new NoAsk({}));113 }114 124- // 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 lines144 : Option.none();145 146 const rules: readonly Rule[] = [directPush, trust, claims];147 158-/** Parse: the first rule the push breaks, or nothing. */148 export const parse: Stage<never> = {149 accumulate: false,150 name: "parse",151 run: (facts) =>4 unmodified linesmodified: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- */3 import type { Ask } from "@repo/protocol/domain/ask";4 import { CheckSpec } from "@repo/protocol/domain/check";5 import { RepoPath } from "@repo/protocol/ids";6 import {12 unmodified lines19 import { importSpecifiers, reachedInternals as reachInto } from "../imports.ts";20 import { markersOf, scanMarkers } from "../markers.ts";21 import type { Stage } from "../stage.ts";22 29-/** The one JSON pointer the gate is told about: whether the scripts changed. */23 const SCRIPTS = "package.json#/scripts";24 32-/** The ask's own files: its file in the config folder, and its check's file. */25 const ownFiles = (ask: Ask): ReadonlySet<string> =>26 new Set([27 ask.file,28 ...(CheckSpec.guards.RedThenGreen(ask.check) ? [ask.check.path] : []),29 ]);30 39-/** Each path once, in a fixed order, if there are any. */31 const someOf = (32 paths: Iterable<RepoPath>33 ): Option.Option<Array.NonEmptyReadonlyArray<RepoPath>> => {34 const each = [...new Set(paths)].toSorted();2 unmodified lines37 ? Option.some(each)38 : Option.none();39 };40 50-/**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- */41 const judges = (facts: PushFacts) => (path: RepoPath) => {42 const own = Option.exists(facts.ask, (ask) => ownFiles(ask).has(path));43 44 return facts.opensAsk && own45 ? false46 : own || matchAny(facts.policy.judge.paths, path);47 };48 62-/**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- */49 const 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 });56 75-/** Changed paths outside the territory. A judged path is TouchedJudge's to name. */57 const outOfScope = (facts: PushFacts): readonly Refusal[] => {58 const judged = judges(facts);59 const allowed = inScope(facts);60 9 unmodified lines70 }71 );72 };73 93-/** Changed paths in the judge closure, and the scripts pointer when it moved. */74 const touchedJudge = (facts: PushFacts): readonly Refusal[] => {75 const scripts =76 facts.scriptsChanged && facts.policy.judge.pointers.includes(SCRIPTS)77 ? [RepoPath.make(SCRIPTS)]10 unmodified lines88 }89 );90 };91 112-/** Every marker added with no reason; a reasoned one is an escape, for `escapeDecisions`. */92 const 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 );99 121-/** Whether a layer's path set holds `path`: the path itself, or a folder above it. */100 const inLayers =101 (layerPaths: ReadonlySet<RepoPath>) =>102 (path: RepoPath): boolean => {103 const held: ReadonlySet<string> = layerPaths;2 unmodified lines106 return parts.some((_, end) => held.has(parts.slice(0, end + 1).join("/")));107 };108 109 /**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 */115 export const layerPathRefusal = (input: {116 readonly changes: readonly Pick<Change, "path" | "status">[];117 readonly layerPaths: ReadonlySet<RepoPath>;12 unmodified lines130 (paths) => new PrivatePathInPublicTree({ paths })131 );132 };133 163-/** Stage 1's guard by path, over the push's facts (`canReadLayers`). */134 const privatePaths = (facts: PushFacts): readonly Refusal[] =>135 Option.toArray(136 layerPathRefusal({137 changes: facts.changes,1 unmodified line139 pusherCanRead: facts.canReadLayers === true,140 })141 );142 173-// The files whose imports are read: JavaScript and TypeScript sources.143 const SCRIPT = /\.[cm]?[jt]sx?$/u;144 176-/**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- */145 const 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 lines157 )158 : [];159 };160 196-/**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- */161 const reachedInternals = (facts: PushFacts): readonly Refusal[] =>162 Option.match(facts.ask, {163 onNone: () => [],164 onSome: ({ territory }) =>25 unmodified lines190 )191 ),192 });193 234-// The Shape group's tags, in union order.194 const unionOrder: readonly string[] =195 groups196 .find((group) => group.name === "Shape")197 ?.members.map((member) => member.identifier) ?? [];198 240-/** Union group order, then path, then line. */199 const 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 ]);204 247-/**248- * Stage 1: every problem the push's changes have, in the union's Shape249- * order, then by path, then by line.250- */205 export const scan: Stage<never> = {206 accumulate: true,207 name: "shape",208 run: (facts) =>10 unmodified linesmodified: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 */5 import type { LaneResult } from "@repo/protocol/domain/answer";6 import type { CommitSha, LaneName, RepoPath } from "@repo/protocol/ids";4 unmodified lines11 VerifierBlocked,12 } from "@repo/protocol/refusal";13 import { Option } from "effect";14 17-/** What the platform saw of one lane on main, on the merged tree and on a fresh run. */15 export 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 }25 33-/** Whether a result is the platform's own trouble, not the code's: a flake, or a checker that never started. */26 const isTrouble = (result: LaneResult["result"]) =>27 result === "flaked" || result === "blocked";28 29 /**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 */35 export const classifyFailure = (36 evidence: LaneEvidence,37 changedPaths: ReadonlySet<RepoPath>,39 unmodified linesmodified: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 */5 import type { Ask } from "@repo/protocol/domain/ask";6 import { DecisionSubject } from "@repo/protocol/domain/decision";7 import type { Policy } from "@repo/protocol/domain/policy";5 unmodified lines13 import { matchAny } from "./glob.ts";14 import { markersOf, scanMarkers } from "./markers.ts";15 import type { MarkerHit } from "./markers.ts";16 25-/** A `Waiver` decision's subject. */17 export type Waiver = Extract<DecisionSubject, { readonly _tag: "Waiver" }>;18 28-/** An answer asking a decider to raise one ratchet in one territory, and why. */19 export interface RaiseRequest {20 readonly ratchet: RatchetName;21 readonly territory: string;22 readonly reason: string;23 }24 35-/**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- */25 export const escapeRatchet = (territory: string): RatchetName =>26 RatchetName.make(27 `escapes-${28 territory3 unmodified lines32 .join("-") || "root"33 }`34 );35 51-/** A marker hit whose line gives a reason. */36 interface Escape extends MarkerHit {37 readonly given: string;38 }39 7 unmodified lines47 onSome: (given) => [{ ...hit, given }],48 })49 );50 67-/**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- */51 export const territoryOf = (policy: Policy, ask: Ask, path: RepoPath) =>52 policy.modules.find((module) => matchAny(module.paths, path))?.module ??53 ask.territory.module;54 76-/**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- */55 export const escapeDecisions = (facts: PushFacts): readonly Waiver[] =>56 Option.match(facts.ask, {57 onNone: () => [],58 onSome: (ask) => {27 unmodified lines86 );87 },88 });89 117-/**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- */90 export const explainedRaises = (91 policy: Policy,92 ask: Ask,93 waivers: readonly Waiver[]8 unmodified linesmodified: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- */1 import type { Ask } from "@repo/protocol/domain/ask";2 import type { ClaimView } from "@repo/protocol/domain/claim";3 import type { RefNameText } from "@repo/protocol/domain/common";4 import type { Policy } from "@repo/protocol/domain/policy";11 unmodified lines16 import type { Principal } from "@repo/protocol/principal";17 import { Data } from "effect";18 import type { Option } from "effect";19 25-/** One path an answer changes, with its blob before and after. */20 export interface Change {21 readonly path: RepoPath;22 readonly status: "added" | "modified" | "deleted";23 readonly before?: BlobSha;24 readonly after?: BlobSha;25 }26 33-/** One line an answer adds to a file, by its 1-based number in the new file. */27 export interface AddedLine {28 readonly line: number;29 readonly text: string;30 }31 39-/**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- */32 export type PushTarget = Data.TaggedEnum<{33 Canonical: { readonly project: ProjectName };34 ClaimFork: {35 readonly project: ProjectName;3 unmodified lines39 Layer: { readonly project: ProjectName; readonly layer: LayerName };40 WorkingFork: { readonly project: ProjectName; readonly owner: Handle };41 }>;42 56-/** Constructors and matchers for `PushTarget`. */43 export const PushTarget = Data.taggedEnum<PushTarget>();44 59-/** Everything the gate's stages decide one push over. */45 export 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 line53 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 else1 unmodified line63 * 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, which11 unmodified linesmodified: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 */5 import type { Refusal } from "@repo/protocol/refusal";6 import { Array, Effect, Option } from "effect";7 1 unmodified line9 import type { Stage } from "./stage.ts";10 import { parse } from "./stages/parse.ts";11 import { scan } from "./stages/shape.ts";12 14-/**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- */13 export const runGate = <R>(14 stages: readonly Stage<R>[],15 facts: PushFacts16 ): Effect.Effect<14 unmodified lines31 32 return Option.none();33 });34 41-/** Stages 0 and 1: what the gateway and `submitAnswer` run before answering a push. */35 export 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 */7 8 // The characters a RegExp reads as syntax, which a glob means literally.9 const SYNTAX = new Set("\\^$.|+()[]{}");10 17-/** The RegExp source for one glob, anchored at both ends. */11 const sourceOf = (glob: string) => {12 let source = "";13 let at = 0;14 41 unmodified lines56 57 return glob.slice(0, -1).includes("/") ? folder : `**/${folder}`;58 };59 67-/** Whether `path` matches `glob`. */60 export const matchGlob = (glob: string, path: string): boolean =>61 new RegExp(sourceOf(anchored(glob)), "u").test(path);62 71-/**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- */63 export 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.3 import type { Policy } from "@repo/protocol/domain/policy";4 import type { RepoPath } from "@repo/protocol/ids";5 import { Array, Option } from "effect";6 7 import { matchAny } from "./glob.ts";8 14-/** One module specifier a text imports, and the 1-based line it sits on. */9 export interface ImportSpecifier {10 readonly specifier: string;11 readonly line: number;12 }9 unmodified lines22 const KEYWORD_BEFORE_REGEX =23 /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/u;24 25 /**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 */29 const 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[] = [];37 38 const emit = (chars: string, as: "blank" | "fill") => {39 for (const char of chars) {11 unmodified lines51 tail = (tail + chars).slice(-32);52 blankLine = chars.endsWith("\n") || (blankLine && chars.trim() === "");53 };54 67- /** Ends the current mode on `char`, which stays as code. */55 const close = (char: string) => {56 mode = "code";57 keep(char);58 };59 73- // 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 lines135 136 return 1;137 };138 154- /** Whether a `/` here opens a regular expression rather than divides. */139 const opensRegex = () => {140 const before = tail.trimEnd();141 142 return (2 unmodified lines145 KEYWORD_BEFORE_REGEX.test(before)146 );147 };148 165- /** 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 lines165 166 return "code";167 };168 186- /** Counts braces inside a template's `${`; its closing one resumes the template. */169 const brace = (char: string) => {170 const open = expressions.pop();171 172 if (open === undefined) {62 unmodified lines235 /(?<![\w$.])import\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,236 /(?<![\w$.])require\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,237 ];238 257-/**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- */239 export const importSpecifiers = (text: string): readonly ImportSpecifier[] => {240 const masked = maskOf(text);241 242 return FORMS.flatMap((form) =>12 unmodified lines255 .toSorted((one, other) => one.start - other.start)256 .map(({ line, specifier }) => ({ line, specifier }));257 };258 285-// A specifier relative to the importing file: `./x`, `../x`, `.` or `..`.259 const RELATIVE = /^\.\.?(?:\/|$)/u;260 288-// The folders a package subpath may not name: they hold a module's insides.261 const INSIDES = new Set(["src", "test", "internal"]);262 263 type Module = Policy["modules"][number];264 265 const moduleOf = (modules: Policy["modules"], path: string) =>266 Array.findFirst(modules, (module) => matchAny(module.paths, path));267 296-/** `from`'s folder joined with a relative specifier; none when it leaves the repo. */268 const resolve = (from: string, specifier: string): Option.Option<string> => {269 const parts = from.split("/").slice(0, -1);270 271 for (const part of specifier.split("/")) {10 unmodified lines282 283 return Option.some(parts.join("/"));284 };285 315-/** A module file's path with its extension and a trailing `/index` dropped. */286 const bare = (path: string) =>287 path.replace(/\.[cm]?[jt]sx?$/u, "").replace(/\/index$/u, "");288 319-/** The folders a module's globs name: `packages/b/**` is `packages/b`. */289 const rootsOf = (module: Module) =>290 module.paths.map((glob) =>291 glob.replace(/^\//u, "").replace(/\/(?:\*\*)?$/u, "")292 );293 325-/**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- */294 const isInternal = (module: Module, target: string) =>295 module.publicFiles !== undefined &&296 !rootsOf(module).includes(target) &&297 !module.publicFiles.some((file) => bare(file) === bare(target));298 335-/** The module a relative specifier lands in, when it is internal there. */299 const relative = (300 from: string,301 specifier: string,302 modules: Policy["modules"]3 unmodified lines306 isInternal(module, target)307 )308 );309 347-/**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- */310 const 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 lines316 ? Array.findFirst(modules, (module) => module.module === name)317 : Option.none();318 };319 362-/**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- */320 export const reachedInternals = (input: {321 readonly from: RepoPath;322 readonly specifier: string;323 readonly modules: Policy["modules"];14 unmodified linesmodified: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- */1 import type { Policy } from "@repo/protocol/domain/policy";2 import type { RepoPath } from "@repo/protocol/ids";3 import { Option, Order } from "effect";4 5 import type { PushFacts } from "./facts.ts";6 12-/** One marker, and the kind of check it turns off. */7 export interface Marker {8 readonly text: string;9 readonly family:10 | "test"5 unmodified lines16 | "rust"17 | "go";18 }19 26-/** The markers every project starts with; a project may add more. */20 export const defaultMarkers: readonly Marker[] = [21 { family: "test", text: ".skip(" },22 { family: "test", text: ".only(" },23 { family: "test", text: ".todo(" },11 unmodified lines35 { family: "coverage", text: "istanbul ignore" },36 { family: "coverage", text: "c8 ignore" },37 ];38 46-/** The defaults and the markers the project adds, each once. */39 export const markersOf = (policy: Policy): readonly string[] => [40 ...new Set([41 ...defaultMarkers.map((marker) => marker.text),42 ...policy.weakening.markers,43 ]),44 ];45 54-/** One marker on one line, with the reason written after it, if any. */46 export interface MarkerHit {47 readonly path: RepoPath;48 readonly line: number;49 readonly marker: string;50 readonly reason: Option.Option<string>;51 }52 62-// The ` -- ` that starts a reason after an escape directive.53 const REASON_MARK = /\s--(?=\s|$)/u;54 65-// What closes a comment after its reason: `*/`, `-->`.55 const CLOSER = /\s*(?:\*\/|-->)\s*$/u;56 68-/** The reason written after a marker on its line, if there is one. */57 const reasonIn = (rest: string): Option.Option<string> => {58 const mark = REASON_MARK.exec(rest);59 60 if (mark === null) {8 unmodified lines69 return reason === "" ? Option.none() : Option.some(reason);70 };71 72 /**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 */76 export const scanMarkers = (77 lines: PushFacts["addedLines"],78 markers: readonly string[]23 unmodified linesmodified:packages/gate/src/stage.ts-5 removed
2 unmodified lines3 import type { Effect } from "effect";4 5 import type { PushFacts } from "./facts.ts";6 7-/**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- */7 export interface Stage<R> {8 readonly name: StageName;9 readonly accumulate: boolean;10 readonly run: (3 unmodified linesmodified: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- */1 import type {2 HeldBackResult,3 LaneResult,4 Verdict,5 unmodified lines10 import type { DateTime } from "effect";11 12 import type { PushFacts } from "./facts.ts";13 19-/** What one check run found, and where it got to. */14 export 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 }25 34-/**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- */26 export 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 linesmodified:packages/gate/test/classify.test.ts-4 removed
17 unmodified lines18 const week = RepoPath.make("packages/parse/src/week.ts");19 20 const pad = RepoPath.make("packages/format/src/pad.ts");21 22-/** The answer changed `week.ts` only. */22 const changed: ReadonlySet<RepoPath> = new Set([week]);23 25-/** The unit lane, green on main and red on the merged tree in `week.ts`. */24 const red: LaneEvidence = {25 command: "bun run test",26 failingPaths: [week],27 isDoctor: false,3 unmodified lines31 onMerged: "failed",32 rerun: Option.none(),33 };34 37-// The classification table: the platform never charges the answerer for its own38-// trouble, nor for a main that moved underneath them.35 const rows: readonly {36 readonly name: string;37 readonly evidence: LaneEvidence;38 readonly refusal: Option.Option<Refusal>;97 unmodified linesmodified:packages/gate/test/escapes.test.ts-1 removed
23 unmodified lines24 const generated = "/* eslint-disable no-console -- generated tables */";25 26 const parseEscapes = RatchetName.make("escapes-datekit-parse");27 28-/** The `Waiver` for the escape `marker` with `reason` at `path:line`. */28 const 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 linesmodified: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- */1 import { Ask } from "@repo/protocol/domain/ask";2 import { CheckSpec } from "@repo/protocol/domain/check";3 import { ClaimView } from "@repo/protocol/domain/claim";4 import { RefNameText } from "@repo/protocol/domain/common";11 unmodified lines16 const { vouch } = Schema.decodeSync(17 Schema.Struct({ vouch: PolicyInput.fields.vouch })18 )({});19 28-/** The config folder's name, as `Brand.configDir` spells it. */20 export const configDir = vouch.file.slice(0, vouch.file.indexOf("/"));21 31-/** A decider for every path, who is in no line of the vouch file. */22 export const alice = Handle.make("alice");23 34-/** Vouched for, and the holder of the claim on `iso-week`. */24 export const bob = Handle.make("bob");25 37-/** Vouched for, with no claim. */26 export const carol = Handle.make("carol");27 40-/** In no line of the vouch file. */28 export const dana = Handle.make("dana");29 43-/** Denounced by the vouch file. */30 export const mallory = Handle.make("mallory");31 32 export const base = CommitSha.make("1111111111111111111111111111111111111111");33 35 unmodified lines69 state: "claimed",70 territory: { ...parseModule, paths: ["packages/parse/**", "/package.json"] },71 } as const;72 87-/** The ask bob answers. */73 export const ask = Schema.decodeSync(Ask)(askWire);74 90-/** Bob's live claim on `iso-week`. */75 export const claim = Schema.decodeSync(ClaimView)({76 ask: askWire.id,77 base,78 checkCommand: `bun test ${checkPath}`,6 unmodified lines85 state: "live",86 warnsAt: "2026-10-07T14:00:00.000Z",87 });88 105-/** The policy at the landed SHA. */89 export const policy = Schema.decodeSync(Policy)({90 agents: "trailer",91 asks: [askWire],92 at: landedSha,41 unmodified lines134 ],135 weakening: { markers: [] },136 });137 155-/** The paths, each changed in place. */138 export const modified = (...paths: readonly string[]): readonly Change[] =>139 paths.map((path) => ({ path: RepoPath.make(path), status: "modified" }));140 159-/** The lines a push adds, as `[path, line, text]`, grouped by path. */141 export const addedLines = (142 ...lines: readonly (readonly [string, number, string])[]143 ): ReadonlyMap<RepoPath, readonly AddedLine[]> => {144 const byPath = new Map<RepoPath, AddedLine[]>();6 unmodified lines151 152 return byPath;153 };154 174-/** Bob's clean push to his claim's fork, with `overrides` applied. */155 export const testFacts = (overrides: Partial<PushFacts> = {}): PushFacts => ({156 addedLines: addedLines([157 "packages/parse/src/week.ts",158 3,19 unmodified lines178 }),179 ...overrides,180 });181 202-/** Refusals as they cross the wire, so a test compares their fields. */182 export const wire = (refusals: readonly Refusal[]) =>183 refusals.map((refusal) => Schema.encodeSync(Refusal)(refusal));modified:packages/gate/test/gate.test.ts-2 removed
6 unmodified lines7 import { pushStages, runGate } from "../src/gate.ts";8 import type { Stage } from "../src/stage.ts";9 import { ask, modified, testFacts, wire } from "./facts.ts";10 11-/** What the gate answered, as it crosses the wire; `None` stays `None`. */11 const wired = (answer: Option.Option<readonly Refusal[]>) =>12 Option.map(answer, wire);13 15-/** A stage that answers every push with `refusals`. */14 const always = (15 accumulate: boolean,16 refusals: readonly Refusal[]17 ): Stage<never> => ({75 unmodified linesmodified:packages/gate/test/glob.test.ts-1 removed
1 import { describe, expect, it } from "@effect/vitest";2 3 import { matchAny, matchGlob } from "../src/glob.ts";4 5-// Each row is a glob, a path, and whether `.gitignore`'s rules match them.5 const 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 linesmodified:packages/gate/test/imports.test.ts-1 removed
3 unmodified lines4 import { Option, Schema } from "effect";5 6 import { importSpecifiers, reachedInternals } from "../src/imports.ts";7 8-/** The text of `lines`, one per line. */8 const text = (...lines: readonly string[]) => lines.join("\n");9 10 describe(importSpecifiers, () => {11 it.each([225 unmodified linesmodified:packages/gate/test/markers.test.ts-1 removed
5 unmodified lines6 import { addedLines, policy } from "./facts.ts";7 8 const texts = defaultMarkers.map((marker) => marker.text);9 10-// One added line per default marker, as each tool writes it.10 const 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 linesmodified:packages/gate/test/parse.test.ts-5 removed
28 unmodified lines29 testFacts,30 wire,31 } from "./facts.ts";32 33-/** Dana's own live claim on the ask, and her push to its fork. */33 const danasPush = (mode: PushFacts["policy"]["vouch"]["mode"]) =>34 testFacts({35 claim: Option.some({ ...claim, claimant: dana }),36 policy: { ...policy, vouch: { ...policy.vouch, mode } },4 unmodified lines41 project: ask.project,42 }),43 });44 46-/** Dana's push to her own working fork (`<project>--me--dana`). */45 const danasWorkingForkPush = (mode: PushFacts["policy"]["vouch"]["mode"]) =>46 testFacts({47 ask: Option.none(),48 claim: Option.none(),5 unmodified lines54 const main = RefNameText.make("refs/heads/main");55 56 const tag = RefNameText.make("refs/tags/v1");57 60-// Each row is one push; parse answers with at most one refusal, the first61-// rule the push breaks.58 const rows: readonly {59 readonly name: string;60 readonly facts: PushFacts;61 readonly refusals: readonly Refusal[];158 unmodified lines220 }),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 linesmodified:packages/gate/test/shape.test.ts-10 removed
36 unmodified lines37 const week = "packages/parse/src/week.ts";38 39 const weekTest = "packages/parse/test/week.test.ts";40 41-/** The path set of a layer holding `each`: files, or folders. */41 const layerHolds = (...each: readonly string[]): ReadonlySet<RepoPath> =>42 new Set(each.map((path) => RepoPath.make(path)));43 45-/** A push that changes `files` and adds `lines` to them. */44 const push = (45 files: readonly string[],46 lines: readonly (readonly [string, number, string])[] = [],47 overrides: Partial<PushFacts> = {}3 unmodified lines51 changes: modified(...files),52 ...overrides,53 });54 57-/** One push with every problem shape knows. */55 const everyProblem = push(56 [week, "docs/guide.md", ".github/workflows/ci.yml"],57 [58 [week, 1, 'export { pad } from "../../format/src/pad";'],6 unmodified lines65 // The language service reads its directive anywhere in a source file, so66 // the marker is joined at run time.67 const effectDiagnostics = ["@effect", "-diagnostics"].join("");68 72-// Two modules, `a` and `b`; the ask's territory is `a`, and the judge73-// closure also holds the lint config.69 const [moduleA, moduleB] = Schema.decodeSync(70 Schema.Tuple([Territory, Territory])71 )([72 {11 unmodified lines84 const x = "packages/a/src/x.ts";85 86 const xTest = "packages/a/test/x.test.ts";87 93-/** A push answering an ask in module `a`. */88 const pushToA = (89 files: readonly string[],90 lines: readonly (readonly [string, number, string])[] = []91 ) =>8 unmodified lines100 modules: [moduleA, moduleB],101 },102 });103 110-// Every default marker, as a tool writes it on an added line.104 const 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 lines121 ];122 123 const pad = "../../format/src/pad.ts";124 132-/** ReachedInternals for an import of `to` on line `line` of `week`. */125 const reachedFromWeek = (line: number, to: string) =>126 new ReachedInternals({ at: at(week, line), from: RepoPath.make(week), to });127 136-// Each row is one push. Shape reports every problem the push has, in the137-// order of the refusal union's Shape group.128 const rows: readonly {129 readonly name: string;130 readonly facts: PushFacts;131 readonly refusals: readonly Refusal[];398 unmodified linesmodified:packages/git/src/upstream/repo-host.ts+1 added-9 removed
13 unmodified lines14 15 import { Exchange, Upstream, UpstreamFailure } from "../upstream.ts";16 import type { Service } from "../upstream.ts";17 18-/** How long a token the upstream mints is asked to last. */18 const TOKEN_TTL = Duration.hours(1);19 20 /** A token is dropped this long before it expires, so none expires mid-exchange. */21 const MARGIN = Duration.minutes(1);22 24-/** Tokens kept at once, one per (repo, scope). */23 const CAPACITY = 1024;24 25 class TokenKey extends Data.Class<{26 readonly repo: RepoName;27 readonly scope: TokenScope;28 }> {}29 32-/** A clone or fetch reads; only a push writes. */30 const scopeOf = (service: Service): TokenScope =>31 service === "git-receive-pack" ? "write" : "read";32 33 /**27 unmodified lines61 },62 });63 };64 68-/**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. */66 export const UpstreamRepoHost: Layer.Layer<Upstream, never, RepoHost | Fetch> =67 Layer.effect(68 Upstream,69 Effect.gen(function* () {49 unmodified linesmodified: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 */5 import type { WhyRange } from "@repo/protocol/domain/code";6 import type { CommitSha } from "@repo/protocol/ids";7 8 import { Edit, lineDiff } from "./line-diff.ts";9 16-/** One version of a file: the commit that made it, and its text. */10 export interface Version {11 readonly sha: CommitSha;12 readonly text: string;13 }14 22-/** Why each line is there, and whether any went to the oldest version given. */15 export interface Blame {16 readonly ranges: readonly WhyRange[];17 readonly reachedEnd: boolean;18 }19 28-/** A text's lines, without the empty one after a final newline. */20 export const linesOf = (text: string): readonly string[] => {21 if (text === "") {22 return [];23 }6 unmodified lines30 31 return lines;32 };33 43-/** Where each line of `after` sits in `before`, or -1 for a line `before` lacks. */34 const originsOf = (before: readonly string[], after: readonly string[]) => {35 const origins = new Int32Array(after.length).fill(-1);36 37 for (const edit of lineDiff(before, after)) {6 unmodified lines44 45 return origins;46 };47 58-/** Each line's version as ranges of consecutive lines, numbered from 1. */48 const rangesOf = (owners: readonly CommitSha[]): readonly WhyRange[] => {49 const ranges: WhyRange[] = [];50 51 for (const [index, sha] of owners.entries()) {9 unmodified lines61 62 return ranges;63 };64 76-/**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- */65 export 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 }71 89-/** A blame of `newest`, every line open. */72 export const blameFrom = (newest: Version): Tracing => {73 const lines = linesOf(newest.text);74 75 return {3 unmodified lines79 sha: newest.sha,80 };81 };82 101-/** Whether every line has its version, so no older one need be read. */83 export const isSettled = (tracing: Tracing) => tracing.open.size === 0;84 104-/**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- */85 export 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 lines100 101 return { lines, open, owners, sha: older.sha };102 };103 127-/** Why each line is there, the open lines going to the version reached. */104 export const settle = (tracing: Tracing): Blame => ({105 ranges: rangesOf(tracing.owners.map((owner) => owner ?? tracing.sha)),106 reachedEnd: tracing.open.size > 0,107 });108 133-/** Why each line of the newest of `versions` (newest first) is there. */109 export const blame = (versions: readonly Version[]): Blame => {110 const [newest, ...older] = versions;111 112 if (newest === undefined) {15 unmodified linesmodified:packages/git/src/custody.ts+2 added-11 removed
2 unmodified lines3 import type { Refusal } from "@repo/protocol/refusal";4 import { Context } from "effect";5 import type { Array, Effect, Option } from "effect";6 7-/** One ref in a push: `None` for `from` creates it, for `to` deletes it. */7 export interface Command {8 readonly ref: RefName;9 readonly from: Option.Option<CommitSha>;10 readonly to: Option.Option<CommitSha>;11 }12 14-/**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. */14 export 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 linesmodified:packages/git/src/gateway.ts+2 added-34 removed
24 unmodified lines25 // or without `.git`, then the endpoint.26 const ROUTE =27 /^\/(?<name>[A-Za-z0-9._-]+?(?:\/[A-Za-z0-9._-]+?){0,2})(?:\.git)?\/(?<endpoint>info\/refs|git-upload-pack|git-receive-pack)$/u;28 29-/** One of the three endpoints of git's smart HTTP. */29 export type GitEndpoint = "info/refs" | "git-upload-pack" | "git-receive-pack";30 32-/** What a smart HTTP path names: the address as spelled, its repo, and the endpoint. */31 export 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 }36 41-/**42- * The repo a smart HTTP path names, and the endpoint it asks for; `None`43- * for any other path.44- */37 export const gitRoute = (pathname: string): Option.Option<GitRoute> =>38 Option.flatMap(39 Option.fromNullishOr(ROUTE.exec(pathname)?.groups),40 ({ endpoint, name }) =>30 unmodified lines71 72 return picked;73 };74 83-/**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. */76 const bytes = () =>77 new TransformStream<unknown, Uint8Array>({78 transform: (chunk, controller) => {79 if (chunk instanceof Uint8Array) {5 unmodified lines85 }86 },87 });88 100-/** A POST's body, the only kind of request with one here. */89 const bodyOf = (request: Request) =>90 request.method === "POST" && request.body !== null91 ? Option.some(request.body.pipeThrough(bytes()))92 : Option.none();93 106-/** A plain-text reply, which git prints as the reason a request failed. */94 export const plain = (95 status: number,96 text: string,97 headers: Readonly<Record<string, string>> = {}2 unmodified lines100 headers: { "content-type": "text/plain; charset=utf-8", ...headers },101 status,102 });103 117-/** The upstream's reply as the client gets it: status, type and body, uncached. */104 const relay = (response: Response) =>105 new Response(response.body, {106 headers: {107 "cache-control": "no-cache",21 unmodified lines129 130 const busy = (messages: readonly Uint8Array[]) =>131 messages.some((message) => new TextDecoder().decode(message).includes(BUSY));132 147-/** Where each ref in the upstream points now. */133 const tipsOf = (repo: RepoName) =>134 Effect.gen(function* () {135 const response = yield* (yield* Upstream).exchange(136 repo,11 unmodified lines148 readAdvertisement(new Uint8Array(advertisement))149 );150 }).pipe(Effect.orElseSucceed(() => new Map<string, CommitSha>()));151 167-/**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- */152 const translate = (153 repo: RepoName,154 commands: readonly Command[],155 refs: readonly RefStatus[]25 unmodified lines181 })182 );183 });184 204-/**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- */185 const answer = (186 repo: RepoName,187 opening: Opening,188 commands: Array.NonEmptyReadonlyArray<Command>,78 unmodified lines267 )268 : result(reply);269 });270 295-/**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- */271 const push = (272 repo: RepoName,273 headers: Headers,274 body: ReadableStream<Uint8Array>39 unmodified lines314 Effect.succeed(plain(400, reason))315 )316 );317 346-/**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. */319 export const gateway = (320 request: Request321 ): Effect.Effect<Response, never, Upstream | Custody> =>322 Effect.gen(function* () {50 unmodified linesmodified: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 */7 import { Data, Option } from "effect";8 14-/** `count` lines from `oldStart` in the old lines and `newStart` in the new. */9 interface Span {10 readonly oldStart: number;11 readonly newStart: number;12 readonly count: number;13 }14 21-/** One run of an edit script: lines both files share, or lines one alone holds. */15 export type Edit = Data.TaggedEnum<{16 Delete: Span;17 Equal: Span;18 Insert: Span;19 }>;20 21 export const Edit = Data.taggedEnum<Edit>();22 30-/** One line's step through the script. */23 type Step = Edit["_tag"];24 33-// Past this many edits the diff stops looking for the shortest script.25 const MAX_EDITS = 1024;26 27 const at = (values: Int32Array, index: number) => values[index] ?? 0;28 38 unmodified lines67 68 return steps.toReversed();69 };70 80-/** A shortest edit script from `previous` to `next`, or none past `MAX_EDITS`. */71 const myers = (72 previous: readonly string[],73 next: readonly string[]74 ): Option.Option<readonly Step[]> => {34 unmodified lines109 110 return Option.none();111 };112 123-/** How many times each line occurs in `lines`. */113 const countsOf = (lines: readonly string[]) => {114 const counts = new Map<string, number>();115 116 for (const line of lines) {2 unmodified lines119 120 return counts;121 };122 134-/**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- */123 const anchored = (124 previous: readonly string[],125 next: readonly string[]126 ): readonly Step[] => {33 unmodified lines160 161 return steps;162 };163 180-/** The steps of a script, as runs: in each run of changes, deletions first. */164 const runsOf = (steps: readonly Step[]): readonly Edit[] => {165 const edits: Edit[] = [];166 let oldStart = 0;167 let newStart = 0;42 unmodified lines210 211 return edits;212 };213 231-/** How many lines from each end `previous` and `next` share. */214 export const sharedEnds = (215 previous: readonly string[],216 next: readonly string[]217 ) => {19 unmodified lines237 238 return { head, tail };239 };240 259-/** `middle` with the shared head and tail around it. */241 const framed = (242 ends: { readonly head: number; readonly tail: number },243 middle: readonly Step[]244 ): readonly Step[] => [1 unmodified line246 ...middle,247 ...Array.from({ length: ends.tail }, (): Step => "Equal"),248 ];249 269-/**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- */250 export const shortestDiff = (251 before: readonly string[],252 after: readonly string[]253 ): Option.Option<readonly Edit[]> => {7 unmodified lines261 (middle) => runsOf(framed(ends, middle))262 );263 };264 288-/**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- */265 export const lineDiff = (266 before: readonly string[],267 after: readonly string[]268 ): readonly Edit[] =>13 unmodified linesmodified:packages/git/src/notes.ts+2 added-20 removed
11 unmodified lines12 import { DateTime, Effect, Option, Schema } from "effect";13 14 import { committerLine } from "./trailers.ts";15 16-/**17- * Where verdicts live as git notes: one JSON note per commit, read18- * with `git notes --ref=<slug> show <commit>`.19- */16 export const notesRef = RefName.make(`refs/notes/${Brand.slug}`);17 22-/** A verdict to write as the note on `target`, on top of the notes at `notesParent` in `repo`. */18 export 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 }25 31-/**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- */26 export interface ScratchSource extends PushSource {27 readonly fs: MemoryFs;28 }29 20 unmodified lines50 51 const bytesOfHex = (id: string) =>52 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));53 63-/** git's zlib stream, as a loose object holds it. */54 const deflate = (bytes: Uint8Array) =>55 Effect.promise(() =>56 new Response(57 // A copy on its own `ArrayBuffer`: Node's `Blob` types refuse a view55 unmodified lines113 input.message,114 ].join("\n")115 );116 127-/**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- */117 const scratch = () =>118 Effect.gen(function* () {119 const fs = memoryFs();120 const gitdir = "/notes.git";45 unmodified lines166 source: { fs, gitdir } satisfies ScratchSource,167 };168 });169 184-/** The notes tree's entries at `parent`, read through the port; none for the first note. */170 const notesAt = (repo: RepoName, parent: Option.Option<CommitSha>) =>171 Option.match(parent, {172 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),173 onSome: (sha) =>17 unmodified lines191 192 const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));193 194 /**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 */200 export const noteCommit = (41 unmodified linesmodified:packages/git/src/patch-id.ts+3 added-5 removed
7 unmodified lines8 .map((byte) => byte.toString(16).padStart(2, "0"))9 .join("");10 11 /**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 */16 export const patchId = (changes: readonly Change[]): Effect.Effect<PatchId> => {17 const lines = Array.sort(18 changes.map(9 unmodified linesmodified:packages/git/src/pkt-line.ts+2 added-12 removed
20 unmodified lines21 };22 23 export const utf8 = (text: string) => encoder.encode(text);24 25-/** One pkt-line around `payload`. */25 export const pkt = (payload: Uint8Array) =>26 concat([27 encoder.encode((payload.length + 4).toString(16).padStart(4, "0")),28 payload,29 ]);30 32-/** A data line's payload, or `Flush`. */31 export type Packet = Uint8Array | "Flush";32 35-/**36- * The packet that starts at `at`, with where the next one starts; `None` if37- * the bytes stop before the packet does.38- */33 export const packetAt = (34 bytes: Uint8Array,35 at: number36 ): Option.Option<{ readonly packet: Packet; readonly next: number }> => {21 unmodified lines58 packet: bytes.subarray(at + 4, at + length),59 });60 };61 68-/** Every packet in `bytes`, which must hold whole packets only. */62 export const packets = (bytes: Uint8Array) => {63 const found: Packet[] = [];64 let at = 0;65 13 unmodified lines79 80 const LENGTH = /^[0-9a-f]{4}$/u;81 82 /**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 */86 export const textLines = (bytes: Uint8Array): readonly string[] => {87 const decoder = new TextDecoder();88 const lines: string[] = [];21 unmodified linesmodified: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- */1 import { RefName } from "@repo/artifacts/repo-host";2 import { CommitSha } from "@repo/protocol/ids";3 import type { Refusal } from "@repo/protocol/refusal";4 import { explain, headline } from "@repo/protocol/render";1 unmodified line6 7 import type { Command } from "./custody.ts";8 import { FLUSH, concat, packetAt, packets, pkt, utf8 } from "./pkt-line.ts";9 14-/** The request is not a receive-pack request git would send. */10 export class Malformed extends Data.TaggedError("Malformed")<{11 readonly reason: string;12 }> {}13 6 unmodified lines20 hex === ZERO ? Option.none() : Option.some(CommitSha.make(hex));21 22 const isRefName = Schema.is(RefName);23 29-/** The opening of a push, and every byte read to find it. */24 export interface Opening {25 readonly commands: readonly Command[];26 readonly capabilities: ReadonlySet<string>;27 readonly read: Uint8Array;45 unmodified lines73 catch: () => new Malformed({ reason: "the push could not be read" }),74 try: () => reader.read(),75 });76 83-/**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. */78 export const readOpening = (body: ReadableStream<Uint8Array>) =>79 Effect.gen(function* () {80 const reader = body.getReader();81 const lines: string[] = [];38 unmodified lines120 evaluate: () => body,121 onError: () => new Malformed({ reason: "the push could not be read" }),122 });123 134-/** Reads the rest of a body and drops it, so the client finishes sending. */124+/** So the client finishes sending. */125 export const drain = (body: ReadableStream<Uint8Array>) =>126 Stream.runDrain(rest(body)).pipe(Effect.ignore);127 138-/** The bytes already read, then the rest of the body, as one stream. */128 export const resume = (read: Uint8Array, body: ReadableStream<Uint8Array>) =>129 Stream.toReadableStream(Stream.concat(Stream.succeed(read), rest(body)));130 131 // The largest payload a side-band packet carries, by the client's capability.17 unmodified lines149 150 return parts;151 };152 164-/** One ref's line in a report: `None` if it landed, else git's reason. */153 export interface RefStatus {154 readonly ref: string;155 readonly ng: Option.Option<string>;156 }157 170-/** The upstream's answer to a push, out of its side band. */158 export 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 line165 new TextDecoder().decode(bytes).replace(/\n$/u, "");166 167 const STATUS = /^(?<verdict>ok|ng) (?<ref>\S+)(?: (?<reason>.*))?$/u;168 184-/** Reads the upstream's reply to a push; throws if it is not pkt-lines. */169 export const readReport = (170 capabilities: ReadonlySet<string>,171 reply: Uint8Array172 ): UpstreamReport => {37 unmodified lines210 211 return { messages, refs, unpack };212 };213 230-/**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- */214 export const writeReport = (215 capabilities: ReadonlySet<string>,216 messages: readonly Uint8Array[],217 refusals: readonly Refusal[],36 unmodified lines254 };255 256 const ADVERTISED = /^(?<oid>[0-9a-f]{40}) (?<ref>[^\0\n ]+)/u;257 278-/** The refs in a ref advertisement (`info/refs`) and the commit each names. */258 export const readAdvertisement = (advertisement: Uint8Array) =>259 new Map(260 packets(advertisement).flatMap((packet) => {261 const fields =4 unmodified lines266 : [[fields.ref, CommitSha.make(fields.oid)] as const];267 })268 );269 291-/** Every ref turned away for the same refusals. */270 export const refuseAll = (271 commands: readonly Command[],272 refusals: Array.NonEmptyReadonlyArray<Refusal>273 ): RefStatus[] =>1 unmodified linemodified:packages/git/src/trailers.ts+1 added-32 removed
9 unmodified lines10 RequestId,11 } from "@repo/protocol/ids";12 import { Array, Option, Order, Schema } from "effect";13 14-/** One `Key: value` line of a commit message's trailer block. */14 export interface Trailer {15 readonly key: string;16 readonly value: string;17 }18 20-/** A git identity: the name and email of an author or committer line. */19 export interface GitIdentity {20 readonly name: string;21 readonly email: string;22 }23 26-/** The accountable person, as a landing's author: their handle at the platform's users domain. */24 export const authorLine = (handle: Handle): GitIdentity => ({25 email: `${handle}@users.${Brand.domain}`,26 name: handle,27 });28 32-/** The platform, which commits every landing. */29 export const committerLine: GitIdentity = {30 email: `platform@${Brand.domain}`,31 name: Brand.name,32 };33 38-/** What a landing commit's message is made of; every trailer comes from the platform's own rows. */34 export interface LandingMessage {35 readonly subject: string;36 readonly body?: string;37 readonly credits: readonly Credit[];3 unmodified lines41 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 lines55 56 // git's scissors line: it and everything below it are not the message.57 const SCISSORS = "# ------------------------ >8 ------------------------";58 65-/**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- */59 const endsMessage = (line: string) =>60 line.startsWith(SCISSORS) ||61 (line.startsWith("---") && (line.length === 3 || isSpace(line.slice(3))));62 19 unmodified lines82 `${oneLine(harness)}${model === undefined ? "" : `:${oneLine(model)}`} (${verified ? "verified" : "claimed"})`;83 84 const roleOrder = (role: CreditRole) => CreditRole.literals.indexOf(role);85 96-/**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- */86 const 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 );92 107-/**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- */93 export const formatLanding = (input: LandingMessage): string => {94 const trailers: readonly Trailer[] = [95 ...ordered(input.credits).map(({ handle, role }) => ({96 key: role,160 unmodified lines257 258 return Option.none();259 };260 280-/** A value with its continuation lines folded to single spaces. */261 const 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, "");266 287-/**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- */267 export const parseTrailers = (message: string): readonly Trailer[] => {268 const lines = logLines(message);269 270 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;275 276 for (const line of lines.slice(start)) {65 unmodified lines342 model === undefined ? { harness, verified } : { harness, model, verified }343 );344 };345 372-/** The people a landing credits, and the agents it discloses. */346 export interface LandingCredits {347 readonly credits: readonly Credit[];348 readonly assisted: readonly AgentTrailer[];349 }350 378-/**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. */352 export const creditsOf = (message: string): LandingCredits => {353 const trailers = parseTrailers(message);354 355 return {4 unmodified linesmodified:packages/git/src/tree-diff.ts+2 added-29 removed
4 unmodified lines5 import { Array, Effect, Option, Order, Semaphore } from "effect";6 7 import { Edit, sharedEnds, shortestDiff } from "./line-diff.ts";8 9-/**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. */10 export interface Change {11 readonly path: RepoPath;12 readonly status: "added" | "modified" | "deleted";13 readonly before?: BlobSha;14 readonly after?: BlobSha;15 }16 20-/** A line a change added, numbered from 1 in the new file. */17 export interface AddedLine {18 readonly line: number;19 readonly text: string;20 }97 unmodified lines118 119 return changed.flat();120 });121 126-/**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. */123 export const treeDiff = (124 repo: RepoName,125 base: TreeSha,126 head: TreeSha17 unmodified lines144 145 return lines;146 };147 157-/**158- * Lines of `next` with no partner in `previous`, matched by count: the159- * fallback for a rewrite too large for the shortest script.160- */148 const unmatched = (previous: readonly string[], next: readonly string[]) => {149 const left = new Map<string, number>();150 151 for (const line of previous) {8 unmodified lines160 return count > 0 ? [] : [index];161 });162 };163 177-/**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- */164 const added = (165 previous: readonly string[],166 next: readonly string[]167 ): readonly AddedLine[] =>13 unmodified lines181 : []182 ),183 }).map((index) => ({ line: index + 1, text: next[index] ?? "" }));184 203-/**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- */185 const 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 lines196 // Changes diffed at once, each reading its two blobs together: eight store197 // calls, and no more than four files' text held at a time.198 const CHANGES = { concurrency: STORE_CALLS / 2 } as const;199 222-/**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- */200 export const addedLines = (201 repo: RepoName,202 changes: readonly Change[]203 ): Effect.Effect<26 unmodified linesmodified: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.3 import { CommitSha } from "@repo/protocol/ids";4 import { Array, Option, Schema } from "effect";5 6 import { textLines } from "./pkt-line.ts";7 13-/** What one upload-pack request reads of a repo. */8 export 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 }12 13 const WANT = /^want (?<oid>[0-9a-f]{40})(?: |$)/u;14 15 const asCommit = Schema.decodeOption(CommitSha);16 25-/** The request `bytes` hold, as git wrote it (inflated, if it was gzipped). */17 export const readUpload = (bytes: Uint8Array): UploadRequest => {18 const lines = textLines(bytes);19 20 return {9 unmodified linesmodified:packages/git/src/upstream.ts+1 added-12 removed
1 unmodified line2 import type { RepoNotFound } from "@repo/artifacts/repo-host";3 import { Context, Data, Schema } from "effect";4 import type { Effect } from "effect";5 6-/** The two git services the gateway carries. */6 export type Service = "git-upload-pack" | "git-receive-pack";7 9-/**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. */9 export type Exchange = Data.TaggedEnum<{10 Advertise: { readonly service: Service; readonly headers: Headers };11 Call: {12 readonly service: Service;3 unmodified lines16 }>;17 18 export const Exchange = Data.taggedEnum<Exchange>();19 26-/** The git server behind the gateway did not answer. */20 export class UpstreamFailure extends Schema.TaggedError<UpstreamFailure>()(21 "UpstreamFailure",22 { reason: Schema.String, repo: RepoName }23 ) {}24 32-/**33- * The git server the gateway forwards to, holding the platform's credentials:34- * Artifacts in production, `git http-backend` in tests.35- */25 export class Upstream extends Context.Service<26 Upstream,27 {28 readonly exchange: (5 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { CommitSha } from "@repo/protocol/ids";3 4 import { blame } from "../src/blame.ts";54 unmodified linesmodified:packages/git/test/gateway.test.ts-11 removed
8 unmodified lines9 import { Custody } from "../src/custody.ts";10 import { gitRoute } from "../src/gateway.ts";11 import { admitAll, commit, world } from "./world.ts";12 13-/** Custody that refuses, before forwarding, any push touching `ref`. */13 const refusing = (ref: string, refusals: readonly Refusal[]) =>14 Custody.of({15 admit: (_repo, commands) =>16 Effect.succeed(1 unmodified line18 ),19 review: () => Effect.succeed([]),20 });21 23-/**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- */22 const artifactsBusy = () =>23 new Response("0024\u0003artifacts_git_receive_pack_busy", {24 headers: { "content-type": "application/x-git-receive-pack-result" },25 });26 32-/**33- * The lines git printed from the server's side band, less the spaces git pads34- * them with to clear a progress line.35- */27 const remoteLines = (stderr: string) =>28 stderr29 .split("\n")30 .filter((line) => line.startsWith("remote: "))1 unmodified line32 33 // A credential the client sends; the gateway must keep it from the upstream.34 const asClient = ["-c", "http.extraHeader=Authorization: Bearer client-secret"];35 45-/** Text that compresses poorly, from a fixed seed (Park and Miller's generator). */36 const noise = (length: number) => {37 const digits: string[] = [];38 let state = 20_261_006;39 201 unmodified lines241 );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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 3 import { Edit, lineDiff } from "../src/line-diff.ts";4 5 const lines = (text: string) => (text === "" ? [] : text.split(" "));6 12-/** `before` with `edits` applied, the inserted lines taken from `after`. */7 const apply = (8 before: readonly string[],9 after: readonly string[],10 edits: readonly Edit[]79 unmodified linesmodified: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.