Skip to content
Myr

Add packages/protocol: the closed Refusal union and its one renderer

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

- 23 Schema.TaggedError refusals from the synthesis §9 #18 list, plus RepoBusy for Artifacts' `receive_pack_busy` (S1). Each carries a fixed `retryable` and a `next` command as fields, since Effect's MCP server sends only what the failure schema encodes, and no `message`, so MCP gets JSON. An optional `at: {path, line}` on every refusal. - Retryable means the same answer can land unchanged after waiting or running `next`: StaleBase, RepoBusy, NotClaimed, ClaimLapsed, AskFull, CapReached, AttemptsExhausted, Flake, VerifierBlocked. - Departures from the plan: ChecksFailed's `next` is its reproducing command (no separate `command`); WeakCheck{shape} is WeakCheck{weakness}, since anti-slop bans "shape" in symbol names. - render: `headline` for git's ng line ("OutOfScope and 2 more") and `explain` for remote: lines and the CLI, through an exhaustive Match. - Branded AskId (shell-safe), CommitSha and RepoPath; Posture. - Tests: the closed tag list with its retryable split, a wire round trip for every member, the MCP JSON shape, and a JSON Schema free of "Infinity" and null.

authored by oscabriel · committed by oscabriel · parent bd50d1c · Browse files · 11 files+679 added−0 removed
This commit

State

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

Diff stats

11 files+679 added−0 removed

  • tests:+235 added−0 removed
  • other:+444 added−0 removed

11 files+679 added−0 removed

added:packages/protocol/src/ids.ts+25 added
added:packages/protocol/src/posture.ts+12 added
added:packages/protocol/src/refusal.ts+273 added
1import { Brand } from "@repo/brand";2import { Effect, Schema } from "effect";34import { AskId, CommitSha, RepoPath } from "./ids.ts";5import { Posture } from "./posture.ts";67const cli = (...args: readonly string[]) => [Brand.cli, ...args].join(" ");89const Label = Schema.NonEmptyString;1011const Paths = Schema.NonEmptyArray(RepoPath);1213/** Where in the tree a refusal points, when it points at one line. */14const At = Schema.Struct({15 line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),16 path: RepoPath,17});1819// Every refusal carries `retryable`, fixed per tag, and `next`, the command to20// run next. Both are fields, not statics: Effect's MCP server sends only what21// the failure schema encodes. No refusal has a `message`, so MCP sends JSON.22const Retryable = {23 at: Schema.optionalKey(At),24 next: Schema.NonEmptyString,25 retryable: Schema.tag(true),26};2728const Final = { ...Retryable, retryable: Schema.tag(false) };2930/** A `next` that needs no ids, so the constructor fills it in. */31const nextIs = (command: string) => ({32 next: Schema.NonEmptyString.pipe(33 Schema.withConstructorDefault(Effect.succeed(command))34 ),35});3637// Push and claim3839/** The pusher holds no claim on the ask. */40export class NotClaimed extends Schema.TaggedError<NotClaimed>()("NotClaimed", {41 ...Retryable,42 ask: AskId,43}) {44 static readonly of = (ask: AskId) =>45 new NotClaimed({ ask, next: cli("claim", ask) });46}4748/** The claim expired before this push. */49export class ClaimLapsed extends Schema.TaggedError<ClaimLapsed>()(50 "ClaimLapsed",51 {52 ...Retryable,53 ask: AskId,54 }55) {56 static readonly of = (ask: AskId) =>57 new ClaimLapsed({ ask, next: cli("claim", ask) });58}5960/** No member of the project has vouched for the pusher. */61export class NotVouched extends Schema.TaggedError<NotVouched>()("NotVouched", {62 ...Final,63 ...nextIs(cli("status")),64}) {}6566/** The pusher already holds as many claims as the project allows. */67export class CapReached extends Schema.TaggedError<CapReached>()("CapReached", {68 ...Retryable,69 ...nextIs(cli("status")),70 cap: Schema.Int,71}) {}7273/** Someone else holds the ask's one claim. */74export class AskFull extends Schema.TaggedError<AskFull>()("AskFull", {75 ...Retryable,76 ...nextIs(cli("asks")),77 ask: AskId,78}) {}7980/** The push names no open ask. */81export class NoAsk extends Schema.TaggedError<NoAsk>()("NoAsk", {82 ...Final,83 ...nextIs(cli("asks")),84}) {}8586/** The repo's storage was busy with another push. */87export class RepoBusy extends Schema.TaggedError<RepoBusy>()("RepoBusy", {88 ...Retryable,89 ...nextIs("git push"),90}) {}9192// Shape: these accumulate, so one push hears about every one at once9394/** The answer changes paths outside the ask's territory. */95export class OutOfScope extends Schema.TaggedError<OutOfScope>()("OutOfScope", {96 ...Final,97 ...nextIs(cli("check")),98 paths: Paths,99}) {}100101/** The answer changes the judge closure. */102export class TouchedJudge extends Schema.TaggedError<TouchedJudge>()(103 "TouchedJudge",104 {105 ...Final,106 ...nextIs(cli("check")),107 paths: Paths,108 }109) {}110111/** The answer adds a marker that disables a check, or raises a ratchet. */112export class Weakened extends Schema.TaggedError<Weakened>()("Weakened", {113 ...Final,114 ...nextIs(cli("check")),115 weakening: Schema.Union([116 Schema.Struct({ marker: Label, reason: Schema.optionalKey(Label) }),117 Schema.Struct({118 after: Schema.Int,119 before: Schema.Int,120 ratchet: Label,121 territory: Label,122 }),123 ]),124}) {}125126/** The answer's tree would put held-back paths on main. */127export class PrivatePathInPublicTree extends Schema.TaggedError<PrivatePathInPublicTree>()(128 "PrivatePathInPublicTree",129 { ...Final, ...nextIs(cli("check")), paths: Paths }130) {}131132// Merge133134/** Main moved past the answer's base; git's `fetch first` and `stale ref` land here too. */135export class StaleBase extends Schema.TaggedError<StaleBase>()("StaleBase", {136 ...Retryable,137 ...nextIs("git pull --rebase"),138 base: CommitSha,139 conflicts: Schema.Array(RepoPath),140 main: CommitSha,141}) {}142143// Checks144145/** A check failed; `next` is the command that reproduces it. */146export class ChecksFailed extends Schema.TaggedError<ChecksFailed>()(147 "ChecksFailed",148 {149 ...Final,150 lane: Label,151 logRef: Label,152 }153) {}154155/** A held-back check failed; only its area and suite are disclosed. */156export class HeldBackFailed extends Schema.TaggedError<HeldBackFailed>()(157 "HeldBackFailed",158 { ...Final, ...nextIs(cli("status")), area: Label, suite: Label }159) {}160161/** The pusher used every attempt on an area's held-back checks for now. */162export class AttemptsExhausted extends Schema.TaggedError<AttemptsExhausted>()(163 "AttemptsExhausted",164 {165 ...Retryable,166 ...nextIs(cli("status")),167 area: Label,168 resetsAt: Schema.DateTimeUtcFromString,169 }170) {}171172// Never counted against the answerer173174/** A check failed and then passed on the same tree; the platform retries it. */175export class Flake extends Schema.TaggedError<Flake>()("Flake", {176 ...Retryable,177 ...nextIs(cli("status")),178 lane: Label,179}) {}180181/** The platform could not run the checks. */182export class VerifierBlocked extends Schema.TaggedError<VerifierBlocked>()(183 "VerifierBlocked",184 { ...Retryable, ...nextIs(cli("status")) }185) {}186187// At ask open188189/** The ask's check does not fail on main twice in the same way, by an assertion. */190export class NotRedFirst extends Schema.TaggedError<NotRedFirst>()(191 "NotRedFirst",192 {193 ...Final,194 ...nextIs(cli("check")),195 }196) {}197198/** The ask's check would pass a trivial answer. */199export class WeakCheck extends Schema.TaggedError<WeakCheck>()("WeakCheck", {200 ...Final,201 ...nextIs(cli("check")),202 weakness: Label,203}) {}204205/** The ask's brief leaves out fields its kind requires. */206export class IncompleteBrief extends Schema.TaggedError<IncompleteBrief>()(207 "IncompleteBrief",208 { ...Final, ...nextIs(cli("check")), missing: Schema.NonEmptyArray(Label) }209) {}210211// Maintainers only212213/** A layer's files would enter a public tree. */214export class LayerContentInPublicTree extends Schema.TaggedError<LayerContentInPublicTree>()(215 "LayerContentInPublicTree",216 { ...Final, ...nextIs(cli("check")), paths: Paths }217) {}218219/** A write-only value showed up in output or in the tree. */220export class SecretInOutput extends Schema.TaggedError<SecretInOutput>()(221 "SecretInOutput",222 {223 ...Final,224 ...nextIs(cli("check")),225 item: Label,226 where: Schema.Literals(["output", "tree"]),227 }228) {}229230// Decision231232/** Landing would change the project's posture, which takes a decider. */233export class PostureChange extends Schema.TaggedError<PostureChange>()(234 "PostureChange",235 { ...Final, ...nextIs(cli("today")), from: Posture, to: Posture }236) {}237238/** The closed union. Each member's tag is public: rename one only with an alias. */239export const Refusal = Schema.Union([240 // Push and claim241 NotClaimed,242 ClaimLapsed,243 NotVouched,244 CapReached,245 AskFull,246 NoAsk,247 RepoBusy,248 // Shape: these accumulate, so one push hears about every one at once249 OutOfScope,250 TouchedJudge,251 Weakened,252 PrivatePathInPublicTree,253 // Merge254 StaleBase,255 // Checks256 ChecksFailed,257 HeldBackFailed,258 AttemptsExhausted,259 // Never counted against the answerer260 Flake,261 VerifierBlocked,262 // At ask open263 NotRedFirst,264 WeakCheck,265 IncompleteBrief,266 // Maintainers only267 LayerContentInPublicTree,268 SecretInOutput,269 // Decision270 PostureChange,271]);272273export type Refusal = typeof Refusal.Type;
added:packages/protocol/src/render.ts+86 added
1import { DateTime, Match } from "effect";2import type { Array } from "effect";34import type { Refusal } from "./refusal.ts";56const short = (sha: string) => sha.slice(0, 7);78const list = (items: readonly string[]) => items.join(", ");910// Reasons name only what the refusal's reader may see: held-back checks give11// their area and suite, never a case or an input.12const reason = Match.typeTags<Refusal, string>()({13 AskFull: ({ ask }) => `someone else holds the claim on ${ask}`,14 AttemptsExhausted: ({ area, resetsAt }) =>15 `no attempts left on ${area} until ${DateTime.formatIso(resetsAt)}`,16 CapReached: ({ cap }) =>17 `you already hold ${cap} claims, the most this project allows`,18 ChecksFailed: ({ lane, logRef }) =>19 `the ${lane} checks failed; the log is at ${logRef}`,20 ClaimLapsed: ({ ask }) => `your claim on ${ask} lapsed`,21 Flake: ({ lane }) =>22 `the ${lane} checks failed, then passed on the same tree; the platform will run them again`,23 HeldBackFailed: ({ area, suite }) =>24 `a held-back check failed in ${area}, suite ${suite}`,25 IncompleteBrief: ({ missing }) => `the brief is missing ${list(missing)}`,26 LayerContentInPublicTree: ({ paths }) =>27 `a layer's files would enter a public tree: ${list(paths)}`,28 NoAsk: () => "this push names no open ask",29 NotClaimed: ({ ask }) => `you hold no claim on ${ask}`,30 NotRedFirst: () =>31 "the ask's check must fail on main twice in the same way, by an assertion",32 NotVouched: () => "no member of this project has vouched for you",33 OutOfScope: ({ paths }) =>34 `changes paths outside the ask's territory: ${list(paths)}`,35 PostureChange: ({ from, to }) =>36 `landing would change the posture from ${from} to ${to}, which takes a decider`,37 PrivatePathInPublicTree: ({ paths }) =>38 `would put held-back paths in a public tree: ${list(paths)}`,39 RepoBusy: () => "the repo was busy with another push",40 SecretInOutput: ({ item, where }) =>41 `the write-only value ${item} appeared in the ${where}`,42 StaleBase: ({ base, conflicts, main }) =>43 conflicts.length === 044 ? `main moved to ${short(main)}, past your base ${short(base)}`45 : `main moved to ${short(main)}, past your base ${short(base)}; conflicts in ${list(conflicts)}`,46 TouchedJudge: ({ paths }) =>47 `changes files that decide what the checks do: ${list(paths)}`,48 VerifierBlocked: () =>49 "the platform could not run the checks; it will run them again",50 WeakCheck: ({ weakness }) => `the ask's check is weak: ${weakness}`,51 Weakened: ({ weakening }) => {52 if ("ratchet" in weakening) {53 return `raises the ${weakening.ratchet} ratchet in ${weakening.territory} from ${weakening.before} to ${weakening.after}`;54 }5556 return weakening.reason === undefined57 ? `adds ${weakening.marker} without a reason`58 : `adds ${weakening.marker}, with the reason "${weakening.reason}"`;59 },60});6162const block = (refusal: Refusal) => [63 `${refusal._tag}: ${reason(refusal)}`,64 ...(refusal.at === undefined65 ? []66 : [` at: ${refusal.at.path}:${refusal.at.line}`]),67 ` next: ${refusal.next}`,68 ` retryable: ${refusal.retryable ? "yes" : "no"}`,69];7071/** The reason on git's `ng` line: the first refusal's tag, and how many follow. */72export const headline = (refusals: Array.NonEmptyReadonlyArray<Refusal>) => {73 const [first, ...rest] = refusals;7475 return rest.length === 076 ? first._tag77 : `${first._tag} and ${rest.length} more`;78};7980/**81 * What a person reads, one line each, for git `remote:` lines and the CLI:82 * every refusal's reason, where it points, its next command and whether83 * retrying can help.84 */85export const explain = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>86 refusals.flatMap(block);
added:packages/protocol/test/examples.ts+74 added
added:packages/protocol/test/refusal.test.ts+87 added
1import { describe, expect, it } from "@effect/vitest";2import { Schema } from "effect";34import { RepoPath } from "../src/ids.ts";5import { Refusal, StaleBase } from "../src/refusal.ts";6import { base, examples, main } from "./examples.ts";78// What Effect's MCP server sends for a declared tool failure that has no9// message: the failure schema's encoding, through JSON.stringify10// (`effect/src/ai/McpServer.ts` l.1864-1867 in 4.0.1).11const overTheWire = (refusal: Refusal) =>12 JSON.stringify(Schema.encodeSync(Refusal)(refusal));1314describe("the refusal union", () => {15 it("reaches MCP as JSON with its tag, fields, retryable and next", () => {16 const refusal = new StaleBase({17 base,18 conflicts: [RepoPath.make("src/a.ts")],19 main,20 });2122 expect(refusal.message).toBe("");23 expect(JSON.parse(overTheWire(refusal))).toStrictEqual({24 _tag: refusal._tag,25 base,26 conflicts: ["src/a.ts"],27 main,28 next: "git pull --rebase",29 retryable: true,30 });31 });3233 it.each(examples)("$_tag comes back from the wire as it left", (refusal) => {34 const decoded = Schema.decodeUnknownSync(Refusal)(35 JSON.parse(overTheWire(refusal))36 );3738 expect(decoded.message).toBe("");39 expect(decoded).toStrictEqual(refusal);40 });4142 // MCP tool schemas come from this document. A bare `Schema.Number` admits43 // the strings "Infinity" and "NaN"; a bare `Schema.optional` admits `null`.44 it("has a JSON Schema with no non-finite numbers and no nulls", () => {45 const document = JSON.stringify(Schema.toJsonSchemaDocument(Refusal));4647 expect(document).not.toMatch(/Infinity|NaN|"null"/u);48 });4950 // A failure here means a tag was added, removed or renamed, or a refusal51 // changed whether retrying helps. Both are public contract: rename a tag only52 // with an alias, and update the reference docs.53 it("is closed: exactly these tags, each saying whether retrying can help", () => {54 expect(Refusal.members.map((member) => member.identifier)).toStrictEqual(55 examples.map((refusal) => refusal._tag)56 );57 expect(58 Object.fromEntries(59 examples.map((refusal) => [refusal._tag, refusal.retryable])60 )61 ).toStrictEqual({62 AskFull: true,63 AttemptsExhausted: true,64 CapReached: true,65 ChecksFailed: false,66 ClaimLapsed: true,67 Flake: true,68 HeldBackFailed: false,69 IncompleteBrief: false,70 LayerContentInPublicTree: false,71 NoAsk: false,72 NotClaimed: true,73 NotRedFirst: false,74 NotVouched: false,75 OutOfScope: false,76 PostureChange: false,77 PrivatePathInPublicTree: false,78 RepoBusy: true,79 SecretInOutput: false,80 StaleBase: true,81 TouchedJudge: false,82 VerifierBlocked: true,83 WeakCheck: false,84 Weakened: false,85 });86 });87});
added:packages/protocol/test/render.test.ts+74 added
added:packages/protocol/package.json+25 added
added:packages/protocol/tsconfig.json+7 added
added:packages/protocol/vitest.config.ts+1 added
modified:bun.lock+15 added
37 unmodified lines
38 "typescript": "catalog:",39 "vitest": "catalog:",40 },41 },42 "packages/protocol": {43 "name": "@repo/protocol",44 "dependencies": {45 "@repo/brand": "workspace:*",46 "effect": "catalog:",47 },48 "devDependencies": {49 "@effect/vitest": "catalog:",50 "@repo/config": "workspace:*",51 "typescript": "catalog:",52 "vitest": "catalog:",53 },54 },55 },56 "catalog": {57 "@effect/platform-bun": "4.0.1",58 "@effect/vitest": "4.0.1",
225 unmodified lines
284 "@repo/brand": ["@repo/brand@workspace:packages/brand"],285286 "@repo/config": ["@repo/config@workspace:packages/config"],287288 "@repo/protocol": ["@repo/protocol@workspace:packages/protocol"],289290 "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],291292 "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.12", "", { "os": "android", "cpu": "arm64" }, "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg=="],293
391 unmodified lines