Skip to content
Myr

Trim comments in drafting, gate and the git package to the essential ones

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

authored by oscabriel · committed by oscabriel · parent f314385 · Browse files · 57 files+84 added−924 removed
This commit

State

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

Diff stats

57 files+84 added−924 removed

  • tests:+3 added−168 removed
  • other:+81 added−756 removed

57 files+84 added−924 removed

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