Skip to content
Myr

Merge build/comments-cli-protocol-checks into main

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

authored by oscabriel · committed by oscabriel · parents 5792317, bc299e2 · Browse files · 165 files+221 added−3717 removed
This commit

State

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

Diff stats

165 files+221 added−3717 removed

  • tests:+20 added−773 removed
  • other:+201 added−2944 removed

165 files+221 added−3717 removed

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

modified:apps/cli/src/entries/protocol.ts-5 removed
1/**2 * The package's `./protocol` export: types only, for a maintainer's config3 * folder that names the data its rules evaluate to (the policy, its asks,4 * kinds, checks and territories) and the ids inside it.5 */1export type {2 AreaName,3 AskId,4 Handle,
35 unmodified lines
modified:apps/cli/src/entries/rules.ts+1 added-7 removed
1/**2 * The package's `./rules` export: the sdk a maintainer imports in the config3 * folder (`project.ts`, `asks/<id>.ask.ts`, `visibility.ts`; a layer's4 * `layer.ts`), inlined at build time so the published package names no5 * workspace package. It names every export of `@repo/sdk`;6 * `test/build.test.ts` fails when the two drift apart.7 */1// Inlined at build time so the published package names no workspace package; `test/build.test.ts` fails when this drifts from `@repo/sdk`.2export {3 type Admit,4 type AreaOf,5 type ArgFields,
64 unmodified lines
modified:apps/cli/src/hook/decide.ts+3 added-68 removed
1/**2 * The one hook policy: what `<cli> hook <event>` answers a harness, from3 * facts gathered elsewhere. Pure, so every harness adapter (Claude Code's4 * hook format here; pi's events in `../pi.ts`) asks the same function.5 *6 * It writes no second policy: a path's refusal is the gate's own reading of7 * the territory and the judge closure (`@repo/gate/glob`, over the closure8 * `@repo/checks` computes), and its text is `@repo/protocol/render`'s9 * `explain`, the very lines the gateway sends. The gateway stays the10 * authority; a hook is early feedback, so anything it cannot judge it allows.11 */1// A hook is early feedback and the gateway stays the authority, so anything it cannot judge it allows.2import { claudeEventOf } from "@repo/agent-kit/hook-events";3import type { HookEvent } from "@repo/agent-kit/hook-events";4import { Brand } from "@repo/brand";5import { matchAny } from "@repo/gate/glob";
6 unmodified lines
12import { Array, Option, Predicate, Schema } from "effect";1314import type { HookInput } from "./input.ts";1526/** The claim this session works on, as the hook needs it. */16export const HookClaim = Schema.Struct({17 ask: AskId,29 /** Main when the claim was made: where the gateway's diff of an answer starts. */18 base: CommitSha,31 /** What `<cli> check` runs locally for the ask: the claim's own. */19 checkCommand: Schema.NonEmptyString,20 project: ProjectName,21 territory: Territory,22 want: Schema.NonEmptyString,23});2425export type HookClaim = typeof HookClaim.Type;2640/** What the policy decides over. */27export interface HookFacts {42 /** The repo's top folder. */28 readonly root: string;29 readonly claim: Option.Option<HookClaim>;45 /** The judge closure at the claim's base, with the ask's own files. */30 readonly judge: Policy["judge"];47 /** Stop only: what `<cli> check --shape-only` refuses now; none when it passes. */31 readonly refusals: readonly Refusal[];49 /** Stop holds in a row this session, before this event. */32 readonly holds: number;33}3453/** Go on, as the harness would without the hook: `{}`, with no field at all. */35type GoOn = Readonly<Record<string, never>>;3656/** Claude Code's PreToolUse denial: the tool does not run, and the agent reads the reason. */37interface Deny {38 readonly hookSpecificOutput: {39 readonly hookEventName: (typeof claudeEventOf)["pre-tool-use"];40 readonly permissionDecision: "deny";41 readonly permissionDecisionReason: string;42 };43}4465/** Claude Code's SessionStart context: Markdown the agent reads first. */45interface Brief {46 readonly hookSpecificOutput: {47 readonly additionalContext: string;48 readonly hookEventName: (typeof claudeEventOf)["session-start"];49 };50}5173/** Claude Code's Stop hold: the agent goes on, with the reason as its next prompt. */52interface Hold {53 readonly decision: "block";54 readonly reason: string;55}5679/** The exact JSON written to stdout. */57export type HookOutput = GoOn | Deny | Brief | Hold;5882/** The answer, the holds in a row after it, and a line for stderr. */59export interface HookDecision {60 readonly output: HookOutput;61 readonly holds: number;62 readonly note: Option.Option<string>;
1 unmodified line
6465const NO_CLAIM =66 "no claim in this session's repo, so the hook allows everything; the gateway still judges every push";6792/** Go on, as the harness would without the hook. */68const allow = (holds: number, note?: string): HookDecision => ({69 holds,70 note: Option.fromUndefinedOr(note),71 output: {},72});7399// ------------------------------------------------------------ paths100101/** `path` with `.` and `..` resolved and no empty segments: `/a/b`. */74const normalize = (path: string) => {75 const parts: string[] = [];7677 for (const part of path.split("/")) {
6 unmodified lines
8485 return `/${parts.join("/")}`;86};87116/**117 * The repo path a tool's file names: absolute, or relative to the118 * harness's cwd. A file outside the repo, or the root itself, is none.119 */88const repoPathOf = (89 root: string,90 cwd: string,91 file: string
6 unmodified lines
98 ? Option.some(RepoPath.make(absolute.slice(prefix.length)))99 : Option.none();100};101134/** The tools that write a file, and the input key that names it. */102const WRITERS = new Map([103 ["Edit", "file_path"],104 ["MultiEdit", "file_path"],105 ["NotebookEdit", "notebook_path"],106 ["Write", "file_path"],107]);108142/** The file a writing tool is about to change, if the call is one. */109const fileOf = (input: HookInput): Option.Option<string> =>110 Option.flatMap(Option.fromUndefinedOr(input.tool_name), (name) =>111 Option.flatMap(Option.fromUndefinedOr(WRITERS.get(name)), (key) =>112 Option.filter(
2 unmodified lines
115 )116 )117 );118153/**154 * What the gate's shape stage says of one changed path: a judged path is155 * `TouchedJudge` wherever it is, any other path outside the territory is156 * `OutOfScope`, as `@repo/gate/stages/shape` reads them.157 */119const pathRefusals = (120 claim: HookClaim,121 judge: Policy["judge"],122 path: RepoPath
6 unmodified lines
129 ? []130 : [new OutOfScope({ paths: [path] })];131};132172/**173 * What the gate's shape stage would refuse of the file a writing tool is174 * about to change: none without a claim, for a tool that writes no file, or175 * for a file outside the repo. Every harness's edit guard asks this (Claude176 * Code's pre-tool-use below; pi's `edit` and `write` in `../pi.ts`).177 */133export const toolRefusals = (134 input: HookInput,135 facts: Pick<HookFacts, "claim" | "judge" | "root">136): readonly Refusal[] =>
32 unmodified lines
169 : allow(facts.holds);170 },171 });172218// ------------------------------------------------------------ brief219173const bullets = (items: readonly string[]) =>174 items.map((item) => `- \`${item}\``);175223/** The claim as the agent reads it first, in Markdown. */176const brief = ({ ask, checkCommand, project, territory, want }: HookClaim) =>177 [178 `# Your claim: ${ask} in ${project}`,179 "",180 `**Want:** ${want}`,181 "",230 // A paths territory (module `.`) is no module a reader would know: it231 // reads as its paths alone, as the project's own brief does.182 // A paths territory (module `.`) reads as its paths alone.183 territory.module === "."184 ? "**Territory:** these paths. Change only these:"185 : `**Territory:** the module \`${territory.module}\`. Change only these paths:`,186 ...bullets(territory.paths),
27 unmodified lines
214 },215 }),216 });217267// ------------------------------------------------------------ stop268269/** The most Stop holds in a row; the next stop goes through. */218export const MAX_HOLDS = 3;219272/**273 * Stop holds the agent while `<cli> check --shape-only` refuses its work274 * with a refusal it can fix, at most `MAX_HOLDS` times in a row. A retryable275 * refusal is a wait (the repo was busy, a lane flaked), not the agent's to276 * fix, so it never holds. Claude Code's `stop_hook_active` says this stop277 * follows a hold, so it counts as at least one even when the session's own278 * count was lost; nothing but an allowed stop resets the count, so the cap279 * holds whatever a harness sends.280 */220/** A retryable refusal never holds. `stop_hook_active` counts as at least one hold even if the session's count was lost. */221const stopHook = (input: HookInput, facts: HookFacts): HookDecision => {222 const before =223 input.stop_hook_active === true ? Math.max(facts.holds, 1) : facts.holds;224
20 unmodified lines
245 output: { decision: "block", reason: explain(fixable).join("\n") },246 };247};248309/** Each event's policy. */249const policies = {250 "pre-tool-use": preToolUse,251 "session-start": (_input, facts) => sessionStart(facts),252 stop: stopHook,
1 unmodified line
254 HookEvent,255 (input: HookInput, facts: HookFacts) => HookDecision256>;257319/**320 * What the hook answers `event`: `{}` to let the harness go on, or Claude321 * Code's own form of a brief, a denial or a hold.322 */258export const decideHook = (259 event: HookEvent,260 input: HookInput,261 facts: HookFacts
1 unmodified line
modified:apps/cli/src/hook/facts.ts+2 added-28 removed
1/**2 * The facts a hook session decides by, gathered once per session: the repo3 * the harness runs in, the claim its remote names, the ask behind it (one4 * `showAsk`), and the judge closure at the claim's base. Anything missing5 * leaves the session without a claim, with the reason, and the hook allows.6 */1import { Brand } from "@repo/brand";2import { Client } from "@repo/protocol/contracts";3import type { ClaimView } from "@repo/protocol/domain/claim";4import { Cause, Duration, Effect, Option, Result, Schema } from "effect";
4 unmodified lines
9import type { HookClaim } from "./decide.ts";10import { askJudge, judgeAt } from "./judge.ts";11import type { SessionState } from "./session.ts";1219/** No closure: a session without a claim judges nothing. */13const NO_JUDGE: SessionState["judge"] = { paths: [], pointers: [] };1415const without = (root: string, why: string): SessionState => ({16 holds: 0,
1 unmodified line
18 root,19 why,20});2129/**30 * How long the platform has to answer one call. A hook the harness kills31 * for its time also lets the agent go on, but only after the harness's own32 * limit (a minute in Claude Code), on every turn.33 */22/** A hook the harness kills for its time also lets the agent go on, but only after the harness's own limit, every turn. */23const PLATFORM_LIMIT = Duration.seconds(10);2436/** The platform did not answer in time; the session goes on without a claim. */25class PlatformSilent extends Schema.TaggedError<PlatformSilent>()(26 "PlatformSilent",27 { limit: Schema.String }28) {
1 unmodified line
30 return `the platform did not answer within ${this.limit}`;31 }32}3346/** A platform call, given at most `PLATFORM_LIMIT` to answer. */34const inTime = <A, E, R>(call: Effect.Effect<A, E, R>) =>35 Effect.timeoutOrElse(call, {36 duration: PLATFORM_LIMIT,37 orElse: () =>
1 unmodified line
39 new PlatformSilent({ limit: Duration.format(PLATFORM_LIMIT) })40 ),41 });4256/** A failure's first line, for a reason on stderr. */43const firstLine = (cause: Cause.Cause<unknown>) =>44 String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";4546const isLive = (claim: ClaimView) =>47 claim.state === "live" || claim.state === "warned";4863/**64 * The caller's claim this repo works on: the one a claim's fork names, or,65 * in the project's own repo or a working fork, the caller's only live claim66 * in the project (an answer may be made in a clone of main and pushed to the67 * fork). Otherwise why there is none.68 */49/** In the project's own repo or a working fork, the caller's only live claim: an answer may be made in a clone of main. */50const claimFor = (51 ref: RepoRef,52 claims: readonly ClaimView[]53): Result.Result<ClaimView, string> => {
23 unmodified lines
77 `you hold ${live.length} live claims in ${ref.project}, and this repo's remote names none of them`78 );79};80100/**101 * The session's facts for a harness running in `cwd`. The repo's remote102 * names the project, and a claim's fork (`<owner>/<name>--<ask>--<handle>`)103 * the ask; `status` gives the caller's live claim and its check104 * command; `showAsk` gives the want and the territory; git gives the files105 * at the claim's base for the judge closure.106 */81export const gatherFacts = (82 cwd: string83): Effect.Effect<84 SessionState,
57 unmodified lines
modified:apps/cli/src/hook/input.ts-11 removed
1/**2 * What a harness hands a hook on stdin, in Claude Code's hook format (which3 * Cursor and Copilot CLI also read), decoded at the boundary. Only the fields4 * the hook policy reads; the rest of the payload is ignored.5 */1import { Schema } from "effect";23export const HookInput = Schema.Struct({9 /** The folder the harness runs in. */4 cwd: Schema.String,5 hook_event_name: Schema.String,12 /** The harness's session: holds and facts are kept per session. */6 session_id: Schema.NonEmptyString,14 /** Claude Code: `true` when this stop follows a Stop hook's hold. */7 stop_hook_active: Schema.optionalKey(Schema.Boolean),16 /** PreToolUse: the tool's arguments. */8 tool_input: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),18 /** PreToolUse: the tool about to run. */9 tool_name: Schema.optionalKey(Schema.String),10});1112export type HookInput = typeof HookInput.Type;1324/** The whole of stdin, as JSON text, to a `HookInput`. */14export const decodeHookInput = Schema.decodeUnknownEffect(15 Schema.fromJsonString(HookInput)16);
modified:apps/cli/src/hook/judge.ts+1 added-23 removed
1/**2 * The judge closure a hook session decides by: the closure `@repo/checks`3 * computes over the repo's files at the claim's base (the files the4 * platform reads, gathered by the same `judgeInputs`), plus the ask's own5 * files, which the gate's shape stage judges for every answer.6 */1import { findRunBlock } from "@repo/checks/finder";2import { judgeClosure } from "@repo/checks/judge";3import type { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec } from "@repo/protocol/domain/check";
4 unmodified lines
9import type { ChildProcessSpawner } from "effect/process";1011import { judgeFilesAt } from "../local/judge-files.ts";1219/**20 * The closure with the ask's own files (its file in the config folder, and21 * a `redThenGreen` check's file), each anchored at the root: the gate's shape22 * stage judges them for every answer to the ask.23 */13export const askJudge = (14 closure: Policy["judge"],15 ask: Ask16): Policy["judge"] => {
7 unmodified lines
24 pointers: closure.pointers,25 };26};2739// ------------------------------------------------------------ at the base4028const decodeRun = Schema.decodeUnknownOption(RunBlock);2943/**44 * The judge closure at `base`, as `@repo/checks` computes it over the files45 * the platform reads there: every file of its tree, with the text of each46 * one the finder or the closure reads, gathered by the same `judgeInputs`47 * the platform and `<cli> check` gather through (none when git cannot read48 * `base`). The run block is the one the finder finds in those files, with49 * the claim's check command as its `test` when it finds none: the config50 * folder's own run block needs the config evaluated, which only51 * `<cli> check` does.52 */30/** The config folder's run block needs the config evaluated, which only `<cli> check` does, so the claim's check command stands in. */31export const judgeAt = (input: {32 readonly root: string;33 readonly base: string;34 readonly test: string;
15 unmodified lines
modified:apps/cli/src/hook/push-check.ts+4 added-34 removed
1/**2 * The Stop hook's question: does `<cli> check` refuse the work as it stands?3 * Asked through a port, so the hook never imports the check command's4 * modules: the default adapter runs this same CLI as a child process,5 * `check --shape-only --offline --json --base <claim's base>`, and decodes6 * its envelope. Offline, the check cannot read the claim's base itself, and7 * main would be the wrong start for work committed on main.8 */1// A port, so the hook never imports the check command's modules. Offline, the check cannot read the2// claim's base itself, so it is passed: main would be the wrong start for work committed on main.3import { Envelope } from "@repo/protocol/envelope";4import type { Refusal } from "@repo/protocol/refusal";5import {6 Context,
5 unmodified lines
12 Stream,13} from "effect";14import { ChildProcess, ChildProcessSpawner } from "effect/process";1522/** The check could not say: it did not start, ran too long, or printed no envelope. */16export class PushCheckFailed extends Schema.TaggedError<PushCheckFailed>()(17 "PushCheckFailed",18 { reason: Schema.String }19) {
4 unmodified lines
2425export class PushCheck extends Context.Service<26 PushCheck,27 {35 /**36 * The refusals `<cli> check --shape-only` gives for the repo at `root`,37 * diffed from the claim's `base` as the gateway diffs; none when it passes.38 */28 readonly run: (29 root: string,30 base: string31 ) => Effect.Effect<readonly Refusal[], PushCheckFailed>;32 }33>()("cli/PushCheck") {}3446/** The arguments after the CLI's own command. */35const CHECK = ["check", "--shape-only", "--offline", "--json"] as const;3649/** The check reads the diff and the config and runs nothing: a minute is plenty. */37const LIMIT = Duration.minutes(1);3839const decodeEnvelope = Schema.decodeUnknownEffect(40 Schema.fromJsonString(Envelope(Schema.Unknown))
1 unmodified line
4243const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>44 bytes.pipe(Stream.decodeText(), Stream.mkString);4559/**60 * `PushCheck` over a child process: `command` (the CLI, as this process was61 * started) with `check --shape-only --offline --json --base <base>`, in62 * `root`. A refusal ends it with the refusal's exit code, but the envelope63 * says all, so only the envelope is read.64 */46/** A refusal ends with the refusal's exit code, but the envelope says all, so only the envelope is read. */47export const pushCheckWith = (48 command: readonly [string, ...string[]]49): Layer.Layer<PushCheck, never, ChildProcessSpawner.ChildProcessSpawner> =>50 Layer.effect(
55 unmodified lines
106 return { run };107 })108 );109128/** How this process was started, as the runtime's `process` global reports it. */110const Started = Schema.Struct({111 argv: Schema.Array(Schema.String),112 execPath: Schema.NonEmptyString,113});114134/** The global scope, read only for its `process`. */115const GlobalScope = Schema.Struct({ process: Started });116137/**138 * The command that runs this CLI again: a compiled binary is its own139 * executable (its entry lives in Bun's embedded `/$bunfs/` or `B:/~BUN/`),140 * otherwise the runtime runs the entry it was started with.141 */117/** A compiled binary is its own executable: its entry lives in Bun's embedded `/$bunfs/` or `B:/~BUN/`. */118export const selfCommand = (119 started: typeof Started.Type120): readonly [string, ...string[]] => {121 const [, entry] = started.argv;
4 unmodified lines
126 ? [started.execPath]127 : [started.execPath, entry];128};129154/**155 * The default `PushCheck`: this same CLI, run again as a child process.156 * The global scope is decoded at the boundary (the CLI's types name no157 * runtime); a runtime without a `process` (none the CLI ships on) fails158 * every check, which the hook allows.159 */130export const PushCheckChild: Layer.Layer<131 PushCheck,132 never,133 ChildProcessSpawner.ChildProcessSpawner
19 unmodified lines
modified:apps/cli/src/hook/session.ts+1 added-22 removed
1/**2 * What a hook session keeps between events: the facts `session-start`3 * gathered (so `pre-tool-use` asks the platform nothing) and the Stop holds4 * in a row. One file per harness session, under5 * `${XDG_STATE_HOME:-$HOME/.local/state}/<slug>/hooks/`. It is a cache: a6 * file that cannot be read is no file, and one that cannot be written is7 * skipped, so the hook still answers.8 */1// A cache: a file that cannot be read is no file, and one that cannot be written is skipped.2import { Brand } from "@repo/brand";3import { NoneOrMore } from "@repo/protocol/domain/common";4import { Policy } from "@repo/protocol/domain/policy";5import { Config, Effect, FileSystem, Hash, Option, Path, Schema } from "effect";67import { HookClaim } from "./decide.ts";816/** One session's facts and holds, as its file holds them. */9export const SessionState = Schema.Struct({10 claim: Schema.optionalKey(HookClaim),11 holds: NoneOrMore,12 judge: Policy.fields.judge,21 /** The repo's top folder, or the harness's cwd outside a repo. */13 root: Schema.String,23 /** Why the session has no claim, said again on each event's stderr. */14 why: Schema.optionalKey(Schema.String),15});1617export type SessionState = typeof SessionState.Type;1829/** The session's state could not be kept; the hook says so and goes on. */19export class SessionUnsaved extends Schema.TaggedError<SessionUnsaved>()(20 "SessionUnsaved",21 { reason: Schema.String }22) {
17 unmodified lines
40const FILE_MODE = 0o600;4142const DIR_MODE = 0o700;4355/**56 * A session id as a file name: as it is when it is a plain name (Claude57 * Code's are UUIDs), else its safe characters and a hash of the whole.58 */44const fileNameOf = (session: string) =>45 /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(session)46 ? `${session}.json`47 : `${session.replaceAll(/[^A-Za-z0-9._-]/gu, "_").slice(0, 64)}-${Hash.string(session).toString(36)}.json`;4864/** The session's file, when the env names a home for it. */49const fileOf = (session: string) =>50 Effect.gen(function* () {51 const path = yield* Path.Path;52
9 unmodified lines
62 (state) => path.join(state, Brand.slug, "hooks", fileNameOf(session))63 );64 });6582/** The session's kept state, if its file is there and reads back whole. */66export const loadSession = (67 session: string68): Effect.Effect<69 Option.Option<SessionState>,
12 unmodified lines
82 yield* Effect.flatMap(fs.readFileString(file.value), decodeFile)83 );84 }).pipe(Effect.orElseSucceed(() => Option.none<SessionState>()));85103/**104 * Keeps the session's state, replacing the file whole. Fails only so the105 * caller can say why on stderr.106 */86export const saveSession = (87 session: string,88 state: SessionState89): Effect.Effect<void, SessionUnsaved, FileSystem.FileSystem | Path.Path> =>
31 unmodified lines
modified:apps/cli/src/local/check.ts+4 added-79 removed
1/**2 * `<cli> check`: the gate's answer for HEAD before it is pushed. It runs the3 * gate's own stages 0 and 1 (`@repo/gate`'s `pushStages`) over the facts a4 * push of HEAD to the claim's fork would give the gateway (`localFacts`),5 * under the policy at `main` (`localPolicy`), and prints the same refusals,6 * tag for tag; then it runs the ask's check and the project's lanes on7 * HEAD's tree, in a temp clone, through `CheckRunner` `/local`, and counts8 * the project's ratchets on HEAD and on its base (`ratchets.ts`), refusing9 * a raised count with the platform's `Weakened{ratchet}`.10 *11 * Nothing here writes to the repo, its config or its refs, and `--offline`12 * calls no platform: the parse stage then judges a live claim made up for13 * the person checking, and says so on stderr.14 */1// Writes nothing to the repo, its config or its refs; `--offline` calls no platform.2import { Brand } from "@repo/brand";3import {4 CheckAt,5 CheckLane,
63 unmodified lines
69import type { StaleCopy } from "./stale.ts";7071const COMMAND = "check";7286/** A generated file in the working copy that main's config no longer gives (`stale.ts`). */73const Stale = Schema.Struct({88 /** The landing the copy says it came from, when it names one. */74 landed: Schema.optionalKey(LandedSha),75 path: Schema.String,76});7793/**94 * What `check --json` prints on success: the ask, the diff it judged, each95 * lane, each ratchet's count on the base and on HEAD when it counted any,96 * and the generated files that are out of date, when any are.97 */78const Checked = Schema.Struct({79 ask: AskId,80 base: CommitSha,81 head: CommitSha,82 lanes: Schema.Array(LaneResult),83 ratchets: Schema.optionalKey(Schema.NonEmptyArray(RatchetMove)),104 /** The last stage that ran: `shape` with `--shape-only`, else `checks`. */84 stage: Schema.Literals(["shape", "checks"]),85 stale: Schema.optionalKey(Schema.NonEmptyArray(Stale)),86});87
2 unmodified lines
90const encodeChecked = Schema.encodeEffect(Checked);9192const isRefusal = Schema.is(Refusal);93115/** The handle a check stands in for when nobody is signed in and no fork names one. */94const SOMEONE = Handle.make("you");9596const asHandle = Schema.decodeOption(Handle);97120/** A claim that holds the fork open: `live`, or `warned` and not yet lapsed. */98const isLive = (claim: ClaimView) =>99 claim.state === "live" || claim.state === "warned";100124/** Prints `text` on stderr, then ends the command: it has said why. */101const stop = (text: string) =>102 Output.use((output) =>103 Effect.andThen(output.note(text), Effect.fail(new Reported()))104 );105130/** Prints `refusals` the way every command does, then ends the command with their exit code. */106const refuse = (107 json: boolean,108 refusals: Array.NonEmptyReadonlyArray<Refusal>109) =>110 Output.use((output) =>111 endRefused(output, { command: COMMAND, json, refusals })112 );113139/**140 * What a stale copy is told: which file, the landing it names, why it can141 * differ (an older config or a hand edit; the copy alone can't say which),142 * and how to get a current one.143 */114const staleNote = ({ landed, path }: StaleCopy) =>115 `${path} differs from what main's config gives${Option.match(landed, {116 onNone: () => "",117 onSome: (sha) => ` (it says it was generated at ${sha})`,118 })}: it was generated for an older config, or edited by hand. The platform regenerates it whenever the config changes; pull main for the current copy instead of editing it.`;119150/** The stale copies as `--json` lists them: absent when there are none. */120const staleField = (stale: readonly StaleCopy[]) =>121 Array.match(stale, {122 onEmpty: () => ({}),123 onNonEmpty: (copies) => ({
5 unmodified lines
129 ),130 }),131 });132164/** The signed-in profile's handle, when `login` learned one. */133const signedInHandle = Effect.flatMap(134 Effect.serviceOption(Credentials),135 Option.match({136 onNone: () => Effect.succeedNone,
3 unmodified lines
140 ),141 })142);143176/** The project and ask a check is for: the flags', else the remote's. */144const subjectOf = (145 context: RepoContext,146 flags: {147 readonly ask: Option.Option<AskId>;
38 unmodified lines
186187 return { ask: inferred.value, project: project.value };188 });189223/** The caller's claims in `project`, as the platform's `status` lists them. */190const claimsOn = (project: ProjectName, json: boolean) =>191 Effect.gen(function* () {192 const client = yield* Client;193
10 unmodified lines
204 )205 );206 });207242/**243 * Where the diff starts: `--base` when given; else the live claim's base,244 * which is what the gateway diffs a push to the claim's fork from (so an245 * answer committed on the clone's own main is still seen), when this repo246 * holds that commit; else `main`.247 */208/** The gateway diffs a fork push from the claim's base, so an answer committed on the clone's own main is still seen. */209const baseOf = (210 root: string,211 given: Option.Option<string>,212 claim: Option.Option<ClaimView>
22 unmodified lines
235236 return "main";237 });238278/**279 * A live claim on `ask` by `claimant`, as the platform would hold one just280 * made: the parse stage's stand-in when the check runs offline.281 */239const syntheticClaim = (input: {240 readonly ask: Ask;241 readonly claimant: Handle;242 readonly fork: RepoName;286 /** The platform the repo's remote reaches, which serves the fork. */243 readonly origin: Option.Option<string>;244 readonly policy: Policy;245}) =>246 Effect.map(DateTime.now, (now): ClaimView => {
11 unmodified lines
258 Duration.millis(policy.claims.lapseAfterMs)259 ),260 openedAt: now,261 project: ask.project,306 // The fork's address: the project's name, then the fork's parts.262 remote: Option.match(input.origin, {263 onNone: () => `${address}.git`,264 onSome: (origin) => `${origin}/${address}.git`,265 }),
4 unmodified lines
270 ),271 };272 });273319/**320 * The lanes an answer's checks run: the ask's own check, then every project321 * lane. A `lintToZero` ask's lane hands back what its lint printed, since322 * its count, not its exit code, judges it.323 */274const lanesOf = (policy: Policy, ask: Ask): readonly CheckLane[] => [275 ...Option.toArray(276 Option.map(277 commandFor(ask.check, policy.run, policy.ratchets),
7 unmodified lines
285 CheckLane.make({ command, lane })286 ),287];288339/**340 * The run with a `lintToZero` ask's lane as its count decides it, as the341 * platform's Answer Workflow does (`countedAskLane` in342 * `apps/platform/src/workflows/answer/lanes.ts`): passed at zero findings343 * of its rule in its territory, failed above (its evidence says how many),344 * a load error when its lint printed no count. A lane that never got going345 * stays as it ran.346 */289/** Mirrors the platform's `countedAskLane` (`apps/platform/src/workflows/answer/lanes.ts`). */290const countedAskLane = (291 policy: Policy,292 ask: Ask,293 ran: CheckRun
58 unmodified lines
352 )353 );354};355413/** The last lines of a setup's output, for the note that says why it failed. */356const TAIL = 4000;357416/**417 * HEAD's tree in a temp clone the scope removes: it borrows the repo's418 * objects (`--shared`), so nothing is copied or written back, runs no hook,419 * and gets the run block's `setup` (the Checker's install step) before any420 * lane runs. Setup's output goes to stderr only when it fails, so `--json`421 * stdout stays one document.422 */358/** Setup's output goes to stderr only when it fails, so `--json` stdout stays one document. */359const checkoutOf = (input: {360 readonly root: string;361 readonly setup: Option.Option<string>;362 readonly note: (text: string) => Effect.Effect<void>;
82 unmodified lines
445 })446 )447 );448513/** A ratchet's count on the base and on HEAD, as a line says it. */449const moveText = ({ after, before, ratchet, territory }: RatchetMove) =>450 `${ratchet} in ${territory}: ${before} on the base, ${after} here`;451517/** The run as a person reads it: each lane and how it ended, then each ratchet's count. */452const viewOf = (checked: Checked) => {453 const moves = checked.ratchets ?? [];454455 const lines = [
18 unmodified lines
474 text: lines.join("\n"),475 };476};477544/** The counts as `--json` lists them: absent when there are none. */478const ratchetsField = (moves: readonly RatchetMove[]) =>479 Array.match(moves, {480 onEmpty: () => ({}),481 onNonEmpty: (ratchets) => ({ ratchets }),
68 unmodified lines
550 const claim = Option.flatMap(claims, (held) =>551 Array.findFirst(held, (each) => each.ask === askId)552 );553621 // Who pushes: the signed-in person, else the claimant the platform622 // names, else the person the fork is named for.554 const handle = Option.getOrElse(555 Option.firstSomeOf([556 yield* signedInHandle,557 Option.map(claim, ({ claimant }) => claimant),
22 unmodified lines
580 )581 )582 );583653 // Copies of the generated agent files main's config no longer gives.584 const stale = yield* staleGenerated({585 landed: policy.at,586 policy,587 project,
9 unmodified lines
597 if (Option.isNone(ask)) {598 return yield* refuse(json, [new UnknownAsk({ ask: askId })]);599 }600671 // The claim's fork, named as the platform names it: by the project's key.601 const fork = claimForkName(project, askId, handle);602603 const facts = yield* localFacts({604 ask,
56 unmodified lines
661 view: viewOf(checked),662 });663 }664736 // Only what the checkout uses: the runner's own scope, not this737 // command's, keeps each job's temp clone.665 const services = Context.make(666 ChildProcessSpawner.ChildProcessSpawner,667 yield* ChildProcessSpawner.ChildProcessSpawner668 ).pipe(
62 unmodified lines
731 yield* output.note(`${evidence.lane} failed: ${evidence.signature}`);732 }733 }734808 // The ratchets, counted on the base and on HEAD as the platform's809 // cheap stage counts them, unless `--lane` asked for lanes alone.735 const declared = Array.isReadonlyArrayNonEmpty(policy.ratchets);736 const counting = declared && flags.lane.length === 0;737738 if (declared && !counting) {
55 unmodified lines
modified:apps/cli/src/local/config-runtime.ts+4 added-42 removed
1/**2 * How this CLI runs bun for a TypeScript config folder: the command, what it3 * needs in its env, and the two modules the bundle and the rules sandbox4 * import (the sdk, and the rules' entry). Run from source or the npm build,5 * that is `bun` on the `PATH` and this CLI's own copies of the modules.6 *7 * The compiled binary can use neither: a machine that has only the binary8 * has no bun, and its modules live in Bun's embedded `/$bunfs/`, which a9 * `bun` child can't read. So `build.ts` bundles both modules whole (effect10 * inlined) and embeds them, and hands their embedded paths to this module11 * through the global scope before the CLI starts. Then each use unpacks them12 * into a temp folder of its own, and the binary runs itself as bun13 * (`BUN_BE_BUN=1`).14 */1// The compiled binary has no bun on the PATH, and a `bun` child can't read its embedded `/$bunfs/`,2// so `build.ts` embeds both modules bundled whole and the binary unpacks them and runs itself as bun.3import { Brand } from "@repo/brand";4import { RulesFailed } from "@repo/rules/rules-evaluator";5import { Context, Effect, FileSystem, Option, Path, Schema } from "effect";6import type { Scope } from "effect";720/** The modules a bun child imports for one use of the config folder. */8export interface ConfigModules {22 /** The sdk: what the folder's imports of it point at. */9 readonly sdk: string;24 /** The rules' entry, when this CLI carries its own copy on disk. */10 readonly entry: Option.Option<string>;26 /** A `node_modules` the folder's other bare imports resolve in. */11 readonly packages: Option.Option<string>;12}1330/** How this CLI runs bun for a config folder, and the modules it hands it. */14export interface ConfigBun {32 /** The command that runs bun. */15 readonly bun: string;34 /** What that command needs in its env beside the rest of it. */16 readonly env: Readonly<Record<string, string>>;36 /** The modules, ready for one scope's use. */17 readonly modules: Effect.Effect<18 ConfigModules,19 RulesFailed,20 FileSystem.FileSystem | Path.Path | Scope.Scope
2 unmodified lines
2324const loadFailed = (detail: string) =>25 new RulesFailed({ detail, reason: "load" });2647/**48 * The file this CLI's own copy of `specifier` is, looked up only when a49 * TypeScript folder is bundled: a build of the CLI that carries no copy on50 * disk still reads a `policy.json` or the defaults.51 */27/** Looked up only when a TypeScript folder is bundled: a build with no copy on disk still reads `policy.json`. */28const ownCopyOf = (path: Path.Path, specifier: string) =>29 Effect.try({30 catch: () =>31 loadFailed(
15 unmodified lines
47 );4849const NODE_MODULES = "/node_modules";5075/** The `node_modules` folder a resolved module sits in. */51const packagesOf = (file: string) => {52 const at = file.lastIndexOf(`${NODE_MODULES}/`);5354 return at === -155 ? Option.none()56 : Option.some(file.slice(0, at + NODE_MODULES.length));57};5884/** Run from source or the npm build: `bun` on the `PATH`, and this CLI's own modules. */59export const ConfigRuntimeOwn: ConfigBun = {60 bun: "bun",61 env: {},62 modules: Effect.gen(function* () {
4 unmodified lines
67 return { entry: Option.none(), packages: packagesOf(effect), sdk };68 }),69};7097/**98 * What `build.ts` hands the compiled binary through the global scope: the99 * embedded paths of the bundled sdk and rules entry.100 */71export const EMBEDDED_KEY = "__configRuntime";7273const Embedded = Schema.Struct({74 [EMBEDDED_KEY]: Schema.Struct({
2 unmodified lines
77 }),78 process: Schema.Struct({ execPath: Schema.NonEmptyString }),79});80111/**112 * The compiled binary's runtime: itself as bun, and the embedded modules113 * copied into a temp folder for the scope (`bun build` and a `bun` child114 * read only real files).115 */81/** `bun build` and a `bun` child read only real files, so the embedded modules are copied to a temp folder. */82export const configRuntimeEmbedded = (embedded: {83 readonly execPath: string;84 readonly entry: string;85 readonly sdk: string;
27 unmodified lines
113 );114 }),115});116151/**152 * The runtime this process has: the compiled binary's when `build.ts` handed153 * it the embedded modules, else this CLI's own.154 */117export const ConfigRuntime = Context.Reference<ConfigBun>("cli/ConfigRuntime", {118 defaultValue: () => {119 // Unknown on purpose: the runtime is whatever started this process.120 const scope: unknown = globalThis;
11 unmodified lines
modified:apps/cli/src/local/env-set.ts+4 added-33 removed
1/**2 * `<cli> env set <KEY>`: stores a write-only value for a project's3 * `@sensitive` env item. The value arrives on stdin (or, for a person at a4 * terminal, through a prompt that shows nothing typed) and leaves only as5 * the `setEnv` payload's `Redacted`: it is never an argument, never printed,6 * logged, hashed or measured, and nothing reads it back. The reply says who7 * set which key, and when.8 */1// The value is never an argument, never printed, logged, hashed or measured, and nothing reads it back.2import { Brand } from "@repo/brand";3import { Client, SetEnv } from "@repo/protocol/contracts";4import { EnvKey, ProjectName } from "@repo/protocol/ids";5import {
16 unmodified lines
22const command = "env set";2324const encodeSet = Schema.encodeEffect(SetEnv.successSchema);2533/** How a value is piped in, for the person who tried another way. */26const pipeHint = (key: string) =>27 `printf '%s\\n' "$VALUE" | ${Brand.cli} ${command} ${key} --yes`;2837/**38 * The value from a person at a terminal, through a prompt that shows nothing39 * typed (not even a mask, which would tell its length). An agent or a40 * script must never be prompted, so it is told to pipe the value instead.41 */29/** Shows nothing typed, not even a mask, which would tell its length. An agent or script is never prompted. */30const prompted = (key: EnvKey, mode: Mode) =>31 mode === "human"32 ? Prompt.run(33 Prompt.Hidden({
3 unmodified lines
37 : usage(38 `${Brand.cli} never prompts an agent or a script, so pipe the value of ${key} on stdin: ${pipeHint(key)}`39 );4053/**54 * The value from stdin, less one trailing newline; a terminal on stdin means55 * nobody piped it, so a person is prompted and anyone else told to pipe it.56 */41const readValue = (key: EnvKey, mode: Mode) =>42 Effect.gen(function* () {43 const stdio = yield* Stdio.Stdio;44
10 unmodified lines
55 ? yield* usage(`No value for ${key} arrived: ${pipeHint(key)}`)56 : value;57 });5875/** The project named, or the one the repo's platform remote names. */59const projectFor = (named: Option.Option<ProjectName>) =>60 Effect.gen(function* () {61 if (Option.isSome(named)) {62 return named.value;
8 unmodified lines
7172 return yield* projectOf(named, context);73 });7492/**93 * Every spelling of a flag `env set` takes: its own, and effect/cli's94 * built-in ones. A boolean's `--no-` form counts as its own spelling. A test95 * holds this list to the flags `env set --help` names.96 */75/** A test holds this list to the flags `env set --help` names. */76const spellings: ReadonlySet<string> = new Set([77 "--acknowledge-short",78 "--completions",79 "--dry-run",
7 unmodified lines
87 "-h",88 "-v",89]);90112/** A word that reads as a flag, but as none `env set` takes. */91const strangeFlag = (word: string) => {92 const [flag = word] = word.split("=", 1);9394 return (
2 unmodified lines
97 !spellings.has(flag.replace(/^--no-/u, "--"))98 );99};100123/**124 * Refuses `<cli> env set` with a word that reads as a flag it does not take,125 * before effect/cli parses the words. The parser would print such a word126 * back (`-abc` a letter per error), or act on a `-h` or `-v` inside it, and127 * a value typed there by mistake must never show, so the line repeats none128 * of it. `program` runs this first. Words after `--` reach the command,129 * which refuses them as `not-the-value`.130 */101/** effect/cli would print a stray flag back (or act on a `-h` inside it), so a value typed there must be refused before parsing. */102export const refuseStrangeFlags = (103 argv: readonly string[]104): Effect.Effect<void, UsageError> => {105 const end = argv.indexOf("--");
108 unmodified lines
modified:apps/cli/src/local/facts.ts+4 added-70 removed
1/**2 * The gate's facts for a push the CLI has not made yet: what `git push` of3 * HEAD would hand the gateway. The change list and the lines it adds come4 * from `@repo/git`'s `treeDiff` and `addedLines` over the working repo,5 * opened through `RepoHost` `/local` as the platform opens a fork, so the6 * local answer matches the gateway's by construction: no diff of its own.7 *8 * Nothing here writes to the working repo, its config or its refs: git runs9 * with optional locks off and never sees the repo a git hook exported (so a10 * temp repo's git stays in the temp repo), and `/local` reads its objects11 * through a link in a temp folder (or a temp bare copy, when the objects12 * live in another repo's store, which isomorphic-git cannot follow).13 */1// Nothing here writes to the working repo, its config or its refs.2import { Fetch, FetchFailed } from "@repo/artifacts/fetch";3import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";4import type { RepoNotFound } from "@repo/artifacts/repo-host";5import { RepoHostLocal } from "@repo/artifacts/repo-host/local";
19 unmodified lines
25import { ChildProcess, ChildProcessSpawner } from "effect/process";2627import { NotARepo } from "../repo-context.ts";2841/** A revision the repo does not have: a branch, tag or commit by that name. */29export class UnknownRevision extends Schema.TaggedError<UnknownRevision>()(30 "UnknownRevision",31 { revision: Schema.String, root: Schema.String }32) {
1 unmodified line
34 return `${this.root} has no commit ${this.revision}`;35 }36}3751/** How a git command ended: its exit code and its output. */38export interface GitRan {39 readonly exitCode: number;40 readonly stdout: string;41 readonly stderr: string;
1 unmodified line
4344const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>45 bytes.pipe(Stream.decodeText(), Stream.mkString);4661/**62 * What git exports to a hook that runs the CLI: where its repo, index and63 * objects are, and the config given with `git -c`. A git that saw them in a64 * temp repo would read and write the hook's repo instead (its HEAD, its65 * index, its refs), so every git and every setup here runs without them and66 * finds its repo from the folder it runs in. `undefined` leaves one out.67 */47/** A git that saw a hook's exported env in a temp repo would read and write the hook's repo instead. */48export const outsideAnyHook = {49 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,50 GIT_COMMON_DIR: undefined,51 GIT_CONFIG: undefined,
6 unmodified lines
58 GIT_PREFIX: undefined,59 GIT_WORK_TREE: undefined,60};6182/**83 * The env of a git that only reads: outside any hook's repo, taking no84 * optional lock (a read that would refresh the index leaves it as it is),85 * and never asking for a password (a partial clone's missing blob is86 * fetched without a prompt, or not at all).87 */62/** No optional lock (an index refresh would write) and no password prompt. */63export const readOnlyGit = {64 ...outsideAnyHook,65 GIT_OPTIONAL_LOCKS: "0",66 GIT_TERMINAL_PROMPT: "0",67};6894/** Runs git in `cwd` to its end; a failing git is a result, not an error. */69export const runGit = (70 cwd: string,71 args: readonly string[]72): Effect.Effect<GitRan, NotARepo, ChildProcessSpawner.ChildProcessSpawner> =>
18 unmodified lines
91 return { exitCode: Number(exitCode), stderr, stdout };92 })93 ).pipe(Effect.catchTag("PlatformError", () => new NotARepo({ cwd })));94121/** The commit `revision` names in the repo at `root`. */95export const commitOf = (root: string, revision: string) =>96 Effect.gen(function* () {97 const ran = yield* runGit(root, [98 "rev-parse",
9 unmodified lines
108 ? sha109 : yield* new UnknownRevision({ revision, root });110 });111139/** The commit `git diff <base>...<head>` starts from: their merge base. */112const mergeBase = (root: string, base: string, head: CommitSha) =>113 Effect.gen(function* () {114 const from = yield* commitOf(root, base);115 const ran = yield* runGit(root, ["merge-base", from, head]);
3 unmodified lines
119 ? sha120 : yield* new UnknownRevision({ revision: `${base}...${head}`, root });121 });122151/** A host that reaches nothing over the network: `/local` here reads disk only. */123const noNetwork = Layer.succeed(Fetch)({124 fetch: (request) =>125 Effect.fail(126 new FetchFailed({
2 unmodified lines
129 })130 ),131});132162/** The name `/local` knows the working repo by: `<temp>/<name>.git`. */133const WORKING = RepoName.make("working");134165/** The name it knows a temp bare copy by. */135const COPY = RepoName.make("copy");136168/** `RepoHost` `/local` over the repos in `folder`. */137const hostOver = (folder: string) =>138 RepoHostLocal.layer({ remoteBase: `file://${folder}`, root: folder }).pipe(139 Layer.provide(noNetwork)140 );141174/** Whether `/local` can read every commit in `shas` from repo `name`. */142const readsAll = (name: RepoName, shas: readonly CommitSha[]) =>143 Effect.forEach(shas, (sha) =>144 RepoHost.use((host) => host.readCommit(name, sha))145 ).pipe(146 Effect.map((commits) => commits.every(Option.isSome)),147 Effect.catchTag("RepoNotFound", () => Effect.succeed(false))148 );149183/** A repo `/local` can read: the host's layer, and the repo's name there. */150interface Opened {151 readonly host: Layer.Layer<RepoHost>;152 readonly name: RepoName;153}154189/**190 * The working repo at `root`, opened through `RepoHost` `/local` for as long191 * as the scope lasts, holding `shas`. `/local` keeps each repo at192 * `<folder>/<name>.git`, so a temp folder gets a link of that name to the193 * repo's git store (its common dir, which a linked worktree shares). A194 * store that keeps its objects in another (`objects/info/alternates`, as a195 * `git clone --shared` does) is one isomorphic-git cannot read; then the196 * commits are fetched into a temp bare repo, which reads the working repo197 * and writes only the copy.198 */155/** isomorphic-git cannot follow `objects/info/alternates`, so such a store is fetched into a temp bare copy. */156const openWorking = (157 root: string,158 shas: readonly CommitSha[]159): Effect.Effect<
59 unmodified lines
219220 return { host, name: COPY } satisfies Opened;221 });222266/** What `localFacts` is told: the repo, the push, and what the project knows of it. */223export interface LocalFactsInput {268 /** The working repo's top folder. */224 readonly root: string;270 /** Where the answer starts: its diff runs from the merge base of `base` and `head`. */225 readonly base: string;272 /** The answer's commit, as git names it: `HEAD` for a local check. */226 readonly head: string;274 /** The policy at the landed SHA (`localPolicy`); `policy.at` is the landed SHA. */227 readonly policy: Policy;228 readonly ask: Option.Option<Ask>;229 readonly claim: Option.Option<ClaimView>;230 readonly pusher: Principal;279 /** Where the push would go: the claim's fork. */231 readonly target: PushTarget;281 /** How many live claims the pusher holds, for `CapReached`. */232 readonly claimsHeld: number;233}234285/** The text of a blob, if the change has one on that side. */235const blobText = (name: RepoName, blob: string | undefined) =>236 blob === undefined237 ? Effect.succeedNone238 : RepoHost.use((host) => host.readBlob(name, ObjectId.make(blob))).pipe(
5 unmodified lines
244);245246const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);247299/** A manifest's `scripts` as JSON text, or `""` with no manifest or no JSON. */248const scriptsIn = (manifest: Option.Option<string>) =>249 Option.getOrElse(250 Option.map(Option.flatMap(manifest, decodeScripts), ({ scripts }) =>251 JSON.stringify(scripts ?? null)252 ),253 () => ""254 );255308/**309 * Whether the root manifest's `scripts` differ across the change, compared310 * as the gateway's facts compare them (`@repo/project`'s `pushFacts`): the311 * gate's `package.json#/scripts` pointer reads this one bit.312 */256const scriptsChanged = (name: RepoName, changes: readonly Change[]) =>257 Option.match(258 Option.fromUndefinedOr(changes.find(({ path }) => path === "package.json")),259 {
8 unmodified lines
268 ),269 }270 );271329/** A commit's root tree, through the port. */272const treeOf = (name: RepoName, sha: CommitSha) =>273 RepoHost.use((host) => host.readCommit(name, sha)).pipe(274 Effect.flatMap(Effect.fromOption),275 Effect.map(({ tree }) => TreeSha.make(tree)),276 Effect.orDie277 );278337/**338 * The gate's facts for pushing `head` to `target`: the change list and the339 * lines it adds from the merge base of `base` and `head` (`git diff340 * base...head`), whether the root scripts moved, and what the caller knows341 * of the ask, the claim and the pusher. The ref is the fork's `main`, as a342 * claimant pushes it; no layer paths or ratchet counts yet, as on the343 * gateway.344 */279export const localFacts = (280 input: LocalFactsInput281): Effect.Effect<282 PushFacts,
36 unmodified lines
modified:apps/cli/src/local/index.ts-7 removed
1/**2 * The CLI's hand-written commands, by the path a person types. Each issue3 * that builds one replaces its file; none edits `main.ts`, which builds the4 * command tree from this list.5 */1import type { Command } from "effect/cli";23import { check } from "./check.ts";4import { envSet } from "./env-set.ts";5import { init } from "./init.ts";6import { login, logout } from "./login.ts";7import { why } from "./why.ts";814/** One hand-written command, and the words that reach it. */9export interface LocalEntry {16 /** The words after the CLI's name; the last is the command's own name. */10 readonly path: readonly [string, ...string[]];11 readonly command: Command.Command.Any;12}13
8 unmodified lines
modified:apps/cli/src/local/init.ts+1 added-53 removed
1/**2 * `init`: makes the repo the CLI stands in, or a public HTTPS repo, a3 * project on the platform. In a repo, it reads how the repo already sets up,4 * tests and lints (`@repo/checks/finder`), writes and commits a proposed5 * `<configDir>/project.ts` saying so, has the platform make the project6 * (`initProject`), adds the project as a remote, sets up git's credential7 * helper for its host, and pushes the first landing. With `--import`, the8 * platform copies the public repo once instead, and nothing here changes.9 * It acts only with `--yes`; `--dry-run` prints what it would do.10 */1import { Brand } from "@repo/brand";2import { findRunBlock } from "@repo/checks/finder";3import type { RepoFile } from "@repo/checks/finder";4import { ApprovalNeeded } from "@repo/protocol/cli";
20 unmodified lines
25import { projectFile } from "./project-file.ts";2627const COMMAND = "init";2839/** The config file `init` proposes, from the repo's root. */29const CONFIG = `${Brand.configDir}/project.ts`;3042/** The one commit `init` makes: the config file alone. */31const SUBJECT = `Add ${CONFIG}: the run block ${Brand.cli} ${COMMAND} found`;3245/** What `--dry-run` shows where the platform's answer will go. */33const PENDING = { origin: "<platform>", remote: "<remote>" } as const;3448/** `init`'s flags ask for something it can't do. A usage error: exit 2. */35export class InitMisused extends Schema.TaggedError<InitMisused>()(36 "InitMisused",37 { reason: Schema.String }38) {
3 unmodified lines
42 return this.reason;43 }44}4560/** A git command `init` ran failed; git's own words say why. */46export class GitFailed extends Schema.TaggedError<GitFailed>()("GitFailed", {47 argv: Schema.Array(Schema.String),48 stderr: Schema.String,49}) {
1 unmodified line
51 return `${this.argv.join(" ")} failed: ${this.stderr.trim()}`;52 }53}5470/** The payload `initProject` takes. */55type Payload = typeof InitProject.payloadSchema.Type;5673/** What `init` would write, send and run: `--dry-run` prints it. */57interface Plan {58 readonly files: readonly RepoFile[];59 readonly git: readonly (readonly string[])[];60 readonly payload: Payload;
46 unmodified lines
107108const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>109 bytes.pipe(Stream.decodeText(), Stream.mkString);110128/** Runs `argv` in `cwd` to the end; a failing command is a result, not an error. */111const run = (cwd: string, argv: readonly string[]) =>112 Effect.scoped(113 Effect.gen(function* () {114 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
11 unmodified lines
126 return { exitCode, stderr, stdout };127 })128 );129148/** Runs `argv` in `cwd`, failing with git's own words when it fails. */130const runOk = (cwd: string, argv: readonly string[]) =>131 run(cwd, argv).pipe(132 Effect.filterOrFail(133 (ran) => ran.exitCode === 0,134 (ran) => new GitFailed({ argv, stderr: ran.stderr })135 )136 );137157/** An argument as a shell reads it back: quoted only when it must be. */138const shellWord = (word: string) =>139 /^[\w@%+=:,./-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;140141const shown = (argv: readonly string[]) => argv.map(shellWord).join(" ");142163/**164 * The tracked files whose contents say how a repo sets up, tests and lints,165 * for the finder and the judge closure: every `package.json`, every166 * `tsconfig*.json`, CI workflows and hook configs.167 */143const READ = [144 /(?:^|\/)package\.json$/u,145 /(?:^|\/)tsconfig[^/]*\.json$/u,146 /^\.(?:github|forgejo)\/workflows\/[^/]+\.ya?ml$/u,
1 unmodified line
148 /^\.husky\/[^/]+$/u,149 /^\.pre-commit-config\.yaml$/u,150];151177/** Every tracked path, with contents for the files the finder reads. */152const trackedFiles = (root: string) =>153 Effect.gen(function* () {154 const fs = yield* FileSystem.FileSystem;155 const path = yield* Path.Path;
11 unmodified lines
167 { concurrency: 16 }168 );169 });170197/** The owner a bare name is given: the profile's handle, when `login` learned it. */171const profileOwner = Effect.map(172 Effect.flatMap(Credentials, ({ current }) => current),173 (profile) =>174 Option.map(
1 unmodified line
176 (handle) => handle.toLowerCase()177 )178);179207/**208 * A name as a project's: `<owner>/<name>` as given, a bare word given under209 * the profile's handle, and with none given `fallback.short` under210 * `fallback.owner` (an import's source namespace), else under the211 * profile's handle. A usage error says how to name it otherwise.212 */180const projectNamed = (181 given: Option.Option<string>,182 fallback: { readonly owner: Option.Option<string>; readonly short: string }183) =>
23 unmodified lines
207const HTTPS = /^https:\/\/\S+$/u;208209const pathnameOf = Option.liftThrowable((url: string) => new URL(url).pathname);210244/** The repo name an import URL ends in: `…/acme/widgets.git` → `widgets`. */211const lastSegment = (url: string) =>212 Option.getOrElse(pathnameOf(url), () => "")213 .split("/")214 .findLast((segment) => segment !== "")215 ?.replace(/\.git$/u, "") ?? "";216251/** The project's remote and how to reach it: `git remote add|set-url`, the helper, the push. */217const wiring = (input: {218 readonly hasRemote: boolean;219 readonly origin: Option.Option<string>;220 readonly push: boolean;
12 unmodified lines
233 }),234 ...(input.push ? [["git", "push", Brand.slug, "HEAD:main"]] : []),235];236272/** The config file's commit: added, then committed alone. */237const committing = (paths: readonly string[]) =>238 paths.flatMap((path) => [239 ["git", "add", "--", path],240 ["git", "commit", "--quiet", "--message", SUBJECT, "--", path],241 ]);242279/** Prints `refusal` once, as the CLI prints every refusal, and ends as `Reported` with its exit code. */243const refuse = (json: boolean) => (refusal: Refusal) =>244 Output.use((output) =>245 endRefused(output, { command: COMMAND, json, refusals: [refusal] })246 );247285/** Asks the platform to make the project; a refusal is printed once. */248const makeProject = (payload: Payload, json: boolean) =>249 Effect.gen(function* () {250 const client = yield* Client;251
4 unmodified lines
256 })257 );258 });259298/** `--dry-run` prints the plan; without `--yes` nothing happens at all. */260const approved = (input: Input, plan: Plan) =>261 Effect.gen(function* () {262 if (input.dryRun) {263 const output = yield* Output;
9 unmodified lines
273274 return true;275 });276316/** An import comes from a public `https://` URL, or not at all. */277const httpsOnly = (url: string) =>278 HTTPS.test(url)279 ? Effect.void280 : Effect.fail(
1 unmodified line
282 reason: `--import takes a public repo's https:// URL, and ${url} is not one`,283 })284 );285326/** `--branch` says which branch to import, so it needs `--import`. */286const importOnly = (branch: Option.Option<string>) =>287 Option.isNone(branch)288 ? Effect.void289 : Effect.fail(
2 unmodified lines
292 "--branch names the branch to import, so it goes with --import",293 })294 );295337/** A reply as `--json` prints it: `landed` only when the platform gave one. */296const withLanded = <A extends object>(297 data: A,298 landed: LandedSha | undefined299) => (landed === undefined ? data : { ...data, landed });300343/** Has the platform copy the repo at `url`, and says how to clone the project. */301const imported = (input: Input, url: string, payload: Payload) =>302 Effect.gen(function* () {303 const output = yield* Output;304 const reply = yield* makeProject(payload, input.json);
18 unmodified lines
323 },324 });325 });326370/** `init --import <url>`: the platform copies a public repo; nothing here changes. */327const importing = (input: Input, url: string) =>328 Effect.gen(function* () {329 yield* httpsOnly(url);330
21 unmodified lines
352 yield* imported(input, url, payload);353 }354 });355400/** What `init` found in the repo it stands in, and so will do there. */356interface Found {402 /** The config file to commit: none when HEAD has one. */357 readonly commits: readonly string[];404 /** Whether the repo already has a remote by the CLI's name. */358 readonly hasRemote: boolean;359 readonly payload: Payload;360 readonly root: string;408 /** The config file to write: none when the work tree or HEAD has one. */361 readonly writes: readonly RepoFile[];362}363412/** Writes and commits the config, makes the project, wires the remote and pushes. */364const made = (input: Input, found: Found) =>365 Effect.gen(function* () {366 const fs = yield* FileSystem.FileSystem;367 const path = yield* Path.Path;
61 unmodified lines
429 view: { markdown: done.join("\n\n"), text: done.join("\n") },430 });431 });432482/** `init` in a repo: propose the config, make the project, wire the remote, push. */433const inRepo = (input: Input) =>434 Effect.gen(function* () {435 yield* importOnly(input.branch);436437 const fs = yield* FileSystem.FileSystem;438 const path = yield* Path.Path;489 // The folder the CLI was started in: git and the spawner resolve it.439 const { root } = yield* repoContext(".");440441 const project = yield* projectNamed(input.project, {442 owner: Option.none(),
1 unmodified line
444 });445446 const inTree = yield* fs.exists(path.join(root, CONFIG));447499 // HEAD is what the push sends: a config only the work tree has (a run500 // whose commit failed left it) is kept as it is, and committed.448 // HEAD is what the push sends: a config only the work tree has is kept and committed.449 const atHead =450 (yield* run(root, ["git", "cat-file", "-e", `HEAD:${CONFIG}`]))451 .exitCode === 0;452
44 unmodified lines
modified:apps/cli/src/local/judge-files.ts+2 added-24 removed
1/**2 * The files the run-block finder and the judge closure are handed at one3 * commit of a repo on this machine, gathered as the platform gathers them at4 * a landing: `@repo/checks`' `judgeInputs` over the commit's listing, each5 * round's files read with one `git cat-file --batch`. `<cli> check` and the6 * harness hooks both read them here, so each judges by the closure the7 * gateway judges a push by.8 *9 * git runs read-only, outside any hook's repo and with no prompt10 * (`readOnlyGit`), and a git that fails reads as nothing: the closure is11 * then the defaults.12 */1// A git that fails reads as nothing: the closure is then the defaults.2import { judgeInputs } from "@repo/checks/judge";3import type { JudgeInput } from "@repo/checks/judge";4import { Array, Effect, Option, Stream } from "effect";5import { ChildProcess, ChildProcessSpawner } from "effect/process";67import { readOnlyGit } from "./facts.ts";820/** One blob of a commit, as `git ls-tree -r -l` lists it: its mode, path, id and size. */9export interface ListedBlob {10 readonly mode: string;11 readonly path: string;12 readonly sha: string;
1 unmodified line
14}1516const decoder = new TextDecoder();1730/** Runs git in `root` to its end, `stdin` given: stdout as bytes, or none if it failed. */18const gitBytes = (root: string, args: readonly string[], stdin?: string) =>19 Effect.scoped(20 Effect.gen(function* () {21 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
22 unmodified lines
4445const ENTRY =46 /^(?<mode>\d+) blob (?<sha>[0-9a-f]+) +(?<size>\d+)\t(?<path>.+)$/su;4761/** Every blob of the commit `revision` names, by its path from the root; none when git can't read it. */48export const blobsAt = (49 root: string,50 revision: string51): Effect.Effect<
36 unmodified lines
88 }),89 })90 );91106/**107 * `git cat-file --batch`'s output, split back into each object's bytes:108 * `<sha> <type> <size>\n<bytes>\n` per object, in the order asked.109 */92/** Output is `<sha> <type> <size>\n<bytes>\n` per object, in the order asked. */93const objectsIn = (output: Uint8Array): readonly Uint8Array[] => {94 const objects: Uint8Array[] = [];95 let at = 0;96
21 unmodified lines
118119 return objects;120};121139/**140 * The files the finder and the judge closure are handed, from a commit's141 * listing (`blobsAt`): every one, with the text of each some walk reads.142 */122export const judgeFilesIn = (123 root: string,124 listing: readonly ListedBlob[]125): Effect.Effect<
32 unmodified lines
158 );159 });160};161183/** The files the finder and the judge closure are handed at the commit `revision` names. */162export const judgeFilesAt = (root: string, revision: string) =>163 Effect.flatMap(blobsAt(root, revision), (listing) =>164 judgeFilesIn(root, listing)165 );
modified:apps/cli/src/local/local-policy.ts+3 added-55 removed
1/**2 * The policy a local `check` judges by: the config folder at the landed SHA,3 * which locally is `main` (or `--base`), never the answer's own tree (ADR4 * 0005), so editing the rules on HEAD changes nothing here, as it changes5 * nothing on the platform.6 *7 * It is evaluated the way the platform evaluates it: a TypeScript folder8 * bundled with the sdk inlined and run by `@repo/rules`' `/bun` adapter (the9 * Lander's `bundleRules` and the `/worker` evaluator, here on this machine),10 * else its `policy.json` through `/json`, else the defaults; then finished11 * with `@repo/checks`' finder and judge closure, from the same facts the12 * platform reads at a landing (`@repo/project`'s `evaluationFacts`): every13 * file at the commit, with the text of each one the finder or the closure14 * reads (`@repo/checks`' `judgeInputs`, through `judge-files.ts`), the15 * workspaces the root manifest names, and the vouch file.16 */1// The policy comes from the config at `main` (or `--base`), never the answer's own tree, as on the platform.2import { Brand } from "@repo/brand";3import { findRunBlock } from "@repo/checks/finder";4import { judgeClosure } from "@repo/checks/judge";5import { workspacesIn } from "@repo/checks/workspaces";
28 unmodified lines
34import { commitOf, runGit } from "./facts.ts";35import { blobsAt, judgeFilesIn } from "./judge-files.ts";36import type { ListedBlob } from "./judge-files.ts";3753/** A file of the config folder, as committed. */38export interface ConfigFile {39 readonly path: string;40 readonly content: string;41}4259/**60 * Turns the config folder's files into the bundle the rules evaluator runs:61 * its project module and ask files as self-contained modules, the sdk62 * inlined, and its other files as committed.63 */43export class ConfigBundler extends Context.Service<44 ConfigBundler,45 {46 readonly bundle: (
1 unmodified line
48 ) => Effect.Effect<ConfigBundle, RulesFailed>;49 }50>()("cli/ConfigBundler") {}5173/** The project module's path: it names the folder, as the platform's bundles do. */52const configEntry = `${Brand.configDir}/project.ts`;5376// Code, which a bundle carries only inlined: as the Lander reads the folder.54// Code, which a bundle carries only inlined.55const SCRIPT = /\.[cm]?[jt]sx?$/u;5657const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;5881/** The modules the evaluator imports, each bundled on its own: the project module and every ask. */59const entriesOf = (paths: readonly string[]) =>60 paths.filter(61 (path) =>62 path === configEntry ||63 (path.startsWith(`${Brand.configDir}/asks/`) && ASK_FILE.test(path))64 );6589/** Where bun writes an entry's bundle: its path, as JavaScript. */66const bundledAs = (entry: string) => entry.replace(/\.[^./]*$/u, ".js");6768const loadFailed = (detail: string) =>69 new RulesFailed({ detail, reason: "load" });7095/**96 * The config folder bundled by `bun build`, as the Lander bundles it at a97 * landing: both names of the sdk (the workspace one and the published98 * `<cli package>/rules`) resolve to this CLI's own copy, any other bare99 * import to the packages beside it, macros are off, and code the entries100 * share goes to chunks in the folder. Bun and the sdk come from101 * `ConfigRuntime`: `bun` on the `PATH` from source, the binary itself once102 * compiled.103 */71export const ConfigBundlerBun: Layer.Layer<72 ConfigBundler,73 never,74 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
2 unmodified lines
77 const fs = yield* FileSystem.FileSystem;78 const path = yield* Path.Path;79 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;80114 /** Writes `content` at `file` under `root`, refusing a path that leaves it. */81 const writeUnder = (root: string, file: string, content: string) => {82 const target = path.join(root, file);83 const relative = path.relative(root, target);84
154 unmodified lines
239 });240 })241);242277/** What the policy is evaluated for, which the repo cannot say. */243export interface PolicyAbout {279 /** The project the asks belong to. */244 readonly project: ProjectName;281 /** Who `owners` names; locally, the person checking, as no stage of a push reads it. */245 /** Locally, the person checking: no stage of a push reads it. */246 readonly initializer: Handle;247}248249// A regular file, executable or not: the Lander bundles only these from the250// config folder, never a link or a submodule.251const FILE_MODES: ReadonlySet<string> = new Set(["100644", "100755"]);252289/** A blob's text. */253const textOf = (root: string, file: ListedBlob) =>254 Effect.map(runGit(root, ["cat-file", "blob", file.sha]), ({ stdout }) => ({255 content: stdout,256 path: RepoPath.make(file.path),257 }));258296/**297 * The facts the platform evaluates the config folder over, read at `sha`:298 * `ci` and the workspaces as `@repo/checks` gathers and reads them for the299 * platform too (`judgeFilesIn`, `workspacesIn`), the vouch file, and the300 * commit's own clock and seed.301 */259const factsAt = (input: {260 readonly root: string;261 readonly sha: CommitSha;262 readonly files: readonly ListedBlob[];
42 unmodified lines
305 onSome: ({ content }) => ({ ...facts, vouchFile: content }),306 });307 });308352/** The finishers the platform passes the rules evaluator: `@repo/checks`' own. */309const finishers = Layer.succeed(Finishers)({ findRunBlock, judgeClosure });310355/** Where a policy that names none keeps its vouch file. */311const defaultVouchFile = `${Brand.configDir}/vouched.td`;312358/**359 * The policy at `base` in the repo at `root`, never HEAD's: the config360 * folder's TypeScript (bundled by `ConfigBundler`, run by the `/bun`361 * evaluator), else its `policy.json` (`/json`), else the defaults (no362 * folder), finished with `@repo/checks`' finder and judge closure. A policy363 * that keeps its vouch file elsewhere is read again with that file.364 */313export const localPolicy = (314 root: string,315 base: string,316 about: PolicyAbout
79 unmodified lines
modified:apps/cli/src/local/login.ts+4 added-78 removed
1/**2 * `login` and `logout`. A person logs in once, through the browser (PKCE3 * against the platform's own OAuth server) or with a token piped to4 * `--token-stdin`; the CLI checks the token with the platform, keeps it as5 * a profile (`Credentials`), and names `git-credential-<slug>` in git's6 * global config for the platform's url, so plain `git clone`, `fetch` and7 * `push` work with no token in a url and no prompt. Profiles let one8 * machine act for several people (`<SLUG>_PROFILE=<name>`).9 *10 * The token stays `Redacted` from stdin or `/token` to the credentials11 * file; it is written out only in the `Authorization` header that checks12 * it, and later in the helper's `password=` line.13 */1// The token stays `Redacted`; it is written out only in the `Authorization` header that checks it and the helper's `password=` line.2import { BunHttpServer } from "@effect/platform-bun";3import { Brand } from "@repo/brand";4import { detectHarness } from "@repo/protocol/audit";5import { Contracts } from "@repo/protocol/contracts";
26 unmodified lines
32import { Credentials, gitHelperConfig } from "../credentials.ts";33import type { Profile } from "../credentials.ts";34import { Output } from "../output.ts";3548/** The env names the CLI reads, spelled from the brand: `<SLUG>_URL`. */36const SLUG = Brand.slug.toUpperCase();3751/** The address the loopback server binds: this machine only. */38const LOOPBACK = "127.0.0.1";3954/** How long `login` waits for the browser to come back. */40const SIGN_IN_WAIT = "5 minutes";4157/**58 * The CLI's OAuth client id on a platform: the URL of the Client ID59 * Metadata Document the platform serves for it60 * (`apps/platform/src/auth/cli-client.ts`). It asks for no scope.61 */42const clientIdOf = (origin: string) => `${origin}/oauth/cli`;4364// --- The host seams: each has a default the binary runs on, and tests swap it.6566/**67 * Where `login` hears the browser come back: an HTTP server on one address,68 * for one scope. The binary listens with Bun.69 */44export const Loopback = Context.Reference<{45 readonly listen: (address: {46 readonly hostname: string;47 readonly port: number;
7 unmodified lines
55 listen: ({ hostname, port }) => BunHttpServer.make({ hostname, port }),56 }),57});5885/**86 * A client of the platform at `url` that presents `token` as its bearer:87 * what `login` checks a token with before it keeps it. The binary's calls88 * go over HTTP to `<url>/rpc`.89 */59export const PlatformClient = Context.Reference<{60 readonly connect: (profile: {61 readonly token: Redacted.Redacted;62 readonly url: string;
15 unmodified lines
78 ),79 }),80});81113/** Opens `url` with the first of `commands` that runs; none running is fine. */82const openWith = (url: string, commands: readonly string[]) =>83 Effect.gen(function* () {84 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;85
13 unmodified lines
99 }100 }101 });102135/**136 * The person's browser. The binary asks the desktop's opener (`xdg-open`,137 * else macOS's `open`); the URL is printed either way.138 */103export const Browser = Context.Reference<{104 readonly open: (105 url: string106 ) => Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner>;
2 unmodified lines
109 open: (url) => openWith(url, ["xdg-open", "open"]),110 }),111});112149// --- Failures.150151/** `login` was run in a way that cannot work; the message says what to run. */113export class LoginUsage extends Schema.TaggedError<LoginUsage>()("LoginUsage", {114 reason: Schema.String,115}) {116 override get message() {117 return this.reason;118 }119}120160/** The platform, or the sign-in, said no; nothing was stored. */121export class LoginRefused extends Schema.TaggedError<LoginRefused>()(122 "LoginRefused",123 { reason: Schema.String }124) {
1 unmodified line
126 return this.reason;127 }128}129170/** git would not take a config line; the message names it, to run by hand. */130export class GitConfigFailed extends Schema.TaggedError<GitConfigFailed>()(131 "GitConfigFailed",132 { command: Schema.String }133) {
1 unmodified line
135 return `git did not take this; run it yourself: ${this.command}`;136 }137}138180// --- Shared parts.181139const flags = {140 json: Flag.Boolean("json").pipe(141 Flag.withDefault(false),142 Flag.withDescription("Print machine-readable JSON")
5 unmodified lines
148 Flag.optional149 ),150};151195/** The profile a command acts on: the flag, else `<SLUG>_PROFILE`, else `default`. */152const profileName = (153 flag: Option.Option<string>,154 env: Readonly<Record<string, string>>155) => Option.getOrElse(flag, () => env[`${SLUG}_PROFILE`] ?? "default");156201/** An argv list as a person would type it in a shell. */157const typed = (argv: readonly string[]) =>158 argv159 .map((arg) => {160 if (arg === "") {
5 unmodified lines
166 : `'${arg.replaceAll("'", String.raw`'\''`)}'`;167 })168 .join(" ");169215/** Runs one `git config` argv list; `allowed` are the exit codes that mean done. */170const runGit = (171 argv: readonly string[],172 env: Readonly<Record<string, string>>,173 allowed: readonly number[] = [0]
20 unmodified lines
194 });195196const asUrl = Option.liftThrowable((text: string) => new URL(text));197244/** Hosts that are this machine, where plain http keeps a token local. */198/** Hosts where plain http keeps a token on this machine. */199const THIS_MACHINE = new Set(["localhost", "127.0.0.1", "[::1]"]);200247/** `given`'s origin, if it is a platform url: https, or http on this machine. */201const originOf = (given: string) =>202 Option.match(203 Option.filter(204 asUrl(given),
11 unmodified lines
216 onSome: ({ origin }) => Effect.succeed(origin),217 }218 );219267/**268 * The platform to log in to: `--url`, else `<SLUG>_URL`, else the profile's269 * own. `Credentials` reads back only the current profile, so another270 * profile named by `--profile` needs `--url`: it is never logged in to the271 * current profile's platform by default.272 */220/** `Credentials` reads back only the current profile, so another profile needs `--url`. */221const platformOf = (222 flag: Option.Option<string>,223 profile: Option.Option<string>,224 env: Readonly<Record<string, string>>
22 unmodified lines
247 reason: `no platform to log in to for profile ${name}: run ${Brand.cli} login --url https://<platform host>${Option.isSome(profile) ? ` --profile ${name}` : ""}`,248 });249 });250303// --- The token, by one of two ways.304305/** The token piped to `--token-stdin`: its first line, read no further. */251const tokenFromStdin = Effect.gen(function* () {252 const { stdin } = yield* Stdio.Stdio;253254 const [line = ""] = yield* stdin.pipe(
16 unmodified lines
271});272273const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);274330/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */275const randomText = (size: number) =>276 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(277 Effect.flatMap(encodeBase64Url),278 Effect.orDie279 );280337/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */281const challengeOf = (verifier: string) =>282 Effect.promise(() =>283 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))284 ).pipe(285 Effect.flatMap((digest) => encodeBase64Url(new Uint8Array(digest))),286 Effect.orDie287 );288346/**347 * A server on 127.0.0.1 at a port the system picks, for this scope, that348 * takes the browser's one return to `/callback`: its `redirect_uri`, and349 * the query the browser brought back.350 */289const loopback = Effect.gen(function* () {290 const { listen } = yield* Loopback;291 const server = yield* listen({ hostname: LOOPBACK, port: 0 });292 const returned = yield* Deferred.make<URLSearchParams>();
31 unmodified lines
324 returned: Deferred.await(returned),325 };326});327390/** What `/token` answers a good code with. */328const TokenResponse = Schema.Struct({329 access_token: Schema.RedactedFromValue(Schema.NonEmptyString),330 token_type: Schema.String,331});332333const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);334398/** Trades the code for an access token at `<url>/token`, showing the verifier. */335const exchange = (input: {336 readonly code: string;337 readonly redirectUri: string;338 readonly url: string;
35 unmodified lines
374 Effect.mapError(() => refused)375 );376};377442/**443 * The token from a browser sign-in: PKCE (S256) against the platform's444 * `/authorize`, its code at the loopback server, then `/token`. The URL is445 * always printed; the browser opens only when `opens`. Waits at most five446 * minutes for the browser, then stops with a usage error.447 */378const tokenFromBrowser = (url: string, opens: boolean) =>379 Effect.scoped(380 Effect.gen(function* () {381 const output = yield* Output;
53 unmodified lines
435 return yield* exchange({ code, redirectUri, url, verifier });436 })437 );438509/** Asks the platform at `url` who `token` is; a refusal or no answer stores nothing. */439const verify = (url: string, token: Redacted.Redacted) =>440 Effect.scoped(441 Effect.gen(function* () {442 const client = yield* (yield* PlatformClient).connect({ token, url });
8 unmodified lines
451 })452 )453 );454526/** Whether `login` may open a browser: only for a person at a terminal. */455const mayOpenBrowser = (env: Readonly<Record<string, string>>) =>456 Effect.gen(function* () {457 const { mode } = yield* Output;458 const { stdoutIsTerminal } = yield* Stdio.Stdio;
5 unmodified lines
464 (yield* stdoutIsTerminal)465 );466 });467540/** The lines of a view: a sentence, then each command on its own line. */468const viewOf = (said: string, commands: readonly (readonly string[])[]) => {469 const lines = commands.map((argv) => typed(argv));470471 return {
83 unmodified lines
555 "Sign in to a platform; git and this CLI then use its token."556 )557);558632/** The `git config --global` lines that undo `gitHelperConfig(url)`; exit 5 means already gone. */559/** Exit 5 means the line is already gone. */560const gitHelperUnset = (url: string): readonly (readonly string[])[] => [561 ["git", "config", "--global", "--unset-all", `credential.${url}.helper`],562 ["git", "config", "--global", "--unset-all", `credential.${url}.useHttpPath`],563];564565const HELPER_KEY = /^credential\.(?<url>.+)\.helper$/u;566640/** The urls whose git config names this CLI's helper. */567const helperUrls = (env: Readonly<Record<string, string>>) =>568 Effect.gen(function* () {569 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;570
74 unmodified lines
modified:apps/cli/src/local/project-file.ts+1 added-27 removed
1/**2 * The config folder's `project.ts` that `init` proposes: the run block the3 * finder read from the repo's own files, each command with where it was4 * found, and nothing else, so every other setting takes its default. Pure:5 * the same commands always give the same text.6 */1import { Brand } from "@repo/brand";2import type { RunBlockEncoded } from "@repo/checks/finder";3import { PATH_PLACEHOLDER } from "@repo/checks/kinds";411/** A value in the run block: a command, or `setupEgress`'s hosts. */5type Value = string | readonly string[];614/** The run block's keys in the order the file writes them; `checks` last. */7const KEYS = ["setup", "test", "doctor", "image", "setupEgress"] as const;817/** A key as TypeScript writes it: bare when it is an identifier. */9const keyOf = (name: string) =>10 /^[A-Za-z_$][\w$]*$/u.test(name) ? name : JSON.stringify(name);1121/** Text as one line of a `//` comment, whatever it holds. */12const oneLine = (text: string) => text.replaceAll(/\s+/gu, " ").trim();1314const comment = (indent: string, text: string) =>15 `${indent}// ${oneLine(text)}`;1627/**28 * The finder's sources for one part of the run block: `setup from <path>`,29 * `setup inferred from <path>`, `checks.lint from <path>`.30 */17const sourcesOf = (sources: readonly string[], part: string) =>18 sources.filter(19 (source) =>20 source.startsWith(`${part} from `) ||21 source.startsWith(`${part} inferred from `)22 );2338/** The parts the run block holds, each with its value, in the file's order. */24const partsOf = (run: Partial<RunBlockEncoded>) => [25 ...KEYS.flatMap((key) =>26 run[key] === undefined ? [] : [{ part: key, value: run[key] }]27 ),
2 unmodified lines
30 value: command,31 })),32];3349/** Every source no written part names: what the finder skipped, and why. */34const others = (35 sources: readonly string[],36 parts: readonly { readonly part: string }[]37) =>
3 unmodified lines
4142const rules = (names: string) =>43 `import { ${names} } from "${Brand.cliPackage}/rules";`;4461/** A run block written out: each command under the comments naming its sources. */45const explicit = (46 run: Partial<RunBlockEncoded>,47 sources: readonly string[]48) => {
31 unmodified lines
80 "",81 ];82};83101/**102 * No command that runs one test file: the file can't state a run block the103 * SDK accepts, so it keeps the platform's own finder, and lists in comments104 * what this one found.105 */84/** With no command that runs one test file, the SDK accepts no run block, so the file keeps the platform's finder. */85const fromCI = (run: Partial<RunBlockEncoded>, sources: readonly string[]) => {86 const parts = partsOf(run);8788 return [
18 unmodified lines
107 "",108 ];109};110132/**133 * The proposed `<configDir>/project.ts` for a run block the finder found134 * and its sources (`findRunBlock` from `@repo/checks/finder`). It imports135 * the SDK from the published CLI's `/rules`, as a maintainer's repo does.136 */111export const projectFile = (112 run: Partial<RunBlockEncoded>,113 sources: readonly string[]114): string =>
4 unmodified lines
modified:apps/cli/src/local/ratchets.ts+3 added-42 removed
1/**2 * `check`'s ratchets: the project's ratchets counted on this machine, on the3 * tree an answer started from and on the answer's own, by the count lanes4 * the platform's cheap stage runs (`countLanes`, from the run block, each5 * handing back its stdout) and read by the platform's own counting code6 * (`measure`); then judged by the Project DO's own `judgeRatchets` (all three7 * in `@repo/checks/kinds/ratchet`), with the base's counts standing in for8 * the baselines, which no contract serves (a landing leaves each baseline at9 * what main then counts). A count over its base's is `Weakened{ratchet}`,10 * unless a reasoned escape the answer adds in that territory asks a decider11 * to raise it (`explainedRaises` in `@repo/gate/escapes`): then the answer12 * will wait on that decision instead.13 *14 * A ratchet this machine cannot count (its command prints nothing the15 * counter reads, or the tree could not be checked out and set up) is named16 * with why, and left to the platform: it never fails `check`.17 */1// The base's counts stand in for the baselines, which no contract serves.2// A ratchet this machine cannot count is left to the platform: it never fails `check`.3import { CheckAt, CheckRunner, outputOf } from "@repo/checks/check-runner";4import type { CheckLane, CheckRun } from "@repo/checks/check-runner";5import {6 countLanes,
13 unmodified lines
20import { RatchetName } from "@repo/protocol/ids";21import type { CommitSha, ProjectName, RepoName } from "@repo/protocol/ids";22import { Array, Effect, Option, Result, Schema } from "effect";2339/** One ratchet's count in one territory, on the answer's base and on its head. */24export const RatchetMove = Schema.Struct({25 after: Schema.Int,26 before: Schema.Int,27 ratchet: RatchetName,
1 unmodified line
29});3031export type RatchetMove = typeof RatchetMove.Type;3249/** A ratchet no count was read for here, and why. */33export interface Uncounted {34 readonly ratchet: RatchetName;35 readonly why: string;36}3755/** What counting on this machine gave: the counts both trees had, and what it could not count. */38export interface LocalCounts {39 readonly moves: readonly RatchetMove[];40 readonly uncounted: readonly Uncounted[];41}4261/** How a count lane that printed no count ended, in words. */43const endings = {44 blocked: "it never ran here, or ran out of time",45 failed: "it failed",46 flaked: "it flaked",47 loadError: "it did not load",48 passed: "it passed",49} as const satisfies Record<LaneOutcome, string>;5070/**71 * How a count lane that printed no count ended, when that says more: the72 * failure's signature, or else the way it ended (a command this machine73 * lacks never ran).74 */51const endedAs = (ran: CheckRun, lane: Option.Option<CheckLane>) =>52 Option.flatMap(lane, ({ lane: name }) =>53 Option.firstSomeOf([54 Array.findFirst(ran.evidence, (each) => each.lane === name).pipe(
5 unmodified lines
60 ),61 ])62 );6388/** One ratchet's counts per territory on one tree, or why none were read. */64interface Counted {65 readonly ratchet: RatchetName;66 readonly counts: Result.Result<readonly RatchetCount[], Uncounted>;67}6894/** Each ratchet's counts from one run of its count lanes. */69const countsIn = (70 policy: Policy,71 ran: CheckRun72): Effect.Effect<readonly Counted[]> => {
26 unmodified lines
99 );100 });101};102129/**130 * The project's ratchets counted at `base` and at `head`, each tree in a131 * checkout of its own set up by the run block, as the platform counts them132 * in a Checker job of their own. A count only one tree has is not judged133 * (the platform's first landing sets that baseline).134 */103/** A count only one tree has is not judged: the platform's first landing sets that baseline. */104export const countRatchets = (input: {105 readonly base: CommitSha;106 readonly head: CommitSha;107 readonly policy: Policy;
67 unmodified lines
175176 return { moves, uncounted };177 });178210/**211 * The answer's counts judged by the Project DO's own `judgeRatchets`, with212 * each count on the base as the baseline and the raises the push's reasoned213 * escapes explain, as the Project DO reads them from the same facts: a count214 * over its base's is refused `Weakened{ratchet}`, unless the answer asks to215 * raise that ratchet in that territory, when it waits on a decider instead216 * (`decisions`).217 */179export const judgeMoves = (180 facts: PushFacts,181 ask: Ask,182 moves: readonly RatchetMove[]
15 unmodified lines
modified:apps/cli/src/local/stale.ts+1 added-21 removed
1/**2 * Stale generated files in a working copy: the project's3 * contribute skill (`.agents/skills/<key>-contribute/SKILL.md` and its4 * `.claude/skills/` copy) and the block in its AGENTS.md, regenerated here5 * with `@repo/agent-kit` from the policy at `main` and compared with what is6 * on disk. The platform lands them again whenever the config changes what7 * they say, so a copy that differs was generated for an older config, or8 * was edited by hand; `<cli> check` warns about each one and lists it.9 *10 * Read only: nothing here writes a file. A missing file is no copy, and11 * never stale; nor is an AGENTS.md with no block, whose text is all the12 * project's own. A skill copy without the platform's frontmatter is stale:13 * its path is the platform's, so the frontmatter was taken off (`isStale`).14 */1// A skill copy without the platform's frontmatter is stale: its path is the platform's, so the frontmatter was taken off.2import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";3import { isStale } from "@repo/agent-kit/generated-file";4import { projectSkill } from "@repo/agent-kit/project-skill";5import type { Policy } from "@repo/protocol/domain/policy";6import type { LandedSha, ProjectName } from "@repo/protocol/ids";7import { Effect, FileSystem, Option, Path } from "effect";822/** A generated file on disk that is not what main's policy gives, and the landing its copy names. */9export interface StaleCopy {10 readonly path: string;25 /** The landing the copy says it came from; none for the AGENTS.md block, which names none, and for a skill copy without frontmatter. */11 readonly landed: Option.Option<LandedSha>;12}1314const agentsFile = "AGENTS.md";1531/**32 * Every generated file in the working copy at `root` that differs from the33 * one `policy` (read at the landing `landed`) gives: the skill's copies by34 * their recorded hash (`isStale`), the AGENTS.md block by its text.35 */16export const staleGenerated = (input: {17 readonly root: string;18 readonly project: ProjectName;19 readonly policy: Policy;
47 unmodified lines
modified:apps/cli/src/local/why.ts+1 added-48 removed
1/**2 * `<cli> why <path>:<line>`: which landing put a line there, and why. git3 * blame names the commit; the platform's landing record names the ask (the4 * one it answers, or the one an ask's opening opened), the accountable5 * author, every credit and the verdict. A commit the platform did not land6 * is said to be none of its landings, with the trailers its author wrote. A verdict note fetched from the platform rides along, but7 * the landing record is the source.8 */1import { notesRef } from "@repo/git/notes";2import { parseTrailers } from "@repo/git/trailers";3import type { Trailer } from "@repo/git/trailers";4import { Client } from "@repo/protocol/contracts";
17 unmodified lines
22import type { View } from "../output.ts";23import { repoContext } from "../repo-context.ts";24import type { RepoContext } from "../repo-context.ts";2534/**35 * Where a local command runs git: the process's own folder unless a caller36 * (a test) provides another. Shared with `env set`.37 */26export const WorkingDirectory = Context.Reference<string>(27 "cli/WorkingDirectory",28 { defaultValue: () => "." }29);3043/**44 * A command used wrongly: `program` prints its one line on stderr and the45 * process exits 2 with nothing more printed. Shared with `env set`.46 */31export class UsageError extends Schema.TaggedError<UsageError>()("UsageError", {32 reason: Schema.String,33}) {34 override readonly [Runtime.errorExitCode] = 2;
3 unmodified lines
38 return this.reason;39 }40}4158/**59 * Ends the command as a usage error: `program` prints `reason` once on60 * stderr, as it does every misuse, and exits 2.61 */42export const usage = (reason: string) =>43 Effect.fail(new UsageError({ reason }));4445const isRefusal = Schema.is(Refusal);4667/**68 * Prints a refusal the platform answered with, once, through `Output`, and69 * ends with `Reported` and the refusal's exit code. Shared with `env set`.70 */47export const reportRefusals =48 (command: string, json: boolean) =>49 <A, E, R>(effect: Effect.Effect<A, E, R>) =>50 effect.pipe(
3 unmodified lines
54 )55 )56 );5782/**83 * The project a command acts on: `--project`, else the one the repo's84 * platform remote names. Shared with `env set`.85 */58export const projectOf = (59 named: Option.Option<ProjectName>,60 context: Option.Option<RepoContext>61) =>
11 unmodified lines
73 onSome: Effect.succeed,74 }75 );76105// A path, then a line number from 1 with no sign or leading zero. The path106// takes everything before the last colon, so a path may hold one.77// The path takes everything before the last colon, so a path may hold one.78const LOCATION = /^(?<path>.+):(?<line>[1-9][0-9]*)$/u;79109/** A line of a file as people and compilers write it: `src/week.ts:42`. */80export const parseLocation = (81 text: string82): Option.Option<{ readonly path: RepoPath; readonly line: number }> => {83 const groups = LOCATION.exec(text)?.groups;
3 unmodified lines
87 ? Option.none()88 : Option.some({ line, path: RepoPath.make(groups.path) });89};90121/** What `why` found: the line's commit and what is known of it. */91const LineOrigin = Schema.Struct({123 /** The platform's record, when the commit is one of its landings. */92 landing: Schema.optionalKey(LandingView),93 line: Schema.Int,126 /** The verdict note on the commit, when one was fetched. */94 note: Schema.optionalKey(Verdict),95 path: RepoPath,96 sha: CommitSha,130 /** The commit's own trailers, when the platform did not land it. */97 trailers: Schema.optionalKey(98 Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.String }))99 ),100});
6 unmodified lines
107108const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>109 bytes.pipe(Stream.decodeText(), Stream.mkString);110145/** Runs git in `cwd` to the end: its stdout and exit code; stderr is dropped. */111const git = (cwd: string, args: readonly string[]) =>112 Effect.scoped(113 Effect.gen(function* () {114 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
14 unmodified lines
129 return { exitCode, stdout };130 })131 );132168/** The line is in no file committed at HEAD. */133const noSuchLine = (location: string) =>134 usage(135 `${location} is not a line of a file committed at HEAD: ${location.replace(/:[0-9]+$/u, "")} is not there, or is shorter.`136 );137174/** `path` as the repo names it from its root, if HEAD holds it. */138const pathAtHead = (cwd: string, path: RepoPath, location: string) =>139 Effect.flatMap(140 git(cwd, [141 "ls-tree",
15 unmodified lines
157158// git blame's porcelain opens with the line's commit, then its line numbers.159const BLAMED = /^(?<sha>[0-9a-f]{40}) /u;160198/** The commit that last changed line `line` of `path` at HEAD. */161const blamed = (cwd: string, path: RepoPath, line: number, location: string) =>162 Effect.flatMap(163 git(cwd, [164 "blame",
12 unmodified lines
177 : noSuchLine(location);178 }179 );180219/** The trailers `sha`'s author wrote, as git reads them. */181const trailersOf = (cwd: string, sha: CommitSha) =>182 Effect.map(git(cwd, ["log", "-1", "--format=%B", sha]), ({ stdout }) =>183 parseTrailers(stdout)184 );185225/** The verdict note on `sha`, if one was fetched and it reads as a verdict. */186const noteOn = (cwd: string, sha: CommitSha) =>187 Effect.flatMap(188 git(cwd, ["notes", `--ref=${notesRef}`, "show", sha]),189 ({ exitCode, stdout }) => {
14 unmodified lines
204 );205206const short = (sha: string) => sha.slice(0, 7);207248/** One fact about the line, as a list item. */208interface Row {209 readonly label: string;210 readonly value: string;252 /** Code in Markdown: an id or a path. */211 readonly code?: boolean;212}213214const verdictRow = (verdict: Verdict): Row => ({
3 unmodified lines
218 ...verdict.lanes.map(({ lane, result }) => `${lane} ${result}`),219 ].join(", "),220});221264/**265 * The ask a landing links: the one it answers ("Ask"), else the one it266 * opened ("Opened": an opening answers nothing), else none.267 */222const askRow = (landing: LandingView): Row => {223 if (landing.ask !== undefined) {224 return { code: true, label: "Ask", value: landing.ask };225 }
21 unmodified lines
247248const trailerRows = (trailers: readonly Trailer[]): readonly Row[] =>249 trailers.map(({ key, value }) => ({ label: key, value }));250297/** The line's story, in Markdown for agents and plain text for a person. */251const viewOf = (origin: LineOrigin): View => {252 const at = `${origin.path}:${origin.line}`;253 const commit = short(origin.sha);254 const verdict = origin.note ?? origin.landing?.verdict;
122 unmodified lines
modified:apps/cli/src/tui/command.ts-17 removed
1/**2 * `<cli> today`, written by hand so it can take `--tui`: without it, the3 * command prints Today exactly as the `today` contract's projected command4 * does (the same flags, view, `--json` envelope and refusals); with it, a5 * person at a terminal gets Today full-screen (`run.ts`). It stands in for6 * the projected command, as `init` and `env set` do for theirs, and calls7 * the same contract through the CLI's remote client.8 */1import { Client, Description, TodayOf } from "@repo/protocol/contracts";2import { ProjectName } from "@repo/protocol/ids";3import type { NotDecider, UnknownProject } from "@repo/protocol/refusal";4import { Context, Effect, Option, Schema } from "effect";
6 unmodified lines
11const COMMAND = "today";1213const encodeToday = Schema.encodeUnknownEffect(TodayOf.successSchema);1423/**24 * The `today` contract's refusals, each printed once where the command's25 * refusals go; the command then ends `Reported`, with the refusal's exit code.26 */15const reported = (json: boolean) => {16 const once = (refusal: NotDecider | UnknownProject) =>17 Effect.flatMap(Effect.service(Output), (output) =>18 endRefused(output, { command: COMMAND, json, refusals: [refusal] })
1 unmodified line
2021 return { NotDecider: once, UnknownProject: once };22};2336/** Today printed once, in the form the invocation policy chose. */24const print = (input: {25 readonly json: boolean;26 readonly project: Option.Option<ProjectName>;27}) =>
20 unmodified lines
48 view,49 });50 });5165/**66 * Today full-screen. `--json` asks for one document for a script, which a67 * screen is not, so the two together are refused like a script's `--tui`.68 */52const full = (input: {53 readonly json: boolean;54 readonly project: Option.Option<ProjectName>;55}) =>
44 unmodified lines
modified:apps/cli/src/tui/run.ts-45 removed
1/**2 * `<cli> today --tui`: Today full-screen, for a person at a terminal. It3 * reads Today and takes decisions through the same `today` and `decide`4 * contracts as every other surface, over the CLI's remote client: no second5 * data path. Under an agent, in a script, or without a terminal to read6 * keys from, it never opens (nor prompts): it refuses and points to7 * `today --json`.8 *9 * The screen is a port: the terminal through OpenTUI (`screen.ts`, loaded10 * only here, so no other command loads OpenTUI or its native library), or11 * whatever a test gives `OpenScreen`.12 */1import { Brand } from "@repo/brand";2import { Client } from "@repo/protocol/contracts";3import type { Decision } from "@repo/protocol/domain/decision";4import type { ProjectName } from "@repo/protocol/ids";
14 unmodified lines
19import { CurrentMode, Policy } from "../policy.ts";20import { placeOf, reduce, refreshed, start } from "./today.ts";21import type { DecideCall, TodayViewState } from "./today.ts";2235/** What a script or an agent runs for Today instead. */23const instead = `${Brand.cli} today --json`;2438/**39 * `--tui` was asked for where no person can work it: under an agent, in a40 * script, or without a terminal. A usage error (exit 2) on the CLI's side,41 * not one of the platform's refusals: nothing was called. Its `next` is the42 * command that reads the same Today as one JSON document.43 */25export class TuiRefused extends Schema.TaggedError<TuiRefused>()("TuiRefused", {26 next: Schema.NonEmptyString.pipe(27 Schema.withConstructorDefault(Effect.succeed(instead))28 ),
5 unmodified lines
34 return `${Brand.cli} today --tui needs a person at a terminal, but ${this.reason}: run ${this.next} instead`;35 }36}3757/** Why something failed, in a few words: its message, or itself. */38export const causeText = (cause: unknown) =>39 Predicate.hasProperty(cause, "message") && Predicate.isString(cause.message)40 ? cause.message41 : String(cause);4263/** A screen Today is drawn on and keys are read from. */43export interface Screen {65 /** Draws a state in place of the one before. */44 readonly show: (state: TodayViewState) => Effect.Effect<void>;67 /** The next key the person presses, by name: `down`, `d`, `return`, `ctrl+c`. */45 readonly key: Effect.Effect<string>;69 /** Forgets the keys pressed and not read yet: those pressed while a choice was on its way. */46 readonly forget: Effect.Effect<void>;47}4849/** Opens the terminal through OpenTUI, loading it only now. */
5 unmodified lines
55 }),56 try: () => import("./screen.ts"),57 }).pipe(Effect.flatMap(({ openTerminal }) => openTerminal));5883/** How `--tui` opens its screen: the terminal, unless a test gives another. */59export const OpenScreen = Context.Reference<60 Effect.Effect<Screen, TuiRefused, Scope.Scope>61>("cli/tui/OpenScreen", { defaultValue: () => terminal });6288/**89 * The invocation policy given, or else this process's own: the tree's90 * commands take the policy as `program` does, as a service that may be91 * absent.92 */63const invocation = Effect.flatMap(64 Effect.serviceOption(Policy),65 Option.match({66 onNone: () => Effect.provide(Effect.service(Policy), CurrentMode),67 onSome: Effect.succeed,68 })69);70101/**102 * A person at a terminal, by the CLI's invocation policy, who can type103 * there too: anything else is refused before the platform is called.104 */71const aPersonAtATerminal = Effect.gen(function* () {72 const { mode, reason } = yield* invocation;7374 const typing = yield* Effect.flatMap(
14 unmodified lines
89});9091const isRefusal = Schema.is(Refusal);92127/** The `today` contract's payload, for one project or every one. */93export const payloadFor = (project: Option.Option<ProjectName>) =>94 Option.match(project, {95 onNone: () => ({}),96 onSome: (name) => ({ project: name }),97 });98134/** What a choice the platform took came to, in one line. */99const decidedLine = (call: DecideCall, decision: Decision) =>100 `Decided: ${decision.decided?.choice ?? call.choice} on ${placeOf(call.project, call.decision)}`;101138/**139 * `runTodayTui`: Today full-screen until the decider closes it. Arrows move,140 * a choice key decides through `decide` (a choice other than the default141 * after a confirmation), and each choice is followed by Today read again.142 * A refusal of a choice shows on the screen in `explain`'s words; a refusal143 * of Today itself, or a platform out of reach, closes the screen and fails.144 */102export const runTodayTui = (input: {103 readonly project: Option.Option<ProjectName>;104}) =>105 Effect.gen(function* () {
4 unmodified lines
110 const payload = payloadFor(input.project);111112 const first = start(yield* client.today(payload));113157 /** Sends a choice, then reads Today again, and says what it came to. */114 const decide = (screen: Screen, state: TodayViewState, call: DecideCall) =>115 Effect.gen(function* () {116 yield* screen.show({117 ...state,
16 unmodified lines
134135 return after;136 });137182 /** One key, then the next, until the decider closes Today. */138 const session = (139 screen: Screen,140 state: TodayViewState141 ): Effect.Effect<void, Effect.Error<ReturnType<typeof decide>>> =>
29 unmodified lines
modified:apps/cli/src/tui/screen.ts+3 added-17 removed
1/**2 * The terminal as Today's screen, through OpenTUI: each state drawn in place3 * of the last by its React renderer, and each key the person presses read4 * by name. `run.ts` loads this module only when `--tui` opens Today, since5 * importing OpenTUI loads its native library.6 */1// Loaded only when `--tui` opens Today, since importing OpenTUI loads its native library.2import { createCliRenderer } from "@opentui/core";3import type { CliRenderer, KeyEvent } from "@opentui/core";4import { createElement, createRoot, flushSync } from "@opentui/react";5import { Effect, Queue } from "effect";
2 unmodified lines
8import { causeText, TuiRefused } from "./run.ts";9import type { Screen } from "./run.ts";10import { TodayView } from "./view.ts";1117/** A key as `reduce` reads it: its name, with `ctrl+` before it when Ctrl is held. */12const keyName = (key: KeyEvent) => (key.ctrl ? `ctrl+${key.name}` : key.name);1320/**21 * Today on `renderer`, for the scope: every key pressed waits in a queue22 * until it is read. A state replaces the tree drawn before it (OpenTUI's23 * root draws one element, so the last one is unmounted first).24 */14/** OpenTUI's root draws one element, so the last one is unmounted first. */15export const screenOn = (16 renderer: CliRenderer17): Effect.Effect<Screen, never, Scope.Scope> =>18 Effect.gen(function* () {
25 unmodified lines
44 }),45 } satisfies Screen;46 });4758/**59 * The process's own terminal, taken over for the scope (the alternate60 * screen, so the decider's scrollback is back as it was when Today61 * closes). Ctrl+C is a key here, which closes Today like `q`.62 */48/** Ctrl+C is a key here, which closes Today like `q`. */49export const openTerminal: Effect.Effect<Screen, TuiRefused, Scope.Scope> =50 Effect.acquireRelease(51 Effect.tryPromise({52 catch: (cause) =>
15 unmodified lines
modified:apps/cli/src/tui/today.ts+5 added-54 removed
1/**2 * Today in the terminal, as pure state: which decision the cursor is on,3 * which choice waits for a confirmation, and what the last choice came to.4 * `reduce` turns one key into the next state and, when the decider has5 * chosen, the `decide` call to make; the screen and the platform are the6 * runner's (`run.ts`). Nothing here touches the terminal, so the CLI loads7 * OpenTUI only when `--tui` opens it.8 *9 * The decisions are in the order a decider takes them, as the web's Today10 * lists them: those expiring within the day first, then by expiry. Each11 * subject offers its own two choices, each on its first letter: a stray12 * push is adopted (`a`) or reverted (`r`), anything else accepted (`a`) or13 * declined (`d`). A decision's default is taken at once; any other choice14 * waits for `y` (or Enter), since the default is the safe one.15 */1// Nothing here touches the terminal, so the CLI loads OpenTUI only when `--tui` opens it.2// A choice other than the decision's default waits for `y`: the default is the safe one.3import type { Decide } from "@repo/protocol/contracts";4import { DecisionSubject } from "@repo/protocol/domain/decision";5import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";6import type { DecisionId, ProjectName } from "@repo/protocol/ids";7import { Array as Arr, DateTime, Option, Order } from "effect";822/** A choice on its way to `decide`: the contract's payload, without a note. */9export type DecideCall = Omit<typeof Decide.payloadSchema.Type, "note">;1011export interface TodayViewState {12 readonly today: Today;27 /** The decision the decider is on, as an index into `inOrder(today)`. */13 readonly cursor: number;29 /** A choice other than the default, waiting for `y` before it is sent. */14 readonly confirming: Option.Option<DecideCall>;31 /** What the last choice came to, one line each: decided, or the refusal. */15 readonly notice: readonly string[];16}1735/** What one key did: the next state, the call to make, and whether to close. */18export interface Step {19 readonly state: TodayViewState;20 readonly call: Option.Option<DecideCall>;21 readonly quit: boolean;22}2342/**43 * A decision's place in a Today that may hold several projects, as the44 * screen names it: ids are minted per project, so the project comes first.45 */24/** Ids are minted per project, so the project comes first. */25export const placeOf = (project: ProjectName, id: DecisionId) =>26 `${project}/${id}`;2728const keyOf = ({ id, project }: Decision) => placeOf(project, id);2951/** Soonest to expire first, then oldest, then by project and id: one order every time. */30const expiryOrder: Order.Order<Decision> = Order.combineAll([31 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),32 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),33 Order.mapInput(Order.String, ({ project }: Decision) => project),34 Order.mapInput(Order.String, ({ id }: Decision) => id),35]);3659/**60 * The decisions `today.expiringSoon` names. Ids are minted per project, so61 * where an id is named `n` times, the `n` of its decisions that expire first62 * are the ones meant (the web's Today reads them the same way).63 */37/** Ids are minted per project: where an id is named `n` times, its `n` soonest-expiring decisions are meant. */38const expiringSoon = (today: Today): ReadonlySet<string> => {39 const named = Arr.groupBy(today.expiringSoon, (id) => id);40 const byExpiry = Arr.sort(today.decisions, expiryOrder);41
6 unmodified lines
48 )49 );50};5178/** Whether a decision is one of those `today.expiringSoon` names. */52export const soonIn = (today: Today) => {53 const soon = expiringSoon(today);5455 return (decision: Decision) => soon.has(keyOf(decision));56};5785/** Today's decisions in the order a decider takes them: expiring soon first, then by expiry. */58export const inOrder = (today: Today): readonly Decision[] => {59 const isSoon = soonIn(today);6061 return Arr.sort(
4 unmodified lines
66 )67 );68};6998/** A choice, and the key that makes it. */70export interface ChoiceKey {71 readonly choice: Choice;72 readonly key: string;73}
2 unmodified lines
76 { choice: "accept", key: "a" },77 { choice: "decline", key: "d" },78];79109/** The choices a decision's subject offers, each with its key. */80export const choicesFor = (decision: Decision): readonly ChoiceKey[] =>81 DecisionSubject.match(decision.subject, {82 Finish: () => yesOrNo,83 OpenProposal: () => yesOrNo,
8 unmodified lines
92 Vouch: () => yesOrNo,93 Waiver: () => yesOrNo,94 });95126/** Today as the decider first sees it: on the first decision, nothing chosen. */96export const start = (today: Today): TodayViewState => ({97 confirming: Option.none(),98 cursor: 0,99 notice: [],100 today,101});102134/** The decision the cursor is on, if Today holds any. */103export const current = (state: TodayViewState): Option.Option<Decision> =>104 Arr.get(inOrder(state.today), state.cursor);105138/** A cursor kept on a decision: never past the last one, never below the first. */106const clamp = (cursor: number, today: Today) =>107 Math.max(0, Math.min(cursor, today.decisions.length - 1));108109const stay = (state: TodayViewState): Step => ({
14 unmodified lines
124 confirming: Option.none(),125 cursor: clamp(state.cursor + by, state.today),126 });127161/**162 * The choice `key` makes on the decision the cursor is on: its default goes163 * at once, any other waits for a confirmation. A key the subject doesn't164 * offer, or a decision already decided, does nothing.165 */128const choose = (state: TodayViewState, key: string): Step =>129 Option.match(current(state), {130 onNone: () => stay(state),131 onSome: (decision) =>
29 unmodified lines
161const CONFIRM = new Set(["y", "return", "enter"]);162163const CANCEL = new Set(["n", "escape"]);164203/** One key, with no confirmation waiting. */165const free = (state: TodayViewState, key: string): Step => {166 if (UP.has(key)) {167 return moveBy(state, -1);168 }
8 unmodified lines
177178 return choose(state, key);179};180220/**221 * One key, by its name (`up`, `d`, `return`, `ctrl+c`): moves the cursor222 * (arrows, `j`/`k`), makes a choice, confirms (`y`, Enter) or cancels (`n`,223 * Escape) a choice waiting, or closes Today (`q`, Escape, Ctrl+C). Any other224 * key while a choice waits cancels it, then does what it does.225 */181export const reduce = (state: TodayViewState, key: string): Step =>182 Option.match(state.confirming, {183 onNone: () => free(state, key),184 onSome: (waiting) => {
6 unmodified lines
191 return CANCEL.has(key) ? stay(cancelled) : free(cancelled, key);192 },193 });194240/**241 * Today again after a choice: the platform's newer page, the cursor on the242 * same place (the decision taken has left it, so the next one is there),243 * and what the choice came to.244 */195/** The decision taken has left the list, so the same cursor lands on the next one. */196export const refreshed = (197 state: TodayViewState,198 today: Today,199 notice: readonly string[]
6 unmodified lines
modified:apps/cli/src/tui/view.ts+3 added-27 removed
1/**2 * Today on a terminal screen, drawn by OpenTUI's React renderer from the3 * state alone: whose Today it is and the budget; the decisions in the order4 * a decider takes them, from the one under the cursor on (those above it5 * counted), each with what it is about, when it expires (marked6 * when that is within the day), its default and its evidence; the newcomers7 * to welcome; what the last choice came to; and the keys the decision under8 * the cursor takes. Written with `createElement`, so the CLI's `.ts` build9 * needs no JSX.10 */1// Written with `createElement`, so the CLI's `.ts` build needs no JSX.2import { TextAttributes } from "@opentui/core";3import { createElement } from "@opentui/react";4import type { BoxProps, TextProps } from "@opentui/react";5import type { JSX } from "@opentui/react/jsx-runtime";
5 unmodified lines
11import type { DecideCall, TodayViewState } from "./today.ts";1213const short = (sha: string) => sha.slice(0, 7);1424/** A ref as people say it: `main` for `refs/heads/main`. */15const refWords = (ref: string) => ref.replace(/^refs\/heads\//u, "");1627/** What a decision is about, in a few words. */17const about = DecisionSubject.match({18 Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,19 OpenProposal: ({ proposal }) => `open the ask ${proposal} proposes`,20 PostureChange: ({ from, to }) => `change the posture from ${from} to ${to}`,
9 unmodified lines
30 Waiver: ({ at, marker, reason }) =>31 `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,32});3345/** An expiry as a decider reads it: weekday, date and time, in UTC. */34const byWhen = (at: DateTime.Utc) =>35 `${DateTime.formatUtc(at, {36 day: "numeric",37 hour: "2-digit",
9 unmodified lines
4748const capitalized = (word: string) =>49 `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`;5063/**64 * Boxes and lines keep their own height: on a terminal shorter than Today65 * the screen is cut at its foot, never squeezed into rows drawn over each66 * other.67 */51/** Boxes keep their own height: a short terminal cuts the screen at its foot rather than drawing rows over each other. */52const box = (props: BoxProps, ...children: readonly JSX.Element[]) =>53 createElement("box", { flexShrink: 0, ...props }, ...children);5455const line = (content: string, props: TextProps = {}) =>56 createElement("text", { flexShrink: 0, wrapMode: "word", ...props }, content);5758const muted = { attributes: TextAttributes.DIM } as const satisfies TextProps;5976/** One fact's value as a row holds it: its first line, and how many follow. */60const firstLine = (value: string) => {61 const [first = "", ...rest] = value.split("\n");6263 return rest.length === 0
44 unmodified lines
108 line(` ${label}: ${firstLine(value)}`, muted)109 )110 );111129/**130 * The decisions from the one under the cursor on, those above it only131 * counted: whatever the terminal's height, the decision a key would take is132 * drawn just below the budget, never cut off at the foot of the screen.133 */112/** Decisions above the cursor are only counted, so the one a key would take is never cut off at the foot. */113const Decisions = ({ state }: { readonly state: TodayViewState }) => {114 const ordered = inOrder(state.today);115 const isSoon = soonIn(state.today);116 const above = state.cursor;
27 unmodified lines
144 state.today.newcomers.length === 0145 ? box({})146 : line(`Newcomers to welcome: ${state.today.newcomers.join(", ")}`);147169/** The question a choice other than the default waits on. */148const question = (call: DecideCall, fallback: Choice) =>149 `${capitalized(call.choice)} ${placeOf(call.project, call.decision)}? Its default is ${fallback}. y to send it, n to keep it open.`;150173/** The keys the decision under the cursor takes, or the confirmation waiting. */151const Keys = ({ state }: { readonly state: TodayViewState }) => {152 const here = current(state);153154 const asking = Option.flatMap(state.confirming, (call) =>
17 unmodified lines
172 line(["up/down move", ...choices, "q quit"].join(" · "), muted)173 );174};175199/** The whole screen for one state. */176export const TodayView = ({177 state,178}: {179 readonly state: TodayViewState;
8 unmodified lines
modified:apps/cli/src/bin.ts+2 added-21 removed
1#!/usr/bin/env node2/**3 * The CLI's process entry: `program` over the arguments the process was4 * started with, on Bun's services and `CliServices` (the credentials file,5 * the invocation policy, output in its form and the remote client).6 * Tests never import this file; they run `program` with their own services,7 * and `test/build.test.ts` runs what `build.ts` makes of it. One file plays8 * two roles, chosen by the name it was started by: the CLI, and git's9 * credential helper.10 */2// One file plays two roles, chosen by the name it was started by: the CLI, and git's credential helper.3import { BunRuntime, BunServices } from "@effect/platform-bun";4import { Brand } from "@repo/brand";5import { Effect, Layer, Path, Stdio } from "effect";67import { CliServices, program } from "./main.ts";89const live = CliServices.pipe(Layer.provideMerge(BunServices.layer));1019/**20 * The names this process may have been started by. The compiled binary21 * keeps the name of the link it was run through in `argv0` (its `argv[1]`22 * is its own bundled path); Node or Bun running `dist/bin.js` through an23 * npm bin link keeps the link's path in `argv[1]` (their `argv0` is the24 * runtime's).25 */11/** The compiled binary keeps its link's name in `argv0`; Node or Bun through an npm bin link keep it in `argv[1]`. */12const startedAs = Effect.map(Path.Path, (path) =>13 [process.argv0, process.argv[1]].map((name) => path.basename(name ?? ""))14);1530/**31 * Run as `git-credential-<slug>`, the process is `<cli> credential` with32 * git's arguments (`get`, `store` or `erase`); run by any other name, it is33 * the CLI.34 */16const main = Effect.gen(function* () {17 const names = yield* startedAs;18 const args = yield* Effect.flatMap(Stdio.Stdio, (stdio) => stdio.args);19
6 unmodified lines
modified:apps/cli/src/credential-helper.ts+3 added-49 removed
1/**2 * git's credential helper: `git-credential-<slug>`, which `login` names in3 * git's config for the platform's url (`gitHelperConfig`). git asks it for a4 * password after a 401 that names Basic; it answers from the stored profile5 * for that host, and never prompts, opens a terminal, or reads past the6 * blank line that ends git's request.7 *8 * The username it hands back carries the harness behind the push as audit9 * metadata (`@repo/protocol/audit`), never identity: the token in the10 * password slot is the only identity the platform reads.11 */1// The username carries the harness as audit metadata, never identity: the token is the only identity the platform reads.2import { Brand } from "@repo/brand";3import { auditUser, detectHarness } from "@repo/protocol/audit";4import {5 ConfigProvider,
8 unmodified lines
1415import { Credentials } from "./credentials.ts";16import { Output } from "./output.ts";1728/** What git asks a helper to do. */18export type Operation = "get" | "store" | "erase";1920const operations = [21 "get",22 "store",23 "erase",24] as const satisfies readonly Operation[];2537/** The env, by name: what `detectHarness` reads. */26export type Env = Readonly<Record<string, string | undefined>>;2740/**41 * The most indices the walk reads under one name. The config provider tells42 * an all-numeric level only its largest index, so a name like43 * `RUN_4294967294` would have the walk count to four billion on every git44 * call; names with an index past this are not read. No harness marker ends45 * in a number, and the binary's git child gets the process env whole.46 */28/** The config provider reports only an all-numeric level's largest index, so a name like `RUN_4294967294` would make the walk count to four billion. */29const INDEX_LIMIT = 1024;3049/** The env-name parts below `path` and their values, from the CLI's config provider. */31const namesBelow = (32 provider: ConfigProvider.ConfigProvider,33 path: ConfigProvider.Path34): Effect.Effect<readonly (readonly [string, string])[]> =>
28 unmodified lines
63 })64 )65 );6686/**87 * The env as the CLI sees it, every name with its value: read through the88 * config provider (the process env when nothing else is given), so a test's89 * env is the one a command sees and passes on.90 */67export const currentEnv: Effect.Effect<Readonly<Record<string, string>>> =68 Effect.gen(function* () {69 const provider = yield* ConfigProvider.ConfigProvider;7071 return Object.fromEntries(yield* namesBelow(provider, []));72 });7398/** git's request: its `key=value` lines, up to the blank line that ends it. */74const requestOf = (input: string) => {75 const fields = new Map<string, string>();7677 for (const line of input.split("\n")) {
10 unmodified lines
8889 return fields;90};91117/** The env names the CLI reads, spelled from the brand: `<SLUG>_PROFILE`. */92const SLUG = Brand.slug.toUpperCase();93120/** `url`'s scheme without its colon, and its `host[:port]` in lowercase, if it is a URL. */94const placeOf = Option.liftThrowable((url: string) => {95 const { host, protocol } = new URL(url);9697 return { host: host.toLowerCase(), scheme: protocol.replace(/:$/u, "") };98});99127/** A value git's credential protocol can carry: one line, no NUL. */100const fitsOneLine = (value: string) => !/[\n\r\0]/u.test(value);101130/** What the helper prints: for git on stdout, and maybe a line for a person on stderr. */102interface Answer {103 readonly stdout: string;104 readonly note: Option.Option<string>;105}106107const silent: Answer = { note: Option.none(), stdout: "" };108138/**139 * The helper's answer to `op` with git's `input`. `get` answers only for a140 * host a profile is on, over that profile's scheme. Under `<SLUG>_PROFILE`141 * only that profile may answer: it names the person git acts for, so the142 * helper never hands over another person's token for the same host. With no143 * login for the profile in use, it also says, once, how to log in. `store`144 * and `erase` do nothing: the stored token changes only through `login`145 * and `logout`.146 */109/** Under `<SLUG>_PROFILE` only that profile may answer, so another person's token for the same host is never handed over. */110const answer = (op: Operation, input: string, env: Env) =>111 Effect.gen(function* () {112 if (op !== "get") {113 return silent;
48 unmodified lines
162 }163 : silent;164 });165203/**204 * What the helper prints on stdout for `op`, given git's `input` and the205 * env it runs in: `username=<audit>\npassword=<token>\n`, or nothing.206 */166export const credentialHelper = (167 op: Operation,168 input: string,169 env: Env170): Effect.Effect<string, never, Credentials> =>171 Effect.map(answer(op, input, env), ({ stdout }) => stdout);172214/**215 * git's request from stdin: the lines up to the first blank one, read no216 * further, or up to the end if git closes stdin first.217 */173const readRequest = Effect.gen(function* () {174 const { stdin } = yield* Stdio.Stdio;175176 const lines = yield* stdin.pipe(
6 unmodified lines
183184 return `${lines.join("\n")}\n\n`;185});186232/** `<cli> credential <get|store|erase>`: what `git-credential-<slug>` runs. */187export const credential = Command.make(188 "credential",189 {190 operation: Argument.Literals("operation", operations).pipe(
27 unmodified lines
modified:apps/cli/src/credentials.ts+2 added-31 removed
1/**2 * The platform tokens the CLI holds, by profile, in the CLI's own file under3 * the user's config dir. git's credential helper, `login` and every remote4 * command read them here, and nowhere else. The env can stand in for the5 * file (`<SLUG>_TOKEN` with `<SLUG>_URL`), as a CI job would set it.6 */1import { Brand } from "@repo/brand";2import { Handle } from "@repo/protocol/ids";3import {4 Array,
7 unmodified lines
12 Path,13 Schema,14} from "effect";1522/** One platform the CLI can call, as whom. */16export const Profile = Schema.Struct({24 /** The handle the token was issued to, when `login` learned it. */17 handle: Schema.optionalKey(Handle),26 /** The platform token: the only identity the CLI and git present. */18 token: Schema.RedactedFromValue(Schema.NonEmptyString),28 /** The platform's origin: `https://platform-dev.example.workers.dev`. */19 url: Schema.NonEmptyString,20});2122export type Profile = typeof Profile.Type;2334/** The credentials file could not be written, or is there and unreadable. */24export class CredentialsUnwritable extends Schema.TaggedError<CredentialsUnwritable>()(25 "CredentialsUnwritable",26 { path: Schema.String }27) {
4 unmodified lines
3233export class Credentials extends Context.Service<34 Credentials,35 {47 /** The env's token and url, else the profile `<SLUG>_PROFILE` names, else `default`. */36 readonly current: Effect.Effect<Option.Option<Profile>>;49 /** The profile whose url is on `host` (`host[:port]`), the current one first. */37 readonly forHost: (host: string) => Effect.Effect<Option.Option<Profile>>;38 readonly put: (39 name: string,40 profile: Profile41 ) => Effect.Effect<void, CredentialsUnwritable>;55 /** Whether there was a profile by that name to remove. */42 readonly remove: (43 name: string44 ) => Effect.Effect<boolean, CredentialsUnwritable>;45 }46>()("cli/Credentials") {}4762/** The file: profiles by name. */48const Store = Schema.fromJsonString(49 Schema.Struct({ profiles: Schema.Record(Schema.String, Profile) })50);5152const decodeStore = Schema.decodeEffect(Store);5354const encodeStore = Schema.encodeEffect(Store);5571/** The env names, spelled from the brand: `<SLUG>_TOKEN`. */56const SLUG = Brand.slug.toUpperCase();5774/** What the CLI reads of its env, once. */58const Env = Config.all({59 configHome: Config.option(Config.NonEmptyString("XDG_CONFIG_HOME")),60 home: Config.option(Config.NonEmptyString("HOME")),61 profile: Config.option(Config.NonEmptyString(`${SLUG}_PROFILE`)),62 token: Config.option(Config.Redacted(`${SLUG}_TOKEN`)),63 url: Config.option(Config.NonEmptyString(`${SLUG}_URL`)),64});6583/** `url`'s `host[:port]`, in lowercase, if it is a URL. */66const hostOf = Option.liftThrowable((url: string) =>67 new URL(url).host.toLowerCase()68);69
1 unmodified line
71const FILE_MODE = 0o600;7273const DIR_MODE = 0o700;7493/**94 * The credentials file: `${XDG_CONFIG_HOME:-$HOME/.config}/<slug>/credentials.json`,95 * mode 0600, replaced whole on every write so no reader sees half of one.96 */75/** Replaced whole on every write so no reader sees half of one. */76export const CredentialsFile = Layer.effect(Credentials)(77 Effect.gen(function* () {78 const fs = yield* FileSystem.FileSystem;79 const path = yield* Path.Path;
16 unmodified lines
96 Option.all({ token: env.token, url: env.url }),97 ({ token, url }): Profile => ({ token, url })98 );99121 /** The profiles on disk: none without a file; a failure if it can't be read. */100 const load = Option.match(file, {101 onNone: () => Effect.succeed<Readonly<Record<string, Profile>>>({}),102 onSome: (at) =>103 Effect.gen(function* () {
9 unmodified lines
113 return store.profiles;114 }).pipe(Effect.mapError(() => new CredentialsUnwritable({ path: at }))),115 });116139 /** The profiles to read from: an unreadable file holds none. */117 const readable = Effect.orElseSucceed(118 load,119 (): Readonly<Record<string, Profile>> => ({})120 );
62 unmodified lines
183 };184 })185);186210/**211 * The `git config --global …` commands `login` and `init` run so that git212 * asks this CLI for the platform's token: `credential.<url>.helper` names213 * `<slug>`, so git runs `git-credential-<slug>`, after an empty helper that214 * drops any general one (a keychain) for this url; `useHttpPath` hands the215 * helper the repo's path too.216 */187/** An empty helper comes first to drop any general one (a keychain) for this url. */188export const gitHelperConfig = (189 url: string190): readonly (readonly string[])[] => [191 [
17 unmodified lines
modified:apps/cli/src/hook.ts+2 added-31 removed
1/**2 * `<cli> hook <event> --json`: the one command behind every harness hook in3 * Claude Code's format (Claude Code itself, and Cursor and Copilot CLI, which4 * read it). It reads the harness's JSON on stdin, gathers the session's facts5 * once (cached per session), asks `decideHook`, and prints the decision as6 * the one JSON document on stdout.7 *8 * Hooks are early feedback; the gateway is the authority. So the hook fails9 * open: without a claim, without the platform, with input it cannot read, or10 * on any failure of its own, it prints `{}` (go on), says why on stderr, and11 * exits 0. Only a wrong event name, a mistake in the hook's own config, is a12 * usage error (exit 2).13 */1// The gateway is the authority, so the hook fails open: on anything it cannot judge it prints `{}` and exits 0.2import { HookEvent } from "@repo/agent-kit/hook-events";3import { Brand } from "@repo/brand";4import {5 Cause,
19 unmodified lines
25import { Output } from "./output.ts";2627const EVENTS = HookEvent.literals.join(", ");2841/**42 * The hook was called with an event it does not answer: its config is43 * wrong. A usage error: `program` prints its one line and exits 2.44 */29export class HookUsage extends Schema.TaggedError<HookUsage>()("HookUsage", {30 event: Schema.String,31}) {32 override readonly [Runtime.errorExitCode] = 2;
5 unmodified lines
38}3940const decodeEvent = Schema.decodeUnknownOption(HookEvent);4158/** The whole of stdin, as text. */42const stdinText = Effect.flatMap(Stdio.Stdio, ({ stdin }) =>43 stdin.pipe(Stream.decodeText(), Stream.mkString)44);4563/** The PushCheck the caller provided, or this CLI run again as a child. */46const pushCheck = Effect.flatMap(47 Effect.serviceOption(PushCheck),48 Option.match({49 onNone: () => Effect.provide(Effect.service(PushCheck), PushCheckChild),50 onSome: Effect.succeed,51 })52);5372/**73 * The session's facts: kept from an earlier event, else gathered and kept.74 * A claim, once found, holds for the session, so `pre-tool-use` never asks75 * the platform again. Without one, `session-start` and `stop` look again76 * (once a turn), so a claim the agent takes mid-session is found at the end77 * of that turn; `pre-tool-use` never does, so an edit never waits on the78 * network.79 */54/** `pre-tool-use` never asks the platform, so an edit never waits on the network. */55const sessionFacts = (event: HookEvent, input: HookInput) =>56 Effect.gen(function* () {57 const kept = yield* loadSession(input.session_id);58
14 unmodified lines
7374 return gathered;75 });76102/** Stop asks the local check, from the claim's base; nothing else does, and only with a claim. */77const refusalsFor = (event: HookEvent, state: SessionState) => {78 const { claim } = state;7980 return event === "stop" && claim !== undefined81 ? Effect.flatMap(pushCheck, (check) => check.run(state.root, claim.base))82 : Effect.succeed([]);83};84111/** Answers one event: the decision's JSON, with its note on stderr. */85const answer = (event: HookEvent, input: HookInput) =>86 Effect.gen(function* () {87 const output = yield* Output;88 const state = yield* sessionFacts(event, input);
40 unmodified lines
129130 return decision.output;131 });132160/** The answer on stdout: one line of JSON, or indented for a person. */133const print = (json: boolean, output: HookOutput) =>134 Console.log(json ? JSON.stringify(output) : JSON.stringify(output, null, 2));135164/** Says why the hook allows, on stderr, and lets the harness go on. */136const failOpen = (json: boolean, why: string) =>137 Effect.andThen(138 Output.use((output) => output.note(`hook: ${why}; allowing`)),139 print(json, {})
54 unmodified lines
modified:apps/cli/src/main.ts+3 added-50 removed
1/**2 * The CLI's command tree and the program that runs it. `bin.ts` runs3 * `program` with the real services (`CliServices`); tests run it, or `root`,4 * with theirs.5 */1import { Brand } from "@repo/brand";2import { ApprovalNeeded, MissingValue, Reported } from "@repo/protocol/cli";3import { ExitCode } from "@repo/protocol/exit-code";4import { Unauthenticated } from "@repo/protocol/principal";
15 unmodified lines
20} from "./remote.ts";21import { commands, mcp, UnknownCommand } from "./surfaces.ts";22import { cliVersion } from "./version.ts";2329/**30 * The three commands that start any contribution, first in `--help`, so a31 * person or an agent who knows nothing else knows where to begin.32 */24export const banner = [25 "Start here:",26 ` ${Brand.cli} asks list the open asks you could take`,27 ` ${Brand.cli} claim take one; you get a fork to push your answer to`,28 ` ${Brand.cli} check run the gate's checks locally before you push`,29].join("\n");3040/** The commands at the top: the contracts and the hand-written ones, then the servers. */31const tree = [...commands, mcp, hook, credential];3233export const root = Command.make(Brand.cli).pipe(34 Command.withDescription(banner),35 Command.withSubcommands(tree)36);3748/** The exit code of a usage error, as for a command line effect/cli can't parse. */38const USAGE = ExitCode.usage;3951/**52 * The command was misused and said so in one line on stderr: the program53 * exits 2 and prints nothing more.54 */40export class Misused extends Schema.TaggedError<Misused>()("Misused", {}) {41 override readonly [Runtime.errorExitCode] = USAGE;42 override readonly [Runtime.errorReported] = false;43}
3 unmodified lines
47const isReported = Schema.is(Reported);4849const isUnauthenticated = Schema.is(Unauthenticated);5066/** Usage errors this CLI shares across its commands, beside effect/cli's. */51const isSharedUsage = Schema.is(52 Schema.Union([ApprovalNeeded, MissingValue, UnknownCommand])53);5471/** What to run when the platform does not know who is calling. */55const signIn = [56 "Unauthenticated: the platform does not know who you are",57 ` next: ${Brand.cli} login`,58 " retryable: no",59].join("\n");6078/** How running the tree can fail. */61type Failure = Command.Error<typeof root> | CliError.CliError;6281/**82 * Whether a failure is a usage error: a shared one, or one a command marks83 * with exit code 2 (`init`'s `InitMisused`).84 */63const isUsage = (failure: Failure) =>64 isSharedUsage(failure) || Runtime.getErrorExitCode(failure) === USAGE;6588/** One line for a failure that is a misuse of the command; none otherwise. */66const usageLine = (failure: Failure): Option.Option<string> => {67 if (CliError.isCliError(failure)) {68 return Option.some(69 Schema.is(CliError.ShowHelp)(failure)
10 unmodified lines
80 ? Option.map(noPlatformOf(failure), ({ message }) => message)81 : Option.none();82};83107/** What to say on stderr about a failure nobody printed yet, and the code the process ends with. */84const noteFor = (failure: Failure) => {85 if (isUnauthenticated(failure)) {86 return { exitCode: ExitCode.noPerm, note: signIn };87 }
7 unmodified lines
9596 return { exitCode: ExitCode.failed, note: String(failure) };97};98123/** How a failure printed already ends: as it said, or with its refusal's code. */99const printed = (failure: Failure): Option.Option<Reported> => {100 if (isReported(failure)) {101 return Option.some(failure);102 }
2 unmodified lines
105 ? Option.some(Reported.of([failure]))106 : Option.none();107};108134/**135 * Says once what nobody printed yet, and how the process ends: a misuse in136 * one line on stderr (exit 2); not being signed in with what to run next137 * (77), a platform out of reach (69) and anything else (1), on stderr; a138 * refusal, or anything `Reported`, nothing more, with its own code.139 */109const settle = (110 failure: Failure111): Effect.Effect<never, Reported | Misused, Output> =>112 Option.match(usageLine(failure), {
13 unmodified lines
126 Effect.andThen(Effect.fail(new Misused()))127 ),128 });129161/** Whether a run ended in a misuse effect/cli found: a parse error. */130const isMisuse = (failure: Failure) =>131 Schema.is(CliError.ShowHelp)(failure) && failure.errors.length > 0;132165/**166 * effect/cli's built-in flags for `mode`: the wizard prompts, so only a167 * person at a terminal gets it.168 */133/** The wizard prompts, so only a person at a terminal gets it. */134const builtInsFor = (policy: Option.Option<Policy["Service"]>) =>135 Option.exists(policy, ({ mode }) => mode !== "human")136 ? GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Wizard)137 : GlobalFlag.BuiltIns;138139/**175 * Runs the command `argv` names. Help asked for, or shown for a group run176 * without a subcommand, is a success. A misuse (a parse error, a missing177 * value, `--yes` left out, any failure whose `Runtime.errorExitCode` is 2)178 * ends as `Misused` (exit 2) after one line on stderr; every other failure179 * ends as `Reported`, printed once: a refusal by the command, with its180 * exit code (`exitCodeFor`), anything else here (`settle`). A defect (a stub's "not built") is not caught: the181 * runtime prints it, loudly. `env set`'s words are screened before182 * effect/cli parses them, so a value typed where a flag goes is never183 * printed back.140 * A defect is not caught: the runtime prints it. `env set`'s words are screened141 * before effect/cli parses them, so a value typed where a flag goes is never printed back.142 */143export const program = (argv: readonly string[]) =>144 Effect.gen(function* () {145 yield* refuseStrangeFlags(argv);
28 unmodified lines
174 onSuccess: () => Effect.void,175 })176 );177220/**221 * What `program` runs on in a real process, beside the host's own services222 * (`BunServices`): the stored credentials, the invocation policy, output in223 * its form, and the platform over HTTP as the stored profile.224 */178export const CliServices = Layer.mergeAll(OutputLive, RemoteClient).pipe(179 Layer.provideMerge(Layer.mergeAll(CurrentMode, CredentialsFile))180);
modified:apps/cli/src/output.ts+2 added-33 removed
1/**2 * The one way every command prints. A command hands its result, its3 * refusals or its plan to `Output`, which decides the form: text for a4 * person, Markdown for an agent or a script, one `--json` envelope when asked5 * for. Notes go to stderr only, so `--json` stdout is always exactly one6 * document.7 */1// Notes go to stderr only, so `--json` stdout is always exactly one document.2import type { View } from "@repo/protocol/cli";3import { Envelope } from "@repo/protocol/envelope";4import type { Refusal } from "@repo/protocol/refusal";5import { explain } from "@repo/protocol/render";
12 unmodified lines
18export class Output extends Context.Service<19 Output,20 {21 readonly mode: Mode;28 /** A command's result; `data` is its encoded success. */22 readonly success: (input: {23 readonly command: string;24 readonly json: boolean;25 readonly data: unknown;26 readonly view: View;27 }) => Effect.Effect<void>;35 /** The refusals a command met instead: printed here, and only here. */28 readonly refused: (input: {29 readonly command: string;30 readonly json: boolean;31 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;32 }) => Effect.Effect<void>;41 /** What `--dry-run` would send; `payload` is encoded. */33 readonly plan: (input: {34 readonly command: string;35 readonly json: boolean;36 readonly payload: unknown;37 }) => Effect.Effect<void>;47 /** A line for whoever watches stderr; never part of `--json` output. */38 readonly note: (text: string) => Effect.Effect<void>;39 }40>()("cli/Output") {}4152/** Any envelope's JSON: its data is already encoded. */42const encodeEnvelope = Schema.encodeEffect(43 Schema.fromJsonString(Envelope(Schema.Unknown))44);4557/** One envelope, as the one document on stdout. */46const printEnvelope = (envelope: Envelope<unknown>) =>47 encodeEnvelope(envelope).pipe(Effect.orDie, Effect.flatMap(Console.log));4849const capitalized = (word: string) =>50 `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`;5164/**65 * `explain`'s lines as a Markdown list: one item per refusal, its pointer,66 * next command and `Retryable: yes|no` beneath it. The renderer stays the67 * one source of the words; only the layout changes.68 */52const asMarkdownList = (lines: readonly string[]) =>53 lines.map((line) => {54 const detail = /^ {2}(?<key>[a-z]+): (?<value>.*)$/u.exec(line)?.groups;55
5 unmodified lines
6162 return ` - ${capitalized(detail.key)}: ${value}`;63 });6482/** The JSON a plan sends, as a person reads it or as a Markdown block. */65const planText = (mode: Mode, command: string, json: string) =>66 mode === "human"67 ? `${command} would send this, and sent nothing:\n${json}`68 : [
3 unmodified lines
72 json,73 "```",74 ].join("\n");7594/**95 * Output for `mode`: a person reads `view.text` (or the Markdown when a view96 * has no text) and refusals as `explain`'s lines; an agent or a script97 * reads Markdown, with refusals as a Markdown list. Under `--json` stdout98 * holds one `Envelope` and nothing else, refusals included.99 */76const outputFor = (mode: Mode): Output["Service"] => ({77 mode,78 note: (text) => Console.error(text),79 plan: ({ command, json, payload }) =>
26 unmodified lines
106 );107 },108});109134/** Output for a person, whatever the process: what tests of a command's text use. */110export const OutputPlain = Layer.succeed(Output)(outputFor("human"));111137/** Output in the form the invocation policy chose for this process. */112export const OutputLive: Layer.Layer<Output, never, Policy> = Layer.effect(113 Output114)(Effect.map(Effect.service(Policy), ({ mode }) => outputFor(mode)));115142/**143 * Stdout held back until a command's handler runs. effect/cli prints help on144 * stdout for a misuse too: held, that help is dropped after a misuse (whose145 * one line goes to stderr), and printed when the run ends any other way146 * (help asked for, the version, a group run bare).147 */116/** effect/cli prints help on stdout for a misuse too: held, it is dropped after a misuse and printed otherwise. */117export const holdStdout = (real: Console.Console) => {118 const held: (readonly unknown[])[] = [];119 let open = false;120
77 unmodified lines
modified:apps/cli/src/pi.ts+7 added-106 removed
1/**2 * The pi adapter: what `pi install npm:<package>` loads, at user level,3 * through the published package's `"pi"` key (`dist/pi.js`), never from a4 * project's `.pi/extensions/` (a stranger's repo runs no code in your5 * harness). It is thin: three pi events, each answered by the one hook6 * policy behind `<cli> hook` (`./hook/decide.ts`), through `PiDeps`.7 */1// Loaded at user level through the package's "pi" key, never from a project's `.pi/extensions/`: a stranger's repo runs no code in your harness.2import type {3 AgentBeforeSettleEvent,4 AgentBeforeSettleEventResult,5 BeforeAgentStartEvent,
38 unmodified lines
44import { loadSession, saveSession } from "./hook/session.ts";45import type { SessionState } from "./hook/session.ts";46import { RemoteClient } from "./remote.ts";4754/** The policy could not answer; the adapter allows, and says why. */48export class HookFailed extends Schema.TaggedError<HookFailed>()("HookFailed", {49 reason: Schema.String,50}) {51 override get message() {52 return `the hook policy gave no answer: ${this.reason}`;53 }54}5563/** One pi session: its id, and the folder its agent runs in. */56export interface PiSession {57 readonly cwd: string;58 readonly id: string;59}6069/** A tool call the policy judges before it runs, read from pi's own. */61export type GuardedCall =71 /** pi's `edit` or `write`: the file it is about to change, as the tool names it. */62 | { readonly _tag: "Write"; readonly file: string }73 /** pi's `bash`, running `git push`. */63 | { readonly _tag: "Push" };6465export const GuardedCall = Data.taggedEnum<GuardedCall>();6678/** Where the session's answer stands when its agent is about to stop. */67export type SettleVerdict =68 | { readonly _tag: "Landed" }69 | { readonly _tag: "Waiting" }70 | {71 readonly _tag: "Refused";72 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;85 /** Whether the agent can act on them now (the policy's call). */73 readonly actionable: boolean;74 };7576export const SettleVerdict = Data.taggedEnum<SettleVerdict>();7791/** The boundary to the hook policy: what the adapter asks it, per session. */78export interface PiDeps {93 /** The claim's brief for the session's repo; none without a claim. */79 readonly brief: (80 session: PiSession81 ) => Effect.Effect<Option.Option<string>, HookFailed>;97 /** What the gate would refuse of the call; none when it would pass. */82 readonly guardTool: (83 session: PiSession,84 call: GuardedCall85 ) => Effect.Effect<
4 unmodified lines
90 session: PiSession91 ) => Effect.Effect<SettleVerdict, HookFailed>;92}93110/** What the adapter reads of a handler's context. */94export type PiContext = Pick<ExtensionContext, "cwd"> & {95 readonly sessionManager: Pick<96 ExtensionContext["sessionManager"],97 "getSessionId"98 >;99 readonly ui?: Pick<ExtensionUIContext, "notify">;100};101119/** The adapter's handlers, by pi event, as pi 1.0.3 types each event. */102export interface PiHandlers {103 readonly agent_before_settle: (104 event: AgentBeforeSettleEvent,105 ctx: PiContext
7 unmodified lines
113 ctx: PiContext114 ) => Promise<ToolCallEventResult | undefined>;115}116135/** The part of pi's `ExtensionAPI` the adapter uses: `on`, for three events. */117export interface PiEvents {118 readonly on: {119 (120 event: "agent_before_settle",
7 unmodified lines
128 };129}130131export interface PiOptions {151 /**152 * The most times one session is sent back to work: the hook policy's153 * `MAX_HOLDS` (3) unless given. pi has no cap of its own.154 */132 readonly maxContinuations?: number;133}134158/** The custom type of the brief pi shows before the agent starts. */135const BRIEF = `${Brand.slug}-brief`;136161/** The custom type of the verdict a settle sends the agent back with. */137const VERDICT = `${Brand.slug}-verdict`;138164/** What the agent reads when it is sent back: why, then the gateway's own text. */139const verdictEntry = (140 refusals: Array.NonEmptyReadonlyArray<Refusal>141): CustomMessageEntryDraft => ({142 content: [
4 unmodified lines
147 display: true,148 type: "custom_message",149});150177/** pi's `edit` and `write` name the file they change as `path`. */151const decodeFile = Schema.decodeUnknownOption(152 Schema.Struct({ path: Schema.String })153);154182/** pi's `bash` runs `command`. */155const decodeCommand = Schema.decodeUnknownOption(156 Schema.Struct({ command: Schema.String })157);158187/**188 * git running `push`, wherever it starts in the command line and after any189 * of git's own options: `git push`, `cd a && git push`, `git -C dir push`.190 * A false match only runs the preflight, which blocks nothing a real push191 * would not be refused.192 */159/** Matches a push after any git options; a false match only runs the preflight. */160const GIT_PUSH =161 /(?:^|[\s;&|(`])git(?:\s+-[Cc]\s+\S+|\s+-\S+)*\s+push(?![\w-])/u;162196/**197 * The call the policy judges, read from pi's tool call at the boundary:198 * `edit` and `write` change a file, and `bash` may push. Every other call199 * runs unjudged. The adapter never changes a call, only blocks one.200 */163const guardedCall = (event: ToolCallEvent): Option.Option<GuardedCall> =>164 Match.value(event.toolName).pipe(165 Match.when(Match.is("edit", "write"), () =>166 Option.map(decodeFile(event.input), ({ path }) =>
7 unmodified lines
174 ),175 Match.orElse(() => Option.none())176 );177216/**217 * The refusals retrying cannot help: the ones the agent must fix. A218 * retryable refusal is a wait (the repo was busy), as the stop hook reads it.219 */178const fixable = (refusals: readonly Refusal[]) =>179 refusals.filter((refusal) => !refusal.retryable);180223/**224 * pi's block for what the gate would refuse that retrying cannot help, with225 * the gateway's own text; a retryable refusal is a wait, never a block.226 */181const blockFor = (182 refusals: Option.Option<Array.NonEmptyReadonlyArray<Refusal>>183): Option.Option<ToolCallEventResult> => {184 const final = fixable(Option.getOrElse(refusals, () => []));
2 unmodified lines
187 ? Option.some({ block: true, reason: explain(final).join("\n") })188 : Option.none();189};190237/**238 * What a verdict tells the agent to act on: the refusals it can fix, as the239 * stop hook's hold names them, or every refusal when the policy holds on240 * retryable ones alone.241 */191const toActOn = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>192 Array.match(fixable(refusals), {193 onEmpty: () => refusals,194 onNonEmpty: (final) => final,195 });196248/** The session a handler runs in. */197const sessionOf = (ctx: PiContext): PiSession => ({198 cwd: ctx.cwd,199 id: ctx.sessionManager.getSessionId(),200});201254/** A failure's first line, for the note. */202const firstLine = (cause: Cause.Cause<unknown>) =>203 String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";204258/**259 * Runs one handler's reply for pi, which awaits a promise. The gate stays260 * the authority, so a policy that fails, or any defect, lets pi go on as it261 * would without the adapter (a `tool_call` handler that rejects would block262 * the tool), and says why through `ctx.ui.notify` when pi gives one.263 */205/** A rejecting `tool_call` handler would block the tool, so a failing policy or defect lets pi go on. */206const reply = <A>(207 ctx: PiContext,208 event: keyof PiHandlers,209 decided: Effect.Effect<Option.Option<A>, HookFailed>
14 unmodified lines
224 Effect.map(Option.getOrUndefined)225 )226 );227286/**287 * The adapter over `deps`: registers its three handlers on `pi`, and no288 * other event or tool. Each pi load counts its own continuations, by289 * session, so no state outlives the extension.290 */228export const piAdapter =229 (deps: PiDeps, options: PiOptions = {}) =>230 (pi: PiEvents): void => {231 const most = options.maxContinuations ?? MAX_HOLDS;232 const continued = new Map<string, number>();233 const briefed = new Set<string>();234298 // pi starts the agent on every prompt; the brief stays in the session,299 // so each session gets it once, at its first prompt with a claim.235 // pi starts the agent on every prompt; each session gets the brief once.236 pi.on("before_agent_start", (_event, ctx) => {237 const session = sessionOf(ctx);238239 return reply(
29 unmodified lines
269 })270 )271 );272337 // Only a verdict the agent can act on sends it back, at most `most`338 // times a session, and only a run that completed: a run the person339 // stopped, or one that failed, stays stopped. Otherwise the policy is340 // not even asked. `event.context.canContinue` is no guide: pi computes341 // it before this handler's entry, and a run that ends on the agent's own342 // reply reads false until the verdict is appended.273 // Only a completed run with an actionable verdict is sent back, at most `most` times.274 // `event.context.canContinue` is no guide: pi computes it before this handler's entry.275 pi.on("agent_before_settle", (event, ctx) => {276 const session = sessionOf(ctx);277 const used = continued.get(session.id) ?? 0;278
20 unmodified lines
299 );300 });301 };302371// ------------------------------------------------------------ live372373/**374 * The session's facts, kept in the hook's own session file under pi's375 * session id: gathered once, and again by the brief and the settle376 * (`look`) while they hold no claim, so a claim taken mid-session is found377 * at the next prompt or stop, and a tool call never waits on the platform.378 * As `<cli> hook` keeps them (its `sessionFacts`).379 */303const factsOf = (session: PiSession, look: boolean) =>304 Effect.gen(function* () {305 const kept = yield* loadSession(session.id);306
8 unmodified lines
315316 return gathered;317 });318396/**397 * What the policy decides over. Holds are 0: the adapter counts pi's398 * continuations itself, so the policy only says whether a stop would hold.399 */319/** Holds are 0: the adapter counts pi's continuations itself. */320const hookFacts = (321 state: SessionState,322 refusals: readonly Refusal[]323): HookFacts => ({
3 unmodified lines
327 refusals,328 root: state.root,329});330411/** The policy's input for `event`, in the hook format it reads. */331const hookInput = (event: HookEvent, session: PiSession): HookInput => ({332 cwd: session.cwd,333 hook_event_name: claudeEventOf[event],334 session_id: session.id,335});336418/**419 * What `<cli> check --shape-only` refuses of the work as it stands, from the420 * claim's base, by the policy's own `PushCheck`; nothing is asked without a421 * claim.422 */337const localCheck = ({ claim, root }: SessionState) =>338 claim === undefined339 ? Effect.succeed<readonly Refusal[]>([])340 : Effect.flatMap(Effect.service(PushCheck), (check) =>341 check.run(root, claim.base)342 );343430/** What the hook policy runs on. */344export type PolicyServices =345 | ChildProcessSpawner.ChildProcessSpawner346 | Client347 | FileSystem.FileSystem348 | Path.Path349 | PushCheck;350438/** The hook policy, in process, as `PiDeps`, over `services`. */351export const policyDeps = (services: Layer.Layer<PolicyServices>): PiDeps => ({352 brief: (session) =>353 Effect.gen(function* () {354 const state = yield* factsOf(session, true);
24 unmodified lines
379 (failed) => new HookFailed({ reason: failed.message })380 ),381 Effect.provide(services)382 ),471 // An edit is judged as the hook's pre-tool-use judges one, from the472 // kept facts alone: no check runs and the platform is never asked.383 Write: ({ file }) =>384 Effect.map(factsOf(session, false), (state) =>385 Array.match(386 toolRefusals(
26 unmodified lines
413 hookInput("stop", session),414 hookFacts(state, refusals)415 );416507 // The policy holds a stop on a refusal the agent can fix.417 return SettleVerdict.Refused({418 actionable: "decision" in output,419 refusals,420 });
2 unmodified lines
423 Effect.provide(services)424 ),425});426518/**519 * The policy's services in pi's process: the stored credentials and the520 * platform over HTTP, and the local check run as the CLI on `PATH` (the521 * same package's bin, where git finds its credential helper too). Node's522 * own file system, paths and processes, which Bun's layers are.523 */427const LiveServices = Layer.mergeAll(428 RemoteClient.pipe(Layer.provide(CredentialsFile)),429 pushCheckWith([Brand.cli])430).pipe(431 Layer.provideMerge(BunChildProcessSpawner.layer),432 Layer.provideMerge(Layer.mergeAll(BunFileSystem.layer, BunPath.layer))433);434532/** The hook policy as pi's process runs it. */435export const livePiDeps = policyDeps(LiveServices);436535/** What `pi install npm:<package>` loads: the adapter over the live policy. */437export default piAdapter(livePiDeps) satisfies ExtensionFactory;
modified:apps/cli/src/policy.ts+2 added-27 removed
1/**2 * The CLI's invocation policy: who is reading what it prints. Under a3 * harness the CLI never prompts and prints Markdown; for a script (CI, or4 * stdout piped) it never prompts either; only a person at a terminal reads5 * plain text. Read once per process.6 */1import { detectHarness } from "@repo/protocol/audit";2import { ConfigProvider, Context, Effect, Layer, Option, Stdio } from "effect";310/** Who is reading: a person at a terminal, an agent, or a script. */4export type Mode = "human" | "agent" | "automation";513/** Who is reading, the harness when an agent is, and why the CLI thinks so. */6export interface Invocation {7 readonly mode: Mode;8 readonly harness: Option.Option<string>;9 readonly reason: string;10}1120/** What the mode is read from. */12export interface Surroundings {13 readonly env: Readonly<Record<string, string | undefined>>;14 readonly isTTY: boolean;15}1626/** `value`, unless it is absent or empty. */17const isSet = (value: string | undefined) =>18 value !== undefined && value !== "";1930/**31 * An agent when the env names a harness (`detectHarness`, the one table of32 * harness markers); else a script when `CI` is set or stdout is not a33 * terminal; else a person.34 */20export const detectMode = ({ env, isTTY }: Surroundings): Invocation => {21 const harness = Option.fromNullishOr(detectHarness(env).harness);2223 if (Option.isSome(harness)) {
12 unmodified lines
36 ? { harness, mode: "human", reason: "stdout is a terminal" }37 : { harness, mode: "automation", reason: "stdout is not a terminal" };38};3955/** Who is reading this process's output. */40export class Policy extends Context.Service<Policy, Invocation>()(41 "cli/Policy"42) {}4360/** The policy for given surroundings: what tests run the CLI under. */44export const policyFor = (surroundings: Surroundings): Layer.Layer<Policy> =>45 Layer.succeed(Policy)(detectMode(surroundings));4664/** The names below a node of the env's tree: a record's keys, an array's indexes. */47const childrenOf = (node: ConfigProvider.Node): readonly string[] => {48 if ("keys" in node) {49 return [...node.keys];50 }
4 unmodified lines
5556 return [];57};5877/**78 * Every variable the env provider holds, by its full name. The provider79 * splits names on `_` into a tree, so this walks it back together.80 */59/** The provider splits names on `_` into a tree, so this walks it back together. */60const envOf = (provider: ConfigProvider.ConfigProvider) => {61 const walk = (62 path: readonly string[]63 ): Effect.Effect<
18 unmodified lines
8283 return Effect.map(walk([]), (entries) => Object.fromEntries(entries));84};85107/**108 * The policy of this process: its env, read through the config provider,109 * and whether stdout is a terminal. An env that cannot be read reads as110 * empty, so the mode then rests on the terminal alone.111 */86/** An env that cannot be read reads as empty, so the mode then rests on the terminal alone. */87export const CurrentMode: Layer.Layer<Policy, never, Stdio.Stdio> =88 Layer.effect(Policy)(89 Effect.gen(function* () {90 const provider = yield* ConfigProvider.ConfigProvider;
10 unmodified lines
modified:apps/cli/src/remote.ts+3 added-33 removed
1/**2 * The platform as the CLI calls it: the contracts over HTTP at `/rpc`, as3 * the stored profile. The token rides as the HTTP `authorization` header,4 * which the platform merges into every call's headers (Rpc headers would5 * ride in the body, where the gate never looks).6 */1// The token rides as the HTTP `authorization` header: Rpc headers would ride in the body, where the gate never looks.2import { Brand } from "@repo/brand";3import { Client, Contracts } from "@repo/protocol/contracts";4import { Authenticated, Unauthenticated } from "@repo/protocol/principal";5import {
19 unmodified lines
25} from "effect/rpc";2627import { Credentials } from "./credentials.ts";2834/** `<SLUG>_URL`: a platform to call as anyone, when no profile names one. */29const URL_VARIABLE = `${Brand.slug.toUpperCase()}_URL`;3037/**38 * No profile names a platform, and the env names none either. A usage39 * error: nothing was called.40 */31export class NoPlatform extends Schema.TaggedError<NoPlatform>()("NoPlatform", {32 variable: Schema.String,33}) {34 override get message() {
8 unmodified lines
43const isNoPlatformError = Schema.is(NoPlatform);4445const isHttpFailure = Schema.is(HttpClientError.HttpClientErrorSchema);4657/** Whether a call failed in transit (not by the contract's own errors). */47export const isTransportFailure = isClientError;4860/**61 * What failed in transit, in words. An HTTP failure's own message is empty:62 * its cause (the transport error, or the status and URL) says what failed.63 */49/** An HTTP failure's own message is empty: its cause says what failed. */50export const transportMessage = (failure: RpcClientError.RpcClientError) =>51 isHttpFailure(failure.reason) &&52 Predicate.hasProperty(failure.reason.cause, "message") &&53 Predicate.isString(failure.reason.cause.message)54 ? failure.reason.cause.message55 : failure.message;5671/** The usage error a call failed with because no platform was there to call. */57export const noPlatformOf = (58 failure: RpcClientError.RpcClientError59): Option.Option<NoPlatform> =>60 isDefect(failure.reason) && isNoPlatformError(failure.reason.cause)61 ? Option.some(failure.reason.cause)62 : Option.none();6379/** Whether the platform's HTTP gate answered a call with a 401. */64const isUnauthorized = (failure: RpcClientError.RpcClientError) =>65 Predicate.hasProperty(failure.reason, "cause") &&66 failure.reason.cause instanceof HttpClientError.StatusCodeError &&67 failure.reason.cause.response.status === 401;6885/**86 * The client side of `Authenticated`: a 401 from the platform's gate (a87 * token it doesn't know) is the same `Unauthenticated` a contract gives a88 * call without one, so the CLI says the same thing for both.89 */69/** A 401 from the platform's gate is the same `Unauthenticated` a contract gives a call without a token. */70const SignedIn = RpcMiddleware.layerClient(Authenticated, ({ next, request }) =>71 next(request).pipe(72 Effect.catchIf(73 (failure) => isClientError(failure) && isUnauthorized(failure),
1 unmodified line
75 )76 )77);7899/** The contracts at `origin`, with `token` as the bearer when there is one. */79const over = (origin: string, token: Option.Option<Redacted.Redacted>) =>80 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(81 Layer.provide(SignedIn),82 Layer.provide(
27 unmodified lines
110 );111112const noPlatform = new NoPlatform({ variable: URL_VARIABLE });113135/**136 * No platform: every call fails, before anything is sent, with a usage error137 * naming `login`. Commands that call nothing (help among them) still run.138 */114const nowhere = Layer.effect(Client)(RpcClient.make(Contracts)).pipe(115 Layer.provide(116 Layer.effect(RpcClient.Protocol)(117 Effect.flatMap(
20 unmodified lines
138 ),139 Layer.provide(RpcSerialization.layerJson)140);141167/**168 * The platform the stored profile names, as that person; else the one169 * `<SLUG>_URL` names, as anyone (public contracts answer; the rest come back170 * `Unauthenticated`); else nowhere.171 */142export const RemoteClient: Layer.Layer<Client, never, Credentials> =143 Layer.unwrap(144 Effect.gen(function* () {145 const profile = yield* Effect.flatMap(
18 unmodified lines
modified:apps/cli/src/render.ts+3 added-45 removed
1/**2 * The CLI's prose for the contracts' results: Markdown for an agent (and a3 * script), and plain text for a person where a table reads better padded.4 * A contract without a view here prints its encoded JSON in a fenced block.5 */1import { IMPORTED_NOTE } from "@repo/agent-kit/docs/imported-note";2import { Brand } from "@repo/brand";3import type { View } from "@repo/protocol/cli";4import {
32 unmodified lines
37const when = (at: DateTime.Utc) => DateTime.formatIso(at);3839const yesNo = (value: boolean) => (value ? "yes" : "no");4046/** A cell's text, safe inside a Markdown table row. */41const cell = (text: string) =>42 text.replaceAll("|", "\\|").replaceAll(/\s*\n\s*/gu, " ");4350/** `text` as a Markdown code span, fenced by one more backtick than its longest run. */44const codeSpan = (text: string) => {45 const longest = Math.max(46 0,47 ...(text.match(/`+/gu) ?? []).map((run) => run.length)
4 unmodified lines
5253 return `${fence}${pad}${text}${pad}${fence}`;54};5563/**64 * Rows as a Markdown table, and as a padded plain table for a person.65 * `empty` stands in for both when there are no rows. The columns in `code`66 * hold literal text (a glob, a path) that Markdown shows as code, so `**`67 * never reads as emphasis; the plain table shows it as it is.68 */56/** Columns in `code` hold literal text (a glob, a path), shown as code so `**` never reads as emphasis. */57const table = (58 headers: readonly string[],59 rows: readonly (readonly string[])[],60 empty: string,
32 unmodified lines
93 ].join("\n"),94 };95};96109/** Labelled values, one a line: a Markdown list, and padded for a person. */97const fields = (rows: readonly (readonly [string, string])[]): View => {98 const width = Math.max(0, ...rows.map(([label]) => label.length));99100 return {
3 unmodified lines
104 .join("\n"),105 };106};107121/** Views one after another, as sections. */108const joined = (...parts: readonly View[]): View => ({109 markdown: parts.map(({ markdown }) => markdown).join("\n\n"),110 text: parts.map(({ markdown, text }) => text ?? markdown).join("\n\n"),111});112127/** The same words for every reader. */113const prose = (text: string): View => ({ markdown: text });114130/** Where an answer stands, in a few words. */115const outcomeText = (outcome: Outcome) =>116 Outcome.match(outcome, {117 AwaitingDecision: ({ decision }) => `waits on decision ${decision}`,118 AwaitingFinish: () => "passed; waits for a decider's finish",
3 unmodified lines
122 `refused: ${refusals.map((refusal) => refusal._tag).join(", ")}`,123 WaitingOnParent: ({ ask }) => `passed; waits for ${ask} to land`,124 });125142/** What a decision is about, in a few words. */126const subjectText = (subject: DecisionSubject) =>127 DecisionSubject.match(subject, {128 Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,129 OpenProposal: ({ proposal }) =>
11 unmodified lines
141 Waiver: ({ at, marker, reason }) =>142 `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,143 });144162/** One ledger entry, in a few words. */145const entryText = (entry: LedgerEntry) =>146 LedgerEntry.match(entry, {147 Admitted: ({ area, knownBadCaught, mainRuns, suite }) =>148 `held-back suite ${suite} admitted in ${area} after ${mainRuns} runs on main, catching ${knownBadCaught} known-bad trees`,
9 unmodified lines
158 `${by} released ${paths} paths from ${layer} in ${short(landing)}`,159 ValueSet: ({ by, key }) => `${by} set the write-only value of ${key}`,160 });161180/** A view that renders a success it can read, and none for anything else. */162const viewOf = <S extends Schema.Top>(163 schema: S,164 render: (success: S["Type"]) => View165) => {
150 unmodified lines
316317const plural = (count: number, one: string, many: string) =>318 `${count} ${count === 1 ? one : many}`;319339/** How many a vouch file names, as the people page says none: "nobody". */320const countOf = (count: number) => (count === 0 ? "nobody" : `${count}`);321322const HOUR_MS = 3_600_000;323344/** A claim timing as the people page says it: whole hours up to two days, then days. */324const spanOf = (ms: number) => {325 if (ms % HOUR_MS !== 0) {326 return plural(Math.round(ms / 60_000), "minute", "minutes");327 }
4 unmodified lines
332 ? plural(hours / 24, "day", "days")333 : plural(hours, "hour", "hours");334};335357/** The config folder's `project.ts`. */336const PROJECT_FILE = `${Brand.configDir}/project.ts`;337360/** What a vouch gates, in the people page's words. */338const vouchModes = {339 all: "For everything: claiming an ask, offering a sealed answer and proposing an ask all need a vouch.",340 bansOnly:341 "Bans only: nobody needs a vouch, but a denounced person still may not claim, push or propose.",342 forCode:343 "For code: claiming an ask or offering a sealed answer needs a vouch; anyone not denounced may propose an ask.",344} as const satisfies Record<PublicPolicy["vouch"]["mode"], string>;345369/** A policy at its landed commit, section by section, as the people page shows it. */346const evaluated = (policy: PublicPolicy) => {347 const { agents, budget, caps, claims, record, vouch, vouches } = policy;348 const denounced = vouches.filter((line) => line.denounced).length;349
49 unmodified lines
399 )400 );401};402427/**428 * Why the config at the landed commit has not evaluated, and the step that429 * makes it, as a terminal's lines. The view sees only the success, which430 * names no project, so the command names it as `<owner>/<name>`.431 */403/** The view sees only the success, which names no project, so the command names it as `<owner>/<name>`. */404const pendingText = ({ at, reason }: PolicyPending) => {405 const notEvaluated = `The config at the landed commit ${short(at)} has not been evaluated`;406407 return reason === "noConfig"
6 unmodified lines
414 `Fix it by landing a change to ${Brand.configDir}/; it is evaluated again at every landing.`,415 ];416};417446/** Where an imported project came from, and what a copy is (ADR 0031). */418const importedText = ({ branch, url }: ImportSource) =>419 prose(420 `Imported from ${url}${branch === undefined ? "" : ` (branch ${branch})`}: this project is ${IMPORTED_NOTE}.`421 );422452/** The policy's own view: evaluated, why not yet, or nothing landed. */423const policyText = (read: typeof PolicyOf.successSchema.Type): View => {424 if (read.policy !== undefined) {425 return evaluated(read.policy);426 }
69 unmodified lines
496 "No open asks anywhere."497 )498);499530/**531 * Where an offered answer stands, in the line git's `remote:` output gives a532 * push of the same answer. A refused one never reaches its view: its533 * refusals print as refusals (`refusalsIn`).534 */500const receipt = (offered: AnswerReceipt) =>501 prose(502 Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)503 );
1 unmodified line
505const submitted = viewOf(SubmitAnswer.successSchema, receipt);506507const finished = viewOf(Finish.successSchema, receipt);508544/** Any receipt: an answer's (`submit`, `finish`) has a landing's fields too. */509const isReceipt = Schema.is(LandReceipt);510547/**548 * The refusals a contract's success carries in place of a result: a refused549 * receipt's (`finish` and `land` refuse at stages 0–1 that way, and `submit`550 * gives a refused request's receipt back again). The command prints them as551 * refusals, once, and exits 1.552 */511/** `finish` and `land` refuse stages 0–1 inside a success's receipt; the command prints them as refusals and exits 1. */512export const refusalsIn = (513 success: Rpc.Success<Contract>514): readonly Refusal[] =>515 isReceipt(success) && Outcome.guards.Refused(success.outcome)516 ? success.outcome.refusals517 : [];518560/** Each contract's view, by tag. */519export const views = {520 claim,521 credits,522 finish: finished,
18 unmodified lines
modified:apps/cli/src/repo-context.ts+1 added-39 removed
1/**2 * The repo the CLI stands in: its root, the remote that reaches a platform,3 * and what that remote's repo name says it is. Read once per4 * command, from git itself.5 */1import { AskId, Handle, LayerName, ProjectName } from "@repo/protocol/ids";2import { Array, Effect, Option, Schema, Stream } from "effect";3import { ChildProcess, ChildProcessSpawner } from "effect/process";45import { Credentials } from "./credentials.ts";612/** What a repo is: a project's own, a claim's fork, a person's working fork, or a layer's. */7export type RepoKind = "canonical" | "claim" | "working" | "layer";815/** What a repo's name says, part by part. */9export interface RepoRef {10 readonly kind: RepoKind;11 readonly project: ProjectName;19 /** A claim's fork: the ask it answers. */12 readonly ask?: AskId;21 /** A claim's or a working fork: whose it is, in lowercase as the name spells it. */13 readonly handle?: Handle;23 /** A layer's repo: the layer. */14 readonly layer?: LayerName;15}1617const asProject = Schema.decodeOption(ProjectName);
1 unmodified line
19const asAsk = Schema.decodeOption(AskId);2021const asLayer = Schema.decodeOption(LayerName);2233/** A handle as a fork's name spells it: valid, and in lowercase. */23const asForkHandle = (part: string) =>24 Option.filter(25 Schema.decodeOption(Handle)(part),26 (handle) => handle === handle.toLowerCase()27 );2840/** The word a working fork has where a claim's fork has its ask. */29const WORKING = "me";3043/** What a three-part name `<project>--<second>--<third>` is. */31const forkOf = (32 project: ProjectName,33 second: string,34 third: string
8 unmodified lines
43 Option.all({ ask: asAsk(second), handle: asForkHandle(third) }),44 ({ ask, handle }): RepoRef => ({ ask, handle, kind: "claim", project })45 );4660/**61 * What a repo's address says it is: `<project>`, `<project>--<ask>--<handle>`,62 * `<project>--me--<handle>` or `<project>--<layer>`, where the project is its63 * name (`alice/datekit`, `github.com/pallets/click`) or a key a project kept64 * from before owners (`datekit`). `--` occurs in no name or ask, so an65 * address splits back into its parts; any other is none of the platform's.66 */47/** `--` occurs in no name or ask, so an address splits back into its parts. */48export const parseRepoName = (name: string): Option.Option<RepoRef> => {49 const slash = name.lastIndexOf("/");50 const [first = "", ...rest] = name.slice(slash + 1).split("--");51 const spelled = slash === -1 ? first : `${name.slice(0, slash)}/${first}`;
18 unmodified lines
70};7172const asUrl = Option.liftThrowable((url: string) => new URL(url));7393/** `url`'s scheme and host, if it is an HTTP(S) url. */74const webOrigin = (url: string) =>75 Option.map(76 Option.filter(asUrl(url), ({ protocol }) =>77 ["http:", "https:"].includes(protocol)
3 unmodified lines
81 pathname,82 })83 );84105/**106 * A remote url as a platform serves repos: `https://<host>/<address>.git`,107 * the address one to three path segments (a project's name, a fork's parts108 * on the last), over HTTP(S). The origin drops any user the url carries.109 */85export const parseRemote = (86 url: string87): Option.Option<{ readonly origin: string; readonly repo: string }> =>88 Option.flatMap(webOrigin(url), ({ origin, pathname }) => {
6 unmodified lines
95 ? Option.some({ origin, repo })96 : Option.none();97 });98124/** Where the CLI stands, as git sees it. */99export interface RepoContext {126 /** The work tree's top folder. */100 readonly root: string;128 /** The remote that reaches a platform: the signed-in one's, else `origin`. */101 readonly remote: Option.Option<{102 readonly name: string;103 readonly url: string;104 }>;133 /** That remote's platform origin, if its url is a platform's. */105 readonly origin: Option.Option<string>;135 /** What that remote's repo name says it is, if it is the platform's. */106 readonly repo: Option.Option<RepoRef>;107}108139/** `cwd` is in no git work tree. */109export class NotARepo extends Schema.TaggedError<NotARepo>()("NotARepo", {110 cwd: Schema.String,111}) {112 override get message() {
3 unmodified lines
116117const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>118 bytes.pipe(Stream.decodeText(), Stream.mkString);119151/** Runs git in `cwd` to the end: its stdout and exit code; stderr is dropped. */120const git = (cwd: string, args: readonly string[]) =>121 Effect.scoped(122 Effect.gen(function* () {123 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
14 unmodified lines
138 return { exitCode, stdout };139 })140 );141174/** `git remote -v`'s fetch urls, by remote, in git's order. */142const remotesOf = (listing: string) =>143 listing.split("\n").flatMap((line) => {144 const match = /^(?<name>\S+)\t(?<url>\S+) \(fetch\)$/u.exec(line);145
1 unmodified line
147 ? []148 : [{ name: match.groups.name, url: match.groups.url }];149 });150184/**185 * Reads the repo at `cwd`: `git rev-parse --show-toplevel`, then `git186 * remote -v`. The remote is the one on the signed-in platform's origin when187 * `Credentials` is there to say which, else `origin`.188 */151export const repoContext = (152 cwd: string153): Effect.Effect<154 RepoContext,
42 unmodified lines
modified:apps/cli/src/surfaces.ts+3 added-63 removed
1/**2 * The CLI's surfaces: every contract served on the CLI as a command, merged3 * with the hand-written ones by the words that reach them; `schema`, which4 * prints a command's payload as JSON Schema; and `mcp`, the contracts as5 * tools over stdio. The only place the CLI's projections are built.6 */1import { commandDocs } from "@repo/agent-kit/command-doc";2import { platformSkill } from "@repo/agent-kit/platform";3import { Brand } from "@repo/brand";4import { commandName, toCommands } from "@repo/protocol/cli";
32 unmodified lines
37import { repoContext } from "./repo-context.ts";38import { today } from "./tui/command.ts";39import { cliVersion } from "./version.ts";4047/** The folder the CLI stands in: the process's own, unless a test says otherwise. */41export const WorkingDirectory = Context.Reference<string>(42 "cli/WorkingDirectory",43 { defaultValue: () => "." }44);4553/**54 * The project a command is about when `--project` is left out: the one the55 * repo the CLI stands in belongs to, by its remote's name (a project's own56 * repo, a claim's fork or a working fork). None outside a platform's repo.57 */46export const fromRepoContext: Defaults<ChildProcessSpawner.ChildProcessSpawner> =47 {48 fields: { project: "the project of the repo you stand in" },49 values: Effect.gen(function* () {
8 unmodified lines
58 );59 }),60 };6174/** A command, and the words after the CLI's name that reach it. */62export interface CommandEntry {63 readonly path: readonly [string, ...string[]];64 readonly command: Command.Command.Any;65}6680/**81 * Contracts that a hand-written command wraps: `init` creates the project82 * after its local work, `env set` reads the value from stdin so it never83 * passes through an argument list or a transcript, and `today` takes84 * `--tui`, which opens Today full-screen for a person at a terminal.85 */67/** `env set` reads the value from stdin so it never passes through an argument list or a transcript. */68const wrapped = ["initProject", "setEnv", "today"];6988/** Every contract served on the CLI, but those wrapped, as a command. */70const projected = toCommands(Contracts, Effect.service(Client), {71 defaults: fromRepoContext,72 exclude: wrapped,73 output: Effect.service(Output),74 refusalsIn,75 views,76});7797/** What a group of commands that is no command itself is for, by its word. */78const groups = new Map([79 ["env", "Read a project's env shape, or set a write-only value."],80]);81102/**103 * Entries as a tree: one command per first word, the rest of each path104 * beneath it. A word that is a command and starts longer paths (`ask`, and105 * `ask open`) is a command with subcommands; a word that only starts them106 * (`env`) is a group.107 */82export const merge = (83 all: readonly CommandEntry[]84): readonly Command.Command.Any[] => {85 const words = [...new Set(all.map(({ path: [word] }) => word))];
21 unmodified lines
107 return Command.withSubcommands(parent, merge(below));108 });109};110137/** A command's words, as `schema` and its errors print them. */111const spoken = (words: readonly string[]) => words.join(" ");112140/** `schema` was asked for a command that takes no payload, or none at all. */113export class UnknownCommand extends Schema.TaggedError<UnknownCommand>()(114 "UnknownCommand",115 { words: Schema.String }116) {
1 unmodified line
118 return `${Brand.cli} has no command "${this.words}" that takes a payload; run ${Brand.cli} --help to list them`;119 }120}121150/**151 * Every contract served on the CLI, by its command's words, wrapped ones152 * included: `schema env set` describes the payload `env set` sends.153 */122const byWords = new Map(123 [...Contracts.requests.values()].flatMap((rpc) =>124 Context.get(rpc.annotations, Surfaces).includes("cli")125 ? [[commandName(rpc), rpc] as const]126 : []127 )128);129162/** Whether a field's value is write-only: a `Redacted` on the decoded side. */130const isWriteOnly = (ast: SchemaAST.AST) =>131 SchemaAST.resolveAt<{ readonly id?: unknown }>("representation")(132 SchemaAST.toType(ast)133 )?.id === "effect/schema/Redacted";
2 unmodified lines
136 "Write-only: the platform keeps it and never returns or prints it, and no MCP tool takes it.";137138const decodeJson = Schema.decodeUnknownEffect(Schema.Json);139173/**174 * A contract's payload as one JSON Schema document (the root as JSON175 * encodes it, as `Schema.toJsonSchemaDocument` does), with every176 * write-only field marked `writeOnly` and described as such.177 */140export const payloadJsonSchema = (rpc: CommandRpc) => {141 const payload = rpc.payloadSchema;142143 const { definitions, schemas } =
31 unmodified lines
175176 return decodeJson(document).pipe(Effect.orDie);177};178217/** `schema <command…>`: the payload a command sends, as JSON Schema. */179export const schema = Command.make(180 "schema",181 {182 json: Flag.Boolean("json").pipe(
31 unmodified lines
214 "Print the JSON Schema of the payload a command sends."215 )216);217257/** Every command the CLI has, projected or hand-written, by its path. */218export const entries: readonly CommandEntry[] = [219 ...projected,220 ...local,221 { command: schema, path: ["schema"] },222 { command: today, path: ["today"] },223];224265/** Any command in the tree: what it may fail with, and what it needs. */225type Every =226 | (typeof projected)[number]["command"]227 | (typeof local)[number]["command"]228 | typeof schema229 | typeof today;230272/**273 * A command at the top of the tree. Merging erases each command's own type,274 * so the tree states what all of them together may fail with and need.275 */231/** Merging erases each command's own type, so the tree states the union. */232export type TreeCommand = Command.Command<233 string,234 never,235 unknown,236 Command.Error<Every>,237 Command.Services<Every>238>;239284/** The CLI's commands at the top, merged by path. */240export const commands: readonly TreeCommand[] = merge(entries);241242const projection = toToolkit(surfaced("mcp"), Effect.service(Client));243289/**290 * The platform's skill, made from agent-kit's command list, the one the291 * platform's prompt and the web's `llms.txt` read, so they say the same.292 */244const skill = skillIn(platformSkill({ commands: commandDocs(Contracts) }));245295/**296 * The MCP-surfaced contracts as tools over stdio, beside each ask's brief297 * and the projects as resources and `made` as the prompt `contribute`, in298 * every protocol a harness may speak: the stateless 2026-07-28 one, and the299 * four session-based ones before it. Calls go through the `Client`.300 */246const server = (made: Skill) =>247 Layer.mergeAll(248 McpServer.toolkit(projection.toolkit).pipe(249 Layer.provideMerge(projection.layer)
15 unmodified lines
265 })266 )267 );268324/**325 * `mcp`: serve the contracts to a harness that spawned this process. The326 * skill is made before the server reads stdin: the server starts reading327 * as soon as it is built, so a prompt made while it builds could miss a328 * client's first `prompts/get`.329 */269/** The skill is made before the server is built: it reads stdin at once and could miss a first `prompts/get`. */270export const mcp = Command.make("mcp", {}, () =>271 Effect.flatMap(skill, (made) => Layer.launch(server(made)))272).pipe(273 Command.withDescription("Serve the platform's tools over MCP on stdio.")
1 unmodified line
modified:apps/cli/src/version.ts+2 added-18 removed
1/**2 * The CLI's version, as its build stamped it: what `--version` prints and3 * what the stdio MCP server says it is.4 *5 * `build.ts` stamps it with a define (`versionDefine`) that both bundlers6 * apply: tsdown for the npm build, `bun build --compile` for each binary.7 * Each replaces `import.meta.env.CLI_BUILD_VERSION` with the version as a8 * string literal at build time. The form is chosen because both bundlers9 * replace it, it needs no `typeof` guard on an undeclared global and no10 * `process.env` read, and a run no build stamped (vitest, `bun11 * src/bin.ts`) leaves it undefined, so it reads as `0.0.0`, the release's12 * own word for unreleased (`scripts/lib/release.ts`' `UNRELEASED`). Bun13 * reads `import.meta.env` from the process env, so an unbuilt run under14 * Bun with `CLI_BUILD_VERSION` set reports that instead; a built one never15 * looks.16 */1// Both bundlers (tsdown, `bun build --compile`) replace `import.meta.env.CLI_BUILD_VERSION`; an unbuilt run reads `0.0.0`.2// Bun reads `import.meta.env` from the process env, so an unbuilt Bun run with it set reports that instead.34declare global {5 interface ImportMeta {20 /** What a bundler's define replaces; unbuilt, Vite's or Bun's env. */6 readonly env: { readonly CLI_BUILD_VERSION?: string };7 }8}925/** The CLI's version as its build stamped it; `0.0.0` in a run no build stamped. */10export const cliVersion: string = import.meta.env.CLI_BUILD_VERSION ?? "0.0.0";
modified:apps/cli/test/local/check.test.ts+1 added-42 removed
65 unmodified lines
66 project,67} from "./fixture.ts";68import type { CheckRepo } from "./fixture.ts";6970/** A platform that says the caller holds no claims anywhere, and answers nothing else. */70const noClaims = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(71 Layer.provide([72 Layer.mergeAll(73 unanswered,
10 unmodified lines
84);8586const claimView = Schema.decodeUnknownSync(ClaimView);8789/**90 * A platform that says the caller holds a live claim on the ask, made when91 * main stood at `base`, and answers nothing else.92 */88const claimedAt = (base: string) =>89 Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(90 Layer.provide([91 Layer.mergeAll(
23 unmodified lines
115 asTester,116 ])117 );118124/** A platform no offline run may call. */119const unreachable = Layer.mock(Client)({});120127/** What `check` runs with: a test console, plain output, real processes. */121const services = (client: Layer.Layer<Client>) =>122 Layer.mergeAll(123 TestConsole.layer,124 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),
1 unmodified line
126 OutputPlain,127 SignedOut128 ).pipe(Layer.provideMerge(NodeServices.layer));129137/** Runs the CLI on `argv`: how it ended, and what it printed where. */130const run = (argv: readonly string[]) =>131 Effect.gen(function* () {132 const exit = yield* Effect.exit(program(argv));133
3 unmodified lines
137 out: (yield* TestConsole.logLines).map(String),138 };139 });140149/** The code a run's process ends with: 0 for a success. */141const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>142 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));143144const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));145155/** The one document `--json` printed on stdout. */146const envelopeOf = (out: readonly string[]) =>147 Effect.gen(function* () {148 expect(out).toHaveLength(1);149
3 unmodified lines
153const decodeEnvelope = Schema.decodeEffect(154 Schema.fromJsonString(Envelope(Schema.Unknown))155);156167/** The one document `--json` printed on stdout, read as the envelope it is. */157const decodedOf = (out: readonly string[]) =>158 Effect.gen(function* () {159 expect(out).toHaveLength(1);160
1 unmodified line
162 });163164const encodeRefusals = Schema.encodeEffect(Schema.Array(Refusal));165177/** A `Fetch` for a host that reaches nothing over the network. */166const offline = Layer.succeed(Fetch)({167 fetch: (request) =>168 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),169});170183/**184 * What the gate says of `head` in `repo`, from facts this test builds on185 * its own: a bare copy of the repo opened through `RepoHost` `/local`, the186 * change list and added lines from `@repo/git`, against the merge base of187 * `main` and `head`; the policy at `main`; and a live claim on the ask by188 * the fork's claimant.189 */171const gateSays = (repo: CheckRepo, head: string) =>172 Effect.gen(function* () {173 const fs = yield* FileSystem.FileSystem;174 const path = yield* Path.Path;
90 unmodified lines
265266 return { encoded: yield* encodeRefusals(refusals), refusals };267 });268288/**289 * What `check` must leave as it found it: where HEAD points, every ref, the290 * repo's config and index, its worktrees, and the files in its git folder.291 */269const stateOf = (root: string) =>270 Effect.gen(function* () {271 const fs = yield* FileSystem.FileSystem;272 const path = yield* Path.Path;
8 unmodified lines
281 worktrees: yield* gitOk(root, "worktree", "list", "--porcelain"),282 };283 });284308/**309 * What git exports to a hook that runs the CLI, such as a pre-commit hook310 * under `git commit -a`: its own repo and index, and the config given with311 * `git -c`. Restored when the scope closes.312 */285// What git exports to a hook it runs, such as pre-commit under `git commit -a`.286const inHook = (root: string) =>287 Effect.acquireRelease(288 Effect.sync(() => {289 vi.stubEnv("GIT_DIR", `${root}/.git`);
2 unmodified lines
292 }),293 () => Effect.sync(() => vi.unstubAllEnvs())294 );295323/** The ratchet the projects below declare, and the rule it counts. */296const ratchet = "no-explicit-any";297326/**327 * A lint that prints oxlint's JSON: one `no-explicit-any` finding per328 * explicit `any` under `packages/`, so its count follows the tree it runs on.329 */298const countingLint = [299 "grep -rnow any packages | awk -F: '",300 ' BEGIN { printf "{\\"diagnostics\\":[" }',301 ' { printf "%s{\\"code\\":\\"typescript(no-explicit-any)\\",\\"filename\\":\\"%s\\"}", (NR > 1 ? "," : ""), $1 }',
2 unmodified lines
304 "exit 1",305 "",306].join("\n");307340/**341 * Main as a project that declares the ratchet, counted by `command`, writes342 * it: the config folder in TypeScript (the fixture's `fix-a`, as a file of343 * its own), the lint, and two explicit `any`s in a. HEAD is left on main.344 */308const declaringRatchet = (repo: CheckRepo, command: string) =>309 Effect.gen(function* () {310 const sdk = `${Brand.cliPackage}/rules`;311
31 unmodified lines
343 "Count explicit anys"344 );345 });346384/** An answer on a branch of its own from main that types a third value in a as `any`. */347const raisingInA = (repo: CheckRepo) =>348 Effect.gen(function* () {349 yield* gitOk(repo.root, "checkout", "--quiet", "-b", "raising", "main");350
263 unmodified lines
614 () =>615 Effect.gen(function* () {616 const repo = yield* aCheckRepo;617656 // What the gateway says of the answer pushed onto the claim's base.618 const expected = yield* gateSays(repo, repo.straying);619620 // A contributor who clones the project and commits the answer on621 // its main, as the zero-install flow does: main...HEAD is empty.
72 unmodified lines
694 "--offline",695 "--json",696 ]).pipe(Effect.provide(services(unreachable)));697737 // What the platform said live of the same raise: the738 // ratchet, the module, and main's count before the answer's after.698 expect(Exit.isFailure(printed.exit)).toBeTruthy();699 expect(yield* decodedOf(printed.out)).toStrictEqual({700 command: "check",701 ok: false,
130 unmodified lines
modified:apps/cli/test/local/credential-helper.test.ts+1 added-19 removed
33 unmodified lines
34import type { Profile } from "../../src/credentials.ts";35import { program } from "../../src/main.ts";36import { OutputPlain } from "../../src/output.ts";3738/** The env names the CLI reads, spelled from the brand. */38const SLUG = Brand.slug.toUpperCase();3940const token = "t0ken-0123456789abcdefghijklmnopqrstuvwxyz";41
1 unmodified line
43 token: Redacted.make(token),44 url: "https://platform.test",45};4648/** What git writes to its helper for a repo on `host`, blank line and all. */47const asked = (host: string, protocol = "https") =>48 `protocol=${protocol}\nhost=${host}\npath=datekit--fix-week--alice.git\n\n`;4952/** A pi session's env, as pi hands it to the git it runs. */50const pi = { AI_AGENT: "pi", PI_MODEL: "kimi-k3" };5152const encoder = new TextEncoder();5354const decoder = new TextDecoder();5559/** The credentials file in the config dir `env` names. */56const credentialsIn = (env: Record<string, string>) =>57 CredentialsFile.pipe(58 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))59 );6065/**66 * A fresh config dir holding `profiles`, and the env that names it: the67 * shell a person who ran `login` would give git.68 */61const storedIn = (profiles: Readonly<Record<string, Profile>>) =>62 Effect.gen(function* () {63 const fs = yield* FileSystem.FileSystem;64 const dir = yield* fs.makeTempDirectoryScoped();
10 unmodified lines
7576 return env;77 });7887/** A terminal that no helper may touch: every use of it dies. */79const noTerminal = Layer.succeed(80 Terminal.Terminal,81 Terminal.make({82 columns: Effect.die("the helper read the terminal's width"),
3 unmodified lines
86 rows: Effect.die("the helper read the terminal's height"),87 })88);8999/**100 * Runs `<cli> credential <op>` as git runs its helper: `stdin` in, with101 * `env`. What it wrote to stdout and stderr, and whether it succeeded.102 */90const helper = (91 op: string,92 stdin: Stream.Stream<Uint8Array>,93 env: Record<string, string>
35 unmodified lines
129130 return { ok: Exit.isSuccess(exit), stderr, stdout };131 }).pipe(Effect.provide(TestConsole.layer));132146/** `text` as stdin that ends after it. */133const input = (text: string) => Stream.make(encoder.encode(text));134135describe(`${Brand.cli} credential, git's credential helper`, () => {136 it.live(
199 unmodified lines
336const Basic = /^Basic (?<encoded>\S+)$/u;337338const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);339354/**355 * `git http-backend` over `root` behind basic auth, on a local port: a356 * request without credentials gets the 401 that makes git ask its helper.340// A request without credentials gets the 401 that makes git ask its helper.357 * Its base URL, and every `user:password` pair it was sent.358 */341const guarded = (root: string) =>342 Effect.gen(function* () {343 const spawner =344 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();
135 unmodified lines
modified:apps/cli/test/local/env-set-live.test.ts+4 added-106 removed
1/**2 * `<cli> env set` end to end: the3 * CLI's real `env set`, `env shape` and `ledger` commands, over its remote4 * client as the stored profile, against the platform's Node world with the5 * visibility cartridge composed under the fake env's test `MASTER_KEY`6 * (`apps/platform/test/visibility/serve-cartridge-world.ts`, a process of7 * its own: apps never import apps).8 *9 * ines-v makes datekit and first pushes it with its committed `.env.schema`10 * and config folder, which names her its decider and vouches for bram. She11 * pipes a token into `env set`; bram, not a decider, tries the same; she12 * tries a public item and a short value. Then she opens an ask, bram13 * answers it, and the world's Checker runs the answer's checks. The value14 * shows nowhere: not in what the CLI printed or logged, not in any `/rpc`15 * or `/mcp` body the world sent, any line it logged or printed, the16 * Project DO's event log or ledger, or any job the Checker was given; the17 * DO's `env_values` row holds it sealed. What the world kept, it gives18 * through its `kept` window, once every step has run.19 */1import { NodeServices } from "@effect/platform-node";2import { expect, layer } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { CheckJob } from "@repo/checks/check-runner";
47 unmodified lines
52import { OutputLive } from "../../src/output.ts";53import { policyFor } from "../../src/policy.ts";54import { RemoteClient } from "../../src/remote.ts";5575/** The world, from the repo root: the platform's Node world, cartridge composed. */56const WORLD = "apps/platform/test/visibility/serve-cartridge-world.ts";5758const project = ProjectName.make("ines-v/datekit");5960const token = EnvKey.make("SENTRY_AUTH_TOKEN");6182/** What ines-v pipes in: a token of 24 characters, then the newline `echo` adds. */62const value = "sk_test_0123456789abcdef";6385/** A value of 8 characters, under the 12 a value needs. */64// Under the 12 characters a value needs.65const short = "tooshort";6688/** The ask ines-v opens and bram answers: one of datekit's own. */67const ask = AskId.make("parse-iso-week");6869interface Person {70 readonly handle: Handle;93 /** Their platform token, as the world's sessions list it. */71 readonly token: string;72}7374const ines: Person = {
5 unmodified lines
80 handle: Handle.make("bram"),81 token: "bram-env-set-live-token-0123456789abcdefgh",82};83107/** Whether datekit's first commit carries a tracked file: the library before anyone asked. */84const seeded = (file: string) =>85 [86 ".env.schema",87 `${Brand.configDir}/project.ts`,
3 unmodified lines
91 ].includes(file) ||92 /^src\/[^/]+\.ts$/u.test(file) ||93 /^test\/[^/]+\.test\.ts$/u.test(file);94119/** The ask's file and the check it names, as datekit commits them. */95const askFiles = [96 `${Brand.configDir}/asks/${ask}.ask.ts`,97 `test/asks/${ask}.test.ts`,98] as const;99125// --------------------------------------------------------------- the world126100const Serving = Schema.fromJsonString(101 Schema.Struct({ kept: Schema.String, origin: Schema.String })102);103104const decodeServing = Schema.decodeUnknownOption(Serving);105133/** Where the world serves: the platform, and the test's window on what it kept. */106interface Served {107 readonly origin: string;108 readonly kept: string;137 /** Everything the world's process printed so far, stdout and stderr. */109 readonly printed: Effect.Effect<string>;110}111141/**142 * The world served by a process of its own for as long as the scope143 * lasts, with ines-v and bram among its sessions. Both of its streams are144 * kept to the end, so it never blocks on a full pipe and every line it145 * printed can be searched.146 */112// Both streams are drained, so the process never blocks on a full pipe.113const servedWorld = (root: string) =>114 Effect.gen(function* () {115 const child = yield* spawn("bun", [WORLD], {116 cwd: root,
45 unmodified lines
162163 return { ...where, printed: Ref.get(printed) } satisfies Served;164 });165200/** What the world's `kept` window gives: each part as the world encoded it. */166const Kept = Schema.fromJsonString(167 Schema.Struct({168 bodies: Schema.Array(Schema.String),169 jobs: Schema.Array(Schema.Unknown),
14 unmodified lines
184 ),185 })186);187223/** What the world kept for datekit. */188const keptBy = (world: Served) =>189 Effect.gen(function* () {190 const http = yield* HttpClient.HttpClient;191 const response = yield* http.get(`${world.kept}/kept?project=${project}`);192193 return yield* Schema.decodeEffect(Kept)(yield* response.text);194 }).pipe(Effect.orDie);195232/** Carries every answer run the world has queued. */196const settle = (world: Served) =>197 Effect.gen(function* () {198 const http = yield* HttpClient.HttpClient;199 const response = yield* http.post(`${world.kept}/settle`);
14 unmodified lines
214 }),215 })216);217255/** The names of the tools the world's `/mcp` lists to `as`. */218const toolsListed = (world: Served, as: Person) =>219 Effect.gen(function* () {220 const http = yield* HttpClient.HttpClient;221
40 unmodified lines
262263 return result.tools.map(({ name }) => name);264 }).pipe(Effect.orDie);265304// ----------------------------------------------------------------- people305306/** Credentials holding `as`'s profile on the world, as `login` would have stored it. */266const signedIn = (world: Served, as: Person) =>267 Layer.succeed(Credentials)({268 current: Effect.succeedSome({269 handle: as.handle,
4 unmodified lines
274 put: () => Effect.die("the test stores no profile"),275 remove: () => Effect.die("the test removes no profile"),276 });277319/** The CLI's own client of the contracts, as `as`, for the steps the test sets up. */278const clientOf = (world: Served, as: Person) =>279 Effect.map(280 Layer.build(RemoteClient.pipe(Layer.provide(signedIn(world, as)))),281 (built) => Context.get(built, Client)282 );283326/**327 * `as`'s git: every command through a credential helper that gives their328 * handle and token, as the CLI's helper gives git a stored profile's.329 */284const gitOf = (helpers: string, as: Person) =>285 Effect.gen(function* () {286 const fs = yield* FileSystem.FileSystem;287 const helper = `${helpers}/${as.handle}`;
18 unmodified lines
306 run: (cwd: string, ...args: string[]) => git(cwd, ...helped, ...args),307 };308 });309356// -------------------------------------------------------------- the CLI357358/** What one run of the CLI did: its exit code, and what it printed and logged, by line. */310interface Ran {311 readonly code: number;312 readonly out: readonly string[];313 readonly err: readonly string[];314 readonly logged: readonly string[];315}316366/** A terminal that fails any prompt: nothing here may prompt. */317const noPrompts = Layer.succeed(Terminal.Terminal)(318 Terminal.make({319 columns: Effect.succeed(80),320 display: () => Effect.die("the CLI prompted"),
2 unmodified lines
323 rows: Effect.succeed(24),324 })325);326377/** How the process would exit, by the runtime's own rule. */327const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>328 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));329381/** Each line of what a stream got, however it was written. */330const linesOf = (chunks: readonly unknown[]) =>331 chunks.flatMap((chunk) => String(chunk).split("\n"));332385/**386 * `<cli> <args>` as `as`, a person at a terminal whose stdin is `stdin`387 * piped in: the real command tree and output, the real remote client over388 * HTTP to the world, and their stored profile.389 */333const cli = (334 world: Served,335 as: Person,336 args: readonly string[],
39 unmodified lines
376 )377 );378 });379437// ------------------------------------------------------------ the scenario438439/** Everything the scenario did and the world kept, read by each test below. */380class Scenario extends Context.Service<381 Scenario,382 {443 /** ines-v's `env set` of the token, its refusals, and bram's. */383 readonly set: Ran;384 readonly byBram: Ran;385 readonly publicItem: Ran;386 readonly tooShort: Ran;448 /** `env shape --json` and `ledger --json` once the token was set. */387 readonly envView: Ran;388 readonly ledger: Ran;451 /** bram's push of his answer, as git printed it. */389 readonly answered: { readonly exitCode: number; readonly stderr: string };453 /** The jobs the Checker was given for the answer: those made while the world settled. */390 readonly answerJobs: readonly CheckJob[];455 /** The tools `/mcp` lists to ines-v. */391 readonly tools: readonly string[];392 readonly kept: typeof Kept.Type;458 /** All the world's process printed, stdout and stderr. */393 readonly printed: string;394 }395>()("test/EnvSetLiveScenario") {}396463/**464 * The jobs as the world encoded them: by `CheckJob`'s fields alone, so a465 * job of unlanded code that carries values decodes, and a test refuses it.466 */397// By `CheckJob`'s fields alone, so a job carrying values still decodes and a test refuses it.398const decodeJobs = Schema.decodeUnknownEffect(399 Schema.Array(Schema.Struct(CheckJob.fields))400);401471/**472 * The scenario, run once: datekit made and first pushed by ines-v, the473 * token set and the refusals met through the CLI, then an ask opened by474 * ines-v and answered by bram, the answer's checks run, and what the world475 * kept read back.476 */402const ScenarioOnce = Layer.effect(403 Scenario,404 Effect.gen(function* () {405 const fs = yield* FileSystem.FileSystem;
14 unmodified lines
420 const bramGit = yield* gitOf(helpers, bram);421 const asInes = yield* clientOf(world, ines);422 const asBram = yield* clientOf(world, bram);423499 // ines-v makes datekit and first pushes the library as committed, its500 // `.env.schema` and its config folder in it.424 const made = yield* asInes.initProject({ project });425 const start = path.join(home, "start");426427 const tracked = yield* gitOk(example, "ls-files", "--full-name", ".");
16 unmodified lines
444 yield* gitOk(start, "add", "--all");445 yield* gitOk(start, "commit", "--quiet", "--message", "Start datekit");446 yield* inesGit.ok(start, "push", "--quiet", made.remote, "HEAD:main");447525 // The token, piped in as `printf '%s\n' "$TOKEN" |` gives it; then bram,526 // a public item and a short value.448 const setting = (key: string) => [449 "env",450 "set",451 key,
28 unmodified lines
480 project,481 "--json",482 ]);483563 // ines-v opens one of datekit's asks (red first on the world's564 // Checker); bram claims it and pushes an answer to his claim's fork.484 const files = yield* Effect.forEach(askFiles, (file) =>485 Effect.map(fs.readFileString(path.join(example, file)), (content) => ({486 content,487 path: RepoPath.make(file),
33 unmodified lines
521 const before = (yield* keptBy(world)).jobs.length;522523 yield* settle(world);524606 // Last, what MCP lists, then everything the world kept and printed.525 const tools = yield* toolsListed(world, ines);526 const kept = yield* keptBy(world);527528 return {
11 unmodified lines
540 };541 }).pipe(Effect.orDie)542).pipe(Layer.provide([NodeServices.layer, FetchHttpClient.layer]));543626// ------------------------------------------------------------------ tests627544const decodeEnvelope = <A extends Schema.Top>(data: A) =>545 Schema.decodeUnknownEffect(Schema.fromJsonString(Envelope(data)));546631/** What a `--json` run printed: its one envelope's data, as encoded, if it was not refused. */547const dataOf = (ran: Ran) =>548 Effect.map(549 decodeEnvelope(Schema.Unknown)(ran.out.join("\n")).pipe(Effect.orDie),550 (printed) => (printed.ok ? printed.data : undefined)551 );552638/** A run's lines, less the empty ones a trailing newline leaves. */553const filled = (lines: readonly string[]) =>554 lines.filter((line) => line.length > 0);555642/** Everything a run printed or logged, as one text. */556const allOf = (ran: Ran) => [...ran.out, ...ran.err, ...ran.logged].join("\n");557645/**646 * The value base64-encoded from `shift` bytes into a longer text, less the647 * characters it shares there with its neighbours: what any base64 text648 * holding the value at that alignment contains.649 */558// What any base64 text holding the value at this byte alignment must contain.559const base64At = (shift: number) => {560 const encoded = btoa(`${"\0".repeat(shift)}${value}`);561562 return encoded.slice(
1 unmodified line
564 (shift + value.length) % 3 === 0 ? encoded.length : encoded.length - 4565 );566};567659/**660 * The value, and what base64 or base64url leaves of it wherever it starts661 * inside an encoded text.662 */568const forms = [569 value,570 ...[0, 1, 2]571 .map(base64At)572 .flatMap((form) => [form, form.replaceAll("+", "-").replaceAll("/", "_")]),573];574670/** Whether a text holds the value in any form. */575const holds = (text: string) => forms.some((form) => text.includes(form));576673/** When the token was set, as the CLI printed it. */577const setAtOf = (set: Ran) =>578 / at (?<at>\S+Z)\. /u.exec(filled(set.out)[0] ?? "")?.groups?.at;579677/** A ledger's entries as encoded: each one's fields, whatever they are. */580const Entries = Schema.Struct({581 entries: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)),582});583682/** The token's item in the env shape `env shape --json` printed, if it lists one. */584const tokenItem = (envView: Ran) =>585 Effect.map(586 decodeEnvelope(EnvSchemaView)(envView.out.join("\n")).pipe(Effect.orDie),587 (printed) =>
1 unmodified line
589 ? printed.data.items.find(({ key }) => key === token)590 : undefined591 );592692/** What unlanded code sees in place of the token: its key, made a placeholder. */593const placeholder = `__${token}_PLACEHOLDER__`;594595layer(ScenarioOnce, { excludeTestServices: true, timeout: "240 seconds" })(596 `${Brand.cli} env set against the platform's Node world, the visibility cartridge composed`,
94 unmodified lines
691 logged: 0,692 printed: false,693 });694795 // What was searched holds what happened: the set's reply, its796 // log line, its sealed row and its ledger event.695 const reply = JSON.stringify({696 key: token,697 setAt: setAtOf(set),698 setBy: "ines-v",
139 unmodified lines
modified:apps/cli/test/local/env-set.test.ts-20 removed
35 unmodified lines
36import { Output, OutputPlain } from "../../src/output.ts";37import type { Mode } from "../../src/output.ts";38import { SignedOut } from "../signed-out.ts";3940/** A value no output, note or log line may ever hold. */40const secret = "sk_live_0123456789abcdef";4142const key = EnvKey.make("SENTRY_AUTH_TOKEN");4344const setAt = DateTime.makeUnsafe("2026-10-07T09:00:00Z");4547/** A person piping the value in, as `printf '…\n' |` does. */46const piped = Stream.make(new TextEncoder().encode(`${secret}\n`));4748type Payload = Rpc.Payload<typeof SetEnv>;4952/** What the platform answers `setEnv` with. */50type Answer = Effect.Effect<51 Rpc.Success<typeof SetEnv>,52 NotSensitive | ValueTooShort53>;
3 unmodified lines
57 setAt,58 setBy: Handle.make("alice"),59});6064/** One call through `Output`, as the command made it. */61interface Printed {62 readonly method: "success" | "refused" | "plan" | "note";67 /** The call's input: a note's text, or the others' object. */63 readonly input: object | string;64}6571/**72 * How one run went: its exit code, what reached stdout, stderr and the73 * logger, what the platform was asked, and what the command handed `Output`.74 */66interface Ran {67 readonly code: number;68 readonly out: string;69 readonly err: string;
3 unmodified lines
73 readonly shown: string;74}7576interface Setup {86 /** Who reads: a person at a terminal, or an agent under the agent policy. */77 readonly mode?: Mode;78 readonly stdin?: Stream.Stream<Uint8Array>;79 readonly stdinIsTerminal?: boolean;90 /** What a person types at the hidden prompt, key by key. */80 readonly typed?: string;81 readonly answer?: Answer;82}8395/** How the process would exit, by the runtime's own rule. */84const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>85 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));8687const press = (name: string, input: Option.Option<string>) => ({88 input,89 key: { ctrl: false, meta: false, name, shift: false },90});91104/**105 * Runs `<cli> env set …` with `setup`'s stdin, terminal and platform, and106 * returns everything it printed, logged and asked.107 */92const run = (args: readonly string[], setup: Setup = {}) =>93 Effect.gen(function* () {94 const calls = yield* Ref.make<readonly Payload[]>([]);95 const printed = yield* Ref.make<readonly Printed[]>([]);
2 unmodified lines
9899 const record = (method: Printed["method"], input: Printed["input"]) =>100 Ref.update(printed, (all) => [...all, { input, method }]);101118 // The CLI's plain output, recorded, as whichever reader `setup` names.102 const output = Layer.effect(103 Output,104 Effect.gen(function* () {105 const plain = yield* Effect.service(Output);
36 unmodified lines
142 rows: Effect.succeed(24),143 })144 );145163 // The platform in process: `setEnv` records what it got and answers.146 const platform = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(147 Layer.provide([148 Layer.mergeAll(149 unanswered,
41 unmodified lines
191 shown: (yield* Ref.get(shown)).join(""),192 } satisfies Ran;193 }).pipe(Effect.provide(TestConsole.layer));194213/** Asserts the value reached no output, note, log line or terminal frame. */195const neverShown = (ran: Ran) => {196 for (const seen of [197 ran.out,198 ran.err,
9 unmodified lines
208const decodeEnvelope = Schema.decodeEffect(209 Schema.fromJsonString(Envelope(Schema.Unknown))210);211231/** The one call the platform got, with its value opened for the check. */212const onlyCall = (ran: Ran) => {213 expect(ran.calls).toHaveLength(1);214215 const [call] = ran.calls;
278 unmodified lines
modified:apps/cli/test/local/facts.test.ts-15 removed
38 unmodified lines
39 initializer: Handle.make(handle),40 project: ProjectName.make(project),41};4243/** The policy at `main`, with this CLI's own bundler for a TypeScript folder. */43const policyAt = (root: string) =>44 localPolicy(root, "main", about).pipe(Effect.provide(ConfigBundlerBun));4546const pusher = Person.make({ handle: Handle.make(handle) });
3 unmodified lines
50 claimant: Handle.make(handle),51 project: ProjectName.make(project),52});5355/** A `Fetch` for a host that reaches nothing over the network. */54const offline = Layer.succeed(Fetch)({55 fetch: (request) =>56 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),57});5861/**62 * `@repo/git`'s change list and added lines from the merge base of `main`63 * and `head` to `head`, over a bare copy of the repo that `RepoHost`64 * `/local` opens as it opens any repo it hosts.65 */59const gitSays = (repo: CheckRepo, head: string) =>60 Effect.gen(function* () {61 const fs = yield* FileSystem.FileSystem;62 const path = yield* Path.Path;
97 unmodified lines
160 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))161 );162});163171/**172 * A tree whose judge reaches past the root and the CI folders, as173 * `packages/project/test/facts.test.ts` gives the platform: lefthook runs a174 * shell script that runs a hook script with a helper, Claude Code's settings175 * run `scripts/hooks/shell-policy.ts`, a package's tsconfig extends the base176 * and a file of its own, oxlint loads a plugin that imports a helper, and a177 * test outside the plugin's folder names it.178 */164const wideTree = {165 ".claude/settings.json": JSON.stringify({166 hooks: {167 PreToolUse: [
229 unmodified lines
modified:apps/cli/test/local/fixture.ts+1 added-25 removed
1/**2 * A project's working repo, built by git in a temp folder, for the local3 * `check`: two workspace packages `a` and `b`, a committed `policy.json`4 * (`../fixtures/check/policy.json`) in the config folder with one ask,5 * `fix-a`, whose territory is the package `a` and whose check is6 * `packages/a/test/a.test.ts`, and two answers to it on branches of their7 * own. The config folder's name comes from the brand, so no fixture on disk8 * spells it: the fixture's `{configDir}` is written over with it.9 */1import { Brand } from "@repo/brand";2import { gitOk } from "@repo/testkit/git";3import { Effect, FileSystem, Path } from "effect";414/** The project, the ask and the person the fixture's remote names. */5export const project = "alice/fixture";67export const ask = "fix-a";89export const handle = "alice";1021/** The platform the fixture's `origin` remote points at. */11export const platform = "https://platform.example.dev";1224/** The claim's fork, as its remote names it: `<project>--<ask>--<handle>`. */13const forkRemote = `${platform}/${project}--${ask}--${handle}.git`;1427/** The policy file, under the config folder. */15export const policyFile = `${Brand.configDir}/policy.json`;1630/** The ask's check file: red on main, by its fourth line's assertion. */17export const checkFile = "packages/a/test/a.test.ts";1833/** What the config folder states: the fixture, in the folder the brand names. */19// The fixture's `{configDir}` is written over with the brand's folder name.20export const policyText = Effect.gen(function* () {21 const fs = yield* FileSystem.FileSystem;22 const path = yield* Path.Path;23
13 unmodified lines
37 'it("is two", () => expect(a).toBe(2));',38 "",39].join("\n");4055/** Main's files but the policy: the root manifest and both packages. */41const onMain = {42 [checkFile]: testOnMain,43 "package.json":44 '{ "name": "fixture", "private": true, "workspaces": ["packages/*"] }\n',
3 unmodified lines
48 "packages/b/package.json": '{ "name": "b" }\n',49 "packages/b/src/b.ts": "export const b = 1;\n",50} as const satisfies Readonly<Record<string, string>>;5167/** The answer that strays: it edits `b`, skips a test at line 4, and fixes `a`. */52const straying = {53 [checkFile]: testOnMain.replace(54 "it(",55 'it.skip("is one", () => expect(a).toBe(1));\nit('
1 unmodified line
57 "packages/a/src/a.ts": "export const a = 2;\n",58 "packages/b/src/b.ts": "export const b = 2;\n",59} as const satisfies Readonly<Record<string, string>>;6077/** The answer that stays inside its territory: it fixes `a`, and only that. */61const clean = {62 "packages/a/src/a.ts": "export const a = 2;\n",63} as const satisfies Readonly<Record<string, string>>;6482/** The fixture's commits: `main`, and the two answers' heads. */65export interface CheckRepo {66 readonly root: string;67 readonly main: string;68 readonly straying: string;
12 unmodified lines
81 yield* fs.writeFileString(at, content);82 }83 });84103/** Writes `files` in `root` and commits them all; the new commit's id. */85export const commit = (86 root: string,87 files: Readonly<Record<string, string>>,88 message: string
5 unmodified lines
9495 return yield* gitOk(root, "rev-parse", "HEAD");96 });97117/**118 * The fixture repo, in a temp folder the scope removes: `main`, then the119 * branches `straying` and `clean` from it, with HEAD on `straying` and the120 * claim's fork as `origin`.121 */98export const aCheckRepo = Effect.gen(function* () {99 const fs = yield* FileSystem.FileSystem;100 const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());101
19 unmodified lines
modified:apps/cli/test/local/init.test.ts-29 removed
31 unmodified lines
32import { program } from "../../src/main.ts";33import { OutputPlain } from "../../src/output.ts";34import { SignedOut } from "../signed-out.ts";3536/** Credentials for a run signed in as `handle`, whose profile `login` wrote. */36const signedInAs = (handle: string) =>37 Layer.mock(Credentials)({38 current: Effect.succeedSome({39 handle: Handle.make(handle),
22 unmodified lines
62 " - run: bun run test",63 "",64].join("\n");6567/**68 * The config `init` proposes for the machine's repo: the commands its CI69 * and scripts run, each with where it was found.70 */66const proposal = projectFile(67 {68 checks: Object.fromEntries(69 new Map([
13 unmodified lines
83 "checks.types from package.json",84 ]85);8692/**93 * A maintainer's machine: a repo on branch `work` whose scripts test, lint94 * and type-check and whose CI installs with Bun; an empty bare repo that95 * stands in for the platform's; and a `HOME` whose git config names who96 * commits and nothing else.97 */87const aMachine = Effect.gen(function* () {88 const fs = yield* FileSystem.FileSystem;89 const path = yield* Path.Path;90 const home = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
26 unmodified lines
117});118119type Machine = Effect.Success<typeof aMachine>;120132/**133 * The real process spawner, as if the CLI were started in `machine.repo`134 * with `machine.home` as `HOME`: a command's relative folder is taken from135 * the repo, and git reads only the machine's global config.136 */121const startedIn = (machine: Machine) =>122 Layer.effect(ChildProcessSpawner.ChildProcessSpawner)(123 Effect.gen(function* () {124 const real = yield* ChildProcessSpawner.ChildProcessSpawner;
22 unmodified lines
147 );148 })149 ).pipe(Layer.provide(NodeServices.layer));150167/**168 * A platform whose `initProject` records each payload it decodes and answers169 * `reply`, reached through a client over the contracts' own schemas; any170 * other contract dies.171 */151const aPlatform = (152 reply: Effect.Effect<153 typeof InitProject.successSchema.Type,154 ProjectExists | ImportFailed
16 unmodified lines
171 ])172 ),173 }));174196/** The exit code the process would end with, as the runtime decides it. */175const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>176 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));177200/** Runs `<cli> argv` on `machine` against `platform`: its exit code and what it printed. */178const cli = (179 machine: Machine,180 platform: Layer.Layer<Client>,181 argv: readonly string[],
26 unmodified lines
208const decodeEnvelope = Schema.decodeEffect(209 Schema.fromJsonString(Envelope(Schema.Unknown))210);211235/** The one envelope `--json` printed. */212const envelopeOf = (out: readonly string[]) =>213 Effect.gen(function* () {214 expect(out).toHaveLength(1);215216 return yield* decodeEnvelope(out[0] ?? "");217 });218243/** What git says about the machine's repo and the platform's. */219const state = (machine: Machine) =>220 Effect.gen(function* () {221 const fs = yield* FileSystem.FileSystem;222 const path = yield* Path.Path;
18 unmodified lines
241 remotes: yield* gitOk(machine.repo, "remote"),242 };243 });244270/** The platform made the project `demo`, served at the machine's bare repo. */245const created = (machine: Machine) =>246 Effect.succeed({247 project: ProjectName.make("oscabriel/demo"),248 remote: machine.remote,
570 unmodified lines
819const decodeCalls = Schema.decodeUnknownEffect(820 Schema.Array(Schema.Struct({ project: Schema.String }))821);822849/** The project `init --import <url>` sends with `flags`, signed in as `handle`. */823const importSends = (handle: string, url: string, flags: readonly string[]) =>824 Effect.gen(function* () {825 const machine = yield* aMachine;826
15 unmodified lines
842843 return calls.map(({ project }) => project);844 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));845873// A bare word is the person's own, and an import named by nobody takes its874// source path when its host is one the platform knows.846describe(`${Brand.cli} init's project name`, () => {847 it.live(848 "gives a bare --project the profile's handle, even on an import from a known host",849 () =>
57 unmodified lines
modified:apps/cli/test/local/login.test.ts-29 removed
38 unmodified lines
39import { program } from "../../src/main.ts";40import { OutputPlain } from "../../src/output.ts";41import { oauthServer } from "../oauth-server.ts";4243/** The env names the CLI reads, spelled from the brand. */43const SLUG = Brand.slug.toUpperCase();4445const url = "https://platform.test";4647const given = "tok-given-0123456789abcdefghijklmnopqrstuvwxyz";4849const issued = "tok-issued-0123456789abcdefghijklmnopqrstuvwxyz";5052/** The three lines `login` sets in git's global config for `at`. */51const helperLines = (at: string) => [52 `git config --global --replace-all credential.${at}.helper ""`,53 `git config --global --add credential.${at}.helper ${Brand.slug}`,54 `git config --global credential.${at}.useHttpPath true`,55];5659/** The same three, as the argv lists `--json` carries. */57const helperArgv = (at: string) => [58 ["git", "config", "--global", "--replace-all", `credential.${at}.helper`, ""],59 ["git", "config", "--global", "--add", `credential.${at}.helper`, Brand.slug],60 ["git", "config", "--global", `credential.${at}.useHttpPath`, "true"],61];6266/** A temp HOME with its own global git config: a person's shell, for the CLI and git. */63const home = Effect.gen(function* () {64 const fs = yield* FileSystem.FileSystem;65 const path = yield* Path.Path;66 const dir = yield* fs.makeTempDirectoryScoped();
5 unmodified lines
72 CredentialsFile.pipe(73 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))74 );7580/** The profile `name` as the file holds it: its url, handle and token. */76const stored = (env: Record<string, string>, name: string) =>77 Effect.provide(78 Effect.flatMap(Effect.service(Credentials), ({ current }) => current),79 credentialsIn({ ...env, [`${SLUG}_PROFILE`]: name })
6 unmodified lines
86 }))87 )88 );8995/** `git config --global <args>` in `env`: its stdout and exit code. */90const gitConfig = (env: Record<string, string>, ...args: string[]) =>91 Effect.scoped(92 Effect.gen(function* () {93 const child = yield* spawn("git", ["config", "--global", ...args], {
13 unmodified lines
107 );108109const isPerson = Schema.is(Person);110117/**118 * The platform's side of a call, as `status` sees it: whoever the server side119 * takes the caller for holds no claim yet (every first login), and `status`120 * names them.121 */111const statusHandler = Contracts.toLayerHandler("status", () =>112 Effect.flatMap(Effect.service(CurrentPrincipal), (principal) =>113 isPerson(principal)114 ? Effect.succeed({ answers: [], claims: [], handle: principal.handle })115 : Effect.die("status is for people signed in")116 )117);118130/** A server side that refuses every credential, as for a revoked token. */119const refusesEveryone = Layer.succeed(Authenticated, () =>120 Effect.fail(new Unauthenticated())121);122135/**136 * The world `login` runs in, faked at its three host seams: the platform's137 * client (an in-process one, whose server side is `server`), the person's138 * browser, and the loopback server (a Node server on an ephemeral port).139 * Each records what `login` asked of it.140 */123const seams = (server: Layer.Layer<Authenticated>) =>124 Effect.gen(function* () {125 const connected = yield* Ref.make<126 readonly { token: string; url: string }[]
40 unmodified lines
167 opened: Ref.get(opened),168 };169 });170189/** A platform that takes the caller for `handle`. */171const signedInAs = (handle: string) => asPerson(Handle.make(handle));172192/** What the tests themselves run on: a test console, and Node for files, git and servers. */173const testServices = Layer.mergeAll(TestConsole.layer, NodeServices.layer);174195/** A terminal nothing may touch: every use of it dies. */175const noTerminal = Layer.succeed(176 Terminal.Terminal,177 Terminal.make({178 columns: Effect.die("login read the terminal's width"),
6 unmodified lines
185186interface Run {187 readonly env: Record<string, string>;188 readonly seams: Layer.Layer<never>;210 /** What stdin holds. */189 readonly stdin?: string;212 /** Whether stdout is a terminal, as a person's would be. */190 readonly terminal?: boolean;191}192216/** Runs `argv` as the CLI would, in `run`'s world; how it ended. */193const cli = (argv: readonly string[], run: Run) =>194 Effect.exit(195 program(argv).pipe(196 Effect.provide(
16 unmodified lines
213 )214 )215 );216241/** What was printed, one entry per line however it was written. */217const lines = (all: readonly unknown[]) =>218 all.flatMap((chunk) => String(chunk).split("\n"));219245/** Every line printed so far, on stdout and on stderr. */220const printed = Effect.gen(function* () {221 return {222 stderr: lines(yield* TestConsole.errorLines),223 stdout: lines(yield* TestConsole.logLines),224 };225});226253/** The sign-in URL `login` printed for `origin`, once it has. */227const signInUrl = (origin: string) =>228 Effect.gen(function* () {229 for (let attempt = 0; attempt < 250; attempt += 1) {230 const line = (yield* printed).stderr
9 unmodified lines
240241 return yield* Effect.die("login printed no sign-in URL");242 });243271/** GET `at` as a browser would, following redirects: the page's status. */244const visit = (at: string) =>245 Effect.gen(function* () {246 const client = yield* HttpClient.HttpClient;247 const response = yield* client.get(at);248249 return response.status;250 }).pipe(Effect.provide(FetchHttpClient.layer));251280/** The query `/authorize` was sent, field by field. */252const fieldsOf = (query: URLSearchParams | undefined) =>253 Object.fromEntries(query?.entries() ?? []);254255describe(`${Brand.cli} login --token-stdin`, () => {
515 unmodified lines
modified:apps/cli/test/local/project-file.test.ts-11 removed
4 unmodified lines
5import { ChildProcess, ChildProcessSpawner } from "effect/process";67import { projectFile } from "../../src/local/project-file.ts";89/**10 * What the finder reads from a repo whose CI installs with Bun and whose11 * scripts test, lint and type-check. Lanes come in the order found, which12 * the file keeps.13 */9const found = {10 run: {11 checks: Object.fromEntries(12 new Map([
13 unmodified lines
26 "checks.types from package.json",27 ],28} as const;2935/** What the finder reads from a repo with scripts but no test runner it knows. */30const noTest = {31 run: {32 checks: { lint: "npm run lint" },33 setup: "npm install",
79 unmodified lines
113114const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>115 bytes.pipe(Stream.decodeText(), Stream.mkString);116123/**124 * Type-checks `files` (name → content) as a maintainer's repo would, with125 * the published CLI's `/rules` mapped to the workspace SDK: tsc's exit code126 * and what it printed.127 */117const typeCheck = (files: Readonly<Record<string, string>>) =>118 Effect.scoped(119 Effect.gen(function* () {120 const fs = yield* FileSystem.FileSystem;
98 unmodified lines
modified:apps/cli/test/local/stale.test.ts-8 removed
16 unmodified lines
17import { SignedOut } from "../signed-out.ts";18import { aCheckRepo, handle, project } from "./fixture.ts";19import type { CheckRepo } from "./fixture.ts";2021/** A platform no offline run may call. */21const unreachable = Layer.mock(Client)({});2223const services = Layer.mergeAll(24 TestConsole.layer,
2 unmodified lines
27 OutputPlain,28 SignedOut29).pipe(Layer.provideMerge(NodeServices.layer));3032/** `check --offline --shape-only --json` in the repo: how it ended, and what it printed where. */31const checked = (root: string) =>32 Effect.gen(function* () {33 const exit = yield* Effect.exit(34 program(["check", "--dir", root, "--offline", "--shape-only", "--json"])
13 unmodified lines
48const name = ProjectName.make(project);4950const skill = `.agents/skills/${keyOf(ProjectName.make(project))}-contribute/SKILL.md`;5154/** The landing an older copy of the skill came from. */52const older = LandedSha.make("a".repeat(40));5357/** The policy at the fixture's main, as `check` reads it. */54const policyAtMain = (repo: CheckRepo) =>55 localPolicy(repo.root, "main", {56 initializer: Handle.make(handle),57 project: name,58 }).pipe(Effect.provide(ConfigBundlerBun));5964/** An older run block: one lane, `ok`, where main has two. */60const olderRun = Schema.decodeSync(RunBlock)({61 checks: { ok: "true" },62 test: "true {path}",63});6470/** The policy at main with the older run block. */65const withOlderRun = (policy: Policy): Policy => ({ ...policy, run: olderRun });6673/** Writes `content` at `file` in the repo's work tree, leaving it uncommitted. */67const writeFile = (repo: CheckRepo, file: string, content: string) =>68 Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;
2 unmodified lines
73 yield* fs.makeDirectory(path.dirname(at), { recursive: true });74 yield* fs.writeFileString(at, content);75 });7684/** The fixture with HEAD on its clean answer, which the shape stage passes. */77const cleanRepo = Effect.gen(function* () {78 const repo = yield* aCheckRepo;7980 yield* gitOk(repo.root, "checkout", "--quiet", "clean");
143 unmodified lines
modified:apps/cli/test/local/why.test.ts-26 removed
50 unmodified lines
51const alice = Handle.make("alice");5253const carol = Handle.make("carol");5455/** The second commit's message: its trailers, as an answerer wrote them. */55const message = [56 "Start the week on Monday",57 "",58 "Asked-by: carol",59 "Signed-off-by: alice",60 "Assisted-by: claude-code",61].join("\n");6264/**65 * A repo with two commits: the first writes `src/week.ts` lines 1 and 2,66 * the second adds line 3 with `message`.67 */63const aRepo = Effect.gen(function* () {64 const fs = yield* FileSystem.FileSystem;65 const path = yield* Path.Path;66 const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
20 unmodified lines
8788 return { dir, first, second };89});9096/** What the platform was asked: each `landing` call's payload. */91type Asked = readonly { readonly project: string; readonly sha: string }[];9299/** A record of `landing` calls, none yet. */93const noCalls = Ref.make<Asked>([]);94102/** The platform's record of the second commit's landing. */95const landingOf = (sha: CommitSha): LandingView => ({96 ask: AskId.make("fix-week"),97 assisted: [{ harness: "claude-code", verified: false }],98 author: alice,
5 unmodified lines
104 project,105 sha: LandedSha.make(sha),106});107116/** The same landing as `--json` prints it. */108const landingJson = (sha: string) => ({109 ask: "fix-week",110 assisted: [{ harness: "claude-code", verified: false }],111 author: "alice",
5 unmodified lines
117 project: "oscabriel/datekit",118 sha,119});120130/**131 * The platform in process, answering `landing` with `answer` and every132 * other contract never: a test reaching one fails.133 */121const platform = (122 answer: (payload: {123 readonly project: ProjectName;124 readonly sha: CommitSha;
8 unmodified lines
133 asTester,134 ])135 );136150/**151 * A platform that knows `landed` as a landing and no other commit, and152 * records every `landing` call it is asked.153 */137const platformKnowing = (138 landed: Option.Option<CommitSha>,139 calls: Ref.Ref<Asked>140) =>
6 unmodified lines
147 )148 )149 );150168/**169 * Output as the agent policy gives it when `CLAUDECODE=1`: Markdown for170 * results, refusals and notes on stderr. `OutputPlain` is the person's.171 */151const OutputForAgent = Layer.succeed(Output)({152 mode: "agent",153 note: (text) => Console.error(text),154 plan: ({ payload }) => Console.log(JSON.stringify(payload)),155 refused: ({ refusals }) => Console.error(explain(refusals).join("\n")),156 success: ({ view }) => Console.log(view.markdown),157});158180/** How the process would exit, by the runtime's own rule. */159const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>160 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));161184/**185 * Runs `<cli> why …` in `dir` against `client`, printing through `output`,186 * and returns its exit code, stdout and stderr.187 */162const run = (163 dir: string,164 args: readonly string[],165 client: Layer.Layer<Client>,
378 unmodified lines
modified:apps/cli/test/tui/fixture.ts-5 removed
1/**2 * One decider's Today, as the TUI's tests read it: three decisions listed3 * out of expiry order, one of them expiring within the day, a budget with4 * room left and one waiting beyond it, and two newcomers to welcome.5 */1import { RefNameText } from "@repo/protocol/domain/common";2import { DecisionSubject } from "@repo/protocol/domain/decision";3import type { Decision, Today } from "@repo/protocol/domain/decision";4import {
67 unmodified lines
modified:apps/cli/test/tui/today.test.ts+1 added-42 removed
1/**2 * Today in the terminal, as a decider works it: the keys they press, the3 * screen they read, and the refusal an agent or a script meets instead.4 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { createTestRenderer } from "@opentui/core/testing";4import { createElement } from "@opentui/react";
33 unmodified lines
38import { TodayView } from "../../src/tui/view.ts";39import { runProgram } from "../remote-server.ts";40import { datekit, okonkwo, proposal, stray, today, vouch } from "./fixture.ts";4146/** The state after `keys`, one after another, and every call they made. */42const press = (state: TodayViewState, keys: readonly string[]) => {43 const calls: DecideCall[] = [];44 let now = state;45
65 unmodified lines
111 expect(reduce(state, "down").quit).toBeFalsy();112 });113});114120/**121 * The screen `TodayView` draws for `state` on a terminal `height` rows tall122 * (40 unless given), one string per row.123 */115const screenOf = (state: TodayViewState, height = 40) =>116 Effect.acquireUseRelease(117 Effect.promise(() =>118 testRender(createElement(TodayView, { state }), { height, width: 120 })
12 unmodified lines
131 setup.renderer.destroy();132 })133 );134144/** The rows of a screen that hold `text`. */135const rowsWith = (rows: readonly string[], text: string) =>136 rows.filter((row) => row.includes(text));137138describe("Today as the terminal shows it", () => {
105 unmodified lines
244 })245 );246});247258/**259 * Where the TUI may be asked to open: the env and terminals of the process,260 * and a platform that no test here may reach.261 */248const surroundings = (input: {249 readonly env: Readonly<Record<string, string>>;250 readonly stdoutIsTTY: boolean;251 readonly stdinIsTTY: boolean;
3 unmodified lines
255 Stdio.layerTest({ stdinIsTerminal: Effect.succeed(input.stdinIsTTY) }),256 Layer.mock(Client)({})257 );258273/** What `runTodayTui` refused with, as its next command and its one line. */259const refusalIn = (layer: ReturnType<typeof surroundings>) =>260 runTodayTui({ project: Option.none() }).pipe(261 Effect.flip,262 Effect.map((failure) =>
75 unmodified lines
338 })339 );340});341357/**358 * A screen that reads `keys` in turn (then `q`) and keeps every state it is359 * shown. The keys are pressed before any is read, so `forget` drops every360 * one not read yet, as the terminal drops those pressed while a choice was361 * on its way.362 */342// Every key is pressed before any is read, so `forget` drops each one not read yet.343const scripted = (keys: readonly string[]) =>344 Effect.gen(function* () {345 const left = yield* Ref.make(keys);346 const shown = yield* Ref.make<readonly TodayViewState[]>([]);
6 unmodified lines
353354 return { screen, shown };355 });356377/**378 * The platform for one decider: `today` lists the fixture's decisions but379 * those decided since, and `decide` takes every choice but those on380 * `closed`, which it refuses as already decided. Returns the client, and381 * every `decide` payload it saw.382 */357const platform = (closed: ReadonlySet<string>) =>358 Effect.gen(function* () {359 const decided = yield* Ref.make<360 readonly (typeof Decide.payloadSchema.Type)[]
39 unmodified lines
400401 return { client, decided };402 });403430/** A person at a terminal, with the platform `client` and the screen `screen`. */404const atTerminal =405 (client: Layer.Layer<Client>, screen: Screen) =>406 <A, E>(effect: Effect.Effect<A, E, Client | Policy | Stdio.Stdio>) =>407 effect.pipe(
96 unmodified lines
504 );505506 const screen = yield* screenOn(setup.renderer);507535 /** The terminal's rows once `state` is drawn. */508 const drawn = (state: TodayViewState) =>509 Effect.gen(function* () {510 yield* screen.show(state);511 yield* Effect.promise(() => setup.renderOnce());
28 unmodified lines
540 )541 );542});543572/** What was printed to a stream, one entry per line however it was written. */544const lines = (chunks: readonly unknown[]) =>545 chunks.flatMap((chunk) => String(chunk).split("\n"));546576/**577 * The `today` contract as the CLI would project it, were the hand-written578 * command not standing in for it: what that command prints without `--tui`579 * is held to it.580 */547const projectedToday = toCommand(TodayOf, Effect.service(Client), {548 output: Effect.service(Output),549 refusalsIn,550 render: views.today,551});552587/**588 * A `today` command (the tree's own unless given), run on `args` as the589 * process would: the mode from `env`, a terminal on both ends, and the590 * platform `client`; no screen opens. Returns what it printed on stdout and591 * stderr, and how it ended.592 */553const runToday = (554 args: readonly string[],555 input: {556 readonly client: Layer.Layer<Client>;
3 unmodified lines
560) => {561 const policy = policyFor({ env: input.env, isTTY: true });562563 return Effect.gen(function* () {604 // Either command's failures, read alike.564 const exit: Exit.Exit<void, unknown> = yield* input.command === undefined565 ? Effect.exit(Command.runWith(todayCommand, { version: "0.0.0" })(args))566 : Effect.exit(Command.runWith(input.command, { version: "0.0.0" })(args));567
121 unmodified lines
modified:apps/cli/test/build-targets.test.ts-5 removed
1/**2 * A cross-compiled binary needs another machine's native packages, which3 * `bun install` leaves out on this one: the build fetches them for npm's4 * `os` and `cpu`, read here from Bun's target names.5 */1import { describe, expect, it } from "@effect/vitest";2import { Option } from "effect";34import { npmMachineOf } from "../build-targets.ts";
25 unmodified lines
modified:apps/cli/test/build.test.ts+2 added-40 removed
1/**2 * The CLI as it ships: `bun run build` makes one standalone binary, its git3 * credential helper link and the npm `dist/`, and each runs as a process4 * here. The build runs twice for the file (the second run shows the npm5 * files come out the same); every case reads what the second run wrote.6 */1import { NodeServices } from "@effect/platform-node";2import { expect, layer } from "@effect/vitest";3import { Brand } from "@repo/brand";4import {
8 unmodified lines
13 Stream,14} from "effect";15import { ChildProcess, ChildProcessSpawner } from "effect/process";1623/** How a process ended, and what it printed. */17interface Ran {18 readonly exitCode: number;19 readonly stderr: string;20 readonly stdout: string;
1 unmodified line
2223const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>24 bytes.pipe(Stream.decodeText(), Stream.mkString);2533/** The whole env a built binary runs with. */26interface Bare {27 readonly HOME: string;28 readonly PATH: string;29 readonly XDG_CONFIG_HOME: string;30}3140/**41 * Runs `command` to its end. With `only`, the process gets exactly that env42 * and nothing of this machine's; without it, it inherits this one's.43 */32const run = (33 command: string,34 args: readonly string[],35 options: {
26 unmodified lines
62 return { exitCode, stderr, stdout } satisfies Ran;63 })64 ).pipe(Effect.orDie);6578/**79 * The npm build's files in `dist/` (not the binaries), each by its name and80 * a hash of its text, so two builds compare in a short diff.81 */66const npmFiles = (dist: string) =>67 Effect.gen(function* () {68 const fs = yield* FileSystem.FileSystem;69 const path = yield* Path.Path;
11 unmodified lines
8182 return files;83 });84101/** What `bun run build` did, where it wrote, and a bare env to run it in. */85class Built extends Context.Service<86 Built,87 {88 readonly build: Ran;106 /** The build run a second time, and the npm files each run wrote. */89 readonly rebuild: Ran;90 readonly firstFiles: Readonly<Record<string, number>>;91 readonly secondFiles: Readonly<Record<string, number>>;110 /** The CLI package's folder, and its `dist/`. */92 readonly root: string;93 readonly dist: string;113 /** `HOME` and `XDG_CONFIG_HOME` in a temp folder, and a `PATH` of one empty folder. */94 readonly bare: Bare;115 /** `bare`, with the built binaries' folder as the whole `PATH`. */95 readonly onPath: Bare;117 /** `bare`, with this machine's `PATH`, where `node` is. */96 readonly withNode: Bare;97 }98>()("cli/test/Built") {}99
30 unmodified lines
130 });131 })132).pipe(Layer.provideMerge(NodeServices.layer));133156/** The path of `segments` under `dist/`, once the test has seen the build write it. */134const written = (...segments: readonly string[]) =>135 Effect.gen(function* () {136 const { dist } = yield* Built;137 const fs = yield* FileSystem.FileSystem;
7 unmodified lines
145146 return file;147 });148172/** Long enough for a case that starts the built binaries a few times on a busy machine. */149const spawning = { timeout: 60_000 };150175/** The start-here banner `--help` opens with (as `test/main.test.ts` holds it). */151const banner = [152 "Start here:",153 `${Brand.cli} asks list the open asks you could take`,154 `${Brand.cli} claim take one; you get a fork to push your answer to`,155 `${Brand.cli} check run the gate's checks locally before you push`,156];157183/** The banner as `--help` printed it, if it did: four lines from "Start here:". */158const bannerIn = (stdout: string) => {159 const lines = stdout.split("\n").map((line) => line.trim());160 const start = lines.indexOf("Start here:");161162 return start === -1 ? [] : lines.slice(start, start + banner.length);163};164191/**192 * The names a module's source exports, types included: each `export {…}`193 * list by its exported names, and each exported declaration. An `export *`194 * shows as `*`, since its names can't be read off the page.195 */165const exportedNames = (source: string) => {166 const listed = [167 ...source.matchAll(/\bexport\s+(?:type\s+)?\{(?<list>[^}]*)\}/gu),168 ]
20 unmodified lines
189 .filter((name) => name.length > 0)190 .toSorted();191};192224/** What git hands a credential helper: the host, then a blank line. */193const request = "protocol=https\nhost=example.test\n\n";194227/**228 * An import, export, `import()` or `require` of a workspace package. A229 * static import or export names its module in quotes, never backticks, so230 * prose in a kept doc comment ("from `@repo/git`'s `treeDiff`") is not one;231 * only a call may take a template literal.232 */195// A static import or export quotes its module, never with backticks, so196// prose in a doc comment is not one.197const workspaceSpecifier =198 /(?:\b(?:from|import)\s*["']|\b(?:import|require)\s*\(\s*["'`])@repo\//u;199200layer(BuiltOnce, { excludeTestServices: true, timeout: "180 seconds" })(
20 unmodified lines
221222 const binary = yield* fs.stat(yield* written("bin", Brand.cli));223224 expect(binary.type).toBe("File");261 // The owner's execute bit.225 expect(Math.floor(binary.mode / 0o100) % 2).toBe(1);226227 // A link, not a shim: the compiled binary sees the name it was228 // invoked by.
129 unmodified lines
358 const binary = yield* written("bin", Brand.cli);359360 yield* written("bin", Brand.gitCredentialHelper);361399 // Found on the PATH by name, as git finds a helper.362 const helper = yield* run(Brand.gitCredentialHelper, ["get"], {363 only: onPath,364 stdin: request,365 });
158 unmodified lines
modified:apps/cli/test/commands-doc.test.ts+2 added-42 removed
1/**2 * The command rows every listing renders from (the platform's skill, the3 * CLI's MCP prompt, the web's `llms.txt`) against the CLI itself: the tree4 * `root` builds, and what each command's `--help` says it takes. A command5 * without a row, a row without a command, or a row naming flags the command6 * doesn't take fails here, before any listing tells an agent so.7 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { commandDocs, contractCommandDocs } from "@repo/agent-kit/command-doc";4import type { CommandDoc } from "@repo/agent-kit/command-doc";
7 unmodified lines
12import { root } from "../src/main.ts";13import { OutputPlain } from "../src/output.ts";14import { SignedOut } from "./signed-out.ts";1523/** What a command's `--help` says it takes, as this test reads it. */16const Takes = Schema.Struct({17 args: Schema.Array(18 Schema.Struct({ name: Schema.String, required: Schema.Boolean })19 ),
11 unmodified lines
31const encodeTakes = Schema.encodeSync(Schema.fromJsonString(Takes));3233const decodeTakes = Schema.decodeSync(Schema.fromJsonString(Takes));3443/** The parts of a help page this test compares, as one JSON line. */35const takesOf = (doc: HelpDoc.HelpDoc) =>36 encodeTakes({37 args: (doc.args ?? []).map(({ name, required }) => ({ name, required })),38 flags: doc.flags.map(({ name, required, type }) => ({
4 unmodified lines
43 });4445const plain = CliOutput.defaultFormatter({ colors: false });4656/** effect/cli's own formatter, but help prints what a command takes as JSON. */47const formatter: CliOutput.Formatter = {48 formatCliError: (error) => plain.formatCliError(error),49 formatError: (error) => plain.formatError(error),50 formatErrors: (errors) => plain.formatErrors(errors),51 formatHelpDoc: takesOf,52 formatVersion: (name, version) => plain.formatVersion(name, version),53};5465/**66 * What the CLI runs with here: a test console, that formatter, and a client67 * and credentials `--help` never calls.68 */55const services = Layer.mergeAll(56 TestConsole.layer,57 CliOutput.layer(formatter),58 Layer.mock(Client)({}),59 SignedOut,60 OutputPlain61).pipe(Layer.provideMerge(NodeServices.layer));6277/**78 * What the command at `path` takes, from its own `--help`; help that fails79 * to print fails the test.80 */63const helpOf = (path: readonly string[]) =>64 Effect.gen(function* () {65 yield* Command.runWith(root, { version: "0.0.0" })([...path, "--help"]);66
8 unmodified lines
75 readonly command: Command.Command.Any;76 readonly takes: Takes;77}7897/** Every command under `command` in the tree, at any depth, with its help. */79const below = (80 command: Command.Command.Any,81 path: readonly string[]82): Effect.Effect<readonly Node[]> =>
7 unmodified lines
90 return [node, ...(yield* below(sub, here))];91 })92 ).pipe(Effect.map((nodes) => nodes.flat()));93113/**114 * Whether a node is a command a person runs: one with nothing under it, or115 * one that takes arguments or flags of its own (`ask <ask>` beside `ask116 * open`). A word that only groups commands (`env`) takes none.117 */94// A word that only groups commands (`env`) takes nothing; `ask <ask>` beside `ask open` does.95const isRunnable = ({ command, takes }: Node) =>96 command.subcommands.length === 0 ||97 takes.args.length + takes.flags.length > 0;98122/** The CLI's runnable commands, by their words. */99const runnable = below(root, []).pipe(100 Effect.map(101 (nodes) =>102 new Map(
5 unmodified lines
108const rows: readonly CommandDoc[] = commandDocs(Contracts);109110const words = ({ path }: CommandDoc) => path.join(" ");111136/**137 * A row's flags as the command declares them: `--no-push` is the negation138 * effect/cli gives the boolean flag `push`, so it names that switch, unless139 * the command has a flag of that very name (`--no-browser`). Only a boolean140 * flag has a negation; any other `--no-…` stays as written.141 */112// `--no-push` names the boolean flag `push`, unless the command has a flag of that very name.113const declared = (row: CommandDoc, takes: Takes) => {114 const names = new Set(takes.flags.map(({ name }) => name));115116 const switches = new Set(
9 unmodified lines
126 })127 );128};129159/** A payload's JSON Schema, as this test reads it: its fields and the required ones. */130const PayloadFields = Schema.Struct({131 properties: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),132 required: Schema.optionalKey(Schema.Array(Schema.String)),133});134135const decodePayloadFields = Schema.decodeUnknownSync(PayloadFields);136167/** The payload of the contract a contract row projects, as JSON Schema. */137const payloadOf = (row: CommandDoc) => {138 const rpc = Contracts.requests.get(row.contract ?? "");139140 return rpc === undefined
2 unmodified lines
143};144145const isBoolean = Schema.is(Schema.Struct({ type: Schema.Literal("boolean") }));146178/** A boolean field is a switch, which the CLI never requires. */147const isSwitch = (field: Schema.Json | undefined) =>148 field !== undefined && isBoolean(field);149182/**183 * The required fields the CLI fills from the repo it stands in, so a person184 * there may leave them out (`fromRepoContext` in `apps/cli/src/surfaces.ts`).185 */150const filledFromRepo = new Set(["project"]);151152describe("the command rows against the CLI", () => {153 it.effect(
41 unmodified lines
195 }),196 30_000197 );198235 // A contract's flag is required when its payload field is, unless it is a236 // switch or the CLI fills it from the repo it stands in: `project`, as237 // `filledFromRepo` above says. A field the CLI starts filling, or stops238 // filling, fails here until that list says so too.199 it.effect(200 "require a contract's required fields as flags, all but the --project the repo fills",201 () =>202 Effect.gen(function* () {
33 unmodified lines
modified:apps/cli/test/credentials.test.ts-5 removed
18 unmodified lines
19 gitHelperConfig,20} from "../src/credentials.ts";21import type { Profile } from "../src/credentials.ts";2223/** The env names the CLI reads, spelled from the brand. */23const SLUG = Brand.slug.toUpperCase();2425const token = "tok-default-0123456789abcdefghijklmnopqrstuvwxyz";26
8 unmodified lines
35 token: Redacted.make("tok-alice-0123456789abcdefghijklmnopqrstuvwxyz"),36 url: "https://platform-demo.example.workers.dev",37};3840/** A fresh config dir, and the env a shell would give the CLI with it. */39const configHome = Effect.map(40 Effect.flatMap(FileSystem.FileSystem, (fs) => fs.makeTempDirectoryScoped()),41 (dir) => ({ dir, env: { HOME: "/nonexistent", XDG_CONFIG_HOME: dir } })42);4346/** The `Credentials` the CLI would build in `env`. */44const credentialsIn = (env: Record<string, string>) =>45 Effect.provide(46 Effect.service(Credentials),47 CredentialsFile.pipe(48 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))49 )50 );5155/** Each profile's url and handle, and the token's value: what a test compares. */52const seen = (profile: Option.Option<Profile>) =>53 Option.map(profile, ({ handle, token: secret, url }) => ({54 handle,55 token: Redacted.value(secret),
17 unmodified lines
73 expect(yield* fs.exists(file)).toBeTruthy();7475 const info = yield* fs.stat(file);7681 // The permission bits: read and write for the owner, nothing else.77 expect(info.mode % 0o1000).toBe(0o600);78 expect(seen(yield* credentials.current)).toStrictEqual(79 seen(Option.some(defaultProfile))80 );
145 unmodified lines
modified:apps/cli/test/hook.test.ts-40 removed
61 unmodified lines
62import { program } from "../src/main.ts";63import { OutputPlain } from "../src/output.ts";64import { SignedOut } from "./signed-out.ts";6566/** The repo's top folder, as the session found it. */66const root = "/work/datekit";6769/** The ask's check, one of the ask's own files: no answer may change it. */68const checkPath = "packages/a/test/week.test.ts";6970const landedSha = "4444444444444444444444444444444444444444";7174/** Bob's ask `fix-week`, as its file states it: module `a` is its territory. */72const askWire = {73 askedBy: "bob",74 blockedBy: [],75 brief: { want: "An ISO week date parses to the Monday of that week." },
13 unmodified lines
89 publicFiles: ["packages/a/src/index.ts"],90 },91} as const;9296/** The ask, as `showAsk` returns it. */93const ask = Schema.decodeSync(Ask)(askWire);9499/** Alice's claim on `fix-week`, as the hook keeps it. */95const claim: HookClaim = {96 ask: ask.id,97 base: CommitSha.make("1".repeat(40)),98 checkCommand: `bun test ${checkPath}`,
1 unmodified line
100 territory: ask.territory,101 want: ask.brief.want,102};103109/** An unreasoned `.skip(` in the ask's check: the agent's to fix. */104const weakened = new Weakened({105 at: { line: 3, path: RepoPath.make(checkPath) },106 weakening: { marker: ".skip(" },107});108109const sha = (digit: string) => CommitSha.make(digit.repeat(40));110117/** A session with a claim, before any stop was held. */111const facts: HookFacts = {112 claim: Option.some(claim),113 holds: 0,114 judge: {
10 unmodified lines
125 session_id: "session-1",126 ...fields,127});128136/** A tool call on one file, as Claude Code sends it. */129const tool = (name: string, toolInput: NonNullable<HookInput["tool_input"]>) =>130 input({ tool_input: toolInput, tool_name: name });131140/** Claude Code's PreToolUse deny, with the gateway's own text as the reason. */132const deny = (refusals: Array.NonEmptyReadonlyArray<Refusal>) => ({133 hookSpecificOutput: {134 hookEventName: "PreToolUse",135 permissionDecision: "deny",
158 unmodified lines
294 ).toStrictEqual({});295 });296});297307/** Claude Code's Stop, as it sends it. */298const stop = (fields: Partial<HookInput> = {}) =>299 input({ hook_event_name: "Stop", stop_hook_active: false, ...fields });300311/** Claude Code's Stop hold, with the gateway's own text as the reason. */301const hold = (refusals: Array.NonEmptyReadonlyArray<Refusal>) => ({302 decision: "block",303 reason: explain(refusals).join("\n"),304});
73 unmodified lines
378 });379});380381describe("the gateway's own reading of a path", () => {393 /** The policy at the landed SHA: the closure `@repo/checks` computes for it. */382 const policy = Schema.decodeSync(Policy)({383 agents: "trailer",384 asks: [askWire],385 at: landedSha,
26 unmodified lines
412 vouches: [],413 weakening: { markers: [] },414 });415428 /** Alice's push to her claim's fork, changing `path` alone. */416 const push = (path: string): PushFacts => ({417 addedLines: new Map(),418 ask: Option.some(ask),419 base: sha("1"),
54 unmodified lines
474 })475 );476});477491// ------------------------------------------------------------ the command492493/** Alice's live claim on `fix-week`, made when main was at `base`. */478const liveClaim = (base: string) =>479 Schema.decodeSync(ClaimView)({480 ask: "fix-week",481 base,
7 unmodified lines
489 state: "live",490 warnsAt: "2026-10-07T14:00:00.000Z",491 });492509/**510 * Alice's clone of her claim's fork: a commit with two modules, the config511 * folder and the ask's check, and the fork as `origin`. Its root, real path.512 */493const aClone = (remote: string) =>494 Effect.gen(function* () {495 const fs = yield* FileSystem.FileSystem;496 const path = yield* Path.Path;
41 unmodified lines
538539 return { base: yield* gitOk(dir, "rev-parse", "HEAD"), dir };540 });541562/**563 * A platform whose `status` gives alice's claims as `claims` holds them564 * when asked, counting each `status` and each `showAsk`.565 */542const platformOf = (543 claims: Ref.Ref<readonly ClaimView[]>,544 asked: Ref.Ref<{ readonly showAsk: number; readonly status: number }>545) =>
28 unmodified lines
574 asPerson(Handle.make("alice")),575 ])576 );577602/** A platform that knows alice's claim, made at `base`, and what it was asked. */578const platformFor = (base: string) =>579 Effect.gen(function* () {580 const asked = yield* Ref.make({ showAsk: 0, status: 0 });581
5 unmodified lines
587 ),588 };589 });590616/** What one run of `<cli> hook …` printed, and the exit code a process would have. */591interface Ran {592 readonly code: number;593 readonly out: readonly string[];594 readonly err: readonly string[];595}596623/** The env a run reads: where the session's state is kept. */597interface StateEnv {598 readonly HOME?: string;599 readonly XDG_STATE_HOME?: string;600}601629/**630 * Runs `argv` as a harness would: `stdin` on stdin, the state kept where631 * `env` says (a folder alone is `XDG_STATE_HOME`), with `services` (the632 * platform, a push check) beside the CLI's own.633 */602const runHook = (603 argv: readonly string[],604 stdin: string,605 env: string | StateEnv,
31 unmodified lines
637 )638 )639 );640673/** `TouchedJudge` for one path. */641const touchedJudgeOf = (path: string) =>642 new TouchedJudge({ paths: [RepoPath.make(path)] });643644const tempDir = Effect.flatMap(FileSystem.FileSystem, (fs) =>
175 unmodified lines
820 "allows a session whose platform never answers once its time is up, and says why",821 () =>822 Effect.gen(function* () {823 const { dir } = yield* aClone(fork);857 // The project the hook asks the platform about, once it asks.824 const asked = yield* Deferred.make<string | undefined>();825826 const hung = Layer.mock(Client)({827 status: ({ project }) =>
63 unmodified lines
891 path.join(state, Brand.slug, "hooks", "s-8.json"),892 path.join(home, ".local", "state", Brand.slug, "hooks", "s-9.json"),893 ];894929 // Each file's permission bits, if it is there.895 expect(896 yield* Effect.forEach(kept, (file) =>897 Effect.map(898 Effect.option(fs.stat(file)),
137 unmodified lines
1036 });10371038 const before = [yield* event("session-start"), yield* edit];10391075 // The agent claims the ask in its first turn.1040 yield* Ref.set(claims, [liveClaim(base)]);10411042 const after = [yield* edit, yield* event("stop"), yield* edit];1043
36 unmodified lines
1080const encodeEnvelope = Schema.encodeSync(1081 Schema.fromJsonString(Envelope(Schema.Unknown))1082);10831120/**1121 * The default check over a stand-in for the CLI that prints `stdout` and1122 * exits `code`, whatever arguments it is given.1123 */1084const checkPrinting = (stdout: string, code: number) =>1085 Effect.gen(function* () {1086 const fs = yield* FileSystem.FileSystem;1087 const path = yield* Path.Path;
105 unmodified lines
modified:apps/cli/test/main.test.ts-7 removed
8 unmodified lines
9import { Credentials } from "../src/credentials.ts";10import { root } from "../src/main.ts";11import { OutputPlain } from "../src/output.ts";1213/** What was printed to stdout, one entry per line however it was written. */13const printed = Effect.map(TestConsole.logLines, (all) =>14 all.flatMap((chunk) => String(chunk).split("\n"))15);1618/**19 * What the CLI runs with in these tests: a test console, plain output, and20 * a client and credentials no command here calls.21 */17const services = Layer.mergeAll(18 TestConsole.layer,19 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),20 Layer.mock(Client)({}),21 Layer.mock(Credentials)({}),22 OutputPlain23).pipe(Layer.provideMerge(NodeServices.layer));2430/** The help `root` prints for `--help`, line by line. */25const help = Effect.gen(function* () {26 yield* Command.runWith(root, { version: "0.0.0" })(["--help"]);2728 return yield* printed;29}).pipe(Effect.provide(services));3037/** The lines of `lines` between the heading `from` and the next heading. */31const section = (lines: readonly string[], from: string) => {32 const start = lines.indexOf(from) + 1;3334 const end = lines.findIndex(
53 unmodified lines
modified:apps/cli/test/mcp-extras.test.ts+1 added-13 removed
1/**2 * `<cli> mcp` beside its tools, forked over stdio as a harness3 * spawns it, in MCP's stateless 2026-07-28 protocol: an ask's brief is a4 * resource read through the CLI's `Client`, and the platform's skill is the5 * prompt `contribute`.6 */1import { describe, expect, it } from "@effect/vitest";2import { commandDocs } from "@repo/agent-kit/command-doc";3import { readManaged } from "@repo/agent-kit/generated-file";4import { platformSkill } from "@repo/agent-kit/platform";
12 unmodified lines
17const fixWeek = AskId.make("fix-week");1819const want = "week reads the ISO week of a date";2027/** fix-week as `showAsk` returns it. */21const askWire = {22 askedBy: "dora",23 blockedBy: [],24 brief: { want },
13 unmodified lines
38} as const;3940const brief = `# ${fixWeek}\n\n${want}.\n`;4149/** A platform with datekit's one open ask, fix-week. */42const datekit = Layer.mergeAll(43 unanswered,44 Contracts.toLayerHandler("showAsk", ({ ask }) =>45 ask === fixWeek
21 unmodified lines
67 "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },68 "io.modelcontextprotocol/protocolVersion": "2026-07-28",69};7079/** A stateless 2026-07-28 request over stdio: each carries its `_meta`. */71// The stateless 2026-07-28 protocol: every request carries its own `_meta`.72const request = (73 id: number,74 method: string,75 params: Readonly<Record<string, Schema.Json>> = {}
21 unmodified lines
97 })98 ),99});100109/**110 * The platform's skill body, from agent-kit's command list: the contracts'111 * commands and the hand-written ones.112 */101const skillBody = platformSkill({ commands: commandDocs(Contracts) }).pipe(102 Effect.map(([file]) =>103 Option.match(104 Option.flatMap(Option.fromNullishOr(file), ({ content }) =>
66 unmodified lines
modified:apps/cli/test/oauth-server.ts-15 removed
1/**2 * A stand-in for the platform's OAuth authorization server, as the CLI's3 * `login` meets it: `/authorize` sends the browser back to the loopback4 * `redirect_uri` with a code and the state it was given, and `/token` trades5 * that code for an access token only if the `code_verifier` hashes (S256,6 * RFC 7636) to the challenge `/authorize` saw.7 */1import { NodeHttpServer } from "@effect/platform-node";2import { Context, Effect, Layer, Ref, Schema } from "effect";3import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";45export interface OAuthServerOptions {13 /** The access token `/token` issues. */6 readonly token: string;15 /** The state `/authorize` sends back: the client's own, or another one. */7 readonly state?: "same" | "other";8}919/** A code `/authorize` gave out, and what `/token` must be shown for it. */10interface Grant {11 readonly challenge: string;12 readonly clientId: string;13 readonly redirectUri: string;
13 unmodified lines
27 .replaceAll("+", "-")28 .replaceAll("/", "_")29 .replace(/=+$/u, "");3041/** `BASE64URL(SHA256(verifier))`. */31const s256 = (verifier: string) =>32 Effect.map(33 Effect.promise(() =>34 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
3 unmodified lines
3839const refused = (error: string) =>40 HttpServerResponse.jsonUnsafe({ error }, { status: 400 });4153/**54 * The server on a local port: its origin, and the query of every55 * `/authorize` request it answered.56 */42export const oauthServer = (options: OAuthServerOptions) =>43 Effect.gen(function* () {44 const grants = yield* Ref.make<ReadonlyMap<string, Grant>>(new Map());45 const authorizations = yield* Ref.make<readonly URLSearchParams[]>([]);
96 unmodified lines
modified:apps/cli/test/output.test.ts-1 removed
13 unmodified lines
14});1516const view = { markdown: "**2** open asks", text: "2 open asks" };1718/** What `use` printed through `OutputPlain`: stdout and stderr, as text. */18const printedBy = (use: (output: Output["Service"]) => Effect.Effect<void>) =>19 Effect.gen(function* () {20 yield* Effect.flatMap(Effect.service(Output), use);21
87 unmodified lines
modified:apps/cli/test/pi.test.ts+2 added-36 removed
1/**2 * The pi adapter on a fake pi: a registry that records each `pi.on` handler,3 * and events shaped as pi 1.0.3 types them, fired at those handlers. The4 * policy behind `PiDeps` is a fake for the adapter's own tests; the last5 * group runs the live deps over the hook policy's modules, with a stand-in6 * local check (`hook.test.ts` tests the policy itself).7 */1import type {2 AgentBeforeSettleEvent,3 BeforeAgentStartEvent,4 SessionBoundaryDraft,
35 unmodified lines
40import type { PiContext, PiDeps, PiEvents, PiHandlers } from "../src/pi.ts";4142const cwd = "/work/datekit";4351/** The brief the fake policy gives a session that holds a claim. */44const briefText = "# Your claim: fix-week in datekit";4554/** The config folder's project file: in every judge closure. */46const projectFile = RepoPath.make(`${Brand.configDir}/project.ts`);4757/** A change outside the claim's territory. */48const outside = new OutOfScope({ paths: [RepoPath.make("README.md")] });4960/** What the fake policy answers. */50interface Policy {51 readonly brief?: Option.Option<string>;52 readonly guard?: (53 call: GuardedCall54 ) => Option.Option<Array.NonEmptyReadonlyArray<Refusal>>;55 readonly settle?: () => SettleVerdict;56}5769/** The fake policy, and what the adapter asked it. */58const fakeDeps = (policy: Policy) => {59 const asked: string[] = [];6061 const deps: PiDeps = {
19 unmodified lines
8182 return { asked, deps };83};8497/** A policy whose every call fails as `failure` does. */85const broken = (failure: Effect.Effect<never, HookFailed>): PiDeps => ({86 brief: () => failure,87 guardTool: () => failure,88 settle: () => failure,89});90104/** The fake policy's judge: the config folder's project file is in its closure. */91const judging = (call: GuardedCall) =>92 GuardedCall.$is("Write")(call) && call.file === projectFile93 ? Option.some(Array.of(new TouchedJudge({ paths: [projectFile] })))94 : Option.none();95110/** A fake preflight: what `<cli> check` refuses of the work as it stands. */96const preflight =97 (...refusals: readonly Refusal[]) =>98 (call: GuardedCall) =>99 GuardedCall.$is("Push")(call) && Array.isReadonlyArrayNonEmpty(refusals)100 ? Option.some(refusals)101 : Option.none();102118/** A fake pi: it records each handler the adapter registers, by event. */103const fakePi = () => {104 const handlers: { -readonly [K in keyof PiHandlers]?: PiHandlers[K] } = {};105 const events: string[] = [];106
8 unmodified lines
115116 return { events, handlers, pi };117};118135/** A handler's context in session `id`, with the notes `ui.notify` got. */119const contextOf = (id: string, withUi = true) => {120 const notes: string[] = [];121 const bare: PiContext = { cwd, sessionManager: { getSessionId: () => id } };122
5 unmodified lines
128129 return { ctx: withUi ? { ...bare, ui } : bare, notes };130};131149/** pi set up with `policy` behind the adapter. */132const loaded = (policy: Policy) => {133 const { asked, deps } = fakeDeps(policy);134 const { events, handlers, pi } = fakePi();135
1 unmodified line
137138 return { asked, events, handlers };139};140159/** Fires one recorded handler at `event`, as pi does, and awaits it. */141const fire = <E, R>(142 handler: ((event: E, ctx: PiContext) => Promise<R>) | undefined,143 event: E,144 ctx: PiContext
34 unmodified lines
179 toolName: "bash",180 type: "tool_call",181});182202/**203 * A completed run's settle with `entries` already proposed by earlier204 * handlers, as pi 1.0.3 hands it over: the run ended on the agent's own205 * reply, so the preview says it cannot go on (`canContinue` is false while206 * the last message is the assistant's, `_buildBoundaryContext` in207 * `dist/core/agent-session.js`) until a handler appends a message.208 */183// pi 1.0.3 previews a run that ended on the agent's reply as unable to go on184// until a handler appends a message.185const settleOf = (entries: SessionBoundaryDraft[]): AgentBeforeSettleEvent => ({186 context: {187 canContinue: false,188 contextEntries: [],
243 unmodified lines
432 );433 });434435 describe("agent_before_settle", () => {460 /** What another handler already appended at this boundary. */436 const earlier: SessionBoundaryDraft = {437 customType: "other-extension",438 type: "custom",439 };
295 unmodified lines
735 })736 );737});738764// ------------------------------------------------------------ live deps765739const want = "An ISO week date parses to the Monday of that week.";740768/** Kept facts for a session on `fix-week` in a clone at `root`. */741const claimedIn = (root: string): SessionState => ({742 claim: {743 ask: AskId.make("fix-week"),744 base: CommitSha.make("1".repeat(40)),
6 unmodified lines
751 judge: { paths: [Glob.make(`/${Brand.configDir}/**`)], pointers: [] },752 root,753});754783/**784 * The live deps with their state in a temp folder, a local check that785 * answers `checked`, and a platform that must not be called. Gives the786 * deps, a folder that is no repo, the roots the check ran in, and a way to787 * keep a session's facts.788 */755const policyWith = (756 checked: Effect.Effect<readonly Refusal[], PushCheckFailed>757) =>758 Effect.gen(function* () {
178 unmodified lines
modified:apps/cli/test/policy-view.test.ts-13 removed
1/**2 * `policy` as a person reads it: datekit's evaluated config folder at the3 * landed commit in the people page's words (deciders by path, the vouch4 * rule and its counts, the caps, budget, claim timing and record window),5 * or, with no policy there, why it has not evaluated and what makes it.6 * The view is a pure function of `projectPolicy`'s decoded success; under7 * `--json` the success prints as JSON whatever the view says.8 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Contracts, PolicyOf } from "@repo/protocol/contracts";4import type { PublicPolicy } from "@repo/protocol/domain/policy";
7 unmodified lines
12const sha = "4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c";1314const decodeSuccess = Schema.decodeSync(PolicyOf.successSchema);1524/** datekit's evaluated config folder at `sha`, encoded. */16const datekitPolicy = {17 agents: "trailer",18 at: sha,19 budget: { decisionsPerDay: 5, expireDays: 14 },
18 unmodified lines
38 ],39 weakening: { markers: [] },40} as const satisfies typeof PublicPolicy.Encoded;4151/** datekit's policy as `projectPolicy` returns it. */42const datekit = decodeSuccess({ policy: datekitPolicy });4344const noConfig = decodeSuccess({45 unevaluated: { at: sha, reason: "noConfig" },
2 unmodified lines
48const configFailed = decodeSuccess({49 unevaluated: { at: sha, reason: "configFailed" },50});5162/** What a person reads: the view's text, or its Markdown when it has none. */52const textOf = (success: typeof PolicyOf.successSchema.Type) =>53 Option.match(views.projectPolicy(success), {54 onNone: () => "",55 onSome: ({ markdown, text }) => text ?? markdown,56 });5769/** Each non-empty line, its runs of spaces made one. */58const linesOf = (text: string) =>59 text60 .split("\n")61 .map((line) => line.replaceAll(/\s+/gu, " ").trim())
99 unmodified lines
161const decodeEnvelope = Schema.decodeEffect(162 Schema.fromJsonString(Envelope(Schema.Unknown))163);164177/** A platform whose `projectPolicy` answers `success`. */165const answering = (success: typeof PolicyOf.successSchema.Type) =>166 Layer.mergeAll(167 unanswered,168 Contracts.toLayerHandler("projectPolicy", () => Effect.succeed(success))
64 unmodified lines
modified:apps/cli/test/policy.test.ts-1 removed
20 unmodified lines
21 territory: "packages/week",22 want: "Weeks start on the locale's first day",23};2425/** `listAsks` lists one open ask; `claim` finds it taken. */25const platform = Layer.mergeAll(26 unanswered,27 Contracts.toLayerHandler("listAsks", () =>28 Effect.succeed({ asks: [listing] })
131 unmodified lines
modified:apps/cli/test/remote-server.ts+1 added-33 removed
1/**2 * The platform as the CLI's tests meet it: in process, through a test3 * client, for `program` runs; or over HTTP, as an `RpcServer` for the4 * contracts on an ephemeral port, for the remote client.5 */1import { NodeHttpServer, NodeServices } from "@effect/platform-node";2import { authenticated, bearerToken } from "@repo/protocol/authenticate";3import { Client, Contracts } from "@repo/protocol/contracts";4import { Handle } from "@repo/protocol/ids";
21 unmodified lines
26import { policyFor } from "../src/policy.ts";27import { WorkingDirectory } from "../src/surfaces.ts";28import { SignedOut } from "./signed-out.ts";2935/** Handlers for every contract, as a test sets them up. */30export type Handlers = Layer.Layer<31 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>32>;3340/** A Terminal that counts every prompt it is asked for, and answers none. */34const promptless = (prompts: Ref.Ref<number>) => {35 const prompted = Ref.update(prompts, (count) => count + 1).pipe(36 Effect.andThen(Effect.die("the CLI prompted"))37 );
8 unmodified lines
46 })47 );48};4957/** What was printed to a stream, one entry per line however it was written. */50const lines = (output: Effect.Effect<readonly unknown[]>) =>51 Effect.map(output, (all) =>52 all.flatMap((chunk) => String(chunk).split("\n"))53 );5455export interface Invocation {64 /** The calls' handlers: the platform in process, as `tester`. */56 readonly handlers: Handlers;66 /** How the CLI reaches the platform instead, such as over HTTP. */57 readonly client?: Layer.Layer<Client>;68 /** The env the CLI reads its mode from. */58 readonly env?: Readonly<Record<string, string>>;70 /** Whether stdout is a terminal; it is, unless said otherwise. */59 readonly isTTY?: boolean;72 /** Where the CLI stands; the test process's own folder unless given. */60 readonly cwd?: string;61}6276/**77 * Runs `program` on `args` as the process would: the mode from `env` and the78 * TTY, the platform from `handlers`, and a terminal that fails any prompt.79 * Returns what it printed, its exit code as the runtime would set it, and80 * how many prompts it asked for.81 */63export const runProgram = (64 args: readonly string[],65 { client, cwd, env = {}, handlers, isTTY = true }: Invocation66) =>
47 unmodified lines
114 prompts: yield* Ref.get(prompts),115 };116 });117137/** A person the HTTP platform knows by their token. */118export const knownToken = "token-of-tester";119140/** The person a token names: `tester` for `knownToken`, nobody for any other. */120const verify = (token: string) =>121 Effect.succeed(122 token === knownToken123 ? Option.some(Person.make({ handle: Handle.make("tester") }))124 : Option.none()125 );126148/** `app` served on an ephemeral port for the test's scope: returns its origin. */127const serving = <E>(128 app: Effect.Effect<129 HttpServerResponse.HttpServerResponse,130 E,
11 unmodified lines
142 ? `http://127.0.0.1:${address.port}`143 : yield* Effect.die("the test platform listens on a socket, not a port");144 });145168/**169 * The contracts over HTTP at `/rpc`, on an ephemeral port: `handlers` answer170 * as the person `knownToken` names, or as anyone for a public contract when171 * a request carries no credential. Any other bearer token is a 401 before172 * the contracts see it, as at the platform's gate. Returns the origin, and173 * every `authorization` header the server saw, in order.174 */146// Any other bearer token is a 401 before the contracts see it, as at the platform's gate.147export const httpPlatform = (handlers: Handlers) =>148 Effect.gen(function* () {149 const seen = yield* Ref.make<readonly (string | undefined)[]>([]);150
21 unmodified lines
172173 return { origin: yield* serving(gate), seen: Ref.get(seen) };174 });175204/**205 * A platform that answers every request with `status` and an empty body, as206 * a platform that is down does: returns its origin.207 */176export const failingPlatform = (status: number) =>177 serving(Effect.succeed(HttpServerResponse.empty({ status })));
modified:apps/cli/test/remote.test.ts-3 removed
14 unmodified lines
15 runProgram,16} from "./remote-server.ts";17import type { Handlers } from "./remote-server.ts";1819/** `listAsks` (public) lists one ask; `status` (signed in) shows nothing yet. */19const handlers: Handlers = Layer.mergeAll(20 unanswered,21 Contracts.toLayerHandler("listAsks", () =>22 Effect.succeed({
13 unmodified lines
36 Effect.succeed({ answers: [], claims: [], handle: Handle.make("tester") })37 )38);3941/** Credentials holding `profile`, or none. */40const holding = (profile: Option.Option<Profile>) =>41 Layer.succeed(Credentials)({42 current: Effect.succeed(profile),43 forHost: () => Effect.succeed(profile),
5 unmodified lines
49 token: Redacted.make(token),50 url,51});5255/** The remote client over `credentials`, with `env` as its whole env. */53const remote = (54 credentials: Layer.Layer<Credentials>,55 env: Readonly<Record<string, string>> = {}56) =>
123 unmodified lines
modified:apps/cli/test/repo-context.test.ts-2 removed
105 unmodified lines
106 expect(parseRemote(url)).toStrictEqual(Option.none());107 });108});109110/** A fresh git repo, its real path, with `remotes` added in order. */110const aRepo = (remotes: readonly (readonly [string, string])[]) =>111 Effect.gen(function* () {112 const fs = yield* FileSystem.FileSystem;113 const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
6 unmodified lines
120121 return dir;122 });123125/** Credentials whose current profile is on `url`. */124const signedIn = (url: string) => {125 const profile: Profile = {126 token: Redacted.make("tok-0123456789abcdefghijklmnopqrstuvwxyz"),127 url,
72 unmodified lines
modified:apps/cli/test/schema.test.ts-2 removed
3 unmodified lines
4import { Effect, Schema } from "effect";56import { runProgram } from "./remote-server.ts";78/** What `schema` prints: a JSON Schema object, as far as these tests read it. */8const PayloadSchema = Schema.fromJsonString(9 Schema.Struct({10 $schema: Schema.String,11 properties: Schema.Record(
10 unmodified lines
22);2324const decodePayloadSchema = Schema.decodeEffect(PayloadSchema);2527/** `schema` asks the platform nothing. */26const schemaOf = (words: readonly string[], env = {}) =>27 runProgram(["schema", ...words], { env, handlers: unanswered });2829describe("schema <command>", () => {
65 unmodified lines
modified:apps/cli/test/signed-out.ts+2 added-6 removed
1/**2 * Credentials for a run where nobody has logged in: no profile, for any3 * host. `login` and `logout` are in the command tree, so `program` needs4 * `Credentials`; a test that writes a profile through this layer is wrong,5 * and the mock's unimplemented `put` and `remove` die and say so.6 */1// `program` needs `Credentials`; the mock's unimplemented `put` and `remove`2// die, so a test that writes a profile fails.3import { Effect, Layer } from "effect";45import { Credentials } from "../src/credentials.ts";6
4 unmodified lines
modified:apps/cli/test/stdio.ts-4 removed
24 unmodified lines
25 result: Schema.optionalKey(Schema.Unknown),26 })27);2829/**30 * Runs `mcp` as a harness would spawn it: `messages` go in on stdin, one JSON31 * line each, then stdin ends. Returns every result it wrote back, by id.32 */29export const session = (30 handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>,31 messages: readonly object[]32) =>
48 unmodified lines
modified:apps/cli/test/surfaces.test.ts-10 removed
47 unmodified lines
48 conflicts: [RepoPath.make("src/a.ts")],49 main,50});5152/** Contracts whose answers always meet a moved main. */52const stale = Layer.mergeAll(53 unanswered,54 Contracts.toLayerHandler("submitAnswer", () => Effect.fail(refusal))55);
8 unmodified lines
64});6566const Initialized = Schema.Struct({ protocolVersion: Schema.String });6769/** A tools/call result whose one content block is JSON text. */68const ToolResult = Schema.Struct({69 content: Schema.Tuple([70 Schema.Struct({71 text: Schema.fromJsonString(Schema.Unknown),
100 unmodified lines
172 })173 );174});175178/** The names of a command's subcommands, in order. */176const subcommandsOf = (command: Command.Command.Any | undefined) =>177 (command?.subcommands ?? []).flatMap(({ commands: group }) =>178 group.map(({ name }) => name)179 );
56 unmodified lines
236 "--choice",237 "accept",238];239243/** A platform that counts the decisions it is asked to take, and takes none. */240const deciding = (calls: Ref.Ref<number>) =>241 Layer.mergeAll(242 unanswered,243 Contracts.toLayerHandler("decide", () =>
96 unmodified lines
340 })341 );342});343348/** A platform that lists no asks, recording the project each listing names. */344const listing = (asked: Ref.Ref<readonly string[]>) =>345 Layer.mergeAll(346 unanswered,347 Contracts.toLayerHandler("listAsks", ({ project: named }) =>348 Ref.update(asked, (all) => [...all, named]).pipe(Effect.as({ asks: [] }))349 )350 );351357/** A fresh git repo whose `origin` is `url`, at its real path. */352const repoWithOrigin = (url: string) =>353 Effect.gen(function* () {354 const fs = yield* FileSystem.FileSystem;355 const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
82 unmodified lines
438 "--requestId",439 requestId,440];441448/** An answer's receipt, standing at `outcome`. */442const receiptAt = (outcome: Outcome) => ({443 ask,444 base,445 head,
1 unmodified line
447 project,448 requestId,449});450458/** A platform whose `submitAnswer` gives `receipt` back. */451const receiving = (receipt: ReturnType<typeof receiptAt>) =>452 Layer.mergeAll(453 unanswered,454 Contracts.toLayerHandler("submitAnswer", () => Effect.succeed(receipt))455 );456465/** Each command that names an ask, and what else it takes, as a person types it. */457const naming = {458 finish: [459 "--project",460 project,
18 unmodified lines
479 ],480 verdict: ["--project", project],481} as const satisfies Readonly<Record<string, readonly string[]>>;482492/** A platform that records the ask each call names, and answers each call plainly. */483const recordingAsks = (named: Ref.Ref<readonly string[]>) => {484 const record = (given: string) => Ref.update(named, (all) => [...all, given]);485486 const receipt = receiptAt(Outcome.cases.Checking.make({ stage: "merge" }));
140 unmodified lines
modified:apps/cli/test/version.test.ts-8 removed
1/**2 * The CLI's version: `src/version.ts` says it, a run no build stamped says3 * `0.0.0`, and `build.ts` stamps a release's version into both bundlers'4 * output through one define. The real build compiles binaries, so it is5 * run by hand (issue 1104's comments), not here.6 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client } from "@repo/protocol/contracts";
17 unmodified lines
22 OutputPlain,23 SignedOut24).pipe(Layer.provideMerge(NodeServices.layer));2532/** What a built `version.ts` exports. */26const Built = Schema.Struct({ cliVersion: Schema.String });2728describe("the CLI's version, unbuilt", () => {29 it.effect("is 0.0.0, and --version prints it", () =>
96 unmodified lines
126 ]);127 });128});129137/** What the build would run with for `argv`, if it would run. */130const parsed = (argv: readonly string[]) =>131 Effect.gen(function* () {132 const seen = yield* Ref.make(Option.none<BuildOptions>());133
28 unmodified lines
modified:apps/cli/build-targets.ts+1 added-18 removed
1/**2 * What `bun build --compile --target=<target>` needs from npm for another3 * machine. `bun install` installs only this machine's optional native4 * packages, so a binary for another one (darwin-arm64 from Linux) cannot5 * embed OpenTUI's native library until the build fetches it (`build.ts`).6 */1import { Option } from "effect";29/** A machine as npm's `os` and `cpu` fields name it. */3export interface NpmMachine {4 readonly cpu: string;5 readonly os: string;6}715/** Bun's operating systems, by npm's name for each. */8const OS = new Map([9 ["darwin", "darwin"],10 ["linux", "linux"],11 ["windows", "win32"],12]);1314const CPU = new Set(["arm64", "x64"]);1524/**25 * npm's machine for a Bun compile target (`bun-darwin-arm64`, `linux-x64`,26 * `bun-linux-x64-musl`, `bun-windows-x64-baseline`): its OS and CPU, with27 * Bun's prefix and modifiers dropped. None for a target Bun does not name.28 */16export const npmMachineOf = (target: string): Option.Option<NpmMachine> => {17 const [os, cpu] = target.replace(/^bun-/u, "").split("-");1819 return Option.flatMap(Option.fromUndefinedOr(OS.get(os ?? "")), (npmOs) =>
2 unmodified lines
22 : Option.none()23 );24};2539/**40 * The packages whose optional dependencies hold the native code the CLI's41 * binary embeds: OpenTUI's core (`today --tui`) loads its library from42 * `@opentui/core-<os>-<cpu>`.43 */26// OpenTUI loads its native library from `@opentui/core-<os>-<cpu>`.27export const NATIVE = ["@opentui/core"] as const;
modified:apps/cli/build.ts+7 added-73 removed
1/**2 * `bun run build`: the CLI as it ships, in `dist/`.3 *4 * 1. tsdown (`tsdown.config.ts`) writes the npm build: `bin.js`, `rules.js`5 * and `protocol.js`, every workspace package inlined.6 * 2. tsgo declares the two library entries, workspace packages included,7 * and tsdown bundles that into `rules.d.ts` and `protocol.d.ts`.8 * 3. `bun build --compile` makes the standalone binary `bin/<cli>` for this9 * machine, or `bin/<target>/<cli>` for each of `--targets`. It embeds the10 * sdk and the rules' entry, each bundled whole, and hands their embedded11 * paths to `src/local/config-runtime.ts` before the CLI starts, so the12 * binary alone can bundle and evaluate a TypeScript config folder. For13 * each of `--targets`, the target's native packages (`build-targets.ts`)14 * are fetched from npm into a temp folder the compile resolves through15 * `NODE_PATH`: `bun install` left out every other machine's.16 * 4. Beside each binary, `git-credential-<slug>` links to it: the binary17 * sees the name it was started by (`src/bin.ts`), so the link is git's18 * credential helper.19 *20 * `--version <semver>` stamps both builds (`versionDefine`): it is what21 * the CLI's `--version` prints. Without it the build says `0.0.0`.22 *23 * A Bun script, outside every Worker's graph. Names come from `Brand`.24 * Importing it builds nothing (`tsdown.config.ts` and the tests read its25 * pure parts): only `bun build.ts` runs the build.26 */1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { Brand } from "@repo/brand";3import {4 Data,
18 unmodified lines
23 UNSTAMPED,24 versionDefine,25} from "./tsdown.config.ts";2653// The one define both bundlers get, kept beside tsdown's configs, which54// this module imports (lint refuses an import cycle).27// Re-exported: tsdown.config.ts defines it, as importing this module would be a cycle.28export { versionDefine } from "./tsdown.config.ts";2957/** What one build is asked for. */30export interface BuildOptions {59 /** Bun targets to cross-compile for, without `bun-`; none builds for this machine. */31 readonly targets: readonly string[];61 /** The version both builds are stamped with. */32 readonly version: string;33}3465/**66 * `bun build --compile`'s arguments for one binary: `entry` compiled to67 * `outfile`, for `target` (this machine when absent), stamped with `version`.68 */35export const compileArgs = (input: {36 readonly entry: string;37 readonly outfile: string;38 readonly target?: string;
16 unmodified lines
55 readonly step: string;56 readonly detail: string;57}> {}5893/** A tsconfig the build writes for one step. */59interface Tsconfig {60 readonly compilerOptions: {61 readonly declaration?: boolean;62 readonly emitDeclarationOnly?: boolean;63 readonly noCheck?: boolean;64 readonly noEmit?: boolean;65 readonly outDir?: string;101 /** Module names onto files: each workspace package's exports. */66 readonly paths: Readonly<Record<string, readonly string[]>>;67 readonly rootDir?: string;68 };69 readonly extends?: string;70 readonly files: readonly string[];71 readonly include?: readonly string[];72}73110/** What the build reads of a native package's manifest: its machines' packages. */74const NativeManifest = Schema.fromJsonString(75 Schema.Struct({76 optionalDependencies: Schema.Record(Schema.String, Schema.String),77 })78);79117/** What the build reads of a workspace package's manifest. */80const Manifest = Schema.fromJsonString(81 Schema.Struct({82 exports: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),83 name: Schema.String,84 })85);86125/**126 * Runs `command` with this terminal's output, in `cwd` and with `env` over127 * this process's own when given; any exit but 0 fails `step`.128 */87const run = (88 step: string,89 command: string,90 args: readonly string[],
23 unmodified lines
114 ),115 Effect.asVoid116 );117160/** tsdown over `config`, as one build step. */118const tsdown = (step: string, config: Parameters<typeof build>[0]) =>119 Effect.tryPromise({120 catch: (cause) => new BuildFailed({ detail: String(cause), step }),121 try: () => build(config),
6 unmodified lines
128 const root = yield* path.fromFileUrl(new URL(".", import.meta.url));129 const repo = path.join(root, "..", "..");130 const dist = path.join(root, "dist");131175 /**176 * `paths` that map every workspace package's exports, as its manifest177 * states them, onto `onto(file)` for each file they name.178 */132 const workspacePaths = (onto: (file: string) => string) =>133 Effect.gen(function* () {134 const packages = path.join(repo, "packages");135 const paths: Record<string, readonly string[]> = {};
18 unmodified lines
154155 return paths;156 });157205 /** Writes `config` as a tsconfig in `dir`, and gives its path. */158 const tsconfigIn = (dir: string, name: string, config: Tsconfig) =>159 Effect.as(160 fs.writeFileString(path.join(dir, name), JSON.stringify(config)),161 path.join(dir, name)162 );163212 // 1. The npm build, one entry at a time: the first cleans `dist/`.164 for (const config of npm(version)) {165 yield* tsdown(`tsdown ${Object.keys(config.entry).join(", ")}`, {166 ...config,167 config: false,168 cwd: root,169 });170 }171221 // 2. The library entries' types. tsgo declares them in a folder at a222 // fixed path, removed once the build ends: the bundled `.d.ts` files keep223 // each source's path in a comment, so a temp folder's random name would224 // make every build's types differ (and publish this machine's paths).172 // A fixed path, not a temp folder: the bundled .d.ts files keep each173 // source path in a comment, so a random name would change every build.174 const scratch = path.join(dist, ".types");175176 yield* Effect.acquireRelease(177 fs.makeDirectory(scratch, { recursive: true }),
1 unmodified line
179 );180181 const declared = path.join(scratch, "declared");182234 /** Where tsgo declares `file` (a source under the repo). */183 const declaration = (file: string) =>184 path.join(declared, path.relative(repo, file)).replace(/\.ts$/u, ".d.ts");185186 const emit = yield* tsconfigIn(scratch, "emit.json", {
34 unmodified lines
221 config: false,222 cwd: root,223 });224277 // 3. What the binary embeds for a TypeScript config folder: the sdk and278 // the rules' entry, each one file with effect inlined (a machine with279 // only the binary has no node_modules), and the entry `bun build280 // --compile` starts from, which hands their embedded paths over before281 // `src/bin.ts` runs (a module's imports run in order).225 // Bundled whole (a machine with only the binary has no node_modules);226 // runtime.ts sets their embedded paths before src/bin.ts runs.227 const compile = path.join(dist, ".compile");228229 yield* Effect.acquireRelease(230 fs.makeDirectory(compile, { recursive: true }),
34 unmodified lines
265 "",266 ].join("\n")267 );268324 /**325 * `node_modules` in a temp folder holding the native packages of326 * `target`'s machine, as each of `NATIVE` pins them: `bun install`327 * filtered them to this machine's. The versions are the installed328 * manifests' own exact pins.329 */269 /** `bun install` installed only this machine's native packages. */270 const nativeFor = (target: string) =>271 Effect.gen(function* () {272 const machine = yield* Effect.fromOption(npmMachineOf(target)).pipe(273 Effect.mapError(
42 unmodified lines
316317 return path.join(folder, "node_modules");318 });319380 // 4. The binaries, each with its credential helper link.320 const outputs =321 targets.length === 0322 ? [{ dir: path.join(dist, "bin"), target: Option.none<string>() }]323 : targets.map((target) => ({
40 unmodified lines
364 ),365 Flag.optional366);367429/** The build's command line, running `then` with what it asks for. */368const command = <E, R>(369 then: (options: BuildOptions) => Effect.Effect<void, E, R>370) =>371 Command.make("build", { targets, version }, (flags) =>
13 unmodified lines
385 "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."386 )387 );388451/**452 * The build's own `--version` takes a value, so effect/cli's built-in453 * `--version` (a boolean that prints and exits) is left out.454 */389// The build's `--version` takes a value, so effect/cli's boolean one is dropped.390const builtIns = CliConfig.make({391 builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Version),392});393459/** Runs `then` with what `argv`, the build's arguments, asks for. */394export const parseBuild = <E, R>(395 argv: readonly string[],396 then: (options: BuildOptions) => Effect.Effect<void, E, R>397) =>
11 unmodified lines
modified:apps/cli/tsdown.config.ts+3 added-30 removed
1/**2 * The npm build of the CLI, which `build.ts` runs first: `dist/bin.js`, the3 * command line under Node or Bun, and two library entries, `./rules` (the4 * sdk a config folder imports) and `./protocol` (the types its data has).5 * Workspace packages are inlined, so the published package names none of6 * them; `effect` and `@effect/platform-bun`, the package's own7 * dependencies, stay imports. Each entry is stamped with the version8 * `build.ts` is given (`npm`).9 */1import { defineConfig } from "tsdown";2import type { UserConfig } from "tsdown";313/** What a build no release stamped says it is (the release's `UNRELEASED`). */4export const UNSTAMPED = "0.0.0";516/**17 * What each bundler replaces so `cliVersion` (`src/version.ts`) reads18 * `version`: the expression it reads, onto the version as a string literal.19 * `build.ts` hands it to tsdown here (`npm`) and to every `bun build20 * --compile` (`compileArgs`).21 */6export const versionDefine = (version: string) => ({7 "import.meta.env.CLI_BUILD_VERSION": JSON.stringify(version),8});926/** The library entries, by the name each is published under. */10export const library = {11 protocol: "src/entries/protocol.ts",12 rules: "src/entries/rules.ts",13} as const;
11 unmodified lines
25 platform: "node",26} as const satisfies UserConfig;2728/**46 * The library entries' types, bundled from declarations `build.ts` has had47 * tsgo write (tsdown's own declaration step passes tsgo this package as its48 * `rootDir`, and TypeScript declares no file it reached through49 * `node_modules`, so every workspace package would be missing). `entry`50 * names each entry's declaration file; `tsconfig` maps each workspace51 * package onto its declarations, so they are inlined too.29 * Bundled from tsgo's declarations: tsdown's own step declares no file30 * reached through node_modules, so workspace packages would be missing.31 */32export const declarations = (33 entry: Readonly<Record<keyof typeof library, string>>,34 tsconfig: string35) =>36 ({37 ...shared,59 // The npm build wrote `dist/` first; this only adds to it.38 clean: false,39 dts: { dtsInput: true, emitDtsOnly: true, tsconfig },40 entry,41 }) satisfies UserConfig;4265/**66 * The npm build stamped with `version` (`src/version.ts`): one define for67 * all three entries, so they agree. `build.ts` builds them in order; only68 * the first cleans `dist/`, so a build one at a time keeps the others' files.69 */43// Only the first entry cleans `dist/`.44export const npm = (version: string) => {45 const stamped = { ...shared, define: versionDefine(version), dts: false };4647 return [
3 unmodified lines
51 { ...stamped, clean: false, entry: { pi: "src/pi.ts" } },52 ] satisfies UserConfig[];53};5481/** `tsdown` run here by hand builds what no release stamped. */55export default defineConfig(npm(UNSTAMPED));
modified:packages/checks/src/check-runner/local.ts+5 added-21 removed
1/**2 * `CheckRunner` as real processes on this machine, for the CLI's `check`:3 * each job gets a checkout from the caller (the CLI makes a git worktree), and4 * each lane runs there under `sh -c`, one after another, to its time limit.5 *6 * It reaches nothing a lane would not: no network of its own, no git config7 * from this machine (`GIT_CONFIG_GLOBAL=/dev/null`, as `@repo/testkit/git`8 * runs git), no repo but the checkout (a hook's `GIT_DIR` is unset), and a9 * `HOME` in a temp dir it removes after the job. Placeholders10 * and proxies are the Checker's; here a lane sees the user's own env. A sealed11 * suite runs only in the Checker, so a job with one is `VerifierBlocked`.12 * A count lane (`output: "stdout"`) hands back what it printed, as the13 * Checker's does.14 */1// Placeholders and proxies are the Checker's: here a lane sees the user's own2// env. A sealed suite runs only in the Checker, so a job with one is3// `VerifierBlocked`.4import { VerifierBlocked } from "@repo/protocol/refusal";5import { Duration, Effect, FileSystem, Layer, Option, Stream } from "effect";6import type { Scope } from "effect";7import { ChildProcess, ChildProcessSpawner } from "effect/process";
3 unmodified lines
11import { classifyRun } from "../classify.ts";12import type { RunExit } from "../classify.ts";1314export interface LocalOptions {26 /** Makes the job's tree a directory, removed when the scope closes. */15 readonly checkout: (16 at: CheckAt17 ) => Effect.Effect<string, VerifierBlocked, Scope.Scope>;18}1932/** A lane with no time limit of its own gets ten minutes. */20const DEFAULT_TIMEOUT = Duration.minutes(10);2135/** After the time limit's SIGTERM, how long a lane has before SIGKILL. */22const FORCE_KILL_AFTER = Duration.seconds(2);2324// Fixed identity and dates, English messages, no prompts, no colours, and no25// git config from this machine. A git hook that runs the CLI exports where
30 unmodified lines
56 bytes.pipe(Stream.decodeText(), Stream.mkString);5758const timedOut: RunExit = { code: -1, stderr: "", stdout: "", timedOut: true };5974// A count lane that ran to its end hands back its stdout, which its count is75// read from; any other lane's output goes nowhere.60const printed = (lane: CheckLane, exit: RunExit): readonly LaneOutput[] =>61 lane.output === "stdout" && exit.timedOut !== true62 ? [{ lane: lane.lane, stdout: exit.stdout }]63 : [];
11 unmodified lines
75 Effect.gen(function* () {76 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;77 const fs = yield* FileSystem.FileSystem;7895 // One lane to its end or its time limit. A process a signal ended96 // has no exit code: -1. The scope's close kills its process group.79 // A process a signal ended has no exit code: -1. The scope's close kills its80 // process group.81 const exitOf = (cwd: string, home: string, lane: CheckLane) =>82 Effect.scoped(83 Effect.gen(function* () {84 const child = yield* spawner.spawn(
85 unmodified lines
modified:packages/checks/src/check-runner/memory.ts+2 added-19 removed
1/**2 * `CheckRunner` from a script, for tests: each `(tree or commit, lane)` gets3 * its scripted results in order, and the last one again once they run out.4 * A pair with no script is `VerifierBlocked`, as a Checker that cannot run is.5 * A count lane (`output: "stdout"`) prints what `outputs` scripts for its6 * pair, a linter's JSON as it was recorded, and nothing when none is.7 */1import type { LaneResult } from "@repo/protocol/domain/answer";2import type { LaneName } from "@repo/protocol/ids";3import { VerifierBlocked } from "@repo/protocol/refusal";4import { Array, Effect, Layer, Option, Ref } from "effect";56import { CheckRunner, shaOf } from "../check-runner.ts";7import type { CheckAt, LaneEvidence, LaneOutput } from "../check-runner.ts";816/** Where a lane's script lives in the map: `<tree or commit sha>:<lane>`. */9export const scriptKey = (at: CheckAt, lane: LaneName) =>10 `${shaOf(at)}:${lane}`;1120/**21 * A scripted lane has no output to read, so a scripted failure counts as one22 * assertion failing the same way every time: two of them on main are red23 * first. Any other result that is not a pass leaves no signature.24 */12// A scripted failure counts as one assertion failing the same way every time.13const evidenceOf = ({ lane, result }: LaneResult): LaneEvidence =>14 result === "failed"15 ? { lane, signature: `${lane}: scripted failure` }16 : { lane };1718export const CheckRunnerMemory = {31 /**32 * `script` holds each pair's results; `outputs`, read when a job runs (so33 * a test may add to it later), the stdout each count lane prints, by the34 * same key.35 */19 // `outputs` is read when a job runs, so a test may add to it later.20 layer: (21 script: ReadonlyMap<string, readonly LaneResult[]>,22 outputs: ReadonlyMap<string, string> = new Map()23 ): Layer.Layer<CheckRunner> =>24 Layer.effect(25 CheckRunner,26 Effect.gen(function* () {43 // How many results each key has served.27 const served = yield* Ref.make<ReadonlyMap<string, number>>(new Map());2829 const next = (30 key: string,
60 unmodified lines
modified:packages/checks/src/check-runner/wire.ts+1 added-17 removed
1/**2 * What crosses the service binding between the platform and the sandbox3 * Worker for a check: the job, with the one remote the Checker clones from,4 * and the run's outcome on the way back. Both sides decode with these5 * schemas (principle 2): the platform encodes the job and decodes the6 * outcome; the sandbox does the reverse.7 */1import { VerifierBlocked } from "@repo/protocol/refusal";2import { Schema } from "effect";34import { CheckJob, CheckRun } from "../check-runner.ts";513/**14 * Where a sandbox job reaches one repo: its git URL and a token the platform15 * minted for this job alone. The token is redacted wherever it is printed,16 * and a Checker's never enters its container: the outbound handler adds it.6// The token never enters a Checker's container: the outbound handler adds it.17 */7export const Remote = Schema.Struct({8 token: Schema.RedactedFromValue(Schema.String),9 url: Schema.NonEmptyString,10});1112export type Remote = typeof Remote.Type;1325/** A check job as the platform sends it: the job and a read token for its repo. */14export const CheckWire = Schema.Struct({ clone: Remote, job: CheckJob });1516export type CheckWire = typeof CheckWire.Type;1730/**31 * A check's outcome as it comes back: the run, `VerifierBlocked`, or a32 * defect, as JSON.33 */18export const CheckExit = Schema.toCodecJson(19 Schema.Exit(CheckRun, VerifierBlocked, Schema.Defect())20);
modified:packages/checks/src/evidence-store/memory.ts-6 removed
1/**2 * `EvidenceStore` in memory: it keeps each log under its name and records3 * every `put` in order, so a test can assert what a run kept.4 */1import { Context, Effect, Layer, Option, Ref } from "effect";23import { EvidenceStore, logRefOf } from "../evidence-store.ts";4import type { LaneLog } from "../evidence-store.ts";510/** Every log the memory store was given, in order, replays included. */6export class EvidenceKept extends Context.Service<7 EvidenceKept,8 { readonly puts: Effect.Effect<readonly LaneLog[]> }9>()("checks/EvidenceKept") {}1016/** A fresh, empty store each time the layer is built, and its record. */11export const EvidenceStoreMemory: Layer.Layer<EvidenceStore | EvidenceKept> =12 Layer.effectContext(13 Effect.gen(function* () {14 const puts = yield* Ref.make<readonly LaneLog[]>([]);
19 unmodified lines
modified:packages/checks/src/evidence-store/r2.ts+1 added-19 removed
1/**2 * `EvidenceStore` over an R2 bucket: the stage's `evidence-<stage>`,3 * so a lane's log outlives the isolate that ran its check. Each log4 * is one object, its key the log's own name (`logRefOf`), its body the text5 * whole, labelled with its project and lane and nothing else. Putting a log6 * again under the same name replaces it, so a replayed step converges7 * (principle 8).8 *9 * R2 is reached only through promises; each enters through10 * `Effect.tryPromise`, and a bucket that cannot be reached is a defect that11 * names the key, never the text: a log is for its readers alone.1// A failure names the key, never the text: a log is for its readers alone.12 */2import { Data, Effect, Layer, Option } from "effect";34import { EvidenceStore, logRefOf } from "../evidence-store.ts";517/**18 * The part of an R2 bucket binding the store uses. Structural, so the Worker19 * passes its `EVIDENCE` binding itself; a type test holds `R2Bucket` to it20 * (`apps/platform/test/evidence.test.ts`).21 */6export interface EvidenceBucket {7 readonly put: (8 key: string,9 value: string,
6 unmodified lines
16 key: string17 ) => Promise<{ readonly text: () => Promise<string> } | null>;18}1936/** R2 refused or never answered a call on one key: the store cannot go on. */20class EvidenceUnreachable extends Data.TaggedError("EvidenceUnreachable")<{21 readonly message: string;22 readonly cause: unknown;23}> {}2442/** One call on the bucket for `key`; a failure dies naming the key and the call. */25const reach = <A>(call: "get" | "put", key: string, run: () => Promise<A>) =>26 Effect.orDie(27 Effect.tryPromise({28 catch: (cause) =>
39 unmodified lines
modified:packages/checks/src/kinds/lint-count.ts+5 added-50 removed
1/**2 * Lint counts: how many findings a project's own linter reports, read from3 * the JSON it prints (oxlint's `--format json` or ESLint's `--format json`),4 * per path, for one rule or all, within a territory. Pure: the linter runs5 * elsewhere, and this reads what it printed, exactly as it printed it.6 */1import type { Glob } from "@repo/protocol/domain/common";2import { RepoPath } from "@repo/protocol/ids";3import { Option, Order, Result, Schema } from "effect";45import { matchGlob } from "../judge.ts";613/** The JSON a linter prints: oxlint's report object, or ESLint's array of files. */7export type LintFormat = "oxlint" | "eslint";816/** A lint count: the findings in all, and per repo path (only paths with any). */9export interface LintCount {10 readonly total: number;11 readonly byPath: ReadonlyMap<RepoPath, number>;12}1322/** How much of an unreadable output a `CountUnreadable` keeps. */14const HEAD_LENGTH = 200;1525/**26 * A counter's output held no count the platform can read: not JSON, not the27 * shape its format prints, or no integer where a metric's path points. It28 * keeps the output's first 200 characters, so the answerer and the deciders29 * see what the command printed instead.30 */16export class CountUnreadable extends Schema.TaggedError<CountUnreadable>()(17 "CountUnreadable",18 { head: Schema.String }19) {20 static readonly of = (output: string) =>21 new CountUnreadable({ head: output.slice(0, HEAD_LENGTH) });22}2339// `oxlint --format json`: one object; each diagnostic names its file and,40// unless it is a parse error or a directive report, its rule as41// `plugin(rule)`.24// A parse error or directive report carries no rule.25const OxlintReport = Schema.Struct({26 diagnostics: Schema.Array(27 Schema.Struct({28 code: Schema.optionalKey(Schema.String),
1 unmodified line
30 })31 ),32});3351// `eslint --format json`: one entry per file, each with its messages; a52// parse error or a directive report has a null `ruleId`.34// A parse error or directive report has a null `ruleId`.35const EslintReport = Schema.Array(36 Schema.Struct({37 filePath: Schema.NonEmptyString,38 messages: Schema.Array(
3 unmodified lines
42 ),43 })44);4564/** One finding: the file it is in, and the rule that reported it, if one did. */46interface Finding {47 readonly path: string;48 readonly rule: Option.Option<string>;49}
21 unmodified lines
71 }))72 )73 );7494/**95 * A rule, as either tool or a maintainer writes it: oxlint's code form96 * `typescript(no-explicit-any)`, a config's `typescript/no-explicit-any`,97 * ESLint's `@typescript-eslint/no-explicit-any`, or a bare `no-debugger`.98 * `plugin` is `None` for a bare name.99 */75interface RuleName {76 readonly plugin: Option.Option<string>;77 readonly name: string;78}79105// `plugin(rule)`, oxlint's code form.80const CODE_FORM = /^(?<plugin>[^()]+)\((?<name>[^()]+)\)$/u;8182// The core rules' plugin: oxlint prints them as `eslint(no-debugger)`, ESLint83// as a bare `no-debugger`.
24 unmodified lines
108 plugin: Option.some(pluginOf(written.slice(0, slash))),109 };110};111138/**139 * Whether a finding's rule is the one asked for. A bare name asks for that140 * rule in any plugin (`no-explicit-any` counts typescript's); a finding's141 * bare name is a core rule. A finding with no rule (a file the linter could142 * not parse, an unused directive) is counted only when no rule is asked for.143 */112// A bare name asks for that rule in any plugin; a finding with no rule is113// counted only when no rule is asked for.114const isRule =115 (wanted: RuleName) =>116 (finding: Finding): boolean =>117 Option.match(finding.rule, {
11 unmodified lines
129 );130 },131 });132163/** A path relative to the repo: without `root`'s prefix and any leading `./`. */133const repoPathOf = (path: string, root: Option.Option<string>): string => {134 const inside = Option.match(root, {135 onNone: () => path,136 onSome: (dir) => {
9 unmodified lines
146};147148const EXCLUDE = "!";149181/** Whether a path is in a territory: some glob matches it, and no `!` glob takes it back. */150const within = (territory: readonly Glob[], path: string) =>151 territory.some(152 (glob) => !glob.startsWith(EXCLUDE) && matchGlob(glob, path)153 ) &&
4 unmodified lines
158159const totalOf = (byPath: ReadonlyMap<RepoPath, number>) =>160 [...byPath.values()].reduce((sum, count) => sum + count, 0);161194/**195 * The part of a count inside a territory: the paths its globs match, with196 * `!` globs taking paths back out. One linter run counted once serves every197 * territory a ratchet keeps a baseline for.198 */162export const countWithin = (163 count: LintCount,164 territory: readonly Glob[]165): LintCount => {
3 unmodified lines
169170 return { byPath, total: totalOf(byPath) };171};172210/** The format an output is in, by its JSON's shape: an array is ESLint's. */173const detect = (output: string): LintFormat =>174 output.trimStart().startsWith("[") ? "eslint" : "oxlint";175214/**215 * Counts a linter's findings from its JSON output, per repo path. `rule`216 * keeps one rule's (in either tool's spelling); `territory` keeps the paths217 * its globs match (with `!` taking paths back out); `root` is stripped from218 * the front of each path, since ESLint prints absolute ones. The format is219 * read from the output when not given. Output it can't read, in the format220 * given or detected, is a `CountUnreadable`, never a thrown error.221 */176// `root` is stripped since ESLint prints absolute paths.177export const countLint = (input: {178 readonly output: string;179 readonly format?: LintFormat | undefined;180 readonly rule?: string | undefined;
38 unmodified lines
modified:packages/checks/src/kinds/lint-to-zero.ts+2 added-17 removed
1/**2 * The `lintToZero` check kind: a lint rule's count in a territory is the3 * test. It is red while the rule reports anything there and green at zero,4 * so an ask of this kind fails on main by the count itself. The count5 * comes from `countLint`, with the rule and territory already applied.6 */1import { RatchetMeasure } from "@repo/protocol/domain/check";2import type { CheckSpec, RatchetSpec } from "@repo/protocol/domain/check";3import type { Territory } from "@repo/protocol/domain/territory";4import { RatchetName } from "@repo/protocol/ids";
1 unmodified line
67import type { CountUnreadable, LintCount } from "./lint-count.ts";8import { measure } from "./ratchet.ts";916/** Red: the rule still reports something in the territory. */10export const lintToZeroRed = (count: LintCount): boolean => count.total > 0;1119/** Green: the rule reports nothing in the territory. */12export const lintToZeroGreen = (count: LintCount): boolean => count.total === 0;1322/** A `lintToZero` check. */14export type LintToZeroCheck = Extract<15 CheckSpec,16 { readonly _tag: "LintToZero" }17>;1828/** The name a `lintToZero` check's count goes by in `measure`. */19const countName = RatchetName.make("lint-to-zero");2031/**32 * What a `lintToZero` check counts in what its lint printed: the rule's33 * findings in the check's territory (a module by its name, else the name34 * read as a glob), or in `asked`, the ask's own territory, when the check35 * names none. Read by `measure`, as a ratchet's count is, so the two never36 * read a lint differently; the lint's exit code is not read.37 */21// Read through `measure`, as a ratchet's count is, so the two never read a22// lint differently.23export const lintToZeroCount = (input: {24 readonly asked: Territory;25 readonly check: LintToZeroCheck;26 readonly modules: readonly Territory[];
21 unmodified lines
modified:packages/checks/src/kinds/metric.ts+1 added-15 removed
1/**2 * A ratchet's metric: one integer a project's own command prints in its JSON,3 * found by a small JSONPath (`$`, `.key`, `[index]`, nothing more). Pure: the4 * command runs elsewhere, and this reads what it printed.5 */1// A JSONPath subset: `$`, `.key` and `[index]`, nothing more.2import type { JsonPath } from "@repo/protocol/domain/common";3import { Option, Predicate, Result, Schema } from "effect";45import { CountUnreadable } from "./lint-count.ts";611/** One step down a JSON value: an object's key, or an array's index. */7type Step = string | number;814// One step at the start of what is left of a path: `.key` or `[index]`.9const STEP = /^(?:\.(?<key>[\w$-]+)|\[(?<index>\d+)\])/u;1017/** A path's steps, or `None` when it leaves the supported subset. */11const stepsOf = (path: string): Option.Option<readonly Step[]> => {12 if (!path.startsWith("$")) {13 return Option.none();14 }
22 unmodified lines
3738const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>39 Predicate.isObject(value);4048/** The value one step down, if the value has it: a key on an object, an index on an array. */41const down = (value: Schema.Json, step: Step): Option.Option<Schema.Json> => {42 if (Predicate.isNumber(step)) {43 return isJsonArray(value)44 ? Option.fromNullishOr(value[step])
4 unmodified lines
49 ? Option.fromNullishOr(value[step])50 : Option.none();51};5261/** The value at the end of a path's steps, if the value has every one. */53const walk = (54 value: Schema.Json,55 steps: readonly Step[]56): Option.Option<Schema.Json> => {
8 unmodified lines
6566const isCount = (value: Schema.Json): value is number =>67 Predicate.isNumber(value) && Number.isSafeInteger(value);6878/**79 * The integer at `path` in a command's JSON output. Output that isn't JSON,80 * a path outside the subset, a path the output lacks, or anything there but81 * an integer is a `CountUnreadable` holding the output's head.82 */69export const readMetric = (70 output: string,71 path: JsonPath72): Result.Result<number, CountUnreadable> =>
8 unmodified lines
modified:packages/checks/src/kinds/ratchet.ts+4 added-51 removed
1/**2 * The `ratchet` check kind: the lanes that count a project's ratchets, the3 * measure that reads a ratchet's declared command's output as its number4 * per territory, exactly as the project's own tool reports it, and the5 * judgement of an answer's counts against the counts it is held to. A lint6 * count splits by path, so it yields one count per territory (per-territory7 * baselines, so the children of a split land on their own); a8 * metric is one number, so it yields one. The command runs through the9 * runner it is given, never here. The platform's cheap stage and the Project10 * DO, and `<cli> check` before a push, all count and judge through here.11 */1import { RatchetMeasure } from "@repo/protocol/domain/check";2import type { RatchetSpec } from "@repo/protocol/domain/check";3import { Glob } from "@repo/protocol/domain/common";4import { DecisionSubject } from "@repo/protocol/domain/decision";
7 unmodified lines
12import { countLint, countWithin } from "./lint-count.ts";13import type { CountUnreadable } from "./lint-count.ts";14import { readMetric } from "./metric.ts";1527/** A ratchet's number in one territory, as one run measured it. */16export interface RatchetCount {17 readonly ratchet: RatchetName;18 readonly territory: string;19 readonly count: number;20}2134/**35 * The territory a ratchet counts when it names none and the project has no36 * modules, and the one a metric counts when it names none: the whole project,37 * named as a single-package repo's module is.38 */22export const WHOLE_PROJECT = ".";2341/** A territory a count is split by: its name, and the globs of its paths. */24interface Counted {25 readonly name: string;26 readonly paths: readonly Glob[];27}2829const ALL_PATHS: readonly Glob[] = [Glob.make("**")];3049/**50 * A territory a spec names: a module by its name, or else the name read as a51 * glob, as the gate reads a ratchet's territory.52 */31const named = (32 territories: readonly Territory[],33 territory: string34): Counted => ({
2 unmodified lines
37 Glob.make(territory),38 ],39});4063/** The territories a spec's count is split by. */41const countedIn = (42 spec: RatchetSpec,43 territories: readonly Territory[]44): readonly Counted[] => {
5 unmodified lines
50 ? [{ name: WHOLE_PROJECT, paths: ALL_PATHS }]51 : territories.map(({ module, paths }) => ({ name: module, paths }));52};5377/**78 * Runs a ratchet's command once and reads its count per territory. A `Count`79 * reads the linter's JSON (oxlint's or ESLint's, detected; `root` makes80 * absolute paths repo-relative) for the spec's rule and yields one count per81 * territory: the one the spec names, else each module, else the whole82 * project. A `Metric` reads one integer at its path and yields one count, for83 * the territory the spec names or the whole project. The command's exit code84 * is not read (a linter with findings exits 1); output with no count in it85 * fails with `CountUnreadable`.86 */54// The command's exit code is not read: a linter with findings exits 1.55export const measure = <E, R>(56 spec: RatchetSpec,57 run: (58 command: string
31 unmodified lines
90 ])91 ),92 });93126/**127 * The lanes that count `ratchets`: one per command, named for the first128 * ratchet that runs it, each handing back what it printed for `measure` to129 * read (a lint's exit code says nothing of its count).130 */94export const countLanes = (95 ratchets: readonly RatchetSpec[]96): readonly CheckLane[] =>97 Array.dedupeWith(
4 unmodified lines
102 lane: LaneName.make(name),103 output: "stdout",104 }));105143/** A ratchet in a territory: the key a baseline, a count and a raise are kept by. */106export interface RatchetKey {107 readonly ratchet: RatchetName;108 readonly territory: string;109}110149/** Whether two rows name one ratchet in one territory. */111export const sameRatchet =112 (one: RatchetKey) =>113 (other: RatchetKey): boolean =>114 one.ratchet === other.ratchet && one.territory === other.territory;115155/** The decision a raise waits on. */116export type RaiseRatchet = Extract<DecisionSubject, { _tag: "RaiseRatchet" }>;117158/** What judging an answer's counts gives: its refusals, and the raises it waits on. */118export interface RatchetJudgement {119 readonly refusals: readonly Weakened[];120 readonly decisions: readonly RaiseRatchet[];121}122164/**165 * Judges an answer's counts against the counts it is held to (the Project166 * DO's baselines; on a person's machine, the counts on the answer's base). A167 * count at or under its baseline passes; one over it is refused with168 * `Weakened{ratchet}`, unless the answer asks to raise that ratchet in that169 * territory: then it is not refused, and waits on a `RaiseRatchet` decision170 * instead. A ratchet with no baseline yet is not judged (its first landing171 * sets it).172 */123// A count over its baseline is refused unless the answer asks to raise that124// ratchet, which then waits on a `RaiseRatchet` decision. A ratchet with no125// baseline yet is not judged: its first landing sets it.126export const judgeRatchets = (input: {127 readonly baselines: readonly RatchetCount[];128 readonly measured: readonly RatchetCount[];129 readonly ask: AskId;
40 unmodified lines
modified:packages/checks/src/check-runner.ts+9 added-85 removed
1/**2 * The `CheckRunner` port: the one way the platform and the CLI run3 * a project's lanes on a tree. `CheckJob` and `CheckRun` are schemas because4 * they cross the sandbox's entrypoint, decoded on both sides.5 * Adapters: `/memory` (scripted, for tests) and `/local` (real processes in a6 * checkout, for the CLI's `check`); the Checker's lives in `apps/platform`.7 */1import { HeldBackResult, LaneResult } from "@repo/protocol/domain/answer";2import { RunBlock } from "@repo/protocol/domain/run";3import {4 AreaName,
12 unmodified lines
1718import { diagnose, Diagnosis } from "./classify.ts";19import type { RunExit } from "./classify.ts";2028/**29 * What a job runs on: an exact tree (an answer merged onto main) or a30 * commit (main itself, when an ask opens).31 */21export const CheckAt = Schema.TaggedUnion({22 Commit: { commit: CommitSha },23 Tree: { tree: TreeSha },24});2526export type CheckAt = typeof CheckAt.Type;2739/** The object id a job runs on, whichever kind it is. */28export const shaOf = (at: CheckAt): string =>29 CheckAt.match(at, {30 Commit: ({ commit }): string => commit,31 Tree: ({ tree }): string => tree,32 });3346/**47 * One lane to run: its name, the project's command for it, and its time48 * limit. A lane with `output: "stdout"` is a count (a lint rule's or a49 * ratchet's), read from what its command prints: the run hands its stdout50 * back in `CheckRun.outputs`, to the platform alone, never to an answerer.34// A count lane's stdout goes back to the platform alone, never to an answerer.51 */35export const CheckLane = Schema.Struct({36 command: Schema.NonEmptyString,37 lane: LaneName,38 output: Schema.optionalKey(Schema.Literal("stdout")),
3 unmodified lines
42});4344export type CheckLane = typeof CheckLane.Type;4563/**64 * One sealed file, as the platform read it from the layer at the pinned65 * commit: its path in the checked tree, its area, and its bytes. On the66 * wire the bytes are base64 (`contentBase64`), decoded to bytes where the67 * job is decoded, before the Checker writes them.68 */46// On the wire the bytes are base64 (`contentBase64`).47export const HeldBackFile = Schema.Struct({48 area: AreaName,49 content: Schema.Uint8ArrayFromBase64,50 path: RepoPath,51}).pipe(Schema.encodeKeys({ content: "contentBase64" }));5253export type HeldBackFile = typeof HeldBackFile.Type;5477/** One sealed check to run: its area, its file, and the command that runs it. */55export const HeldBackCheck = Schema.Struct({56 area: AreaName,57 command: Schema.NonEmptyString,58 path: RepoPath,59});6061export type HeldBackCheck = typeof HeldBackCheck.Type;6286/**87 * A sealed suite's part of a job: the layer's files88 * under the sealed areas and one run per sealed check, all read by the89 * platform at the commit the claim was pinned to. No layer repo, route or90 * token is named: the sandbox never reaches the layer.91 */63// Names no layer repo, route or token: the sandbox never reaches the layer.64export const HeldBackPart = Schema.Struct({65 areas: Schema.Array(AreaName),94 /** The layer commit the suite was pinned at. */66 at: CommitSha,67 files: Schema.Array(HeldBackFile),68 runs: Schema.Array(HeldBackCheck),69 suite: SuiteRoot,70});7172export type HeldBackPart = typeof HeldBackPart.Type;73103/**104 * What a run sees in place of one write-only value: its item's key, set in105 * every command's env to the placeholder. The platform makes106 * the placeholder (`@repo/visibility/proxy`'s `placeholderFor`); the sandbox107 * only sets it.108 */74export const EnvPlaceholder = Schema.Struct({75 key: EnvKey,76 placeholder: Schema.NonEmptyString,77});7879export type EnvPlaceholder = typeof EnvPlaceholder.Type;80116/**117 * One outbound host of a `@proxy` item, as `@repo/visibility/proxy`'s118 * `ProxyRule` crosses the wire: HTTPS requests to `host` (a glob119 * stays one) go through the Checker's env gateway, which lets out only those120 * whose path matches `path` and whose method is `method` (any, when absent),121 * none when `block`, and, in a run of landed code alone, swaps `placeholder`122 * for the value of `key` in the request's headers.123 */81// `placeholder` is swapped for the value of `key` only in a run of landed code.82export const EnvProxy = Schema.Struct({83 block: Schema.Boolean,84 host: Schema.NonEmptyString,85 key: EnvKey,
3 unmodified lines
89});9091export type EnvProxy = typeof EnvProxy.Type;92135/**136 * One write-only value, opened by the platform for a run of landed code137 * (`ProjectEnv.runEnv(…, landed: true)`). Redacted wherever it is printed;138 * the sandbox hands it only to its env gateway, never to the container.93// The sandbox hands it only to its env gateway, never to the container.139 */94export const EnvValue = Schema.Struct({95 key: EnvKey,96 value: Schema.RedactedFromValue(Schema.NonEmptyString),97});9899export type EnvValue = typeof EnvValue.Type;100147/**148 * A request to run lanes on one tree of one project's repo. Only a job of149 * landed code carries values: a job that is not `landed` and carries any150 * does not decode, nor encode.151 */101// A job that is not `landed` and carries values neither decodes nor encodes.102export const CheckJob = Schema.Struct({103 at: CheckAt,154 /** The sealed suite, from the layer at its pinned commit. */104 heldBack: Schema.optionalKey(HeldBackPart),156 /** Whether the job runs landed code. Absent, it does not. */105 landed: Schema.optionalKey(Schema.Boolean),106 lanes: Schema.Array(CheckLane),159 /** What the run sees, in place of each write-only value. */107 placeholders: Schema.Array(EnvPlaceholder),108 project: ProjectName,162 /** The outbound hosts whose requests go through the platform's env gateway. */109 proxies: Schema.Array(EnvProxy),110 repo: RepoName,165 /**166 * The project's run block at the policy the job was made under: how the167 * Checker sets up (`setup`, `setupEgress`, `image`). The Checker never168 * guesses a project's setup.169 */111 run: RunBlock,171 /** The values the env gateway swaps in, for a job of landed code only. */112 values: Schema.optionalKey(Schema.Array(EnvValue)),113}).check(114 Schema.makeFilter(({ landed, values }) =>115 values === undefined || landed === true
3 unmodified lines
119);120121export type CheckJob = typeof CheckJob.Type;122183/**184 * What a lane that did not pass leaves for comparing runs without logs: its185 * failure signature when it failed on assertions, and `no assertion` when it186 * found no tests at all.187 */123export const LaneEvidence = Schema.Struct({124 lane: LaneName,125 signature: Schema.optionalKey(Schema.NonEmptyString),126 weakness: Schema.optionalKey(Schema.Literal("no assertion")),127});128129export type LaneEvidence = typeof LaneEvidence.Type;130196/** A lane's evidence, read from its exit where the run happened. */131export const evidenceFrom = (lane: LaneName, exit: RunExit): LaneEvidence =>132 Diagnosis.$match(diagnose(exit), {133 Blocked: () => ({ lane }),134 Failed: ({ signature }) =>
5 unmodified lines
140 NoTests: () => ({ lane, weakness: "no assertion" as const }),141 Passed: () => ({ lane }),142 });143210/** What a count lane printed: the stdout its count is read from. */144export const LaneOutput = Schema.Struct({145 lane: LaneName,146 stdout: Schema.String,147});148149export type LaneOutput = typeof LaneOutput.Type;150218/**219 * One job's result: each lane, the held-back areas' bits, the whole run's220 * time, and the evidence of every lane that did not pass. Logs never travel221 * here; a lane's `logRef` names where the platform keeps its log. A count222 * lane's stdout does, in `outputs` (one per lane that asked for it), since223 * its count is read from it.224 */151// Logs never travel here; a lane's `logRef` names where the platform keeps them.152export const CheckRun = Schema.Struct({153 durationMs: Schema.Int,154 evidence: Schema.Array(LaneEvidence),155 heldBack: Schema.Array(HeldBackResult),
2 unmodified lines
158});159160export type CheckRun = typeof CheckRun.Type;161235/** What a count lane of `run` printed; none when the lane did not ask for it, or did not run. */162export const outputOf = (163 run: CheckRun,164 lane: LaneName165): Option.Option<string> =>
1 unmodified line
167 Option.fromUndefinedOr(run.outputs?.find((each) => each.lane === lane)),168 ({ stdout }) => stdout169 );170245/**246 * Runs a job's lanes. `VerifierBlocked` means the run could not happen at all247 * (no checkout, no script for it): the gate's trouble, never the answer's.248 */171// `VerifierBlocked` means the run could not happen at all: the gate's172// trouble, never the answer's.173export class CheckRunner extends Context.Service<174 CheckRunner,175 {176 readonly run: (job: CheckJob) => Effect.Effect<CheckRun, VerifierBlocked>;
2 unmodified lines
modified:packages/checks/src/classify.ts+4 added-40 removed
1/**2 * Red for the right reason: what one run of a lane says happened.3 * A failure by an assertion is told apart from a run that never got that4 * far (a load or compile error, or no tests at all), from the runner's JSON5 * report where there is one and from its output otherwise.6 */1import type { LaneOutcome } from "@repo/protocol/domain/answer";2import type { LaneName } from "@repo/protocol/ids";3import { Array, Data, Option, Order, pipe, Schema, String } from "effect";411/** How one lane's command ended, as the runner saw it. */5export interface RunExit {6 /** The exit code; negative when the process had none (a signal ended it). */7 readonly code: number;8 readonly stdout: string;9 readonly stderr: string;17 /** The runner's JSON report, when it wrote one (vitest's `--reporter=json`). */10 readonly report?: unknown;19 /** The runner was stopped at the lane's time limit. */11 readonly timedOut?: boolean;12}1323/**24 * What one run says happened. `Failed` carries the failing tests' signature25 * when every failure was an assertion's; a test that threw anything else26 * (`TypeError: parseWeek is not a function`) failed with none.27 */14export type Diagnosis =15 | { readonly _tag: "Blocked" }16 | { readonly _tag: "Failed"; readonly signature: Option.Option<string> }17 | { readonly _tag: "LoadError" }
1 unmodified line
19 | { readonly _tag: "Passed" };2021export const Diagnosis = Data.taggedEnum<Diagnosis>();2237// The fields of vitest's JSON report (jest's shape) that tell what happened.23// A file that failed with a message and collected no tests failed to load.24const VitestReport = Schema.Struct({25 numTotalTests: Schema.Finite,26 testResults: Schema.Array(
14 unmodified lines
41type VitestReport = typeof VitestReport.Type;4243const decodeReport = Schema.decodeUnknownOption(VitestReport);4460/** A line that reports a failed assertion: chai's, node's, jest's and bun's `expect`, pytest's `assert`. */45const ASSERTION =46 /AssertionError|^E\s+assert\b|^(?:error: |Error: )?expect\(|^Snapshot .+ mismatched/u;4764/** The details jest and bun print under an `expect(received)` line. */48const EXPECTATION_DETAIL = /^(?:Expected|Received)\b/u;4967/** The output of a run that never reached its tests. */50const LOAD_ERROR = [51 /Cannot find (?:module|package)/u,52 /ERR_MODULE_NOT_FOUND/u,53 /Failed to load url/u,
1 unmodified line
55 /\b(?:ModuleNotFound|Import)Error\b/u,56 /Transform failed/u,57];5877/** The output of a run that found no tests: vitest's, bun's or jest's, pytest's, node's. */59const NO_TESTS = [60 /No test files found/u,61 /did not match any test files|No tests found/u,62 /\bno tests ran\b/u,63 /^ℹ tests 0$/mu,64];6585/** A line naming a failed test: bun's `(fail)`, pytest's `FAILED`, vitest's `FAIL`. */66const FAILED_TEST = [67 /^\(fail\) (?<name>.+)$/u,68 /^FAILED (?<name>\S+)/u,69 /^FAIL\s+(?<name>.+)$/u,
13 unmodified lines
83const BRACKETED_DURATION = /\s*[[(]\d+(?:\.\d+)?\s?m?s[\])]/gu;8485const DURATION = /\b\d+(?:\.\d+)?\s?m?s\b/gu;86107/** Without the parts that change between two runs of the same failure. */87const normalise = (text: string) =>88 text89 .replaceAll(ANSI, "")90 .replaceAll(ADDRESS, "<address>")
7 unmodified lines
9899const signatureOf = (entries: readonly string[]) =>100 Array.dedupe(entries).toSorted(Order.String).join("\n");101123/** The first assertion line, with jest's and bun's `Expected:`/`Received:` lines under it. */102const assertionOf = (lines: readonly string[]) =>103 Option.map(104 Array.findFirstIndex(lines, (line) => ASSERTION.test(line)),105 (at) => {
89 unmodified lines
195// the shell's 128+n for a process a signal killed.196const neverRan = (code: number) =>197 code < 0 || code === 126 || code === 127 || (code > 128 && code < 160);198221/**222 * What one run says happened. A run stopped at its time limit, or one whose223 * command never ran, is `Blocked`: the verifier's trouble, not the answer's.224 * Otherwise exit 0 is `Passed` whatever the report says (a run with225 * `--passWithNoTests` found none and passed), and a failure is read from the226 * report, or from the output when there is none.227 */199// A timeout or a command that never ran is `Blocked`, the verifier's trouble.200// Exit 0 is `Passed` whatever the report says (`--passWithNoTests`).201export const diagnose = (exit: RunExit): Diagnosis => {202 if (exit.timedOut === true || neverRan(exit.code)) {203 return Diagnosis.Blocked();204 }
7 unmodified lines
212 onSome: (report) => fromReport(report, exit),213 });214};215243/**244 * How one lane's run ended. `failed` is any failure once the tests ran;245 * `loadError` is a run that never reached them (a load or compile error, or246 * no tests found). A single run is never `flaked`: that takes a second run.216// A single run is never `flaked`: that takes a second run.247 */217export const classifyRun = (lane: LaneName, exit: RunExit): LaneOutcome =>218 Diagnosis.$match(diagnose(exit), {219 Blocked: () => "blocked" as const,220 Failed: () => "failed" as const,
1 unmodified line
222 NoTests: () => "loadError" as const,223 Passed: () => "passed" as const,224 });225257/**258 * The failing tests' names and the first line of each one's assertion,259 * normalised (absolute paths, durations and addresses stripped), so two runs260 * that failed the same way have the same signature. None unless the run261 * failed on assertions.262 */226// Normalised so two runs that failed the same way share a signature.227export const failureSignature = (exit: RunExit): Option.Option<string> => {228 const diagnosis = diagnose(exit);229230 return Diagnosis.$is("Failed")(diagnosis)
3 unmodified lines
modified:packages/checks/src/evidence-store.ts+3 added-31 removed
1/**2 * The `EvidenceStore` port: where a lane's raw log goes, so a3 * `LaneResult.logRef` (and a `ChecksFailed.logRef`) names something real and4 * the log itself never travels to an answerer.5 *6 * Adapters: `/memory`, for tests and the web's dev backend, and `/r2` over7 * the stage's `evidence-<stage>` bucket, which the Worker runs.8 */1import type { ProjectName } from "@repo/protocol/ids";2import {3 keyOf,4 LaneName,
2 unmodified lines
7} from "@repo/protocol/ids";8import { Context, Option, Schema } from "effect";9import type { Effect } from "effect";1019/**20 * A kept log's name: `<project>/<requestId>/<lane>#<attempt>`. It is21 * deterministic, so a replayed step overwrites its log, never adds a second22 * one (principle 8).23 */11// Deterministic, so a replayed step overwrites its log rather than adding one.12export const LogRef = Schema.NonEmptyString.pipe(Schema.brand("LogRef"));1314export type LogRef = typeof LogRef.Type;1528/** One lane's log from one attempt at one answer request. */16export interface LaneLog {17 readonly project: ProjectName;18 readonly requestId: RequestId;19 readonly lane: LaneName;20 readonly attempt: number;21 readonly text: string;22}2337/**38 * The name a lane's log is kept under, whichever adapter keeps it: by the39 * project's key, so a name holds one `/` before the request (ADR 0032).40 */24export const logRefOf = (log: Omit<LaneLog, "text">): LogRef =>25 LogRef.make(26 `${keyOf(log.project)}/${log.requestId}/${log.lane}#${log.attempt}`27 );2846/** A log's name, read back into what it names. */29const LogName = Schema.TemplateLiteralParser([30 ProjectNameFromKey,31 "/",32 RequestId,
2 unmodified lines
35 "#",36 Schema.Int,37]);3857/**58 * What a log's name points at: `logRefOf` read backwards, or `None` for a59 * name it never makes. None of its parts holds a `/` or a `#`; the attempt60 * reads as a number (`#01`, `#1.0` and `#+1` all read as 1), so a name is61 * kept only when `logRefOf` spells it back the same.39// A name is kept only when `logRefOf` spells it back the same.62 */40export const logOfRef = (ref: string): Option.Option<Omit<LaneLog, "text">> =>41 Option.filter(42 Option.map(43 Schema.decodeUnknownOption(LogName)(ref),
9 unmodified lines
5354export class EvidenceStore extends Context.Service<55 EvidenceStore,56 {80 /** Keeps the log, replacing any kept under the same name. */57 readonly put: (log: LaneLog) => Effect.Effect<LogRef>;82 /**83 * A kept log, for its answer's claimant and the project's deciders84 * only: callers check who asks (`ProjectApi.evidence`); the port does85 * not.86 */58 // Callers check who asks (`ProjectApi.evidence`); the port does not.59 readonly get: (ref: LogRef) => Effect.Effect<Option.Option<string>>;60 }61>()("checks/EvidenceStore") {}
modified:packages/checks/src/finder.ts+5 added-86 removed
1/**2 * The command finder: a project's own commands (how to set up, how to run3 * one test file, and the lanes every answer must pass), read from the files4 * it already has: GitHub and Forgejo workflows, lefthook, husky, pre-commit5 * and `package.json` scripts. Pure: it reads the contents it is given and6 * runs nothing. A maintainer confirms what it finds at init.7 */1import type { RunBlock } from "@repo/protocol/domain/run";2import { LaneName } from "@repo/protocol/ids";3import { Array as Arr, Option, Result, Schema } from "effect";4import { parse } from "yaml";56import { PATH_PLACEHOLDER } from "./kinds.ts";715/** The run block as it travels before decoding. */8export type RunBlockEncoded = typeof RunBlock.Encoded;918/** One file of a repo, by its path from the root. */10export interface RepoFile {11 readonly content: string;12 readonly path: string;13}1424/**25 * What the finder found: a partial run block, and where each part came from26 * (`checks.lint from .github/workflows/ci.yml`), plus every file it skipped27 * and why (`skipped <path>: <reason>`). The shape `@repo/rules`'28 * `Finishers.findRunBlock` takes.29 */15export interface FoundRunBlock {16 readonly run: Partial<RunBlockEncoded>;17 readonly sources: readonly string[];18}1935/** The lane names the finder prefers; any other lane takes its script's name. */20type Canonical = "build" | "format" | "lint" | "types" | "unit";2122const isLaneName = Schema.is(LaneName);23
7 unmodified lines
31 tokens.some((token) =>32 flags.some((flag) => token === flag || token.startsWith(`${flag}=`))33 );3451// --- What a command is --------------------------------------------------5235const SETUP: readonly (readonly string[])[] = [36 ["corepack", "enable"],37 ["npm", "ci"],38 ["npm", "install"],
17 unmodified lines
56 ["bundle", "install"],57 ["pre-commit", "install-hooks"],58];5978// Leading `NAME=value` words set the environment; they aren't the command.60const withoutEnv = (tokens: readonly string[]) => {61 const first = tokens.findIndex((token) => !/^\w+=/u.test(token));6263 return first === -1 ? [] : tokens.slice(first);
7 unmodified lines
71 SETUP.some((prefix) => startsWith(tokens, prefix))72 );73};7494// Words that run a tool rather than being one: `npx eslint`, `uv run pytest`.75const RUNNERS: readonly (readonly string[])[] = [76 ["npx"],77 ["bunx"],78 ["pnpm", "exec"],
13 unmodified lines
92 ["pnpm"],93 ["yarn"],94];95116/** Where the tool starts in a command's words, past env and runner words. */96const toolIndex = (tokens: readonly string[]): number => {97 let at = tokens.length - withoutEnv(tokens).length;9899 for (
8 unmodified lines
108};109110const CHECK_FLAGS = ["--check", "-c", "--list-different", "-l"];111133/** A tool's words, the lane it checks, and whether these arguments check. */112const TOOLS: readonly {113 readonly lane: Canonical;114 readonly tool: readonly string[];115 readonly when?: (args: readonly string[]) => boolean;
82 unmodified lines
198 { lane: "build", tool: ["go", "build"] },199 { lane: "build", tool: ["zig", "build"] },200];201224/** Script, task and hook names that say their lane outright. */202const NAMED: readonly { readonly lane: Canonical; readonly names: RegExp }[] = [203 { lane: "unit", names: /^(?:tests?|unit|tests?[:-](?:unit|ci))$/u },204 { lane: "lint", names: /^(?:lint|lint[:-](?:check|ci)|eslint|oxlint)$/u },205 {
7 unmodified lines
213 },214 { lane: "build", names: /^build$/u },215];216240// Names that are never a check, even when a workflow runs them.217const NEVER_A_LANE =218 /(?:^|[:-])(?:dev|start|serve|preview|watch|deploy|release|publish|prepare|install|clean|version|fix|docs)(?:$|[:-])/u;219220const namedLane = (name: string): Option.Option<Canonical> =>221 Option.fromNullishOr(NAMED.find(({ names }) => names.test(name))?.lane);222247/** A name as a lane name: `test:e2e` → `test-e2e`. */223const asLaneName = (name: string): Option.Option<string> =>224 Option.liftPredicate(225 name.replaceAll(/[^A-Za-z0-9-]+/gu, "-").replaceAll(/^-+|-+$/gu, ""),226 isLaneName227 );228254/** A script or task's name as a lane, unless the name says it checks nothing. */229const scriptLane = (name: string): Option.Option<string> =>230 NEVER_A_LANE.test(name) ? Option.none() : asLaneName(name);231232const FIXERS = ["--fix", "--write"];233260/** Whether a command, or any command a script chains, rewrites files. */234const fixes = (body: string) =>235 body.split("&&").some((part) => hasAny(words(part), FIXERS));236264/** The lane a tool command checks: `npx eslint .` → `lint`. Fixers check nothing. */237const toolLane = (command: string): Option.Option<Canonical> => {238 const tokens = words(command);239 const rest = tokens.slice(toolIndex(tokens));240
8 unmodified lines
249 )?.lane250 );251};252281// --- Scripts -------------------------------------------------------------282253type PackageManager = "bun" | "npm" | "pnpm" | "yarn";254255const MANAGERS: readonly PackageManager[] = ["bun", "npm", "pnpm", "yarn"];256257const isManager = (word: string | undefined): word is PackageManager =>258 MANAGERS.some((manager) => manager === word);259290/** What the repo's root `package.json` says: its scripts and package manager. */260interface Scripts {261 readonly byName: ReadonlyMap<string, string>;262 readonly manager: Option.Option<PackageManager>;263}264296/**297 * The script a command runs, if it runs one: `npm test`, `bun run lint`,298 * `pnpm typecheck` (a pnpm or yarn word that names a script).299 */265const scriptOf = (command: string, scripts: Scripts): Option.Option<string> => {266 const [manager, verb, name] = withoutEnv(words(command));267268 if (!isManager(manager)) {
14 unmodified lines
283 ? Option.some(verb)284 : Option.none();285};286322// Task runners name a task the way a script is named: `make test`,323// `just lint`, `turbo run typecheck`; several turbo tasks make one lane.287const TASKS: readonly (readonly string[])[] = [288 ["make"],289 ["just"],290 ["task"],
16 unmodified lines
307};308309const segments = (body: string) => body.split("&&").map((part) => part.trim());310348/** A script's body, followed through scripts that only run another script. */311const bodyOf = (312 name: string,313 scripts: Scripts,314 depth = 0
12 unmodified lines
327 )328 : Option.some(body);329 });330369/** How the repo's package manager runs a script: `pnpm run build`, `npm test`. */331const runScript = (manager: PackageManager, name: string) =>332 manager === "npm" && name === "test" ? "npm test" : `${manager} run ${name}`;333373// --- One test file ------------------------------------------------------374334const insertBefore = (335 tokens: readonly string[],336 marker: string,337 added: readonly string[]
4 unmodified lines
342 ? [...tokens, ...added]343 : [...tokens.slice(0, at), ...added, ...tokens.slice(at)];344};345387/** A `go test` package pattern: `.`, `./pkg`, `./...`, `example.com/m/...`. */346const isGoPackages = (arg: string) =>347 arg === "." ||348 arg.startsWith("./") ||349 arg.startsWith("../") ||350 arg.includes("...");351394/**395 * The command that runs one test file, for runners that can: `vitest run`396 * → `vitest run {path}`. Go runs a package and Cargo a test target, so theirs397 * name the file's directory or stem through the shell.398 */352// Go runs a package and Cargo a test target, so theirs name the file's353// directory or stem through the shell.354const oneFile = (command: string): Option.Option<string> => {355 const tokens = words(command);356 const at = toolIndex(tokens);357 const head = tokens.slice(0, at);
19 unmodified lines
377 return write(...rest, PATH_PLACEHOLDER);378 }379380 if (startsWith(rest, ["go", "test"])) {426 // Keep every flag and its value (`-run TestX`); drop the packages.381 const flags = rest.slice(2).filter((arg) => !isGoPackages(arg));382383 return write("go", "test", ...flags, `"./$(dirname ${PATH_PLACEHOLDER})"`);384 }
9 unmodified lines
394395 return Option.none();396};397444// --- Reading sources ----------------------------------------------------445446/** A command a source runs, with the name the source gives it, if any. */398interface Step {399 readonly command: string;400 readonly name: Option.Option<string>;401}402452/** A lane a source offers: its command, and the file its test runner was read from. */403interface Offer {404 readonly command: string;405 readonly fallback: Option.Option<string>;406 readonly lane: string;407 readonly path: string;408 readonly runner: { readonly body: string; readonly path: string };409}410461/** One source file, read: its setup commands and lanes, or why it was skipped. */411interface Read {412 readonly offers: readonly Offer[];413 readonly path: string;414 readonly setup: readonly string[];415}416417const PACKAGE_JSON = "package.json";418470// An error's message on one line, for a `skipped …` source.419const oneLine = (message: string) =>420 message421 .split("\n")422 .map((line) => line.trim())423 .filter(Boolean)424 .join(" ");425478/**479 * A YAML file decoded by `schema`, or why not. YAML errors keep their first480 * line (the rest is a code frame); schema errors keep every line.481 */426// YAML errors keep their first line (the rest is a code frame).427const readYaml = <A>(428 schema: Schema.ConstraintDecoder<A>,429 content: string430): Result.Result<A, string> =>
8 unmodified lines
439 Result.mapError(decoded, (issue) => oneLine(issue.message))440 )441 );442498// A shell line split into the commands it chains; comments and blank lines499// dropped, `\` continuations joined.443const shellCommands = (text: string): readonly string[] =>444 text445 .replaceAll("\\\n", " ")446 .split("\n")
94 unmodified lines
541 "commit",542 "pre-commit",543]);544602/** pre-commit's hook ids that name a canonical lane. */545const HOOKS: ReadonlyMap<string, Canonical> = new Map([546 ["ruff", "lint"],547 ["ruff-check", "lint"],548 ["flake8", "lint"],
16 unmodified lines
565const isWorkflow = (file: RepoFile) => workflowFile.test(file.path);566567const huskyFile = /^\.husky\/pre-(?:commit|push)$/u;568627// Every name lefthook reads its config from, as the judge closure lists them.569const LEFTHOOK: ReadonlySet<string> = new Set([570 "lefthook.yml",571 "lefthook.yaml",572 ".lefthook.yml",
19 unmodified lines
592 ["yarn.lock", "yarn"],593 ["package-lock.json", "npm"],594];595655// --- Putting it together ------------------------------------------------656596const offerFromStep = (597 step: Step,598 path: string,599 scripts: Scripts
17 unmodified lines
617 );618619 const fallback = Option.flatMap(ownName, scriptLane);620682 // A dev server, deploy or release is no check, whatever tool its body runs.621 const neverALane = [step.name, task].some((name) =>622 Option.exists(name, (text) => NEVER_A_LANE.test(text))623 );624
59 unmodified lines
684 setup: [],685 }))686 );687750// Root scripts that name or run a check become lanes, run the repo's way.688const readScripts = (manager: PackageManager, scripts: Scripts): Read => ({689 offers: [...scripts.byName].flatMap(([name, body]) => {690 const lane = Option.orElse(namedLane(name), () =>691 Option.firstSomeOf(segments(body).map(toolLane))
17 unmodified lines
709 path: PACKAGE_JSON,710 setup: [],711});712776/** Lanes by name, in the order found, each with its offer. */713type Lanes = ReadonlyMap<string, Offer>;714715// One group's offers, merged under the lanes already found by the groups716// before it. Inside a group a second offer for a lane takes its own name;
46 unmodified lines
763} as const satisfies Record<PackageManager, string>;764765const skip = (path: string, reason: string) => `skipped ${path}: ${reason}`;766831/** Each file read, and a `skipped …` line for each one that wasn't. */767const readEach = (768 files: readonly RepoFile[],769 read: (file: RepoFile) => Result.Result<Read, string>770) => {
6 unmodified lines
777 skipped: Arr.getFailures(results),778 };779};780846/** The root `package.json`'s scripts and package manager, or why it can't be read. */781const readPackage = (files: readonly RepoFile[]) =>782 Option.map(783 Option.fromNullishOr(files.find(fileNamed(PACKAGE_JSON))),784 (file) =>
14 unmodified lines
799 )800 ),801});802869/** Setup commands with the file each came from, deduplicated, in order. */803type Setup = readonly (readonly [command: string, path: string])[];804805// The install commands of the source group setup comes from, plus the hook806// environments pre-commit's lanes need before the network closes.
8 unmodified lines
815816 return [...new Map([...found, ...hooks])];817};818886/** The one-file test command, and where its runner was read. */819const testOf = (lanes: Lanes) =>820 Option.map(Option.fromNullishOr(lanes.get("unit")), (unit) =>821 Option.match(Option.firstSomeOf(segments(unit.runner.body).map(oneFile)), {822 onNone: () => ({ command: unit.command, path: unit.path }),823 onSome: (command) => ({ command, path: unit.runner.path }),824 })825 );826895/**896 * Finds a project's run block in its files. Sources rank CI workflows first,897 * then lefthook, husky and pre-commit hooks, then root `package.json`898 * scripts; a lower source only adds lanes the higher ones lack. Lanes are899 * named `lint`, `types`, `unit`, `build` and `format` when the finder knows900 * the tool or the name, else by their script's name; a dev server, deploy,901 * release or fixer is never a lane. `test` runs one file (`{path}`) for902 * runners it knows (vitest, jest, bun test, pytest, go test, cargo test, and903 * a few more); otherwise it is the unit lane's command as found. Setup is the904 * install commands the top source runs, or else the package manager's905 * install, frozen only when a lockfile is committed. A file that doesn't906 * parse is skipped with its reason in `sources`; nothing found leaves `run`907 * and `sources` empty.908 */827// Sources rank CI workflows, then hooks, then root scripts; a lower source828// only adds lanes the higher ones lack.829export const findRunBlock = (files: readonly RepoFile[]): FoundRunBlock => {830 const sorted = files.toSorted(byPath);831 const root = readPackage(sorted);832 const rootPackage = Option.flatMap(root, Result.getSuccess);
25 unmodified lines
858 );859860 const hooks = [...lefthook.reads, ...husky, ...preCommit.reads];861942 // Setup comes from the highest-ranked group that installs anything.862 const installing =863 [workflows.reads, hooks].find((reads) =>864 reads.some(({ setup }) => setup.length > 0)865 ) ?? [];
64 unmodified lines
modified:packages/checks/src/held-back-filter.ts+4 added-13 removed
1/**2 * What a sealed suite's run discloses: one result per3 * area, `passed` of `total` under the suite's root, and nothing else. The4 * Checker hands this module only how each held-back run ended, never what5 * it printed, so no name, path, case or line of output can reach a result:6 * neither type has a field for one.7 */1// Only how each held-back run ended reaches here, never what it printed, so no2// name, path or output can reach a result: neither type has a field for one.3import type { HeldBackResult } from "@repo/protocol/domain/answer";4import type { AreaName, SuiteRoot } from "@repo/protocol/ids";511/** How one held-back run ended: its area, its exit code, and whether it ran out of time. */6export interface HeldBackExit {7 readonly area: AreaName;8 readonly code: number;9 readonly timedOut: boolean;
6 unmodified lines
16 * one bit per check.17 */18const passed = ({ code, timedOut }: HeldBackExit) => code === 0 && !timedOut;1926/**27 * The area bits of one held-back run: every declared area once, in the28 * declared order, even one no run counted (0 of 0, which the trailer shows29 * as "n/a"). A run in an area the suite does not declare counts nowhere.30 */20// Every declared area once, in order, even one no run counted (0 of 0).21// A run in an undeclared area counts nowhere.22export const areaBits = ({23 areas,24 exits,25 suite,
15 unmodified lines
modified:packages/checks/src/judge.ts+11 added-258 removed
1/**2 * The judge closure: every file that decides what an answer's checks do, so3 * no answer may change it (GLOSSARY "Judge closure"). It is data: globs, plus4 * JSON pointers into files an answer may still edit elsewhere, such as5 * `package.json#/scripts` beside its dependencies. Pure; it reads only the6 * file contents it is given.7 */1import { Brand } from "@repo/brand";2import { Glob } from "@repo/protocol/domain/common";3import type { Policy } from "@repo/protocol/domain/policy";4import type { RunBlock } from "@repo/protocol/domain/run";
3 unmodified lines
89import { findRunBlock } from "./finder.ts";10import type { RepoFile } from "./finder.ts";1119/** A closure glob that starts with this takes paths back out of the closure. */12const EXCLUDE = "!";1322/**23 * Where each harness and git hook manager the platform knows keeps its hooks:24 * Claude Code, Cursor, Codex, GitHub Copilot, Gemini CLI, pi, OpenCode and25 * Amp; lefthook (and its scripts folder), husky and pre-commit. A hook runs in26 * every contributor's session, so an answer may not change one.27 */14export const hookConfigGlobs: readonly Glob[] = [15 ".claude/settings*.json",16 ".cursor/hooks.json",17 ".codex/hooks.json",
12 unmodified lines
30 ".husky/**",31 ".pre-commit-config.yaml",32].map((glob) => Glob.make(glob));3348/**49 * The workspace and task-runner policy files, and formatter config: what a50 * package manager, a task runner or a formatter check reads before it runs51 * anything (bun's and pnpm's install policy, turbo's and nx's task graph,52 * yarn's own release and plugins). `.editorconfig` is not one: no check53 * reads it.54 */34export const policyFileGlobs: readonly Glob[] = [35 "**/bunfig.toml",36 "pnpm-workspace.yaml",37 "**/turbo.json",
8 unmodified lines
46 "**/.prettierrc*",47 "**/prettier.config.*",48].map((glob) => Glob.make(glob));4971/**72 * What every project's judge holds before its run block adds to it: the73 * config folder, the env schema and committed env files (never `*.local`74 * ones), CI, test and lint config, the tsconfig files, generated contribute75 * skills, the workspace and task-runner policy files, and every hook config.76 */50export const defaultJudgeGlobs: readonly Glob[] = [51 ...[52 `${Brand.configDir}/**`,53 "**/.env.schema",
23 unmodified lines
77];7879const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");80108// One path segment against one glob segment: `*` is any run of characters109// and `?` is one, never a `/`. Greedy, backing up to the last `*` on a miss.81const matchSegment = (pattern: string, text: string): boolean => {82 let at = 0;83 let from = 0;84 let star = -1;
49 unmodified lines
134 matchSegments(restGlobs, restParts)135 );136};137167/**168 * Whether a repo path matches a glob: `**` as a whole segment is any number169 * of directories (none included), `*` is any run of characters within a170 * segment and `?` one character. A leading dot is matched like any other171 * character, so `*` reaches dotfiles. No braces, no classes, no negation.172 * Pure and dependency-free, so the gate can copy it.173 */138// A leading dot is matched like any other character, so `*` reaches dotfiles.139export const matchGlob = (glob: string, path: string): boolean =>140 matchSegments(141 withoutDotSlash(glob).split("/"),142 withoutDotSlash(path).split("/")143 );144180/**181 * Whether an answer that changes `path` changes the judge: some closure glob182 * matches it and no `!` glob takes it back out. A JSON pointer never judges a183 * whole file (`package.json` stays editable); `touchedPointers` reads those.184 */145export const isJudged = (closure: Policy["judge"], path: string): boolean => {146 const excluded = closure.paths.some(147 (glob) =>148 glob.startsWith(EXCLUDE) && matchGlob(glob.slice(EXCLUDE.length), path)
14 unmodified lines
163164const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>165 Predicate.isObject(value) && !isJsonArray(value);166207// The index just past the string literal whose quote is at `at`; an208// unclosed string runs to the end.167const stringEnd = (text: string, at: number): number => {168 const quote = text.charAt(at);169 let next = at + 1;170
3 unmodified lines
174175 return Math.min(next + 1, text.length);176};177220/** Where the comment that opens at `at` ends, if one opens there. */178type CommentEnd = (text: string, at: number) => Option.Option<number>;179223// The index just past the comment that opens at `at`, if one does.180const commentEnd: CommentEnd = (text, at) => {181 if (text.startsWith("//", at)) {182 const end = text.indexOf("\n", at);183
8 unmodified lines
192193 return Option.none();194};195240// The index just past the `#` comment (TOML's) that opens at `at`, if one does.196const hashCommentEnd: CommentEnd = (text, at) => {197 if (text.charAt(at) !== "#") {198 return Option.none();199 }
4 unmodified lines
204};205206const QUOTES = new Set(['"', "'", "`"]);207253/**254 * Text with each comment outside a string as one space: `//` and `/* *\/`255 * ones by default (JavaScript, JSONC), or those `opens` finds.256 */208const withoutComments = (209 text: string,210 opens: CommentEnd = commentEnd211): string => {
20 unmodified lines
232};233234const isSpace = (char: string) => /\s/u.test(char);235285// Whether the next character after `at` that isn't space closes a bracket.236const closesNext = (text: string, at: number) => {237 let peek = at;238239 while (isSpace(text.charAt(peek))) {
2 unmodified lines
242243 return peek < text.length && "]}".includes(text.charAt(peek));244};245296/** JSON text with each comma that closes nothing (`[1, 2,]`) left out. */246const withoutTrailingCommas = (text: string): string => {247 let kept = "";248 let at = 0;249
7 unmodified lines
257258 return kept;259};260312/**313 * JSONC (tsconfig, `.oxlintrc.json`, harness settings) read as JSON: its314 * comments and trailing commas are dropped first. Pure and dependency-free.315 */261const decodeJsonc = (text: string): Option.Option<Schema.Json> =>262 decodeJson(withoutTrailingCommas(withoutComments(text)));263264const UNREADABLE =
2 unmodified lines
267const UNREAD = "not among the files read; judged unread";268269const dirname = (path: string) => path.split("/").slice(0, -1).join("/");270326// `a/b` joined with `../c` is `c`; `..` above the root leaves the repo.271const join = (dir: string, relative: string): Option.Option<string> => {272 const parts: string[] = dir === "" ? [] : dir.split("/");273274 for (const part of relative.split("/")) {
16 unmodified lines
291 specifier.startsWith("../");292293const isPackageJson = (path: string) => matchGlob("**/package.json", path);294351/**352 * The files a closure is computed over: every path, in the order given, and353 * a file's text when asked for it (`undefined` for a path not among them).354 * Every walk reads a file's text only through `read`, so a caller can learn355 * which files a closure reads (`judgeReads`).356 */295interface Tree {296 readonly paths: ReadonlySet<string>;297 readonly read: (path: string) => string | undefined;298}
2 unmodified lines
301 paths: new Set(contents.keys()),302 read: (path) => contents.get(path),303});304367/** Each workspace package's name and folder, from the manifests given. */305const workspacesOf = (tree: Tree): ReadonlyMap<string, string> =>306 new Map(307 [...tree.paths]308 .filter((path) => isPackageJson(path))
10 unmodified lines
319 )320 )321 );322386/**387 * A package specifier read as a workspace package's own file: `@repo/x/y`388 * is `y` inside the folder of the package named `@repo/x`, the longest name389 * winning. A package no workspace declares is a dependency, not a path.390 */323const inWorkspace = (324 specifier: string,325 workspaces: ReadonlyMap<string, string>326): Option.Option<{ readonly dir: string; readonly rest: string }> =>
12 unmodified lines
339const configFile = (path: string, paths: ReadonlySet<string>) =>340 [path, `${path}.json`].find((candidate) => paths.has(candidate)) ??341 (path.endsWith(".json") ? path : `${path}.json`);342411/**412 * Where a tsconfig's `extends` entry points: a relative path from the file's413 * folder, or a file of a workspace package (a bare package name is its414 * `tsconfig.json`). Any other package (`@tsconfig/node24`) is a dependency.415 */343const resolveExtends = (344 from: string,345 specifier: string,346 paths: ReadonlySet<string>,
17 unmodified lines
364365 return [value ?? []].flat().filter(Predicate.isString);366};367441/** A path the walk could not read past, and why. */368const note = (path: string, reason: string) => `${path}: ${reason}`;369370const chainFrom = (371 start: string,
25 unmodified lines
397398 return { chain: chain.map((path) => RepoPath.make(path)), notes };399};400475/**476 * A tsconfig and every file its `extends` reaches, in the order tsc reads477 * them: string and array forms, relative paths (`.json` added as tsc adds478 * it) and workspace packages' files. Files are read as JSONC. A file that479 * still doesn't parse ends its branch and stays in the chain, as does a480 * target not among `files`; each says why in `notes`.481 */401export const tsconfigChain = (402 start: RepoPath,403 files: ReadonlyMap<string, string>404): {
4 unmodified lines
409410 return chainFrom(start, tree, workspacesOf(tree));411};412494/** A token of JavaScript or JSON text, its comments dropped. */413interface Token {414 readonly kind: "mark" | "string" | "word";415 readonly text: string;416}417418const isWordChar = (char: string) => /[\w$]/u.test(char);419502// A string literal's value; a template with `${…}` in it is no one value.420const literal = (quote: string, body: string): Token =>421 quote === "`" && body.includes("${")422 ? { kind: "mark", text: quote }423 : { kind: "string", text: body.replaceAll(/\\(?<char>.)/gu, "$<char>") };424508/**509 * Source text as words, string literals and single marks, comments510 * dropped (JavaScript's by default; TOML passes its `#`). Enough to read511 * imports and literal arrays without running the file; a regex literal that512 * holds a quote can mislead it.513 */425// Not a full lexer: a regex literal that holds a quote can mislead it.426const tokensOf = (427 source: string,428 comments: CommentEnd = commentEnd429): readonly Token[] => {
23 unmodified lines
453454 return tokens;455};456545// Words a module path follows as a call's first argument: `import("…")`,546// `require("…")`, `require.resolve("…")`, `new URL("…", import.meta.url)`.457const LOADERS = new Set(["URL", "import", "require", "resolve"]);458549/** The module specifiers source text imports, exports from or requires. */459const importSpecifiers = (tokens: readonly Token[]): readonly string[] =>460 tokens.flatMap((token, at) => {461 const next = tokens[at + 1];462 const after = tokens[at + 2];
15 unmodified lines
478 ? [after.text]479 : [];480 });481573// Marks that open and close a nesting level in source text.482const OPENS = new Set(["(", "[", "{"]);483484const CLOSES = new Set([")", "]", "}"]);485578/** What a `jsPlugins` key in source text holds, as far as its text says. */486interface PluginList {580 /** Each plugin string in a literal array, or an object's `specifier:` string. */487 readonly specifiers: readonly string[];582 /** Whether some `jsPlugins` holds something other than a literal array. */488 readonly opaque: boolean;489}490586// The strings of one `jsPlugins: [...]` array that starts at token `at`.491const listedAt = (tokens: readonly Token[], at: number): readonly string[] => {492 const found: string[] = [];493 let depth = 0;494
20 unmodified lines
515516 return found;517};518615/**616 * The `jsPlugins` arrays of an oxlint config's source, read as text: a key's617 * (`jsPlugins: [...]`) or a variable's (`const jsPlugins = [...]`).618 */519const jsPluginsInSource = (tokens: readonly Token[]): PluginList => {520 const starts = tokens.flatMap((token, at) =>521 token.text === "jsPlugins" &&522 (tokens[at + 1]?.text === ":" || tokens[at + 1]?.text === "=")
8 unmodified lines
531 .flatMap((at) => listedAt(tokens, at)),532 };533};534635/** The `jsPlugins` of a JSON oxlint config: strings, or `{specifier}` objects. */535const jsPluginsInJson = (config: Schema.Json): readonly string[] => {536 const list = isJsonObject(config) ? config.jsPlugins : undefined;537538 return (list !== undefined && isJsonArray(list) ? list : []).flatMap(
10 unmodified lines
549};550551const basename = (path: string) => path.split("/").at(-1) ?? path;552654// `.oxlintrc.json`, `.oxlintrc`, `.eslintrc.json`: configs written as JSONC.553const isJsonConfig = (path: string) =>554 /\.jsonc?$/u.test(path) || basename(path) === ".oxlintrc";555658/** The lint configs whose plugins and imports judge: oxlint's and eslint's. */556const lintConfigGlobs = [557 "**/oxlint.config.*",558 "**/oxlint.*.config.*",559 "**/.oxlintrc*",
4 unmodified lines
564565const isLintConfig = (path: string) =>566 lintConfigGlobs.some((glob) => matchGlob(glob, path));567671/** What one lint config names: its plugins, and the modules it imports or extends. */568interface LintNames {569 readonly imports: readonly string[];570 readonly notes: readonly string[];571 readonly plugins: readonly string[];
31 unmodified lines
603 plugins: plugins.specifiers,604 };605};606711// Relative specifiers, as paths from the repo root.607const relativeFrom = (608 from: string,609 specifiers: readonly string[]610): readonly RepoPath[] =>
1 unmodified line
612 .filter(isRelative)613 .flatMap((specifier) => Option.toArray(join(dirname(from), specifier)))614 .map((path) => RepoPath.make(path));615721/**722 * The local plugins an oxlint config loads, as repo paths: each `jsPlugins`723 * entry of a `.oxlintrc*.json` (a string or `{specifier}`), or each string in724 * an `oxlint.config.*`'s `jsPlugins` array, read as text and never run.725 * Relative to the config's folder; a package name (`eslint-plugin-foo`) is a726 * dependency, not a path. A config that doesn't parse names none.727 */616export const jsPluginSpecifiers = (config: RepoFile): readonly RepoPath[] =>617 relativeFrom(config.path, lintNames(config).plugins);618731/**732 * The local modules an eslint config imports or requires (plugins and shared733 * configs alike), as repo paths from the config's folder, read as text and734 * never run. Packages are dependencies, not paths.735 */619export const eslintLocalPlugins = (config: RepoFile): readonly RepoPath[] =>620 relativeFrom(config.path, lintNames(config).imports);621622const MODULE_EXTENSIONS = [
25 unmodified lines
648649 return (TWINS.get(path.slice(dot)) ?? []).map((ext) => `${stem}${ext}`);650};651769/**770 * What a module path turns out to be among the repo's files: a file (an771 * `index.*` brings its whole folder), a folder (`./rules` with772 * `rules/index.js`), or, when it is neither, the path, its extensions and773 * its folder, so a file an answer adds there is judged too.774 */652interface Settled {776 /** The plugin's own path: its file, or its folder for a folder plugin. */653 readonly anchor: string;778 /** The file to read next, when one exists. */654 readonly file: Option.Option<string>;655 readonly globs: readonly string[];656}657
41 unmodified lines
699 globs: [path, `${path}.*`, `${path}/**`],700 };701};702828// A command's words that could name a file: split on whitespace and shell829// operators, quotes dropped, a leading `$VAR/` or `${VAR}/` dropped (the830// project folder a harness exports), a `--flag=value`'s value, and a path831// after `$(…)` read from the root.703const wordsOf = (command: string): readonly string[] =>704 command705 .split(/[\s;&|()<>`]+/u)706 .map((word) =>
2 unmodified lines
709 .flatMap((word) => [word, word.slice(word.indexOf("=") + 1)])710 .flatMap((word) => [word, word.replace(/^\/+/u, "")])711 .map(withoutDotSlash);712842/**843 * Manifests, lockfiles and dependency lists. A command may name one (`pip844 * install -r requirements.txt`), and it stays editable all the same:845 * dependency edits are allowed, as they are in `package.json`, whose scripts846 * alone judge, by pointer.847 */713// A command may name one of these, yet it stays editable: dependency edits714// are allowed, as in `package.json`, where only the scripts are judged.715const dependencyFileGlobs = [716 "**/package.json",717 "**/bun.lock",718 "**/bun.lockb",
14 unmodified lines
733734const isDependencyFile = (path: string) =>735 dependencyFileGlobs.some((glob) => matchGlob(glob, path));736870/**871 * The tracked files commands run or read, from the words that name one:872 * `bun "${CLAUDE_PROJECT_DIR}/scripts/hooks/x.ts"` → `scripts/hooks/x.ts`.873 * A manifest, lockfile or dependency list is never one (dependency edits stay874 * allowed). Sorted.875 */737export const commandScripts = (738 commands: readonly string[],739 files: ReadonlySet<string>740): readonly RepoPath[] =>
11 unmodified lines
752 /\.(?:ba|z)?sh$/u.test(path) || !hasExtension(path);753754const CODE = /\.[cm]?[jt]sx?$/u;755895// What one file runs, as repo paths: a code file's relative imports and896// `jsPlugins` strings, or the tracked files a shell script's lines name.756const runsFrom = (757 path: string,758 content: string,759 paths: ReadonlySet<string>
9 unmodified lines
769770 return isShell(path) ? commandScripts(content.split("\n"), paths) : [];771};772914/**915 * Every module the seeds reach by relative imports, and every script a916 * shell script among them runs, settled to globs: what a lint plugin, a hook917 * script or a check script runs is judged with it. Packages, workspace ones918 * included, are not followed, nor any path `follows` refuses. A file without919 * contents ends its branch.920 */773const walkImports = (774 seeds: readonly string[],775 tree: Tree,776 follows: (path: string) => boolean = () => true
20 unmodified lines
797798 return globs;799};800949/** The lint sources a repo's lint configs name, and where they stand. */801interface LintSources {951 /** Each plugin's own path, for its rule fixtures. */802 readonly anchors: readonly string[];803 readonly globs: readonly string[];804 readonly notes: readonly string[];805}806957/**958 * Every lint config's plugins and imports, settled: relative paths, and959 * workspace packages by their folders (a package a lint config names is960 * lint source too). Then what those modules import, relatively.961 */807const lintSources = (808 tree: Tree,809 workspaces: ReadonlyMap<string, string>810): LintSources => {
32 unmodified lines
843 notes: named.flatMap((config) => config.notes),844 };845};8461002// A whole folder (`a/b/**`) the closure holds makes any other glob or path1003// under it redundant.847const withoutCovered = (globs: readonly string[]): readonly string[] => {848 const folders = globs.flatMap((glob) =>849 glob.endsWith("/**") && !glob.slice(0, -3).includes("*")850 ? [glob.slice(0, -2)]
12 unmodified lines
863864const TEST_FILE =865 /(?:^|\/)(?:__fixtures__|__tests__|tests?)\/|\.(?:spec|test)\.[cm]?[jt]sx?$/u;8661024// A path without its file's extension: `lint/plugin.mjs` is `lint/plugin`.867const stemOf = (path: string) =>868 hasExtension(path) ? path.slice(0, path.lastIndexOf(".")) : path;8691028/** A plugin as a test can name it: its folder, or its file with or without extension. */870interface PluginName {871 readonly folder: boolean;872 readonly path: string;873}
2 unmodified lines
876 plugin.folder877 ? candidate === plugin.path || candidate.startsWith(`${plugin.path}/`)878 : stemOf(candidate) === stemOf(plugin.path);8791039// The paths a string in a test at `from` can mean: relative to the test,1040// and, for `./x` or a bare path, from the repo root (a config written inline).880const readingsOf = (from: string, text: string): readonly string[] => {881 if (text.startsWith("../")) {882 return Option.toArray(join(dirname(from), text));883 }
4 unmodified lines
888 ? [...Option.toArray(join(dirname(from), text)), rooted]889 : [rooted];890};8911053/** `ruleFixtures`, reading a test file's text only when some plugin may be named in it. */892const fixturesOf = (893 pluginPaths: readonly string[],894 files: readonly string[],895 read: Tree["read"]
6 unmodified lines
902 path: plugin,903 }904 );9051068 // A plugin's folder sits beside its fixtures as a plugin file does.906 const beside = plugins.flatMap((plugin) => {907 const folder = dirname(plugin.path);908909 return folder === ""910 ? []911 : FIXTURE_FOLDERS.map((name) => `${folder}/${name}/**`);912 });9131077 // Cheap first: a test that never spells a plugin's last name can't name it.914 const lastNames = plugins.map((plugin) => basename(stemOf(plugin.path)));915916 const naming = files.filter((path) => {917 if (plugins.length === 0 || !TEST_FILE.test(path)) {
21 unmodified lines
939 .toSorted()940 .map((glob) => Glob.make(glob));941};9421107/**1108 * The rule fixture tests of local lint plugins: the `test/`, `tests/` and1109 * `__fixtures__/` folders beside each plugin (beside a plugin file, or beside1110 * a plugin's folder; never at the repo root, where they hold the project's1111 * own tests), any `*-rule.test.*`, and every test file whose text names a1112 * plugin's path, by import or as a string from the root. Plugins are given1113 * as their entry files (an `index.*` stands for its folder) or folders.1114 */943// Fixture folders are never taken at the repo root, where they hold the944// project's own tests.945export const ruleFixtures = (946 pluginPaths: readonly string[],947 files: readonly string[],948 contents: ReadonlyMap<string, string>949): readonly Glob[] =>950 fixturesOf(pluginPaths, files, (path) => contents.get(path));9511122// Keys whose strings a hook manager runs: Claude Code, Cursor, Codex and1123// Gemini's `command` (with `args`), Copilot's `bash` and `powershell`,1124// lefthook's `run` and `script`, pre-commit's `entry`.952const COMMAND_KEYS = new Set([953 "args",954 "bash",955 "command",
3 unmodified lines
959 "run",960 "script",961]);9621136// Every string under a command key, at any depth of a JSON or YAML value.963const commandsIn = (964 value: Schema.Json,965 underKey: boolean966): readonly string[] => {
13 unmodified lines
980};981982const decodeAnyJson = Schema.decodeUnknownOption(Schema.Json);9831158// YAML that `yaml` can't parse, or that holds a value JSON can't, is None.984const decodeYaml = (text: string): Option.Option<Schema.Json> =>985 Option.flatten(986 Option.liftThrowable((source: string) =>987 decodeAnyJson(parse(source, { logLevel: "error", strict: false }))988 )(text)989 );9901166/** What one hook config runs, as command lines, and why it could not be read. */991interface HookCommands {992 readonly commands: readonly string[];993 readonly notes: readonly string[];994}
2 unmodified lines
997 commands: [],998 notes: [note(path, reason)],999});10001177/**1178 * The commands a hook config runs: the strings under command keys of a JSON1179 * (JSONC) or YAML config, the strings of a TOML config or a code plugin, and1180 * every line of a shell hook. Other files (a README) run nothing.1181 */1001const hookCommands = (hook: RepoFile): HookCommands => {1002 const { content, path } = hook;10031004 if (/\.jsonc?$/u.test(path)) {
24 unmodified lines
10291030 return { commands: isShell(path) ? content.split("\n") : [], notes: [] };1031};10321214/**1215 * The hook configs among the files, the scripts their commands name, and1216 * what those scripts and code plugins (pi, OpenCode, Amp) import.1217 */1033const hookSources = (tree: Tree, sorted: readonly string[]) => {1034 const configs = sorted.filter((path) =>1035 hookConfigGlobs.some((glob) => matchGlob(glob, path))1036 );
16 unmodified lines
1053};10541055const SCRIPTS = "#/scripts";10561242/**1243 * A judge closure as data, the shape `Policy.judge` stores: globs (a `!` glob1244 * takes paths back out), and `<file>#<JSON pointer>` parts of files.1245 */1057export interface JudgeClosure {1058 readonly paths: readonly Glob[];1059 readonly pointers: readonly string[];1249 /** Where the walk stopped early (a file that isn't JSONC, one not read), and why. */1060 readonly notes?: readonly string[];1061}10621253/**1254 * What the scripts run commands name import and run in turn, inside each1255 * script's own folder only: a check script's helpers sit beside it, while1256 * what it imports from elsewhere is the product it checks, which an answer1257 * must stay free to change. A script at the root follows nothing.1258 */1063// Only a check script's own folder is followed: what it imports from1064// elsewhere is the product it checks, which an answer must stay free to change.1065const checkScripts = (1066 scripts: readonly string[],1067 tree: Tree1068): readonly string[] =>
4 unmodified lines
1073 ? []1074 : walkImports([script], tree, (path) => path.startsWith(`${folder}/`));1075 });10761271/** Every command a run block runs. */1077const commandsOf = (run: RunBlock): readonly string[] =>1078 [run.setup, run.doctor, run.test, ...Object.values(run.checks)].filter(1079 Predicate.isNotUndefined1080 );10811277/** `judgeClosure` over a tree, for run commands given as text. */1082const closureOf = (commands: readonly string[], tree: Tree): JudgeClosure => {1083 const { paths } = tree;1084 const sorted = [...paths].toSorted();1085 const workspaces = workspacesOf(tree);
43 unmodified lines
11291130 return notes.length === 0 ? closure : { ...closure, notes };1131};11321329/**1330 * The judge closure for a run block over a repo's files: the defaults (the1331 * policy files and every hook config among them); every file a run command1332 * names (`./test.sh` → `test.sh`) and what it imports or runs from its own1333 * folder; every script a hook command names, with all it imports or runs;1334 * each tsconfig's `extends` chain; every lint plugin and module a lint config1335 * loads, with what it imports and its rule fixture tests; and each1336 * `package.json`'s scripts as a pointer. Manifests, lockfiles and dependency1337 * lists stay editable. Files are read as text, never run; one that doesn't1338 * parse is still judged, and `notes` says where the walk stopped. Its shape1339 * is `@repo/rules`' `Finishers.judgeClosure`, so the platform passes it in.1340 */1133export const judgeClosure = (1134 run: RunBlock,1135 files: readonly RepoFile[]1136): JudgeClosure =>
12 unmodified lines
1149 .slice(1)1150 .split("/")1151 .map((token) => token.replaceAll("~1", "/").replaceAll("~0", "~"));11521361// One step down a JSON value: an object's own key, or an array's index.1153const childAt = (1154 value: Schema.Json,1155 token: string1156): Option.Option<Schema.Json> => {
20 unmodified lines
11771178 return value;1179};11801390// What one side of a change holds at a pointer: nothing (no file, or no such1391// key), the value, or the text of a file that isn't JSON.1181const read = (1182 file: RepoFile | undefined,1183 target: string,1184 tokens: readonly string[]
4 unmodified lines
1189 onNone: () => Option.some(Result.fail(file.content)),1190 onSome: (json) => Option.map(valueAt(json, tokens), Result.succeed),1191 });11921404/**1405 * The closure's pointers whose value differs between a file's two versions:1406 * `["package.json#/scripts"]` when a script changed, `[]` for a dependency1407 * edit. Values compare as JSON, so moving a key or reformatting is no change.1408 * A file added (no `before`), deleted (no `after`), or no longer valid JSON1409 * counts as a change.1410 */1193export const touchedPointers = (1194 closure: Policy["judge"],1195 before: RepoFile | undefined,1196 after?: RepoFile
8 unmodified lines
1205 read(after, target, tokens)1206 );1207 });12081427// ------------------------------------------------------------ what it reads14281429/** The largest file the finder and the judge closure read; a larger one is listed with no text. */1209// A larger file is listed with no text.1210export const MAX_FACT_BYTES = 256 * 1024;12111432/** One file of a commit, as a listing gives it: its path, and its size in bytes when the listing knows it. */1212export interface ListedFile {1213 readonly path: string;1214 readonly size?: number;1215}12161438/** One file's bytes, as a reader gives them back. */1217export interface ReadFile {1218 readonly bytes: Uint8Array;1219 readonly path: string;1220}12211444/** One file as the finder and the judge closure are handed it. */1222export interface JudgeInput {1223 readonly content: string;1224 readonly path: RepoPath;1225}12261450/** The folders whose files the run-block finder reads, beside the root's. */1227const CI_FOLDERS: ReadonlySet<string> = new Set([1228 ".github/workflows",1229 ".forgejo/workflows",1230 ".husky",1231]);12321457/**1458 * Whether a file is read before any walk: the finder reads the root's files1459 * and the CI folders', and the config folder's run block names the scripts1460 * its checks run.1461 */1233const isSeed = (path: string) =>1234 dirname(path) === "" ||1235 CI_FOLDERS.has(dirname(path)) ||1236 path.startsWith(`${Brand.configDir}/`);12371467/** The commands a found run block runs. */1238const foundCommands = (files: readonly RepoFile[]): readonly string[] => {1239 const { run } = findRunBlock(files);12401241 return [
3 unmodified lines
1245 ...Object.values(run.checks ?? {}),1246 ].filter(Predicate.isNotUndefined);1247};12481479/**1480 * Which listed files' text the finder and the judge closure still need,1481 * given the texts read so far: the root's files and the CI folders' (the1482 * finder's), the config folder's, and every file the closure's walks reach1483 * from what is read, for any command the config folder's strings or the1484 * found run block could run. Pure: the closure is walked over the listing1485 * with each file not read yet as empty text, and every such file it reads is1486 * wanted. A file the listing says is over `MAX_FACT_BYTES` is never wanted.1487 * Read what it returns and ask again until it returns nothing1488 * (`judgeInputs` does): reading more can only reach more.1489 */1249// Call again with what it returned read until it returns nothing: reading1250// more can only reach more.1251const judgeReads = (1252 listed: readonly ListedFile[],1253 texts: ReadonlyMap<string, string>1254): readonly string[] => {
37 unmodified lines
12921293 return [...wanted].toSorted();1294};12951535/**1536 * The files the finder and the judge closure are handed for one commit:1537 * every listed file, sorted by path, with its text where some walk reads it1538 * (`judgeReads`) and empty text elsewhere, or where it is over1539 * `MAX_FACT_BYTES`. `readAll` reads a batch of paths; a path it leaves out1540 * reads as empty. The platform's facts and the CLI's local check and hook1541 * all gather through this, so each hands the closure the same files.1542 */1296export const judgeInputs = <E, R>(1297 listed: readonly ListedFile[],1298 readAll: (1299 paths: readonly string[]
38 unmodified lines
modified:packages/checks/src/kinds.ts+2 added-22 removed
1/**2 * Check kinds: what each kind of ask check runs, and the version that keys3 * its cached verdicts together with the tree SHA (principle 8).4 */1import { CheckSpec } from "@repo/protocol/domain/check";2import type { RatchetSpec } from "@repo/protocol/domain/check";3import { Command } from "@repo/protocol/domain/common";4import type { CheckKind } from "@repo/protocol/domain/kind";
1 unmodified line
6import { CheckVersion, LaneName } from "@repo/protocol/ids";7import { Option, Predicate } from "effect";8import type { Schema } from "effect";914/** The placeholder a run block's `test` holds for the one check file it runs. */10export const PATH_PLACEHOLDER = "{path}";1117/** The check kind a check is of, as an ask kind names it: `RedThenGreen` → `redThenGreen`. */12export const checkKindOf = (spec: CheckSpec): CheckKind =>13 CheckSpec.match(spec, {14 LintToZero: (): CheckKind => "lintToZero",15 Migrate: (): CheckKind => "migrate",
1 unmodified line
17 RedThenGreen: (): CheckKind => "redThenGreen",18 SymbolAbsent: (): CheckKind => "symbolAbsent",19 });2027// Bare when the shell would read it as one word, single-quoted otherwise.21const shellWord = (path: string) =>22 /^[\w./@+-]+$/u.test(path) ? path : `'${path.replaceAll("'", `'\\''`)}'`;2324const declared = (
1 unmodified line
26 name: string27): Option.Option<RatchetSpec> =>28 Option.fromNullishOr(ratchets.find((ratchet) => ratchet.name === name));2937/**38 * The command an ask's check runs, and the lane its result is reported as39 * (the check kind's name, which no project lane shadows in practice).40 * `redThenGreen` fills the run block's `{path}` with the check file;41 * `lintToZero`, `migrate` and `symbolAbsent` run their own command; a42 * `ratchet` runs the measure its policy declares. `None` when the check can't43 * run: a `test` command with no `{path}`, or an undeclared ratchet.44 */30export const commandFor = (31 spec: CheckSpec,32 run: RunBlock,33 ratchets: readonly RatchetSpec[] = []
97 unmodified lines
131132 return hash.toString(16).padStart(16, "0");133};134150/**151 * The version of a check run: `<checkKind>@<sdkVersion>+<runHash>`, where152 * the run hash covers everything the run executes and nothing else: the153 * check itself and its command (a ratchet's declared measure included), every154 * lane, setup, its egress and the image. `doctor` judges nothing, so it is155 * left out. A verdict is reused only for the same tree and the same version.156 */135// The run hash covers everything the run executes and nothing else; `doctor`136// judges nothing, so it is left out.137export const checkVersion = (138 spec: CheckSpec,139 sdkVersion: string,140 run: RunBlock,
22 unmodified lines
modified:packages/checks/src/null-answer.ts+3 added-92 removed
1/**2 * The null answer: the ask's territory as an answer that does3 * nothing. Every function, arrow, class method and getter the territory4 * exports returns `undefined`, a name a check imports from the territory5 * that main lacks gets a stand-in that does the same, and the rest of the6 * tree stays as it is. A check that still passes against it observes no7 * behaviour, so any answer passes it: `nullAnswerVerdict` calls it8 * `WeakCheck{weakness: "nullAnswer"}`.9 *10 * The codemod runs on an in-memory ts-morph project and hands back new11 * contents; it never touches a disk. ts-morph bundles the TypeScript12 * compiler, so this module is reached only through `@repo/checks/null-answer`13 * and only by Bun hosts (the Checker image, the CLI): no Worker imports it.14 */1// ts-morph bundles the TypeScript compiler: only Bun hosts import this module, never a Worker.2import { WeakCheck } from "@repo/protocol/refusal";3import { Array, Effect, Option, pipe, Predicate, Result, Schema } from "effect";4import { Node, Project, ts } from "ts-morph";5import type { ImportDeclaration, SourceFile } from "ts-morph";
2 unmodified lines
8import type { RepoFile } from "./finder.ts";9import { matchGlob } from "./judge.ts";10import type { RunEvidence } from "./red-first.ts";1125/** The null answer could not be made: a file that does not parse, or nothing to stub. */12export class NullAnswerFailed extends Schema.TaggedError<NullAnswerFailed>()(13 "NullAnswerFailed",14 { path: Schema.String, reason: Schema.String }15) {}1631/** The part of an ask's territory the null answer reads. */17export interface NullAnswerTerritory {33 /** The territory's globs; a `!` glob takes paths back out. */18 readonly paths: readonly string[];35 /** The module's public files; without them, its `package.json` `exports`. */19 readonly publicFiles?: readonly string[];20}2139/** A replacement of `[start, end)` in one file's text. */22interface Edit {23 readonly end: number;24 readonly start: number;25 readonly text: string;26}2746/** A body that returns nothing, typed to fit any declared return type. */28const NULL_BODY = "{ return undefined as never; }";2949/** An arrow's expression body that returns nothing. */30const NULL_EXPRESSION = "undefined as never";3132const SOURCE = /\.(?:[cm]?ts|tsx)$/u;3334const DECLARATION = /\.d\.[cm]?ts$/u;3556/** A TypeScript source the codemod reads (declaration files hold no bodies). */36const isSource = (path: string) => SOURCE.test(path) && !DECLARATION.test(path);3738const EXCLUDE = "!";39
5 unmodified lines
45 (glob) =>46 glob.startsWith(EXCLUDE) && matchGlob(glob.slice(EXCLUDE.length), path)47 );4870// The in-memory project's files sit under `/`, at their repo paths.49const ROOT = "/";5051const placed = (path: string) => `${ROOT}${path}`;52
21 unmodified lines
7475const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>76 Predicate.isObject(value) && !isJsonArray(value);77100/** Every string an `exports` field leads to, nested conditions included. */78const exportTargets = (value: Schema.Json | undefined): readonly string[] => {79 if (value === undefined || value === null) {80 return [];81 }
8 unmodified lines
9091 return isJsonObject(value) ? Object.values(value).flatMap(exportTargets) : [];92};93117/** What a manifest exports: its `exports`, or its `main` when it has none, as Node reads a package. */94const targetsOf = ({95 exports,96 main,97}: typeof Manifest.Type): readonly string[] =>
2 unmodified lines
100 : exportTargets(exports);101102const PATTERN = "*";103128/**129 * The repo paths one target names: the target itself, or, for a subpath130 * pattern (`./src/*.ts`), each of `paths` its `*` matches, any run of131 * characters with `/` included, as Node reads one.132 */104const targetPaths = (105 target: string,106 paths: readonly string[]107): readonly string[] => {
22 unmodified lines
130131const joined = (folder: string, path: string) =>132 folder === "" ? path : `${folder}/${path}`;133163/** The folders from `path`'s own up to the root (`""`). */134const foldersAbove = (path: string): readonly string[] => {135 const folders: string[] = [];136 let folder = folderOf(path);137
4 unmodified lines
142143 return [...folders, ""];144};145176/**177 * The module's entry points when the territory names no public files: the178 * source files the `exports` (or else the `main`) of the `package.json`179 * nearest each territory file lead to, a subpath pattern's included.180 */146const manifestEntries = (147 files: readonly RepoFile[],148 territory: NullAnswerTerritory149): readonly string[] => {
35 unmodified lines
185 Array.dedupe186 );187};188224/** A function-like node's body, as returning nothing. */189const bodyEdit = (body: Node | undefined): readonly Edit[] => {190 if (body === undefined) {191 return [];192 }
6 unmodified lines
199 },200 ];201};202239/** An expression without the parentheses and type assertions around it. */203const unwrapped = (node: Node): Node =>204 Node.isParenthesizedExpression(node) ||205 Node.isAsExpression(node) ||206 Node.isSatisfiesExpression(node)207 ? unwrapped(node.getExpression())208 : node;209247/** The edits that make one exported declaration return nothing. */210const stubsOf = (node: Node): readonly Edit[] => {211 if (212 Node.isFunctionDeclaration(node) ||213 Node.isFunctionExpression(node) ||
25 unmodified lines
239240 return [];241};242281/** A file's text with the edits made, from its last edit to its first. */243const edited = (text: string, edits: readonly Edit[]) => {244 const lastFirst = Array.dedupeWith(245 edits,246 (left, right) => left.start === right.start
7 unmodified lines
254255 return result;256};257297/** The declarations a file exports that it declares itself. */258const ownExports = (file: SourceFile): readonly Node[] =>259 [...file.getExportedDeclarations().values()]260 .flat()261 .filter((node) => node.getSourceFile() === file);262303/** A name a stand-in can be declared as (not a string-literal import name). */263const IDENTIFIER = /^[A-Za-z_$][\w$]*$/u;264265const DEFAULT = "default";266308/** A stand-in for a name the territory does not have yet: it returns nothing too. */267const standIn = (name: string) =>268 `export ${name === DEFAULT ? "default function " : `function ${name}`}(..._args: readonly unknown[]): never ${NULL_BODY}`;269312/** A file's text with stand-ins for `names` written after it. */270const withStandIns = (text: string, names: readonly string[]) => {271 const lines = names.map(standIn).join("\n");272273 if (text === "") {
11 unmodified lines
285 [/\.mjs$/u, ".mts"],286 [/\.cjs$/u, ".cts"],287] as const;288332/** The repo path a relative import names, when no file answers it yet. */289const intendedPath = (importer: string, specifier: string) => {290 const segments: string[] = [];291292 for (const segment of [
17 unmodified lines
310311 return SOURCE.test(path) ? path : `${path}.ts`;312};313358/** What an import asks for at run time: its default and its value names. */314const valueNamesOf = (declaration: ImportDeclaration): readonly string[] =>315 declaration.isTypeOnly()316 ? []317 : [
4 unmodified lines
322 .map((specifier) => specifier.getName())323 .filter((name) => IDENTIFIER.test(name)),324 ];325371/**372 * Where a name an import asks of `target` would be declared: `target`373 * itself when it is in the territory, or else the first territory file it374 * re-exports whole (`export * from`, which passes on no default).375 */326const homeOf = (327 territory: NullAnswerTerritory,328 target: SourceFile329): Option.Option<SourceFile> =>
8 unmodified lines
338 Option.filter((file) => inTerritory(territory, repoPathOf(file)))339 )340 );341392/**393 * The names the tree imports from the territory that the territory does not394 * have yet, by the territory file they belong in: a check written before its395 * subject imports a name main lacks, or a file main lacks. A name a file396 * declares but does not export is left out (a stand-in would clash with it).397 */342const wantedNames = (343 project: Project,344 territory: NullAnswerTerritory345): ReadonlyMap<string, readonly string[]> => {
43 unmodified lines
389390const messageOf = (cause: unknown) =>391 cause instanceof Error ? cause.message : globalThis.String(cause);392449/**450 * The new contents of every territory file the entry points reach: each one451 * an entry point lies in, or declares something an entry point exports (at452 * any depth of re-export).453 */393const stubbedContents = (394 files: readonly RepoFile[],395 territory: NullAnswerTerritory,396 entryPaths: readonly string[]
66 unmodified lines
463464 return Result.succeed(contents);465};466528/**529 * The tree with the ask's territory made a null answer: each function and530 * arrow the territory exports returns `undefined as never`, and so does each531 * method and getter of each class it exports. Constructors, setters, values,532 * types and every other file stay as they were. Entry points are the533 * territory's `publicFiles`, or else the source files its `package.json`534 * `exports` (or `main`) lead to; a territory file is stubbed when an entry535 * point lies in it or exports something it declares, through any number of536 * re-exports.537 *538 * A check written before its subject imports what main lacks: each value539 * name the tree imports from a territory file that the file does not export540 * gets a stand-in function there that returns nothing, and a territory file541 * it imports that does not exist is made of stand-ins. So the check loads,542 * and fails, or passes, on what it asserts.543 *544 * The files come back in their order, then any new file in path order; the545 * input is untouched. It reads TypeScript sources (`.ts`, `.mts`, `.cts`,546 * `.tsx`) and follows relative imports only, so `files` holds at least the547 * territory, the manifests naming its entry points, and the check. The null548 * answer has only to run: a project that typechecks with `noUnusedLocals` or549 * `noUnusedParameters` finds the stubs' unread parameters and helpers.550 */467// The null answer has only to run: a project with `noUnusedLocals` or468// `noUnusedParameters` will flag the stubs' unread parameters.469export const nullAnswer = (470 files: readonly RepoFile[],471 territory: NullAnswerTerritory472): Effect.Effect<readonly RepoFile[], NullAnswerFailed> =>
48 unmodified lines
521 ...added,522 ];523 });524607/**608 * What a run of the check against the null answer says of the check:609 * passing it is `WeakCheck{nullAnswer}` (it observes no behaviour), and610 * finding no tests is `WeakCheck{no assertion}`, as in red first. Any other611 * end shows no weakness here; whether the check failed for the right reason612 * (by an assertion) is red first's question, read with `failureSignature`.613 */525export const nullAnswerVerdict = (run: RunEvidence): Option.Option<WeakCheck> =>526 Diagnosis.$match(diagnose(run.exit), {527 Blocked: () => Option.none(),528 Failed: () => Option.none(),
4 unmodified lines
modified:packages/checks/src/phases.ts+3 added-24 removed
1/**2 * The Checker's phases as data. `apps/sandbox` runs the plan; this3 * module only decides it, so its order can be proved over every input:4 *5 * 1. `Setup` installs what the checks need, with egress to the registries and6 * the run block's `setupEgress` only;7 * 2. `Snapshot` saves that install, keyed by what it came from. It is the only8 * snapshot, and it comes before held-back files exist: a snapshot taken9 * after them would carry them into the next Sandbox;10 * 3. `EgressOff` cuts the network, leaving only the platform's handlers;11 * 4. `WriteHeldBack` writes the sealed suite, only when there is one;12 * 5. `Run` runs the lanes, seeing placeholders, never values;13 * 6. `Report` sends back lanes and one bit per area, never logs.14 *15 * With no setup command there is nothing to install or snapshot, so the plan16 * starts at `EgressOff`. The checkout itself comes before the plan.17 */1// `Snapshot` must come before held-back files are written: a snapshot taken2// after them would carry them into the next Sandbox.3import type { RunBlock } from "@repo/protocol/domain/run";4import type { AreaName, EnvKey, LaneName } from "@repo/protocol/ids";5import { Data, Hash, Option } from "effect";622/** A lane as the `Run` phase runs it. */7export interface PlannedLane {8 readonly lane: LaneName;9 readonly command: string;10}
25 unmodified lines
36 readonly run: RunBlock;37 readonly lanes: readonly PlannedLane[];38 readonly heldBack: Option.Option<{ readonly areas: readonly AreaName[] }>;39 readonly placeholders: readonly EnvKey[];56 /** The hash of the project's lockfile at the tree being checked. */40 readonly lockfileHash: string;41}4243const DEFAULT_IMAGE = "checker:default";4462/**63 * A snapshot holds what setup installed, so it is reused only for the same64 * image, setup command, setup hosts and lockfile.45// Reused only for the same image, setup command, setup hosts and lockfile.65 */46const snapshotKey = (47 run: RunBlock,48 command: string,49 egress: readonly string[],
8 unmodified lines
5859 return `setup:${lockfileHash}:${setupHash}`;60};6182/** The phases the Checker runs for one job, in order. */62export const phasePlan = ({63 heldBack,64 lanes,65 lockfileHash,
31 unmodified lines
modified:packages/checks/src/red-first.ts+4 added-20 removed
1/**2 * Red first, for the right reason: an ask opens only when its check3 * fails on main twice in the same way, by an assertion. A check that fails to4 * load fails because its subject is missing, and any answer that exports the5 * subject could pass it; a check that fails two different ways is flaky.6 */1// A check that fails to load fails because its subject is missing, and any2// answer that exports the subject could pass it; a check that fails two3// different ways is flaky.4import type { LaneName } from "@repo/protocol/ids";5import { NotRedFirst, WeakCheck } from "@repo/protocol/refusal";6import { Data, Option, Result } from "effect";78import type { CheckRun } from "./check-runner.ts";9import { diagnose, Diagnosis } from "./classify.ts";10import type { RunExit } from "./classify.ts";1115/** One run of an ask's check on main. */12export interface RunEvidence {13 readonly lane: LaneName;14 readonly exit: RunExit;15}1621/** How the check fails on main, the same both times. */17export interface RedSignature {18 readonly signature: string;19 readonly lane: LaneName;20}2127/** What one run says about the check, for comparing it with the other. */22type Reading =23 | { readonly _tag: "Red"; readonly signature: string }24 | { readonly _tag: "NoTests" }25 | { readonly _tag: "NotRed" };
40 unmodified lines
66 ? Result.succeed({ lane, signature: first.signature })67 : Result.fail(new NotRedFirst({}));68};6976/**77 * Whether two runs of one check, from their exits, failed the same way by an78 * assertion. A run that found no tests is `WeakCheck{no assertion}`; a pass,79 * a load error, a time-out, a throw that is not an assertion, two different80 * failures or two different lanes are `NotRedFirst`.81 */70export const redFirst = ([first, second]: readonly [71 RunEvidence,72 RunEvidence,73]): Result.Result<RedSignature, NotRedFirst | WeakCheck> =>74 first.lane === second.lane75 ? judge(first.lane, [readExit(first.exit), readExit(second.exit)])76 : Result.fail(new NotRedFirst({}));7790/**91 * `redFirst` for the platform, which sees two `CheckRun`s and never their92 * output: the lane must have failed both times with the same evidence93 * signature.94 */78// The platform never sees a run's output, only its evidence signature.79export const redFirstOfRuns = (80 [first, second]: readonly [CheckRun, CheckRun],81 lane: LaneName82): Result.Result<RedSignature, NotRedFirst | WeakCheck> =>
1 unmodified line
modified:packages/checks/src/weak-shapes.ts+8 added-62 removed
1/**2 * The static half of "red for the right reason": five shapes of check3 * that pass whatever the answer does, read from the check file's source4 * before it ever runs. It reads expect-style checks (vitest, jest, bun); a5 * file with no `expect(` call (pytest, go test) is outside it and flags6 * nothing, and the twice-red run still guards it.7 */1// Reads expect-style checks (vitest, jest, bun) only: a file with no2// `expect(` call flags nothing, and the twice-red run still guards it.3import { Array, Option, pipe } from "effect";410/**11 * A shape of check that passes whatever the answer does, as `WeakCheck`'s12 * `weakness` names it.13 */5export type Weakness =6 | "self-referential"7 | "constant pin"8 | "absence-only"9 | "mock-only"10 | "fixture-asserts-fixture";1121/**22 * The check file as an ask carries it: its repo path, which places its23 * relative imports, and its source.24 */12export interface CheckFile {13 readonly path: string;14 readonly content: string;15}1630/** One `expect(subject).matcher(expected)` in the check, as source text. */17interface Expectation {18 readonly subject: string;19 readonly negated: boolean;20 readonly matcher: string;21 readonly expected: string;22}2338/** The check's source twice: without comments, and with string contents blanked too. */24interface Source {25 readonly text: string;26 readonly masked: string;27}2829const QUOTES = new Set(['"', "'", "`"]);3046/** The index just past the string literal that opens at `start`. */31const stringEnd = (source: string, start: number) => {32 const quote = source[start];33 let at = start + 1;34
5 unmodified lines
40};4142const blank = (text: string) => text.replaceAll(/[^\n]/gu, " ");4360/**61 * Comments become spaces in both copies; a string stays in `text` and keeps62 * only its quotes in `masked`. Both keep every index, so a position found in63 * `masked` reads the same span of `text`.64 */44// Both copies keep every index, so a position found in `masked` reads the45// same span of `text`.46const read = (source: string): Source => {47 const text: string[] = [];48 const masked: string[] = [];49 let at = 0;
2 unmodified lines
52 const pair = source.slice(at, at + 2);53 const char = source[at] ?? "";5455 if (pair === "//" || pair === "/*") {75 // A line comment ends before its newline, a block comment after `*/`.56 const close = pair === "//" ? "\n" : "*/";57 const found = source.indexOf(close, at + 2);58 const end = found === -1 ? source.length : found + close.length;59 const span = blank(source.slice(at, end));
17 unmodified lines
7778 return { masked: masked.join(""), text: text.join("") };79};80101/** The index of the `)` that closes the `(` at `open`, in masked source. */81const closing = (masked: string, open: number) => {82 let depth = 0;8384 for (let at = open; at < masked.length; at += 1) {
18 unmodified lines
103 Option.gen(function* () {104 const open = masked.indexOf("(", start);105 const close = yield* closing(masked, open);106128 // `.not`, `.resolves` and `.rejects`, then the matcher's call.107 const chain =108 /\s*(?<modifiers>(?:\.\s*(?:not|resolves|rejects)\s*)*)\.\s*(?<matcher>[A-Za-z_$][\w$]*)\s*\(/uy;109110 chain.lastIndex = close + 1;
35 unmodified lines
146147const segmentsOf = (path: string) =>148 path.split("/").filter((segment) => segment !== "" && segment !== ".");149172/**173 * The folder a territory glob covers: its fixed head (`packages/week/**` →174 * `packages/week`), or, for a glob naming one file, that file's folder, since175 * a check reaches a file through its folder's index too.176 */150// A glob naming one file covers its folder, since a check reaches a file151// through its folder's index too.152const baseOf = (glob: string) => {153 const segments = segmentsOf(glob);154 const fixed = Array.takeWhile(segments, (segment) => !GLOB.test(segment));155
2 unmodified lines
158159 return isFile ? fixed.slice(0, -1) : fixed;160};161187/** A relative import's repo path, resolved from the check file's folder. */162const resolve = (checkPath: string, specifier: string) => {163 const resolved = segmentsOf(checkPath).slice(0, -1);164165 for (const segment of segmentsOf(specifier)) {
9 unmodified lines
175176const startsWith = (path: readonly string[], head: readonly string[]) =>177 head.every((segment, index) => path[index] === segment);178205/**206 * Whether an import reaches into a territory's folder: a relative import207 * that resolves inside it, or to a folder above it (`../src` reaching208 * `src/week.ts` through `src/index.ts`), or a package import whose unscoped209 * name is one of its folders (`@datekit/week` for `packages/week/**`).210 */179const reaches =180 (checkPath: string) => (specifier: string, base: readonly string[]) => {181 if (!specifier.startsWith(".")) {182 const parts = specifier.split("/");
25 unmodified lines
208 .replaceAll(/\b(?:true|false|null|undefined|NaN|Infinity)\b/gu, "0")209 .replaceAll(/[A-Za-z_$][\w$]*\s*:/gu, "")210 );211244/** `not.toThrow()`, `toBeUndefined()`, `toBeFalsy()` and their mirrors. */212const isAbsence = ({ matcher, negated }: Expectation) =>213 negated214 ? ["toThrow", "toThrowError", "toBeDefined", "toBeTruthy"].includes(matcher)215 : ["toBeUndefined", "toBeFalsy"].includes(matcher);
21 unmodified lines
237 each.subject.includes(".mock.") ||238 /\b(?:vi|jest)\.fn\s*\(/u.test(each.subject) ||239 mocks.has(rootOf(each.subject) ?? "");240274/** The names the check binds to a call's result (`const range = weekRange(…)`). */241const resultsOf = ({ text }: Source) =>242 new Set(243 Array.map(244 [
6 unmodified lines
251 );252253const squash = (text: string) => text.replaceAll(/\s+/gu, "");254289/**290 * Expected and actual from one source: the same expression twice, or the291 * subject read straight off the fixture the expected one comes from. A value292 * the check computed is not a fixture: two of its fields may be compared293 * (`expect(range.start).toBeLessThan(range.end)`).294 */255const isFromOneFixture =256 (results: ReadonlySet<string>) =>257 ({ expected, subject }: Expectation) => {258 const root = rootOf(subject);
7 unmodified lines
266 root === rootOf(expected)))267 );268 };269310/** `expect(1).toBe(1)`: a literal held against a literal, or against nothing. */270const isConstantPin = ({ expected, subject }: Expectation) =>271 isLiteral(subject) && (expected === "" || isLiteral(expected));272314/**315 * The weak shapes a check file is in, given the territory's paths (globs).316 * A shape over expectations holds only when every expectation in the file317 * has it, so one real assertion among weak ones keeps the check:318 *319 * - `self-referential`: the check imports nothing from the territory's320 * folders (its relative imports resolved from its own path);321 * - `constant pin`: every expectation holds a literal against a literal322 * (`expect(1).toBe(1)`);323 * - `absence-only`: every expectation is `not.toThrow`, `toBeUndefined` or324 * `toBeFalsy` (or a mirror);325 * - `mock-only`: every expectation is on a `vi.fn()` or a spy;326 * - `fixture-asserts-fixture`: every expectation takes expected and actual327 * from the same fixture, or computes both the same way.328 */273// A shape over expectations holds only when every expectation has it, so one274// real assertion among weak ones keeps the check.275export const weaknessesOf = (276 checkFile: CheckFile,277 territoryPaths: readonly string[]278): readonly Weakness[] => {
29 unmodified lines
modified:packages/checks/src/workspaces.ts+3 added-21 removed
1/**2 * The workspace packages a repo's root manifest declares, read from the3 * files `judgeInputs` gathers (it reads every `package.json`, for the judge4 * closure's own workspace lookups). The platform's facts at a landing and the5 * CLI's local check both read them here, from the same files. Pure.6 */1import { RepoPath } from "@repo/protocol/ids";2import { Array, Option, Predicate, Schema } from "effect";34import type { RepoFile } from "./finder.ts";512/** One workspace package: its folder, its name, and the files its `exports` name. */6export interface Workspace {7 readonly dir: string;8 readonly exports: readonly RepoPath[];9 readonly name: string;
19 unmodified lines
29 value !== undefined && isJsonArray(value)30 ? value.filter(Predicate.isString)31 : [];3240/** A manifest's `workspaces`: an array of globs, or `{ packages: [...] }`. */33const workspaceGlobs = (value: Schema.Json | undefined): readonly string[] => {34 if (value === undefined || value === null) {35 return [];36 }
4 unmodified lines
4142 return isJsonObject(value) ? strings(value.packages) : [];43};4453/** Every string an `exports` field leads to, nested conditions included. */45const exportTargets = (value: Schema.Json | undefined): readonly string[] => {46 if (value === undefined || value === null) {47 return [];48 }
10 unmodified lines
59};6061const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");6272/** The folders directly in `folder` (`""` is the root) that hold any file, in path order. */63const foldersIn = (paths: readonly string[], folder: string) => {64 const prefix = folder === "" ? "" : `${folder}/`;6566 return Array.dedupe(
9 unmodified lines
76 })77 );78};7990/**91 * The folders a workspace glob names: `packages/*` is every folder in92 * `packages`, and a glob with no `*` is its own folder. Deeper globs are93 * read as their folder prefix's children.80// Deeper globs are read as their folder prefix's children.94 */81const foldersOf = (paths: readonly string[], glob: string) => {82 const clean = withoutDotSlash(glob).replace(/\/+$/u, "");83 const star = clean.indexOf("*");84
1 unmodified line
86 ? [clean]87 : foldersIn(paths, clean.slice(0, star).replace(/\/+$/u, ""));88};89104/**105 * Each folder the root `package.json`'s `workspaces` globs name whose own106 * `package.json` has a name, in the globs' order: its folder, its name, and107 * the files its `exports` lead to, from the root. A manifest that doesn't108 * parse (or was too large to read, so its text is empty) declares nothing.109 */90// A manifest that doesn't parse (or was too large, so its text is empty)91// declares nothing.92export const workspacesIn = (93 files: readonly RepoFile[]94): readonly Workspace[] => {95 const sorted = files.toSorted((left, right) =>
32 unmodified lines
modified:packages/checks/test/fixtures/finder/repos.ts-16 removed
1/**2 * Fixture repos for the command finder, as the in-memory file lists the3 * platform reads at a landed commit. Each one is shaped like a real project's4 * CI, hook and script files.5 */1import type { RepoFile } from "../../../src/finder.ts";23const file = (path: string, ...lines: readonly string[]): RepoFile => ({4 content: `${lines.join("\n")}\n`,5 path,6});713/** A Bun workspace whose GitHub workflow installs, lints and tests. */8export const bunWorkspace: readonly RepoFile[] = [9 file(10 "package.json",11 "{",
36 unmodified lines
48 ),49 file("src/index.ts", "export const parse = (text: string) => text;"),50];5158/** A pnpm library on Forgejo, with lefthook running lint and types before a commit. */52export const forgejoLefthook: readonly RepoFile[] = [53 file(54 "package.json",55 "{",
35 unmodified lines
91 " run: pnpm test"92 ),93];94102/** An npm package with husky hooks and no CI. */95export const huskyOnly: readonly RepoFile[] = [96 file(97 "package.json",98 "{",
9 unmodified lines
108 file(".husky/pre-commit", "npx lint-staged", "npm test"),109 file(".husky/_/husky.sh", "#!/usr/bin/env sh", "exit 0"),110];111120/** A Python project: pre-commit runs ruff and mypy, and the workflow runs pytest. */112export const python: readonly RepoFile[] = [113 file(114 ".pre-commit-config.yaml",115 "repos:",
29 unmodified lines
145 ),146 file("pyproject.toml", "[project]", 'name = "fossil"'),147];148158/** A repo with nothing the finder reads. */149export const nothing: readonly RepoFile[] = [150 file("README.md", "# wrec"),151 file("src/main.zig", "pub fn main() void {}"),152];153164/** A broken workflow beside a good one: the broken one is skipped, not thrown. */154export const brokenWorkflow: readonly RepoFile[] = [155 file(".github/workflows/bad.yml", "jobs: [unclosed", " steps: {"),156 file(".github/workflows/shape.yml", "jobs: just a string"),157 file(
4 unmodified lines
162 " - run: go test ./..."163 ),164];165177/** A fence-shaped monorepo with no CI: its root scripts are its gate, run by turbo. */166export const turboMonorepo: readonly RepoFile[] = [167 file(168 "package.json",169 JSON.stringify({
12 unmodified lines
182 JSON.stringify({ scripts: { test: "vitest run" } })183 ),184];185198/**199 * A workflow that runs a fixer, a deploy that builds first, a dev server, an200 * unknown script and both kinds of `ruff format`.201 */186export const mixedWorkflow: readonly RepoFile[] = [187 file(188 "package.json",189 JSON.stringify({
22 unmodified lines
modified:packages/checks/test/fixtures/null-answer/dates.ts-14 removed
1/**2 * A fixture repo for the null answer: a Bun workspace whose `dates` package3 * exports a function (`parse`), an arrow (`format`) and a class (`Clock`)4 * through its `exports` entry, beside a `notes` package no ask's territory5 * holds, and two checks of `parse`: one that observes what it returns and6 * one that only asks that it exists. Then the same `dates` files as the null7 * answer has them, written out by hand.8 */1import type { Schema } from "effect";23import type { RepoFile } from "../../../src/finder.ts";4
4 unmodified lines
910const manifest = (path: string, fields: Schema.JsonObject) =>11 file(path, JSON.stringify(fields, undefined, 2));1221/** The check that only asks that `parse` exists, which any answer passes. */13export const weakCheck = file(14 "checks/weak.test.ts",15 'import { expect, test } from "bun:test";',16 "",
3 unmodified lines
20 " expect(parse).toBeDefined();",21 "});"22);2333/** The check that asserts what `parse` reads a day as. */24export const strongCheck = file(25 "checks/strong.test.ts",26 'import { expect, test } from "bun:test";',27 "",
3 unmodified lines
31 ' expect(parse("2026-10-06")).toStrictEqual({ day: 6, month: 10, year: 2026 });',32 "});"33);3445/** A check written before its subject: `dates` exports no `weekOf` yet. */35export const weakNewCheck = file(36 "checks/week-weak.test.ts",37 'import { expect, test } from "bun:test";',38 "",
3 unmodified lines
42 " expect(weekOf).toBeDefined();",43 "});"44);4557/** The same, asserting the week a day falls in. */46export const strongNewCheck = file(47 "checks/week-strong.test.ts",48 'import { expect, test } from "bun:test";',49 "",
46 unmodified lines
96 " }",97 "",98] as const;99112/** The repo at main, every file a null answer reads. */100export const datesRepo: readonly RepoFile[] = [101 manifest("package.json", {102 name: "dates-repo",103 private: true,
66 unmodified lines
170 weakCheck,171 strongCheck,172];173187/** The `dates` files of `datesRepo` as the null answer has them. */174export const nullDates: readonly RepoFile[] = [175 file(176 "packages/dates/src/index.ts",177 ...datesIndex,
19 unmodified lines
modified:packages/checks/test/kinds/lint-count.test.ts-3 removed
56 unmodified lines
5758const globs = (...patterns: readonly string[]) =>59 patterns.map((pattern) => Glob.make(pattern));6061/** What an unreadable count kept of the output, or `None` when it counted. */61const unreadHead = (result: Result.Result<LintCount, CountUnreadable>) =>62 Result.match(result, {63 onFailure: ({ head }) => Option.some(head),64 onSuccess: () => Option.none(),65 });6668/** Both recordings, each with what makes its paths repo-relative. */67const both = Effect.all({68 eslint: recorded("eslint").pipe(69 Effect.map((output) => ({ output, root: ESLINT_ROOT }))70 ),71 oxlint: recorded("oxlint").pipe(Effect.map((output) => ({ output }))),72});7376/** How many `any`s a recording counts within a territory's globs. */74const anysWithin = (75 input: { readonly output: string; readonly root?: string },76 territory: readonly string[]77) =>
174 unmodified lines
modified:packages/checks/test/kinds/lint-to-zero.test.ts-3 removed
7 unmodified lines
8 lintToZeroRed,9} from "../../src/kinds/lint-to-zero.ts";10import { recorded } from "./recorded.ts";1112// The recordings `lint-count.test.ts` describes: oxlint over a fixture with13// `any` in `packages/parser` and `packages/lexer`, none in `packages/printer`.1412const anysIn = (output: string, territory: string) =>13 Result.getOrThrow(14 countLint({15 output,
47 unmodified lines
modified:packages/checks/test/kinds/metric.test.ts-1 removed
8 unmodified lines
910const read = (output: string, path: string) =>11 readMetric(output, JsonPath.make(path));1213/** What an unreadable count kept of the output, or `None` when it read one. */13const unreadHead = (result: Result.Result<number, CountUnreadable>) =>14 Result.match(result, {15 onFailure: ({ head }) => Option.some(head),16 onSuccess: () => Option.none(),
55 unmodified lines
modified:packages/checks/test/kinds/ratchet.test.ts+1 added-4 removed
29 unmodified lines
30const anyCount = RatchetName.make("anyCount");3132const lintCommand = "oxlint --format json";3334/** Counts `any` with the project's linter, in every territory. */34const counting = RatchetSpec.make({35 measure: RatchetMeasure.cases.Count.make({36 command: Command.make(lintCommand),37 rule: "typescript/no-explicit-any",38 }),39 name: anyCount,40});4143/** Counts `any` in the one territory the spec names. */42const countingIn = (territory: string) =>43 RatchetSpec.make({ ...counting, territory });4445const bundleKb = RatchetName.make("bundleKb");4647const bundleCommand = "bun scripts/bundle-size.ts --json";4851/** Reads one number from a bundle report, for the whole project. */49const bundle = RatchetSpec.make({50 measure: RatchetMeasure.cases.Metric.make({51 command: Command.make(bundleCommand),52 path: JsonPath.make("$.parts[1].kb"),53 }),54 name: bundleKb,55});5660/** A fake runner that prints `stdout` for any command, exiting 1 as a linter with findings does, and keeps what it was asked to run. */57// Exits 1, as a linter with findings does.58const printing = (stdout: string) =>59 Effect.gen(function* () {60 const ran = yield* Ref.make<readonly string[]>([]);61
253 unmodified lines
modified:packages/checks/test/kinds/recorded.ts-6 removed
1/**2 * The recorded linter output the kinds' tests read: stdout byte for byte,3 * from `test/fixtures/lint/<name>.stdout`. `lint-count.test.ts` describes4 * the fixture repo and the commands that printed each one.5 */1import { NodeServices } from "@effect/platform-node";2import { Effect, FileSystem } from "effect";39/** One recording's stdout, by its name without `.stdout`. */4export const recorded = (name: string) =>5 Effect.gen(function* () {6 const fs = yield* FileSystem.FileSystem;7
4 unmodified lines
modified:packages/checks/test/check-runner-local.test.ts-5 removed
21 unmodified lines
22 command,23 lane: LaneName.make(name),24});2526/**27 * A git repo whose `test` script fails, and a runner whose checkout copies28 * it into a fresh temp dir for each job.29 */26const world = Effect.gen(function* () {27 const fs = yield* FileSystem.FileSystem;28 const repo = yield* fs.makeTempDirectoryScoped({ prefix: "datekit-" });29
50 unmodified lines
80 runner.run(81 job([82 lane("test", "bun run test"),83 lane("ok", "exit 0"),88 // The user's git config never reaches a lane.84 lane(85 "isolated",86 `test -z "$(git config --global --get user.name)"`87 ),
150 unmodified lines
modified:packages/checks/test/classify.test.ts-3 removed
47 unmodified lines
48 "Error: Failed to load url ../src/week.ts (resolved id: ../src/week.ts) in /work/datekit/test/week.test.ts. Does the file exist?",49 stdout: " Test Files 1 failed (1)\n Tests no tests",50};5152// A bun-style failure whose assertion line names a path, a duration and an address.52const exit = (path: string, ms: string, address: string): RunExit => ({53 code: 1,54 stderr: `(fail) parses [${ms}]\nAssertionError: ${path}/week.ts took ${ms} at ${address}`,55 stdout: "",56});5759// The same run as the /local runner sees it: output only, never a report.58const withoutReport = ({ code, stderr, stdout }: RunExit): RunExit => ({59 code,60 stderr,61 stdout,
17 unmodified lines
79 expect(classifyRun(unit, { ...vitestNoTests, code: 0 })).toBe("passed");80 });81 });8285 // The /local runner never has a report: vitest's own output decides.83 describe("from vitest's output, with the report left out", () => {84 it("is failed on an assertion", () => {85 expect(classifyRun(unit, withoutReport(vitestAssertion))).toBe("failed");86 expect(failureSignature(withoutReport(vitestAssertion))).toStrictEqual(
144 unmodified lines
modified:packages/checks/test/evidence-store-r2.test.ts-9 removed
5 unmodified lines
6import { EvidenceStore, LogRef } from "../src/evidence-store.ts";7import { EvidenceStoreR2 } from "../src/evidence-store/r2.ts";8import type { EvidenceBucket } from "../src/evidence-store/r2.ts";910/** One object as the fake bucket keeps it: its body and the options it was put with. */10interface Kept {11 readonly text: string;12 readonly options: Parameters<EvidenceBucket["put"]>[2];13}1416/**17 * An R2 bucket in memory, in the shape the Worker's `EVIDENCE` binding has:18 * `put` keeps a body under its key, replacing any there, and `get` answers19 * the body or `null`.20 */15const fakeBucket = () => {16 const objects = new Map<string, Kept>();1718 const bucket: EvidenceBucket = {
13 unmodified lines
3233 return { bucket, objects };34};3542/** A bucket whose every call fails, as R2 does when it cannot be reached. */36const brokenBucket: EvidenceBucket = {37 get: () => Promise.reject(new Error("R2 is unreachable")),38 put: () => Promise.reject(new Error("R2 is unreachable")),39};
7 unmodified lines
47};4849const key = "datekit/push-0123456789/unit#1";5058/** How a call ended, as its defect prints. */51const printed = <A>(call: Effect.Effect<A>) =>52 Effect.map(Effect.exit(call), (exit) =>53 Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "it succeeded"54 );5564/** The store over `bucket`, as the Worker composes it. */56const over = (bucket: EvidenceBucket) =>57 Effect.provide(EvidenceStoreR2(bucket) satisfies Layer.Layer<EvidenceStore>);5859describe("EvidenceStore over an R2 bucket", () => {
114 unmodified lines
modified:packages/checks/test/example-burrow.test.ts-12 removed
1/**2 * The command finder over the fence-shaped example:3 * `examples/burrow`'s tracked files, read as `init` reads a repo's, give the4 * run block burrow's config folder states. Its lanes come from the hooks in5 * `lefthook.yml`, which run its `package.json` scripts; its setup from its6 * lockfile; and one test file's command from its pre-push `bun test`.7 *8 * The finder is pure, so the case only reads files. That burrow's manifest9 * is among them is asserted first, so a missing example is a failed10 * assertion, not an empty run block.11 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { gitOk } from "@repo/testkit/git";4import { Effect, FileSystem, Path } from "effect";56import { findRunBlock } from "../src/finder.ts";7import type { RepoFile } from "../src/finder.ts";820/** burrow's tracked files, by their paths from its own root. */9const burrowFiles = () =>10 Effect.gen(function* () {11 const fs = yield* FileSystem.FileSystem;12 const path = yield* Path.Path;
45 unmodified lines
modified:packages/checks/test/held-back-filter.test.ts-3 removed
37 unmodified lines
38 expect(39 areaBits({40 areas: [parser],41 exits: [42 // An assertion failed.42 exit(parser, 1),44 // The file did not load (a runner's own exit code for that).43 exit(parser, 2),46 // It ran out of time: no exit code of its own.44 exit(parser, -1, true),45 // It exited 0 as the time limit hit: still a timeout.46 exit(parser, 0, true),47 exit(parser, 0),
40 unmodified lines
modified:packages/checks/test/judge-inputs.test.ts-15 removed
1/**2 * `judgeInputs`: the files the finder and the judge closure are handed,3 * chosen from a commit's listing by reading only what their walks reach.4 * The platform's facts and the CLI's local check both gather them through5 * it, so the closure over its files must be the closure over every file.6 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Command } from "@repo/protocol/domain/common";4import type { RunBlock } from "@repo/protocol/domain/run";
10 unmodified lines
15import type { ListedFile } from "../src/judge.ts";1617const file = (path: string, content: string): RepoFile => ({ content, path });1825/**26 * A small monorepo whose judge reaches past the root: a hook config naming a27 * shell script that runs a hook script with a helper, a package tsconfig28 * extending the base and a file of its own, a lint plugin with a helper and29 * a test elsewhere that names it, a config folder whose run block names a30 * check script with a helper beside it, and product code nothing reaches.31 */19const tree: readonly RepoFile[] = [20 file(21 "package.json",22 JSON.stringify({ name: "kit", workspaces: ["packages/*"] })
55 unmodified lines
78 file("scripts/check/surface.ts", "export const surface = () => 0;\n"),79 file("src/app.ts", 'import { a } from "@kit/a";\n\nexport const app = a;\n'),80];8195/** The run block the config folder above declares. */82const run: RunBlock = {83 checks: { [LaneName.make("api")]: Command.make("bun scripts/check/api.ts") },84 test: Command.make("bun test {path}"),85};
2 unmodified lines
8889const listingOf = (files: readonly RepoFile[]): readonly ListedFile[] =>90 files.map(({ path }) => ({ path }));91106/** `judgeInputs` over `files`, and every path it asked to read, batch by batch. */92const gathered = (93 files: readonly RepoFile[],94 listing: readonly ListedFile[] = listingOf(files)95) =>
105 unmodified lines
modified:packages/checks/test/judge.test.ts+1 added-6 removed
23 unmodified lines
24import type { JudgeClosure } from "../src/judge.ts";2526const file = (path: string, content = ""): RepoFile => ({ content, path });2728/** A fence-shaped monorepo: root scripts, a tsconfig chain, a lint config, a hook config. */28const fence: readonly RepoFile[] = [29 file(30 "package.json",31 JSON.stringify({
822 unmodified lines
854const MAX_BYTES = 256 * 1024;855856const encoder = new TextEncoder();857859/** One tracked file of this repo: its path, its size in bytes, and its text (empty above the limit). */858interface Tracked {859 readonly content: string;860 readonly path: string;861 readonly size: number;862}863866/** This repo's tracked files, as `git ls-files` lists them, and its closure. */864class ThisRepo extends Context.Service<865 ThisRepo,866 {867 readonly closure: JudgeClosure;
135 unmodified lines
10031004 expect(judgeClosure(verify, inputs)).toStrictEqual(judge);1005 expect((yield* Ref.get(read)).length).toBeLessThan(files.length);1006 }),1010 // A walk of the whole repo per round, a few rounds: half a second1011 // alone, several while turbo runs every package's tests at once. The1012 // limit catches a hang, not a busy machine.1007 // The limit catches a hang, not a busy machine.1008 { timeout: 30_000 }1009 );10101011 repo.effect(
54 unmodified lines
modified:packages/checks/test/null-answer.test.ts-4 removed
28 unmodified lines
29const unit = LaneName.make("unit");3031const onUnit = (exit: RunExit) => ({ exit, lane: unit });3233/** A tree as path → content, to compare whole trees at once. */33const contentsOf = (files: readonly RepoFile[]) =>34 Object.fromEntries(files.map(({ content, path }) => [path, content]));3536describe("the null answer", () => {
219 unmodified lines
256257const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>258 bytes.pipe(Stream.decodeText(), Stream.mkString);259261/** The tree in a temp folder of its own, removed when the scope closes. */260const written = (files: readonly RepoFile[]) =>261 Effect.gen(function* () {262 const fs = yield* FileSystem.FileSystem;263 const path = yield* Path.Path;
8 unmodified lines
272273 return dir;274 });275278/** Runs `command` in `dir` under `sh -c`, as the Checker runs a lane: how it ended. */276const ran = (dir: string, command: string) =>277 Effect.scoped(278 Effect.gen(function* () {279 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
58 unmodified lines
338 );339});340341describe("a check written before its subject", () => {345 /** Main with two checks of `weekOf`, which no file exports yet. */342 const beforeWeekOf = [...datesRepo, weakNewCheck, strongNewCheck];343344 it.live("fails on main by a load error, not an assertion", () =>345 Effect.gen(function* () {
115 unmodified lines
modified:packages/checks/test/phases.test.ts-3 removed
37 unmodified lines
3839const keyOf = (phases: readonly Phase[]) =>40 phases.flatMap((phase) => (Phase.$is("Snapshot")(phase) ? [phase.key] : []));4142// Every input combination: setup or none, extra setup hosts or none,43// held-back or none, placeholders or none, and zero, one or two lanes.42const { setup: _setup, setupEgress: _egress, ...bare } = run;4344const runBlocks: readonly RunBlock[] = [45 bare,
96 unmodified lines
142 at("WriteHeldBack") === -1 ? [] : order.slice(at("WriteHeldBack"));143144 expect(afterWrite).not.toContain("Snapshot");145148 // Egress is off before the run, and the report comes last.146 expect(147 order.filter((tag) => ["EgressOff", "Run", "Report"].includes(tag))148 ).toStrictEqual(["EgressOff", "Run", "Report"]);149 expect(order.at(-1)).toBe("Report");
17 unmodified lines
modified:packages/checks/test/red-first.test.ts-1 removed
18 unmodified lines
19const passed: RunExit = { code: 0, stderr: "", stdout: " 1 pass\n 0 fail" };2021const notRedFirst = Result.fail(new NotRedFirst({}));2223// What the platform sees of a run: lanes and evidence, never the output.23const checkRun = (24 result: CheckRun["lanes"][number]["result"],25 evidence: Omit<CheckRun["evidence"][number], "lane">26): CheckRun => ({
130 unmodified lines
modified:packages/checks/test/weak-shapes.test.ts-2 removed
1import { describe, expect, it } from "@effect/vitest";23import { weaknessesOf } from "../src/weak-shapes.ts";45// The check files are datekit's, held as text: the lint reads source, never6// runs it. The territory is what `territory.package` gives a workspace.5const territory = ["packages/week/**"];67const check = (8 imports: string,
218 unmodified lines
modified:packages/protocol/src/domain/answer.ts+1 added-23 removed
12 unmodified lines
13 TreeSha,14} from "../ids.ts";15import { Outcome, StageName } from "./outcome.ts";1617/** How one lane's run ended. A load error is not a failure by an assertion. */17export const LaneOutcome = Schema.Literals([18 "passed",19 "failed",20 "loadError",
2 unmodified lines
23]);2425export type LaneOutcome = typeof LaneOutcome.Type;2628/** One lane of the project's checks, run on an answer's merged tree. */27export const LaneResult = Schema.Struct({28 command: Schema.NonEmptyString,29 durationMs: Schema.Int,30 lane: LaneName,33 /** Where the platform keeps the log; an answerer reads it through the platform, never raw. */31 logRef: Schema.optionalKey(Schema.NonEmptyString),32 result: LaneOutcome,33});3435export type LaneResult = typeof LaneResult.Type;3640/**41 * Held-back checks in one area: how many passed, of how many, under which42 * commitment. Nothing else about them is disclosed.43 */37/** Held-back checks in one area. Nothing beyond these counts is disclosed. */38export const HeldBackResult = Schema.Struct({39 area: AreaName,40 passed: Schema.Int,41 suite: SuiteRoot,
1 unmodified line
43});4445export type HeldBackResult = typeof HeldBackResult.Type;4653/**54 * The record of one check run on an answer: base, head, the merged tree, the55 * patch id, the check version and the platform as verifier, with each lane56 * and the outcome. It is kept with the landing.57 */47export const Verdict = Schema.Struct({48 ask: AskId,49 at: Schema.DateTimeUtcFromString,50 base: CommitSha,
3 unmodified lines
54 lanes: Schema.Array(LaneResult),55 outcome: Outcome,56 patchId: PatchId,57 project: ProjectName,69 /** The furthest stage the answer reached. */58 stage: StageName,71 /** The merged tree the checks ran on. */59 tree: TreeSha,60 verifier: Schema.Literal("platform"),61});6263export type Verdict = typeof Verdict.Type;6478/**79 * What an answerer gets back on offering an answer: the request, and where80 * the answer stands, usually still being checked.81 */65export const AnswerReceipt = Schema.Struct({66 ask: AskId,67 base: CommitSha,68 head: CommitSha,
3 unmodified lines
72});7374export type AnswerReceipt = typeof AnswerReceipt.Type;7593/**94 * What a decider gets back on landing their own change from their working95 * fork: an answer's receipt without an ask, since such a landing answers none.96 */76export const LandReceipt = AnswerReceipt.mapFields(Struct.omit(["ask"]));7778export type LandReceipt = typeof LandReceipt.Type;79101/** One of a person's answers, as their status shows it. */80export const AnswerView = Schema.Struct({81 ask: AskId,82 at: Schema.DateTimeUtcFromString,83 head: CommitSha,
5 unmodified lines
modified:packages/protocol/src/domain/ask.ts-18 removed
9 unmodified lines
10} from "../ids.ts";11import { CheckSpec } from "./check.ts";12import { Territory } from "./territory.ts";1314/**15 * An ask's brief: what an answerer reads first. The want is behavioural; it16 * names no file and no line.17 */14export const Brief = Schema.Struct({15 context: Schema.optionalKey(Schema.Array(Schema.NonEmptyString)),20 /** What happens on main today. */16 current: Schema.optionalKey(Schema.NonEmptyString),17 outOfScope: Schema.optionalKey(Schema.NonEmptyArray(Schema.NonEmptyString)),23 /** Words the ask uses in its project's sense. */18 terms: Schema.optionalKey(Schema.Array(Schema.NonEmptyString)),19 want: Schema.NonEmptyString,20});2122export type Brief = typeof Brief.Type;2330/** Where an ask stands: open, claimed, waiting on its parent, or closed. */24export const AskState = Schema.Literals([25 "open",26 "claimed",27 "waitingOnParent",
1 unmodified line
29]);3031export type AskState = typeof AskState.Type;3240/** Who an ask is held for, when it is held for someone: `newcomers` (with a mentor) or `people`. */33export const Reserve = Schema.Literals(["newcomers", "people"]);3435export type Reserve = typeof Reserve.Type;3645/**46 * An ask: a file on main in which a project states one change it wants, with47 * a behavioural want, a territory, and a check that fails on main.48 */37export const Ask = Schema.Struct({38 askedBy: Handle,51 /** Asks that must land first, as a migrate's last step waits on its siblings. */39 blockedBy: Schema.Array(AskId),40 brief: Brief,41 check: CheckSpec,55 /** The ask's file on main, in the config folder's `asks/`. */42 file: RepoPath,43 id: AskId,44 kind: KindName,45 mentor: Schema.optionalKey(Handle),46 openedAt: Schema.DateTimeUtcFromString,61 /** The landing that opened it. */47 openedIn: LandedSha,63 /** The migrate ask this one is a step of. */48 parent: Schema.optionalKey(AskId),49 project: ProjectName,50 reserve: Schema.optionalKey(Reserve),51 state: AskState,
1 unmodified line
53});5455export type Ask = typeof Ask.Type;5673/** One open ask, as a list of asks shows it. */57export const AskListing = Schema.Struct({58 ask: AskId,59 blockedBy: Schema.Array(AskId),60 claimed: Schema.Boolean,61 kind: KindName,62 reserve: Schema.optionalKey(Reserve),80 /** The territory's module. */63 territory: Schema.NonEmptyString,64 want: Schema.NonEmptyString,65});66
1 unmodified line
modified:packages/protocol/src/domain/check.ts-20 removed
1 unmodified line
23import { RatchetName, RepoPath } from "../ids.ts";4import { Command, JsonPath, SymbolName } from "./common.ts";56/**7 * An ask's check: what judges an answer to it, by check kind. `RedThenGreen`8 * runs the run block's `test` on one file; the others count something with a9 * command of the project's own.10 */6export const CheckSpec = Schema.TaggedUnion({12 /** A lint rule's count goes to zero in the territory. */7 LintToZero: {8 command: Command,9 rule: Schema.NonEmptyString,10 territory: Schema.optionalKey(Schema.NonEmptyString),
3 unmodified lines
14 count: Command,15 from: SymbolName,16 to: Schema.optionalKey(SymbolName),17 },24 /** A named ratchet goes down. */18 Ratchet: { ratchet: RatchetName },26 /** One check file fails on main by an assertion, and passes on the answer. */19 RedThenGreen: { path: RepoPath },28 /** The last step of a migrate: `symbol` is gone. */20 SymbolAbsent: { count: Command, symbol: SymbolName },21});2223export type CheckSpec = typeof CheckSpec.Type;2434/**35 * How strong an ask's check must be: failing on main by an assertion, or36 * also failing a null answer.37 */25export const Strength = Schema.Literals(["assertion", "nullAnswer"]);2627export type Strength = typeof Strength.Type;2842/** How a ratchet measures its number: a lint count, or a number in a command's JSON. */29export const RatchetMeasure = Schema.TaggedUnion({44 /** Counts lint findings from oxlint or ESLint JSON, for one rule or all. */30 Count: { command: Command, rule: Schema.optionalKey(Schema.NonEmptyString) },46 /** Reads one number at `path` in the command's JSON output. */31 Metric: { command: Command, path: JsonPath },32});3334export type RatchetMeasure = typeof RatchetMeasure.Type;3552/**53 * A ratchet: a counted budget per territory that answers may lower and never54 * raise; only a decider raises it.55 */36export const RatchetSpec = Schema.Struct({37 measure: RatchetMeasure,38 name: RatchetName,39 territory: Schema.optionalKey(Schema.NonEmptyString),
3 unmodified lines
modified:packages/protocol/src/domain/claim.ts-12 removed
7 unmodified lines
8 RepoName,9 SuiteRoot,10} from "../ids.ts";1112/**13 * Where a claim stands. A live claim is warned after a quiet spell and14 * lapses after a longer one; only a push keeps it alive.15 */12export const ClaimState = Schema.Literals([13 "live",14 "warned",15 "lapsed",
2 unmodified lines
18]);1920export type ClaimState = typeof ClaimState.Type;2126/**27 * A claim, as its claimant sees it: one person's exclusive, expiring right to28 * answer an ask, with the fork to push to and when it lapses.29 */22export const ClaimView = Schema.Struct({23 ask: AskId,32 /** Main's landed commit when the claim was made. */24 base: CommitSha,34 /** What `<cli> check` runs locally for this ask. */25 checkCommand: Schema.NonEmptyString,26 claimant: Handle,37 /** The claim's fork: `<project>--<ask>--<handle in lowercase>`. */27 fork: RepoName,28 lapsesAt: Schema.DateTimeUtcFromString,29 lastPushAt: Schema.optionalKey(Schema.DateTimeUtcFromString),30 openedAt: Schema.DateTimeUtcFromString,31 project: ProjectName,32 /** The fork's URL at the gateway; never a storage URL. */33 remote: Schema.NonEmptyString,34 state: ClaimState,46 /** The held-back suite pinned when the claim was made. */35 suite: Schema.optionalKey(SuiteRoot),36 warnsAt: Schema.DateTimeUtcFromString,37});38
1 unmodified line
modified:packages/protocol/src/domain/code.ts+2 added-45 removed
1/**2 * A project's code as its readers browse it: refs, trees, files, commits3 * and "why" per line, each read from the project's canonical repo only (no4 * payload names a repo). Every read names the 40-hex commit it resolved5 * to (`at`), so any page can become a permalink.6 */1// Read from the project's canonical repo only: no payload names a repo.2import { Option, Schema } from "effect";34import {5 AskId,
8 unmodified lines
14} from "../ids.ts";15import { ClaimState } from "./claim.ts";16import { LandingView } from "./landing.ts";1723/** A tag's name, as `refs/tags/<name>` spells it: `v1.2.0`, `@changesets/cli@2.27.1`. */18export const TagName = Schema.NonEmptyString.check(19 Schema.isMaxLength(255)20).pipe(Schema.brand("TagName"));2122export type TagName = typeof TagName.Type;2330/**31 * The package a tag versions: the name before its last `@`, when that `@`32 * is past the first character (`@changesets/cli@2.27.1` versions33 * `@changesets/cli`, `get-workspaces@1.0.11` versions `get-workspaces`).34 * A tag with no such `@` (`v1.2.3`, a bare scope) versions no package. The35 * platform orders tags by it and the refs page groups them by it.36 */24export const packageOf = (tag: string): Option.Option<string> => {25 const at = tag.lastIndexOf("@");2627 return at > 0 ? Option.some(tag.slice(0, at)) : Option.none();28};2943/**44 * A revision as a reader names it: `main` (the landed commit), a full45 * 40-hex commit id, or a tag's name. Decoded into one of the three where46 * it is read; anything else is `UnknownRevision`.47 */30export const Rev = Schema.String.check(31 Schema.isMinLength(1),32 Schema.isMaxLength(255)33);3435export type Rev = typeof Rev.Type;3655/** One tag, peeled to the commit it names. */37export const TagRef = Schema.Struct({ name: TagName, sha: CommitSha });3839export type TagRef = typeof TagRef.Type;4060/**61 * One fork of the project: a claim's (`<project>--<ask>--<handle>`), with62 * its ask and the claim's state, or a person's working fork.63 */41export const ForkRef = Schema.Struct({42 ask: Schema.optionalKey(AskId),43 handle: Handle,44 kind: Schema.Literals(["claim", "working"]),
2 unmodified lines
47});4849export type ForkRef = typeof ForkRef.Type;5074/** A project's refs as a reader sees them: main's landed commit, its tags and its forks. */51export const RefsView = Schema.Struct({52 forks: Schema.Array(ForkRef),53 landed: Schema.optionalKey(LandedSha),54 project: ProjectName,
1 unmodified line
56});5758export type RefsView = typeof RefsView.Type;5984/** One entry of a directory. */60export const CodeEntry = Schema.Struct({61 mode: Schema.String,62 name: Schema.NonEmptyString,63 path: RepoPath,
2 unmodified lines
66});6768export type CodeEntry = typeof CodeEntry.Type;6995/** One directory at one commit: folders first, then by name, and its README when it has one. */70export const TreeListing = Schema.Struct({71 at: CommitSha,72 entries: Schema.Array(CodeEntry),99 /** Absent for the root. */73 path: Schema.optionalKey(RepoPath),74 readme: Schema.optionalKey(Schema.Struct({ path: RepoPath, sha: BlobSha })),75});7677export type TreeListing = typeof TreeListing.Type;78106/** Every file path at one commit, for a file tree; `truncated` past the cap. */79export const PathList = Schema.Struct({80 at: CommitSha,81 paths: Schema.Array(RepoPath),82 truncated: Schema.Boolean,83});8485export type PathList = typeof PathList.Type;86115/**116 * One file at one commit. `text` is absent for a binary file and for one117 * past the size cap (`truncated`).118 */87export const FileView = Schema.Struct({88 at: CommitSha,89 binary: Schema.Boolean,90 path: RepoPath,
4 unmodified lines
95});9697export type FileView = typeof FileView.Type;98131/** Who wrote or committed a commit, and when. */99export const Signature = Schema.Struct({100 at: Schema.DateTimeUtcFromString,101 email: Schema.String,102 name: Schema.String,103});104105export type Signature = typeof Signature.Type;106140/**141 * One commit as a reader sees it. `landing` is the platform's own record of142 * it, when it is a landing: a trailer in an imported commit never makes one.143 */107/** `landing` is the platform's own record: a trailer in an imported commit never makes one. */108export const CommitView = Schema.Struct({109 author: Signature,110 body: Schema.String,111 committer: Signature,
8 unmodified lines
120});121122export type CommitView = typeof CommitView.Type;123160/** One file a commit changed, against its first parent. */124export const ChangedFile = Schema.Struct({125 after: Schema.optionalKey(BlobSha),126 before: Schema.optionalKey(BlobSha),127 binary: Schema.Boolean,
4 unmodified lines
132});133134export type ChangedFile = typeof ChangedFile.Type;135173/** A commit and what it changed; past the caps, paths only and `truncated`. */136export const CommitDiff = Schema.Struct({137 commit: CommitView,138 files: Schema.Array(ChangedFile),139 truncated: Schema.Boolean,
9 unmodified lines
149});150151export type WhyRange = typeof WhyRange.Type;152191/**192 * Why each line of a file is there: the first-parent commit that brought193 * it, and that commit's landing when it is one. Lines older than the walk194 * reached go to `stoppedAt`.195 */153export const WhyView = Schema.Struct({154 at: CommitSha,155 commits: Schema.Array(CommitView),156 landings: Schema.Array(LandingView),
6 unmodified lines
modified:packages/protocol/src/domain/common.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/credit.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/decision.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/env.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/event.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/front-page.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/kind.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/landing.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/outcome.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/policy.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/proposal.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/record.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/run.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/territory.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/domain/visibility.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/annotations.ts+2 added-26 removed
1import { Context, Schema } from "effect";23/**4 * What every contract says about itself, beside its schemas. Each is set with5 * `.annotate(Key, value)` on `Rpc.make(…)` and read with `Context.get`; a6 * contract that sets none gets the defaults below.7 */89/** What a contract does, in one sentence, for every surface that lists it. */3export const Description = Context.Reference<string>("protocol/Description", {4 defaultValue: () => "",5});614/**15 * Who may call it: anyone, a signed-in person, or one of the project's16 * deciders. The handler checks `decider`; the annotation documents it.17 */7export const Audience = Context.Reference<"public" | "signedIn" | "decider">(8 "protocol/Audience",9 { defaultValue: () => "signedIn" }10);1123/** Whether its response may be shown to anyone, or only to maintainers. */12export const Visibility = Context.Reference<"public" | "maintainers">(13 "protocol/Visibility",14 { defaultValue: () => "public" }15);1629/** It only reads: it changes nothing. */17export const ReadOnly = Context.Reference<boolean>("protocol/ReadOnly", {18 defaultValue: () => false,19});2034/** Calling it again with the same payload changes nothing more. */21export const Idempotent = Context.Reference<boolean>("protocol/Idempotent", {22 defaultValue: () => false,23});2439/**40 * It can destroy something a person cannot get back. Set it on every41 * contract: every tool carries this value, so a destructive contract that42 * forgot it would tell an agent it is safe (`annotations.test.ts` holds this).43 */25export const Destructive = Context.Reference<boolean>("protocol/Destructive", {26 defaultValue: () => false,27});2848/** A person approves it before it runs: the CLI asks for `--yes`. */29export const NeedsApproval = Context.Reference<boolean>(30 "protocol/NeedsApproval",31 { defaultValue: () => false }32);3334/**55 * The CLI command it becomes: its name, the payload fields taken in order,56 * and those of them that were flags until now (`formerFlags`): each still57 * parses as a flag of its own name, hidden from help, so a script that types58 * it keeps working for a release. Drop a name from `formerFlags` to end that.35 * `formerFlags`: positionals that still parse as hidden flags of their own36 * name, so scripts that type them keep working for a release.37 */38export const Cli = Context.Reference<{39 readonly name?: string;40 readonly positional?: readonly string[];41 readonly formerFlags?: readonly string[];42}>("protocol/Cli", { defaultValue: () => ({}) });4366/** Every surface a contract can be served on. */44export const SurfaceName = Schema.Literals(["rpc", "mcp", "cli", "web"]);4546export type SurfaceName = typeof SurfaceName.Type;4771/** The surfaces it is served on; every one by default. */48export const Surfaces = Context.Reference<readonly SurfaceName[]>(49 "protocol/Surfaces",50 { defaultValue: () => SurfaceName.literals }51);
modified:packages/protocol/src/audit.ts+3 added-34 removed
1/**2 * Which harness runs the CLI, read from the env the harness gives its3 * children, and how that travels to the platform: as the basic-auth4 * username git sends beside the token. It is audit metadata, never5 * identity: the token in the password slot is the only identity. The env6 * table lives here once; the CLI's agent policy and git's credential helper7 * both read it through `detectHarness`.8 */1// The harness travels as the basic-auth username: audit metadata, never2// identity. The token in the password slot is the only identity.3import { Option, Schema } from "effect";4import type { Types } from "effect";512/** What the platform records of the harness behind a call. */6export const HarnessAudit = Schema.Struct({7 harness: Schema.optionalKey(Schema.NonEmptyString),8 model: Schema.optionalKey(Schema.NonEmptyString),9 session: Schema.optionalKey(Schema.NonEmptyString),10});1112export type HarnessAudit = typeof HarnessAudit.Type;1321/** Whether an env name is one of a harness's markers. */14const named =15 (...names: readonly string[]) =>16 (key: string) =>17 names.includes(key);1819const prefixed = (prefix: string) => (key: string) => key.startsWith(prefix);2029/**30 * Each harness and the env names that mark it, in the order they are31 * tried. `AI_AGENT` comes before all of them and is taken verbatim.32 */21const markers = [22 {23 harness: "claude-code",24 marks: named("CLAUDECODE", "CLAUDE_CODE", "CLAUDE_CODE_ENTRYPOINT"),
8 unmodified lines
33 readonly harness: string;34 readonly marks: (key: string) => boolean;35}[];3649/** `value`, unless it is absent or empty. */37const given = (value: string | undefined) =>38 value === undefined || value === "" ? undefined : value;3953/** pi's model, as `provider/model` when pi names both. */40const piModel = (env: Readonly<Record<string, string | undefined>>) => {41 const model = given(env.PI_MODEL);42 const provider = given(env.PI_PROVIDER);43
1 unmodified line
45 ? model46 : `${provider}/${model}`;47};4863/**64 * The harness `env` says runs this process: `AI_AGENT` verbatim, else the65 * first harness whose marker is set. pi also names its model66 * (`PI_PROVIDER/PI_MODEL`) and session (`PI_SESSION_ID`) to its children.67 */49export const detectHarness = (50 env: Readonly<Record<string, string | undefined>>51): HarnessAudit => {52 const set = Object.keys(env).filter((key) => given(env[key]) !== undefined);
27 unmodified lines
8081 return audit;82};83103/** The username's fields, in the order they are written. */84const fields = ["harness", "model", "session"] as const;8586const PREFIX = "audit;";87108/**109 * The longest value a field keeps: three of them, with the prefix and their110 * keys, stay within 200 characters (30 + 3 × 56 = 198).88// Three fields with the prefix and keys stay within 200 characters (30 + 3 × 56 = 198).111 */89const VALUE_LIMIT = 56;90114/** `value` with every character a username field can't carry as `_`, cut to the limit. */91const clean = (value: string) =>92 value.replaceAll(/[^A-Za-z0-9._/-]/gu, "_").slice(0, VALUE_LIMIT);93118/**119 * The basic-auth username that carries `audit`:120 * `audit;harness=pi&model=moonshot/kimi-k3`. Values keep `[A-Za-z0-9._/-]`121 * and turn anything else into `_`, so `;`, `&`, `=` and `:` never occur in122 * one; the whole stays within 200 characters.123 */94export const auditUser = (audit: HarnessAudit): string =>95 `${PREFIX}${fields96 .flatMap((field) => {97 const value = audit[field];
3 unmodified lines
101 .join("&")}`;102103const Pair = /^(?<field>harness|model|session)=(?<value>[A-Za-z0-9._/-]+)$/u;104135/** What an `auditUser` username carries; none for any other username. */105export const parseAuditUser = (user: string): Option.Option<HarnessAudit> => {106 if (!user.startsWith(PREFIX)) {107 return Option.none();108 }
16 unmodified lines
modified:packages/protocol/src/authenticate.ts+3 added-11 removed
7 unmodified lines
8 Unauthenticated,9} from "./principal.ts";10import type { Person, Principal } from "./principal.ts";1112/**13 * The credential in an `authorization: Bearer <token>` header, if it holds14 * one; the scheme matches in any case (RFC 7235 §2.1). A host's HTTP gate15 * reads it with this too, so the gate and the server side agree on what a16 * credential is.17 */12export const bearerToken = (authorization: string | undefined) =>13 Option.fromNullishOr(14 /^Bearer (?<token>\S+)$/iu.exec(authorization ?? "")?.groups?.token15 );1617/**24 * Server side of `Authenticated`: a credential names a Person; no credential25 * is Anonymous only for a `public` contract. A credential `verify` doesn't26 * know is refused, never taken for anyone, and so is an `authorization`27 * header that holds no bearer token. A `verify` that fails can't say who is28 * calling, so the call dies rather than run as anyone.18 * An unknown credential, or an `authorization` header with no bearer token,19 * is refused, never taken for anyone; a failing `verify` kills the call20 * rather than run it as anyone.21 */22export const authenticated = <E, R>(23 verify: (credential: string) => Effect.Effect<Option.Option<Person>, E, R>24): Layer.Layer<Authenticated, never, R> =>
43 unmodified lines
modified:packages/protocol/src/cli.ts+4 added-100 removed
48 unmodified lines
49import { ExitCode, exitCodeFor } from "./exit-code.ts";50import type { Unauthenticated } from "./principal.ts";51import { Refusal } from "./refusal.ts";5253/** How a call can fail before its handler runs: in transit, or unauthenticated. */53type CallError = RpcClientError.RpcClientError | Unauthenticated;5456/** A schema that needs no services to decode or encode, as every wire schema is. */55type Plain = Schema.Top & {56 readonly DecodingServices: never;57 readonly EncodingServices: never;58};5962/**63 * An Rpc a command can project: its payload is a struct of plain fields, or64 * a record that takes none (`listProjects`).65 */60export type CommandRpc = Rpc.AnyWithProps & {61 readonly errorSchema: Plain;62 readonly payloadSchema: Plain;63 readonly successSchema: Plain;64};6572/** A result as prose: Markdown, and plain text where a person reads it. */66export interface View {67 readonly markdown: string;68 readonly text?: string;69}7078/**79 * How a projected command prints. apps/cli's `Output` implements it, and80 * decides the form: text for a person, Markdown for an agent, one `--json`81 * envelope for a script.82 */71export interface CommandOutput {84 /** The command's result; `data` is its encoded success. */72 readonly success: (input: {73 readonly command: string;74 readonly json: boolean;75 readonly data: unknown;76 readonly view: View;77 }) => Effect.Effect<void>;91 /** The refusals the command met instead: printed there, and only there. */78 readonly refused: (input: {79 readonly command: string;80 readonly json: boolean;81 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;82 }) => Effect.Effect<void>;97 /** What `--dry-run` would send; `payload` is encoded. */83 readonly plan: (input: {84 readonly command: string;85 readonly json: boolean;86 readonly payload: unknown;87 }) => Effect.Effect<void>;88}89105/**106 * Values for payload fields a person may leave out, such as the project the107 * repo they stand in belongs to.108 */90export interface Defaults<R> {110 /** The fields it may fill, each with where its value comes from, for `--help`. */91 readonly fields: Readonly<Record<string, string>>;112 /**113 * Their values, as typed on the command line. Read only when a required114 * field it may fill was left out; a field it has no value for stays out.115 */92 readonly values: Effect.Effect<Readonly<Record<string, string>>, never, R>;93}9495export interface ToCommandOptions<Success, OutputR, DefaultsR> {120 /** Where the command prints its result, its refusals and its plan. */96 readonly output: Effect.Effect<CommandOutput, never, OutputR>;97 readonly defaults?: Defaults<DefaultsR> | undefined;123 /** The result as prose; none, or none given, prints the encoded JSON. */98 readonly render?: ((success: Success) => Option.Option<View>) | undefined;125 /**126 * The refusals a success carries in place of a result, such as a refused127 * answer's receipt: they print as a refusal does, once, and the command128 * fails with `Reported`.129 */99 readonly refusalsIn?: ((success: Success) => readonly Refusal[]) | undefined;100}101133/**134 * Each contract's result as prose, by tag. A view reads any contract's135 * success and renders the one it knows; a contract with no view prints its136 * encoded JSON.137 */102export type Views<Rpcs extends Rpc.Any> = Readonly<103 Record<string, (success: Rpc.Success<Rpcs>) => Option.Option<View>>104>;105142/**143 * A command that changes something a person must approve ran without144 * `--yes`. A usage error: nothing was called.145 */106export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(107 "ApprovalNeeded",108 { command: Schema.String }109) {
1 unmodified line
111 return `${this.command} needs a person's approval: run it again with --yes, or with --dry-run to see what it would send`;112 }113}114155/**156 * A required payload field was given neither on the command line nor by the157 * defaults. A usage error: nothing was called, and nobody was asked for it.158 */115export class MissingValue extends Schema.TaggedError<MissingValue>()(116 "MissingValue",117 { command: Schema.String, flag: Schema.String }118) {
1 unmodified line
120 return `${this.command} needs ${this.flag}: give it, since nothing here does`;121 }122}123168/**169 * Everything a command printed has been printed: the program exits with170 * `exitCode` (1 unless refusals set it) and prints nothing more, and the171 * runtime reports nothing of its own.172 */124export class Reported extends Schema.TaggedError<Reported>()("Reported", {125 exitCode: Schema.optionalKey(Schema.Int),126}) {127 override readonly [Runtime.errorExitCode] = this.exitCode ?? ExitCode.failed;128 override readonly [Runtime.errorReported] = false;129179 /** Refusals printed: the program exits with the code they share (`exitCodeFor`). */130 static readonly of = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>131 new Reported({ exitCode: exitCodeFor(refusals) });132}133184/**185 * Hands `refusals` to `output` once, then ends the command as `Reported`186 * with their exit code: how every command meets a refusal.187 */134export const endRefused = (135 output: Pick<CommandOutput, "refused">,136 input: Parameters<CommandOutput["refused"]>[0]137): Effect.Effect<never, Reported> =>
76 unmodified lines
214215 return { description, kind, literals: [], optional };216};217272/**273 * A payload's fields, by name: a struct's, or none for a payload that takes274 * nothing (an empty record, which an MCP tool's input needs).275 */218const fieldsOf = (payload: Plain): readonly (readonly [string, Plain])[] =>219 SchemaAST.isObjects(payload.ast)220 ? payload.ast.propertySignatures.flatMap(({ name, type }) =>221 Predicate.isString(name)
1 unmodified line
223 : []224 )225 : [];226285/** Whether a person must give the field: a switch is off unless named. */227const isRequired = (spec: FieldSpec) =>228 !spec.optional && spec.kind !== "boolean" && spec.kind !== "switch";229230const jsonFlag = (name: string, field: Plain) =>
9 unmodified lines
240 number: (name) => Flag.Finite(name),241 // The field's own schema checks the text, so a malformed value is refused242 // by the parser, naming its flag, before anything is called.243 string: (name, field) => Flag.String(name).pipe(Flag.withSchema(field)),303 // On when named; left out of the payload otherwise.244 switch: (name) =>245 Flag.Boolean(name).pipe(246 Flag.withDefault(false),247 Flag.map((on) => (on ? true : undefined))
2 unmodified lines
250 FieldSpec["kind"],251 (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>252>;253314/** A field's help text, and where its default comes from when it has one. */254const helpOf = (spec: FieldSpec, fallback: string | undefined) => {255 if (fallback === undefined) {256 return spec.description;257 }
2 unmodified lines
260 ? `Defaults to ${fallback}`261 : `${spec.description}; defaults to ${fallback}`;262};263325/**326 * A field as a flag. It is optional when the payload says so, or when the327 * defaults may fill it; the handler then says if it is still missing.328 */264const flagFor = (265 name: string,266 field: Plain,267 fallback: string | undefined
30 unmodified lines
298 (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>299>;300301/**367 * An argument that was a flag until now, left out: none yet. The parser368 * takes it so, since the flag it was may still give its value, and the369 * handler says if neither did (`MissingValue`). Unlike `Argument.optional`,370 * a fallback leaves help showing the argument as required.302 * The former flag may still give the value, so the parser lets the argument303 * be left out and the handler refuses if neither did. Unlike304 * `Argument.optional`, a fallback keeps help showing it as required.305 */306const leftOutForNow = (307 argument: Argument.Argument<unknown>308): Argument.Argument<unknown> =>
25 unmodified lines
334335 return wasFlag ? leftOutForNow(described) : described;336};337404/**405 * The flag a positional field was until now (`Cli`'s `formerFlags`): it406 * still parses, checked by the field's schema, but help leaves it out and407 * using it prints nothing more.408 */338/** Still parses, checked by the field's schema, but hidden from help. */339const formerFlagFor = (name: string, field: Plain): Flag.Flag<unknown> => {340 const spec = describe(field);341342 return flagBuilders[spec.kind](name, field, spec).pipe(
2 unmodified lines
345 Flag.map(Option.getOrUndefined)346 );347};348419/**420 * The flags a projected command takes beside its payload's: `--json`421 * always, `--yes` when a person approves it, and `--dry-run` unless it only422 * reads.423 */349const controls = (approval: boolean, readOnly: boolean) =>350 Object.fromEntries([351 [352 "json",
33 unmodified lines
386 ]);387388const isRefusal = Schema.is(Refusal);389465/** The contract's command, as a person types it: `asks`, `ask open`. */390export const commandName = (rpc: Rpc.AnyWithProps): string =>391 Context.get(rpc.annotations, Cli).name ?? rpc._tag;392469/** The words that reach the contract's command: `["ask", "open"]`. */393export const commandPath = (394 rpc: Rpc.AnyWithProps395): readonly [string, ...string[]] => {396 const [first = rpc._tag, ...rest] = commandName(rpc).split(" ");397398 return [first, ...rest];399};400478/** JSON text as Markdown, and as itself for a person. */401const asJson = (text: string): View => ({402 markdown: ["```json", text, "```"].join("\n"),403 text,404});405484/**485 * Projects one contract onto a CLI command. Its payload's fields become486 * flags (or the positional arguments its `Cli` annotation names), and it is487 * named by the last word of that annotation's name. Every command takes488 * `--json`; one that needs approval takes `--yes` and runs only with it;489 * one that changes something takes `--dry-run`, which prints the encoded490 * payload and calls nothing. A refusal, or the refusals a success carries491 * (`refusalsIn`), go to `output.refused` once, and the command fails with492 * `Reported` and their exit code (`endRefused`).493 */406export const toCommand = <407 R extends CommandRpc,408 ClientR,409 OutputR,
42 unmodified lines
452 const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);453 const encodePayload = Schema.encodeUnknownEffect(rpc.payloadSchema);454 const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);455544 /** The fields given, by name, then the defaults for required ones left out. */456 const complete = (given: readonly (readonly [string, unknown])[]) =>457 Effect.gen(function* () {458 const provided = Object.fromEntries(459 given.filter(([, value]) => value !== undefined)
40 unmodified lines
500 if (approval && control.yes !== true && !dryRun) {501 return yield* new ApprovalNeeded({ command });502 }503593 // An argument left out takes the value its former flag gave.504 const decoded = yield* complete(505 Object.entries(given).map(506 ([name, value]) => [name, value ?? formerly[name]] as const507 )
65 unmodified lines
573export interface ToCommandsOptions<Rpcs extends Rpc.Any, OutputR, DefaultsR> {574 readonly output: Effect.Effect<CommandOutput, never, OutputR>;575 readonly defaults?: Defaults<DefaultsR> | undefined;576 readonly views?: Views<Rpcs> | undefined;667 /** The refusals any contract's success carries in place of a result. */577 readonly refusalsIn?:578 | ((success: Rpc.Success<Rpcs>) => readonly Refusal[])579 | undefined;671 /** Tags a hand-written command wraps instead, such as `setEnv`'s `env set`. */580 readonly exclude: readonly string[];581}582675/**676 * Every contract in `group` whose `Surfaces` include `cli`, but those677 * `exclude` names, as a command at the path its `Cli` annotation names.678 */583export const toCommands = <584 Rpcs extends CommandRpc,585 ClientR,586 OutputR,
23 unmodified lines
modified:packages/protocol/src/contracts.ts+5 added-82 removed
94 unmodified lines
95 WeakCheck,96 Weakened,97} from "./refusal.ts";9899/** The keys every contract is annotated with, for the surfaces that read them. */99export {100 Audience,101 Cli,102 Description,
5 unmodified lines
108 Surfaces,109 Visibility,110} from "./annotations.ts";111113/**114 * The env shape contract's tag. Lint keeps "shape" out of code names, so the115 * tag is spelled once, here, and the contract's class is `EnvSchemaOf`.116 */112// Lint keeps "shape" out of code names, so the tag is spelled once, here.113const envSchemaTag = "envShape";114119/**120 * The surfaces each contract is served on. Every contract's121 * `Surfaces` annotation is read from this table, and `surfaced` types each122 * surface's group by it, so the type and the annotation cannot disagree.123 */115const servedOn = {116 claim: ["rpc", "mcp", "cli"],117 credits: SurfaceName.literals,118 decide: SurfaceName.literals,
9 unmodified lines
128 land: ["rpc", "mcp", "cli"],129 landing: SurfaceName.literals,130 ledger: SurfaceName.literals,131 listAsks: SurfaceName.literals,141 // The code reads an agent without git can use, each capped (1 MiB a file,142 // 100 commits a page, 200 scanned for why); a commit's diff and every path143 // stay off MCP until a cap fits a transcript. No command: git reads code144 // locally.132 // A commit's diff and every path stay off MCP: no cap fits a transcript.133 // No command: git reads code locally.134 listPaths: ["rpc", "web"],135 listProjects: SurfaceName.literals,136 listRefs: ["rpc", "mcp", "web"],137 log: ["rpc", "mcp", "web"],
12 unmodified lines
150 submitAnswer: ["rpc", "mcp", "cli"],151 today: SurfaceName.literals,152 verdict: SurfaceName.literals,153 vouch: ["rpc", "mcp", "cli"],165 // A stream has no tool or command form.154 watch: ["rpc", "web"],155 why: ["rpc", "mcp", "web"],156} as const satisfies Record<string, readonly SurfaceName[]>;157170/**171 * The payload of a contract that takes nothing: an object with no keys. An172 * empty `Schema.Struct` has no object root in JSON Schema, which an MCP tool's173 * input needs; this is the form `Tool.EmptyParams` takes.174 */158// An empty `Schema.Struct` has no object root in JSON Schema, which an MCP159// tool's input needs; this is the form `Tool.EmptyParams` takes.160const NoPayload = Schema.Record(Schema.String, Schema.Never);161177// --- Reads ------------------------------------------------------------------178162export class ListProjects extends Rpc.make("listProjects", {163 payload: NoPayload,164 success: Schema.Struct({ projects: Schema.Array(ProjectListing) }),165})
49 unmodified lines
215 error: Schema.Union([UnknownProject, UnknownAsk]),216 payload: { ask: AskId, project: ProjectName },217 success: Schema.Struct({218 ask: Ask,236 /** The ask as an answerer reads it first, in Markdown. */219 brief: Schema.NonEmptyString,220 }),221})222 .annotate(
14 unmodified lines
237 payload: { project: Schema.optionalKey(ProjectName) },238 success: Schema.Struct({239 answers: Schema.Array(AnswerView),240 claims: Schema.Array(ClaimView),259 /** The caller's own handle, as the platform knows them. */241 handle: Handle,242 }),243})244 .annotate(
76 unmodified lines
321 Description,322 "Show the caller's Today: the decisions to take, held to their budget, each with its evidence and a safe default."323 )324 .annotate(Audience, "decider")344 // A decider's page: its evidence is for deciders, so no cache keeps it.325 .annotate(Visibility, "maintainers")326 .annotate(ReadOnly, true)327 .annotate(Idempotent, true)328 .annotate(Destructive, false)
18 unmodified lines
347 .annotate(NeedsApproval, false)348 .annotate(Cli, { name: "ledger" })349 .annotate(Surfaces, servedOn.ledger) {}350371/** The env shape contract, named for the file it reads: `.env.schema`. */351export class EnvSchemaOf extends Rpc.make(envSchemaTag, {352 error: UnknownProject,353 payload: { project: ProjectName },354 success: EnvSchemaView,
14 unmodified lines
369export class Watch extends Rpc.make("watch", {370 error: UnknownProject,371 payload: {372 project: ProjectName,394 /** Replay from the event after this sequence number. */373 since: Schema.optionalKey(Schema.Int),374 },375 stream: true,376 success: ProjectEvent,
9 unmodified lines
386 .annotate(Destructive, false)387 .annotate(NeedsApproval, false)388 .annotate(Surfaces, servedOn.watch) {}389412// --- Code reads (the canonical repo only; git reads it locally too) --------413390export class ListRefs extends Rpc.make("listRefs", {391 error: UnknownProject,392 payload: { project: ProjectName },393 success: RefsView,
14 unmodified lines
408 error: Schema.Union([UnknownProject, UnknownRevision, UnknownPath]),409 payload: {410 /** `main`, a commit or a tag; main's landed commit when absent. */411 at: Schema.optionalKey(Rev),436 /** The folder; the root when absent. */412 path: Schema.optionalKey(RepoPath),413 project: ProjectName,414 },415 success: TreeListing,
51 unmodified lines
467export class LogOf extends Rpc.make("log", {468 error: Schema.Union([UnknownProject, UnknownRevision]),469 payload: {470 at: Schema.optionalKey(Rev),496 /** How many commits to skip: a page's `next`. */471 from: Schema.optionalKey(NoneOrMore),472 /** 30 when absent. */473 limit: Schema.optionalKey(474 Schema.Int.check(Schema.isBetween({ maximum: 100, minimum: 1 }))475 ),502 /** Only the commits that changed this path. */476 path: Schema.optionalKey(RepoPath),477 project: ProjectName,478 },479 success: Schema.Struct({
55 unmodified lines
535export class PolicyOf extends Rpc.make("projectPolicy", {536 error: UnknownProject,537 payload: { project: ProjectName },538 success: Schema.Struct({566 /** Where the project was imported from; absent for one that started empty. */539 importedFrom: Schema.optionalKey(ImportSource),568 /** Absent while the config folder at the landed commit has not evaluated. */540 policy: Schema.optionalKey(PublicPolicy),570 /**571 * Why there is no policy at the landed commit: no config folder, or one572 * that did not evaluate. Absent before the first landing and once a573 * policy has evaluated.574 */541 unevaluated: Schema.optionalKey(PolicyPending),542 }),543})544 .annotate(
12 unmodified lines
557export class ShowProposal extends Rpc.make("showProposal", {558 error: Schema.Union([UnknownProject, UnknownProposal]),559 payload: { project: ProjectName, proposal: ProposalId },560 success: Schema.Struct({595 /** The files the proposal holds until a decider accepts it. */561 files: Schema.Array(ConfigFile),562 proposal: Proposal,563 }),564})
9 unmodified lines
574 .annotate(NeedsApproval, false)575 .annotate(Cli, { name: "proposal", positional: ["proposal"] })576 .annotate(Surfaces, servedOn.showProposal) {}577613// --- Writes -----------------------------------------------------------------614578export class InitProject extends Rpc.make("initProject", {579 error: Schema.Union([ProjectExists, NotYourNamespace, ImportFailed]),580 payload: {618 /** A public repo to import, instead of starting empty. */581 import: Schema.optionalKey(ImportSource),582 project: ProjectName,583 },584 success: Schema.Struct({623 /** Absent until the first push to an empty project. */585 landed: Schema.optionalKey(LandedSha),586 project: ProjectName,626 /** The project's URL at the gateway. */587 remote: Schema.NonEmptyString,588 }),589})590 .annotate(
5 unmodified lines
596 .annotate(ReadOnly, false)597 .annotate(Idempotent, false)598 .annotate(Destructive, false)599 .annotate(NeedsApproval, true)640 // The local `init` command calls it, with `--remote`.600 .annotate(Cli, { name: "init" })601 .annotate(Surfaces, servedOn.initProject) {}602603export class OpenAsk extends Rpc.make("openAsk", {
26 unmodified lines
630 .annotate(NeedsApproval, true)631 .annotate(Cli, { name: "ask open", positional: ["ask"] })632 .annotate(Surfaces, servedOn.openAsk) {}633675/**676 * A drafted proposal brings no files and no sealed answer: the platform's677 * agent writes the ask's files.678 */634const draftsAlone = Schema.makeFilter(635 (payload: {636 readonly draft?: true;637 readonly files?: unknown;
5 unmodified lines
643 : "a drafted proposal carries neither files nor a sealed answer"644);645646export class ProposeAsk extends Rpc.make("proposeAsk", {692 // `NotVouched` under the `all` mode, or for a sealed answer from someone693 // unvouched under `forCode` (a vouch admits sealed answers).647 error: Schema.Union([UnknownProject, Denounced, CapReached, NotVouched]),648 payload: Schema.Struct({696 /** Have the platform's agent draft the ask's files from the want. */649 draft: Schema.optionalKey(Schema.Literal(true)),650 files: Schema.optionalKey(Schema.NonEmptyArray(ConfigFile)),651 project: ProjectName,700 /** A sealed answer: the commit in the caller's working fork that answers it. */652 sealed: Schema.optionalKey(Schema.Struct({ head: CommitSha })),653 territory: Schema.optionalKey(Schema.NonEmptyString),654 want: Schema.NonEmptyString,655 }).check(draftsAlone),
21 unmodified lines
677 DraftInProgress,678 CapReached,679 ]),680 payload: {730 /** What the draft should do differently, for the agent to read. */681 note: Schema.optionalKey(DraftNote),682 project: ProjectName,683 proposal: ProposalId,684 },
39 unmodified lines
724 UnknownProject,725 UnknownDecision,726 DecisionClosed,727 NotDecider,778 // Accepting a proposal opens its ask, red first on main: a blocked779 // Checker or a main that moved fails the call, and the decider can780 // accept again.728 VerifierBlocked,729 StaleBase,730 ]),731 payload: {
8 unmodified lines
740 Description,741 "Take one decision from Today: accept, decline, adopt or revert."742 )743 .annotate(Audience, "decider")797 // The decision's evidence is for deciders.744 .annotate(Visibility, "maintainers")745 .annotate(ReadOnly, false)746 .annotate(Idempotent, false)747 .annotate(Destructive, false)
62 unmodified lines
810 ask: AskId,811 base: CommitSha,812 head: CommitSha,813 project: ProjectName,868 /** Offering the same request again returns the same receipt. */814 requestId: RequestId,815 },816 success: AnswerReceipt,817})
67 unmodified lines
885export class Fork extends Rpc.make("fork", {886 error: Schema.Union([UnknownProject, NotVouched, Denounced]),887 payload: { project: ProjectName },888 success: Schema.Struct({944 /** `<project>--me--<handle>`. */889 fork: RepoName,946 /** The fork's URL at the gateway. */890 remote: Schema.NonEmptyString,891 }),892})893 .annotate(
35 unmodified lines
929export class EvidenceOf extends Rpc.make("evidence", {930 error: Schema.Union([UnknownProject, NotDecider]),931 payload: {932 project: ProjectName,990 /** The `logRef` a verdict's lane or a `ChecksFailed` refusal names. */933 ref: Schema.NonEmptyString,934 },935 success: Schema.Struct({936 lane: LaneName,937 /** The log's tail: its last 256 KiB, where a failure prints. */938 text: Schema.String,997 /** Whether the log was longer than the tail given back. */939 truncated: Schema.Boolean,940 }),941})942 .annotate(
1 unmodified line
944 "Show the log a failing lane left, by the logRef its verdict names, to the answer's own claimant and the project's deciders only; the last 256 KiB."945 )946 // The handler lets in the answer's claimant and the project's deciders.947 .annotate(Audience, "signedIn")1007 // A log is for its answerer and the deciders: no cache keeps it.948 .annotate(Visibility, "maintainers")949 .annotate(ReadOnly, true)950 .annotate(Idempotent, true)951 .annotate(Destructive, false)
9 unmodified lines
961 NotSensitive,962 ValueTooShort,963 ]),964 payload: {1025 /** Store a value shorter than the item's minimum anyway. */965 acknowledgeShort: Schema.optionalKey(Schema.Boolean),966 key: EnvKey,967 project: ProjectName,968 /** The write-only value: the raw string on the wire, never printed. */
14 unmodified lines
983 .annotate(ReadOnly, false)984 .annotate(Idempotent, true)985 .annotate(Destructive, false)986 .annotate(NeedsApproval, true)1048 // The local `env set` command reads the value from stdin.987 .annotate(Cli, { name: "env set" })988 .annotate(Surfaces, servedOn.setEnv) {}9891052/** The one schema: every surface is a projection of this group. */990export class Contracts extends RpcGroup.make(991 ListProjects,992 FrontPage,993 ListAsks,
31 unmodified lines
1025 EvidenceOf,1026 SetEnv1027).middleware(Authenticated) {}10281092/** Every contract in the group, as its handlers and clients see it. */1029export type Contract = RpcGroup.Rpcs<typeof Contracts>;10301031type ServedOn = typeof servedOn;10321097/** The tags of the contracts `surface` serves. */1033export type TagOn<S extends SurfaceName> = {1034 readonly [Tag in keyof ServedOn]: S extends ServedOn[Tag][number]1035 ? Tag1036 : never;1037}[keyof ServedOn];10381104/** The contracts `surface` serves. */1039export type ContractOn<S extends SurfaceName> = Extract<1040 Contract,1041 { readonly _tag: TagOn<S> }1042>;10431110/**1111 * Whether a contract is served on `surface`, by its `Surfaces` annotation.1112 * The annotation is read from `servedOn`, which `ContractOn` reads too.1113 */1044const isServedOn =1045 <S extends SurfaceName>(surface: S) =>1046 (rpc: Contract): rpc is ContractOn<S> =>1047 Context.get(rpc.annotations, Surfaces).includes(surface);10481119/** The group as one surface serves it: the contracts its `Surfaces` include, in order. */1049export const surfaced = <S extends SurfaceName>(1050 surface: S1051): RpcGroup.RpcGroup<ContractOn<S>> =>1052 RpcGroup.make(1053 ...[...Contracts.requests.values()].filter(isServedOn(surface))1054 );10551127/**1128 * A contract's payload, success and error as a client meets them. A stream's1129 * success is one of its elements, and its error is the stream's: the call1130 * itself never fails outside the stream.1131 */1056export const partsOf = (rpc: Contract) =>1057 RpcSchema.isStreamSchema(rpc.successSchema)1058 ? {1059 error: rpc.successSchema.error,
5 unmodified lines
1065 payload: rpc.payloadSchema,1066 success: rpc.successSchema,1067 };10681145/** A way to call the contracts, in process or over the wire. */1069export class Client extends Context.Service<1070 Client,1071 RpcClient.RpcClient<1072 RpcGroup.Rpcs<typeof Contracts>,
3 unmodified lines
modified:packages/protocol/src/envelope.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/exit-code.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/ids.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/legacy.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/mcp-extras.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/mcp.tsnot shown

Its text is not shown, modified.

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

Its text is not shown, modified.

modified:packages/protocol/src/principal.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/refusal.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/render.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/src/testing.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/annotations.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/authenticate.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/cli.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/contract-examples.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/contracts.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/domain.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/examples.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/exit-code.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/leaks.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/mcp.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/mcp.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/project-name.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/refusal.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/render.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/testing.test.tsnot shown

Its text is not shown, modified.