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.
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
Provenance
- Commit
c86204f- Tree
99c48c3- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
5792317- Parent 2
bc299e2
165 files changed+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- */1 export type {2 AreaName,3 AskId,4 Handle,35 unmodified linesmodified: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`.2 export {3 type Admit,4 type AreaOf,5 type ArgFields,64 unmodified linesmodified: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.2 import { claudeEventOf } from "@repo/agent-kit/hook-events";3 import type { HookEvent } from "@repo/agent-kit/hook-events";4 import { Brand } from "@repo/brand";5 import { matchAny } from "@repo/gate/glob";6 unmodified lines12 import { Array, Option, Predicate, Schema } from "effect";13 14 import type { HookInput } from "./input.ts";15 26-/** The claim this session works on, as the hook needs it. */16 export 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 });24 25 export type HookClaim = typeof HookClaim.Type;26 40-/** What the policy decides over. */27 export 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 }34 53-/** Go on, as the harness would without the hook: `{}`, with no field at all. */35 type GoOn = Readonly<Record<string, never>>;36 56-/** Claude Code's PreToolUse denial: the tool does not run, and the agent reads the reason. */37 interface Deny {38 readonly hookSpecificOutput: {39 readonly hookEventName: (typeof claudeEventOf)["pre-tool-use"];40 readonly permissionDecision: "deny";41 readonly permissionDecisionReason: string;42 };43 }44 65-/** Claude Code's SessionStart context: Markdown the agent reads first. */45 interface Brief {46 readonly hookSpecificOutput: {47 readonly additionalContext: string;48 readonly hookEventName: (typeof claudeEventOf)["session-start"];49 };50 }51 73-/** Claude Code's Stop hold: the agent goes on, with the reason as its next prompt. */52 interface Hold {53 readonly decision: "block";54 readonly reason: string;55 }56 79-/** The exact JSON written to stdout. */57 export type HookOutput = GoOn | Deny | Brief | Hold;58 82-/** The answer, the holds in a row after it, and a line for stderr. */59 export interface HookDecision {60 readonly output: HookOutput;61 readonly holds: number;62 readonly note: Option.Option<string>;1 unmodified line64 65 const NO_CLAIM =66 "no claim in this session's repo, so the hook allows everything; the gateway still judges every push";67 92-/** Go on, as the harness would without the hook. */68 const allow = (holds: number, note?: string): HookDecision => ({69 holds,70 note: Option.fromUndefinedOr(note),71 output: {},72 });73 99-// ------------------------------------------------------------ paths100-101-/** `path` with `.` and `..` resolved and no empty segments: `/a/b`. */74 const normalize = (path: string) => {75 const parts: string[] = [];76 77 for (const part of path.split("/")) {6 unmodified lines84 85 return `/${parts.join("/")}`;86 };87 116-/**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- */88 const repoPathOf = (89 root: string,90 cwd: string,91 file: string6 unmodified lines98 ? Option.some(RepoPath.make(absolute.slice(prefix.length)))99 : Option.none();100 };101 134-/** The tools that write a file, and the input key that names it. */102 const WRITERS = new Map([103 ["Edit", "file_path"],104 ["MultiEdit", "file_path"],105 ["NotebookEdit", "notebook_path"],106 ["Write", "file_path"],107 ]);108 142-/** The file a writing tool is about to change, if the call is one. */109 const 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 lines115 )116 )117 );118 153-/**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- */119 const pathRefusals = (120 claim: HookClaim,121 judge: Policy["judge"],122 path: RepoPath6 unmodified lines129 ? []130 : [new OutOfScope({ paths: [path] })];131 };132 172-/**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- */133 export const toolRefusals = (134 input: HookInput,135 facts: Pick<HookFacts, "claim" | "judge" | "root">136 ): readonly Refusal[] =>32 unmodified lines169 : allow(facts.holds);170 },171 });172 218-// ------------------------------------------------------------ brief219-173 const bullets = (items: readonly string[]) =>174 items.map((item) => `- \`${item}\``);175 223-/** The claim as the agent reads it first, in Markdown. */176 const 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 lines214 },215 }),216 });217 267-// ------------------------------------------------------------ stop268-269-/** The most Stop holds in a row; the next stop goes through. */218 export const MAX_HOLDS = 3;219 272-/**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. */221 const 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 lines245 output: { decision: "block", reason: explain(fixable).join("\n") },246 };247 };248 309-/** Each event's policy. */249 const policies = {250 "pre-tool-use": preToolUse,251 "session-start": (_input, facts) => sessionStart(facts),252 stop: stopHook,1 unmodified line254 HookEvent,255 (input: HookInput, facts: HookFacts) => HookDecision256 >;257 319-/**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- */258 export const decideHook = (259 event: HookEvent,260 input: HookInput,261 facts: HookFacts1 unmodified linemodified: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- */1 import { Brand } from "@repo/brand";2 import { Client } from "@repo/protocol/contracts";3 import type { ClaimView } from "@repo/protocol/domain/claim";4 import { Cause, Duration, Effect, Option, Result, Schema } from "effect";4 unmodified lines9 import type { HookClaim } from "./decide.ts";10 import { askJudge, judgeAt } from "./judge.ts";11 import type { SessionState } from "./session.ts";12 19-/** No closure: a session without a claim judges nothing. */13 const NO_JUDGE: SessionState["judge"] = { paths: [], pointers: [] };14 15 const without = (root: string, why: string): SessionState => ({16 holds: 0,1 unmodified line18 root,19 why,20 });21 29-/**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. */23 const PLATFORM_LIMIT = Duration.seconds(10);24 36-/** The platform did not answer in time; the session goes on without a claim. */25 class PlatformSilent extends Schema.TaggedError<PlatformSilent>()(26 "PlatformSilent",27 { limit: Schema.String }28 ) {1 unmodified line30 return `the platform did not answer within ${this.limit}`;31 }32 }33 46-/** A platform call, given at most `PLATFORM_LIMIT` to answer. */34 const inTime = <A, E, R>(call: Effect.Effect<A, E, R>) =>35 Effect.timeoutOrElse(call, {36 duration: PLATFORM_LIMIT,37 orElse: () =>1 unmodified line39 new PlatformSilent({ limit: Duration.format(PLATFORM_LIMIT) })40 ),41 });42 56-/** A failure's first line, for a reason on stderr. */43 const firstLine = (cause: Cause.Cause<unknown>) =>44 String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";45 46 const isLive = (claim: ClaimView) =>47 claim.state === "live" || claim.state === "warned";48 63-/**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. */50 const claimFor = (51 ref: RepoRef,52 claims: readonly ClaimView[]53 ): Result.Result<ClaimView, string> => {23 unmodified lines77 `you hold ${live.length} live claims in ${ref.project}, and this repo's remote names none of them`78 );79 };80 100-/**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- */81 export const gatherFacts = (82 cwd: string83 ): Effect.Effect<84 SessionState,57 unmodified linesmodified: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- */1 import { Schema } from "effect";2 3 export 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 });11 12 export type HookInput = typeof HookInput.Type;13 24-/** The whole of stdin, as JSON text, to a `HookInput`. */14 export 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- */1 import { findRunBlock } from "@repo/checks/finder";2 import { judgeClosure } from "@repo/checks/judge";3 import type { Ask } from "@repo/protocol/domain/ask";4 import { CheckSpec } from "@repo/protocol/domain/check";4 unmodified lines9 import type { ChildProcessSpawner } from "effect/process";10 11 import { judgeFilesAt } from "../local/judge-files.ts";12 19-/**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- */13 export const askJudge = (14 closure: Policy["judge"],15 ask: Ask16 ): Policy["judge"] => {7 unmodified lines24 pointers: closure.pointers,25 };26 };27 39-// ------------------------------------------------------------ at the base40-28 const decodeRun = Schema.decodeUnknownOption(RunBlock);29 43-/**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. */31 export const judgeAt = (input: {32 readonly root: string;33 readonly base: string;34 readonly test: string;15 unmodified linesmodified: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.3 import { Envelope } from "@repo/protocol/envelope";4 import type { Refusal } from "@repo/protocol/refusal";5 import {6 Context,5 unmodified lines12 Stream,13 } from "effect";14 import { ChildProcess, ChildProcessSpawner } from "effect/process";15 22-/** The check could not say: it did not start, ran too long, or printed no envelope. */16 export class PushCheckFailed extends Schema.TaggedError<PushCheckFailed>()(17 "PushCheckFailed",18 { reason: Schema.String }19 ) {4 unmodified lines24 25 export 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") {}34 46-/** The arguments after the CLI's own command. */35 const CHECK = ["check", "--shape-only", "--offline", "--json"] as const;36 49-/** The check reads the diff and the config and runs nothing: a minute is plenty. */37 const LIMIT = Duration.minutes(1);38 39 const decodeEnvelope = Schema.decodeUnknownEffect(40 Schema.fromJsonString(Envelope(Schema.Unknown))1 unmodified line42 43 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>44 bytes.pipe(Stream.decodeText(), Stream.mkString);45 59-/**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. */47 export const pushCheckWith = (48 command: readonly [string, ...string[]]49 ): Layer.Layer<PushCheck, never, ChildProcessSpawner.ChildProcessSpawner> =>50 Layer.effect(55 unmodified lines106 return { run };107 })108 );109 128-/** How this process was started, as the runtime's `process` global reports it. */110 const Started = Schema.Struct({111 argv: Schema.Array(Schema.String),112 execPath: Schema.NonEmptyString,113 });114 134-/** The global scope, read only for its `process`. */115 const GlobalScope = Schema.Struct({ process: Started });116 137-/**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/`. */118 export const selfCommand = (119 started: typeof Started.Type120 ): readonly [string, ...string[]] => {121 const [, entry] = started.argv;4 unmodified lines126 ? [started.execPath]127 : [started.execPath, entry];128 };129 154-/**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- */130 export const PushCheckChild: Layer.Layer<131 PushCheck,132 never,133 ChildProcessSpawner.ChildProcessSpawner19 unmodified linesmodified: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.2 import { Brand } from "@repo/brand";3 import { NoneOrMore } from "@repo/protocol/domain/common";4 import { Policy } from "@repo/protocol/domain/policy";5 import { Config, Effect, FileSystem, Hash, Option, Path, Schema } from "effect";6 7 import { HookClaim } from "./decide.ts";8 16-/** One session's facts and holds, as its file holds them. */9 export 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 });16 17 export type SessionState = typeof SessionState.Type;18 29-/** The session's state could not be kept; the hook says so and goes on. */19 export class SessionUnsaved extends Schema.TaggedError<SessionUnsaved>()(20 "SessionUnsaved",21 { reason: Schema.String }22 ) {17 unmodified lines40 const FILE_MODE = 0o600;41 42 const DIR_MODE = 0o700;43 55-/**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- */44 const 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`;48 64-/** The session's file, when the env names a home for it. */49 const fileOf = (session: string) =>50 Effect.gen(function* () {51 const path = yield* Path.Path;52 9 unmodified lines62 (state) => path.join(state, Brand.slug, "hooks", fileNameOf(session))63 );64 });65 82-/** The session's kept state, if its file is there and reads back whole. */66 export const loadSession = (67 session: string68 ): Effect.Effect<69 Option.Option<SessionState>,12 unmodified lines82 yield* Effect.flatMap(fs.readFileString(file.value), decodeFile)83 );84 }).pipe(Effect.orElseSucceed(() => Option.none<SessionState>()));85 103-/**104- * Keeps the session's state, replacing the file whole. Fails only so the105- * caller can say why on stderr.106- */86 export const saveSession = (87 session: string,88 state: SessionState89 ): Effect.Effect<void, SessionUnsaved, FileSystem.FileSystem | Path.Path> =>31 unmodified linesmodified: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.2 import { Brand } from "@repo/brand";3 import {4 CheckAt,5 CheckLane,63 unmodified lines69 import type { StaleCopy } from "./stale.ts";70 71 const COMMAND = "check";72 86-/** A generated file in the working copy that main's config no longer gives (`stale.ts`). */73 const 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 });77 93-/**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- */78 const 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 lines90 const encodeChecked = Schema.encodeEffect(Checked);91 92 const isRefusal = Schema.is(Refusal);93 115-/** The handle a check stands in for when nobody is signed in and no fork names one. */94 const SOMEONE = Handle.make("you");95 96 const asHandle = Schema.decodeOption(Handle);97 120-/** A claim that holds the fork open: `live`, or `warned` and not yet lapsed. */98 const isLive = (claim: ClaimView) =>99 claim.state === "live" || claim.state === "warned";100 124-/** Prints `text` on stderr, then ends the command: it has said why. */101 const stop = (text: string) =>102 Output.use((output) =>103 Effect.andThen(output.note(text), Effect.fail(new Reported()))104 );105 130-/** Prints `refusals` the way every command does, then ends the command with their exit code. */106 const refuse = (107 json: boolean,108 refusals: Array.NonEmptyReadonlyArray<Refusal>109 ) =>110 Output.use((output) =>111 endRefused(output, { command: COMMAND, json, refusals })112 );113 139-/**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- */114 const 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.`;119 150-/** The stale copies as `--json` lists them: absent when there are none. */120 const staleField = (stale: readonly StaleCopy[]) =>121 Array.match(stale, {122 onEmpty: () => ({}),123 onNonEmpty: (copies) => ({5 unmodified lines129 ),130 }),131 });132 164-/** The signed-in profile's handle, when `login` learned one. */133 const signedInHandle = Effect.flatMap(134 Effect.serviceOption(Credentials),135 Option.match({136 onNone: () => Effect.succeedNone,3 unmodified lines140 ),141 })142 );143 176-/** The project and ask a check is for: the flags', else the remote's. */144 const subjectOf = (145 context: RepoContext,146 flags: {147 readonly ask: Option.Option<AskId>;38 unmodified lines186 187 return { ask: inferred.value, project: project.value };188 });189 223-/** The caller's claims in `project`, as the platform's `status` lists them. */190 const claimsOn = (project: ProjectName, json: boolean) =>191 Effect.gen(function* () {192 const client = yield* Client;193 10 unmodified lines204 )205 );206 });207 242-/**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. */209 const baseOf = (210 root: string,211 given: Option.Option<string>,212 claim: Option.Option<ClaimView>22 unmodified lines235 236 return "main";237 });238 278-/**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- */239 const 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 lines258 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 lines270 ),271 };272 });273 319-/**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- */274 const lanesOf = (policy: Policy, ask: Ask): readonly CheckLane[] => [275 ...Option.toArray(276 Option.map(277 commandFor(ask.check, policy.run, policy.ratchets),7 unmodified lines285 CheckLane.make({ command, lane })286 ),287 ];288 339-/**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`). */290 const countedAskLane = (291 policy: Policy,292 ask: Ask,293 ran: CheckRun58 unmodified lines352 )353 );354 };355 413-/** The last lines of a setup's output, for the note that says why it failed. */356 const TAIL = 4000;357 416-/**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. */359 const checkoutOf = (input: {360 readonly root: string;361 readonly setup: Option.Option<string>;362 readonly note: (text: string) => Effect.Effect<void>;82 unmodified lines445 })446 )447 );448 513-/** A ratchet's count on the base and on HEAD, as a line says it. */449 const moveText = ({ after, before, ratchet, territory }: RatchetMove) =>450 `${ratchet} in ${territory}: ${before} on the base, ${after} here`;451 517-/** The run as a person reads it: each lane and how it ended, then each ratchet's count. */452 const viewOf = (checked: Checked) => {453 const moves = checked.ratchets ?? [];454 455 const lines = [18 unmodified lines474 text: lines.join("\n"),475 };476 };477 544-/** The counts as `--json` lists them: absent when there are none. */478 const ratchetsField = (moves: readonly RatchetMove[]) =>479 Array.match(moves, {480 onEmpty: () => ({}),481 onNonEmpty: (ratchets) => ({ ratchets }),68 unmodified lines550 const claim = Option.flatMap(claims, (held) =>551 Array.findFirst(held, (each) => each.ask === askId)552 );553 621- // 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 lines580 )581 )582 );583 653- // 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 lines597 if (Option.isNone(ask)) {598 return yield* refuse(json, [new UnknownAsk({ ask: askId })]);599 }600 671- // The claim's fork, named as the platform names it: by the project's key.601 const fork = claimForkName(project, askId, handle);602 603 const facts = yield* localFacts({604 ask,56 unmodified lines661 view: viewOf(checked),662 });663 }664 736- // 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 lines731 yield* output.note(`${evidence.lane} failed: ${evidence.signature}`);732 }733 }734 808- // 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;737 738 if (declared && !counting) {55 unmodified linesmodified: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.3 import { Brand } from "@repo/brand";4 import { RulesFailed } from "@repo/rules/rules-evaluator";5 import { Context, Effect, FileSystem, Option, Path, Schema } from "effect";6 import type { Scope } from "effect";7 20-/** The modules a bun child imports for one use of the config folder. */8 export 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 }13 30-/** How this CLI runs bun for a config folder, and the modules it hands it. */14 export 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.Scope2 unmodified lines23 24 const loadFailed = (detail: string) =>25 new RulesFailed({ detail, reason: "load" });26 47-/**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`. */28 const ownCopyOf = (path: Path.Path, specifier: string) =>29 Effect.try({30 catch: () =>31 loadFailed(15 unmodified lines47 );48 49 const NODE_MODULES = "/node_modules";50 75-/** The `node_modules` folder a resolved module sits in. */51 const packagesOf = (file: string) => {52 const at = file.lastIndexOf(`${NODE_MODULES}/`);53 54 return at === -155 ? Option.none()56 : Option.some(file.slice(0, at + NODE_MODULES.length));57 };58 84-/** Run from source or the npm build: `bun` on the `PATH`, and this CLI's own modules. */59 export const ConfigRuntimeOwn: ConfigBun = {60 bun: "bun",61 env: {},62 modules: Effect.gen(function* () {4 unmodified lines67 return { entry: Option.none(), packages: packagesOf(effect), sdk };68 }),69 };70 97-/**98- * What `build.ts` hands the compiled binary through the global scope: the99- * embedded paths of the bundled sdk and rules entry.100- */71 export const EMBEDDED_KEY = "__configRuntime";72 73 const Embedded = Schema.Struct({74 [EMBEDDED_KEY]: Schema.Struct({2 unmodified lines77 }),78 process: Schema.Struct({ execPath: Schema.NonEmptyString }),79 });80 111-/**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. */82 export const configRuntimeEmbedded = (embedded: {83 readonly execPath: string;84 readonly entry: string;85 readonly sdk: string;27 unmodified lines113 );114 }),115 });116 151-/**152- * The runtime this process has: the compiled binary's when `build.ts` handed153- * it the embedded modules, else this CLI's own.154- */117 export 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 linesmodified: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.2 import { Brand } from "@repo/brand";3 import { Client, SetEnv } from "@repo/protocol/contracts";4 import { EnvKey, ProjectName } from "@repo/protocol/ids";5 import {16 unmodified lines22 const command = "env set";23 24 const encodeSet = Schema.encodeEffect(SetEnv.successSchema);25 33-/** How a value is piped in, for the person who tried another way. */26 const pipeHint = (key: string) =>27 `printf '%s\\n' "$VALUE" | ${Brand.cli} ${command} ${key} --yes`;28 37-/**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. */30 const prompted = (key: EnvKey, mode: Mode) =>31 mode === "human"32 ? Prompt.run(33 Prompt.Hidden({3 unmodified lines37 : usage(38 `${Brand.cli} never prompts an agent or a script, so pipe the value of ${key} on stdin: ${pipeHint(key)}`39 );40 53-/**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- */41 const readValue = (key: EnvKey, mode: Mode) =>42 Effect.gen(function* () {43 const stdio = yield* Stdio.Stdio;44 10 unmodified lines55 ? yield* usage(`No value for ${key} arrived: ${pipeHint(key)}`)56 : value;57 });58 75-/** The project named, or the one the repo's platform remote names. */59 const projectFor = (named: Option.Option<ProjectName>) =>60 Effect.gen(function* () {61 if (Option.isSome(named)) {62 return named.value;8 unmodified lines71 72 return yield* projectOf(named, context);73 });74 92-/**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. */76 const spellings: ReadonlySet<string> = new Set([77 "--acknowledge-short",78 "--completions",79 "--dry-run",7 unmodified lines87 "-h",88 "-v",89 ]);90 112-/** A word that reads as a flag, but as none `env set` takes. */91 const strangeFlag = (word: string) => {92 const [flag = word] = word.split("=", 1);93 94 return (2 unmodified lines97 !spellings.has(flag.replace(/^--no-/u, "--"))98 );99 };100 123-/**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. */102 export const refuseStrangeFlags = (103 argv: readonly string[]104 ): Effect.Effect<void, UsageError> => {105 const end = argv.indexOf("--");108 unmodified linesmodified: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.2 import { Fetch, FetchFailed } from "@repo/artifacts/fetch";3 import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";4 import type { RepoNotFound } from "@repo/artifacts/repo-host";5 import { RepoHostLocal } from "@repo/artifacts/repo-host/local";19 unmodified lines25 import { ChildProcess, ChildProcessSpawner } from "effect/process";26 27 import { NotARepo } from "../repo-context.ts";28 41-/** A revision the repo does not have: a branch, tag or commit by that name. */29 export class UnknownRevision extends Schema.TaggedError<UnknownRevision>()(30 "UnknownRevision",31 { revision: Schema.String, root: Schema.String }32 ) {1 unmodified line34 return `${this.root} has no commit ${this.revision}`;35 }36 }37 51-/** How a git command ended: its exit code and its output. */38 export interface GitRan {39 readonly exitCode: number;40 readonly stdout: string;41 readonly stderr: string;1 unmodified line43 44 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>45 bytes.pipe(Stream.decodeText(), Stream.mkString);46 61-/**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. */48 export const outsideAnyHook = {49 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,50 GIT_COMMON_DIR: undefined,51 GIT_CONFIG: undefined,6 unmodified lines58 GIT_PREFIX: undefined,59 GIT_WORK_TREE: undefined,60 };61 82-/**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. */63 export const readOnlyGit = {64 ...outsideAnyHook,65 GIT_OPTIONAL_LOCKS: "0",66 GIT_TERMINAL_PROMPT: "0",67 };68 94-/** Runs git in `cwd` to its end; a failing git is a result, not an error. */69 export const runGit = (70 cwd: string,71 args: readonly string[]72 ): Effect.Effect<GitRan, NotARepo, ChildProcessSpawner.ChildProcessSpawner> =>18 unmodified lines91 return { exitCode: Number(exitCode), stderr, stdout };92 })93 ).pipe(Effect.catchTag("PlatformError", () => new NotARepo({ cwd })));94 121-/** The commit `revision` names in the repo at `root`. */95 export const commitOf = (root: string, revision: string) =>96 Effect.gen(function* () {97 const ran = yield* runGit(root, [98 "rev-parse",9 unmodified lines108 ? sha109 : yield* new UnknownRevision({ revision, root });110 });111 139-/** The commit `git diff <base>...<head>` starts from: their merge base. */112 const 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 lines119 ? sha120 : yield* new UnknownRevision({ revision: `${base}...${head}`, root });121 });122 151-/** A host that reaches nothing over the network: `/local` here reads disk only. */123 const noNetwork = Layer.succeed(Fetch)({124 fetch: (request) =>125 Effect.fail(126 new FetchFailed({2 unmodified lines129 })130 ),131 });132 162-/** The name `/local` knows the working repo by: `<temp>/<name>.git`. */133 const WORKING = RepoName.make("working");134 165-/** The name it knows a temp bare copy by. */135 const COPY = RepoName.make("copy");136 168-/** `RepoHost` `/local` over the repos in `folder`. */137 const hostOver = (folder: string) =>138 RepoHostLocal.layer({ remoteBase: `file://${folder}`, root: folder }).pipe(139 Layer.provide(noNetwork)140 );141 174-/** Whether `/local` can read every commit in `shas` from repo `name`. */142 const 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 );149 183-/** A repo `/local` can read: the host's layer, and the repo's name there. */150 interface Opened {151 readonly host: Layer.Layer<RepoHost>;152 readonly name: RepoName;153 }154 189-/**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. */156 const openWorking = (157 root: string,158 shas: readonly CommitSha[]159 ): Effect.Effect<59 unmodified lines219 220 return { host, name: COPY } satisfies Opened;221 });222 266-/** What `localFacts` is told: the repo, the push, and what the project knows of it. */223 export 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 }234 285-/** The text of a blob, if the change has one on that side. */235 const blobText = (name: RepoName, blob: string | undefined) =>236 blob === undefined237 ? Effect.succeedNone238 : RepoHost.use((host) => host.readBlob(name, ObjectId.make(blob))).pipe(5 unmodified lines244 );245 246 const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);247 299-/** A manifest's `scripts` as JSON text, or `""` with no manifest or no JSON. */248 const scriptsIn = (manifest: Option.Option<string>) =>249 Option.getOrElse(250 Option.map(Option.flatMap(manifest, decodeScripts), ({ scripts }) =>251 JSON.stringify(scripts ?? null)252 ),253 () => ""254 );255 308-/**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- */256 const scriptsChanged = (name: RepoName, changes: readonly Change[]) =>257 Option.match(258 Option.fromUndefinedOr(changes.find(({ path }) => path === "package.json")),259 {8 unmodified lines268 ),269 }270 );271 329-/** A commit's root tree, through the port. */272 const 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 );278 337-/**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- */279 export const localFacts = (280 input: LocalFactsInput281 ): Effect.Effect<282 PushFacts,36 unmodified linesmodified: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- */1 import type { Command } from "effect/cli";2 3 import { check } from "./check.ts";4 import { envSet } from "./env-set.ts";5 import { init } from "./init.ts";6 import { login, logout } from "./login.ts";7 import { why } from "./why.ts";8 14-/** One hand-written command, and the words that reach it. */9 export 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 linesmodified: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- */1 import { Brand } from "@repo/brand";2 import { findRunBlock } from "@repo/checks/finder";3 import type { RepoFile } from "@repo/checks/finder";4 import { ApprovalNeeded } from "@repo/protocol/cli";20 unmodified lines25 import { projectFile } from "./project-file.ts";26 27 const COMMAND = "init";28 39-/** The config file `init` proposes, from the repo's root. */29 const CONFIG = `${Brand.configDir}/project.ts`;30 42-/** The one commit `init` makes: the config file alone. */31 const SUBJECT = `Add ${CONFIG}: the run block ${Brand.cli} ${COMMAND} found`;32 45-/** What `--dry-run` shows where the platform's answer will go. */33 const PENDING = { origin: "<platform>", remote: "<remote>" } as const;34 48-/** `init`'s flags ask for something it can't do. A usage error: exit 2. */35 export class InitMisused extends Schema.TaggedError<InitMisused>()(36 "InitMisused",37 { reason: Schema.String }38 ) {3 unmodified lines42 return this.reason;43 }44 }45 60-/** A git command `init` ran failed; git's own words say why. */46 export class GitFailed extends Schema.TaggedError<GitFailed>()("GitFailed", {47 argv: Schema.Array(Schema.String),48 stderr: Schema.String,49 }) {1 unmodified line51 return `${this.argv.join(" ")} failed: ${this.stderr.trim()}`;52 }53 }54 70-/** The payload `initProject` takes. */55 type Payload = typeof InitProject.payloadSchema.Type;56 73-/** What `init` would write, send and run: `--dry-run` prints it. */57 interface Plan {58 readonly files: readonly RepoFile[];59 readonly git: readonly (readonly string[])[];60 readonly payload: Payload;46 unmodified lines107 108 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>109 bytes.pipe(Stream.decodeText(), Stream.mkString);110 128-/** Runs `argv` in `cwd` to the end; a failing command is a result, not an error. */111 const run = (cwd: string, argv: readonly string[]) =>112 Effect.scoped(113 Effect.gen(function* () {114 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;11 unmodified lines126 return { exitCode, stderr, stdout };127 })128 );129 148-/** Runs `argv` in `cwd`, failing with git's own words when it fails. */130 const 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 );137 157-/** An argument as a shell reads it back: quoted only when it must be. */138 const shellWord = (word: string) =>139 /^[\w@%+=:,./-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;140 141 const shown = (argv: readonly string[]) => argv.map(shellWord).join(" ");142 163-/**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- */143 const READ = [144 /(?:^|\/)package\.json$/u,145 /(?:^|\/)tsconfig[^/]*\.json$/u,146 /^\.(?:github|forgejo)\/workflows\/[^/]+\.ya?ml$/u,1 unmodified line148 /^\.husky\/[^/]+$/u,149 /^\.pre-commit-config\.yaml$/u,150 ];151 177-/** Every tracked path, with contents for the files the finder reads. */152 const trackedFiles = (root: string) =>153 Effect.gen(function* () {154 const fs = yield* FileSystem.FileSystem;155 const path = yield* Path.Path;11 unmodified lines167 { concurrency: 16 }168 );169 });170 197-/** The owner a bare name is given: the profile's handle, when `login` learned it. */171 const profileOwner = Effect.map(172 Effect.flatMap(Credentials, ({ current }) => current),173 (profile) =>174 Option.map(1 unmodified line176 (handle) => handle.toLowerCase()177 )178 );179 207-/**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- */180 const projectNamed = (181 given: Option.Option<string>,182 fallback: { readonly owner: Option.Option<string>; readonly short: string }183 ) =>23 unmodified lines207 const HTTPS = /^https:\/\/\S+$/u;208 209 const pathnameOf = Option.liftThrowable((url: string) => new URL(url).pathname);210 244-/** The repo name an import URL ends in: `…/acme/widgets.git` → `widgets`. */211 const lastSegment = (url: string) =>212 Option.getOrElse(pathnameOf(url), () => "")213 .split("/")214 .findLast((segment) => segment !== "")215 ?.replace(/\.git$/u, "") ?? "";216 251-/** The project's remote and how to reach it: `git remote add|set-url`, the helper, the push. */217 const wiring = (input: {218 readonly hasRemote: boolean;219 readonly origin: Option.Option<string>;220 readonly push: boolean;12 unmodified lines233 }),234 ...(input.push ? [["git", "push", Brand.slug, "HEAD:main"]] : []),235 ];236 272-/** The config file's commit: added, then committed alone. */237 const committing = (paths: readonly string[]) =>238 paths.flatMap((path) => [239 ["git", "add", "--", path],240 ["git", "commit", "--quiet", "--message", SUBJECT, "--", path],241 ]);242 279-/** Prints `refusal` once, as the CLI prints every refusal, and ends as `Reported` with its exit code. */243 const refuse = (json: boolean) => (refusal: Refusal) =>244 Output.use((output) =>245 endRefused(output, { command: COMMAND, json, refusals: [refusal] })246 );247 285-/** Asks the platform to make the project; a refusal is printed once. */248 const makeProject = (payload: Payload, json: boolean) =>249 Effect.gen(function* () {250 const client = yield* Client;251 4 unmodified lines256 })257 );258 });259 298-/** `--dry-run` prints the plan; without `--yes` nothing happens at all. */260 const approved = (input: Input, plan: Plan) =>261 Effect.gen(function* () {262 if (input.dryRun) {263 const output = yield* Output;9 unmodified lines273 274 return true;275 });276 316-/** An import comes from a public `https://` URL, or not at all. */277 const httpsOnly = (url: string) =>278 HTTPS.test(url)279 ? Effect.void280 : Effect.fail(1 unmodified line282 reason: `--import takes a public repo's https:// URL, and ${url} is not one`,283 })284 );285 326-/** `--branch` says which branch to import, so it needs `--import`. */286 const importOnly = (branch: Option.Option<string>) =>287 Option.isNone(branch)288 ? Effect.void289 : Effect.fail(2 unmodified lines292 "--branch names the branch to import, so it goes with --import",293 })294 );295 337-/** A reply as `--json` prints it: `landed` only when the platform gave one. */296 const withLanded = <A extends object>(297 data: A,298 landed: LandedSha | undefined299 ) => (landed === undefined ? data : { ...data, landed });300 343-/** Has the platform copy the repo at `url`, and says how to clone the project. */301 const 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 lines323 },324 });325 });326 370-/** `init --import <url>`: the platform copies a public repo; nothing here changes. */327 const importing = (input: Input, url: string) =>328 Effect.gen(function* () {329 yield* httpsOnly(url);330 21 unmodified lines352 yield* imported(input, url, payload);353 }354 });355 400-/** What `init` found in the repo it stands in, and so will do there. */356 interface 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 }363 412-/** Writes and commits the config, makes the project, wires the remote and pushes. */364 const made = (input: Input, found: Found) =>365 Effect.gen(function* () {366 const fs = yield* FileSystem.FileSystem;367 const path = yield* Path.Path;61 unmodified lines429 view: { markdown: done.join("\n\n"), text: done.join("\n") },430 });431 });432 482-/** `init` in a repo: propose the config, make the project, wire the remote, push. */433 const inRepo = (input: Input) =>434 Effect.gen(function* () {435 yield* importOnly(input.branch);436 437 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(".");440 441 const project = yield* projectNamed(input.project, {442 owner: Option.none(),1 unmodified line444 });445 446 const inTree = yield* fs.exists(path.join(root, CONFIG));447 499- // 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 linesmodified: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.2 import { judgeInputs } from "@repo/checks/judge";3 import type { JudgeInput } from "@repo/checks/judge";4 import { Array, Effect, Option, Stream } from "effect";5 import { ChildProcess, ChildProcessSpawner } from "effect/process";6 7 import { readOnlyGit } from "./facts.ts";8 20-/** One blob of a commit, as `git ls-tree -r -l` lists it: its mode, path, id and size. */9 export interface ListedBlob {10 readonly mode: string;11 readonly path: string;12 readonly sha: string;1 unmodified line14 }15 16 const decoder = new TextDecoder();17 30-/** Runs git in `root` to its end, `stdin` given: stdout as bytes, or none if it failed. */18 const gitBytes = (root: string, args: readonly string[], stdin?: string) =>19 Effect.scoped(20 Effect.gen(function* () {21 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;22 unmodified lines44 45 const ENTRY =46 /^(?<mode>\d+) blob (?<sha>[0-9a-f]+) +(?<size>\d+)\t(?<path>.+)$/su;47 61-/** Every blob of the commit `revision` names, by its path from the root; none when git can't read it. */48 export const blobsAt = (49 root: string,50 revision: string51 ): Effect.Effect<36 unmodified lines88 }),89 })90 );91 106-/**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. */93 const objectsIn = (output: Uint8Array): readonly Uint8Array[] => {94 const objects: Uint8Array[] = [];95 let at = 0;96 21 unmodified lines118 119 return objects;120 };121 139-/**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- */122 export const judgeFilesIn = (123 root: string,124 listing: readonly ListedBlob[]125 ): Effect.Effect<32 unmodified lines158 );159 });160 };161 183-/** The files the finder and the judge closure are handed at the commit `revision` names. */162 export 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.2 import { Brand } from "@repo/brand";3 import { findRunBlock } from "@repo/checks/finder";4 import { judgeClosure } from "@repo/checks/judge";5 import { workspacesIn } from "@repo/checks/workspaces";28 unmodified lines34 import { commitOf, runGit } from "./facts.ts";35 import { blobsAt, judgeFilesIn } from "./judge-files.ts";36 import type { ListedBlob } from "./judge-files.ts";37 53-/** A file of the config folder, as committed. */38 export interface ConfigFile {39 readonly path: string;40 readonly content: string;41 }42 59-/**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- */43 export class ConfigBundler extends Context.Service<44 ConfigBundler,45 {46 readonly bundle: (1 unmodified line48 ) => Effect.Effect<ConfigBundle, RulesFailed>;49 }50 >()("cli/ConfigBundler") {}51 73-/** The project module's path: it names the folder, as the platform's bundles do. */52 const configEntry = `${Brand.configDir}/project.ts`;53 76-// Code, which a bundle carries only inlined: as the Lander reads the folder.54+// Code, which a bundle carries only inlined.55 const SCRIPT = /\.[cm]?[jt]sx?$/u;56 57 const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;58 81-/** The modules the evaluator imports, each bundled on its own: the project module and every ask. */59 const entriesOf = (paths: readonly string[]) =>60 paths.filter(61 (path) =>62 path === configEntry ||63 (path.startsWith(`${Brand.configDir}/asks/`) && ASK_FILE.test(path))64 );65 89-/** Where bun writes an entry's bundle: its path, as JavaScript. */66 const bundledAs = (entry: string) => entry.replace(/\.[^./]*$/u, ".js");67 68 const loadFailed = (detail: string) =>69 new RulesFailed({ detail, reason: "load" });70 95-/**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- */71 export const ConfigBundlerBun: Layer.Layer<72 ConfigBundler,73 never,74 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path2 unmodified lines77 const fs = yield* FileSystem.FileSystem;78 const path = yield* Path.Path;79 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;80 114- /** 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 lines239 });240 })241 );242 277-/** What the policy is evaluated for, which the repo cannot say. */243 export 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 }248 249 // A regular file, executable or not: the Lander bundles only these from the250 // config folder, never a link or a submodule.251 const FILE_MODES: ReadonlySet<string> = new Set(["100644", "100755"]);252 289-/** A blob's text. */253 const 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 }));258 296-/**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- */259 const factsAt = (input: {260 readonly root: string;261 readonly sha: CommitSha;262 readonly files: readonly ListedBlob[];42 unmodified lines305 onSome: ({ content }) => ({ ...facts, vouchFile: content }),306 });307 });308 352-/** The finishers the platform passes the rules evaluator: `@repo/checks`' own. */309 const finishers = Layer.succeed(Finishers)({ findRunBlock, judgeClosure });310 355-/** Where a policy that names none keeps its vouch file. */311 const defaultVouchFile = `${Brand.configDir}/vouched.td`;312 358-/**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- */313 export const localPolicy = (314 root: string,315 base: string,316 about: PolicyAbout79 unmodified linesmodified: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.2 import { BunHttpServer } from "@effect/platform-bun";3 import { Brand } from "@repo/brand";4 import { detectHarness } from "@repo/protocol/audit";5 import { Contracts } from "@repo/protocol/contracts";26 unmodified lines32 import { Credentials, gitHelperConfig } from "../credentials.ts";33 import type { Profile } from "../credentials.ts";34 import { Output } from "../output.ts";35 48-/** The env names the CLI reads, spelled from the brand: `<SLUG>_URL`. */36 const SLUG = Brand.slug.toUpperCase();37 51-/** The address the loopback server binds: this machine only. */38 const LOOPBACK = "127.0.0.1";39 54-/** How long `login` waits for the browser to come back. */40 const SIGN_IN_WAIT = "5 minutes";41 57-/**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- */42 const clientIdOf = (origin: string) => `${origin}/oauth/cli`;43 64-// --- The host seams: each has a default the binary runs on, and tests swap it.65-66-/**67- * Where `login` hears the browser come back: an HTTP server on one address,68- * for one scope. The binary listens with Bun.69- */44 export const Loopback = Context.Reference<{45 readonly listen: (address: {46 readonly hostname: string;47 readonly port: number;7 unmodified lines55 listen: ({ hostname, port }) => BunHttpServer.make({ hostname, port }),56 }),57 });58 85-/**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- */59 export const PlatformClient = Context.Reference<{60 readonly connect: (profile: {61 readonly token: Redacted.Redacted;62 readonly url: string;15 unmodified lines78 ),79 }),80 });81 113-/** Opens `url` with the first of `commands` that runs; none running is fine. */82 const openWith = (url: string, commands: readonly string[]) =>83 Effect.gen(function* () {84 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;85 13 unmodified lines99 }100 }101 });102 135-/**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- */103 export const Browser = Context.Reference<{104 readonly open: (105 url: string106 ) => Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner>;2 unmodified lines109 open: (url) => openWith(url, ["xdg-open", "open"]),110 }),111 });112 149-// --- Failures.150-151-/** `login` was run in a way that cannot work; the message says what to run. */113 export class LoginUsage extends Schema.TaggedError<LoginUsage>()("LoginUsage", {114 reason: Schema.String,115 }) {116 override get message() {117 return this.reason;118 }119 }120 160-/** The platform, or the sign-in, said no; nothing was stored. */121 export class LoginRefused extends Schema.TaggedError<LoginRefused>()(122 "LoginRefused",123 { reason: Schema.String }124 ) {1 unmodified line126 return this.reason;127 }128 }129 170-/** git would not take a config line; the message names it, to run by hand. */130 export class GitConfigFailed extends Schema.TaggedError<GitConfigFailed>()(131 "GitConfigFailed",132 { command: Schema.String }133 ) {1 unmodified line135 return `git did not take this; run it yourself: ${this.command}`;136 }137 }138 180-// --- Shared parts.181-139 const flags = {140 json: Flag.Boolean("json").pipe(141 Flag.withDefault(false),142 Flag.withDescription("Print machine-readable JSON")5 unmodified lines148 Flag.optional149 ),150 };151 195-/** The profile a command acts on: the flag, else `<SLUG>_PROFILE`, else `default`. */152 const profileName = (153 flag: Option.Option<string>,154 env: Readonly<Record<string, string>>155 ) => Option.getOrElse(flag, () => env[`${SLUG}_PROFILE`] ?? "default");156 201-/** An argv list as a person would type it in a shell. */157 const typed = (argv: readonly string[]) =>158 argv159 .map((arg) => {160 if (arg === "") {5 unmodified lines166 : `'${arg.replaceAll("'", String.raw`'\''`)}'`;167 })168 .join(" ");169 215-/** Runs one `git config` argv list; `allowed` are the exit codes that mean done. */170 const runGit = (171 argv: readonly string[],172 env: Readonly<Record<string, string>>,173 allowed: readonly number[] = [0]20 unmodified lines194 });195 196 const asUrl = Option.liftThrowable((text: string) => new URL(text));197 244-/** Hosts that are this machine, where plain http keeps a token local. */198+/** Hosts where plain http keeps a token on this machine. */199 const THIS_MACHINE = new Set(["localhost", "127.0.0.1", "[::1]"]);200 247-/** `given`'s origin, if it is a platform url: https, or http on this machine. */201 const originOf = (given: string) =>202 Option.match(203 Option.filter(204 asUrl(given),11 unmodified lines216 onSome: ({ origin }) => Effect.succeed(origin),217 }218 );219 267-/**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`. */221 const platformOf = (222 flag: Option.Option<string>,223 profile: Option.Option<string>,224 env: Readonly<Record<string, string>>22 unmodified lines247 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 });250 303-// --- The token, by one of two ways.304-305-/** The token piped to `--token-stdin`: its first line, read no further. */251 const tokenFromStdin = Effect.gen(function* () {252 const { stdin } = yield* Stdio.Stdio;253 254 const [line = ""] = yield* stdin.pipe(16 unmodified lines271 });272 273 const encodeBase64Url = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);274 330-/** `size` bytes from WebCrypto's `getRandomValues`, in base64url. */275 const randomText = (size: number) =>276 Effect.sync(() => crypto.getRandomValues(new Uint8Array(size))).pipe(277 Effect.flatMap(encodeBase64Url),278 Effect.orDie279 );280 337-/** The S256 code challenge for `verifier`: `BASE64URL(SHA256(verifier))`. */281 const 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 );288 346-/**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- */289 const 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 lines324 returned: Deferred.await(returned),325 };326 });327 390-/** What `/token` answers a good code with. */328 const TokenResponse = Schema.Struct({329 access_token: Schema.RedactedFromValue(Schema.NonEmptyString),330 token_type: Schema.String,331 });332 333 const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);334 398-/** Trades the code for an access token at `<url>/token`, showing the verifier. */335 const exchange = (input: {336 readonly code: string;337 readonly redirectUri: string;338 readonly url: string;35 unmodified lines374 Effect.mapError(() => refused)375 );376 };377 442-/**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- */378 const tokenFromBrowser = (url: string, opens: boolean) =>379 Effect.scoped(380 Effect.gen(function* () {381 const output = yield* Output;53 unmodified lines435 return yield* exchange({ code, redirectUri, url, verifier });436 })437 );438 509-/** Asks the platform at `url` who `token` is; a refusal or no answer stores nothing. */439 const verify = (url: string, token: Redacted.Redacted) =>440 Effect.scoped(441 Effect.gen(function* () {442 const client = yield* (yield* PlatformClient).connect({ token, url });8 unmodified lines451 })452 )453 );454 526-/** Whether `login` may open a browser: only for a person at a terminal. */455 const mayOpenBrowser = (env: Readonly<Record<string, string>>) =>456 Effect.gen(function* () {457 const { mode } = yield* Output;458 const { stdoutIsTerminal } = yield* Stdio.Stdio;5 unmodified lines464 (yield* stdoutIsTerminal)465 );466 });467 540-/** The lines of a view: a sentence, then each command on its own line. */468 const viewOf = (said: string, commands: readonly (readonly string[])[]) => {469 const lines = commands.map((argv) => typed(argv));470 471 return {83 unmodified lines555 "Sign in to a platform; git and this CLI then use its token."556 )557 );558 632-/** The `git config --global` lines that undo `gitHelperConfig(url)`; exit 5 means already gone. */559+/** Exit 5 means the line is already gone. */560 const 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 ];564 565 const HELPER_KEY = /^credential\.(?<url>.+)\.helper$/u;566 640-/** The urls whose git config names this CLI's helper. */567 const helperUrls = (env: Readonly<Record<string, string>>) =>568 Effect.gen(function* () {569 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;570 74 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import type { RunBlockEncoded } from "@repo/checks/finder";3 import { PATH_PLACEHOLDER } from "@repo/checks/kinds";4 11-/** A value in the run block: a command, or `setupEgress`'s hosts. */5 type Value = string | readonly string[];6 14-/** The run block's keys in the order the file writes them; `checks` last. */7 const KEYS = ["setup", "test", "doctor", "image", "setupEgress"] as const;8 17-/** A key as TypeScript writes it: bare when it is an identifier. */9 const keyOf = (name: string) =>10 /^[A-Za-z_$][\w$]*$/u.test(name) ? name : JSON.stringify(name);11 21-/** Text as one line of a `//` comment, whatever it holds. */12 const oneLine = (text: string) => text.replaceAll(/\s+/gu, " ").trim();13 14 const comment = (indent: string, text: string) =>15 `${indent}// ${oneLine(text)}`;16 27-/**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- */17 const sourcesOf = (sources: readonly string[], part: string) =>18 sources.filter(19 (source) =>20 source.startsWith(`${part} from `) ||21 source.startsWith(`${part} inferred from `)22 );23 38-/** The parts the run block holds, each with its value, in the file's order. */24 const partsOf = (run: Partial<RunBlockEncoded>) => [25 ...KEYS.flatMap((key) =>26 run[key] === undefined ? [] : [{ part: key, value: run[key] }]27 ),2 unmodified lines30 value: command,31 })),32 ];33 49-/** Every source no written part names: what the finder skipped, and why. */34 const others = (35 sources: readonly string[],36 parts: readonly { readonly part: string }[]37 ) =>3 unmodified lines41 42 const rules = (names: string) =>43 `import { ${names} } from "${Brand.cliPackage}/rules";`;44 61-/** A run block written out: each command under the comments naming its sources. */45 const explicit = (46 run: Partial<RunBlockEncoded>,47 sources: readonly string[]48 ) => {31 unmodified lines80 "",81 ];82 };83 101-/**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. */85 const fromCI = (run: Partial<RunBlockEncoded>, sources: readonly string[]) => {86 const parts = partsOf(run);87 88 return [18 unmodified lines107 "",108 ];109 };110 132-/**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- */111 export const projectFile = (112 run: Partial<RunBlockEncoded>,113 sources: readonly string[]114 ): string =>4 unmodified linesmodified: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`.3 import { CheckAt, CheckRunner, outputOf } from "@repo/checks/check-runner";4 import type { CheckLane, CheckRun } from "@repo/checks/check-runner";5 import {6 countLanes,13 unmodified lines20 import { RatchetName } from "@repo/protocol/ids";21 import type { CommitSha, ProjectName, RepoName } from "@repo/protocol/ids";22 import { Array, Effect, Option, Result, Schema } from "effect";23 39-/** One ratchet's count in one territory, on the answer's base and on its head. */24 export const RatchetMove = Schema.Struct({25 after: Schema.Int,26 before: Schema.Int,27 ratchet: RatchetName,1 unmodified line29 });30 31 export type RatchetMove = typeof RatchetMove.Type;32 49-/** A ratchet no count was read for here, and why. */33 export interface Uncounted {34 readonly ratchet: RatchetName;35 readonly why: string;36 }37 55-/** What counting on this machine gave: the counts both trees had, and what it could not count. */38 export interface LocalCounts {39 readonly moves: readonly RatchetMove[];40 readonly uncounted: readonly Uncounted[];41 }42 61-/** How a count lane that printed no count ended, in words. */43 const 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>;50 70-/**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- */51 const 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 lines60 ),61 ])62 );63 88-/** One ratchet's counts per territory on one tree, or why none were read. */64 interface Counted {65 readonly ratchet: RatchetName;66 readonly counts: Result.Result<readonly RatchetCount[], Uncounted>;67 }68 94-/** Each ratchet's counts from one run of its count lanes. */69 const countsIn = (70 policy: Policy,71 ran: CheckRun72 ): Effect.Effect<readonly Counted[]> => {26 unmodified lines99 );100 });101 };102 129-/**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. */104 export const countRatchets = (input: {105 readonly base: CommitSha;106 readonly head: CommitSha;107 readonly policy: Policy;67 unmodified lines175 176 return { moves, uncounted };177 });178 210-/**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- */179 export const judgeMoves = (180 facts: PushFacts,181 ask: Ask,182 moves: readonly RatchetMove[]15 unmodified linesmodified: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.2 import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";3 import { isStale } from "@repo/agent-kit/generated-file";4 import { projectSkill } from "@repo/agent-kit/project-skill";5 import type { Policy } from "@repo/protocol/domain/policy";6 import type { LandedSha, ProjectName } from "@repo/protocol/ids";7 import { Effect, FileSystem, Option, Path } from "effect";8 22-/** A generated file on disk that is not what main's policy gives, and the landing its copy names. */9 export 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 }13 14 const agentsFile = "AGENTS.md";15 31-/**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- */16 export const staleGenerated = (input: {17 readonly root: string;18 readonly project: ProjectName;19 readonly policy: Policy;47 unmodified linesmodified: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- */1 import { notesRef } from "@repo/git/notes";2 import { parseTrailers } from "@repo/git/trailers";3 import type { Trailer } from "@repo/git/trailers";4 import { Client } from "@repo/protocol/contracts";17 unmodified lines22 import type { View } from "../output.ts";23 import { repoContext } from "../repo-context.ts";24 import type { RepoContext } from "../repo-context.ts";25 34-/**35- * Where a local command runs git: the process's own folder unless a caller36- * (a test) provides another. Shared with `env set`.37- */26 export const WorkingDirectory = Context.Reference<string>(27 "cli/WorkingDirectory",28 { defaultValue: () => "." }29 );30 43-/**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- */31 export class UsageError extends Schema.TaggedError<UsageError>()("UsageError", {32 reason: Schema.String,33 }) {34 override readonly [Runtime.errorExitCode] = 2;3 unmodified lines38 return this.reason;39 }40 }41 58-/**59- * Ends the command as a usage error: `program` prints `reason` once on60- * stderr, as it does every misuse, and exits 2.61- */42 export const usage = (reason: string) =>43 Effect.fail(new UsageError({ reason }));44 45 const isRefusal = Schema.is(Refusal);46 67-/**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- */47 export const reportRefusals =48 (command: string, json: boolean) =>49 <A, E, R>(effect: Effect.Effect<A, E, R>) =>50 effect.pipe(3 unmodified lines54 )55 )56 );57 82-/**83- * The project a command acts on: `--project`, else the one the repo's84- * platform remote names. Shared with `env set`.85- */58 export const projectOf = (59 named: Option.Option<ProjectName>,60 context: Option.Option<RepoContext>61 ) =>11 unmodified lines73 onSome: Effect.succeed,74 }75 );76 105-// 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.78 const LOCATION = /^(?<path>.+):(?<line>[1-9][0-9]*)$/u;79 109-/** A line of a file as people and compilers write it: `src/week.ts:42`. */80 export const parseLocation = (81 text: string82 ): Option.Option<{ readonly path: RepoPath; readonly line: number }> => {83 const groups = LOCATION.exec(text)?.groups;3 unmodified lines87 ? Option.none()88 : Option.some({ line, path: RepoPath.make(groups.path) });89 };90 121-/** What `why` found: the line's commit and what is known of it. */91 const 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 lines107 108 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>109 bytes.pipe(Stream.decodeText(), Stream.mkString);110 145-/** Runs git in `cwd` to the end: its stdout and exit code; stderr is dropped. */111 const git = (cwd: string, args: readonly string[]) =>112 Effect.scoped(113 Effect.gen(function* () {114 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;14 unmodified lines129 return { exitCode, stdout };130 })131 );132 168-/** The line is in no file committed at HEAD. */133 const 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 );137 174-/** `path` as the repo names it from its root, if HEAD holds it. */138 const pathAtHead = (cwd: string, path: RepoPath, location: string) =>139 Effect.flatMap(140 git(cwd, [141 "ls-tree",15 unmodified lines157 158 // git blame's porcelain opens with the line's commit, then its line numbers.159 const BLAMED = /^(?<sha>[0-9a-f]{40}) /u;160 198-/** The commit that last changed line `line` of `path` at HEAD. */161 const blamed = (cwd: string, path: RepoPath, line: number, location: string) =>162 Effect.flatMap(163 git(cwd, [164 "blame",12 unmodified lines177 : noSuchLine(location);178 }179 );180 219-/** The trailers `sha`'s author wrote, as git reads them. */181 const trailersOf = (cwd: string, sha: CommitSha) =>182 Effect.map(git(cwd, ["log", "-1", "--format=%B", sha]), ({ stdout }) =>183 parseTrailers(stdout)184 );185 225-/** The verdict note on `sha`, if one was fetched and it reads as a verdict. */186 const noteOn = (cwd: string, sha: CommitSha) =>187 Effect.flatMap(188 git(cwd, ["notes", `--ref=${notesRef}`, "show", sha]),189 ({ exitCode, stdout }) => {14 unmodified lines204 );205 206 const short = (sha: string) => sha.slice(0, 7);207 248-/** One fact about the line, as a list item. */208 interface Row {209 readonly label: string;210 readonly value: string;252- /** Code in Markdown: an id or a path. */211 readonly code?: boolean;212 }213 214 const verdictRow = (verdict: Verdict): Row => ({3 unmodified lines218 ...verdict.lanes.map(({ lane, result }) => `${lane} ${result}`),219 ].join(", "),220 });221 264-/**265- * The ask a landing links: the one it answers ("Ask"), else the one it266- * opened ("Opened": an opening answers nothing), else none.267- */222 const askRow = (landing: LandingView): Row => {223 if (landing.ask !== undefined) {224 return { code: true, label: "Ask", value: landing.ask };225 }21 unmodified lines247 248 const trailerRows = (trailers: readonly Trailer[]): readonly Row[] =>249 trailers.map(({ key, value }) => ({ label: key, value }));250 297-/** The line's story, in Markdown for agents and plain text for a person. */251 const 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 linesmodified: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- */1 import { Client, Description, TodayOf } from "@repo/protocol/contracts";2 import { ProjectName } from "@repo/protocol/ids";3 import type { NotDecider, UnknownProject } from "@repo/protocol/refusal";4 import { Context, Effect, Option, Schema } from "effect";6 unmodified lines11 const COMMAND = "today";12 13 const encodeToday = Schema.encodeUnknownEffect(TodayOf.successSchema);14 23-/**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- */15 const 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 line20 21 return { NotDecider: once, UnknownProject: once };22 };23 36-/** Today printed once, in the form the invocation policy chose. */24 const print = (input: {25 readonly json: boolean;26 readonly project: Option.Option<ProjectName>;27 }) =>20 unmodified lines48 view,49 });50 });51 65-/**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- */52 const full = (input: {53 readonly json: boolean;54 readonly project: Option.Option<ProjectName>;55 }) =>44 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import { Client } from "@repo/protocol/contracts";3 import type { Decision } from "@repo/protocol/domain/decision";4 import type { ProjectName } from "@repo/protocol/ids";14 unmodified lines19 import { CurrentMode, Policy } from "../policy.ts";20 import { placeOf, reduce, refreshed, start } from "./today.ts";21 import type { DecideCall, TodayViewState } from "./today.ts";22 35-/** What a script or an agent runs for Today instead. */23 const instead = `${Brand.cli} today --json`;24 38-/**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- */25 export class TuiRefused extends Schema.TaggedError<TuiRefused>()("TuiRefused", {26 next: Schema.NonEmptyString.pipe(27 Schema.withConstructorDefault(Effect.succeed(instead))28 ),5 unmodified lines34 return `${Brand.cli} today --tui needs a person at a terminal, but ${this.reason}: run ${this.next} instead`;35 }36 }37 57-/** Why something failed, in a few words: its message, or itself. */38 export const causeText = (cause: unknown) =>39 Predicate.hasProperty(cause, "message") && Predicate.isString(cause.message)40 ? cause.message41 : String(cause);42 63-/** A screen Today is drawn on and keys are read from. */43 export 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 }48 49 /** Opens the terminal through OpenTUI, loading it only now. */5 unmodified lines55 }),56 try: () => import("./screen.ts"),57 }).pipe(Effect.flatMap(({ openTerminal }) => openTerminal));58 83-/** How `--tui` opens its screen: the terminal, unless a test gives another. */59 export const OpenScreen = Context.Reference<60 Effect.Effect<Screen, TuiRefused, Scope.Scope>61 >("cli/tui/OpenScreen", { defaultValue: () => terminal });62 88-/**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- */63 const invocation = Effect.flatMap(64 Effect.serviceOption(Policy),65 Option.match({66 onNone: () => Effect.provide(Effect.service(Policy), CurrentMode),67 onSome: Effect.succeed,68 })69 );70 101-/**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- */71 const aPersonAtATerminal = Effect.gen(function* () {72 const { mode, reason } = yield* invocation;73 74 const typing = yield* Effect.flatMap(14 unmodified lines89 });90 91 const isRefusal = Schema.is(Refusal);92 127-/** The `today` contract's payload, for one project or every one. */93 export const payloadFor = (project: Option.Option<ProjectName>) =>94 Option.match(project, {95 onNone: () => ({}),96 onSome: (name) => ({ project: name }),97 });98 134-/** What a choice the platform took came to, in one line. */99 const decidedLine = (call: DecideCall, decision: Decision) =>100 `Decided: ${decision.decided?.choice ?? call.choice} on ${placeOf(call.project, call.decision)}`;101 138-/**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- */102 export const runTodayTui = (input: {103 readonly project: Option.Option<ProjectName>;104 }) =>105 Effect.gen(function* () {4 unmodified lines110 const payload = payloadFor(input.project);111 112 const first = start(yield* client.today(payload));113 157- /** 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 lines134 135 return after;136 });137 182- /** 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 linesmodified: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.2 import { createCliRenderer } from "@opentui/core";3 import type { CliRenderer, KeyEvent } from "@opentui/core";4 import { createElement, createRoot, flushSync } from "@opentui/react";5 import { Effect, Queue } from "effect";2 unmodified lines8 import { causeText, TuiRefused } from "./run.ts";9 import type { Screen } from "./run.ts";10 import { TodayView } from "./view.ts";11 17-/** A key as `reduce` reads it: its name, with `ctrl+` before it when Ctrl is held. */12 const keyName = (key: KeyEvent) => (key.ctrl ? `ctrl+${key.name}` : key.name);13 20-/**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. */15 export const screenOn = (16 renderer: CliRenderer17 ): Effect.Effect<Screen, never, Scope.Scope> =>18 Effect.gen(function* () {25 unmodified lines44 }),45 } satisfies Screen;46 });47 58-/**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`. */49 export const openTerminal: Effect.Effect<Screen, TuiRefused, Scope.Scope> =50 Effect.acquireRelease(51 Effect.tryPromise({52 catch: (cause) =>15 unmodified linesmodified: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.3 import type { Decide } from "@repo/protocol/contracts";4 import { DecisionSubject } from "@repo/protocol/domain/decision";5 import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";6 import type { DecisionId, ProjectName } from "@repo/protocol/ids";7 import { Array as Arr, DateTime, Option, Order } from "effect";8 22-/** A choice on its way to `decide`: the contract's payload, without a note. */9 export type DecideCall = Omit<typeof Decide.payloadSchema.Type, "note">;10 11 export 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 }17 35-/** What one key did: the next state, the call to make, and whether to close. */18 export interface Step {19 readonly state: TodayViewState;20 readonly call: Option.Option<DecideCall>;21 readonly quit: boolean;22 }23 42-/**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. */25 export const placeOf = (project: ProjectName, id: DecisionId) =>26 `${project}/${id}`;27 28 const keyOf = ({ id, project }: Decision) => placeOf(project, id);29 51-/** Soonest to expire first, then oldest, then by project and id: one order every time. */30 const 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 ]);36 59-/**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. */38 const 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 lines48 )49 );50 };51 78-/** Whether a decision is one of those `today.expiringSoon` names. */52 export const soonIn = (today: Today) => {53 const soon = expiringSoon(today);54 55 return (decision: Decision) => soon.has(keyOf(decision));56 };57 85-/** Today's decisions in the order a decider takes them: expiring soon first, then by expiry. */58 export const inOrder = (today: Today): readonly Decision[] => {59 const isSoon = soonIn(today);60 61 return Arr.sort(4 unmodified lines66 )67 );68 };69 98-/** A choice, and the key that makes it. */70 export interface ChoiceKey {71 readonly choice: Choice;72 readonly key: string;73 }2 unmodified lines76 { choice: "accept", key: "a" },77 { choice: "decline", key: "d" },78 ];79 109-/** The choices a decision's subject offers, each with its key. */80 export const choicesFor = (decision: Decision): readonly ChoiceKey[] =>81 DecisionSubject.match(decision.subject, {82 Finish: () => yesOrNo,83 OpenProposal: () => yesOrNo,8 unmodified lines92 Vouch: () => yesOrNo,93 Waiver: () => yesOrNo,94 });95 126-/** Today as the decider first sees it: on the first decision, nothing chosen. */96 export const start = (today: Today): TodayViewState => ({97 confirming: Option.none(),98 cursor: 0,99 notice: [],100 today,101 });102 134-/** The decision the cursor is on, if Today holds any. */103 export const current = (state: TodayViewState): Option.Option<Decision> =>104 Arr.get(inOrder(state.today), state.cursor);105 138-/** A cursor kept on a decision: never past the last one, never below the first. */106 const clamp = (cursor: number, today: Today) =>107 Math.max(0, Math.min(cursor, today.decisions.length - 1));108 109 const stay = (state: TodayViewState): Step => ({14 unmodified lines124 confirming: Option.none(),125 cursor: clamp(state.cursor + by, state.today),126 });127 161-/**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- */128 const choose = (state: TodayViewState, key: string): Step =>129 Option.match(current(state), {130 onNone: () => stay(state),131 onSome: (decision) =>29 unmodified lines161 const CONFIRM = new Set(["y", "return", "enter"]);162 163 const CANCEL = new Set(["n", "escape"]);164 203-/** One key, with no confirmation waiting. */165 const free = (state: TodayViewState, key: string): Step => {166 if (UP.has(key)) {167 return moveBy(state, -1);168 }8 unmodified lines177 178 return choose(state, key);179 };180 220-/**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- */181 export const reduce = (state: TodayViewState, key: string): Step =>182 Option.match(state.confirming, {183 onNone: () => free(state, key),184 onSome: (waiting) => {6 unmodified lines191 return CANCEL.has(key) ? stay(cancelled) : free(cancelled, key);192 },193 });194 240-/**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. */196 export const refreshed = (197 state: TodayViewState,198 today: Today,199 notice: readonly string[]6 unmodified linesmodified: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.2 import { TextAttributes } from "@opentui/core";3 import { createElement } from "@opentui/react";4 import type { BoxProps, TextProps } from "@opentui/react";5 import type { JSX } from "@opentui/react/jsx-runtime";5 unmodified lines11 import type { DecideCall, TodayViewState } from "./today.ts";12 13 const short = (sha: string) => sha.slice(0, 7);14 24-/** A ref as people say it: `main` for `refs/heads/main`. */15 const refWords = (ref: string) => ref.replace(/^refs\/heads\//u, "");16 27-/** What a decision is about, in a few words. */17 const 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 lines30 Waiver: ({ at, marker, reason }) =>31 `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,32 });33 45-/** An expiry as a decider reads it: weekday, date and time, in UTC. */34 const byWhen = (at: DateTime.Utc) =>35 `${DateTime.formatUtc(at, {36 day: "numeric",37 hour: "2-digit",9 unmodified lines47 48 const capitalized = (word: string) =>49 `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`;50 63-/**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. */52 const box = (props: BoxProps, ...children: readonly JSX.Element[]) =>53 createElement("box", { flexShrink: 0, ...props }, ...children);54 55 const line = (content: string, props: TextProps = {}) =>56 createElement("text", { flexShrink: 0, wrapMode: "word", ...props }, content);57 58 const muted = { attributes: TextAttributes.DIM } as const satisfies TextProps;59 76-/** One fact's value as a row holds it: its first line, and how many follow. */60 const firstLine = (value: string) => {61 const [first = "", ...rest] = value.split("\n");62 63 return rest.length === 044 unmodified lines108 line(` ${label}: ${firstLine(value)}`, muted)109 )110 );111 129-/**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. */113 const Decisions = ({ state }: { readonly state: TodayViewState }) => {114 const ordered = inOrder(state.today);115 const isSoon = soonIn(state.today);116 const above = state.cursor;27 unmodified lines144 state.today.newcomers.length === 0145 ? box({})146 : line(`Newcomers to welcome: ${state.today.newcomers.join(", ")}`);147 169-/** The question a choice other than the default waits on. */148 const 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.`;150 173-/** The keys the decision under the cursor takes, or the confirmation waiting. */151 const Keys = ({ state }: { readonly state: TodayViewState }) => {152 const here = current(state);153 154 const asking = Option.flatMap(state.confirming, (call) =>17 unmodified lines172 line(["up/down move", ...choices, "q quit"].join(" · "), muted)173 );174 };175 199-/** The whole screen for one state. */176 export const TodayView = ({177 state,178 }: {179 readonly state: TodayViewState;8 unmodified linesmodified: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.3 import { BunRuntime, BunServices } from "@effect/platform-bun";4 import { Brand } from "@repo/brand";5 import { Effect, Layer, Path, Stdio } from "effect";6 7 import { CliServices, program } from "./main.ts";8 9 const live = CliServices.pipe(Layer.provideMerge(BunServices.layer));10 19-/**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]`. */12 const startedAs = Effect.map(Path.Path, (path) =>13 [process.argv0, process.argv[1]].map((name) => path.basename(name ?? ""))14 );15 30-/**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- */16 const main = Effect.gen(function* () {17 const names = yield* startedAs;18 const args = yield* Effect.flatMap(Stdio.Stdio, (stdio) => stdio.args);19 6 unmodified linesmodified: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.2 import { Brand } from "@repo/brand";3 import { auditUser, detectHarness } from "@repo/protocol/audit";4 import {5 ConfigProvider,8 unmodified lines14 15 import { Credentials } from "./credentials.ts";16 import { Output } from "./output.ts";17 28-/** What git asks a helper to do. */18 export type Operation = "get" | "store" | "erase";19 20 const operations = [21 "get",22 "store",23 "erase",24 ] as const satisfies readonly Operation[];25 37-/** The env, by name: what `detectHarness` reads. */26 export type Env = Readonly<Record<string, string | undefined>>;27 40-/**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. */29 const INDEX_LIMIT = 1024;30 49-/** The env-name parts below `path` and their values, from the CLI's config provider. */31 const namesBelow = (32 provider: ConfigProvider.ConfigProvider,33 path: ConfigProvider.Path34 ): Effect.Effect<readonly (readonly [string, string])[]> =>28 unmodified lines63 })64 )65 );66 86-/**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- */67 export const currentEnv: Effect.Effect<Readonly<Record<string, string>>> =68 Effect.gen(function* () {69 const provider = yield* ConfigProvider.ConfigProvider;70 71 return Object.fromEntries(yield* namesBelow(provider, []));72 });73 98-/** git's request: its `key=value` lines, up to the blank line that ends it. */74 const requestOf = (input: string) => {75 const fields = new Map<string, string>();76 77 for (const line of input.split("\n")) {10 unmodified lines88 89 return fields;90 };91 117-/** The env names the CLI reads, spelled from the brand: `<SLUG>_PROFILE`. */92 const SLUG = Brand.slug.toUpperCase();93 120-/** `url`'s scheme without its colon, and its `host[:port]` in lowercase, if it is a URL. */94 const placeOf = Option.liftThrowable((url: string) => {95 const { host, protocol } = new URL(url);96 97 return { host: host.toLowerCase(), scheme: protocol.replace(/:$/u, "") };98 });99 127-/** A value git's credential protocol can carry: one line, no NUL. */100 const fitsOneLine = (value: string) => !/[\n\r\0]/u.test(value);101 130-/** What the helper prints: for git on stdout, and maybe a line for a person on stderr. */102 interface Answer {103 readonly stdout: string;104 readonly note: Option.Option<string>;105 }106 107 const silent: Answer = { note: Option.none(), stdout: "" };108 138-/**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. */110 const answer = (op: Operation, input: string, env: Env) =>111 Effect.gen(function* () {112 if (op !== "get") {113 return silent;48 unmodified lines162 }163 : silent;164 });165 203-/**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- */166 export 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);172 214-/**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- */173 const readRequest = Effect.gen(function* () {174 const { stdin } = yield* Stdio.Stdio;175 176 const lines = yield* stdin.pipe(6 unmodified lines183 184 return `${lines.join("\n")}\n\n`;185 });186 232-/** `<cli> credential <get|store|erase>`: what `git-credential-<slug>` runs. */187 export const credential = Command.make(188 "credential",189 {190 operation: Argument.Literals("operation", operations).pipe(27 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import { Handle } from "@repo/protocol/ids";3 import {4 Array,7 unmodified lines12 Path,13 Schema,14 } from "effect";15 22-/** One platform the CLI can call, as whom. */16 export 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 });21 22 export type Profile = typeof Profile.Type;23 34-/** The credentials file could not be written, or is there and unreadable. */24 export class CredentialsUnwritable extends Schema.TaggedError<CredentialsUnwritable>()(25 "CredentialsUnwritable",26 { path: Schema.String }27 ) {4 unmodified lines32 33 export 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") {}47 62-/** The file: profiles by name. */48 const Store = Schema.fromJsonString(49 Schema.Struct({ profiles: Schema.Record(Schema.String, Profile) })50 );51 52 const decodeStore = Schema.decodeEffect(Store);53 54 const encodeStore = Schema.encodeEffect(Store);55 71-/** The env names, spelled from the brand: `<SLUG>_TOKEN`. */56 const SLUG = Brand.slug.toUpperCase();57 74-/** What the CLI reads of its env, once. */58 const 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 });65 83-/** `url`'s `host[:port]`, in lowercase, if it is a URL. */66 const hostOf = Option.liftThrowable((url: string) =>67 new URL(url).host.toLowerCase()68 );69 1 unmodified line71 const FILE_MODE = 0o600;72 73 const DIR_MODE = 0o700;74 93-/**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. */76 export const CredentialsFile = Layer.effect(Credentials)(77 Effect.gen(function* () {78 const fs = yield* FileSystem.FileSystem;79 const path = yield* Path.Path;16 unmodified lines96 Option.all({ token: env.token, url: env.url }),97 ({ token, url }): Profile => ({ token, url })98 );99 121- /** 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 lines113 return store.profiles;114 }).pipe(Effect.mapError(() => new CredentialsUnwritable({ path: at }))),115 });116 139- /** 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 lines183 };184 })185 );186 210-/**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. */188 export const gitHelperConfig = (189 url: string190 ): readonly (readonly string[])[] => [191 [17 unmodified linesmodified: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.2 import { HookEvent } from "@repo/agent-kit/hook-events";3 import { Brand } from "@repo/brand";4 import {5 Cause,19 unmodified lines25 import { Output } from "./output.ts";26 27 const EVENTS = HookEvent.literals.join(", ");28 41-/**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- */29 export class HookUsage extends Schema.TaggedError<HookUsage>()("HookUsage", {30 event: Schema.String,31 }) {32 override readonly [Runtime.errorExitCode] = 2;5 unmodified lines38 }39 40 const decodeEvent = Schema.decodeUnknownOption(HookEvent);41 58-/** The whole of stdin, as text. */42 const stdinText = Effect.flatMap(Stdio.Stdio, ({ stdin }) =>43 stdin.pipe(Stream.decodeText(), Stream.mkString)44 );45 63-/** The PushCheck the caller provided, or this CLI run again as a child. */46 const pushCheck = Effect.flatMap(47 Effect.serviceOption(PushCheck),48 Option.match({49 onNone: () => Effect.provide(Effect.service(PushCheck), PushCheckChild),50 onSome: Effect.succeed,51 })52 );53 72-/**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. */55 const sessionFacts = (event: HookEvent, input: HookInput) =>56 Effect.gen(function* () {57 const kept = yield* loadSession(input.session_id);58 14 unmodified lines73 74 return gathered;75 });76 102-/** Stop asks the local check, from the claim's base; nothing else does, and only with a claim. */77 const refusalsFor = (event: HookEvent, state: SessionState) => {78 const { claim } = state;79 80 return event === "stop" && claim !== undefined81 ? Effect.flatMap(pushCheck, (check) => check.run(state.root, claim.base))82 : Effect.succeed([]);83 };84 111-/** Answers one event: the decision's JSON, with its note on stderr. */85 const answer = (event: HookEvent, input: HookInput) =>86 Effect.gen(function* () {87 const output = yield* Output;88 const state = yield* sessionFacts(event, input);40 unmodified lines129 130 return decision.output;131 });132 160-/** The answer on stdout: one line of JSON, or indented for a person. */133 const print = (json: boolean, output: HookOutput) =>134 Console.log(json ? JSON.stringify(output) : JSON.stringify(output, null, 2));135 164-/** Says why the hook allows, on stderr, and lets the harness go on. */136 const failOpen = (json: boolean, why: string) =>137 Effect.andThen(138 Output.use((output) => output.note(`hook: ${why}; allowing`)),139 print(json, {})54 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import { ApprovalNeeded, MissingValue, Reported } from "@repo/protocol/cli";3 import { ExitCode } from "@repo/protocol/exit-code";4 import { Unauthenticated } from "@repo/protocol/principal";15 unmodified lines20 } from "./remote.ts";21 import { commands, mcp, UnknownCommand } from "./surfaces.ts";22 import { cliVersion } from "./version.ts";23 29-/**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- */24 export 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");30 40-/** The commands at the top: the contracts and the hand-written ones, then the servers. */31 const tree = [...commands, mcp, hook, credential];32 33 export const root = Command.make(Brand.cli).pipe(34 Command.withDescription(banner),35 Command.withSubcommands(tree)36 );37 48-/** The exit code of a usage error, as for a command line effect/cli can't parse. */38 const USAGE = ExitCode.usage;39 51-/**52- * The command was misused and said so in one line on stderr: the program53- * exits 2 and prints nothing more.54- */40 export class Misused extends Schema.TaggedError<Misused>()("Misused", {}) {41 override readonly [Runtime.errorExitCode] = USAGE;42 override readonly [Runtime.errorReported] = false;43 }3 unmodified lines47 const isReported = Schema.is(Reported);48 49 const isUnauthenticated = Schema.is(Unauthenticated);50 66-/** Usage errors this CLI shares across its commands, beside effect/cli's. */51 const isSharedUsage = Schema.is(52 Schema.Union([ApprovalNeeded, MissingValue, UnknownCommand])53 );54 71-/** What to run when the platform does not know who is calling. */55 const signIn = [56 "Unauthenticated: the platform does not know who you are",57 ` next: ${Brand.cli} login`,58 " retryable: no",59 ].join("\n");60 78-/** How running the tree can fail. */61 type Failure = Command.Error<typeof root> | CliError.CliError;62 81-/**82- * Whether a failure is a usage error: a shared one, or one a command marks83- * with exit code 2 (`init`'s `InitMisused`).84- */63 const isUsage = (failure: Failure) =>64 isSharedUsage(failure) || Runtime.getErrorExitCode(failure) === USAGE;65 88-/** One line for a failure that is a misuse of the command; none otherwise. */66 const usageLine = (failure: Failure): Option.Option<string> => {67 if (CliError.isCliError(failure)) {68 return Option.some(69 Schema.is(CliError.ShowHelp)(failure)10 unmodified lines80 ? Option.map(noPlatformOf(failure), ({ message }) => message)81 : Option.none();82 };83 107-/** What to say on stderr about a failure nobody printed yet, and the code the process ends with. */84 const noteFor = (failure: Failure) => {85 if (isUnauthenticated(failure)) {86 return { exitCode: ExitCode.noPerm, note: signIn };87 }7 unmodified lines95 96 return { exitCode: ExitCode.failed, note: String(failure) };97 };98 123-/** How a failure printed already ends: as it said, or with its refusal's code. */99 const printed = (failure: Failure): Option.Option<Reported> => {100 if (isReported(failure)) {101 return Option.some(failure);102 }2 unmodified lines105 ? Option.some(Reported.of([failure]))106 : Option.none();107 };108 134-/**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- */109 const settle = (110 failure: Failure111 ): Effect.Effect<never, Reported | Misused, Output> =>112 Option.match(usageLine(failure), {13 unmodified lines126 Effect.andThen(Effect.fail(new Misused()))127 ),128 });129 161-/** Whether a run ended in a misuse effect/cli found: a parse error. */130 const isMisuse = (failure: Failure) =>131 Schema.is(CliError.ShowHelp)(failure) && failure.errors.length > 0;132 165-/**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. */134 const builtInsFor = (policy: Option.Option<Policy["Service"]>) =>135 Option.exists(policy, ({ mode }) => mode !== "human")136 ? GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Wizard)137 : GlobalFlag.BuiltIns;138 139 /**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 */143 export const program = (argv: readonly string[]) =>144 Effect.gen(function* () {145 yield* refuseStrangeFlags(argv);28 unmodified lines174 onSuccess: () => Effect.void,175 })176 );177 220-/**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- */178 export 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.2 import type { View } from "@repo/protocol/cli";3 import { Envelope } from "@repo/protocol/envelope";4 import type { Refusal } from "@repo/protocol/refusal";5 import { explain } from "@repo/protocol/render";12 unmodified lines18 export 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") {}41 52-/** Any envelope's JSON: its data is already encoded. */42 const encodeEnvelope = Schema.encodeEffect(43 Schema.fromJsonString(Envelope(Schema.Unknown))44 );45 57-/** One envelope, as the one document on stdout. */46 const printEnvelope = (envelope: Envelope<unknown>) =>47 encodeEnvelope(envelope).pipe(Effect.orDie, Effect.flatMap(Console.log));48 49 const capitalized = (word: string) =>50 `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`;51 64-/**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- */52 const asMarkdownList = (lines: readonly string[]) =>53 lines.map((line) => {54 const detail = /^ {2}(?<key>[a-z]+): (?<value>.*)$/u.exec(line)?.groups;55 5 unmodified lines61 62 return ` - ${capitalized(detail.key)}: ${value}`;63 });64 82-/** The JSON a plan sends, as a person reads it or as a Markdown block. */65 const planText = (mode: Mode, command: string, json: string) =>66 mode === "human"67 ? `${command} would send this, and sent nothing:\n${json}`68 : [3 unmodified lines72 json,73 "```",74 ].join("\n");75 94-/**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- */76 const outputFor = (mode: Mode): Output["Service"] => ({77 mode,78 note: (text) => Console.error(text),79 plan: ({ command, json, payload }) =>26 unmodified lines106 );107 },108 });109 134-/** Output for a person, whatever the process: what tests of a command's text use. */110 export const OutputPlain = Layer.succeed(Output)(outputFor("human"));111 137-/** Output in the form the invocation policy chose for this process. */112 export const OutputLive: Layer.Layer<Output, never, Policy> = Layer.effect(113 Output114 )(Effect.map(Effect.service(Policy), ({ mode }) => outputFor(mode)));115 142-/**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. */117 export const holdStdout = (real: Console.Console) => {118 const held: (readonly unknown[])[] = [];119 let open = false;120 77 unmodified linesmodified: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.2 import type {3 AgentBeforeSettleEvent,4 AgentBeforeSettleEventResult,5 BeforeAgentStartEvent,38 unmodified lines44 import { loadSession, saveSession } from "./hook/session.ts";45 import type { SessionState } from "./hook/session.ts";46 import { RemoteClient } from "./remote.ts";47 54-/** The policy could not answer; the adapter allows, and says why. */48 export 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 }55 63-/** One pi session: its id, and the folder its agent runs in. */56 export interface PiSession {57 readonly cwd: string;58 readonly id: string;59 }60 69-/** A tool call the policy judges before it runs, read from pi's own. */61 export 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" };64 65 export const GuardedCall = Data.taggedEnum<GuardedCall>();66 78-/** Where the session's answer stands when its agent is about to stop. */67 export 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 };75 76 export const SettleVerdict = Data.taggedEnum<SettleVerdict>();77 91-/** The boundary to the hook policy: what the adapter asks it, per session. */78 export 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 lines90 session: PiSession91 ) => Effect.Effect<SettleVerdict, HookFailed>;92 }93 110-/** What the adapter reads of a handler's context. */94 export type PiContext = Pick<ExtensionContext, "cwd"> & {95 readonly sessionManager: Pick<96 ExtensionContext["sessionManager"],97 "getSessionId"98 >;99 readonly ui?: Pick<ExtensionUIContext, "notify">;100 };101 119-/** The adapter's handlers, by pi event, as pi 1.0.3 types each event. */102 export interface PiHandlers {103 readonly agent_before_settle: (104 event: AgentBeforeSettleEvent,105 ctx: PiContext7 unmodified lines113 ctx: PiContext114 ) => Promise<ToolCallEventResult | undefined>;115 }116 135-/** The part of pi's `ExtensionAPI` the adapter uses: `on`, for three events. */117 export interface PiEvents {118 readonly on: {119 (120 event: "agent_before_settle",7 unmodified lines128 };129 }130 131 export 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 }134 158-/** The custom type of the brief pi shows before the agent starts. */135 const BRIEF = `${Brand.slug}-brief`;136 161-/** The custom type of the verdict a settle sends the agent back with. */137 const VERDICT = `${Brand.slug}-verdict`;138 164-/** What the agent reads when it is sent back: why, then the gateway's own text. */139 const verdictEntry = (140 refusals: Array.NonEmptyReadonlyArray<Refusal>141 ): CustomMessageEntryDraft => ({142 content: [4 unmodified lines147 display: true,148 type: "custom_message",149 });150 177-/** pi's `edit` and `write` name the file they change as `path`. */151 const decodeFile = Schema.decodeUnknownOption(152 Schema.Struct({ path: Schema.String })153 );154 182-/** pi's `bash` runs `command`. */155 const decodeCommand = Schema.decodeUnknownOption(156 Schema.Struct({ command: Schema.String })157 );158 187-/**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. */160 const GIT_PUSH =161 /(?:^|[\s;&|(`])git(?:\s+-[Cc]\s+\S+|\s+-\S+)*\s+push(?![\w-])/u;162 196-/**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- */163 const 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 lines174 ),175 Match.orElse(() => Option.none())176 );177 216-/**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- */178 const fixable = (refusals: readonly Refusal[]) =>179 refusals.filter((refusal) => !refusal.retryable);180 223-/**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- */181 const blockFor = (182 refusals: Option.Option<Array.NonEmptyReadonlyArray<Refusal>>183 ): Option.Option<ToolCallEventResult> => {184 const final = fixable(Option.getOrElse(refusals, () => []));2 unmodified lines187 ? Option.some({ block: true, reason: explain(final).join("\n") })188 : Option.none();189 };190 237-/**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- */191 const toActOn = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>192 Array.match(fixable(refusals), {193 onEmpty: () => refusals,194 onNonEmpty: (final) => final,195 });196 248-/** The session a handler runs in. */197 const sessionOf = (ctx: PiContext): PiSession => ({198 cwd: ctx.cwd,199 id: ctx.sessionManager.getSessionId(),200 });201 254-/** A failure's first line, for the note. */202 const firstLine = (cause: Cause.Cause<unknown>) =>203 String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";204 258-/**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. */206 const reply = <A>(207 ctx: PiContext,208 event: keyof PiHandlers,209 decided: Effect.Effect<Option.Option<A>, HookFailed>14 unmodified lines224 Effect.map(Option.getOrUndefined)225 )226 );227 286-/**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- */228 export 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>();234 298- // 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);238 239 return reply(29 unmodified lines269 })270 )271 );272 337- // 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 lines299 );300 });301 };302 371-// ------------------------------------------------------------ live372-373-/**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- */303 const factsOf = (session: PiSession, look: boolean) =>304 Effect.gen(function* () {305 const kept = yield* loadSession(session.id);306 8 unmodified lines315 316 return gathered;317 });318 396-/**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. */320 const hookFacts = (321 state: SessionState,322 refusals: readonly Refusal[]323 ): HookFacts => ({3 unmodified lines327 refusals,328 root: state.root,329 });330 411-/** The policy's input for `event`, in the hook format it reads. */331 const hookInput = (event: HookEvent, session: PiSession): HookInput => ({332 cwd: session.cwd,333 hook_event_name: claudeEventOf[event],334 session_id: session.id,335 });336 418-/**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- */337 const 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 );343 430-/** What the hook policy runs on. */344 export type PolicyServices =345 | ChildProcessSpawner.ChildProcessSpawner346 | Client347 | FileSystem.FileSystem348 | Path.Path349 | PushCheck;350 438-/** The hook policy, in process, as `PiDeps`, over `services`. */351 export const policyDeps = (services: Layer.Layer<PolicyServices>): PiDeps => ({352 brief: (session) =>353 Effect.gen(function* () {354 const state = yield* factsOf(session, true);24 unmodified lines379 (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 lines413 hookInput("stop", session),414 hookFacts(state, refusals)415 );416 507- // 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 lines423 Effect.provide(services)424 ),425 });426 518-/**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- */427 const 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 );434 532-/** The hook policy as pi's process runs it. */435 export const livePiDeps = policyDeps(LiveServices);436 535-/** What `pi install npm:<package>` loads: the adapter over the live policy. */437 export 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- */1 import { detectHarness } from "@repo/protocol/audit";2 import { ConfigProvider, Context, Effect, Layer, Option, Stdio } from "effect";3 10-/** Who is reading: a person at a terminal, an agent, or a script. */4 export type Mode = "human" | "agent" | "automation";5 13-/** Who is reading, the harness when an agent is, and why the CLI thinks so. */6 export interface Invocation {7 readonly mode: Mode;8 readonly harness: Option.Option<string>;9 readonly reason: string;10 }11 20-/** What the mode is read from. */12 export interface Surroundings {13 readonly env: Readonly<Record<string, string | undefined>>;14 readonly isTTY: boolean;15 }16 26-/** `value`, unless it is absent or empty. */17 const isSet = (value: string | undefined) =>18 value !== undefined && value !== "";19 30-/**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- */20 export const detectMode = ({ env, isTTY }: Surroundings): Invocation => {21 const harness = Option.fromNullishOr(detectHarness(env).harness);22 23 if (Option.isSome(harness)) {12 unmodified lines36 ? { harness, mode: "human", reason: "stdout is a terminal" }37 : { harness, mode: "automation", reason: "stdout is not a terminal" };38 };39 55-/** Who is reading this process's output. */40 export class Policy extends Context.Service<Policy, Invocation>()(41 "cli/Policy"42 ) {}43 60-/** The policy for given surroundings: what tests run the CLI under. */44 export const policyFor = (surroundings: Surroundings): Layer.Layer<Policy> =>45 Layer.succeed(Policy)(detectMode(surroundings));46 64-/** The names below a node of the env's tree: a record's keys, an array's indexes. */47 const childrenOf = (node: ConfigProvider.Node): readonly string[] => {48 if ("keys" in node) {49 return [...node.keys];50 }4 unmodified lines55 56 return [];57 };58 77-/**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. */60 const envOf = (provider: ConfigProvider.ConfigProvider) => {61 const walk = (62 path: readonly string[]63 ): Effect.Effect<18 unmodified lines82 83 return Effect.map(walk([]), (entries) => Object.fromEntries(entries));84 };85 107-/**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. */87 export const CurrentMode: Layer.Layer<Policy, never, Stdio.Stdio> =88 Layer.effect(Policy)(89 Effect.gen(function* () {90 const provider = yield* ConfigProvider.ConfigProvider;10 unmodified linesmodified: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.2 import { Brand } from "@repo/brand";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import { Authenticated, Unauthenticated } from "@repo/protocol/principal";5 import {19 unmodified lines25 } from "effect/rpc";26 27 import { Credentials } from "./credentials.ts";28 34-/** `<SLUG>_URL`: a platform to call as anyone, when no profile names one. */29 const URL_VARIABLE = `${Brand.slug.toUpperCase()}_URL`;30 37-/**38- * No profile names a platform, and the env names none either. A usage39- * error: nothing was called.40- */31 export class NoPlatform extends Schema.TaggedError<NoPlatform>()("NoPlatform", {32 variable: Schema.String,33 }) {34 override get message() {8 unmodified lines43 const isNoPlatformError = Schema.is(NoPlatform);44 45 const isHttpFailure = Schema.is(HttpClientError.HttpClientErrorSchema);46 57-/** Whether a call failed in transit (not by the contract's own errors). */47 export const isTransportFailure = isClientError;48 60-/**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. */50 export 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;56 71-/** The usage error a call failed with because no platform was there to call. */57 export 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();63 79-/** Whether the platform's HTTP gate answered a call with a 401. */64 const isUnauthorized = (failure: RpcClientError.RpcClientError) =>65 Predicate.hasProperty(failure.reason, "cause") &&66 failure.reason.cause instanceof HttpClientError.StatusCodeError &&67 failure.reason.cause.response.status === 401;68 85-/**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. */70 const SignedIn = RpcMiddleware.layerClient(Authenticated, ({ next, request }) =>71 next(request).pipe(72 Effect.catchIf(73 (failure) => isClientError(failure) && isUnauthorized(failure),1 unmodified line75 )76 )77 );78 99-/** The contracts at `origin`, with `token` as the bearer when there is one. */79 const 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 lines110 );111 112 const noPlatform = new NoPlatform({ variable: URL_VARIABLE });113 135-/**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- */114 const nowhere = Layer.effect(Client)(RpcClient.make(Contracts)).pipe(115 Layer.provide(116 Layer.effect(RpcClient.Protocol)(117 Effect.flatMap(20 unmodified lines138 ),139 Layer.provide(RpcSerialization.layerJson)140 );141 167-/**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- */142 export const RemoteClient: Layer.Layer<Client, never, Credentials> =143 Layer.unwrap(144 Effect.gen(function* () {145 const profile = yield* Effect.flatMap(18 unmodified linesmodified: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- */1 import { IMPORTED_NOTE } from "@repo/agent-kit/docs/imported-note";2 import { Brand } from "@repo/brand";3 import type { View } from "@repo/protocol/cli";4 import {32 unmodified lines37 const when = (at: DateTime.Utc) => DateTime.formatIso(at);38 39 const yesNo = (value: boolean) => (value ? "yes" : "no");40 46-/** A cell's text, safe inside a Markdown table row. */41 const cell = (text: string) =>42 text.replaceAll("|", "\\|").replaceAll(/\s*\n\s*/gu, " ");43 50-/** `text` as a Markdown code span, fenced by one more backtick than its longest run. */44 const codeSpan = (text: string) => {45 const longest = Math.max(46 0,47 ...(text.match(/`+/gu) ?? []).map((run) => run.length)4 unmodified lines52 53 return `${fence}${pad}${text}${pad}${fence}`;54 };55 63-/**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. */57 const table = (58 headers: readonly string[],59 rows: readonly (readonly string[])[],60 empty: string,32 unmodified lines93 ].join("\n"),94 };95 };96 109-/** Labelled values, one a line: a Markdown list, and padded for a person. */97 const fields = (rows: readonly (readonly [string, string])[]): View => {98 const width = Math.max(0, ...rows.map(([label]) => label.length));99 100 return {3 unmodified lines104 .join("\n"),105 };106 };107 121-/** Views one after another, as sections. */108 const 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 });112 127-/** The same words for every reader. */113 const prose = (text: string): View => ({ markdown: text });114 130-/** Where an answer stands, in a few words. */115 const 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 lines122 `refused: ${refusals.map((refusal) => refusal._tag).join(", ")}`,123 WaitingOnParent: ({ ask }) => `passed; waits for ${ask} to land`,124 });125 142-/** What a decision is about, in a few words. */126 const subjectText = (subject: DecisionSubject) =>127 DecisionSubject.match(subject, {128 Finish: ({ ask, head }) => `finish the answer to ${ask} at ${short(head)}`,129 OpenProposal: ({ proposal }) =>11 unmodified lines141 Waiver: ({ at, marker, reason }) =>142 `allow ${marker} at ${at.path}:${at.line} ("${reason}")`,143 });144 162-/** One ledger entry, in a few words. */145 const 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 lines158 `${by} released ${paths} paths from ${layer} in ${short(landing)}`,159 ValueSet: ({ by, key }) => `${by} set the write-only value of ${key}`,160 });161 180-/** A view that renders a success it can read, and none for anything else. */162 const viewOf = <S extends Schema.Top>(163 schema: S,164 render: (success: S["Type"]) => View165 ) => {150 unmodified lines316 317 const plural = (count: number, one: string, many: string) =>318 `${count} ${count === 1 ? one : many}`;319 339-/** How many a vouch file names, as the people page says none: "nobody". */320 const countOf = (count: number) => (count === 0 ? "nobody" : `${count}`);321 322 const HOUR_MS = 3_600_000;323 344-/** A claim timing as the people page says it: whole hours up to two days, then days. */324 const spanOf = (ms: number) => {325 if (ms % HOUR_MS !== 0) {326 return plural(Math.round(ms / 60_000), "minute", "minutes");327 }4 unmodified lines332 ? plural(hours / 24, "day", "days")333 : plural(hours, "hour", "hours");334 };335 357-/** The config folder's `project.ts`. */336 const PROJECT_FILE = `${Brand.configDir}/project.ts`;337 360-/** What a vouch gates, in the people page's words. */338 const 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>;345 369-/** A policy at its landed commit, section by section, as the people page shows it. */346 const 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 lines399 )400 );401 };402 427-/**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>`. */404 const pendingText = ({ at, reason }: PolicyPending) => {405 const notEvaluated = `The config at the landed commit ${short(at)} has not been evaluated`;406 407 return reason === "noConfig"6 unmodified lines414 `Fix it by landing a change to ${Brand.configDir}/; it is evaluated again at every landing.`,415 ];416 };417 446-/** Where an imported project came from, and what a copy is (ADR 0031). */418 const importedText = ({ branch, url }: ImportSource) =>419 prose(420 `Imported from ${url}${branch === undefined ? "" : ` (branch ${branch})`}: this project is ${IMPORTED_NOTE}.`421 );422 452-/** The policy's own view: evaluated, why not yet, or nothing landed. */423 const policyText = (read: typeof PolicyOf.successSchema.Type): View => {424 if (read.policy !== undefined) {425 return evaluated(read.policy);426 }69 unmodified lines496 "No open asks anywhere."497 )498 );499 530-/**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- */500 const receipt = (offered: AnswerReceipt) =>501 prose(502 Result.getOrElse(receiptLine(offered), () => `${offered.ask} was refused`)503 );1 unmodified line505 const submitted = viewOf(SubmitAnswer.successSchema, receipt);506 507 const finished = viewOf(Finish.successSchema, receipt);508 544-/** Any receipt: an answer's (`submit`, `finish`) has a landing's fields too. */509 const isReceipt = Schema.is(LandReceipt);510 547-/**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. */512 export const refusalsIn = (513 success: Rpc.Success<Contract>514 ): readonly Refusal[] =>515 isReceipt(success) && Outcome.guards.Refused(success.outcome)516 ? success.outcome.refusals517 : [];518 560-/** Each contract's view, by tag. */519 export const views = {520 claim,521 credits,522 finish: finished,18 unmodified linesmodified: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- */1 import { AskId, Handle, LayerName, ProjectName } from "@repo/protocol/ids";2 import { Array, Effect, Option, Schema, Stream } from "effect";3 import { ChildProcess, ChildProcessSpawner } from "effect/process";4 5 import { Credentials } from "./credentials.ts";6 12-/** What a repo is: a project's own, a claim's fork, a person's working fork, or a layer's. */7 export type RepoKind = "canonical" | "claim" | "working" | "layer";8 15-/** What a repo's name says, part by part. */9 export 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 }16 17 const asProject = Schema.decodeOption(ProjectName);1 unmodified line19 const asAsk = Schema.decodeOption(AskId);20 21 const asLayer = Schema.decodeOption(LayerName);22 33-/** A handle as a fork's name spells it: valid, and in lowercase. */23 const asForkHandle = (part: string) =>24 Option.filter(25 Schema.decodeOption(Handle)(part),26 (handle) => handle === handle.toLowerCase()27 );28 40-/** The word a working fork has where a claim's fork has its ask. */29 const WORKING = "me";30 43-/** What a three-part name `<project>--<second>--<third>` is. */31 const forkOf = (32 project: ProjectName,33 second: string,34 third: string8 unmodified lines43 Option.all({ ask: asAsk(second), handle: asForkHandle(third) }),44 ({ ask, handle }): RepoRef => ({ ask, handle, kind: "claim", project })45 );46 60-/**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. */48 export 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 lines70 };71 72 const asUrl = Option.liftThrowable((url: string) => new URL(url));73 93-/** `url`'s scheme and host, if it is an HTTP(S) url. */74 const webOrigin = (url: string) =>75 Option.map(76 Option.filter(asUrl(url), ({ protocol }) =>77 ["http:", "https:"].includes(protocol)3 unmodified lines81 pathname,82 })83 );84 105-/**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- */85 export const parseRemote = (86 url: string87 ): Option.Option<{ readonly origin: string; readonly repo: string }> =>88 Option.flatMap(webOrigin(url), ({ origin, pathname }) => {6 unmodified lines95 ? Option.some({ origin, repo })96 : Option.none();97 });98 124-/** Where the CLI stands, as git sees it. */99 export 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 }108 139-/** `cwd` is in no git work tree. */109 export class NotARepo extends Schema.TaggedError<NotARepo>()("NotARepo", {110 cwd: Schema.String,111 }) {112 override get message() {3 unmodified lines116 117 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>118 bytes.pipe(Stream.decodeText(), Stream.mkString);119 151-/** Runs git in `cwd` to the end: its stdout and exit code; stderr is dropped. */120 const git = (cwd: string, args: readonly string[]) =>121 Effect.scoped(122 Effect.gen(function* () {123 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;14 unmodified lines138 return { exitCode, stdout };139 })140 );141 174-/** `git remote -v`'s fetch urls, by remote, in git's order. */142 const remotesOf = (listing: string) =>143 listing.split("\n").flatMap((line) => {144 const match = /^(?<name>\S+)\t(?<url>\S+) \(fetch\)$/u.exec(line);145 1 unmodified line147 ? []148 : [{ name: match.groups.name, url: match.groups.url }];149 });150 184-/**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- */151 export const repoContext = (152 cwd: string153 ): Effect.Effect<154 RepoContext,42 unmodified linesmodified: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- */1 import { commandDocs } from "@repo/agent-kit/command-doc";2 import { platformSkill } from "@repo/agent-kit/platform";3 import { Brand } from "@repo/brand";4 import { commandName, toCommands } from "@repo/protocol/cli";32 unmodified lines37 import { repoContext } from "./repo-context.ts";38 import { today } from "./tui/command.ts";39 import { cliVersion } from "./version.ts";40 47-/** The folder the CLI stands in: the process's own, unless a test says otherwise. */41 export const WorkingDirectory = Context.Reference<string>(42 "cli/WorkingDirectory",43 { defaultValue: () => "." }44 );45 53-/**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- */46 export const fromRepoContext: Defaults<ChildProcessSpawner.ChildProcessSpawner> =47 {48 fields: { project: "the project of the repo you stand in" },49 values: Effect.gen(function* () {8 unmodified lines58 );59 }),60 };61 74-/** A command, and the words after the CLI's name that reach it. */62 export interface CommandEntry {63 readonly path: readonly [string, ...string[]];64 readonly command: Command.Command.Any;65 }66 80-/**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. */68 const wrapped = ["initProject", "setEnv", "today"];69 88-/** Every contract served on the CLI, but those wrapped, as a command. */70 const projected = toCommands(Contracts, Effect.service(Client), {71 defaults: fromRepoContext,72 exclude: wrapped,73 output: Effect.service(Output),74 refusalsIn,75 views,76 });77 97-/** What a group of commands that is no command itself is for, by its word. */78 const groups = new Map([79 ["env", "Read a project's env shape, or set a write-only value."],80 ]);81 102-/**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- */82 export const merge = (83 all: readonly CommandEntry[]84 ): readonly Command.Command.Any[] => {85 const words = [...new Set(all.map(({ path: [word] }) => word))];21 unmodified lines107 return Command.withSubcommands(parent, merge(below));108 });109 };110 137-/** A command's words, as `schema` and its errors print them. */111 const spoken = (words: readonly string[]) => words.join(" ");112 140-/** `schema` was asked for a command that takes no payload, or none at all. */113 export class UnknownCommand extends Schema.TaggedError<UnknownCommand>()(114 "UnknownCommand",115 { words: Schema.String }116 ) {1 unmodified line118 return `${Brand.cli} has no command "${this.words}" that takes a payload; run ${Brand.cli} --help to list them`;119 }120 }121 150-/**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- */122 const 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 );129 162-/** Whether a field's value is write-only: a `Redacted` on the decoded side. */130 const isWriteOnly = (ast: SchemaAST.AST) =>131 SchemaAST.resolveAt<{ readonly id?: unknown }>("representation")(132 SchemaAST.toType(ast)133 )?.id === "effect/schema/Redacted";2 unmodified lines136 "Write-only: the platform keeps it and never returns or prints it, and no MCP tool takes it.";137 138 const decodeJson = Schema.decodeUnknownEffect(Schema.Json);139 173-/**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- */140 export const payloadJsonSchema = (rpc: CommandRpc) => {141 const payload = rpc.payloadSchema;142 143 const { definitions, schemas } =31 unmodified lines175 176 return decodeJson(document).pipe(Effect.orDie);177 };178 217-/** `schema <command…>`: the payload a command sends, as JSON Schema. */179 export const schema = Command.make(180 "schema",181 {182 json: Flag.Boolean("json").pipe(31 unmodified lines214 "Print the JSON Schema of the payload a command sends."215 )216 );217 257-/** Every command the CLI has, projected or hand-written, by its path. */218 export const entries: readonly CommandEntry[] = [219 ...projected,220 ...local,221 { command: schema, path: ["schema"] },222 { command: today, path: ["today"] },223 ];224 265-/** Any command in the tree: what it may fail with, and what it needs. */225 type Every =226 | (typeof projected)[number]["command"]227 | (typeof local)[number]["command"]228 | typeof schema229 | typeof today;230 272-/**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. */232 export type TreeCommand = Command.Command<233 string,234 never,235 unknown,236 Command.Error<Every>,237 Command.Services<Every>238 >;239 284-/** The CLI's commands at the top, merged by path. */240 export const commands: readonly TreeCommand[] = merge(entries);241 242 const projection = toToolkit(surfaced("mcp"), Effect.service(Client));243 289-/**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- */244 const skill = skillIn(platformSkill({ commands: commandDocs(Contracts) }));245 295-/**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- */246 const server = (made: Skill) =>247 Layer.mergeAll(248 McpServer.toolkit(projection.toolkit).pipe(249 Layer.provideMerge(projection.layer)15 unmodified lines265 })266 )267 );268 324-/**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`. */270 export 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 linemodified: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.3 4 declare 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 }9 25-/** The CLI's version as its build stamped it; `0.0.0` in a run no build stamped. */10 export 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 lines66 project,67 } from "./fixture.ts";68 import type { CheckRepo } from "./fixture.ts";69 70-/** A platform that says the caller holds no claims anywhere, and answers nothing else. */70 const noClaims = Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(71 Layer.provide([72 Layer.mergeAll(73 unanswered,10 unmodified lines84 );85 86 const claimView = Schema.decodeUnknownSync(ClaimView);87 89-/**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- */88 const claimedAt = (base: string) =>89 Layer.effect(Client)(RpcTest.makeClient(Contracts)).pipe(90 Layer.provide([91 Layer.mergeAll(23 unmodified lines115 asTester,116 ])117 );118 124-/** A platform no offline run may call. */119 const unreachable = Layer.mock(Client)({});120 127-/** What `check` runs with: a test console, plain output, real processes. */121 const services = (client: Layer.Layer<Client>) =>122 Layer.mergeAll(123 TestConsole.layer,124 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),1 unmodified line126 OutputPlain,127 SignedOut128 ).pipe(Layer.provideMerge(NodeServices.layer));129 137-/** Runs the CLI on `argv`: how it ended, and what it printed where. */130 const run = (argv: readonly string[]) =>131 Effect.gen(function* () {132 const exit = yield* Effect.exit(program(argv));133 3 unmodified lines137 out: (yield* TestConsole.logLines).map(String),138 };139 });140 149-/** The code a run's process ends with: 0 for a success. */141 const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>142 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));143 144 const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));145 155-/** The one document `--json` printed on stdout. */146 const envelopeOf = (out: readonly string[]) =>147 Effect.gen(function* () {148 expect(out).toHaveLength(1);149 3 unmodified lines153 const decodeEnvelope = Schema.decodeEffect(154 Schema.fromJsonString(Envelope(Schema.Unknown))155 );156 167-/** The one document `--json` printed on stdout, read as the envelope it is. */157 const decodedOf = (out: readonly string[]) =>158 Effect.gen(function* () {159 expect(out).toHaveLength(1);160 1 unmodified line162 });163 164 const encodeRefusals = Schema.encodeEffect(Schema.Array(Refusal));165 177-/** A `Fetch` for a host that reaches nothing over the network. */166 const offline = Layer.succeed(Fetch)({167 fetch: (request) =>168 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),169 });170 183-/**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- */171 const gateSays = (repo: CheckRepo, head: string) =>172 Effect.gen(function* () {173 const fs = yield* FileSystem.FileSystem;174 const path = yield* Path.Path;90 unmodified lines265 266 return { encoded: yield* encodeRefusals(refusals), refusals };267 });268 288-/**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- */269 const stateOf = (root: string) =>270 Effect.gen(function* () {271 const fs = yield* FileSystem.FileSystem;272 const path = yield* Path.Path;8 unmodified lines281 worktrees: yield* gitOk(root, "worktree", "list", "--porcelain"),282 };283 });284 308-/**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`.286 const inHook = (root: string) =>287 Effect.acquireRelease(288 Effect.sync(() => {289 vi.stubEnv("GIT_DIR", `${root}/.git`);2 unmodified lines292 }),293 () => Effect.sync(() => vi.unstubAllEnvs())294 );295 323-/** The ratchet the projects below declare, and the rule it counts. */296 const ratchet = "no-explicit-any";297 326-/**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- */298 const 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 lines304 "exit 1",305 "",306 ].join("\n");307 340-/**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- */308 const declaringRatchet = (repo: CheckRepo, command: string) =>309 Effect.gen(function* () {310 const sdk = `${Brand.cliPackage}/rules`;311 31 unmodified lines343 "Count explicit anys"344 );345 });346 384-/** An answer on a branch of its own from main that types a third value in a as `any`. */347 const raisingInA = (repo: CheckRepo) =>348 Effect.gen(function* () {349 yield* gitOk(repo.root, "checkout", "--quiet", "-b", "raising", "main");350 263 unmodified lines614 () =>615 Effect.gen(function* () {616 const repo = yield* aCheckRepo;617 656- // What the gateway says of the answer pushed onto the claim's base.618 const expected = yield* gateSays(repo, repo.straying);619 620 // 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 lines694 "--offline",695 "--json",696 ]).pipe(Effect.provide(services(unreachable)));697 737- // 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 linesmodified:apps/cli/test/local/credential-helper.test.ts+1 added-19 removed
33 unmodified lines34 import type { Profile } from "../../src/credentials.ts";35 import { program } from "../../src/main.ts";36 import { OutputPlain } from "../../src/output.ts";37 38-/** The env names the CLI reads, spelled from the brand. */38 const SLUG = Brand.slug.toUpperCase();39 40 const token = "t0ken-0123456789abcdefghijklmnopqrstuvwxyz";41 1 unmodified line43 token: Redacted.make(token),44 url: "https://platform.test",45 };46 48-/** What git writes to its helper for a repo on `host`, blank line and all. */47 const asked = (host: string, protocol = "https") =>48 `protocol=${protocol}\nhost=${host}\npath=datekit--fix-week--alice.git\n\n`;49 52-/** A pi session's env, as pi hands it to the git it runs. */50 const pi = { AI_AGENT: "pi", PI_MODEL: "kimi-k3" };51 52 const encoder = new TextEncoder();53 54 const decoder = new TextDecoder();55 59-/** The credentials file in the config dir `env` names. */56 const credentialsIn = (env: Record<string, string>) =>57 CredentialsFile.pipe(58 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))59 );60 65-/**66- * A fresh config dir holding `profiles`, and the env that names it: the67- * shell a person who ran `login` would give git.68- */61 const storedIn = (profiles: Readonly<Record<string, Profile>>) =>62 Effect.gen(function* () {63 const fs = yield* FileSystem.FileSystem;64 const dir = yield* fs.makeTempDirectoryScoped();10 unmodified lines75 76 return env;77 });78 87-/** A terminal that no helper may touch: every use of it dies. */79 const noTerminal = Layer.succeed(80 Terminal.Terminal,81 Terminal.make({82 columns: Effect.die("the helper read the terminal's width"),3 unmodified lines86 rows: Effect.die("the helper read the terminal's height"),87 })88 );89 99-/**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- */90 const helper = (91 op: string,92 stdin: Stream.Stream<Uint8Array>,93 env: Record<string, string>35 unmodified lines129 130 return { ok: Exit.isSuccess(exit), stderr, stdout };131 }).pipe(Effect.provide(TestConsole.layer));132 146-/** `text` as stdin that ends after it. */133 const input = (text: string) => Stream.make(encoder.encode(text));134 135 describe(`${Brand.cli} credential, git's credential helper`, () => {136 it.live(199 unmodified lines336 const Basic = /^Basic (?<encoded>\S+)$/u;337 338 const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);339 354-/**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- */341 const guarded = (root: string) =>342 Effect.gen(function* () {343 const spawner =344 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();135 unmodified linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { expect, layer } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import { CheckJob } from "@repo/checks/check-runner";47 unmodified lines52 import { OutputLive } from "../../src/output.ts";53 import { policyFor } from "../../src/policy.ts";54 import { RemoteClient } from "../../src/remote.ts";55 75-/** The world, from the repo root: the platform's Node world, cartridge composed. */56 const WORLD = "apps/platform/test/visibility/serve-cartridge-world.ts";57 58 const project = ProjectName.make("ines-v/datekit");59 60 const token = EnvKey.make("SENTRY_AUTH_TOKEN");61 82-/** What ines-v pipes in: a token of 24 characters, then the newline `echo` adds. */62 const value = "sk_test_0123456789abcdef";63 85-/** A value of 8 characters, under the 12 a value needs. */64+// Under the 12 characters a value needs.65 const short = "tooshort";66 88-/** The ask ines-v opens and bram answers: one of datekit's own. */67 const ask = AskId.make("parse-iso-week");68 69 interface Person {70 readonly handle: Handle;93- /** Their platform token, as the world's sessions list it. */71 readonly token: string;72 }73 74 const ines: Person = {5 unmodified lines80 handle: Handle.make("bram"),81 token: "bram-env-set-live-token-0123456789abcdefgh",82 };83 107-/** Whether datekit's first commit carries a tracked file: the library before anyone asked. */84 const seeded = (file: string) =>85 [86 ".env.schema",87 `${Brand.configDir}/project.ts`,3 unmodified lines91 ].includes(file) ||92 /^src\/[^/]+\.ts$/u.test(file) ||93 /^test\/[^/]+\.test\.ts$/u.test(file);94 119-/** The ask's file and the check it names, as datekit commits them. */95 const askFiles = [96 `${Brand.configDir}/asks/${ask}.ask.ts`,97 `test/asks/${ask}.test.ts`,98 ] as const;99 125-// --------------------------------------------------------------- the world126-100 const Serving = Schema.fromJsonString(101 Schema.Struct({ kept: Schema.String, origin: Schema.String })102 );103 104 const decodeServing = Schema.decodeUnknownOption(Serving);105 133-/** Where the world serves: the platform, and the test's window on what it kept. */106 interface 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 }111 141-/**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.113 const servedWorld = (root: string) =>114 Effect.gen(function* () {115 const child = yield* spawn("bun", [WORLD], {116 cwd: root,45 unmodified lines162 163 return { ...where, printed: Ref.get(printed) } satisfies Served;164 });165 200-/** What the world's `kept` window gives: each part as the world encoded it. */166 const Kept = Schema.fromJsonString(167 Schema.Struct({168 bodies: Schema.Array(Schema.String),169 jobs: Schema.Array(Schema.Unknown),14 unmodified lines184 ),185 })186 );187 223-/** What the world kept for datekit. */188 const keptBy = (world: Served) =>189 Effect.gen(function* () {190 const http = yield* HttpClient.HttpClient;191 const response = yield* http.get(`${world.kept}/kept?project=${project}`);192 193 return yield* Schema.decodeEffect(Kept)(yield* response.text);194 }).pipe(Effect.orDie);195 232-/** Carries every answer run the world has queued. */196 const settle = (world: Served) =>197 Effect.gen(function* () {198 const http = yield* HttpClient.HttpClient;199 const response = yield* http.post(`${world.kept}/settle`);14 unmodified lines214 }),215 })216 );217 255-/** The names of the tools the world's `/mcp` lists to `as`. */218 const toolsListed = (world: Served, as: Person) =>219 Effect.gen(function* () {220 const http = yield* HttpClient.HttpClient;221 40 unmodified lines262 263 return result.tools.map(({ name }) => name);264 }).pipe(Effect.orDie);265 304-// ----------------------------------------------------------------- people305-306-/** Credentials holding `as`'s profile on the world, as `login` would have stored it. */266 const signedIn = (world: Served, as: Person) =>267 Layer.succeed(Credentials)({268 current: Effect.succeedSome({269 handle: as.handle,4 unmodified lines274 put: () => Effect.die("the test stores no profile"),275 remove: () => Effect.die("the test removes no profile"),276 });277 319-/** The CLI's own client of the contracts, as `as`, for the steps the test sets up. */278 const 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 );283 326-/**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- */284 const gitOf = (helpers: string, as: Person) =>285 Effect.gen(function* () {286 const fs = yield* FileSystem.FileSystem;287 const helper = `${helpers}/${as.handle}`;18 unmodified lines306 run: (cwd: string, ...args: string[]) => git(cwd, ...helped, ...args),307 };308 });309 356-// -------------------------------------------------------------- the CLI357-358-/** What one run of the CLI did: its exit code, and what it printed and logged, by line. */310 interface Ran {311 readonly code: number;312 readonly out: readonly string[];313 readonly err: readonly string[];314 readonly logged: readonly string[];315 }316 366-/** A terminal that fails any prompt: nothing here may prompt. */317 const noPrompts = Layer.succeed(Terminal.Terminal)(318 Terminal.make({319 columns: Effect.succeed(80),320 display: () => Effect.die("the CLI prompted"),2 unmodified lines323 rows: Effect.succeed(24),324 })325 );326 377-/** How the process would exit, by the runtime's own rule. */327 const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>328 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));329 381-/** Each line of what a stream got, however it was written. */330 const linesOf = (chunks: readonly unknown[]) =>331 chunks.flatMap((chunk) => String(chunk).split("\n"));332 385-/**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- */333 const cli = (334 world: Served,335 as: Person,336 args: readonly string[],39 unmodified lines376 )377 );378 });379 437-// ------------------------------------------------------------ the scenario438-439-/** Everything the scenario did and the world kept, read by each test below. */380 class 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") {}396 463-/**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.398 const decodeJobs = Schema.decodeUnknownEffect(399 Schema.Array(Schema.Struct(CheckJob.fields))400 );401 471-/**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- */402 const ScenarioOnce = Layer.effect(403 Scenario,404 Effect.gen(function* () {405 const fs = yield* FileSystem.FileSystem;14 unmodified lines420 const bramGit = yield* gitOf(helpers, bram);421 const asInes = yield* clientOf(world, ines);422 const asBram = yield* clientOf(world, bram);423 499- // 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");426 427 const tracked = yield* gitOk(example, "ls-files", "--full-name", ".");16 unmodified lines444 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");447 525- // 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 lines480 project,481 "--json",482 ]);483 563- // 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 lines521 const before = (yield* keptBy(world)).jobs.length;522 523 yield* settle(world);524 606- // Last, what MCP lists, then everything the world kept and printed.525 const tools = yield* toolsListed(world, ines);526 const kept = yield* keptBy(world);527 528 return {11 unmodified lines540 };541 }).pipe(Effect.orDie)542 ).pipe(Layer.provide([NodeServices.layer, FetchHttpClient.layer]));543 626-// ------------------------------------------------------------------ tests627-544 const decodeEnvelope = <A extends Schema.Top>(data: A) =>545 Schema.decodeUnknownEffect(Schema.fromJsonString(Envelope(data)));546 631-/** What a `--json` run printed: its one envelope's data, as encoded, if it was not refused. */547 const 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 );552 638-/** A run's lines, less the empty ones a trailing newline leaves. */553 const filled = (lines: readonly string[]) =>554 lines.filter((line) => line.length > 0);555 642-/** Everything a run printed or logged, as one text. */556 const allOf = (ran: Ran) => [...ran.out, ...ran.err, ...ran.logged].join("\n");557 645-/**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.559 const base64At = (shift: number) => {560 const encoded = btoa(`${"\0".repeat(shift)}${value}`);561 562 return encoded.slice(1 unmodified line564 (shift + value.length) % 3 === 0 ? encoded.length : encoded.length - 4565 );566 };567 659-/**660- * The value, and what base64 or base64url leaves of it wherever it starts661- * inside an encoded text.662- */568 const forms = [569 value,570 ...[0, 1, 2]571 .map(base64At)572 .flatMap((form) => [form, form.replaceAll("+", "-").replaceAll("/", "_")]),573 ];574 670-/** Whether a text holds the value in any form. */575 const holds = (text: string) => forms.some((form) => text.includes(form));576 673-/** When the token was set, as the CLI printed it. */577 const setAtOf = (set: Ran) =>578 / at (?<at>\S+Z)\. /u.exec(filled(set.out)[0] ?? "")?.groups?.at;579 677-/** A ledger's entries as encoded: each one's fields, whatever they are. */580 const Entries = Schema.Struct({581 entries: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)),582 });583 682-/** The token's item in the env shape `env shape --json` printed, if it lists one. */584 const tokenItem = (envView: Ran) =>585 Effect.map(586 decodeEnvelope(EnvSchemaView)(envView.out.join("\n")).pipe(Effect.orDie),587 (printed) =>1 unmodified line589 ? printed.data.items.find(({ key }) => key === token)590 : undefined591 );592 692-/** What unlanded code sees in place of the token: its key, made a placeholder. */593 const placeholder = `__${token}_PLACEHOLDER__`;594 595 layer(ScenarioOnce, { excludeTestServices: true, timeout: "240 seconds" })(596 `${Brand.cli} env set against the platform's Node world, the visibility cartridge composed`,94 unmodified lines691 logged: 0,692 printed: false,693 });694 795- // 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 linesmodified:apps/cli/test/local/env-set.test.ts-20 removed
35 unmodified lines36 import { Output, OutputPlain } from "../../src/output.ts";37 import type { Mode } from "../../src/output.ts";38 import { SignedOut } from "../signed-out.ts";39 40-/** A value no output, note or log line may ever hold. */40 const secret = "sk_live_0123456789abcdef";41 42 const key = EnvKey.make("SENTRY_AUTH_TOKEN");43 44 const setAt = DateTime.makeUnsafe("2026-10-07T09:00:00Z");45 47-/** A person piping the value in, as `printf '…\n' |` does. */46 const piped = Stream.make(new TextEncoder().encode(`${secret}\n`));47 48 type Payload = Rpc.Payload<typeof SetEnv>;49 52-/** What the platform answers `setEnv` with. */50 type Answer = Effect.Effect<51 Rpc.Success<typeof SetEnv>,52 NotSensitive | ValueTooShort53 >;3 unmodified lines57 setAt,58 setBy: Handle.make("alice"),59 });60 64-/** One call through `Output`, as the command made it. */61 interface 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 }65 71-/**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- */66 interface Ran {67 readonly code: number;68 readonly out: string;69 readonly err: string;3 unmodified lines73 readonly shown: string;74 }75 76 interface 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 }83 95-/** How the process would exit, by the runtime's own rule. */84 const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>85 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));86 87 const press = (name: string, input: Option.Option<string>) => ({88 input,89 key: { ctrl: false, meta: false, name, shift: false },90 });91 104-/**105- * Runs `<cli> env set …` with `setup`'s stdin, terminal and platform, and106- * returns everything it printed, logged and asked.107- */92 const 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 lines98 99 const record = (method: Printed["method"], input: Printed["input"]) =>100 Ref.update(printed, (all) => [...all, { input, method }]);101 118- // 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 lines142 rows: Effect.succeed(24),143 })144 );145 163- // 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 lines191 shown: (yield* Ref.get(shown)).join(""),192 } satisfies Ran;193 }).pipe(Effect.provide(TestConsole.layer));194 213-/** Asserts the value reached no output, note, log line or terminal frame. */195 const neverShown = (ran: Ran) => {196 for (const seen of [197 ran.out,198 ran.err,9 unmodified lines208 const decodeEnvelope = Schema.decodeEffect(209 Schema.fromJsonString(Envelope(Schema.Unknown))210 );211 231-/** The one call the platform got, with its value opened for the check. */212 const onlyCall = (ran: Ran) => {213 expect(ran.calls).toHaveLength(1);214 215 const [call] = ran.calls;278 unmodified linesmodified:apps/cli/test/local/facts.test.ts-15 removed
38 unmodified lines39 initializer: Handle.make(handle),40 project: ProjectName.make(project),41 };42 43-/** The policy at `main`, with this CLI's own bundler for a TypeScript folder. */43 const policyAt = (root: string) =>44 localPolicy(root, "main", about).pipe(Effect.provide(ConfigBundlerBun));45 46 const pusher = Person.make({ handle: Handle.make(handle) });3 unmodified lines50 claimant: Handle.make(handle),51 project: ProjectName.make(project),52 });53 55-/** A `Fetch` for a host that reaches nothing over the network. */54 const offline = Layer.succeed(Fetch)({55 fetch: (request) =>56 Effect.fail(new FetchFailed({ reason: "offline", url: request.url })),57 });58 61-/**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- */59 const gitSays = (repo: CheckRepo, head: string) =>60 Effect.gen(function* () {61 const fs = yield* FileSystem.FileSystem;62 const path = yield* Path.Path;97 unmodified lines160 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))161 );162 });163 171-/**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- */164 const wideTree = {165 ".claude/settings.json": JSON.stringify({166 hooks: {167 PreToolUse: [229 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import { gitOk } from "@repo/testkit/git";3 import { Effect, FileSystem, Path } from "effect";4 14-/** The project, the ask and the person the fixture's remote names. */5 export const project = "alice/fixture";6 7 export const ask = "fix-a";8 9 export const handle = "alice";10 21-/** The platform the fixture's `origin` remote points at. */11 export const platform = "https://platform.example.dev";12 24-/** The claim's fork, as its remote names it: `<project>--<ask>--<handle>`. */13 const forkRemote = `${platform}/${project}--${ask}--${handle}.git`;14 27-/** The policy file, under the config folder. */15 export const policyFile = `${Brand.configDir}/policy.json`;16 30-/** The ask's check file: red on main, by its fourth line's assertion. */17 export const checkFile = "packages/a/test/a.test.ts";18 33-/** 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.20 export const policyText = Effect.gen(function* () {21 const fs = yield* FileSystem.FileSystem;22 const path = yield* Path.Path;23 13 unmodified lines37 'it("is two", () => expect(a).toBe(2));',38 "",39 ].join("\n");40 55-/** Main's files but the policy: the root manifest and both packages. */41 const onMain = {42 [checkFile]: testOnMain,43 "package.json":44 '{ "name": "fixture", "private": true, "workspaces": ["packages/*"] }\n',3 unmodified lines48 "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>>;51 67-/** The answer that strays: it edits `b`, skips a test at line 4, and fixes `a`. */52 const straying = {53 [checkFile]: testOnMain.replace(54 "it(",55 'it.skip("is one", () => expect(a).toBe(1));\nit('1 unmodified line57 "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>>;60 77-/** The answer that stays inside its territory: it fixes `a`, and only that. */61 const clean = {62 "packages/a/src/a.ts": "export const a = 2;\n",63 } as const satisfies Readonly<Record<string, string>>;64 82-/** The fixture's commits: `main`, and the two answers' heads. */65 export interface CheckRepo {66 readonly root: string;67 readonly main: string;68 readonly straying: string;12 unmodified lines81 yield* fs.writeFileString(at, content);82 }83 });84 103-/** Writes `files` in `root` and commits them all; the new commit's id. */85 export const commit = (86 root: string,87 files: Readonly<Record<string, string>>,88 message: string5 unmodified lines94 95 return yield* gitOk(root, "rev-parse", "HEAD");96 });97 117-/**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- */98 export const aCheckRepo = Effect.gen(function* () {99 const fs = yield* FileSystem.FileSystem;100 const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());101 19 unmodified linesmodified:apps/cli/test/local/init.test.ts-29 removed
31 unmodified lines32 import { program } from "../../src/main.ts";33 import { OutputPlain } from "../../src/output.ts";34 import { SignedOut } from "../signed-out.ts";35 36-/** Credentials for a run signed in as `handle`, whose profile `login` wrote. */36 const signedInAs = (handle: string) =>37 Layer.mock(Credentials)({38 current: Effect.succeedSome({39 handle: Handle.make(handle),22 unmodified lines62 " - run: bun run test",63 "",64 ].join("\n");65 67-/**68- * The config `init` proposes for the machine's repo: the commands its CI69- * and scripts run, each with where it was found.70- */66 const proposal = projectFile(67 {68 checks: Object.fromEntries(69 new Map([13 unmodified lines83 "checks.types from package.json",84 ]85 );86 92-/**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- */87 const 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 lines117 });118 119 type Machine = Effect.Success<typeof aMachine>;120 132-/**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- */121 const startedIn = (machine: Machine) =>122 Layer.effect(ChildProcessSpawner.ChildProcessSpawner)(123 Effect.gen(function* () {124 const real = yield* ChildProcessSpawner.ChildProcessSpawner;22 unmodified lines147 );148 })149 ).pipe(Layer.provide(NodeServices.layer));150 167-/**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- */151 const aPlatform = (152 reply: Effect.Effect<153 typeof InitProject.successSchema.Type,154 ProjectExists | ImportFailed16 unmodified lines171 ])172 ),173 }));174 196-/** The exit code the process would end with, as the runtime decides it. */175 const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>176 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));177 200-/** Runs `<cli> argv` on `machine` against `platform`: its exit code and what it printed. */178 const cli = (179 machine: Machine,180 platform: Layer.Layer<Client>,181 argv: readonly string[],26 unmodified lines208 const decodeEnvelope = Schema.decodeEffect(209 Schema.fromJsonString(Envelope(Schema.Unknown))210 );211 235-/** The one envelope `--json` printed. */212 const envelopeOf = (out: readonly string[]) =>213 Effect.gen(function* () {214 expect(out).toHaveLength(1);215 216 return yield* decodeEnvelope(out[0] ?? "");217 });218 243-/** What git says about the machine's repo and the platform's. */219 const state = (machine: Machine) =>220 Effect.gen(function* () {221 const fs = yield* FileSystem.FileSystem;222 const path = yield* Path.Path;18 unmodified lines241 remotes: yield* gitOk(machine.repo, "remote"),242 };243 });244 270-/** The platform made the project `demo`, served at the machine's bare repo. */245 const created = (machine: Machine) =>246 Effect.succeed({247 project: ProjectName.make("oscabriel/demo"),248 remote: machine.remote,570 unmodified lines819 const decodeCalls = Schema.decodeUnknownEffect(820 Schema.Array(Schema.Struct({ project: Schema.String }))821 );822 849-/** The project `init --import <url>` sends with `flags`, signed in as `handle`. */823 const importSends = (handle: string, url: string, flags: readonly string[]) =>824 Effect.gen(function* () {825 const machine = yield* aMachine;826 15 unmodified lines842 843 return calls.map(({ project }) => project);844 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));845 873-// 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.846 describe(`${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 linesmodified:apps/cli/test/local/login.test.ts-29 removed
38 unmodified lines39 import { program } from "../../src/main.ts";40 import { OutputPlain } from "../../src/output.ts";41 import { oauthServer } from "../oauth-server.ts";42 43-/** The env names the CLI reads, spelled from the brand. */43 const SLUG = Brand.slug.toUpperCase();44 45 const url = "https://platform.test";46 47 const given = "tok-given-0123456789abcdefghijklmnopqrstuvwxyz";48 49 const issued = "tok-issued-0123456789abcdefghijklmnopqrstuvwxyz";50 52-/** The three lines `login` sets in git's global config for `at`. */51 const 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 ];56 59-/** The same three, as the argv lists `--json` carries. */57 const 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 ];62 66-/** A temp HOME with its own global git config: a person's shell, for the CLI and git. */63 const home = Effect.gen(function* () {64 const fs = yield* FileSystem.FileSystem;65 const path = yield* Path.Path;66 const dir = yield* fs.makeTempDirectoryScoped();5 unmodified lines72 CredentialsFile.pipe(73 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))74 );75 80-/** The profile `name` as the file holds it: its url, handle and token. */76 const 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 lines86 }))87 )88 );89 95-/** `git config --global <args>` in `env`: its stdout and exit code. */90 const 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 lines107 );108 109 const isPerson = Schema.is(Person);110 117-/**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- */111 const 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 );118 130-/** A server side that refuses every credential, as for a revoked token. */119 const refusesEveryone = Layer.succeed(Authenticated, () =>120 Effect.fail(new Unauthenticated())121 );122 135-/**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- */123 const seams = (server: Layer.Layer<Authenticated>) =>124 Effect.gen(function* () {125 const connected = yield* Ref.make<126 readonly { token: string; url: string }[]40 unmodified lines167 opened: Ref.get(opened),168 };169 });170 189-/** A platform that takes the caller for `handle`. */171 const signedInAs = (handle: string) => asPerson(Handle.make(handle));172 192-/** What the tests themselves run on: a test console, and Node for files, git and servers. */173 const testServices = Layer.mergeAll(TestConsole.layer, NodeServices.layer);174 195-/** A terminal nothing may touch: every use of it dies. */175 const noTerminal = Layer.succeed(176 Terminal.Terminal,177 Terminal.make({178 columns: Effect.die("login read the terminal's width"),6 unmodified lines185 186 interface 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 }192 216-/** Runs `argv` as the CLI would, in `run`'s world; how it ended. */193 const cli = (argv: readonly string[], run: Run) =>194 Effect.exit(195 program(argv).pipe(196 Effect.provide(16 unmodified lines213 )214 )215 );216 241-/** What was printed, one entry per line however it was written. */217 const lines = (all: readonly unknown[]) =>218 all.flatMap((chunk) => String(chunk).split("\n"));219 245-/** Every line printed so far, on stdout and on stderr. */220 const printed = Effect.gen(function* () {221 return {222 stderr: lines(yield* TestConsole.errorLines),223 stdout: lines(yield* TestConsole.logLines),224 };225 });226 253-/** The sign-in URL `login` printed for `origin`, once it has. */227 const signInUrl = (origin: string) =>228 Effect.gen(function* () {229 for (let attempt = 0; attempt < 250; attempt += 1) {230 const line = (yield* printed).stderr9 unmodified lines240 241 return yield* Effect.die("login printed no sign-in URL");242 });243 271-/** GET `at` as a browser would, following redirects: the page's status. */244 const visit = (at: string) =>245 Effect.gen(function* () {246 const client = yield* HttpClient.HttpClient;247 const response = yield* client.get(at);248 249 return response.status;250 }).pipe(Effect.provide(FetchHttpClient.layer));251 280-/** The query `/authorize` was sent, field by field. */252 const fieldsOf = (query: URLSearchParams | undefined) =>253 Object.fromEntries(query?.entries() ?? []);254 255 describe(`${Brand.cli} login --token-stdin`, () => {515 unmodified linesmodified:apps/cli/test/local/project-file.test.ts-11 removed
4 unmodified lines5 import { ChildProcess, ChildProcessSpawner } from "effect/process";6 7 import { projectFile } from "../../src/local/project-file.ts";8 9-/**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- */9 const found = {10 run: {11 checks: Object.fromEntries(12 new Map([13 unmodified lines26 "checks.types from package.json",27 ],28 } as const;29 35-/** What the finder reads from a repo with scripts but no test runner it knows. */30 const noTest = {31 run: {32 checks: { lint: "npm run lint" },33 setup: "npm install",79 unmodified lines113 114 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>115 bytes.pipe(Stream.decodeText(), Stream.mkString);116 123-/**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- */117 const typeCheck = (files: Readonly<Record<string, string>>) =>118 Effect.scoped(119 Effect.gen(function* () {120 const fs = yield* FileSystem.FileSystem;98 unmodified linesmodified:apps/cli/test/local/stale.test.ts-8 removed
16 unmodified lines17 import { SignedOut } from "../signed-out.ts";18 import { aCheckRepo, handle, project } from "./fixture.ts";19 import type { CheckRepo } from "./fixture.ts";20 21-/** A platform no offline run may call. */21 const unreachable = Layer.mock(Client)({});22 23 const services = Layer.mergeAll(24 TestConsole.layer,2 unmodified lines27 OutputPlain,28 SignedOut29 ).pipe(Layer.provideMerge(NodeServices.layer));30 32-/** `check --offline --shape-only --json` in the repo: how it ended, and what it printed where. */31 const checked = (root: string) =>32 Effect.gen(function* () {33 const exit = yield* Effect.exit(34 program(["check", "--dir", root, "--offline", "--shape-only", "--json"])13 unmodified lines48 const name = ProjectName.make(project);49 50 const skill = `.agents/skills/${keyOf(ProjectName.make(project))}-contribute/SKILL.md`;51 54-/** The landing an older copy of the skill came from. */52 const older = LandedSha.make("a".repeat(40));53 57-/** The policy at the fixture's main, as `check` reads it. */54 const policyAtMain = (repo: CheckRepo) =>55 localPolicy(repo.root, "main", {56 initializer: Handle.make(handle),57 project: name,58 }).pipe(Effect.provide(ConfigBundlerBun));59 64-/** An older run block: one lane, `ok`, where main has two. */60 const olderRun = Schema.decodeSync(RunBlock)({61 checks: { ok: "true" },62 test: "true {path}",63 });64 70-/** The policy at main with the older run block. */65 const withOlderRun = (policy: Policy): Policy => ({ ...policy, run: olderRun });66 73-/** Writes `content` at `file` in the repo's work tree, leaving it uncommitted. */67 const 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 lines73 yield* fs.makeDirectory(path.dirname(at), { recursive: true });74 yield* fs.writeFileString(at, content);75 });76 84-/** The fixture with HEAD on its clean answer, which the shape stage passes. */77 const cleanRepo = Effect.gen(function* () {78 const repo = yield* aCheckRepo;79 80 yield* gitOk(repo.root, "checkout", "--quiet", "clean");143 unmodified linesmodified:apps/cli/test/local/why.test.ts-26 removed
50 unmodified lines51 const alice = Handle.make("alice");52 53 const carol = Handle.make("carol");54 55-/** The second commit's message: its trailers, as an answerer wrote them. */55 const 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");62 64-/**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- */63 const 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 lines87 88 return { dir, first, second };89 });90 96-/** What the platform was asked: each `landing` call's payload. */91 type Asked = readonly { readonly project: string; readonly sha: string }[];92 99-/** A record of `landing` calls, none yet. */93 const noCalls = Ref.make<Asked>([]);94 102-/** The platform's record of the second commit's landing. */95 const landingOf = (sha: CommitSha): LandingView => ({96 ask: AskId.make("fix-week"),97 assisted: [{ harness: "claude-code", verified: false }],98 author: alice,5 unmodified lines104 project,105 sha: LandedSha.make(sha),106 });107 116-/** The same landing as `--json` prints it. */108 const landingJson = (sha: string) => ({109 ask: "fix-week",110 assisted: [{ harness: "claude-code", verified: false }],111 author: "alice",5 unmodified lines117 project: "oscabriel/datekit",118 sha,119 });120 130-/**131- * The platform in process, answering `landing` with `answer` and every132- * other contract never: a test reaching one fails.133- */121 const platform = (122 answer: (payload: {123 readonly project: ProjectName;124 readonly sha: CommitSha;8 unmodified lines133 asTester,134 ])135 );136 150-/**151- * A platform that knows `landed` as a landing and no other commit, and152- * records every `landing` call it is asked.153- */137 const platformKnowing = (138 landed: Option.Option<CommitSha>,139 calls: Ref.Ref<Asked>140 ) =>6 unmodified lines147 )148 )149 );150 168-/**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- */151 const 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 });158 180-/** How the process would exit, by the runtime's own rule. */159 const exitCodeOf = (exit: Exit.Exit<unknown, unknown>) =>160 Exit.isSuccess(exit) ? 0 : Runtime.getErrorExitCode(Cause.squash(exit.cause));161 184-/**185- * Runs `<cli> why …` in `dir` against `client`, printing through `output`,186- * and returns its exit code, stdout and stderr.187- */162 const run = (163 dir: string,164 args: readonly string[],165 client: Layer.Layer<Client>,378 unmodified linesmodified: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- */1 import { RefNameText } from "@repo/protocol/domain/common";2 import { DecisionSubject } from "@repo/protocol/domain/decision";3 import type { Decision, Today } from "@repo/protocol/domain/decision";4 import {67 unmodified linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { createTestRenderer } from "@opentui/core/testing";4 import { createElement } from "@opentui/react";33 unmodified lines38 import { TodayView } from "../../src/tui/view.ts";39 import { runProgram } from "../remote-server.ts";40 import { datekit, okonkwo, proposal, stray, today, vouch } from "./fixture.ts";41 46-/** The state after `keys`, one after another, and every call they made. */42 const press = (state: TodayViewState, keys: readonly string[]) => {43 const calls: DecideCall[] = [];44 let now = state;45 65 unmodified lines111 expect(reduce(state, "down").quit).toBeFalsy();112 });113 });114 120-/**121- * The screen `TodayView` draws for `state` on a terminal `height` rows tall122- * (40 unless given), one string per row.123- */115 const screenOf = (state: TodayViewState, height = 40) =>116 Effect.acquireUseRelease(117 Effect.promise(() =>118 testRender(createElement(TodayView, { state }), { height, width: 120 })12 unmodified lines131 setup.renderer.destroy();132 })133 );134 144-/** The rows of a screen that hold `text`. */135 const rowsWith = (rows: readonly string[], text: string) =>136 rows.filter((row) => row.includes(text));137 138 describe("Today as the terminal shows it", () => {105 unmodified lines244 })245 );246 });247 258-/**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- */248 const surroundings = (input: {249 readonly env: Readonly<Record<string, string>>;250 readonly stdoutIsTTY: boolean;251 readonly stdinIsTTY: boolean;3 unmodified lines255 Stdio.layerTest({ stdinIsTerminal: Effect.succeed(input.stdinIsTTY) }),256 Layer.mock(Client)({})257 );258 273-/** What `runTodayTui` refused with, as its next command and its one line. */259 const refusalIn = (layer: ReturnType<typeof surroundings>) =>260 runTodayTui({ project: Option.none() }).pipe(261 Effect.flip,262 Effect.map((failure) =>75 unmodified lines338 })339 );340 });341 357-/**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.343 const 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 lines353 354 return { screen, shown };355 });356 377-/**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- */357 const platform = (closed: ReadonlySet<string>) =>358 Effect.gen(function* () {359 const decided = yield* Ref.make<360 readonly (typeof Decide.payloadSchema.Type)[]39 unmodified lines400 401 return { client, decided };402 });403 430-/** A person at a terminal, with the platform `client` and the screen `screen`. */404 const 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 lines504 );505 506 const screen = yield* screenOn(setup.renderer);507 535- /** 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 lines540 )541 );542 });543 572-/** What was printed to a stream, one entry per line however it was written. */544 const lines = (chunks: readonly unknown[]) =>545 chunks.flatMap((chunk) => String(chunk).split("\n"));546 576-/**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- */547 const projectedToday = toCommand(TodayOf, Effect.service(Client), {548 output: Effect.service(Output),549 refusalsIn,550 render: views.today,551 });552 587-/**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- */553 const runToday = (554 args: readonly string[],555 input: {556 readonly client: Layer.Layer<Client>;3 unmodified lines560 ) => {561 const policy = policyFor({ env: input.env, isTTY: true });562 563 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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Option } from "effect";3 4 import { npmMachineOf } from "../build-targets.ts";25 unmodified linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { expect, layer } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import {8 unmodified lines13 Stream,14 } from "effect";15 import { ChildProcess, ChildProcessSpawner } from "effect/process";16 23-/** How a process ended, and what it printed. */17 interface Ran {18 readonly exitCode: number;19 readonly stderr: string;20 readonly stdout: string;1 unmodified line22 23 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>24 bytes.pipe(Stream.decodeText(), Stream.mkString);25 33-/** The whole env a built binary runs with. */26 interface Bare {27 readonly HOME: string;28 readonly PATH: string;29 readonly XDG_CONFIG_HOME: string;30 }31 40-/**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- */32 const run = (33 command: string,34 args: readonly string[],35 options: {26 unmodified lines62 return { exitCode, stderr, stdout } satisfies Ran;63 })64 ).pipe(Effect.orDie);65 78-/**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- */66 const npmFiles = (dist: string) =>67 Effect.gen(function* () {68 const fs = yield* FileSystem.FileSystem;69 const path = yield* Path.Path;11 unmodified lines81 82 return files;83 });84 101-/** What `bun run build` did, where it wrote, and a bare env to run it in. */85 class 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 lines130 });131 })132 ).pipe(Layer.provideMerge(NodeServices.layer));133 156-/** The path of `segments` under `dist/`, once the test has seen the build write it. */134 const written = (...segments: readonly string[]) =>135 Effect.gen(function* () {136 const { dist } = yield* Built;137 const fs = yield* FileSystem.FileSystem;7 unmodified lines145 146 return file;147 });148 172-/** Long enough for a case that starts the built binaries a few times on a busy machine. */149 const spawning = { timeout: 60_000 };150 175-/** The start-here banner `--help` opens with (as `test/main.test.ts` holds it). */151 const 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 ];157 183-/** The banner as `--help` printed it, if it did: four lines from "Start here:". */158 const bannerIn = (stdout: string) => {159 const lines = stdout.split("\n").map((line) => line.trim());160 const start = lines.indexOf("Start here:");161 162 return start === -1 ? [] : lines.slice(start, start + banner.length);163 };164 191-/**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- */165 const exportedNames = (source: string) => {166 const listed = [167 ...source.matchAll(/\bexport\s+(?:type\s+)?\{(?<list>[^}]*)\}/gu),168 ]20 unmodified lines189 .filter((name) => name.length > 0)190 .toSorted();191 };192 224-/** What git hands a credential helper: the host, then a blank line. */193 const request = "protocol=https\nhost=example.test\n\n";194 227-/**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.197 const workspaceSpecifier =198 /(?:\b(?:from|import)\s*["']|\b(?:import|require)\s*\(\s*["'`])@repo\//u;199 200 layer(BuiltOnce, { excludeTestServices: true, timeout: "180 seconds" })(20 unmodified lines221 222 const binary = yield* fs.stat(yield* written("bin", Brand.cli));223 224 expect(binary.type).toBe("File");261- // The owner's execute bit.225 expect(Math.floor(binary.mode / 0o100) % 2).toBe(1);226 227 // A link, not a shim: the compiled binary sees the name it was228 // invoked by.129 unmodified lines358 const binary = yield* written("bin", Brand.cli);359 360 yield* written("bin", Brand.gitCredentialHelper);361 399- // 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 linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { commandDocs, contractCommandDocs } from "@repo/agent-kit/command-doc";4 import type { CommandDoc } from "@repo/agent-kit/command-doc";7 unmodified lines12 import { root } from "../src/main.ts";13 import { OutputPlain } from "../src/output.ts";14 import { SignedOut } from "./signed-out.ts";15 23-/** What a command's `--help` says it takes, as this test reads it. */16 const Takes = Schema.Struct({17 args: Schema.Array(18 Schema.Struct({ name: Schema.String, required: Schema.Boolean })19 ),11 unmodified lines31 const encodeTakes = Schema.encodeSync(Schema.fromJsonString(Takes));32 33 const decodeTakes = Schema.decodeSync(Schema.fromJsonString(Takes));34 43-/** The parts of a help page this test compares, as one JSON line. */35 const 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 lines43 });44 45 const plain = CliOutput.defaultFormatter({ colors: false });46 56-/** effect/cli's own formatter, but help prints what a command takes as JSON. */47 const 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 };54 65-/**66- * What the CLI runs with here: a test console, that formatter, and a client67- * and credentials `--help` never calls.68- */55 const services = Layer.mergeAll(56 TestConsole.layer,57 CliOutput.layer(formatter),58 Layer.mock(Client)({}),59 SignedOut,60 OutputPlain61 ).pipe(Layer.provideMerge(NodeServices.layer));62 77-/**78- * What the command at `path` takes, from its own `--help`; help that fails79- * to print fails the test.80- */63 const helpOf = (path: readonly string[]) =>64 Effect.gen(function* () {65 yield* Command.runWith(root, { version: "0.0.0" })([...path, "--help"]);66 8 unmodified lines75 readonly command: Command.Command.Any;76 readonly takes: Takes;77 }78 97-/** Every command under `command` in the tree, at any depth, with its help. */79 const below = (80 command: Command.Command.Any,81 path: readonly string[]82 ): Effect.Effect<readonly Node[]> =>7 unmodified lines90 return [node, ...(yield* below(sub, here))];91 })92 ).pipe(Effect.map((nodes) => nodes.flat()));93 113-/**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.95 const isRunnable = ({ command, takes }: Node) =>96 command.subcommands.length === 0 ||97 takes.args.length + takes.flags.length > 0;98 122-/** The CLI's runnable commands, by their words. */99 const runnable = below(root, []).pipe(100 Effect.map(101 (nodes) =>102 new Map(5 unmodified lines108 const rows: readonly CommandDoc[] = commandDocs(Contracts);109 110 const words = ({ path }: CommandDoc) => path.join(" ");111 136-/**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.113 const declared = (row: CommandDoc, takes: Takes) => {114 const names = new Set(takes.flags.map(({ name }) => name));115 116 const switches = new Set(9 unmodified lines126 })127 );128 };129 159-/** A payload's JSON Schema, as this test reads it: its fields and the required ones. */130 const PayloadFields = Schema.Struct({131 properties: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),132 required: Schema.optionalKey(Schema.Array(Schema.String)),133 });134 135 const decodePayloadFields = Schema.decodeUnknownSync(PayloadFields);136 167-/** The payload of the contract a contract row projects, as JSON Schema. */137 const payloadOf = (row: CommandDoc) => {138 const rpc = Contracts.requests.get(row.contract ?? "");139 140 return rpc === undefined2 unmodified lines143 };144 145 const isBoolean = Schema.is(Schema.Struct({ type: Schema.Literal("boolean") }));146 178-/** A boolean field is a switch, which the CLI never requires. */147 const isSwitch = (field: Schema.Json | undefined) =>148 field !== undefined && isBoolean(field);149 182-/**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- */150 const filledFromRepo = new Set(["project"]);151 152 describe("the command rows against the CLI", () => {153 it.effect(41 unmodified lines195 }),196 30_000197 );198 235- // 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 linesmodified:apps/cli/test/credentials.test.ts-5 removed
18 unmodified lines19 gitHelperConfig,20 } from "../src/credentials.ts";21 import type { Profile } from "../src/credentials.ts";22 23-/** The env names the CLI reads, spelled from the brand. */23 const SLUG = Brand.slug.toUpperCase();24 25 const token = "tok-default-0123456789abcdefghijklmnopqrstuvwxyz";26 8 unmodified lines35 token: Redacted.make("tok-alice-0123456789abcdefghijklmnopqrstuvwxyz"),36 url: "https://platform-demo.example.workers.dev",37 };38 40-/** A fresh config dir, and the env a shell would give the CLI with it. */39 const configHome = Effect.map(40 Effect.flatMap(FileSystem.FileSystem, (fs) => fs.makeTempDirectoryScoped()),41 (dir) => ({ dir, env: { HOME: "/nonexistent", XDG_CONFIG_HOME: dir } })42 );43 46-/** The `Credentials` the CLI would build in `env`. */44 const 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 );51 55-/** Each profile's url and handle, and the token's value: what a test compares. */52 const seen = (profile: Option.Option<Profile>) =>53 Option.map(profile, ({ handle, token: secret, url }) => ({54 handle,55 token: Redacted.value(secret),17 unmodified lines73 expect(yield* fs.exists(file)).toBeTruthy();74 75 const info = yield* fs.stat(file);76 81- // 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 linesmodified:apps/cli/test/hook.test.ts-40 removed
61 unmodified lines62 import { program } from "../src/main.ts";63 import { OutputPlain } from "../src/output.ts";64 import { SignedOut } from "./signed-out.ts";65 66-/** The repo's top folder, as the session found it. */66 const root = "/work/datekit";67 69-/** The ask's check, one of the ask's own files: no answer may change it. */68 const checkPath = "packages/a/test/week.test.ts";69 70 const landedSha = "4444444444444444444444444444444444444444";71 74-/** Bob's ask `fix-week`, as its file states it: module `a` is its territory. */72 const askWire = {73 askedBy: "bob",74 blockedBy: [],75 brief: { want: "An ISO week date parses to the Monday of that week." },13 unmodified lines89 publicFiles: ["packages/a/src/index.ts"],90 },91 } as const;92 96-/** The ask, as `showAsk` returns it. */93 const ask = Schema.decodeSync(Ask)(askWire);94 99-/** Alice's claim on `fix-week`, as the hook keeps it. */95 const claim: HookClaim = {96 ask: ask.id,97 base: CommitSha.make("1".repeat(40)),98 checkCommand: `bun test ${checkPath}`,1 unmodified line100 territory: ask.territory,101 want: ask.brief.want,102 };103 109-/** An unreasoned `.skip(` in the ask's check: the agent's to fix. */104 const weakened = new Weakened({105 at: { line: 3, path: RepoPath.make(checkPath) },106 weakening: { marker: ".skip(" },107 });108 109 const sha = (digit: string) => CommitSha.make(digit.repeat(40));110 117-/** A session with a claim, before any stop was held. */111 const facts: HookFacts = {112 claim: Option.some(claim),113 holds: 0,114 judge: {10 unmodified lines125 session_id: "session-1",126 ...fields,127 });128 136-/** A tool call on one file, as Claude Code sends it. */129 const tool = (name: string, toolInput: NonNullable<HookInput["tool_input"]>) =>130 input({ tool_input: toolInput, tool_name: name });131 140-/** Claude Code's PreToolUse deny, with the gateway's own text as the reason. */132 const deny = (refusals: Array.NonEmptyReadonlyArray<Refusal>) => ({133 hookSpecificOutput: {134 hookEventName: "PreToolUse",135 permissionDecision: "deny",158 unmodified lines294 ).toStrictEqual({});295 });296 });297 307-/** Claude Code's Stop, as it sends it. */298 const stop = (fields: Partial<HookInput> = {}) =>299 input({ hook_event_name: "Stop", stop_hook_active: false, ...fields });300 311-/** Claude Code's Stop hold, with the gateway's own text as the reason. */301 const hold = (refusals: Array.NonEmptyReadonlyArray<Refusal>) => ({302 decision: "block",303 reason: explain(refusals).join("\n"),304 });73 unmodified lines378 });379 });380 381 describe("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 lines412 vouches: [],413 weakening: { markers: [] },414 });415 428- /** 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 lines474 })475 );476 });477 491-// ------------------------------------------------------------ the command492-493-/** Alice's live claim on `fix-week`, made when main was at `base`. */478 const liveClaim = (base: string) =>479 Schema.decodeSync(ClaimView)({480 ask: "fix-week",481 base,7 unmodified lines489 state: "live",490 warnsAt: "2026-10-07T14:00:00.000Z",491 });492 509-/**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- */493 const aClone = (remote: string) =>494 Effect.gen(function* () {495 const fs = yield* FileSystem.FileSystem;496 const path = yield* Path.Path;41 unmodified lines538 539 return { base: yield* gitOk(dir, "rev-parse", "HEAD"), dir };540 });541 562-/**563- * A platform whose `status` gives alice's claims as `claims` holds them564- * when asked, counting each `status` and each `showAsk`.565- */542 const platformOf = (543 claims: Ref.Ref<readonly ClaimView[]>,544 asked: Ref.Ref<{ readonly showAsk: number; readonly status: number }>545 ) =>28 unmodified lines574 asPerson(Handle.make("alice")),575 ])576 );577 602-/** A platform that knows alice's claim, made at `base`, and what it was asked. */578 const platformFor = (base: string) =>579 Effect.gen(function* () {580 const asked = yield* Ref.make({ showAsk: 0, status: 0 });581 5 unmodified lines587 ),588 };589 });590 616-/** What one run of `<cli> hook …` printed, and the exit code a process would have. */591 interface Ran {592 readonly code: number;593 readonly out: readonly string[];594 readonly err: readonly string[];595 }596 623-/** The env a run reads: where the session's state is kept. */597 interface StateEnv {598 readonly HOME?: string;599 readonly XDG_STATE_HOME?: string;600 }601 629-/**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- */602 const runHook = (603 argv: readonly string[],604 stdin: string,605 env: string | StateEnv,31 unmodified lines637 )638 )639 );640 673-/** `TouchedJudge` for one path. */641 const touchedJudgeOf = (path: string) =>642 new TouchedJudge({ paths: [RepoPath.make(path)] });643 644 const tempDir = Effect.flatMap(FileSystem.FileSystem, (fs) =>175 unmodified lines820 "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>();825 826 const hung = Layer.mock(Client)({827 status: ({ project }) =>63 unmodified lines891 path.join(state, Brand.slug, "hooks", "s-8.json"),892 path.join(home, ".local", "state", Brand.slug, "hooks", "s-9.json"),893 ];894 929- // 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 lines1036 });1037 1038 const before = [yield* event("session-start"), yield* edit];1039 1075- // The agent claims the ask in its first turn.1040 yield* Ref.set(claims, [liveClaim(base)]);1041 1042 const after = [yield* edit, yield* event("stop"), yield* edit];1043 36 unmodified lines1080 const encodeEnvelope = Schema.encodeSync(1081 Schema.fromJsonString(Envelope(Schema.Unknown))1082 );1083 1120-/**1121- * The default check over a stand-in for the CLI that prints `stdout` and1122- * exits `code`, whatever arguments it is given.1123- */1084 const checkPrinting = (stdout: string, code: number) =>1085 Effect.gen(function* () {1086 const fs = yield* FileSystem.FileSystem;1087 const path = yield* Path.Path;105 unmodified linesmodified:apps/cli/test/main.test.ts-7 removed
8 unmodified lines9 import { Credentials } from "../src/credentials.ts";10 import { root } from "../src/main.ts";11 import { OutputPlain } from "../src/output.ts";12 13-/** What was printed to stdout, one entry per line however it was written. */13 const printed = Effect.map(TestConsole.logLines, (all) =>14 all.flatMap((chunk) => String(chunk).split("\n"))15 );16 18-/**19- * What the CLI runs with in these tests: a test console, plain output, and20- * a client and credentials no command here calls.21- */17 const 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));24 30-/** The help `root` prints for `--help`, line by line. */25 const help = Effect.gen(function* () {26 yield* Command.runWith(root, { version: "0.0.0" })(["--help"]);27 28 return yield* printed;29 }).pipe(Effect.provide(services));30 37-/** The lines of `lines` between the heading `from` and the next heading. */31 const section = (lines: readonly string[], from: string) => {32 const start = lines.indexOf(from) + 1;33 34 const end = lines.findIndex(53 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { commandDocs } from "@repo/agent-kit/command-doc";3 import { readManaged } from "@repo/agent-kit/generated-file";4 import { platformSkill } from "@repo/agent-kit/platform";12 unmodified lines17 const fixWeek = AskId.make("fix-week");18 19 const want = "week reads the ISO week of a date";20 27-/** fix-week as `showAsk` returns it. */21 const askWire = {22 askedBy: "dora",23 blockedBy: [],24 brief: { want },13 unmodified lines38 } as const;39 40 const brief = `# ${fixWeek}\n\n${want}.\n`;41 49-/** A platform with datekit's one open ask, fix-week. */42 const datekit = Layer.mergeAll(43 unanswered,44 Contracts.toLayerHandler("showAsk", ({ ask }) =>45 ask === fixWeek21 unmodified lines67 "io.modelcontextprotocol/clientInfo": { name: "test", version: "0.0.0" },68 "io.modelcontextprotocol/protocolVersion": "2026-07-28",69 };70 79-/** 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`.72 const request = (73 id: number,74 method: string,75 params: Readonly<Record<string, Schema.Json>> = {}21 unmodified lines97 })98 ),99 });100 109-/**110- * The platform's skill body, from agent-kit's command list: the contracts'111- * commands and the hand-written ones.112- */101 const skillBody = platformSkill({ commands: commandDocs(Contracts) }).pipe(102 Effect.map(([file]) =>103 Option.match(104 Option.flatMap(Option.fromNullishOr(file), ({ content }) =>66 unmodified linesmodified: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- */1 import { NodeHttpServer } from "@effect/platform-node";2 import { Context, Effect, Layer, Ref, Schema } from "effect";3 import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";4 5 export 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 }9 19-/** A code `/authorize` gave out, and what `/token` must be shown for it. */10 interface Grant {11 readonly challenge: string;12 readonly clientId: string;13 readonly redirectUri: string;13 unmodified lines27 .replaceAll("+", "-")28 .replaceAll("/", "_")29 .replace(/=+$/u, "");30 41-/** `BASE64URL(SHA256(verifier))`. */31 const s256 = (verifier: string) =>32 Effect.map(33 Effect.promise(() =>34 crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))3 unmodified lines38 39 const refused = (error: string) =>40 HttpServerResponse.jsonUnsafe({ error }, { status: 400 });41 53-/**54- * The server on a local port: its origin, and the query of every55- * `/authorize` request it answered.56- */42 export 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 linesmodified:apps/cli/test/output.test.ts-1 removed
13 unmodified lines14 });15 16 const view = { markdown: "**2** open asks", text: "2 open asks" };17 18-/** What `use` printed through `OutputPlain`: stdout and stderr, as text. */18 const printedBy = (use: (output: Output["Service"]) => Effect.Effect<void>) =>19 Effect.gen(function* () {20 yield* Effect.flatMap(Effect.service(Output), use);21 87 unmodified linesmodified: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- */1 import type {2 AgentBeforeSettleEvent,3 BeforeAgentStartEvent,4 SessionBoundaryDraft,35 unmodified lines40 import type { PiContext, PiDeps, PiEvents, PiHandlers } from "../src/pi.ts";41 42 const cwd = "/work/datekit";43 51-/** The brief the fake policy gives a session that holds a claim. */44 const briefText = "# Your claim: fix-week in datekit";45 54-/** The config folder's project file: in every judge closure. */46 const projectFile = RepoPath.make(`${Brand.configDir}/project.ts`);47 57-/** A change outside the claim's territory. */48 const outside = new OutOfScope({ paths: [RepoPath.make("README.md")] });49 60-/** What the fake policy answers. */50 interface Policy {51 readonly brief?: Option.Option<string>;52 readonly guard?: (53 call: GuardedCall54 ) => Option.Option<Array.NonEmptyReadonlyArray<Refusal>>;55 readonly settle?: () => SettleVerdict;56 }57 69-/** The fake policy, and what the adapter asked it. */58 const fakeDeps = (policy: Policy) => {59 const asked: string[] = [];60 61 const deps: PiDeps = {19 unmodified lines81 82 return { asked, deps };83 };84 97-/** A policy whose every call fails as `failure` does. */85 const broken = (failure: Effect.Effect<never, HookFailed>): PiDeps => ({86 brief: () => failure,87 guardTool: () => failure,88 settle: () => failure,89 });90 104-/** The fake policy's judge: the config folder's project file is in its closure. */91 const judging = (call: GuardedCall) =>92 GuardedCall.$is("Write")(call) && call.file === projectFile93 ? Option.some(Array.of(new TouchedJudge({ paths: [projectFile] })))94 : Option.none();95 110-/** A fake preflight: what `<cli> check` refuses of the work as it stands. */96 const preflight =97 (...refusals: readonly Refusal[]) =>98 (call: GuardedCall) =>99 GuardedCall.$is("Push")(call) && Array.isReadonlyArrayNonEmpty(refusals)100 ? Option.some(refusals)101 : Option.none();102 118-/** A fake pi: it records each handler the adapter registers, by event. */103 const fakePi = () => {104 const handlers: { -readonly [K in keyof PiHandlers]?: PiHandlers[K] } = {};105 const events: string[] = [];106 8 unmodified lines115 116 return { events, handlers, pi };117 };118 135-/** A handler's context in session `id`, with the notes `ui.notify` got. */119 const contextOf = (id: string, withUi = true) => {120 const notes: string[] = [];121 const bare: PiContext = { cwd, sessionManager: { getSessionId: () => id } };122 5 unmodified lines128 129 return { ctx: withUi ? { ...bare, ui } : bare, notes };130 };131 149-/** pi set up with `policy` behind the adapter. */132 const loaded = (policy: Policy) => {133 const { asked, deps } = fakeDeps(policy);134 const { events, handlers, pi } = fakePi();135 1 unmodified line137 138 return { asked, events, handlers };139 };140 159-/** Fires one recorded handler at `event`, as pi does, and awaits it. */141 const fire = <E, R>(142 handler: ((event: E, ctx: PiContext) => Promise<R>) | undefined,143 event: E,144 ctx: PiContext34 unmodified lines179 toolName: "bash",180 type: "tool_call",181 });182 202-/**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.185 const settleOf = (entries: SessionBoundaryDraft[]): AgentBeforeSettleEvent => ({186 context: {187 canContinue: false,188 contextEntries: [],243 unmodified lines432 );433 });434 435 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 lines735 })736 );737 });738 764-// ------------------------------------------------------------ live deps765-739 const want = "An ISO week date parses to the Monday of that week.";740 768-/** Kept facts for a session on `fix-week` in a clone at `root`. */741 const claimedIn = (root: string): SessionState => ({742 claim: {743 ask: AskId.make("fix-week"),744 base: CommitSha.make("1".repeat(40)),6 unmodified lines751 judge: { paths: [Glob.make(`/${Brand.configDir}/**`)], pointers: [] },752 root,753 });754 783-/**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- */755 const policyWith = (756 checked: Effect.Effect<readonly Refusal[], PushCheckFailed>757 ) =>758 Effect.gen(function* () {178 unmodified linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Contracts, PolicyOf } from "@repo/protocol/contracts";4 import type { PublicPolicy } from "@repo/protocol/domain/policy";7 unmodified lines12 const sha = "4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c";13 14 const decodeSuccess = Schema.decodeSync(PolicyOf.successSchema);15 24-/** datekit's evaluated config folder at `sha`, encoded. */16 const datekitPolicy = {17 agents: "trailer",18 at: sha,19 budget: { decisionsPerDay: 5, expireDays: 14 },18 unmodified lines38 ],39 weakening: { markers: [] },40 } as const satisfies typeof PublicPolicy.Encoded;41 51-/** datekit's policy as `projectPolicy` returns it. */42 const datekit = decodeSuccess({ policy: datekitPolicy });43 44 const noConfig = decodeSuccess({45 unevaluated: { at: sha, reason: "noConfig" },2 unmodified lines48 const configFailed = decodeSuccess({49 unevaluated: { at: sha, reason: "configFailed" },50 });51 62-/** What a person reads: the view's text, or its Markdown when it has none. */52 const textOf = (success: typeof PolicyOf.successSchema.Type) =>53 Option.match(views.projectPolicy(success), {54 onNone: () => "",55 onSome: ({ markdown, text }) => text ?? markdown,56 });57 69-/** Each non-empty line, its runs of spaces made one. */58 const linesOf = (text: string) =>59 text60 .split("\n")61 .map((line) => line.replaceAll(/\s+/gu, " ").trim())99 unmodified lines161 const decodeEnvelope = Schema.decodeEffect(162 Schema.fromJsonString(Envelope(Schema.Unknown))163 );164 177-/** A platform whose `projectPolicy` answers `success`. */165 const answering = (success: typeof PolicyOf.successSchema.Type) =>166 Layer.mergeAll(167 unanswered,168 Contracts.toLayerHandler("projectPolicy", () => Effect.succeed(success))64 unmodified linesmodified:apps/cli/test/policy.test.ts-1 removed
20 unmodified lines21 territory: "packages/week",22 want: "Weeks start on the locale's first day",23 };24 25-/** `listAsks` lists one open ask; `claim` finds it taken. */25 const platform = Layer.mergeAll(26 unanswered,27 Contracts.toLayerHandler("listAsks", () =>28 Effect.succeed({ asks: [listing] })131 unmodified linesmodified: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- */1 import { NodeHttpServer, NodeServices } from "@effect/platform-node";2 import { authenticated, bearerToken } from "@repo/protocol/authenticate";3 import { Client, Contracts } from "@repo/protocol/contracts";4 import { Handle } from "@repo/protocol/ids";21 unmodified lines26 import { policyFor } from "../src/policy.ts";27 import { WorkingDirectory } from "../src/surfaces.ts";28 import { SignedOut } from "./signed-out.ts";29 35-/** Handlers for every contract, as a test sets them up. */30 export type Handlers = Layer.Layer<31 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>32 >;33 40-/** A Terminal that counts every prompt it is asked for, and answers none. */34 const 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 lines46 })47 );48 };49 57-/** What was printed to a stream, one entry per line however it was written. */50 const lines = (output: Effect.Effect<readonly unknown[]>) =>51 Effect.map(output, (all) =>52 all.flatMap((chunk) => String(chunk).split("\n"))53 );54 55 export 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 }62 76-/**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- */63 export const runProgram = (64 args: readonly string[],65 { client, cwd, env = {}, handlers, isTTY = true }: Invocation66 ) =>47 unmodified lines114 prompts: yield* Ref.get(prompts),115 };116 });117 137-/** A person the HTTP platform knows by their token. */118 export const knownToken = "token-of-tester";119 140-/** The person a token names: `tester` for `knownToken`, nobody for any other. */120 const verify = (token: string) =>121 Effect.succeed(122 token === knownToken123 ? Option.some(Person.make({ handle: Handle.make("tester") }))124 : Option.none()125 );126 148-/** `app` served on an ephemeral port for the test's scope: returns its origin. */127 const serving = <E>(128 app: Effect.Effect<129 HttpServerResponse.HttpServerResponse,130 E,11 unmodified lines142 ? `http://127.0.0.1:${address.port}`143 : yield* Effect.die("the test platform listens on a socket, not a port");144 });145 168-/**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.147 export const httpPlatform = (handlers: Handlers) =>148 Effect.gen(function* () {149 const seen = yield* Ref.make<readonly (string | undefined)[]>([]);150 21 unmodified lines172 173 return { origin: yield* serving(gate), seen: Ref.get(seen) };174 });175 204-/**205- * A platform that answers every request with `status` and an empty body, as206- * a platform that is down does: returns its origin.207- */176 export const failingPlatform = (status: number) =>177 serving(Effect.succeed(HttpServerResponse.empty({ status })));modified:apps/cli/test/remote.test.ts-3 removed
14 unmodified lines15 runProgram,16 } from "./remote-server.ts";17 import type { Handlers } from "./remote-server.ts";18 19-/** `listAsks` (public) lists one ask; `status` (signed in) shows nothing yet. */19 const handlers: Handlers = Layer.mergeAll(20 unanswered,21 Contracts.toLayerHandler("listAsks", () =>22 Effect.succeed({13 unmodified lines36 Effect.succeed({ answers: [], claims: [], handle: Handle.make("tester") })37 )38 );39 41-/** Credentials holding `profile`, or none. */40 const holding = (profile: Option.Option<Profile>) =>41 Layer.succeed(Credentials)({42 current: Effect.succeed(profile),43 forHost: () => Effect.succeed(profile),5 unmodified lines49 token: Redacted.make(token),50 url,51 });52 55-/** The remote client over `credentials`, with `env` as its whole env. */53 const remote = (54 credentials: Layer.Layer<Credentials>,55 env: Readonly<Record<string, string>> = {}56 ) =>123 unmodified linesmodified:apps/cli/test/repo-context.test.ts-2 removed
105 unmodified lines106 expect(parseRemote(url)).toStrictEqual(Option.none());107 });108 });109 110-/** A fresh git repo, its real path, with `remotes` added in order. */110 const 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 lines120 121 return dir;122 });123 125-/** Credentials whose current profile is on `url`. */124 const signedIn = (url: string) => {125 const profile: Profile = {126 token: Redacted.make("tok-0123456789abcdefghijklmnopqrstuvwxyz"),127 url,72 unmodified linesmodified:apps/cli/test/schema.test.ts-2 removed
3 unmodified lines4 import { Effect, Schema } from "effect";5 6 import { runProgram } from "./remote-server.ts";7 8-/** What `schema` prints: a JSON Schema object, as far as these tests read it. */8 const PayloadSchema = Schema.fromJsonString(9 Schema.Struct({10 $schema: Schema.String,11 properties: Schema.Record(10 unmodified lines22 );23 24 const decodePayloadSchema = Schema.decodeEffect(PayloadSchema);25 27-/** `schema` asks the platform nothing. */26 const schemaOf = (words: readonly string[], env = {}) =>27 runProgram(["schema", ...words], { env, handlers: unanswered });28 29 describe("schema <command>", () => {65 unmodified linesmodified: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.3 import { Effect, Layer } from "effect";4 5 import { Credentials } from "../src/credentials.ts";6 4 unmodified linesmodified:apps/cli/test/stdio.ts-4 removed
24 unmodified lines25 result: Schema.optionalKey(Schema.Unknown),26 })27 );28 29-/**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- */29 export const session = (30 handlers: Layer.Layer<Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>>,31 messages: readonly object[]32 ) =>48 unmodified linesmodified:apps/cli/test/surfaces.test.ts-10 removed
47 unmodified lines48 conflicts: [RepoPath.make("src/a.ts")],49 main,50 });51 52-/** Contracts whose answers always meet a moved main. */52 const stale = Layer.mergeAll(53 unanswered,54 Contracts.toLayerHandler("submitAnswer", () => Effect.fail(refusal))55 );8 unmodified lines64 });65 66 const Initialized = Schema.Struct({ protocolVersion: Schema.String });67 69-/** A tools/call result whose one content block is JSON text. */68 const ToolResult = Schema.Struct({69 content: Schema.Tuple([70 Schema.Struct({71 text: Schema.fromJsonString(Schema.Unknown),100 unmodified lines172 })173 );174 });175 178-/** The names of a command's subcommands, in order. */176 const subcommandsOf = (command: Command.Command.Any | undefined) =>177 (command?.subcommands ?? []).flatMap(({ commands: group }) =>178 group.map(({ name }) => name)179 );56 unmodified lines236 "--choice",237 "accept",238 ];239 243-/** A platform that counts the decisions it is asked to take, and takes none. */240 const deciding = (calls: Ref.Ref<number>) =>241 Layer.mergeAll(242 unanswered,243 Contracts.toLayerHandler("decide", () =>96 unmodified lines340 })341 );342 });343 348-/** A platform that lists no asks, recording the project each listing names. */344 const 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 );351 357-/** A fresh git repo whose `origin` is `url`, at its real path. */352 const repoWithOrigin = (url: string) =>353 Effect.gen(function* () {354 const fs = yield* FileSystem.FileSystem;355 const dir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());82 unmodified lines438 "--requestId",439 requestId,440 ];441 448-/** An answer's receipt, standing at `outcome`. */442 const receiptAt = (outcome: Outcome) => ({443 ask,444 base,445 head,1 unmodified line447 project,448 requestId,449 });450 458-/** A platform whose `submitAnswer` gives `receipt` back. */451 const receiving = (receipt: ReturnType<typeof receiptAt>) =>452 Layer.mergeAll(453 unanswered,454 Contracts.toLayerHandler("submitAnswer", () => Effect.succeed(receipt))455 );456 465-/** Each command that names an ask, and what else it takes, as a person types it. */457 const naming = {458 finish: [459 "--project",460 project,18 unmodified lines479 ],480 verdict: ["--project", project],481 } as const satisfies Readonly<Record<string, readonly string[]>>;482 492-/** A platform that records the ask each call names, and answers each call plainly. */483 const recordingAsks = (named: Ref.Ref<readonly string[]>) => {484 const record = (given: string) => Ref.update(named, (all) => [...all, given]);485 486 const receipt = receiptAt(Outcome.cases.Checking.make({ stage: "merge" }));140 unmodified linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 import { Client } from "@repo/protocol/contracts";17 unmodified lines22 OutputPlain,23 SignedOut24 ).pipe(Layer.provideMerge(NodeServices.layer));25 32-/** What a built `version.ts` exports. */26 const Built = Schema.Struct({ cliVersion: Schema.String });27 28 describe("the CLI's version, unbuilt", () => {29 it.effect("is 0.0.0, and --version prints it", () =>96 unmodified lines126 ]);127 });128 });129 137-/** What the build would run with for `argv`, if it would run. */130 const parsed = (argv: readonly string[]) =>131 Effect.gen(function* () {132 const seen = yield* Ref.make(Option.none<BuildOptions>());133 28 unmodified linesmodified: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- */1 import { Option } from "effect";2 9-/** A machine as npm's `os` and `cpu` fields name it. */3 export interface NpmMachine {4 readonly cpu: string;5 readonly os: string;6 }7 15-/** Bun's operating systems, by npm's name for each. */8 const OS = new Map([9 ["darwin", "darwin"],10 ["linux", "linux"],11 ["windows", "win32"],12 ]);13 14 const CPU = new Set(["arm64", "x64"]);15 24-/**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- */16 export const npmMachineOf = (target: string): Option.Option<NpmMachine> => {17 const [os, cpu] = target.replace(/^bun-/u, "").split("-");18 19 return Option.flatMap(Option.fromUndefinedOr(OS.get(os ?? "")), (npmOs) =>2 unmodified lines22 : Option.none()23 );24 };25 39-/**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>`.27 export 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- */1 import { BunRuntime, BunServices } from "@effect/platform-bun";2 import { Brand } from "@repo/brand";3 import {4 Data,18 unmodified lines23 UNSTAMPED,24 versionDefine,25 } from "./tsdown.config.ts";26 53-// 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.28 export { versionDefine } from "./tsdown.config.ts";29 57-/** What one build is asked for. */30 export 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 }34 65-/**66- * `bun build --compile`'s arguments for one binary: `entry` compiled to67- * `outfile`, for `target` (this machine when absent), stamped with `version`.68- */35 export const compileArgs = (input: {36 readonly entry: string;37 readonly outfile: string;38 readonly target?: string;16 unmodified lines55 readonly step: string;56 readonly detail: string;57 }> {}58 93-/** A tsconfig the build writes for one step. */59 interface 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 }73 110-/** What the build reads of a native package's manifest: its machines' packages. */74 const NativeManifest = Schema.fromJsonString(75 Schema.Struct({76 optionalDependencies: Schema.Record(Schema.String, Schema.String),77 })78 );79 117-/** What the build reads of a workspace package's manifest. */80 const Manifest = Schema.fromJsonString(81 Schema.Struct({82 exports: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),83 name: Schema.String,84 })85 );86 125-/**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- */87 const run = (88 step: string,89 command: string,90 args: readonly string[],23 unmodified lines114 ),115 Effect.asVoid116 );117 160-/** tsdown over `config`, as one build step. */118 const 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 lines128 const root = yield* path.fromFileUrl(new URL(".", import.meta.url));129 const repo = path.join(root, "..", "..");130 const dist = path.join(root, "dist");131 175- /**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 lines154 155 return paths;156 });157 205- /** 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 );163 212- // 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 }171 221- // 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");175 176 yield* Effect.acquireRelease(177 fs.makeDirectory(scratch, { recursive: true }),1 unmodified line179 );180 181 const declared = path.join(scratch, "declared");182 234- /** 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");185 186 const emit = yield* tsconfigIn(scratch, "emit.json", {34 unmodified lines221 config: false,222 cwd: root,223 });224 277- // 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");228 229 yield* Effect.acquireRelease(230 fs.makeDirectory(compile, { recursive: true }),34 unmodified lines265 "",266 ].join("\n")267 );268 324- /**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 lines316 317 return path.join(folder, "node_modules");318 });319 380- // 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 lines364 ),365 Flag.optional366 );367 429-/** The build's command line, running `then` with what it asks for. */368 const command = <E, R>(369 then: (options: BuildOptions) => Effect.Effect<void, E, R>370 ) =>371 Command.make("build", { targets, version }, (flags) =>13 unmodified lines385 "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."386 )387 );388 451-/**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.390 const builtIns = CliConfig.make({391 builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Version),392 });393 459-/** Runs `then` with what `argv`, the build's arguments, asks for. */394 export const parseBuild = <E, R>(395 argv: readonly string[],396 then: (options: BuildOptions) => Effect.Effect<void, E, R>397 ) =>11 unmodified linesmodified: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- */1 import { defineConfig } from "tsdown";2 import type { UserConfig } from "tsdown";3 13-/** What a build no release stamped says it is (the release's `UNRELEASED`). */4 export const UNSTAMPED = "0.0.0";5 16-/**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- */6 export const versionDefine = (version: string) => ({7 "import.meta.env.CLI_BUILD_VERSION": JSON.stringify(version),8 });9 26-/** The library entries, by the name each is published under. */10 export const library = {11 protocol: "src/entries/protocol.ts",12 rules: "src/entries/rules.ts",13 } as const;11 unmodified lines25 platform: "node",26 } as const satisfies UserConfig;27 28 /**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 */32 export 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;42 65-/**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/`.44 export const npm = (version: string) => {45 const stamped = { ...shared, define: versionDefine(version), dts: false };46 47 return [3 unmodified lines51 { ...stamped, clean: false, entry: { pi: "src/pi.ts" } },52 ] satisfies UserConfig[];53 };54 81-/** `tsdown` run here by hand builds what no release stamped. */55 export 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`.4 import { VerifierBlocked } from "@repo/protocol/refusal";5 import { Duration, Effect, FileSystem, Layer, Option, Stream } from "effect";6 import type { Scope } from "effect";7 import { ChildProcess, ChildProcessSpawner } from "effect/process";3 unmodified lines11 import { classifyRun } from "../classify.ts";12 import type { RunExit } from "../classify.ts";13 14 export 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 }19 32-/** A lane with no time limit of its own gets ten minutes. */20 const DEFAULT_TIMEOUT = Duration.minutes(10);21 35-/** After the time limit's SIGTERM, how long a lane has before SIGKILL. */22 const FORCE_KILL_AFTER = Duration.seconds(2);23 24 // 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 where30 unmodified lines56 bytes.pipe(Stream.decodeText(), Stream.mkString);57 58 const timedOut: RunExit = { code: -1, stderr: "", stdout: "", timedOut: true };59 74-// 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.60 const printed = (lane: CheckLane, exit: RunExit): readonly LaneOutput[] =>61 lane.output === "stdout" && exit.timedOut !== true62 ? [{ lane: lane.lane, stdout: exit.stdout }]63 : [];11 unmodified lines75 Effect.gen(function* () {76 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;77 const fs = yield* FileSystem.FileSystem;78 95- // 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 linesmodified: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- */1 import type { LaneResult } from "@repo/protocol/domain/answer";2 import type { LaneName } from "@repo/protocol/ids";3 import { VerifierBlocked } from "@repo/protocol/refusal";4 import { Array, Effect, Layer, Option, Ref } from "effect";5 6 import { CheckRunner, shaOf } from "../check-runner.ts";7 import type { CheckAt, LaneEvidence, LaneOutput } from "../check-runner.ts";8 16-/** Where a lane's script lives in the map: `<tree or commit sha>:<lane>`. */9 export const scriptKey = (at: CheckAt, lane: LaneName) =>10 `${shaOf(at)}:${lane}`;11 20-/**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.13 const evidenceOf = ({ lane, result }: LaneResult): LaneEvidence =>14 result === "failed"15 ? { lane, signature: `${lane}: scripted failure` }16 : { lane };17 18 export 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());28 29 const next = (30 key: string,60 unmodified linesmodified: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- */1 import { VerifierBlocked } from "@repo/protocol/refusal";2 import { Schema } from "effect";3 4 import { CheckJob, CheckRun } from "../check-runner.ts";5 13-/**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- */7 export const Remote = Schema.Struct({8 token: Schema.RedactedFromValue(Schema.String),9 url: Schema.NonEmptyString,10 });11 12 export type Remote = typeof Remote.Type;13 25-/** A check job as the platform sends it: the job and a read token for its repo. */14 export const CheckWire = Schema.Struct({ clone: Remote, job: CheckJob });15 16 export type CheckWire = typeof CheckWire.Type;17 30-/**31- * A check's outcome as it comes back: the run, `VerifierBlocked`, or a32- * defect, as JSON.33- */18 export 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- */1 import { Context, Effect, Layer, Option, Ref } from "effect";2 3 import { EvidenceStore, logRefOf } from "../evidence-store.ts";4 import type { LaneLog } from "../evidence-store.ts";5 10-/** Every log the memory store was given, in order, replays included. */6 export class EvidenceKept extends Context.Service<7 EvidenceKept,8 { readonly puts: Effect.Effect<readonly LaneLog[]> }9 >()("checks/EvidenceKept") {}10 16-/** A fresh, empty store each time the layer is built, and its record. */11 export const EvidenceStoreMemory: Layer.Layer<EvidenceStore | EvidenceKept> =12 Layer.effectContext(13 Effect.gen(function* () {14 const puts = yield* Ref.make<readonly LaneLog[]>([]);19 unmodified linesmodified: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- */2 import { Data, Effect, Layer, Option } from "effect";3 4 import { EvidenceStore, logRefOf } from "../evidence-store.ts";5 17-/**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- */6 export interface EvidenceBucket {7 readonly put: (8 key: string,9 value: string,6 unmodified lines16 key: string17 ) => Promise<{ readonly text: () => Promise<string> } | null>;18 }19 36-/** R2 refused or never answered a call on one key: the store cannot go on. */20 class EvidenceUnreachable extends Data.TaggedError("EvidenceUnreachable")<{21 readonly message: string;22 readonly cause: unknown;23 }> {}24 42-/** One call on the bucket for `key`; a failure dies naming the key and the call. */25 const reach = <A>(call: "get" | "put", key: string, run: () => Promise<A>) =>26 Effect.orDie(27 Effect.tryPromise({28 catch: (cause) =>39 unmodified linesmodified: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- */1 import type { Glob } from "@repo/protocol/domain/common";2 import { RepoPath } from "@repo/protocol/ids";3 import { Option, Order, Result, Schema } from "effect";4 5 import { matchGlob } from "../judge.ts";6 13-/** The JSON a linter prints: oxlint's report object, or ESLint's array of files. */7 export type LintFormat = "oxlint" | "eslint";8 16-/** A lint count: the findings in all, and per repo path (only paths with any). */9 export interface LintCount {10 readonly total: number;11 readonly byPath: ReadonlyMap<RepoPath, number>;12 }13 22-/** How much of an unreadable output a `CountUnreadable` keeps. */14 const HEAD_LENGTH = 200;15 25-/**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- */16 export 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 }23 39-// `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.25 const OxlintReport = Schema.Struct({26 diagnostics: Schema.Array(27 Schema.Struct({28 code: Schema.optionalKey(Schema.String),1 unmodified line30 })31 ),32 });33 51-// `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`.35 const EslintReport = Schema.Array(36 Schema.Struct({37 filePath: Schema.NonEmptyString,38 messages: Schema.Array(3 unmodified lines42 ),43 })44 );45 64-/** One finding: the file it is in, and the rule that reported it, if one did. */46 interface Finding {47 readonly path: string;48 readonly rule: Option.Option<string>;49 }21 unmodified lines71 }))72 )73 );74 94-/**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- */75 interface RuleName {76 readonly plugin: Option.Option<string>;77 readonly name: string;78 }79 105-// `plugin(rule)`, oxlint's code form.80 const CODE_FORM = /^(?<plugin>[^()]+)\((?<name>[^()]+)\)$/u;81 82 // The core rules' plugin: oxlint prints them as `eslint(no-debugger)`, ESLint83 // as a bare `no-debugger`.24 unmodified lines108 plugin: Option.some(pluginOf(written.slice(0, slash))),109 };110 };111 138-/**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.114 const isRule =115 (wanted: RuleName) =>116 (finding: Finding): boolean =>117 Option.match(finding.rule, {11 unmodified lines129 );130 },131 });132 163-/** A path relative to the repo: without `root`'s prefix and any leading `./`. */133 const repoPathOf = (path: string, root: Option.Option<string>): string => {134 const inside = Option.match(root, {135 onNone: () => path,136 onSome: (dir) => {9 unmodified lines146 };147 148 const EXCLUDE = "!";149 181-/** Whether a path is in a territory: some glob matches it, and no `!` glob takes it back. */150 const within = (territory: readonly Glob[], path: string) =>151 territory.some(152 (glob) => !glob.startsWith(EXCLUDE) && matchGlob(glob, path)153 ) &&4 unmodified lines158 159 const totalOf = (byPath: ReadonlyMap<RepoPath, number>) =>160 [...byPath.values()].reduce((sum, count) => sum + count, 0);161 194-/**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- */162 export const countWithin = (163 count: LintCount,164 territory: readonly Glob[]165 ): LintCount => {3 unmodified lines169 170 return { byPath, total: totalOf(byPath) };171 };172 210-/** The format an output is in, by its JSON's shape: an array is ESLint's. */173 const detect = (output: string): LintFormat =>174 output.trimStart().startsWith("[") ? "eslint" : "oxlint";175 214-/**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.177 export const countLint = (input: {178 readonly output: string;179 readonly format?: LintFormat | undefined;180 readonly rule?: string | undefined;38 unmodified linesmodified: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- */1 import { RatchetMeasure } from "@repo/protocol/domain/check";2 import type { CheckSpec, RatchetSpec } from "@repo/protocol/domain/check";3 import type { Territory } from "@repo/protocol/domain/territory";4 import { RatchetName } from "@repo/protocol/ids";1 unmodified line6 7 import type { CountUnreadable, LintCount } from "./lint-count.ts";8 import { measure } from "./ratchet.ts";9 16-/** Red: the rule still reports something in the territory. */10 export const lintToZeroRed = (count: LintCount): boolean => count.total > 0;11 19-/** Green: the rule reports nothing in the territory. */12 export const lintToZeroGreen = (count: LintCount): boolean => count.total === 0;13 22-/** A `lintToZero` check. */14 export type LintToZeroCheck = Extract<15 CheckSpec,16 { readonly _tag: "LintToZero" }17 >;18 28-/** The name a `lintToZero` check's count goes by in `measure`. */19 const countName = RatchetName.make("lint-to-zero");20 31-/**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.23 export const lintToZeroCount = (input: {24 readonly asked: Territory;25 readonly check: LintToZeroCheck;26 readonly modules: readonly Territory[];21 unmodified linesmodified: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.2 import type { JsonPath } from "@repo/protocol/domain/common";3 import { Option, Predicate, Result, Schema } from "effect";4 5 import { CountUnreadable } from "./lint-count.ts";6 11-/** One step down a JSON value: an object's key, or an array's index. */7 type Step = string | number;8 14-// One step at the start of what is left of a path: `.key` or `[index]`.9 const STEP = /^(?:\.(?<key>[\w$-]+)|\[(?<index>\d+)\])/u;10 17-/** A path's steps, or `None` when it leaves the supported subset. */11 const stepsOf = (path: string): Option.Option<readonly Step[]> => {12 if (!path.startsWith("$")) {13 return Option.none();14 }22 unmodified lines37 38 const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>39 Predicate.isObject(value);40 48-/** The value one step down, if the value has it: a key on an object, an index on an array. */41 const 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 lines49 ? Option.fromNullishOr(value[step])50 : Option.none();51 };52 61-/** The value at the end of a path's steps, if the value has every one. */53 const walk = (54 value: Schema.Json,55 steps: readonly Step[]56 ): Option.Option<Schema.Json> => {8 unmodified lines65 66 const isCount = (value: Schema.Json): value is number =>67 Predicate.isNumber(value) && Number.isSafeInteger(value);68 78-/**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- */69 export const readMetric = (70 output: string,71 path: JsonPath72 ): Result.Result<number, CountUnreadable> =>8 unmodified linesmodified: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- */1 import { RatchetMeasure } from "@repo/protocol/domain/check";2 import type { RatchetSpec } from "@repo/protocol/domain/check";3 import { Glob } from "@repo/protocol/domain/common";4 import { DecisionSubject } from "@repo/protocol/domain/decision";7 unmodified lines12 import { countLint, countWithin } from "./lint-count.ts";13 import type { CountUnreadable } from "./lint-count.ts";14 import { readMetric } from "./metric.ts";15 27-/** A ratchet's number in one territory, as one run measured it. */16 export interface RatchetCount {17 readonly ratchet: RatchetName;18 readonly territory: string;19 readonly count: number;20 }21 34-/**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- */22 export const WHOLE_PROJECT = ".";23 41-/** A territory a count is split by: its name, and the globs of its paths. */24 interface Counted {25 readonly name: string;26 readonly paths: readonly Glob[];27 }28 29 const ALL_PATHS: readonly Glob[] = [Glob.make("**")];30 49-/**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- */31 const named = (32 territories: readonly Territory[],33 territory: string34 ): Counted => ({2 unmodified lines37 Glob.make(territory),38 ],39 });40 63-/** The territories a spec's count is split by. */41 const countedIn = (42 spec: RatchetSpec,43 territories: readonly Territory[]44 ): readonly Counted[] => {5 unmodified lines50 ? [{ name: WHOLE_PROJECT, paths: ALL_PATHS }]51 : territories.map(({ module, paths }) => ({ name: module, paths }));52 };53 77-/**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.55 export const measure = <E, R>(56 spec: RatchetSpec,57 run: (58 command: string31 unmodified lines90 ])91 ),92 });93 126-/**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- */94 export const countLanes = (95 ratchets: readonly RatchetSpec[]96 ): readonly CheckLane[] =>97 Array.dedupeWith(4 unmodified lines102 lane: LaneName.make(name),103 output: "stdout",104 }));105 143-/** A ratchet in a territory: the key a baseline, a count and a raise are kept by. */106 export interface RatchetKey {107 readonly ratchet: RatchetName;108 readonly territory: string;109 }110 149-/** Whether two rows name one ratchet in one territory. */111 export const sameRatchet =112 (one: RatchetKey) =>113 (other: RatchetKey): boolean =>114 one.ratchet === other.ratchet && one.territory === other.territory;115 155-/** The decision a raise waits on. */116 export type RaiseRatchet = Extract<DecisionSubject, { _tag: "RaiseRatchet" }>;117 158-/** What judging an answer's counts gives: its refusals, and the raises it waits on. */118 export interface RatchetJudgement {119 readonly refusals: readonly Weakened[];120 readonly decisions: readonly RaiseRatchet[];121 }122 164-/**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.126 export const judgeRatchets = (input: {127 readonly baselines: readonly RatchetCount[];128 readonly measured: readonly RatchetCount[];129 readonly ask: AskId;40 unmodified linesmodified: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- */1 import { HeldBackResult, LaneResult } from "@repo/protocol/domain/answer";2 import { RunBlock } from "@repo/protocol/domain/run";3 import {4 AreaName,12 unmodified lines17 18 import { diagnose, Diagnosis } from "./classify.ts";19 import type { RunExit } from "./classify.ts";20 28-/**29- * What a job runs on: an exact tree (an answer merged onto main) or a30- * commit (main itself, when an ask opens).31- */21 export const CheckAt = Schema.TaggedUnion({22 Commit: { commit: CommitSha },23 Tree: { tree: TreeSha },24 });25 26 export type CheckAt = typeof CheckAt.Type;27 39-/** The object id a job runs on, whichever kind it is. */28 export const shaOf = (at: CheckAt): string =>29 CheckAt.match(at, {30 Commit: ({ commit }): string => commit,31 Tree: ({ tree }): string => tree,32 });33 46-/**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- */35 export const CheckLane = Schema.Struct({36 command: Schema.NonEmptyString,37 lane: LaneName,38 output: Schema.optionalKey(Schema.Literal("stdout")),3 unmodified lines42 });43 44 export type CheckLane = typeof CheckLane.Type;45 63-/**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`).47 export const HeldBackFile = Schema.Struct({48 area: AreaName,49 content: Schema.Uint8ArrayFromBase64,50 path: RepoPath,51 }).pipe(Schema.encodeKeys({ content: "contentBase64" }));52 53 export type HeldBackFile = typeof HeldBackFile.Type;54 77-/** One sealed check to run: its area, its file, and the command that runs it. */55 export const HeldBackCheck = Schema.Struct({56 area: AreaName,57 command: Schema.NonEmptyString,58 path: RepoPath,59 });60 61 export type HeldBackCheck = typeof HeldBackCheck.Type;62 86-/**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.64 export 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 });71 72 export type HeldBackPart = typeof HeldBackPart.Type;73 103-/**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- */74 export const EnvPlaceholder = Schema.Struct({75 key: EnvKey,76 placeholder: Schema.NonEmptyString,77 });78 79 export type EnvPlaceholder = typeof EnvPlaceholder.Type;80 116-/**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.82 export const EnvProxy = Schema.Struct({83 block: Schema.Boolean,84 host: Schema.NonEmptyString,85 key: EnvKey,3 unmodified lines89 });90 91 export type EnvProxy = typeof EnvProxy.Type;92 135-/**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- */94 export const EnvValue = Schema.Struct({95 key: EnvKey,96 value: Schema.RedactedFromValue(Schema.NonEmptyString),97 });98 99 export type EnvValue = typeof EnvValue.Type;100 147-/**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.102 export 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 === true3 unmodified lines119 );120 121 export type CheckJob = typeof CheckJob.Type;122 183-/**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- */123 export const LaneEvidence = Schema.Struct({124 lane: LaneName,125 signature: Schema.optionalKey(Schema.NonEmptyString),126 weakness: Schema.optionalKey(Schema.Literal("no assertion")),127 });128 129 export type LaneEvidence = typeof LaneEvidence.Type;130 196-/** A lane's evidence, read from its exit where the run happened. */131 export const evidenceFrom = (lane: LaneName, exit: RunExit): LaneEvidence =>132 Diagnosis.$match(diagnose(exit), {133 Blocked: () => ({ lane }),134 Failed: ({ signature }) =>5 unmodified lines140 NoTests: () => ({ lane, weakness: "no assertion" as const }),141 Passed: () => ({ lane }),142 });143 210-/** What a count lane printed: the stdout its count is read from. */144 export const LaneOutput = Schema.Struct({145 lane: LaneName,146 stdout: Schema.String,147 });148 149 export type LaneOutput = typeof LaneOutput.Type;150 218-/**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.152 export const CheckRun = Schema.Struct({153 durationMs: Schema.Int,154 evidence: Schema.Array(LaneEvidence),155 heldBack: Schema.Array(HeldBackResult),2 unmodified lines158 });159 160 export type CheckRun = typeof CheckRun.Type;161 235-/** What a count lane of `run` printed; none when the lane did not ask for it, or did not run. */162 export const outputOf = (163 run: CheckRun,164 lane: LaneName165 ): Option.Option<string> =>1 unmodified line167 Option.fromUndefinedOr(run.outputs?.find((each) => each.lane === lane)),168 ({ stdout }) => stdout169 );170 245-/**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.173 export class CheckRunner extends Context.Service<174 CheckRunner,175 {176 readonly run: (job: CheckJob) => Effect.Effect<CheckRun, VerifierBlocked>;2 unmodified linesmodified: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- */1 import type { LaneOutcome } from "@repo/protocol/domain/answer";2 import type { LaneName } from "@repo/protocol/ids";3 import { Array, Data, Option, Order, pipe, Schema, String } from "effect";4 11-/** How one lane's command ended, as the runner saw it. */5 export 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 }13 23-/**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- */14 export type Diagnosis =15 | { readonly _tag: "Blocked" }16 | { readonly _tag: "Failed"; readonly signature: Option.Option<string> }17 | { readonly _tag: "LoadError" }1 unmodified line19 | { readonly _tag: "Passed" };20 21 export const Diagnosis = Data.taggedEnum<Diagnosis>();22 37-// 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.24 const VitestReport = Schema.Struct({25 numTotalTests: Schema.Finite,26 testResults: Schema.Array(14 unmodified lines41 type VitestReport = typeof VitestReport.Type;42 43 const decodeReport = Schema.decodeUnknownOption(VitestReport);44 60-/** A line that reports a failed assertion: chai's, node's, jest's and bun's `expect`, pytest's `assert`. */45 const ASSERTION =46 /AssertionError|^E\s+assert\b|^(?:error: |Error: )?expect\(|^Snapshot .+ mismatched/u;47 64-/** The details jest and bun print under an `expect(received)` line. */48 const EXPECTATION_DETAIL = /^(?:Expected|Received)\b/u;49 67-/** The output of a run that never reached its tests. */50 const LOAD_ERROR = [51 /Cannot find (?:module|package)/u,52 /ERR_MODULE_NOT_FOUND/u,53 /Failed to load url/u,1 unmodified line55 /\b(?:ModuleNotFound|Import)Error\b/u,56 /Transform failed/u,57 ];58 77-/** The output of a run that found no tests: vitest's, bun's or jest's, pytest's, node's. */59 const 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 ];65 85-/** A line naming a failed test: bun's `(fail)`, pytest's `FAILED`, vitest's `FAIL`. */66 const FAILED_TEST = [67 /^\(fail\) (?<name>.+)$/u,68 /^FAILED (?<name>\S+)/u,69 /^FAIL\s+(?<name>.+)$/u,13 unmodified lines83 const BRACKETED_DURATION = /\s*[[(]\d+(?:\.\d+)?\s?m?s[\])]/gu;84 85 const DURATION = /\b\d+(?:\.\d+)?\s?m?s\b/gu;86 107-/** Without the parts that change between two runs of the same failure. */87 const normalise = (text: string) =>88 text89 .replaceAll(ANSI, "")90 .replaceAll(ADDRESS, "<address>")7 unmodified lines98 99 const signatureOf = (entries: readonly string[]) =>100 Array.dedupe(entries).toSorted(Order.String).join("\n");101 123-/** The first assertion line, with jest's and bun's `Expected:`/`Received:` lines under it. */102 const assertionOf = (lines: readonly string[]) =>103 Option.map(104 Array.findFirstIndex(lines, (line) => ASSERTION.test(line)),105 (at) => {89 unmodified lines195 // the shell's 128+n for a process a signal killed.196 const neverRan = (code: number) =>197 code < 0 || code === 126 || code === 127 || (code > 128 && code < 160);198 221-/**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`).201 export const diagnose = (exit: RunExit): Diagnosis => {202 if (exit.timedOut === true || neverRan(exit.code)) {203 return Diagnosis.Blocked();204 }7 unmodified lines212 onSome: (report) => fromReport(report, exit),213 });214 };215 243-/**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- */217 export const classifyRun = (lane: LaneName, exit: RunExit): LaneOutcome =>218 Diagnosis.$match(diagnose(exit), {219 Blocked: () => "blocked" as const,220 Failed: () => "failed" as const,1 unmodified line222 NoTests: () => "loadError" as const,223 Passed: () => "passed" as const,224 });225 257-/**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.227 export const failureSignature = (exit: RunExit): Option.Option<string> => {228 const diagnosis = diagnose(exit);229 230 return Diagnosis.$is("Failed")(diagnosis)3 unmodified linesmodified: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- */1 import type { ProjectName } from "@repo/protocol/ids";2 import {3 keyOf,4 LaneName,2 unmodified lines7 } from "@repo/protocol/ids";8 import { Context, Option, Schema } from "effect";9 import type { Effect } from "effect";10 19-/**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.12 export const LogRef = Schema.NonEmptyString.pipe(Schema.brand("LogRef"));13 14 export type LogRef = typeof LogRef.Type;15 28-/** One lane's log from one attempt at one answer request. */16 export interface LaneLog {17 readonly project: ProjectName;18 readonly requestId: RequestId;19 readonly lane: LaneName;20 readonly attempt: number;21 readonly text: string;22 }23 37-/**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- */24 export const logRefOf = (log: Omit<LaneLog, "text">): LogRef =>25 LogRef.make(26 `${keyOf(log.project)}/${log.requestId}/${log.lane}#${log.attempt}`27 );28 46-/** A log's name, read back into what it names. */29 const LogName = Schema.TemplateLiteralParser([30 ProjectNameFromKey,31 "/",32 RequestId,2 unmodified lines35 "#",36 Schema.Int,37 ]);38 57-/**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- */40 export const logOfRef = (ref: string): Option.Option<Omit<LaneLog, "text">> =>41 Option.filter(42 Option.map(43 Schema.decodeUnknownOption(LogName)(ref),9 unmodified lines53 54 export 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- */1 import type { RunBlock } from "@repo/protocol/domain/run";2 import { LaneName } from "@repo/protocol/ids";3 import { Array as Arr, Option, Result, Schema } from "effect";4 import { parse } from "yaml";5 6 import { PATH_PLACEHOLDER } from "./kinds.ts";7 15-/** The run block as it travels before decoding. */8 export type RunBlockEncoded = typeof RunBlock.Encoded;9 18-/** One file of a repo, by its path from the root. */10 export interface RepoFile {11 readonly content: string;12 readonly path: string;13 }14 24-/**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- */15 export interface FoundRunBlock {16 readonly run: Partial<RunBlockEncoded>;17 readonly sources: readonly string[];18 }19 35-/** The lane names the finder prefers; any other lane takes its script's name. */20 type Canonical = "build" | "format" | "lint" | "types" | "unit";21 22 const isLaneName = Schema.is(LaneName);23 7 unmodified lines31 tokens.some((token) =>32 flags.some((flag) => token === flag || token.startsWith(`${flag}=`))33 );34 51-// --- What a command is --------------------------------------------------52-35 const SETUP: readonly (readonly string[])[] = [36 ["corepack", "enable"],37 ["npm", "ci"],38 ["npm", "install"],17 unmodified lines56 ["bundle", "install"],57 ["pre-commit", "install-hooks"],58 ];59 78-// Leading `NAME=value` words set the environment; they aren't the command.60 const withoutEnv = (tokens: readonly string[]) => {61 const first = tokens.findIndex((token) => !/^\w+=/u.test(token));62 63 return first === -1 ? [] : tokens.slice(first);7 unmodified lines71 SETUP.some((prefix) => startsWith(tokens, prefix))72 );73 };74 94-// Words that run a tool rather than being one: `npx eslint`, `uv run pytest`.75 const RUNNERS: readonly (readonly string[])[] = [76 ["npx"],77 ["bunx"],78 ["pnpm", "exec"],13 unmodified lines92 ["pnpm"],93 ["yarn"],94 ];95 116-/** Where the tool starts in a command's words, past env and runner words. */96 const toolIndex = (tokens: readonly string[]): number => {97 let at = tokens.length - withoutEnv(tokens).length;98 99 for (8 unmodified lines108 };109 110 const CHECK_FLAGS = ["--check", "-c", "--list-different", "-l"];111 133-/** A tool's words, the lane it checks, and whether these arguments check. */112 const TOOLS: readonly {113 readonly lane: Canonical;114 readonly tool: readonly string[];115 readonly when?: (args: readonly string[]) => boolean;82 unmodified lines198 { lane: "build", tool: ["go", "build"] },199 { lane: "build", tool: ["zig", "build"] },200 ];201 224-/** Script, task and hook names that say their lane outright. */202 const 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 lines213 },214 { lane: "build", names: /^build$/u },215 ];216 240-// Names that are never a check, even when a workflow runs them.217 const NEVER_A_LANE =218 /(?:^|[:-])(?:dev|start|serve|preview|watch|deploy|release|publish|prepare|install|clean|version|fix|docs)(?:$|[:-])/u;219 220 const namedLane = (name: string): Option.Option<Canonical> =>221 Option.fromNullishOr(NAMED.find(({ names }) => names.test(name))?.lane);222 247-/** A name as a lane name: `test:e2e` → `test-e2e`. */223 const asLaneName = (name: string): Option.Option<string> =>224 Option.liftPredicate(225 name.replaceAll(/[^A-Za-z0-9-]+/gu, "-").replaceAll(/^-+|-+$/gu, ""),226 isLaneName227 );228 254-/** A script or task's name as a lane, unless the name says it checks nothing. */229 const scriptLane = (name: string): Option.Option<string> =>230 NEVER_A_LANE.test(name) ? Option.none() : asLaneName(name);231 232 const FIXERS = ["--fix", "--write"];233 260-/** Whether a command, or any command a script chains, rewrites files. */234 const fixes = (body: string) =>235 body.split("&&").some((part) => hasAny(words(part), FIXERS));236 264-/** The lane a tool command checks: `npx eslint .` → `lint`. Fixers check nothing. */237 const toolLane = (command: string): Option.Option<Canonical> => {238 const tokens = words(command);239 const rest = tokens.slice(toolIndex(tokens));240 8 unmodified lines249 )?.lane250 );251 };252 281-// --- Scripts -------------------------------------------------------------282-253 type PackageManager = "bun" | "npm" | "pnpm" | "yarn";254 255 const MANAGERS: readonly PackageManager[] = ["bun", "npm", "pnpm", "yarn"];256 257 const isManager = (word: string | undefined): word is PackageManager =>258 MANAGERS.some((manager) => manager === word);259 290-/** What the repo's root `package.json` says: its scripts and package manager. */260 interface Scripts {261 readonly byName: ReadonlyMap<string, string>;262 readonly manager: Option.Option<PackageManager>;263 }264 296-/**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- */265 const scriptOf = (command: string, scripts: Scripts): Option.Option<string> => {266 const [manager, verb, name] = withoutEnv(words(command));267 268 if (!isManager(manager)) {14 unmodified lines283 ? Option.some(verb)284 : Option.none();285 };286 322-// 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.287 const TASKS: readonly (readonly string[])[] = [288 ["make"],289 ["just"],290 ["task"],16 unmodified lines307 };308 309 const segments = (body: string) => body.split("&&").map((part) => part.trim());310 348-/** A script's body, followed through scripts that only run another script. */311 const bodyOf = (312 name: string,313 scripts: Scripts,314 depth = 012 unmodified lines327 )328 : Option.some(body);329 });330 369-/** How the repo's package manager runs a script: `pnpm run build`, `npm test`. */331 const runScript = (manager: PackageManager, name: string) =>332 manager === "npm" && name === "test" ? "npm test" : `${manager} run ${name}`;333 373-// --- One test file ------------------------------------------------------374-334 const insertBefore = (335 tokens: readonly string[],336 marker: string,337 added: readonly string[]4 unmodified lines342 ? [...tokens, ...added]343 : [...tokens.slice(0, at), ...added, ...tokens.slice(at)];344 };345 387-/** A `go test` package pattern: `.`, `./pkg`, `./...`, `example.com/m/...`. */346 const isGoPackages = (arg: string) =>347 arg === "." ||348 arg.startsWith("./") ||349 arg.startsWith("../") ||350 arg.includes("...");351 394-/**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.354 const 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 lines377 return write(...rest, PATH_PLACEHOLDER);378 }379 380 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));382 383 return write("go", "test", ...flags, `"./$(dirname ${PATH_PLACEHOLDER})"`);384 }9 unmodified lines394 395 return Option.none();396 };397 444-// --- Reading sources ----------------------------------------------------445-446-/** A command a source runs, with the name the source gives it, if any. */398 interface Step {399 readonly command: string;400 readonly name: Option.Option<string>;401 }402 452-/** A lane a source offers: its command, and the file its test runner was read from. */403 interface 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 }410 461-/** One source file, read: its setup commands and lanes, or why it was skipped. */411 interface Read {412 readonly offers: readonly Offer[];413 readonly path: string;414 readonly setup: readonly string[];415 }416 417 const PACKAGE_JSON = "package.json";418 470-// An error's message on one line, for a `skipped …` source.419 const oneLine = (message: string) =>420 message421 .split("\n")422 .map((line) => line.trim())423 .filter(Boolean)424 .join(" ");425 478-/**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).427 const readYaml = <A>(428 schema: Schema.ConstraintDecoder<A>,429 content: string430 ): Result.Result<A, string> =>8 unmodified lines439 Result.mapError(decoded, (issue) => oneLine(issue.message))440 )441 );442 498-// A shell line split into the commands it chains; comments and blank lines499-// dropped, `\` continuations joined.443 const shellCommands = (text: string): readonly string[] =>444 text445 .replaceAll("\\\n", " ")446 .split("\n")94 unmodified lines541 "commit",542 "pre-commit",543 ]);544 602-/** pre-commit's hook ids that name a canonical lane. */545 const HOOKS: ReadonlyMap<string, Canonical> = new Map([546 ["ruff", "lint"],547 ["ruff-check", "lint"],548 ["flake8", "lint"],16 unmodified lines565 const isWorkflow = (file: RepoFile) => workflowFile.test(file.path);566 567 const huskyFile = /^\.husky\/pre-(?:commit|push)$/u;568 627-// Every name lefthook reads its config from, as the judge closure lists them.569 const LEFTHOOK: ReadonlySet<string> = new Set([570 "lefthook.yml",571 "lefthook.yaml",572 ".lefthook.yml",19 unmodified lines592 ["yarn.lock", "yarn"],593 ["package-lock.json", "npm"],594 ];595 655-// --- Putting it together ------------------------------------------------656-596 const offerFromStep = (597 step: Step,598 path: string,599 scripts: Scripts17 unmodified lines617 );618 619 const fallback = Option.flatMap(ownName, scriptLane);620 682- // 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 lines684 setup: [],685 }))686 );687 750-// Root scripts that name or run a check become lanes, run the repo's way.688 const 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 lines709 path: PACKAGE_JSON,710 setup: [],711 });712 776-/** Lanes by name, in the order found, each with its offer. */713 type Lanes = ReadonlyMap<string, Offer>;714 715 // 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 lines763 } as const satisfies Record<PackageManager, string>;764 765 const skip = (path: string, reason: string) => `skipped ${path}: ${reason}`;766 831-/** Each file read, and a `skipped …` line for each one that wasn't. */767 const readEach = (768 files: readonly RepoFile[],769 read: (file: RepoFile) => Result.Result<Read, string>770 ) => {6 unmodified lines777 skipped: Arr.getFailures(results),778 };779 };780 846-/** The root `package.json`'s scripts and package manager, or why it can't be read. */781 const readPackage = (files: readonly RepoFile[]) =>782 Option.map(783 Option.fromNullishOr(files.find(fileNamed(PACKAGE_JSON))),784 (file) =>14 unmodified lines799 )800 ),801 });802 869-/** Setup commands with the file each came from, deduplicated, in order. */803 type Setup = readonly (readonly [command: string, path: string])[];804 805 // 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 lines815 816 return [...new Map([...found, ...hooks])];817 };818 886-/** The one-file test command, and where its runner was read. */819 const 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 );826 895-/**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.829 export 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 lines858 );859 860 const hooks = [...lefthook.reads, ...husky, ...preCommit.reads];861 942- // 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 linesmodified: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.3 import type { HeldBackResult } from "@repo/protocol/domain/answer";4 import type { AreaName, SuiteRoot } from "@repo/protocol/ids";5 11-/** How one held-back run ended: its area, its exit code, and whether it ran out of time. */6 export interface HeldBackExit {7 readonly area: AreaName;8 readonly code: number;9 readonly timedOut: boolean;6 unmodified lines16 * one bit per check.17 */18 const passed = ({ code, timedOut }: HeldBackExit) => code === 0 && !timedOut;19 26-/**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.22 export const areaBits = ({23 areas,24 exits,25 suite,15 unmodified linesmodified: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- */1 import { Brand } from "@repo/brand";2 import { Glob } from "@repo/protocol/domain/common";3 import type { Policy } from "@repo/protocol/domain/policy";4 import type { RunBlock } from "@repo/protocol/domain/run";3 unmodified lines8 9 import { findRunBlock } from "./finder.ts";10 import type { RepoFile } from "./finder.ts";11 19-/** A closure glob that starts with this takes paths back out of the closure. */12 const EXCLUDE = "!";13 22-/**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- */14 export const hookConfigGlobs: readonly Glob[] = [15 ".claude/settings*.json",16 ".cursor/hooks.json",17 ".codex/hooks.json",12 unmodified lines30 ".husky/**",31 ".pre-commit-config.yaml",32 ].map((glob) => Glob.make(glob));33 48-/**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- */34 export const policyFileGlobs: readonly Glob[] = [35 "**/bunfig.toml",36 "pnpm-workspace.yaml",37 "**/turbo.json",8 unmodified lines46 "**/.prettierrc*",47 "**/prettier.config.*",48 ].map((glob) => Glob.make(glob));49 71-/**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- */50 export const defaultJudgeGlobs: readonly Glob[] = [51 ...[52 `${Brand.configDir}/**`,53 "**/.env.schema",23 unmodified lines77 ];78 79 const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");80 108-// 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.81 const matchSegment = (pattern: string, text: string): boolean => {82 let at = 0;83 let from = 0;84 let star = -1;49 unmodified lines134 matchSegments(restGlobs, restParts)135 );136 };137 167-/**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.139 export const matchGlob = (glob: string, path: string): boolean =>140 matchSegments(141 withoutDotSlash(glob).split("/"),142 withoutDotSlash(path).split("/")143 );144 180-/**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- */145 export 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 lines163 164 const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>165 Predicate.isObject(value) && !isJsonArray(value);166 207-// The index just past the string literal whose quote is at `at`; an208-// unclosed string runs to the end.167 const stringEnd = (text: string, at: number): number => {168 const quote = text.charAt(at);169 let next = at + 1;170 3 unmodified lines174 175 return Math.min(next + 1, text.length);176 };177 220-/** Where the comment that opens at `at` ends, if one opens there. */178 type CommentEnd = (text: string, at: number) => Option.Option<number>;179 223-// The index just past the comment that opens at `at`, if one does.180 const commentEnd: CommentEnd = (text, at) => {181 if (text.startsWith("//", at)) {182 const end = text.indexOf("\n", at);183 8 unmodified lines192 193 return Option.none();194 };195 240-// The index just past the `#` comment (TOML's) that opens at `at`, if one does.196 const hashCommentEnd: CommentEnd = (text, at) => {197 if (text.charAt(at) !== "#") {198 return Option.none();199 }4 unmodified lines204 };205 206 const QUOTES = new Set(['"', "'", "`"]);207 253-/**254- * Text with each comment outside a string as one space: `//` and `/* *\/`255- * ones by default (JavaScript, JSONC), or those `opens` finds.256- */208 const withoutComments = (209 text: string,210 opens: CommentEnd = commentEnd211 ): string => {20 unmodified lines232 };233 234 const isSpace = (char: string) => /\s/u.test(char);235 285-// Whether the next character after `at` that isn't space closes a bracket.236 const closesNext = (text: string, at: number) => {237 let peek = at;238 239 while (isSpace(text.charAt(peek))) {2 unmodified lines242 243 return peek < text.length && "]}".includes(text.charAt(peek));244 };245 296-/** JSON text with each comma that closes nothing (`[1, 2,]`) left out. */246 const withoutTrailingCommas = (text: string): string => {247 let kept = "";248 let at = 0;249 7 unmodified lines257 258 return kept;259 };260 312-/**313- * JSONC (tsconfig, `.oxlintrc.json`, harness settings) read as JSON: its314- * comments and trailing commas are dropped first. Pure and dependency-free.315- */261 const decodeJsonc = (text: string): Option.Option<Schema.Json> =>262 decodeJson(withoutTrailingCommas(withoutComments(text)));263 264 const UNREADABLE =2 unmodified lines267 const UNREAD = "not among the files read; judged unread";268 269 const dirname = (path: string) => path.split("/").slice(0, -1).join("/");270 326-// `a/b` joined with `../c` is `c`; `..` above the root leaves the repo.271 const join = (dir: string, relative: string): Option.Option<string> => {272 const parts: string[] = dir === "" ? [] : dir.split("/");273 274 for (const part of relative.split("/")) {16 unmodified lines291 specifier.startsWith("../");292 293 const isPackageJson = (path: string) => matchGlob("**/package.json", path);294 351-/**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- */295 interface Tree {296 readonly paths: ReadonlySet<string>;297 readonly read: (path: string) => string | undefined;298 }2 unmodified lines301 paths: new Set(contents.keys()),302 read: (path) => contents.get(path),303 });304 367-/** Each workspace package's name and folder, from the manifests given. */305 const workspacesOf = (tree: Tree): ReadonlyMap<string, string> =>306 new Map(307 [...tree.paths]308 .filter((path) => isPackageJson(path))10 unmodified lines319 )320 )321 );322 386-/**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- */323 const inWorkspace = (324 specifier: string,325 workspaces: ReadonlyMap<string, string>326 ): Option.Option<{ readonly dir: string; readonly rest: string }> =>12 unmodified lines339 const configFile = (path: string, paths: ReadonlySet<string>) =>340 [path, `${path}.json`].find((candidate) => paths.has(candidate)) ??341 (path.endsWith(".json") ? path : `${path}.json`);342 411-/**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- */343 const resolveExtends = (344 from: string,345 specifier: string,346 paths: ReadonlySet<string>,17 unmodified lines364 365 return [value ?? []].flat().filter(Predicate.isString);366 };367 441-/** A path the walk could not read past, and why. */368 const note = (path: string, reason: string) => `${path}: ${reason}`;369 370 const chainFrom = (371 start: string,25 unmodified lines397 398 return { chain: chain.map((path) => RepoPath.make(path)), notes };399 };400 475-/**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- */401 export const tsconfigChain = (402 start: RepoPath,403 files: ReadonlyMap<string, string>404 ): {4 unmodified lines409 410 return chainFrom(start, tree, workspacesOf(tree));411 };412 494-/** A token of JavaScript or JSON text, its comments dropped. */413 interface Token {414 readonly kind: "mark" | "string" | "word";415 readonly text: string;416 }417 418 const isWordChar = (char: string) => /[\w$]/u.test(char);419 502-// A string literal's value; a template with `${…}` in it is no one value.420 const literal = (quote: string, body: string): Token =>421 quote === "`" && body.includes("${")422 ? { kind: "mark", text: quote }423 : { kind: "string", text: body.replaceAll(/\\(?<char>.)/gu, "$<char>") };424 508-/**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.426 const tokensOf = (427 source: string,428 comments: CommentEnd = commentEnd429 ): readonly Token[] => {23 unmodified lines453 454 return tokens;455 };456 545-// Words a module path follows as a call's first argument: `import("…")`,546-// `require("…")`, `require.resolve("…")`, `new URL("…", import.meta.url)`.457 const LOADERS = new Set(["URL", "import", "require", "resolve"]);458 549-/** The module specifiers source text imports, exports from or requires. */459 const 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 lines478 ? [after.text]479 : [];480 });481 573-// Marks that open and close a nesting level in source text.482 const OPENS = new Set(["(", "[", "{"]);483 484 const CLOSES = new Set([")", "]", "}"]);485 578-/** What a `jsPlugins` key in source text holds, as far as its text says. */486 interface 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 }490 586-// The strings of one `jsPlugins: [...]` array that starts at token `at`.491 const listedAt = (tokens: readonly Token[], at: number): readonly string[] => {492 const found: string[] = [];493 let depth = 0;494 20 unmodified lines515 516 return found;517 };518 615-/**616- * The `jsPlugins` arrays of an oxlint config's source, read as text: a key's617- * (`jsPlugins: [...]`) or a variable's (`const jsPlugins = [...]`).618- */519 const 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 lines531 .flatMap((at) => listedAt(tokens, at)),532 };533 };534 635-/** The `jsPlugins` of a JSON oxlint config: strings, or `{specifier}` objects. */535 const jsPluginsInJson = (config: Schema.Json): readonly string[] => {536 const list = isJsonObject(config) ? config.jsPlugins : undefined;537 538 return (list !== undefined && isJsonArray(list) ? list : []).flatMap(10 unmodified lines549 };550 551 const basename = (path: string) => path.split("/").at(-1) ?? path;552 654-// `.oxlintrc.json`, `.oxlintrc`, `.eslintrc.json`: configs written as JSONC.553 const isJsonConfig = (path: string) =>554 /\.jsonc?$/u.test(path) || basename(path) === ".oxlintrc";555 658-/** The lint configs whose plugins and imports judge: oxlint's and eslint's. */556 const lintConfigGlobs = [557 "**/oxlint.config.*",558 "**/oxlint.*.config.*",559 "**/.oxlintrc*",4 unmodified lines564 565 const isLintConfig = (path: string) =>566 lintConfigGlobs.some((glob) => matchGlob(glob, path));567 671-/** What one lint config names: its plugins, and the modules it imports or extends. */568 interface LintNames {569 readonly imports: readonly string[];570 readonly notes: readonly string[];571 readonly plugins: readonly string[];31 unmodified lines603 plugins: plugins.specifiers,604 };605 };606 711-// Relative specifiers, as paths from the repo root.607 const relativeFrom = (608 from: string,609 specifiers: readonly string[]610 ): readonly RepoPath[] =>1 unmodified line612 .filter(isRelative)613 .flatMap((specifier) => Option.toArray(join(dirname(from), specifier)))614 .map((path) => RepoPath.make(path));615 721-/**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- */616 export const jsPluginSpecifiers = (config: RepoFile): readonly RepoPath[] =>617 relativeFrom(config.path, lintNames(config).plugins);618 731-/**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- */619 export const eslintLocalPlugins = (config: RepoFile): readonly RepoPath[] =>620 relativeFrom(config.path, lintNames(config).imports);621 622 const MODULE_EXTENSIONS = [25 unmodified lines648 649 return (TWINS.get(path.slice(dot)) ?? []).map((ext) => `${stem}${ext}`);650 };651 769-/**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- */652 interface 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 lines699 globs: [path, `${path}.*`, `${path}/**`],700 };701 };702 828-// 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.703 const wordsOf = (command: string): readonly string[] =>704 command705 .split(/[\s;&|()<>`]+/u)706 .map((word) =>2 unmodified lines709 .flatMap((word) => [word, word.slice(word.indexOf("=") + 1)])710 .flatMap((word) => [word, word.replace(/^\/+/u, "")])711 .map(withoutDotSlash);712 842-/**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.715 const dependencyFileGlobs = [716 "**/package.json",717 "**/bun.lock",718 "**/bun.lockb",14 unmodified lines733 734 const isDependencyFile = (path: string) =>735 dependencyFileGlobs.some((glob) => matchGlob(glob, path));736 870-/**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- */737 export const commandScripts = (738 commands: readonly string[],739 files: ReadonlySet<string>740 ): readonly RepoPath[] =>11 unmodified lines752 /\.(?:ba|z)?sh$/u.test(path) || !hasExtension(path);753 754 const CODE = /\.[cm]?[jt]sx?$/u;755 895-// 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.756 const runsFrom = (757 path: string,758 content: string,759 paths: ReadonlySet<string>9 unmodified lines769 770 return isShell(path) ? commandScripts(content.split("\n"), paths) : [];771 };772 914-/**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- */773 const walkImports = (774 seeds: readonly string[],775 tree: Tree,776 follows: (path: string) => boolean = () => true20 unmodified lines797 798 return globs;799 };800 949-/** The lint sources a repo's lint configs name, and where they stand. */801 interface 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 }806 957-/**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- */807 const lintSources = (808 tree: Tree,809 workspaces: ReadonlyMap<string, string>810 ): LintSources => {32 unmodified lines843 notes: named.flatMap((config) => config.notes),844 };845 };846 1002-// A whole folder (`a/b/**`) the closure holds makes any other glob or path1003-// under it redundant.847 const 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 lines863 864 const TEST_FILE =865 /(?:^|\/)(?:__fixtures__|__tests__|tests?)\/|\.(?:spec|test)\.[cm]?[jt]sx?$/u;866 1024-// A path without its file's extension: `lint/plugin.mjs` is `lint/plugin`.867 const stemOf = (path: string) =>868 hasExtension(path) ? path.slice(0, path.lastIndexOf(".")) : path;869 1028-/** A plugin as a test can name it: its folder, or its file with or without extension. */870 interface PluginName {871 readonly folder: boolean;872 readonly path: string;873 }2 unmodified lines876 plugin.folder877 ? candidate === plugin.path || candidate.startsWith(`${plugin.path}/`)878 : stemOf(candidate) === stemOf(plugin.path);879 1039-// 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).880 const readingsOf = (from: string, text: string): readonly string[] => {881 if (text.startsWith("../")) {882 return Option.toArray(join(dirname(from), text));883 }4 unmodified lines888 ? [...Option.toArray(join(dirname(from), text)), rooted]889 : [rooted];890 };891 1053-/** `ruleFixtures`, reading a test file's text only when some plugin may be named in it. */892 const fixturesOf = (893 pluginPaths: readonly string[],894 files: readonly string[],895 read: Tree["read"]6 unmodified lines902 path: plugin,903 }904 );905 1068- // 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);908 909 return folder === ""910 ? []911 : FIXTURE_FOLDERS.map((name) => `${folder}/${name}/**`);912 });913 1077- // 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)));915 916 const naming = files.filter((path) => {917 if (plugins.length === 0 || !TEST_FILE.test(path)) {21 unmodified lines939 .toSorted()940 .map((glob) => Glob.make(glob));941 };942 1107-/**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.945 export 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));951 1122-// 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`.952 const COMMAND_KEYS = new Set([953 "args",954 "bash",955 "command",3 unmodified lines959 "run",960 "script",961 ]);962 1136-// Every string under a command key, at any depth of a JSON or YAML value.963 const commandsIn = (964 value: Schema.Json,965 underKey: boolean966 ): readonly string[] => {13 unmodified lines980 };981 982 const decodeAnyJson = Schema.decodeUnknownOption(Schema.Json);983 1158-// YAML that `yaml` can't parse, or that holds a value JSON can't, is None.984 const 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 );990 1166-/** What one hook config runs, as command lines, and why it could not be read. */991 interface HookCommands {992 readonly commands: readonly string[];993 readonly notes: readonly string[];994 }2 unmodified lines997 commands: [],998 notes: [note(path, reason)],999 });1000 1177-/**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- */1001 const hookCommands = (hook: RepoFile): HookCommands => {1002 const { content, path } = hook;1003 1004 if (/\.jsonc?$/u.test(path)) {24 unmodified lines1029 1030 return { commands: isShell(path) ? content.split("\n") : [], notes: [] };1031 };1032 1214-/**1215- * The hook configs among the files, the scripts their commands name, and1216- * what those scripts and code plugins (pi, OpenCode, Amp) import.1217- */1033 const hookSources = (tree: Tree, sorted: readonly string[]) => {1034 const configs = sorted.filter((path) =>1035 hookConfigGlobs.some((glob) => matchGlob(glob, path))1036 );16 unmodified lines1053 };1054 1055 const SCRIPTS = "#/scripts";1056 1242-/**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- */1057 export 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 }1062 1253-/**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.1065 const checkScripts = (1066 scripts: readonly string[],1067 tree: Tree1068 ): readonly string[] =>4 unmodified lines1073 ? []1074 : walkImports([script], tree, (path) => path.startsWith(`${folder}/`));1075 });1076 1271-/** Every command a run block runs. */1077 const commandsOf = (run: RunBlock): readonly string[] =>1078 [run.setup, run.doctor, run.test, ...Object.values(run.checks)].filter(1079 Predicate.isNotUndefined1080 );1081 1277-/** `judgeClosure` over a tree, for run commands given as text. */1082 const closureOf = (commands: readonly string[], tree: Tree): JudgeClosure => {1083 const { paths } = tree;1084 const sorted = [...paths].toSorted();1085 const workspaces = workspacesOf(tree);43 unmodified lines1129 1130 return notes.length === 0 ? closure : { ...closure, notes };1131 };1132 1329-/**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- */1133 export const judgeClosure = (1134 run: RunBlock,1135 files: readonly RepoFile[]1136 ): JudgeClosure =>12 unmodified lines1149 .slice(1)1150 .split("/")1151 .map((token) => token.replaceAll("~1", "/").replaceAll("~0", "~"));1152 1361-// One step down a JSON value: an object's own key, or an array's index.1153 const childAt = (1154 value: Schema.Json,1155 token: string1156 ): Option.Option<Schema.Json> => {20 unmodified lines1177 1178 return value;1179 };1180 1390-// 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.1181 const read = (1182 file: RepoFile | undefined,1183 target: string,1184 tokens: readonly string[]4 unmodified lines1189 onNone: () => Option.some(Result.fail(file.content)),1190 onSome: (json) => Option.map(valueAt(json, tokens), Result.succeed),1191 });1192 1404-/**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- */1193 export const touchedPointers = (1194 closure: Policy["judge"],1195 before: RepoFile | undefined,1196 after?: RepoFile8 unmodified lines1205 read(after, target, tokens)1206 );1207 });1208 1427-// ------------------------------------------------------------ what it reads1428-1429-/** 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.1210 export const MAX_FACT_BYTES = 256 * 1024;1211 1432-/** One file of a commit, as a listing gives it: its path, and its size in bytes when the listing knows it. */1212 export interface ListedFile {1213 readonly path: string;1214 readonly size?: number;1215 }1216 1438-/** One file's bytes, as a reader gives them back. */1217 export interface ReadFile {1218 readonly bytes: Uint8Array;1219 readonly path: string;1220 }1221 1444-/** One file as the finder and the judge closure are handed it. */1222 export interface JudgeInput {1223 readonly content: string;1224 readonly path: RepoPath;1225 }1226 1450-/** The folders whose files the run-block finder reads, beside the root's. */1227 const CI_FOLDERS: ReadonlySet<string> = new Set([1228 ".github/workflows",1229 ".forgejo/workflows",1230 ".husky",1231 ]);1232 1457-/**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- */1233 const isSeed = (path: string) =>1234 dirname(path) === "" ||1235 CI_FOLDERS.has(dirname(path)) ||1236 path.startsWith(`${Brand.configDir}/`);1237 1467-/** The commands a found run block runs. */1238 const foundCommands = (files: readonly RepoFile[]): readonly string[] => {1239 const { run } = findRunBlock(files);1240 1241 return [3 unmodified lines1245 ...Object.values(run.checks ?? {}),1246 ].filter(Predicate.isNotUndefined);1247 };1248 1479-/**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.1251 const judgeReads = (1252 listed: readonly ListedFile[],1253 texts: ReadonlyMap<string, string>1254 ): readonly string[] => {37 unmodified lines1292 1293 return [...wanted].toSorted();1294 };1295 1535-/**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- */1296 export const judgeInputs = <E, R>(1297 listed: readonly ListedFile[],1298 readAll: (1299 paths: readonly string[]38 unmodified linesmodified: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- */1 import { CheckSpec } from "@repo/protocol/domain/check";2 import type { RatchetSpec } from "@repo/protocol/domain/check";3 import { Command } from "@repo/protocol/domain/common";4 import type { CheckKind } from "@repo/protocol/domain/kind";1 unmodified line6 import { CheckVersion, LaneName } from "@repo/protocol/ids";7 import { Option, Predicate } from "effect";8 import type { Schema } from "effect";9 14-/** The placeholder a run block's `test` holds for the one check file it runs. */10 export const PATH_PLACEHOLDER = "{path}";11 17-/** The check kind a check is of, as an ask kind names it: `RedThenGreen` → `redThenGreen`. */12 export const checkKindOf = (spec: CheckSpec): CheckKind =>13 CheckSpec.match(spec, {14 LintToZero: (): CheckKind => "lintToZero",15 Migrate: (): CheckKind => "migrate",1 unmodified line17 RedThenGreen: (): CheckKind => "redThenGreen",18 SymbolAbsent: (): CheckKind => "symbolAbsent",19 });20 27-// Bare when the shell would read it as one word, single-quoted otherwise.21 const shellWord = (path: string) =>22 /^[\w./@+-]+$/u.test(path) ? path : `'${path.replaceAll("'", `'\\''`)}'`;23 24 const declared = (1 unmodified line26 name: string27 ): Option.Option<RatchetSpec> =>28 Option.fromNullishOr(ratchets.find((ratchet) => ratchet.name === name));29 37-/**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- */30 export const commandFor = (31 spec: CheckSpec,32 run: RunBlock,33 ratchets: readonly RatchetSpec[] = []97 unmodified lines131 132 return hash.toString(16).padStart(16, "0");133 };134 150-/**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.137 export const checkVersion = (138 spec: CheckSpec,139 sdkVersion: string,140 run: RunBlock,22 unmodified linesmodified: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.2 import { WeakCheck } from "@repo/protocol/refusal";3 import { Array, Effect, Option, pipe, Predicate, Result, Schema } from "effect";4 import { Node, Project, ts } from "ts-morph";5 import type { ImportDeclaration, SourceFile } from "ts-morph";2 unmodified lines8 import type { RepoFile } from "./finder.ts";9 import { matchGlob } from "./judge.ts";10 import type { RunEvidence } from "./red-first.ts";11 25-/** The null answer could not be made: a file that does not parse, or nothing to stub. */12 export class NullAnswerFailed extends Schema.TaggedError<NullAnswerFailed>()(13 "NullAnswerFailed",14 { path: Schema.String, reason: Schema.String }15 ) {}16 31-/** The part of an ask's territory the null answer reads. */17 export 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 }21 39-/** A replacement of `[start, end)` in one file's text. */22 interface Edit {23 readonly end: number;24 readonly start: number;25 readonly text: string;26 }27 46-/** A body that returns nothing, typed to fit any declared return type. */28 const NULL_BODY = "{ return undefined as never; }";29 49-/** An arrow's expression body that returns nothing. */30 const NULL_EXPRESSION = "undefined as never";31 32 const SOURCE = /\.(?:[cm]?ts|tsx)$/u;33 34 const DECLARATION = /\.d\.[cm]?ts$/u;35 56-/** A TypeScript source the codemod reads (declaration files hold no bodies). */36 const isSource = (path: string) => SOURCE.test(path) && !DECLARATION.test(path);37 38 const EXCLUDE = "!";39 5 unmodified lines45 (glob) =>46 glob.startsWith(EXCLUDE) && matchGlob(glob.slice(EXCLUDE.length), path)47 );48 70-// The in-memory project's files sit under `/`, at their repo paths.49 const ROOT = "/";50 51 const placed = (path: string) => `${ROOT}${path}`;52 21 unmodified lines74 75 const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>76 Predicate.isObject(value) && !isJsonArray(value);77 100-/** Every string an `exports` field leads to, nested conditions included. */78 const exportTargets = (value: Schema.Json | undefined): readonly string[] => {79 if (value === undefined || value === null) {80 return [];81 }8 unmodified lines90 91 return isJsonObject(value) ? Object.values(value).flatMap(exportTargets) : [];92 };93 117-/** What a manifest exports: its `exports`, or its `main` when it has none, as Node reads a package. */94 const targetsOf = ({95 exports,96 main,97 }: typeof Manifest.Type): readonly string[] =>2 unmodified lines100 : exportTargets(exports);101 102 const PATTERN = "*";103 128-/**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- */104 const targetPaths = (105 target: string,106 paths: readonly string[]107 ): readonly string[] => {22 unmodified lines130 131 const joined = (folder: string, path: string) =>132 folder === "" ? path : `${folder}/${path}`;133 163-/** The folders from `path`'s own up to the root (`""`). */134 const foldersAbove = (path: string): readonly string[] => {135 const folders: string[] = [];136 let folder = folderOf(path);137 4 unmodified lines142 143 return [...folders, ""];144 };145 176-/**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- */146 const manifestEntries = (147 files: readonly RepoFile[],148 territory: NullAnswerTerritory149 ): readonly string[] => {35 unmodified lines185 Array.dedupe186 );187 };188 224-/** A function-like node's body, as returning nothing. */189 const bodyEdit = (body: Node | undefined): readonly Edit[] => {190 if (body === undefined) {191 return [];192 }6 unmodified lines199 },200 ];201 };202 239-/** An expression without the parentheses and type assertions around it. */203 const unwrapped = (node: Node): Node =>204 Node.isParenthesizedExpression(node) ||205 Node.isAsExpression(node) ||206 Node.isSatisfiesExpression(node)207 ? unwrapped(node.getExpression())208 : node;209 247-/** The edits that make one exported declaration return nothing. */210 const stubsOf = (node: Node): readonly Edit[] => {211 if (212 Node.isFunctionDeclaration(node) ||213 Node.isFunctionExpression(node) ||25 unmodified lines239 240 return [];241 };242 281-/** A file's text with the edits made, from its last edit to its first. */243 const edited = (text: string, edits: readonly Edit[]) => {244 const lastFirst = Array.dedupeWith(245 edits,246 (left, right) => left.start === right.start7 unmodified lines254 255 return result;256 };257 297-/** The declarations a file exports that it declares itself. */258 const ownExports = (file: SourceFile): readonly Node[] =>259 [...file.getExportedDeclarations().values()]260 .flat()261 .filter((node) => node.getSourceFile() === file);262 303-/** A name a stand-in can be declared as (not a string-literal import name). */263 const IDENTIFIER = /^[A-Za-z_$][\w$]*$/u;264 265 const DEFAULT = "default";266 308-/** A stand-in for a name the territory does not have yet: it returns nothing too. */267 const standIn = (name: string) =>268 `export ${name === DEFAULT ? "default function " : `function ${name}`}(..._args: readonly unknown[]): never ${NULL_BODY}`;269 312-/** A file's text with stand-ins for `names` written after it. */270 const withStandIns = (text: string, names: readonly string[]) => {271 const lines = names.map(standIn).join("\n");272 273 if (text === "") {11 unmodified lines285 [/\.mjs$/u, ".mts"],286 [/\.cjs$/u, ".cts"],287 ] as const;288 332-/** The repo path a relative import names, when no file answers it yet. */289 const intendedPath = (importer: string, specifier: string) => {290 const segments: string[] = [];291 292 for (const segment of [17 unmodified lines310 311 return SOURCE.test(path) ? path : `${path}.ts`;312 };313 358-/** What an import asks for at run time: its default and its value names. */314 const valueNamesOf = (declaration: ImportDeclaration): readonly string[] =>315 declaration.isTypeOnly()316 ? []317 : [4 unmodified lines322 .map((specifier) => specifier.getName())323 .filter((name) => IDENTIFIER.test(name)),324 ];325 371-/**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- */326 const homeOf = (327 territory: NullAnswerTerritory,328 target: SourceFile329 ): Option.Option<SourceFile> =>8 unmodified lines338 Option.filter((file) => inTerritory(territory, repoPathOf(file)))339 )340 );341 392-/**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- */342 const wantedNames = (343 project: Project,344 territory: NullAnswerTerritory345 ): ReadonlyMap<string, readonly string[]> => {43 unmodified lines389 390 const messageOf = (cause: unknown) =>391 cause instanceof Error ? cause.message : globalThis.String(cause);392 449-/**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- */393 const stubbedContents = (394 files: readonly RepoFile[],395 territory: NullAnswerTerritory,396 entryPaths: readonly string[]66 unmodified lines463 464 return Result.succeed(contents);465 };466 528-/**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.469 export const nullAnswer = (470 files: readonly RepoFile[],471 territory: NullAnswerTerritory472 ): Effect.Effect<readonly RepoFile[], NullAnswerFailed> =>48 unmodified lines521 ...added,522 ];523 });524 607-/**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- */525 export const nullAnswerVerdict = (run: RunEvidence): Option.Option<WeakCheck> =>526 Diagnosis.$match(diagnose(run.exit), {527 Blocked: () => Option.none(),528 Failed: () => Option.none(),4 unmodified linesmodified: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.3 import type { RunBlock } from "@repo/protocol/domain/run";4 import type { AreaName, EnvKey, LaneName } from "@repo/protocol/ids";5 import { Data, Hash, Option } from "effect";6 22-/** A lane as the `Run` phase runs it. */7 export interface PlannedLane {8 readonly lane: LaneName;9 readonly command: string;10 }25 unmodified lines36 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 }42 43 const DEFAULT_IMAGE = "checker:default";44 62-/**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- */46 const snapshotKey = (47 run: RunBlock,48 command: string,49 egress: readonly string[],8 unmodified lines58 59 return `setup:${lockfileHash}:${setupHash}`;60 };61 82-/** The phases the Checker runs for one job, in order. */62 export const phasePlan = ({63 heldBack,64 lanes,65 lockfileHash,31 unmodified linesmodified: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.4 import type { LaneName } from "@repo/protocol/ids";5 import { NotRedFirst, WeakCheck } from "@repo/protocol/refusal";6 import { Data, Option, Result } from "effect";7 8 import type { CheckRun } from "./check-runner.ts";9 import { diagnose, Diagnosis } from "./classify.ts";10 import type { RunExit } from "./classify.ts";11 15-/** One run of an ask's check on main. */12 export interface RunEvidence {13 readonly lane: LaneName;14 readonly exit: RunExit;15 }16 21-/** How the check fails on main, the same both times. */17 export interface RedSignature {18 readonly signature: string;19 readonly lane: LaneName;20 }21 27-/** What one run says about the check, for comparing it with the other. */22 type Reading =23 | { readonly _tag: "Red"; readonly signature: string }24 | { readonly _tag: "NoTests" }25 | { readonly _tag: "NotRed" };40 unmodified lines66 ? Result.succeed({ lane, signature: first.signature })67 : Result.fail(new NotRedFirst({}));68 };69 76-/**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- */70 export 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({}));77 90-/**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.79 export const redFirstOfRuns = (80 [first, second]: readonly [CheckRun, CheckRun],81 lane: LaneName82 ): Result.Result<RedSignature, NotRedFirst | WeakCheck> =>1 unmodified linemodified: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.3 import { Array, Option, pipe } from "effect";4 10-/**11- * A shape of check that passes whatever the answer does, as `WeakCheck`'s12- * `weakness` names it.13- */5 export type Weakness =6 | "self-referential"7 | "constant pin"8 | "absence-only"9 | "mock-only"10 | "fixture-asserts-fixture";11 21-/**22- * The check file as an ask carries it: its repo path, which places its23- * relative imports, and its source.24- */12 export interface CheckFile {13 readonly path: string;14 readonly content: string;15 }16 30-/** One `expect(subject).matcher(expected)` in the check, as source text. */17 interface Expectation {18 readonly subject: string;19 readonly negated: boolean;20 readonly matcher: string;21 readonly expected: string;22 }23 38-/** The check's source twice: without comments, and with string contents blanked too. */24 interface Source {25 readonly text: string;26 readonly masked: string;27 }28 29 const QUOTES = new Set(['"', "'", "`"]);30 46-/** The index just past the string literal that opens at `start`. */31 const stringEnd = (source: string, start: number) => {32 const quote = source[start];33 let at = start + 1;34 5 unmodified lines40 };41 42 const blank = (text: string) => text.replaceAll(/[^\n]/gu, " ");43 60-/**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`.46 const read = (source: string): Source => {47 const text: string[] = [];48 const masked: string[] = [];49 let at = 0;2 unmodified lines52 const pair = source.slice(at, at + 2);53 const char = source[at] ?? "";54 55 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 lines77 78 return { masked: masked.join(""), text: text.join("") };79 };80 101-/** The index of the `)` that closes the `(` at `open`, in masked source. */81 const closing = (masked: string, open: number) => {82 let depth = 0;83 84 for (let at = open; at < masked.length; at += 1) {18 unmodified lines103 Option.gen(function* () {104 const open = masked.indexOf("(", start);105 const close = yield* closing(masked, open);106 128- // `.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;109 110 chain.lastIndex = close + 1;35 unmodified lines146 147 const segmentsOf = (path: string) =>148 path.split("/").filter((segment) => segment !== "" && segment !== ".");149 172-/**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.152 const baseOf = (glob: string) => {153 const segments = segmentsOf(glob);154 const fixed = Array.takeWhile(segments, (segment) => !GLOB.test(segment));155 2 unmodified lines158 159 return isFile ? fixed.slice(0, -1) : fixed;160 };161 187-/** A relative import's repo path, resolved from the check file's folder. */162 const resolve = (checkPath: string, specifier: string) => {163 const resolved = segmentsOf(checkPath).slice(0, -1);164 165 for (const segment of segmentsOf(specifier)) {9 unmodified lines175 176 const startsWith = (path: readonly string[], head: readonly string[]) =>177 head.every((segment, index) => path[index] === segment);178 205-/**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- */179 const reaches =180 (checkPath: string) => (specifier: string, base: readonly string[]) => {181 if (!specifier.startsWith(".")) {182 const parts = specifier.split("/");25 unmodified lines208 .replaceAll(/\b(?:true|false|null|undefined|NaN|Infinity)\b/gu, "0")209 .replaceAll(/[A-Za-z_$][\w$]*\s*:/gu, "")210 );211 244-/** `not.toThrow()`, `toBeUndefined()`, `toBeFalsy()` and their mirrors. */212 const isAbsence = ({ matcher, negated }: Expectation) =>213 negated214 ? ["toThrow", "toThrowError", "toBeDefined", "toBeTruthy"].includes(matcher)215 : ["toBeUndefined", "toBeFalsy"].includes(matcher);21 unmodified lines237 each.subject.includes(".mock.") ||238 /\b(?:vi|jest)\.fn\s*\(/u.test(each.subject) ||239 mocks.has(rootOf(each.subject) ?? "");240 274-/** The names the check binds to a call's result (`const range = weekRange(…)`). */241 const resultsOf = ({ text }: Source) =>242 new Set(243 Array.map(244 [6 unmodified lines251 );252 253 const squash = (text: string) => text.replaceAll(/\s+/gu, "");254 289-/**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- */255 const isFromOneFixture =256 (results: ReadonlySet<string>) =>257 ({ expected, subject }: Expectation) => {258 const root = rootOf(subject);7 unmodified lines266 root === rootOf(expected)))267 );268 };269 310-/** `expect(1).toBe(1)`: a literal held against a literal, or against nothing. */270 const isConstantPin = ({ expected, subject }: Expectation) =>271 isLiteral(subject) && (expected === "" || isLiteral(expected));272 314-/**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.275 export const weaknessesOf = (276 checkFile: CheckFile,277 territoryPaths: readonly string[]278 ): readonly Weakness[] => {29 unmodified linesmodified: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- */1 import { RepoPath } from "@repo/protocol/ids";2 import { Array, Option, Predicate, Schema } from "effect";3 4 import type { RepoFile } from "./finder.ts";5 12-/** One workspace package: its folder, its name, and the files its `exports` name. */6 export interface Workspace {7 readonly dir: string;8 readonly exports: readonly RepoPath[];9 readonly name: string;19 unmodified lines29 value !== undefined && isJsonArray(value)30 ? value.filter(Predicate.isString)31 : [];32 40-/** A manifest's `workspaces`: an array of globs, or `{ packages: [...] }`. */33 const workspaceGlobs = (value: Schema.Json | undefined): readonly string[] => {34 if (value === undefined || value === null) {35 return [];36 }4 unmodified lines41 42 return isJsonObject(value) ? strings(value.packages) : [];43 };44 53-/** Every string an `exports` field leads to, nested conditions included. */45 const exportTargets = (value: Schema.Json | undefined): readonly string[] => {46 if (value === undefined || value === null) {47 return [];48 }10 unmodified lines59 };60 61 const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");62 72-/** The folders directly in `folder` (`""` is the root) that hold any file, in path order. */63 const foldersIn = (paths: readonly string[], folder: string) => {64 const prefix = folder === "" ? "" : `${folder}/`;65 66 return Array.dedupe(9 unmodified lines76 })77 );78 };79 90-/**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- */81 const foldersOf = (paths: readonly string[], glob: string) => {82 const clean = withoutDotSlash(glob).replace(/\/+$/u, "");83 const star = clean.indexOf("*");84 1 unmodified line86 ? [clean]87 : foldersIn(paths, clean.slice(0, star).replace(/\/+$/u, ""));88 };89 104-/**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.92 export const workspacesIn = (93 files: readonly RepoFile[]94 ): readonly Workspace[] => {95 const sorted = files.toSorted((left, right) =>32 unmodified linesmodified: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- */1 import type { RepoFile } from "../../../src/finder.ts";2 3 const file = (path: string, ...lines: readonly string[]): RepoFile => ({4 content: `${lines.join("\n")}\n`,5 path,6 });7 13-/** A Bun workspace whose GitHub workflow installs, lints and tests. */8 export const bunWorkspace: readonly RepoFile[] = [9 file(10 "package.json",11 "{",36 unmodified lines48 ),49 file("src/index.ts", "export const parse = (text: string) => text;"),50 ];51 58-/** A pnpm library on Forgejo, with lefthook running lint and types before a commit. */52 export const forgejoLefthook: readonly RepoFile[] = [53 file(54 "package.json",55 "{",35 unmodified lines91 " run: pnpm test"92 ),93 ];94 102-/** An npm package with husky hooks and no CI. */95 export const huskyOnly: readonly RepoFile[] = [96 file(97 "package.json",98 "{",9 unmodified lines108 file(".husky/pre-commit", "npx lint-staged", "npm test"),109 file(".husky/_/husky.sh", "#!/usr/bin/env sh", "exit 0"),110 ];111 120-/** A Python project: pre-commit runs ruff and mypy, and the workflow runs pytest. */112 export const python: readonly RepoFile[] = [113 file(114 ".pre-commit-config.yaml",115 "repos:",29 unmodified lines145 ),146 file("pyproject.toml", "[project]", 'name = "fossil"'),147 ];148 158-/** A repo with nothing the finder reads. */149 export const nothing: readonly RepoFile[] = [150 file("README.md", "# wrec"),151 file("src/main.zig", "pub fn main() void {}"),152 ];153 164-/** A broken workflow beside a good one: the broken one is skipped, not thrown. */154 export 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 lines162 " - run: go test ./..."163 ),164 ];165 177-/** A fence-shaped monorepo with no CI: its root scripts are its gate, run by turbo. */166 export const turboMonorepo: readonly RepoFile[] = [167 file(168 "package.json",169 JSON.stringify({12 unmodified lines182 JSON.stringify({ scripts: { test: "vitest run" } })183 ),184 ];185 198-/**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- */186 export const mixedWorkflow: readonly RepoFile[] = [187 file(188 "package.json",189 JSON.stringify({22 unmodified linesmodified: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- */1 import type { Schema } from "effect";2 3 import type { RepoFile } from "../../../src/finder.ts";4 4 unmodified lines9 10 const manifest = (path: string, fields: Schema.JsonObject) =>11 file(path, JSON.stringify(fields, undefined, 2));12 21-/** The check that only asks that `parse` exists, which any answer passes. */13 export const weakCheck = file(14 "checks/weak.test.ts",15 'import { expect, test } from "bun:test";',16 "",3 unmodified lines20 " expect(parse).toBeDefined();",21 "});"22 );23 33-/** The check that asserts what `parse` reads a day as. */24 export const strongCheck = file(25 "checks/strong.test.ts",26 'import { expect, test } from "bun:test";',27 "",3 unmodified lines31 ' expect(parse("2026-10-06")).toStrictEqual({ day: 6, month: 10, year: 2026 });',32 "});"33 );34 45-/** A check written before its subject: `dates` exports no `weekOf` yet. */35 export const weakNewCheck = file(36 "checks/week-weak.test.ts",37 'import { expect, test } from "bun:test";',38 "",3 unmodified lines42 " expect(weekOf).toBeDefined();",43 "});"44 );45 57-/** The same, asserting the week a day falls in. */46 export const strongNewCheck = file(47 "checks/week-strong.test.ts",48 'import { expect, test } from "bun:test";',49 "",46 unmodified lines96 " }",97 "",98 ] as const;99 112-/** The repo at main, every file a null answer reads. */100 export const datesRepo: readonly RepoFile[] = [101 manifest("package.json", {102 name: "dates-repo",103 private: true,66 unmodified lines170 weakCheck,171 strongCheck,172 ];173 187-/** The `dates` files of `datesRepo` as the null answer has them. */174 export const nullDates: readonly RepoFile[] = [175 file(176 "packages/dates/src/index.ts",177 ...datesIndex,19 unmodified linesmodified:packages/checks/test/kinds/lint-count.test.ts-3 removed
56 unmodified lines57 58 const globs = (...patterns: readonly string[]) =>59 patterns.map((pattern) => Glob.make(pattern));60 61-/** What an unreadable count kept of the output, or `None` when it counted. */61 const unreadHead = (result: Result.Result<LintCount, CountUnreadable>) =>62 Result.match(result, {63 onFailure: ({ head }) => Option.some(head),64 onSuccess: () => Option.none(),65 });66 68-/** Both recordings, each with what makes its paths repo-relative. */67 const 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 });73 76-/** How many `any`s a recording counts within a territory's globs. */74 const anysWithin = (75 input: { readonly output: string; readonly root?: string },76 territory: readonly string[]77 ) =>174 unmodified linesmodified:packages/checks/test/kinds/lint-to-zero.test.ts-3 removed
7 unmodified lines8 lintToZeroRed,9 } from "../../src/kinds/lint-to-zero.ts";10 import { recorded } from "./recorded.ts";11 12-// The recordings `lint-count.test.ts` describes: oxlint over a fixture with13-// `any` in `packages/parser` and `packages/lexer`, none in `packages/printer`.14-12 const anysIn = (output: string, territory: string) =>13 Result.getOrThrow(14 countLint({15 output,47 unmodified linesmodified:packages/checks/test/kinds/metric.test.ts-1 removed
8 unmodified lines9 10 const read = (output: string, path: string) =>11 readMetric(output, JsonPath.make(path));12 13-/** What an unreadable count kept of the output, or `None` when it read one. */13 const unreadHead = (result: Result.Result<number, CountUnreadable>) =>14 Result.match(result, {15 onFailure: ({ head }) => Option.some(head),16 onSuccess: () => Option.none(),55 unmodified linesmodified:packages/checks/test/kinds/ratchet.test.ts+1 added-4 removed
29 unmodified lines30 const anyCount = RatchetName.make("anyCount");31 32 const lintCommand = "oxlint --format json";33 34-/** Counts `any` with the project's linter, in every territory. */34 const 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 });41 43-/** Counts `any` in the one territory the spec names. */42 const countingIn = (territory: string) =>43 RatchetSpec.make({ ...counting, territory });44 45 const bundleKb = RatchetName.make("bundleKb");46 47 const bundleCommand = "bun scripts/bundle-size.ts --json";48 51-/** Reads one number from a bundle report, for the whole project. */49 const 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 });56 60-/** 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.58 const printing = (stdout: string) =>59 Effect.gen(function* () {60 const ran = yield* Ref.make<readonly string[]>([]);61 253 unmodified linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { Effect, FileSystem } from "effect";3 9-/** One recording's stdout, by its name without `.stdout`. */4 export const recorded = (name: string) =>5 Effect.gen(function* () {6 const fs = yield* FileSystem.FileSystem;7 4 unmodified linesmodified:packages/checks/test/check-runner-local.test.ts-5 removed
21 unmodified lines22 command,23 lane: LaneName.make(name),24 });25 26-/**27- * A git repo whose `test` script fails, and a runner whose checkout copies28- * it into a fresh temp dir for each job.29- */26 const world = Effect.gen(function* () {27 const fs = yield* FileSystem.FileSystem;28 const repo = yield* fs.makeTempDirectoryScoped({ prefix: "datekit-" });29 50 unmodified lines80 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 linesmodified:packages/checks/test/classify.test.ts-3 removed
47 unmodified lines48 "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 };51 52-// A bun-style failure whose assertion line names a path, a duration and an address.52 const 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 });57 59-// The same run as the /local runner sees it: output only, never a report.58 const withoutReport = ({ code, stderr, stdout }: RunExit): RunExit => ({59 code,60 stderr,61 stdout,17 unmodified lines79 expect(classifyRun(unit, { ...vitestNoTests, code: 0 })).toBe("passed");80 });81 });82 85- // 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 linesmodified:packages/checks/test/evidence-store-r2.test.ts-9 removed
5 unmodified lines6 import { EvidenceStore, LogRef } from "../src/evidence-store.ts";7 import { EvidenceStoreR2 } from "../src/evidence-store/r2.ts";8 import type { EvidenceBucket } from "../src/evidence-store/r2.ts";9 10-/** One object as the fake bucket keeps it: its body and the options it was put with. */10 interface Kept {11 readonly text: string;12 readonly options: Parameters<EvidenceBucket["put"]>[2];13 }14 16-/**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- */15 const fakeBucket = () => {16 const objects = new Map<string, Kept>();17 18 const bucket: EvidenceBucket = {13 unmodified lines32 33 return { bucket, objects };34 };35 42-/** A bucket whose every call fails, as R2 does when it cannot be reached. */36 const brokenBucket: EvidenceBucket = {37 get: () => Promise.reject(new Error("R2 is unreachable")),38 put: () => Promise.reject(new Error("R2 is unreachable")),39 };7 unmodified lines47 };48 49 const key = "datekit/push-0123456789/unit#1";50 58-/** How a call ended, as its defect prints. */51 const printed = <A>(call: Effect.Effect<A>) =>52 Effect.map(Effect.exit(call), (exit) =>53 Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "it succeeded"54 );55 64-/** The store over `bucket`, as the Worker composes it. */56 const over = (bucket: EvidenceBucket) =>57 Effect.provide(EvidenceStoreR2(bucket) satisfies Layer.Layer<EvidenceStore>);58 59 describe("EvidenceStore over an R2 bucket", () => {114 unmodified linesmodified: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- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { gitOk } from "@repo/testkit/git";4 import { Effect, FileSystem, Path } from "effect";5 6 import { findRunBlock } from "../src/finder.ts";7 import type { RepoFile } from "../src/finder.ts";8 20-/** burrow's tracked files, by their paths from its own root. */9 const burrowFiles = () =>10 Effect.gen(function* () {11 const fs = yield* FileSystem.FileSystem;12 const path = yield* Path.Path;45 unmodified linesmodified:packages/checks/test/held-back-filter.test.ts-3 removed
37 unmodified lines38 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 linesmodified: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- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { Command } from "@repo/protocol/domain/common";4 import type { RunBlock } from "@repo/protocol/domain/run";10 unmodified lines15 import type { ListedFile } from "../src/judge.ts";16 17 const file = (path: string, content: string): RepoFile => ({ content, path });18 25-/**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- */19 const tree: readonly RepoFile[] = [20 file(21 "package.json",22 JSON.stringify({ name: "kit", workspaces: ["packages/*"] })55 unmodified lines78 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 ];81 95-/** The run block the config folder above declares. */82 const run: RunBlock = {83 checks: { [LaneName.make("api")]: Command.make("bun scripts/check/api.ts") },84 test: Command.make("bun test {path}"),85 };2 unmodified lines88 89 const listingOf = (files: readonly RepoFile[]): readonly ListedFile[] =>90 files.map(({ path }) => ({ path }));91 106-/** `judgeInputs` over `files`, and every path it asked to read, batch by batch. */92 const gathered = (93 files: readonly RepoFile[],94 listing: readonly ListedFile[] = listingOf(files)95 ) =>105 unmodified linesmodified:packages/checks/test/judge.test.ts+1 added-6 removed
23 unmodified lines24 import type { JudgeClosure } from "../src/judge.ts";25 26 const file = (path: string, content = ""): RepoFile => ({ content, path });27 28-/** A fence-shaped monorepo: root scripts, a tsconfig chain, a lint config, a hook config. */28 const fence: readonly RepoFile[] = [29 file(30 "package.json",31 JSON.stringify({822 unmodified lines854 const MAX_BYTES = 256 * 1024;855 856 const encoder = new TextEncoder();857 859-/** One tracked file of this repo: its path, its size in bytes, and its text (empty above the limit). */858 interface Tracked {859 readonly content: string;860 readonly path: string;861 readonly size: number;862 }863 866-/** This repo's tracked files, as `git ls-files` lists them, and its closure. */864 class ThisRepo extends Context.Service<865 ThisRepo,866 {867 readonly closure: JudgeClosure;135 unmodified lines1003 1004 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 );1010 1011 repo.effect(54 unmodified linesmodified:packages/checks/test/null-answer.test.ts-4 removed
28 unmodified lines29 const unit = LaneName.make("unit");30 31 const onUnit = (exit: RunExit) => ({ exit, lane: unit });32 33-/** A tree as path → content, to compare whole trees at once. */33 const contentsOf = (files: readonly RepoFile[]) =>34 Object.fromEntries(files.map(({ content, path }) => [path, content]));35 36 describe("the null answer", () => {219 unmodified lines256 257 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>258 bytes.pipe(Stream.decodeText(), Stream.mkString);259 261-/** The tree in a temp folder of its own, removed when the scope closes. */260 const written = (files: readonly RepoFile[]) =>261 Effect.gen(function* () {262 const fs = yield* FileSystem.FileSystem;263 const path = yield* Path.Path;8 unmodified lines272 273 return dir;274 });275 278-/** Runs `command` in `dir` under `sh -c`, as the Checker runs a lane: how it ended. */276 const ran = (dir: string, command: string) =>277 Effect.scoped(278 Effect.gen(function* () {279 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;58 unmodified lines338 );339 });340 341 describe("a check written before its subject", () => {345- /** Main with two checks of `weekOf`, which no file exports yet. */342 const beforeWeekOf = [...datesRepo, weakNewCheck, strongNewCheck];343 344 it.live("fails on main by a load error, not an assertion", () =>345 Effect.gen(function* () {115 unmodified linesmodified:packages/checks/test/phases.test.ts-3 removed
37 unmodified lines38 39 const keyOf = (phases: readonly Phase[]) =>40 phases.flatMap((phase) => (Phase.$is("Snapshot")(phase) ? [phase.key] : []));41 42-// 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.42 const { setup: _setup, setupEgress: _egress, ...bare } = run;43 44 const runBlocks: readonly RunBlock[] = [45 bare,96 unmodified lines142 at("WriteHeldBack") === -1 ? [] : order.slice(at("WriteHeldBack"));143 144 expect(afterWrite).not.toContain("Snapshot");145 148- // 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 linesmodified:packages/checks/test/red-first.test.ts-1 removed
18 unmodified lines19 const passed: RunExit = { code: 0, stderr: "", stdout: " 1 pass\n 0 fail" };20 21 const notRedFirst = Result.fail(new NotRedFirst({}));22 23-// What the platform sees of a run: lanes and evidence, never the output.23 const checkRun = (24 result: CheckRun["lanes"][number]["result"],25 evidence: Omit<CheckRun["evidence"][number], "lane">26 ): CheckRun => ({130 unmodified linesmodified:packages/checks/test/weak-shapes.test.ts-2 removed
1 import { describe, expect, it } from "@effect/vitest";2 3 import { weaknessesOf } from "../src/weak-shapes.ts";4 5-// 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.5 const territory = ["packages/week/**"];6 7 const check = (8 imports: string,218 unmodified linesmodified:packages/protocol/src/domain/answer.ts+1 added-23 removed
12 unmodified lines13 TreeSha,14 } from "../ids.ts";15 import { Outcome, StageName } from "./outcome.ts";16 17-/** How one lane's run ended. A load error is not a failure by an assertion. */17 export const LaneOutcome = Schema.Literals([18 "passed",19 "failed",20 "loadError",2 unmodified lines23 ]);24 25 export type LaneOutcome = typeof LaneOutcome.Type;26 28-/** One lane of the project's checks, run on an answer's merged tree. */27 export 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 });34 35 export type LaneResult = typeof LaneResult.Type;36 40-/**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. */38 export const HeldBackResult = Schema.Struct({39 area: AreaName,40 passed: Schema.Int,41 suite: SuiteRoot,1 unmodified line43 });44 45 export type HeldBackResult = typeof HeldBackResult.Type;46 53-/**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- */47 export const Verdict = Schema.Struct({48 ask: AskId,49 at: Schema.DateTimeUtcFromString,50 base: CommitSha,3 unmodified lines54 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 });62 63 export type Verdict = typeof Verdict.Type;64 78-/**79- * What an answerer gets back on offering an answer: the request, and where80- * the answer stands, usually still being checked.81- */65 export const AnswerReceipt = Schema.Struct({66 ask: AskId,67 base: CommitSha,68 head: CommitSha,3 unmodified lines72 });73 74 export type AnswerReceipt = typeof AnswerReceipt.Type;75 93-/**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- */76 export const LandReceipt = AnswerReceipt.mapFields(Struct.omit(["ask"]));77 78 export type LandReceipt = typeof LandReceipt.Type;79 101-/** One of a person's answers, as their status shows it. */80 export const AnswerView = Schema.Struct({81 ask: AskId,82 at: Schema.DateTimeUtcFromString,83 head: CommitSha,5 unmodified linesmodified:packages/protocol/src/domain/ask.ts-18 removed
9 unmodified lines10 } from "../ids.ts";11 import { CheckSpec } from "./check.ts";12 import { Territory } from "./territory.ts";13 14-/**15- * An ask's brief: what an answerer reads first. The want is behavioural; it16- * names no file and no line.17- */14 export 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 });21 22 export type Brief = typeof Brief.Type;23 30-/** Where an ask stands: open, claimed, waiting on its parent, or closed. */24 export const AskState = Schema.Literals([25 "open",26 "claimed",27 "waitingOnParent",1 unmodified line29 ]);30 31 export type AskState = typeof AskState.Type;32 40-/** Who an ask is held for, when it is held for someone: `newcomers` (with a mentor) or `people`. */33 export const Reserve = Schema.Literals(["newcomers", "people"]);34 35 export type Reserve = typeof Reserve.Type;36 45-/**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- */37 export 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 line53 });54 55 export type Ask = typeof Ask.Type;56 73-/** One open ask, as a list of asks shows it. */57 export 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 linemodified:packages/protocol/src/domain/check.ts-20 removed
1 unmodified line2 3 import { RatchetName, RepoPath } from "../ids.ts";4 import { Command, JsonPath, SymbolName } from "./common.ts";5 6-/**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- */6 export 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 lines14 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 });22 23 export type CheckSpec = typeof CheckSpec.Type;24 34-/**35- * How strong an ask's check must be: failing on main by an assertion, or36- * also failing a null answer.37- */25 export const Strength = Schema.Literals(["assertion", "nullAnswer"]);26 27 export type Strength = typeof Strength.Type;28 42-/** How a ratchet measures its number: a lint count, or a number in a command's JSON. */29 export 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 });33 34 export type RatchetMeasure = typeof RatchetMeasure.Type;35 52-/**53- * A ratchet: a counted budget per territory that answers may lower and never54- * raise; only a decider raises it.55- */36 export const RatchetSpec = Schema.Struct({37 measure: RatchetMeasure,38 name: RatchetName,39 territory: Schema.optionalKey(Schema.NonEmptyString),3 unmodified linesmodified:packages/protocol/src/domain/claim.ts-12 removed
7 unmodified lines8 RepoName,9 SuiteRoot,10 } from "../ids.ts";11 12-/**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- */12 export const ClaimState = Schema.Literals([13 "live",14 "warned",15 "lapsed",2 unmodified lines18 ]);19 20 export type ClaimState = typeof ClaimState.Type;21 26-/**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- */22 export 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 linemodified: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.2 import { Option, Schema } from "effect";3 4 import {5 AskId,8 unmodified lines14 } from "../ids.ts";15 import { ClaimState } from "./claim.ts";16 import { LandingView } from "./landing.ts";17 23-/** A tag's name, as `refs/tags/<name>` spells it: `v1.2.0`, `@changesets/cli@2.27.1`. */18 export const TagName = Schema.NonEmptyString.check(19 Schema.isMaxLength(255)20 ).pipe(Schema.brand("TagName"));21 22 export type TagName = typeof TagName.Type;23 30-/**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- */24 export const packageOf = (tag: string): Option.Option<string> => {25 const at = tag.lastIndexOf("@");26 27 return at > 0 ? Option.some(tag.slice(0, at)) : Option.none();28 };29 43-/**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- */30 export const Rev = Schema.String.check(31 Schema.isMinLength(1),32 Schema.isMaxLength(255)33 );34 35 export type Rev = typeof Rev.Type;36 55-/** One tag, peeled to the commit it names. */37 export const TagRef = Schema.Struct({ name: TagName, sha: CommitSha });38 39 export type TagRef = typeof TagRef.Type;40 60-/**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- */41 export const ForkRef = Schema.Struct({42 ask: Schema.optionalKey(AskId),43 handle: Handle,44 kind: Schema.Literals(["claim", "working"]),2 unmodified lines47 });48 49 export type ForkRef = typeof ForkRef.Type;50 74-/** A project's refs as a reader sees them: main's landed commit, its tags and its forks. */51 export const RefsView = Schema.Struct({52 forks: Schema.Array(ForkRef),53 landed: Schema.optionalKey(LandedSha),54 project: ProjectName,1 unmodified line56 });57 58 export type RefsView = typeof RefsView.Type;59 84-/** One entry of a directory. */60 export const CodeEntry = Schema.Struct({61 mode: Schema.String,62 name: Schema.NonEmptyString,63 path: RepoPath,2 unmodified lines66 });67 68 export type CodeEntry = typeof CodeEntry.Type;69 95-/** One directory at one commit: folders first, then by name, and its README when it has one. */70 export 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 });76 77 export type TreeListing = typeof TreeListing.Type;78 106-/** Every file path at one commit, for a file tree; `truncated` past the cap. */79 export const PathList = Schema.Struct({80 at: CommitSha,81 paths: Schema.Array(RepoPath),82 truncated: Schema.Boolean,83 });84 85 export type PathList = typeof PathList.Type;86 115-/**116- * One file at one commit. `text` is absent for a binary file and for one117- * past the size cap (`truncated`).118- */87 export const FileView = Schema.Struct({88 at: CommitSha,89 binary: Schema.Boolean,90 path: RepoPath,4 unmodified lines95 });96 97 export type FileView = typeof FileView.Type;98 131-/** Who wrote or committed a commit, and when. */99 export const Signature = Schema.Struct({100 at: Schema.DateTimeUtcFromString,101 email: Schema.String,102 name: Schema.String,103 });104 105 export type Signature = typeof Signature.Type;106 140-/**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. */108 export const CommitView = Schema.Struct({109 author: Signature,110 body: Schema.String,111 committer: Signature,8 unmodified lines120 });121 122 export type CommitView = typeof CommitView.Type;123 160-/** One file a commit changed, against its first parent. */124 export const ChangedFile = Schema.Struct({125 after: Schema.optionalKey(BlobSha),126 before: Schema.optionalKey(BlobSha),127 binary: Schema.Boolean,4 unmodified lines132 });133 134 export type ChangedFile = typeof ChangedFile.Type;135 173-/** A commit and what it changed; past the caps, paths only and `truncated`. */136 export const CommitDiff = Schema.Struct({137 commit: CommitView,138 files: Schema.Array(ChangedFile),139 truncated: Schema.Boolean,9 unmodified lines149 });150 151 export type WhyRange = typeof WhyRange.Type;152 191-/**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- */153 export const WhyView = Schema.Struct({154 at: CommitSha,155 commits: Schema.Array(CommitView),156 landings: Schema.Array(LandingView),6 unmodified linesmodified: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
1 import { Context, Schema } from "effect";2 3-/**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- */8-9-/** What a contract does, in one sentence, for every surface that lists it. */3 export const Description = Context.Reference<string>("protocol/Description", {4 defaultValue: () => "",5 });6 14-/**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- */7 export const Audience = Context.Reference<"public" | "signedIn" | "decider">(8 "protocol/Audience",9 { defaultValue: () => "signedIn" }10 );11 23-/** Whether its response may be shown to anyone, or only to maintainers. */12 export const Visibility = Context.Reference<"public" | "maintainers">(13 "protocol/Visibility",14 { defaultValue: () => "public" }15 );16 29-/** It only reads: it changes nothing. */17 export const ReadOnly = Context.Reference<boolean>("protocol/ReadOnly", {18 defaultValue: () => false,19 });20 34-/** Calling it again with the same payload changes nothing more. */21 export const Idempotent = Context.Reference<boolean>("protocol/Idempotent", {22 defaultValue: () => false,23 });24 39-/**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- */25 export const Destructive = Context.Reference<boolean>("protocol/Destructive", {26 defaultValue: () => false,27 });28 48-/** A person approves it before it runs: the CLI asks for `--yes`. */29 export const NeedsApproval = Context.Reference<boolean>(30 "protocol/NeedsApproval",31 { defaultValue: () => false }32 );33 34 /**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 */38 export const Cli = Context.Reference<{39 readonly name?: string;40 readonly positional?: readonly string[];41 readonly formerFlags?: readonly string[];42 }>("protocol/Cli", { defaultValue: () => ({}) });43 66-/** Every surface a contract can be served on. */44 export const SurfaceName = Schema.Literals(["rpc", "mcp", "cli", "web"]);45 46 export type SurfaceName = typeof SurfaceName.Type;47 71-/** The surfaces it is served on; every one by default. */48 export 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.3 import { Option, Schema } from "effect";4 import type { Types } from "effect";5 12-/** What the platform records of the harness behind a call. */6 export const HarnessAudit = Schema.Struct({7 harness: Schema.optionalKey(Schema.NonEmptyString),8 model: Schema.optionalKey(Schema.NonEmptyString),9 session: Schema.optionalKey(Schema.NonEmptyString),10 });11 12 export type HarnessAudit = typeof HarnessAudit.Type;13 21-/** Whether an env name is one of a harness's markers. */14 const named =15 (...names: readonly string[]) =>16 (key: string) =>17 names.includes(key);18 19 const prefixed = (prefix: string) => (key: string) => key.startsWith(prefix);20 29-/**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- */21 const markers = [22 {23 harness: "claude-code",24 marks: named("CLAUDECODE", "CLAUDE_CODE", "CLAUDE_CODE_ENTRYPOINT"),8 unmodified lines33 readonly harness: string;34 readonly marks: (key: string) => boolean;35 }[];36 49-/** `value`, unless it is absent or empty. */37 const given = (value: string | undefined) =>38 value === undefined || value === "" ? undefined : value;39 53-/** pi's model, as `provider/model` when pi names both. */40 const piModel = (env: Readonly<Record<string, string | undefined>>) => {41 const model = given(env.PI_MODEL);42 const provider = given(env.PI_PROVIDER);43 1 unmodified line45 ? model46 : `${provider}/${model}`;47 };48 63-/**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- */49 export 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 lines80 81 return audit;82 };83 103-/** The username's fields, in the order they are written. */84 const fields = ["harness", "model", "session"] as const;85 86 const PREFIX = "audit;";87 108-/**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- */89 const VALUE_LIMIT = 56;90 114-/** `value` with every character a username field can't carry as `_`, cut to the limit. */91 const clean = (value: string) =>92 value.replaceAll(/[^A-Za-z0-9._/-]/gu, "_").slice(0, VALUE_LIMIT);93 118-/**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- */94 export const auditUser = (audit: HarnessAudit): string =>95 `${PREFIX}${fields96 .flatMap((field) => {97 const value = audit[field];3 unmodified lines101 .join("&")}`;102 103 const Pair = /^(?<field>harness|model|session)=(?<value>[A-Za-z0-9._/-]+)$/u;104 135-/** What an `auditUser` username carries; none for any other username. */105 export const parseAuditUser = (user: string): Option.Option<HarnessAudit> => {106 if (!user.startsWith(PREFIX)) {107 return Option.none();108 }16 unmodified linesmodified:packages/protocol/src/authenticate.ts+3 added-11 removed
7 unmodified lines8 Unauthenticated,9 } from "./principal.ts";10 import type { Person, Principal } from "./principal.ts";11 12-/**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- */12 export const bearerToken = (authorization: string | undefined) =>13 Option.fromNullishOr(14 /^Bearer (?<token>\S+)$/iu.exec(authorization ?? "")?.groups?.token15 );16 17 /**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 */22 export const authenticated = <E, R>(23 verify: (credential: string) => Effect.Effect<Option.Option<Person>, E, R>24 ): Layer.Layer<Authenticated, never, R> =>43 unmodified linesmodified:packages/protocol/src/cli.ts+4 added-100 removed
48 unmodified lines49 import { ExitCode, exitCodeFor } from "./exit-code.ts";50 import type { Unauthenticated } from "./principal.ts";51 import { Refusal } from "./refusal.ts";52 53-/** How a call can fail before its handler runs: in transit, or unauthenticated. */53 type CallError = RpcClientError.RpcClientError | Unauthenticated;54 56-/** A schema that needs no services to decode or encode, as every wire schema is. */55 type Plain = Schema.Top & {56 readonly DecodingServices: never;57 readonly EncodingServices: never;58 };59 62-/**63- * An Rpc a command can project: its payload is a struct of plain fields, or64- * a record that takes none (`listProjects`).65- */60 export type CommandRpc = Rpc.AnyWithProps & {61 readonly errorSchema: Plain;62 readonly payloadSchema: Plain;63 readonly successSchema: Plain;64 };65 72-/** A result as prose: Markdown, and plain text where a person reads it. */66 export interface View {67 readonly markdown: string;68 readonly text?: string;69 }70 78-/**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- */71 export 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 }89 105-/**106- * Values for payload fields a person may leave out, such as the project the107- * repo they stand in belongs to.108- */90 export 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 }94 95 export 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 }101 133-/**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- */102 export type Views<Rpcs extends Rpc.Any> = Readonly<103 Record<string, (success: Rpc.Success<Rpcs>) => Option.Option<View>>104 >;105 142-/**143- * A command that changes something a person must approve ran without144- * `--yes`. A usage error: nothing was called.145- */106 export class ApprovalNeeded extends Schema.TaggedError<ApprovalNeeded>()(107 "ApprovalNeeded",108 { command: Schema.String }109 ) {1 unmodified line111 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 }114 155-/**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- */115 export class MissingValue extends Schema.TaggedError<MissingValue>()(116 "MissingValue",117 { command: Schema.String, flag: Schema.String }118 ) {1 unmodified line120 return `${this.command} needs ${this.flag}: give it, since nothing here does`;121 }122 }123 168-/**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- */124 export 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;129 179- /** 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 }133 184-/**185- * Hands `refusals` to `output` once, then ends the command as `Reported`186- * with their exit code: how every command meets a refusal.187- */134 export const endRefused = (135 output: Pick<CommandOutput, "refused">,136 input: Parameters<CommandOutput["refused"]>[0]137 ): Effect.Effect<never, Reported> =>76 unmodified lines214 215 return { description, kind, literals: [], optional };216 };217 272-/**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- */218 const 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 line223 : []224 )225 : [];226 285-/** Whether a person must give the field: a switch is off unless named. */227 const isRequired = (spec: FieldSpec) =>228 !spec.optional && spec.kind !== "boolean" && spec.kind !== "switch";229 230 const jsonFlag = (name: string, field: Plain) =>9 unmodified lines240 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 lines250 FieldSpec["kind"],251 (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>252 >;253 314-/** A field's help text, and where its default comes from when it has one. */254 const helpOf = (spec: FieldSpec, fallback: string | undefined) => {255 if (fallback === undefined) {256 return spec.description;257 }2 unmodified lines260 ? `Defaults to ${fallback}`261 : `${spec.description}; defaults to ${fallback}`;262 };263 325-/**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- */264 const flagFor = (265 name: string,266 field: Plain,267 fallback: string | undefined30 unmodified lines298 (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>299 >;300 301 /**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 */306 const leftOutForNow = (307 argument: Argument.Argument<unknown>308 ): Argument.Argument<unknown> =>25 unmodified lines334 335 return wasFlag ? leftOutForNow(described) : described;336 };337 404-/**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. */339 const formerFlagFor = (name: string, field: Plain): Flag.Flag<unknown> => {340 const spec = describe(field);341 342 return flagBuilders[spec.kind](name, field, spec).pipe(2 unmodified lines345 Flag.map(Option.getOrUndefined)346 );347 };348 419-/**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- */349 const controls = (approval: boolean, readOnly: boolean) =>350 Object.fromEntries([351 [352 "json",33 unmodified lines386 ]);387 388 const isRefusal = Schema.is(Refusal);389 465-/** The contract's command, as a person types it: `asks`, `ask open`. */390 export const commandName = (rpc: Rpc.AnyWithProps): string =>391 Context.get(rpc.annotations, Cli).name ?? rpc._tag;392 469-/** The words that reach the contract's command: `["ask", "open"]`. */393 export const commandPath = (394 rpc: Rpc.AnyWithProps395 ): readonly [string, ...string[]] => {396 const [first = rpc._tag, ...rest] = commandName(rpc).split(" ");397 398 return [first, ...rest];399 };400 478-/** JSON text as Markdown, and as itself for a person. */401 const asJson = (text: string): View => ({402 markdown: ["```json", text, "```"].join("\n"),403 text,404 });405 484-/**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- */406 export const toCommand = <407 R extends CommandRpc,408 ClientR,409 OutputR,42 unmodified lines452 const decodePayload = Schema.decodeUnknownEffect(rpc.payloadSchema);453 const encodePayload = Schema.encodeUnknownEffect(rpc.payloadSchema);454 const encodeSuccess = Schema.encodeUnknownEffect(rpc.successSchema);455 544- /** 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 lines500 if (approval && control.yes !== true && !dryRun) {501 return yield* new ApprovalNeeded({ command });502 }503 593- // 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 lines573 export 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 }582 675-/**676- * Every contract in `group` whose `Surfaces` include `cli`, but those677- * `exclude` names, as a command at the path its `Cli` annotation names.678- */583 export const toCommands = <584 Rpcs extends CommandRpc,585 ClientR,586 OutputR,23 unmodified linesmodified:packages/protocol/src/contracts.ts+5 added-82 removed
94 unmodified lines95 WeakCheck,96 Weakened,97 } from "./refusal.ts";98 99-/** The keys every contract is annotated with, for the surfaces that read them. */99 export {100 Audience,101 Cli,102 Description,5 unmodified lines108 Surfaces,109 Visibility,110 } from "./annotations.ts";111 113-/**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.113 const envSchemaTag = "envShape";114 119-/**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- */115 const servedOn = {116 claim: ["rpc", "mcp", "cli"],117 credits: SurfaceName.literals,118 decide: SurfaceName.literals,9 unmodified lines128 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 lines150 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[]>;157 170-/**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.160 const NoPayload = Schema.Record(Schema.String, Schema.Never);161 177-// --- Reads ------------------------------------------------------------------178-162 export class ListProjects extends Rpc.make("listProjects", {163 payload: NoPayload,164 success: Schema.Struct({ projects: Schema.Array(ProjectListing) }),165 })49 unmodified lines215 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 lines237 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 lines321 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 lines347 .annotate(NeedsApproval, false)348 .annotate(Cli, { name: "ledger" })349 .annotate(Surfaces, servedOn.ledger) {}350 371-/** The env shape contract, named for the file it reads: `.env.schema`. */351 export class EnvSchemaOf extends Rpc.make(envSchemaTag, {352 error: UnknownProject,353 payload: { project: ProjectName },354 success: EnvSchemaView,14 unmodified lines369 export 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 lines386 .annotate(Destructive, false)387 .annotate(NeedsApproval, false)388 .annotate(Surfaces, servedOn.watch) {}389 412-// --- Code reads (the canonical repo only; git reads it locally too) --------413-390 export class ListRefs extends Rpc.make("listRefs", {391 error: UnknownProject,392 payload: { project: ProjectName },393 success: RefsView,14 unmodified lines408 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 lines467 export 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 lines535 export 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 lines557 export 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 lines574 .annotate(NeedsApproval, false)575 .annotate(Cli, { name: "proposal", positional: ["proposal"] })576 .annotate(Surfaces, servedOn.showProposal) {}577 613-// --- Writes -----------------------------------------------------------------614-578 export 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 lines596 .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) {}602 603 export class OpenAsk extends Rpc.make("openAsk", {26 unmodified lines630 .annotate(NeedsApproval, true)631 .annotate(Cli, { name: "ask open", positional: ["ask"] })632 .annotate(Surfaces, servedOn.openAsk) {}633 675-/**676- * A drafted proposal brings no files and no sealed answer: the platform's677- * agent writes the ask's files.678- */634 const draftsAlone = Schema.makeFilter(635 (payload: {636 readonly draft?: true;637 readonly files?: unknown;5 unmodified lines643 : "a drafted proposal carries neither files nor a sealed answer"644 );645 646 export 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 lines677 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 lines724 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 lines740 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 lines810 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 lines885 export 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 lines929 export 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 line944 "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 lines961 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 lines983 .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) {}989 1052-/** The one schema: every surface is a projection of this group. */990 export class Contracts extends RpcGroup.make(991 ListProjects,992 FrontPage,993 ListAsks,31 unmodified lines1025 EvidenceOf,1026 SetEnv1027 ).middleware(Authenticated) {}1028 1092-/** Every contract in the group, as its handlers and clients see it. */1029 export type Contract = RpcGroup.Rpcs<typeof Contracts>;1030 1031 type ServedOn = typeof servedOn;1032 1097-/** The tags of the contracts `surface` serves. */1033 export type TagOn<S extends SurfaceName> = {1034 readonly [Tag in keyof ServedOn]: S extends ServedOn[Tag][number]1035 ? Tag1036 : never;1037 }[keyof ServedOn];1038 1104-/** The contracts `surface` serves. */1039 export type ContractOn<S extends SurfaceName> = Extract<1040 Contract,1041 { readonly _tag: TagOn<S> }1042 >;1043 1110-/**1111- * Whether a contract is served on `surface`, by its `Surfaces` annotation.1112- * The annotation is read from `servedOn`, which `ContractOn` reads too.1113- */1044 const isServedOn =1045 <S extends SurfaceName>(surface: S) =>1046 (rpc: Contract): rpc is ContractOn<S> =>1047 Context.get(rpc.annotations, Surfaces).includes(surface);1048 1119-/** The group as one surface serves it: the contracts its `Surfaces` include, in order. */1049 export const surfaced = <S extends SurfaceName>(1050 surface: S1051 ): RpcGroup.RpcGroup<ContractOn<S>> =>1052 RpcGroup.make(1053 ...[...Contracts.requests.values()].filter(isServedOn(surface))1054 );1055 1127-/**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- */1056 export const partsOf = (rpc: Contract) =>1057 RpcSchema.isStreamSchema(rpc.successSchema)1058 ? {1059 error: rpc.successSchema.error,5 unmodified lines1065 payload: rpc.payloadSchema,1066 success: rpc.successSchema,1067 };1068 1145-/** A way to call the contracts, in process or over the wire. */1069 export class Client extends Context.Service<1070 Client,1071 RpcClient.RpcClient<1072 RpcGroup.Rpcs<typeof Contracts>,3 unmodified linesmodified: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.