Skip to content
Myr

state.ts

This file

Path

packages/project/src/visibility/state.ts

1,061 lines · 30.3 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { ObjectId, Revision } from "@repo/artifacts/repo-host";2import type { RepoExists } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { commandFor } from "@repo/checks/kinds";5import { CheckSpec } from "@repo/protocol/domain/check";6import { DecisionSubject } from "@repo/protocol/domain/decision";7import type { Decision } from "@repo/protocol/domain/decision";8import type { Policy } from "@repo/protocol/domain/policy";9import { LedgerEntry } from "@repo/protocol/domain/visibility";10import type {11  Layer as LayerDeclaration,12  Members,13  SealedChecks,14  VisibilityPolicy,15} from "@repo/protocol/domain/visibility";16import {17  AreaName,18  BlobSha,19  CommitSha,20  keyOf,21  LayerName,22  ProjectName,23  RepoName,24  RepoPath,25  sameHandle,26} from "@repo/protocol/ids";27import type { Handle } from "@repo/protocol/ids";28import type { Posture } from "@repo/protocol/posture";29import { Person, Principal } from "@repo/protocol/principal";30import { areaRoots, suiteRoot } from "@repo/visibility/commitment";31import type { SuiteFile } from "@repo/visibility/commitment";32import { LayerRepos } from "@repo/visibility/layer-repos";33import { entriesForPolicy } from "@repo/visibility/ledger";34import { narrows } from "@repo/visibility/posture";35import {36  Array as Arr,37  Cause,38  Clock,39  Context,40  DateTime,41  Effect,42  Equal,43  Layer,44  Option,45  Order,46  Result,47  Schema,48  Struct,49} from "effect";5051import { decidersFor, openDecision } from "../attention/decisions.ts";52import { platformHandle } from "../attention/effects.ts";53import { decidersOn, nextDecisionId } from "../deciders.ts";54import type { ProjectSnapshot, ProjectWrites } from "../project-store.ts";55import type { LayerRow } from "../project-store/rows.ts";56import { noPlan, policyIn, ProjectVisibility } from "../visibility-port.ts";57import type {58  AdmissionPlan,59  HeldBackJob,60  LayerAccess,61  VisibilityEffect,62  VisibilityPlan,63  VisibilityPort,64} from "../visibility-port.ts";65import { judgeAdmission, planAdmission, PushedManifest } from "./admission.ts";66import type { LayerFile, OverlayFile } from "./admission.ts";67import { judgeAttempts } from "./claims.ts";68import {69  appended,70  declaredBy,71  ledgerFor,72  nextMove,73  nextSeq,74  postureCaughtUp,75  sealedInEffect,76  standing,77  visibilityIn,78} from "./ledger.ts";7980export class SaltSource extends Context.Service<81  SaltSource,82  { readonly next: Effect.Effect<Uint8Array> }83>()("project/SaltSource") {}8485export class AdmissionStarts extends Context.Service<86  AdmissionStarts,87  {88    readonly start: (input: {89      readonly head: CommitSha;90      readonly layer: LayerName;91      readonly project: ProjectName;92    }) => Effect.Effect<void>;93  }94>()("project/AdmissionStarts") {}9596export const manifestPath = RepoPath.make(`${Brand.configDir}/layer.json`);9798const Planned = Schema.Union([99  Schema.TaggedStruct("Provision", { repo: RepoName }),100  Schema.TaggedStruct("Admit", {101    head: CommitSha,102    layer: LayerName,103    project: ProjectName,104  }),105]).pipe(Schema.toTaggedUnion("_tag"));106107type Planned = typeof Planned.Type;108109const PlannedJson = Schema.toCodecJson(Planned);110111const encodePlanned = Schema.encodeEffect(PlannedJson);112113const decodePlanned = Schema.decodeUnknownEffect(PlannedJson);114115// A manifest may leave a clause out: admission refuses it (`UnstatedRequirement`) rather than read it as none.116const decodeManifest = Schema.decodeUnknownEffect(117  Schema.fromJsonString(PushedManifest)118);119120const repoFor = (project: ProjectName, layer: LayerName) =>121  RepoName.make(`${keyOf(project)}--${layer}`);122123const ownsRepo = (layer: LayerDeclaration) =>124  layer.audience !== "personal" && layer.audience !== "security";125126const membersOf = (policy: Policy, members: Members): readonly Handle[] =>127  members === "deciders"128    ? policy.deciders.flatMap(({ handles }) => handles)129    : members;130131const names = (handles: readonly Handle[], who: Principal) =>132  Principal.guards.Person(who) &&133  handles.some((handle) => sameHandle(handle, who.handle));134135const hexOf = (bytes: Uint8Array) =>136  [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");137138const byPath = Order.mapInput(139  Order.String,140  (file: { readonly path: RepoPath }) => file.path141);142143const areasOf = (checks: SealedChecks) =>144  Arr.sort(Object.keys(checks.areas), Order.String).map((area) =>145    AreaName.make(area)146  );147148interface Sealed extends SuiteFile {149  readonly author: Handle;150}151152const projectOf = (snapshot: ProjectSnapshot) =>153  Option.map(snapshot.project, ({ project }) => project);154155const declaredLayer = (156  visibility: Option.Option<VisibilityPolicy>,157  layer: LayerName158) =>159  Option.flatMap(visibility, ({ layers }) =>160    Arr.findFirst(layers, (each) => each.name === layer && ownsRepo(each))161  );162163const checksIn = (164  visibility: Option.Option<VisibilityPolicy>,165  layer: LayerName166) =>167  Option.filter(168    Option.flatMap(visibility, ({ checks }) => Option.fromUndefinedOr(checks)),169    (checks) => checks.layer === layer170  );171172const rowFor = (173  snapshot: ProjectSnapshot,174  project: ProjectName,175  layer: LayerName176): LayerRow =>177  Option.getOrElse(178    Arr.findFirst(snapshot.layers, ({ name }) => name === layer),179    () => ({ name: layer, repo: repoFor(project, layer) })180  );181182/** Excludes those who landed it, so a second maintainer countersigns; when nobody else decides, the maintainers as they are. */183const narrowingDecision = (input: {184  readonly after: Policy;185  readonly from: Posture;186  readonly landedBy: readonly Handle[];187  readonly now: DateTime.Utc;188  readonly project: ProjectName;189  readonly snapshot: ProjectSnapshot;190  readonly to: { readonly label: string; readonly posture: Posture };191}): Decision => {192  const noticeDays = input.after.visibility?.notice.narrowingDays ?? 0;193194  const others = decidersFor(input.after, []).filter(195    (decider) => !input.landedBy.some((by) => sameHandle(by, decider))196  );197198  const deciders = Arr.isReadonlyArrayNonEmpty(others)199    ? others200    : decidersOn(201        input.after,202        [],203        Option.match(input.snapshot.project, {204          onNone: () => platformHandle,205          onSome: ({ initializer }) => initializer,206        })207      );208209  return openDecision({210    deciders,211    evidence: [212      { label: "narrows to", value: input.to.label },213      {214        label: "notice",215        value: `${noticeDays} days: it stands no earlier than ${DateTime.formatIso(216          DateTime.add(input.now, { days: noticeDays })217        )}, once accepted`,218      },219      ...(input.landedBy.length === 0220        ? []221        : [222            {223              label: "landed by",224              value: Arr.dedupeWith(input.landedBy, sameHandle).join(", "),225            },226          ]),227    ],228    expireDays: input.after.budget.expireDays + noticeDays,229    id: nextDecisionId(input.snapshot.decisions, new Map()),230    now: input.now,231    project: input.project,232    subject: DecisionSubject.cases.PostureChange.make({233      from: input.from,234      to: input.to.posture,235    }),236  });237};238239const planOf = (240  writes: ProjectWrites,241  effects: readonly VisibilityEffect[] = []242): VisibilityPlan => ({ effects, writes });243244const effectOf = (id: string, planned: Planned) =>245  Effect.map(246    Effect.orDie(encodePlanned(planned)),247    (body): VisibilityEffect => ({ body, id })248  );249250const caughtUp = (251  snapshot: ProjectSnapshot,252  visibility: Option.Option<VisibilityPolicy>,253  now: DateTime.Utc254) =>255  postureCaughtUp(256    snapshot,257    standing({ decisions: snapshot.decisions, now, visibility }),258    nextSeq(snapshot.ledger)259  );260261const reach = (262  policy: Policy,263  layer: LayerDeclaration,264  who: Principal265): LayerAccess => {266  if (names(membersOf(policy, layer.writers), who)) {267    return "write";268  }269270  return names(membersOf(policy, layer.readers), who) ? "read" : "none";271};272273const judgeHeldBack: VisibilityPort["judgeHeldBack"] = (input, snapshot) => {274  const checks = Option.flatMap(visibilityIn(snapshot), ({ checks: sealed }) =>275    Option.fromUndefinedOr(sealed)276  );277278  if (Option.isNone(checks)) {279    return { refusals: [], trailer: Option.none(), writes: {} };280  }281282  const judged = judgeAttempts({283    ask: input.ask,284    attempts: snapshot.attempts,285    checks: checks.value,286    claimant: input.claimant,287    now: input.now,288    results: input.results,289    suite: input.pinned.suite,290  });291292  return {293    refusals: judged.refusals,294    trailer: judged.trailer,295    writes: judged.attempts.length === 0 ? {} : { attempts: judged.attempts },296  };297};298299const recordRead: VisibilityPort["recordRead"] = (input) => ({300  layerReads: [301    {302      at: input.at,303      handle: input.handle,304      layer: input.layer,305      ...Option.match(input.sha, {306        onNone: () => ({}),307        onSome: (sha) => ({ sha }),308      }),309    },310  ],311});312313const access: VisibilityPort["access"] = (who, layer, snapshot) =>314  Option.flatMap(policyIn(snapshot), (policy) =>315    Option.map(316      declaredLayer(Option.fromUndefinedOr(policy.visibility), layer),317      (declared) => reach(policy, declared, who)318    )319  );320321const readableLayers: VisibilityPort["readableLayers"] = (who, snapshot) =>322  new Set(323    Option.match(policyIn(snapshot), {324      onNone: () => [],325      onSome: (policy) =>326        (policy.visibility?.layers ?? []).flatMap((layer) =>327          ownsRepo(layer) && reach(policy, layer, who) !== "none"328            ? [layer.name]329            : []330        ),331    })332  );333334const onPolicy: VisibilityPort["onPolicy"] = (input, snapshot) =>335  Effect.gen(function* () {336    const project = projectOf(snapshot);337    const after = Option.fromUndefinedOr(input.after.visibility);338339    const before = Option.flatMap(input.before, (policy) =>340      Option.fromUndefinedOr(policy.visibility)341    );342343    if (344      Option.isNone(project) ||345      (Option.isNone(before) && Option.isNone(after))346    ) {347      return noPlan;348    }349350    const was = standing({351      decisions: snapshot.decisions,352      now: input.now,353      visibility: before,354    });355356    const owed = postureCaughtUp(snapshot, was, nextSeq(snapshot.ledger));357358    const declared = entriesForPolicy(359      before,360      after,361      nextSeq([...snapshot.ledger, ...owed]),362      input.now363    );364365    const fresh = Option.match(after, {366      onNone: (): readonly LayerRow[] => [],367      onSome: ({ layers }) =>368        layers.flatMap((layer) =>369          ownsRepo(layer) &&370          !snapshot.layers.some(({ name }) => name === layer.name)371            ? [{ name: layer.name, repo: repoFor(project.value, layer.name) }]372            : []373        ),374    });375376    const provisions = yield* Effect.forEach(fresh, ({ repo }) =>377      effectOf(`provision:${repo}`, Planned.cases.Provision.make({ repo }))378    );379380    // A first config stands at once; an unchanged one decides nothing again (a declined narrowing stays declined).381    const changed = Option.isSome(input.before) && !Equal.equals(before, after);382383    const to = declaredBy(after);384385    const decisions =386      changed && narrows(was.posture, to.posture)387        ? [388            narrowingDecision({389              after: input.after,390              from: was.posture,391              landedBy: input.landings.map(({ author }) => author),392              now: input.now,393              project: project.value,394              snapshot,395              to,396            }),397          ]398        : [];399400    return planOf(401      {402        ...appended([...owed, ...declared]),403        decisions,404        layers: fresh,405      },406      provisions407    );408  });409410const live = Effect.gen(function* () {411  const repos = yield* LayerRepos;412  const salts = yield* SaltSource;413  const admissions = yield* AdmissionStarts;414  // `pinSuite` and `ledger` take no `now`: the posture's notice runs on this clock.415  const clock = yield* Clock.Clock;416417  const nowOf = () => DateTime.makeUnsafe(clock.currentTimeMillisUnsafe());418419  const commitAt = (repo: RepoName, at: CommitSha) =>420    Effect.flatMap(Effect.orDie(repos.readCommit(repo, at)), (found) =>421      Option.match(found, {422        onNone: () => Effect.die(`the layer repo ${repo} has no commit ${at}`),423        onSome: Effect.succeed,424      })425    );426427  const blobsAt = (repo: RepoName, at: CommitSha) =>428    Effect.gen(function* () {429      const commit = yield* commitAt(repo, at);430      const blobs = new Map<string, ObjectId>();431432      const walk = (tree: ObjectId, prefix: string): Effect.Effect<void> =>433        Effect.gen(function* () {434          const entries = yield* Effect.flatMap(435            Effect.orDie(repos.readTree(repo, tree)),436            (found) =>437              Option.match(found, {438                onNone: () =>439                  Effect.die(`the layer repo ${repo} has no tree ${tree}`),440                onSome: Effect.succeed,441              })442          );443444          for (const entry of entries) {445            if (entry.type === "tree") {446              yield* walk(entry.sha, `${prefix}${entry.name}/`);447            } else if (entry.type === "blob") {448              blobs.set(`${prefix}${entry.name}`, entry.sha);449            }450          }451        });452453      yield* walk(commit.tree, "");454455      return blobs;456    });457458  const manifestAt = (repo: RepoName, layer: LayerName, at: CommitSha) =>459    Effect.gen(function* () {460      const bytes = yield* Effect.orDie(461        repos.readFile(repo, Revision.Commit({ sha: at }), manifestPath)462      );463464      if (Option.isNone(bytes)) {465        return Option.none<PushedManifest>();466      }467468      const manifest = Option.filter(469        yield* Effect.option(470          decodeManifest(new TextDecoder().decode(bytes.value))471        ),472        (decoded) => decoded.layer === layer473      );474475      if (Option.isNone(manifest)) {476        yield* Effect.logWarning(477          `the manifest in ${repo} at ${at} is no manifest of ${layer}`478        );479      }480481      return manifest;482    });483484  const sealedAt = (485    repo: RepoName,486    layer: LayerName,487    at: CommitSha,488    checks: SealedChecks489  ) =>490    Effect.gen(function* () {491      const manifest = yield* manifestAt(repo, layer, at);492493      if (Option.isNone(manifest)) {494        return [];495      }496497      const blobs = yield* blobsAt(repo, at);498      const areas = new Set<string>(Object.keys(checks.areas));499500      const uncited = Arr.dedupe(501        manifest.value.checks.flatMap(({ area, clause }) =>502          clause === undefined ? [area] : []503        )504      );505506      if (Arr.isReadonlyArrayNonEmpty(uncited)) {507        yield* Effect.logWarning(508          `a check in ${layer} at ${at} cites no clause and is left out of its suite`,509          { areas: uncited }510        );511      }512513      return Arr.sort(514        manifest.value.checks.flatMap((check): readonly Sealed[] => {515          const blob = blobs.get(check.path);516517          return blob === undefined ||518            !areas.has(check.area) ||519            check.clause === undefined520            ? []521            : [522                {523                  area: check.area,524                  author: check.author,525                  blob: BlobSha.make(blob),526                  path: check.path,527                },528              ];529        }),530        byPath531      );532    });533534  const landLayer = (input: {535    readonly checks: Option.Option<SealedChecks>;536    readonly head: CommitSha;537    readonly now: DateTime.Utc;538    readonly row: LayerRow;539    readonly seq: number;540  }): Effect.Effect<ProjectWrites> =>541    Effect.gen(function* () {542      const landed: LayerRow = {543        ...Struct.omit(input.row, ["proposed", "saltRef", "suiteRoot"]),544        admittedAt: input.now,545        landedSha: input.head,546      };547548      const files = yield* Option.match(input.checks, {549        onNone: () => Effect.succeed<readonly Sealed[]>([]),550        onSome: (checks) =>551          sealedAt(input.row.repo, input.row.name, input.head, checks),552      });553554      if (!Arr.isReadonlyArrayNonEmpty(files)) {555        return { layers: [landed] } satisfies ProjectWrites;556      }557558      const salt = yield* salts.next;559      const roots = yield* areaRoots(salt, files);560561      const published = [...roots].map(([area, root], index) => {562        const inArea = files.filter((file) => file.area === area);563564        return LedgerEntry.cases.CommitmentPublished.make({565          area,566          at: input.now,567          authors: Arr.dedupeWith(568            inArea.map(({ author }) => author),569            sameHandle570          ).length,571          checks: inArea.length,572          seq: input.seq + index,573          suite: root,574        });575      });576577      return {578        ...appended(published),579        layers: [580          {581            ...landed,582            saltRef: hexOf(salt),583            suiteRoot: yield* suiteRoot(salt, files),584          },585        ],586      } satisfies ProjectWrites;587    });588589  /** Deny by default: heads still proposed count too, so nothing from a layer enters a public tree, admitted or not. */590  const layerPaths: VisibilityPort["layerPaths"] = (snapshot) =>591    Effect.gen(function* () {592      const heads = snapshot.layers.flatMap(({ landedSha, proposed, repo }) =>593        Arr.dedupe(594          [landedSha, proposed].filter(595            (head): head is CommitSha => head !== undefined596          )597        ).map((at) => [repo, at] as const)598      );599600      const paths = yield* Effect.forEach(heads, ([repo, at]) =>601        Effect.map(blobsAt(repo, at), (blobs) => [...blobs.keys()])602      );603604      return new Set(paths.flat().map((path) => RepoPath.make(path)));605    });606607  const pinSuite: VisibilityPort["pinSuite"] = (_claim, snapshot) => {608    const visibility = visibilityIn(snapshot);609610    const inEffect = sealedInEffect(611      standing({ decisions: snapshot.decisions, now: nowOf(), visibility })612    );613614    return Option.flatMap(615      Option.filter(616        Option.flatMap(617          Option.flatMap(visibility, ({ checks }) =>618            Option.fromUndefinedOr(checks)619          ),620          (checks) =>621            Arr.findFirst(snapshot.layers, ({ name }) => name === checks.layer)622        ),623        () => inEffect624      ),625      ({ landedSha, suiteRoot: suite }) =>626        landedSha === undefined || suite === undefined627          ? Option.none()628          : Option.some({ at: landedSha, suite })629    );630  };631632  const heldBackJob: VisibilityPort["heldBackJob"] = (claim, snapshot) =>633    Effect.gen(function* () {634      const policy = policyIn(snapshot);635636      const checks = Option.flatMap(policy, ({ visibility }) =>637        Option.fromUndefinedOr(visibility?.checks)638      );639640      if (Option.isNone(policy) || Option.isNone(checks)) {641        return Option.none<HeldBackJob>();642      }643644      const row = Arr.findFirst(645        snapshot.layers,646        ({ name }) => name === checks.value.layer647      );648649      if (Option.isNone(row)) {650        return yield* Effect.die(651          `a claim was pinned to ${checks.value.layer}, which the project keeps no repo for`652        );653      }654655      const { at, suite } = claim.pinned;656      const { name, repo } = row.value;657      const sealed = yield* sealedAt(repo, name, at, checks.value);658659      const files = yield* Effect.forEach(sealed, ({ area, blob, path }) =>660        Effect.flatMap(661          Effect.orDie(repos.readBlob(repo, ObjectId.make(blob))),662          (content) =>663            Option.match(content, {664              // The blob's id stays out: unsalted, it would test a guess at the check.665              onNone: () =>666                Effect.die(667                  `the layer repo ${repo} lost a sealed check at ${at}`668                ),669              onSome: (bytes) => Effect.succeed({ area, content: bytes, path }),670            })671        )672      );673674      const runs = yield* Effect.forEach(sealed, ({ area, path }) =>675        Option.match(676          commandFor(677            CheckSpec.cases.RedThenGreen.make({ path }),678            policy.value.run679          ),680          {681            onNone: () =>682              Effect.die(683                "the run block's `test` names no `{path}` to run a sealed check by"684              ),685            onSome: ({ command }) => Effect.succeed({ area, command, path }),686          }687        )688      );689690      return Option.some<HeldBackJob>({691        areas: areasOf(checks.value),692        at,693        files,694        runs,695        suite,696      });697    });698699  const contentOf = (repo: RepoName, blob: ObjectId) =>700    Effect.flatMap(Effect.orDie(repos.readBlob(repo, blob)), (content) =>701      Option.match(content, {702        onNone: () =>703          Effect.die(`the layer repo ${repo} lost a blob its tree names`),704        onSome: Effect.succeed,705      })706    );707708  const overlayAt = (709    repo: RepoName,710    at: CommitSha,711    head: ReadonlyMap<string, ObjectId>712  ) =>713    Effect.gen(function* () {714      const found = yield* Effect.orDie(repos.readCommit(repo, at));715716      if (Option.isNone(found)) {717        yield* Effect.logWarning(718          `the layer repo ${repo} holds no known-bad commit ${at}`719        );720721        return Option.none<readonly OverlayFile[]>();722      }723724      const blobs = [...(yield* blobsAt(repo, at))].filter(725        ([path]) => !head.has(path)726      );727728      return Option.some(729        yield* Effect.forEach(blobs, ([path, blob]) =>730          Effect.map(contentOf(repo, blob), (content): OverlayFile => ({731            content,732            path: RepoPath.make(path),733          }))734        )735      );736    });737738  /** The runs carry a salt drawn here and kept nowhere: the landing draws its own. */739  const admissionOf = (740    input: { readonly head: CommitSha; readonly layer: LayerName },741    snapshot: ProjectSnapshot742  ) =>743    Effect.gen(function* () {744      const project = projectOf(snapshot);745      const policy = policyIn(snapshot);746      const checks = checksIn(visibilityIn(snapshot), input.layer);747748      const main = Option.flatMap(snapshot.project, ({ landed }) =>749        Option.fromUndefinedOr(landed)750      );751752      if (753        Option.isNone(project) ||754        Option.isNone(policy) ||755        Option.isNone(checks) ||756        Option.isNone(main)757      ) {758        return Option.none<AdmissionPlan>();759      }760761      const row = rowFor(snapshot, project.value, input.layer);762      const manifest = yield* manifestAt(row.repo, row.name, input.head);763764      if (Option.isNone(manifest)) {765        return Option.none<AdmissionPlan>();766      }767768      const head = yield* blobsAt(row.repo, input.head);769770      const landed =771        row.landedSha === undefined772          ? new Map<string, ObjectId>()773          : yield* blobsAt(row.repo, row.landedSha);774775      const previous =776        row.landedSha === undefined777          ? Option.none<PushedManifest>()778          : yield* manifestAt(row.repo, row.name, row.landedSha);779780      const files = new Map(781        yield* Effect.forEach(782          manifest.value.checks.flatMap(({ path }) =>783            Option.match(Option.fromUndefinedOr(head.get(path)), {784              onNone: () => [],785              onSome: (blob) => [[path, blob] as const],786            })787          ),788          ([path, blob]) =>789            Effect.map(790              contentOf(row.repo, blob),791              (content): readonly [string, LayerFile] => [792                path,793                { blob: BlobSha.make(blob), content },794              ]795            )796        )797      );798799      const knownBad = new Map(800        Arr.getSomes(801          yield* Effect.forEach(Arr.dedupe(manifest.value.knownBad), (tree) =>802            Effect.map(overlayAt(row.repo, tree, head), (overlay) =>803              Option.map(overlay, (laid) => [tree, laid] as const)804            )805          )806        )807      );808809      const sealed = manifest.value.checks.flatMap(({ area, path }) =>810        Option.match(Option.fromUndefinedOr(files.get(path)), {811          onNone: () => [],812          onSome: ({ blob }) =>813            Object.hasOwn(checks.value.areas, area)814              ? [{ area, blob, path }]815              : [],816        })817      );818819      const plan = planAdmission({820        files,821        head: input.head,822        knownBad,823        landed: new Map(824          [...landed].map(([path, blob]) => [path, BlobSha.make(blob)])825        ),826        main: main.value,827        manifest: manifest.value,828        policy: checks.value,829        previous,830        run: policy.value.run,831        suite: yield* suiteRoot(yield* salts.next, sealed),832      });833834      if (Result.isFailure(plan)) {835        yield* Effect.logWarning(836          `a check pushed to ${input.layer} cites no clause`,837          plan.failure838        );839840        return Option.none<AdmissionPlan>();841      }842843      return Option.some(plan.success);844    });845846  const onLayerPush: VisibilityPort["onLayerPush"] = (input, snapshot) =>847    Effect.gen(function* () {848      const project = projectOf(snapshot);849      const visibility = visibilityIn(snapshot);850851      // Only the layer's writers may push; anyone else, or an undeclared layer, moves nothing.852      if (853        Option.isNone(project) ||854        !Option.contains(855          access(Person.make({ handle: input.pusher }), input.layer, snapshot),856          "write"857        )858      ) {859        yield* Effect.logWarning(860          `a push to ${input.layer} by ${input.pusher} moves nothing: not one of its writers`861        );862863        return noPlan;864      }865866      const row = rowFor(snapshot, project.value, input.layer);867868      if (row.landedSha === input.head || row.proposed === input.head) {869        return noPlan;870      }871872      const owed = caughtUp(snapshot, visibility, input.now);873      const checks = checksIn(visibility, input.layer);874      const admits = Option.exists(checks, ({ admit }) => admit !== undefined);875876      // A push that changes no held-back check has no runs, and lands at once.877      const planned = admits878        ? yield* admissionOf({ head: input.head, layer: input.layer }, snapshot)879        : Option.none<AdmissionPlan>();880881      if (!admits || Option.exists(planned, ({ runs }) => runs.length === 0)) {882        const landed = yield* landLayer({883          checks,884          head: input.head,885          now: input.now,886          row,887          seq: nextSeq(snapshot.ledger) + owed.length,888        });889890        return planOf({891          ...landed,892          ...appended([...owed, ...(landed.ledger ?? [])]),893        });894      }895896      const start = Option.isSome(planned)897        ? [898            yield* effectOf(899              `admit:${input.layer}:${input.head}`,900              Planned.cases.Admit.make({901                head: input.head,902                layer: input.layer,903                project: project.value,904              })905            ),906          ]907        : [];908909      return planOf(910        { ...appended(owed), layers: [{ ...row, proposed: input.head }] },911        start912      );913    });914915  // Only a head still proposed has a plan (every run step asks again).916  const admissionPlan: VisibilityPort["admissionPlan"] = (input, snapshot) =>917    Arr.some(918      snapshot.layers,919      ({ name, proposed }) => name === input.layer && proposed === input.head920    )921      ? admissionOf(input, snapshot)922      : Effect.succeedNone;923924  const onAdmission: VisibilityPort["onAdmission"] = (input, snapshot) =>925    Effect.gen(function* () {926      const row = Arr.findFirst(927        snapshot.layers,928        ({ name, proposed }) => name === input.layer && proposed === input.head929      );930931      const planned = Option.isNone(row)932        ? Option.none<AdmissionPlan>()933        : yield* admissionOf(934            { head: input.head, layer: input.layer },935            snapshot936          );937938      if (Option.isNone(row) || Option.isNone(planned)) {939        return noPlan;940      }941942      const judged = judgeAdmission(planned.value, input.results, input.now);943      const areas = Arr.dedupe(planned.value.runs.map(({ area }) => area));944945      if (judged.admitted.length < areas.length) {946        yield* Effect.logWarning(947          `the push of ${input.head} to ${input.layer} was not admitted`,948          judged.refused949        );950951        return noPlan;952      }953954      const visibility = visibilityIn(snapshot);955      const owed = caughtUp(snapshot, visibility, input.now);956      const seq = nextSeq(snapshot.ledger) + owed.length;957958      const landed = yield* landLayer({959        checks: checksIn(visibility, input.layer),960        head: input.head,961        now: input.now,962        row: row.value,963        seq,964      });965966      const published = landed.ledger ?? [];967968      const roots = new Map(969        published.flatMap((entry) =>970          LedgerEntry.guards.CommitmentPublished(entry)971            ? [[entry.area, entry.suite] as const]972            : []973        )974      );975976      // Each admitted area cites its new commitment, never its runs' root (that salt was kept nowhere).977      const admitted = yield* Effect.forEach(judged.admitted, (entry, index) =>978        Option.match(Option.fromUndefinedOr(roots.get(entry.area)), {979          onNone: () =>980            Effect.die(981              `the landing of ${input.head} published no commitment for admitted area ${entry.area}`982            ),983          onSome: (suite) =>984            Effect.succeed({985              ...entry,986              seq: seq + published.length + index,987              suite,988            }),989        })990      );991992      return planOf({993        ...landed,994        ...appended([...owed, ...published, ...admitted]),995      });996    });997998  const run = (planned: Planned) =>999    Planned.match(planned, {1000      Admit: ({ head, layer, project }) =>1001        Effect.as(admissions.start({ head, layer, project }), true),1002      Provision: ({ repo }) =>1003        repos.create(repo).pipe(1004          Effect.as(true),1005          Effect.catchTag("RepoExists", (exists: RepoExists) =>1006            Effect.as(Effect.logDebug(`${exists.name} was made before`), true)1007          )1008        ),1009    });10101011  const settle: VisibilityPort["settle"] = (effect) =>1012    decodePlanned(effect.body).pipe(1013      Effect.flatMap(run),1014      // A failure runs again with the outbox; an interruption stays one.1015      Effect.catchCause((cause) =>1016        Cause.hasInterruptsOnly(cause)1017          ? Effect.interrupt1018          : Effect.as(1019              Effect.logWarning(1020                `visibility effect ${effect.id} did not settle`,1021                cause1022              ),1023              false1024            )1025      )1026    );10271028  const port: VisibilityPort = {1029    access,1030    admissionPlan,1031    heldBackJob,1032    judgeHeldBack,1033    layerPaths,1034    ledger: (project, snapshot) => ledgerFor(project, snapshot, nowOf()),1035    onAdmission,1036    onLayerPush,1037    onPolicy,1038    pinSuite,1039    readableLayers,1040    recordRead,1041    settle,1042    standing: (snapshot) => {1043      const now = nowOf();1044      const visibility = visibilityIn(snapshot);10451046      return {1047        posture: standing({ decisions: snapshot.decisions, now, visibility })1048          .posture,1049        until: nextMove({ decisions: snapshot.decisions, now, visibility }),1050      };1051    },1052  };10531054  return port;1055});10561057export const ProjectVisibilityLive: Layer.Layer<1058  never,1059  never,1060  AdmissionStarts | LayerRepos | SaltSource1061> = Layer.effect(ProjectVisibility, live);