Skip to content
Myr

check.ts

This file

Path

apps/cli/src/local/check.ts

793 lines · 22.1 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1// Writes nothing to the repo, its config or its refs; `--offline` calls no platform.2import { Brand } from "@repo/brand";3import {4  CheckAt,5  CheckLane,6  CheckRunner,7  outputOf,8  shaOf,9} from "@repo/checks/check-runner";10import type { CheckRun, LaneEvidence } from "@repo/checks/check-runner";11import { CheckRunnerLocal } from "@repo/checks/check-runner/local";12import { commandFor } from "@repo/checks/kinds";13import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";14import { PushTarget } from "@repo/gate/facts";15import { pushStages, runGate } from "@repo/gate/gate";16import { Client } from "@repo/protocol/contracts";17import { LaneResult } from "@repo/protocol/domain/answer";18import type { Ask } from "@repo/protocol/domain/ask";19import { CheckSpec } from "@repo/protocol/domain/check";20import type { ClaimView } from "@repo/protocol/domain/claim";21import type { Policy } from "@repo/protocol/domain/policy";22import type { RepoName } from "@repo/protocol/ids";23import {24  AskId,25  CommitSha,26  Handle,27  LandedSha,28  ProjectName,29  addressOfRepo,30  claimForkName,31} from "@repo/protocol/ids";32import { Person } from "@repo/protocol/principal";33import {34  ChecksFailed,35  NoAsk,36  Refusal,37  UnknownAsk,38  VerifierBlocked,39} from "@repo/protocol/refusal";40import {41  Array,42  Context,43  DateTime,44  Duration,45  Effect,46  Exit,47  FileSystem,48  Option,49  Path,50  Record,51  Schema,52  Stream,53} from "effect";54import { Command, Flag } from "effect/cli";55import { ChildProcess, ChildProcessSpawner } from "effect/process";5657import { Credentials } from "../credentials.ts";58import { endRefused, Output, Reported } from "../output.ts";59import { repoContext } from "../repo-context.ts";60import type { RepoContext } from "../repo-context.ts";61import { commitOf, localFacts, outsideAnyHook, runGit } from "./facts.ts";62import {63  ConfigBundler,64  ConfigBundlerBun,65  localPolicy,66} from "./local-policy.ts";67import { countRatchets, judgeMoves, RatchetMove } from "./ratchets.ts";68import { staleGenerated } from "./stale.ts";69import type { StaleCopy } from "./stale.ts";7071const COMMAND = "check";7273const Stale = Schema.Struct({74  landed: Schema.optionalKey(LandedSha),75  path: Schema.String,76});7778const Checked = Schema.Struct({79  ask: AskId,80  base: CommitSha,81  head: CommitSha,82  lanes: Schema.Array(LaneResult),83  ratchets: Schema.optionalKey(Schema.NonEmptyArray(RatchetMove)),84  stage: Schema.Literals(["shape", "checks"]),85  stale: Schema.optionalKey(Schema.NonEmptyArray(Stale)),86});8788type Checked = typeof Checked.Type;8990const encodeChecked = Schema.encodeEffect(Checked);9192const isRefusal = Schema.is(Refusal);9394const SOMEONE = Handle.make("you");9596const asHandle = Schema.decodeOption(Handle);9798const isLive = (claim: ClaimView) =>99  claim.state === "live" || claim.state === "warned";100101const stop = (text: string) =>102  Output.use((output) =>103    Effect.andThen(output.note(text), Effect.fail(new Reported()))104  );105106const refuse = (107  json: boolean,108  refusals: Array.NonEmptyReadonlyArray<Refusal>109) =>110  Output.use((output) =>111    endRefused(output, { command: COMMAND, json, refusals })112  );113114const 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.`;119120const staleField = (stale: readonly StaleCopy[]) =>121  Array.match(stale, {122    onEmpty: () => ({}),123    onNonEmpty: (copies) => ({124      stale: Array.map(copies, ({ landed, path }) =>125        Option.match(landed, {126          onNone: () => ({ path }),127          onSome: (sha) => ({ landed: sha, path }),128        })129      ),130    }),131  });132133const signedInHandle = Effect.flatMap(134  Effect.serviceOption(Credentials),135  Option.match({136    onNone: () => Effect.succeedNone,137    onSome: (credentials) =>138      Effect.map(credentials.current, (profile) =>139        Option.flatMap(profile, ({ handle }) => Option.fromUndefinedOr(handle))140      ),141  })142);143144const subjectOf = (145  context: RepoContext,146  flags: {147    readonly ask: Option.Option<AskId>;148    readonly project: Option.Option<ProjectName>;149  },150  json: boolean151) =>152  Effect.gen(function* () {153    const output = yield* Output;154    const { repo } = context;155156    const project = Option.orElse(flags.project, () =>157      Option.map(repo, (ref) => ref.project)158    );159160    if (Option.isNone(project)) {161      return yield* stop(162        "No project: this repo has no remote on the platform. Name it with --project <owner>/<name>."163      );164    }165166    if (Option.isSome(flags.ask)) {167      return { ask: flags.ask.value, project: project.value };168    }169170    const inferred = Option.flatMap(repo, (ref) =>171      Option.fromUndefinedOr(ref.ask)172    );173174    if (Option.isNone(inferred)) {175      return yield* refuse(json, [new NoAsk({})]);176    }177178    const remote = Option.match(context.remote, {179      onNone: () => "its remote",180      onSome: ({ name, url }) => `the remote ${name} (${url})`,181    });182183    yield* output.note(184      `Checking the ask ${inferred.value}, which ${remote} names; pass --ask to check another.`185    );186187    return { ask: inferred.value, project: project.value };188  });189190const claimsOn = (project: ProjectName, json: boolean) =>191  Effect.gen(function* () {192    const client = yield* Client;193194    return yield* client.status({ project }).pipe(195      Effect.map(({ claims }) =>196        claims.filter((claim) => claim.project === project)197      ),198      Effect.catch((error) =>199        isRefusal(error)200          ? refuse(json, [error])201          : stop(202              `The platform could not say which claims you hold (${String(error)}). Run with --offline to check against a made-up claim.`203            )204      )205    );206  });207208/** The gateway diffs a fork push from the claim's base, so an answer committed on the clone's own main is still seen. */209const baseOf = (210  root: string,211  given: Option.Option<string>,212  claim: Option.Option<ClaimView>213) =>214  Effect.gen(function* () {215    if (Option.isSome(given)) {216      return given.value;217    }218219    if (Option.isNone(claim)) {220      return "main";221    }222223    const { base } = claim.value;224    const held = yield* Effect.exit(commitOf(root, base));225226    if (Exit.isSuccess(held)) {227      return base;228    }229230    yield* Output.use((output) =>231      output.note(232        `Your claim was made at ${base}, which this repo doesn't have, so the diff starts at main; fetch the project's main, or pass --base.`233      )234    );235236    return "main";237  });238239const syntheticClaim = (input: {240  readonly ask: Ask;241  readonly claimant: Handle;242  readonly fork: RepoName;243  readonly origin: Option.Option<string>;244  readonly policy: Policy;245}) =>246  Effect.map(DateTime.now, (now): ClaimView => {247    const { ask, claimant, fork, policy } = input;248    const address = Option.getOrElse(addressOfRepo(fork), () => fork);249250    return {251      ask: ask.id,252      base: policy.at,253      checkCommand: `${Brand.cli} ${COMMAND} --ask ${ask.id}`,254      claimant,255      fork,256      lapsesAt: DateTime.addDuration(257        now,258        Duration.millis(policy.claims.lapseAfterMs)259      ),260      openedAt: now,261      project: ask.project,262      remote: Option.match(input.origin, {263        onNone: () => `${address}.git`,264        onSome: (origin) => `${origin}/${address}.git`,265      }),266      state: "live",267      warnsAt: DateTime.addDuration(268        now,269        Duration.millis(policy.claims.warnAfterMs)270      ),271    };272  });273274const lanesOf = (policy: Policy, ask: Ask): readonly CheckLane[] => [275  ...Option.toArray(276    Option.map(277      commandFor(ask.check, policy.run, policy.ratchets),278      ({ command, lane }) =>279        CheckSpec.guards.LintToZero(ask.check)280          ? CheckLane.make({ command, lane, output: "stdout" })281          : CheckLane.make({ command, lane })282    )283  ),284  ...Record.toEntries(policy.run.checks).map(([lane, command]) =>285    CheckLane.make({ command, lane })286  ),287];288289/** Mirrors the platform's `countedAskLane` (`apps/platform/src/workflows/answer/lanes.ts`). */290const countedAskLane = (291  policy: Policy,292  ask: Ask,293  ran: CheckRun294): Effect.Effect<CheckRun> => {295  const { check } = ask;296297  const lane = Option.map(298    commandFor(check, policy.run, policy.ratchets),299    (found) => found.lane300  );301302  const result = Option.flatMap(lane, (name) =>303    Array.findFirst(ran.lanes, (each) => each.lane === name)304  );305306  if (307    !CheckSpec.guards.LintToZero(check) ||308    Option.isNone(result) ||309    result.value.result === "blocked"310  ) {311    return Effect.succeed(ran);312  }313314  const counted = result.value;315316  const replaced = (317    outcome: LaneResult["result"],318    evidence: Option.Option<LaneEvidence>319  ): CheckRun => ({320    ...ran,321    evidence: [322      ...ran.evidence.filter((each) => each.lane !== counted.lane),323      ...Option.toArray(evidence),324    ],325    lanes: ran.lanes.map((each) =>326      each.lane === counted.lane ? { ...counted, result: outcome } : each327    ),328  });329330  return Effect.fromOption(outputOf(ran, counted.lane)).pipe(331    Effect.flatMap((stdout) =>332      lintToZeroCount({333        asked: ask.territory,334        check,335        modules: policy.modules,336        stdout,337      })338    ),339    Effect.map((count) =>340      count === 0341        ? replaced("passed", Option.none())342        : replaced(343            "failed",344            Option.some({345              lane: counted.lane,346              signature: `${check.rule}: ${count} in ${check.territory ?? ask.territory.module}`,347            })348          )349    ),350    Effect.orElseSucceed(() =>351      replaced("loadError", Option.some({ lane: counted.lane }))352    )353  );354};355356const TAIL = 4000;357358/** Setup's output goes to stderr only when it fails, so `--json` stdout stays one document. */359const checkoutOf = (input: {360  readonly root: string;361  readonly setup: Option.Option<string>;362  readonly note: (text: string) => Effect.Effect<void>;363}) =>364  Effect.fnUntraced(365    function* (at: CheckAt) {366      const fs = yield* FileSystem.FileSystem;367      const path = yield* Path.Path;368      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;369370      const folder = yield* fs.makeTempDirectoryScoped({371        prefix: "check-tree-",372      });373374      const tree = path.join(folder, "tree");375376      const sha = shaOf(at);377378      const steps = [379        ["clone", "--shared", "--no-checkout", "--quiet", input.root, tree],380        [381          "-c",382          "core.hooksPath=/dev/null",383          "-C",384          tree,385          "checkout",386          "--quiet",387          "--detach",388          sha,389        ],390      ];391392      for (const args of steps) {393        const ran = yield* runGit(folder, args);394395        if (ran.exitCode !== 0) {396          yield* input.note(`Could not check out ${sha}: ${ran.stderr.trim()}`);397398          return yield* new VerifierBlocked({});399        }400      }401402      if (Option.isNone(input.setup)) {403        return tree;404      }405406      yield* input.note(`Setting up: ${input.setup.value}`);407408      const [out, err, code] = yield* Effect.scoped(409        Effect.flatMap(410          spawner.spawn(411            ChildProcess.make("sh", ["-c", input.setup.value], {412              cwd: tree,413              env: outsideAnyHook,414              extendEnv: true,415              stdin: "ignore",416            })417          ),418          (child) =>419            Effect.all(420              [421                Stream.mkString(Stream.decodeText(child.stdout)),422                Stream.mkString(Stream.decodeText(child.stderr)),423                child.exitCode,424              ],425              { concurrency: "unbounded" }426            )427        )428      );429430      if (Number(code) !== 0) {431        yield* input.note(432          `Setup exited with ${code}:\n${`${out}${err}`.slice(-TAIL).trimEnd()}`433        );434435        return yield* new VerifierBlocked({});436      }437438      return tree;439    },440    (effect) =>441      effect.pipe(442        Effect.catchTags({443          NotARepo: () => Effect.fail(new VerifierBlocked({})),444          PlatformError: () => Effect.fail(new VerifierBlocked({})),445        })446      )447  );448449const moveText = ({ after, before, ratchet, territory }: RatchetMove) =>450  `${ratchet} in ${territory}: ${before} on the base, ${after} here`;451452const viewOf = (checked: Checked) => {453  const moves = checked.ratchets ?? [];454455  const lines = [456    `${checked.ask} at ${checked.head.slice(0, 12)}: the gate's shape stage has nothing to say.`,457    ...checked.lanes.map(458      ({ durationMs, lane, result }) =>459        `  ${lane}: ${result} (${durationMs} ms)`460    ),461    ...moves.map((move) => `  ratchet ${moveText(move)}`),462  ];463464  return {465    markdown: [466      `**${checked.ask}** at \`${checked.head.slice(0, 12)}\`: the gate's shape stage has nothing to say.`,467      "",468      ...checked.lanes.map(469        ({ durationMs, lane, result }) =>470          `- \`${lane}\`: ${result} (${durationMs} ms)`471      ),472      ...moves.map((move) => `- ratchet ${moveText(move)}`),473    ].join("\n"),474    text: lines.join("\n"),475  };476};477478const ratchetsField = (moves: readonly RatchetMove[]) =>479  Array.match(moves, {480    onEmpty: () => ({}),481    onNonEmpty: (ratchets) => ({ ratchets }),482  });483484export const check = Command.make(485  COMMAND,486  {487    ask: Flag.String("ask").pipe(488      Flag.withSchema(AskId),489      Flag.optional,490      Flag.withDescription(491        "The ask to check against; the claim fork's remote names it when left out"492      )493    ),494    base: Flag.String("base").pipe(495      Flag.optional,496      Flag.withDescription(497        "Main as you have it: the policy is read here, and the diff starts at its merge base with HEAD. Defaults to your live claim's base, as the gateway diffs, else main"498      )499    ),500    dir: Flag.Directory("dir", { mustExist: true }).pipe(501      Flag.withAlias("C"),502      Flag.optional,503      Flag.withDescription("Run as if started in this folder, as git -C does")504    ),505    json: Flag.Boolean("json").pipe(506      Flag.withDefault(false),507      Flag.withDescription("Print machine-readable JSON")508    ),509    lane: Flag.String("lane").pipe(510      Flag.atLeast(0),511      Flag.withDescription(512        "Run only this lane (repeat for more); every lane when left out"513      )514    ),515    noLanes: Flag.Boolean("shape-only").pipe(516      Flag.withDefault(false),517      Flag.withDescription("Stop after the gate's shape stage: run no lanes")518    ),519    offline: Flag.Boolean("offline").pipe(520      Flag.withDefault(false),521      Flag.withDescription(522        "Call no platform: judge as if you held a live claim on the ask"523      )524    ),525    project: Flag.String("project").pipe(526      Flag.withSchema(ProjectName),527      Flag.optional,528      Flag.withDescription(529        "The project; the repo's remote names it when left out"530      )531    ),532  },533  (flags) =>534    Effect.gen(function* () {535      const output = yield* Output;536      const path = yield* Path.Path;537      const { json } = flags;538      const cwd = path.resolve(Option.getOrElse(flags.dir, () => "."));539540      const context = yield* repoContext(cwd).pipe(541        Effect.catchTag("NotARepo", (failure) => stop(failure.message))542      );543544      const { ask: askId, project } = yield* subjectOf(context, flags, json);545546      const claims = flags.offline547        ? Option.none<readonly ClaimView[]>()548        : Option.some(yield* claimsOn(project, json));549550      const claim = Option.flatMap(claims, (held) =>551        Array.findFirst(held, (each) => each.ask === askId)552      );553554      const handle = Option.getOrElse(555        Option.firstSomeOf([556          yield* signedInHandle,557          Option.map(claim, ({ claimant }) => claimant),558          Option.flatMap(context.repo, ({ handle: forkOf }) =>559            Option.flatMap(Option.fromUndefinedOr(forkOf), asHandle)560          ),561        ]),562        () => SOMEONE563      );564565      const base = yield* baseOf(context.root, flags.base, claim);566567      const bundler = yield* Effect.serviceOption(ConfigBundler);568569      const policy = yield* localPolicy(context.root, base, {570        initializer: handle,571        project,572      }).pipe(573        Option.match(bundler, {574          onNone: () => Effect.provide(ConfigBundlerBun),575          onSome: (found) => Effect.provideService(ConfigBundler, found),576        }),577        Effect.catchTag("RulesFailed", (failure) =>578          stop(579            `The policy at ${base} did not evaluate (${failure.reason}): ${failure.detail}`580          )581        )582      );583584      const stale = yield* staleGenerated({585        landed: policy.at,586        policy,587        project,588        root: context.root,589      });590591      yield* Effect.forEach(stale, (copy) => output.note(staleNote(copy)), {592        discard: true,593      });594595      const ask = Array.findFirst(policy.asks, ({ id }) => id === askId);596597      if (Option.isNone(ask)) {598        return yield* refuse(json, [new UnknownAsk({ ask: askId })]);599      }600601      const fork = claimForkName(project, askId, handle);602603      const facts = yield* localFacts({604        ask,605        base,606        claim: flags.offline607          ? Option.some(608              yield* syntheticClaim({609                ask: ask.value,610                claimant: handle,611                fork,612                origin: context.origin,613                policy,614              })615            )616          : claim,617        claimsHeld: Option.match(claims, {618          onNone: () => 1,619          onSome: (held) => held.filter(isLive).length,620        }),621        head: "HEAD",622        policy,623        pusher: Person.make({ handle }),624        root: context.root,625        target: PushTarget.ClaimFork({ ask: askId, claimant: handle, project }),626      }).pipe(627        Effect.catchTags({628          NotARepo: (failure) => stop(failure.message),629          RepoNotFound: () =>630            stop(`${context.root} could not be read as a git repo.`),631          UnknownRevision: (failure) => stop(failure.message),632        })633      );634635      if (flags.offline) {636        yield* output.note(637          `Offline: the parse stage judged a live claim on ${askId} made up for ${handle}; the platform judges the claim you hold.`638        );639      }640641      const refused = yield* runGate(pushStages, facts);642643      if (Option.isSome(refused)) {644        return yield* refuse(json, refused.value);645      }646647      const judged = { ask: askId, base: facts.base, head: facts.head };648649      if (flags.noLanes) {650        const checked: Checked = {651          ...judged,652          lanes: [],653          stage: "shape",654          ...staleField(stale),655        };656657        return yield* output.success({658          command: COMMAND,659          data: yield* Effect.orDie(encodeChecked(checked)),660          json,661          view: viewOf(checked),662        });663      }664665      const services = Context.make(666        ChildProcessSpawner.ChildProcessSpawner,667        yield* ChildProcessSpawner.ChildProcessSpawner668      ).pipe(669        Context.add(FileSystem.FileSystem, yield* FileSystem.FileSystem),670        Context.add(Path.Path, path)671      );672673      const all = lanesOf(policy, ask.value);674675      const lanes =676        flags.lane.length === 0677          ? all678          : all.filter(({ lane }) => flags.lane.includes(lane));679680      const unknown = flags.lane.filter(681        (wanted) => !all.some(({ lane }) => lane === wanted)682      );683684      if (unknown.length > 0) {685        return yield* stop(686          `No lane named ${unknown.join(", ")}; this project's lanes are ${all.map(({ lane }) => lane).join(", ")}.`687        );688      }689690      const runner = CheckRunnerLocal.layer({691        checkout: (at) =>692          checkoutOf({693            note: output.note,694            root: context.root,695            setup: Option.fromUndefinedOr(policy.run.setup),696          })(at).pipe(Effect.provide(services)),697      });698699      const run = yield* CheckRunner.use((checker) =>700        checker.run({701          at: CheckAt.cases.Commit.make({ commit: facts.head }),702          lanes,703          placeholders: [],704          project,705          proxies: [],706          repo: fork,707          run: policy.run,708        })709      ).pipe(710        Effect.provide(runner),711        Effect.catchTag("VerifierBlocked", (blocked) =>712          refuse(json, [blocked])713        ),714        Effect.flatMap((ran) => countedAskLane(policy, ask.value, ran))715      );716717      const failed = run.lanes.flatMap(({ command, lane, result }) =>718        result === "passed"719          ? []720          : [721              new ChecksFailed({722                lane,723                logRef: ChecksFailed.localRef(lane),724                next: command,725              }),726            ]727      );728729      for (const evidence of run.evidence) {730        if (evidence.signature !== undefined) {731          yield* output.note(`${evidence.lane} failed: ${evidence.signature}`);732        }733      }734735      const declared = Array.isReadonlyArrayNonEmpty(policy.ratchets);736      const counting = declared && flags.lane.length === 0;737738      if (declared && !counting) {739        yield* output.note(740          "The ratchets were not counted: --lane runs only the lanes it names."741        );742      }743744      const counts = counting745        ? yield* countRatchets({746            base: facts.base,747            head: facts.head,748            policy,749            project,750            repo: fork,751          }).pipe(Effect.provide(runner))752        : { moves: [], uncounted: [] };753754      for (const { ratchet, why } of counts.uncounted) {755        yield* output.note(756          `Could not count the ratchet ${ratchet} here: ${why}. The platform counts it after the push.`757        );758      }759760      const ratcheted = judgeMoves(facts, ask.value, counts.moves);761762      for (const move of ratcheted.decisions) {763        yield* output.note(764          `The ratchet ${moveText(move)}: a reasoned escape you add there asks a maintainer to raise it, so the answer will wait on that decision.`765        );766      }767768      const refusals = [...failed, ...ratcheted.refusals];769770      if (Array.isReadonlyArrayNonEmpty(refusals)) {771        return yield* refuse(json, refusals);772      }773774      const checked: Checked = {775        ...judged,776        lanes: run.lanes,777        ...ratchetsField(counts.moves),778        stage: "checks",779        ...staleField(stale),780      };781782      return yield* output.success({783        command: COMMAND,784        data: yield* Effect.orDie(encodeChecked(checked)),785        json,786        view: viewOf(checked),787      });788    })789).pipe(790  Command.withDescription(791    "Run the gate's checks on your answer locally, before you push."792  )793);