Skip to content
Myr

seed.ts

This file

Path

scripts/lib/seed.ts

1,228 lines · 35.5 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { Brand } from "@repo/brand";2import { Client, Contracts } from "@repo/protocol/contracts";3import type { AskListing } from "@repo/protocol/domain/ask";4import { LayerManifest } from "@repo/protocol/domain/visibility";5import {6  addressOfRepo,7  AskId,8  CommitSha,9  Handle,10  keyOf,11  LayerName,12  ProjectName,13  RepoName,14  RepoPath,15  sameHandle,16} from "@repo/protocol/ids";17import { ProjectExists, Refusal } from "@repo/protocol/refusal";18import { explain } from "@repo/protocol/render";19import {20  Array,21  Config,22  Context,23  Deferred,24  Duration,25  Effect,26  FileSystem,27  Layer,28  Option,29  Path,30  Redacted,31  Ref,32  Schedule,33  Schema,34  Stream,35} from "effect";36import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";37import { ChildProcess, ChildProcessSpawner } from "effect/process";38import { RpcClient, RpcSerialization } from "effect/rpc";3940import { repoRoot } from "../../infra/stages.ts";4142export class SeedFailed extends Schema.TaggedError<SeedFailed>()("SeedFailed", {43  reason: Schema.String,44  refusals: Schema.optionalKey(Schema.NonEmptyArray(Refusal)),45}) {46  override get message() {47    return this.reason;48  }49}5051export interface SeedFile {52  readonly path: RepoPath;53  readonly content: Uint8Array;54}5556export interface AskFile {57  readonly path: RepoPath;58  readonly content: string;59}6061export interface AskStep {62  readonly id: AskId;63  readonly kind: string;64  readonly files: Array.NonEmptyReadonlyArray<AskFile>;65}6667/**68 * A parentless commit at the seed's fixed dates, so it is the same commit on69 * every platform and the layer's manifest can name it.70 */71export interface KnownBadStep {72  readonly branch: string;73  readonly commit: CommitSha;74  readonly message: string;75  readonly files: Array.NonEmptyReadonlyArray<SeedFile>;76}7778export interface LayerStep {79  readonly layer: LayerName;80  readonly repo: RepoName;81  readonly files: Array.NonEmptyReadonlyArray<SeedFile>;82  readonly knownBad: readonly KnownBadStep[];83}8485export interface SeedPlan {86  readonly project: ProjectName;87  readonly decider: Handle;88  readonly initFiles: Array.NonEmptyReadonlyArray<SeedFile>;89  readonly asks: readonly AskStep[];90  readonly ratchets: readonly string[];91  readonly layers: readonly LayerStep[];92  readonly copyOf?: ProjectName;93}9495const ASKS = `${Brand.configDir}/asks/`;9697/** Nothing under it enters the public tree. */98const LAYERS = "layers/";99100const KNOWN_BAD = /^known-bad\/(?<area>[^/]+)\.patch$/u;101102const MANIFEST_FILE = `${Brand.configDir}/layer.json`;103104const DIFF_START = /^(?:diff --git |--- )/mu;105106const PROJECT_FILE = `${Brand.configDir}/project.ts`;107108const ASK_FILE = /^(?<id>[^/]+)\.ask\.ts$/u;109110/** Env files whose values stay on each machine: an example that tracks one is refused, never read. */111const CLOSED_ENV = /^\.env(?:\.local|\.[^/]+\.local)?$/u;112113const KIND = /\bkinds\.(?<kind>\w+)\.ask\(/u;114115// The check file is the `path` the ask's kind takes; a kind that counts (`migrate`) names none.116const CHECK_PATH = /\bpath:\s*"(?<path>[^"]+)"/u;117118const WHOLE_TREE_DECIDER = /"\*\*"\s*:\s*\[\s*"(?<handle>[^"]+)"/u;119120const RATCHET = /"(?<name>[^"]+)"\s*:\s*check\.ratchet\./gu;121122const failed = (reason: string) => new SeedFailed({ reason });123124const decoded =125  <S extends Schema.Codec<unknown, string>>(schema: S, what: string) =>126  (raw: string) =>127    Schema.decodeEffect(schema)(raw).pipe(128      Effect.mapError(() => failed(`${what} ${JSON.stringify(raw)} is not one`))129    );130131const trackedIn = (root: string, dir: string) =>132  Effect.gen(function* () {133    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;134135    const listed = yield* spawner136      .string(137        ChildProcess.make("git", ["ls-files", "-z", "--", dir], { cwd: root })138      )139      .pipe(140        Effect.mapError((error) =>141          failed(`git ls-files ${dir} failed: ${error.message}`)142        )143      );144145    return listed146      .split("\0")147      .filter((path) => path.startsWith(`${dir}/`))148      .map((path) => path.slice(dir.length + 1));149  });150151const textOf = (fs: FileSystem.FileSystem, at: string, path: string) =>152  fs153    .readFileString(at)154    .pipe(Effect.mapError(() => failed(`can't read ${path}`)));155156// Fixed dates and no machine config, so the same files make the same commit everywhere.157const authorEnv = (handle: Handle) => ({158  GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",159  GIT_AUTHOR_EMAIL: `${handle}@example.com`,160  GIT_AUTHOR_NAME: handle,161  GIT_COMMITTER_DATE: "2026-10-06T12:00:00Z",162  GIT_COMMITTER_EMAIL: `${handle}@example.com`,163  GIT_COMMITTER_NAME: handle,164  GIT_CONFIG_GLOBAL: "/dev/null",165  GIT_CONFIG_NOSYSTEM: "1",166  GIT_TERMINAL_PROMPT: "0",167  LC_ALL: "C",168});169170const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>171  bytes.pipe(Stream.decodeText(), Stream.mkString);172173const runGit = (174  spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],175  cwd: string,176  args: readonly string[],177  env: Readonly<Record<string, string>>,178  settings: readonly string[] = []179) =>180  Effect.scoped(181    Effect.gen(function* () {182      const child = yield* spawner.spawn(183        ChildProcess.make("git", [...settings, ...args], {184          cwd,185          env,186          extendEnv: true,187        })188      );189190      const [stdout, stderr, code] = yield* Effect.all(191        [streamText(child.stdout), streamText(child.stderr), child.exitCode],192        { concurrency: "unbounded" }193      );194195      return { code: Number(code), stderr, stdout };196    })197  ).pipe(198    Effect.mapError(({ message }) =>199      failed(`git ${args[0] ?? ""} didn't run: ${message}`)200    )201  );202203const okOutput =204  (args: readonly string[]) =>205  ({ code, stderr, stdout }: Effect.Success<ReturnType<typeof runGit>>) =>206    code === 0207      ? Effect.succeed(stdout)208      : Effect.fail(209          failed(`git ${args.join(" ")} exited ${code}: ${stderr.trim()}`)210        );211212const writeTree = (213  fs: FileSystem.FileSystem,214  path: Path.Path,215  dir: string,216  files: readonly { readonly path: string; readonly content: Uint8Array }[]217) =>218  Effect.forEach(219    files,220    ({ content, path: file }) =>221      Effect.gen(function* () {222        const at = path.join(dir, file);223224        yield* fs.makeDirectory(path.dirname(at), { recursive: true });225        yield* fs.writeFile(at, content);226      }).pipe(Effect.mapError(() => failed(`can't write ${file} to seed`))),227    { discard: true }228  );229230const knownBadOf = (input: {231  readonly area: string;232  readonly decider: Handle;233  readonly initFiles: SeedPlan["initFiles"];234  readonly patch: string;235  readonly named: string;236}) =>237  Effect.scoped(238    Effect.gen(function* () {239      const fs = yield* FileSystem.FileSystem;240      const path = yield* Path.Path;241      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;242      const env = authorEnv(input.decider);243244      const git = (dir: string, args: readonly string[]) =>245        Effect.flatMap(runGit(spawner, dir, args, env), okOutput(args));246247      const words = yield* textOf(fs, input.patch, input.named);248      const message = words.split(DIFF_START)[0]?.trim() ?? "";249250      if (message === "" || !DIFF_START.test(words)) {251        return yield* failed(252          `${input.named} needs a few words on what it breaks, then its diff`253        );254      }255256      const dir = yield* fs257        .makeTempDirectoryScoped({ prefix: "seed-known-bad-" })258        .pipe(Effect.mapError(() => failed("can't make a temporary folder")));259260      yield* writeTree(fs, path, dir, input.initFiles);261      yield* git(dir, ["init", "--quiet", "--initial-branch=main"]);262      yield* git(dir, ["apply", input.patch]);263      yield* git(dir, ["add", "--all"]);264      yield* git(dir, ["commit", "--quiet", "--message", `${message}\n`]);265266      const commit = yield* decoded(267        CommitSha,268        `the commit ${input.named} makes`269      )((yield* git(dir, ["rev-parse", "HEAD"])).trim());270271      const paths = (yield* git(dir, ["ls-files", "-z"]))272        .split("\0")273        .filter((file) => file.length > 0);274275      const files = yield* Effect.forEach(paths, (file) =>276        fs.readFile(path.join(dir, file)).pipe(277          Effect.map((content) => ({ content, path: RepoPath.make(file) })),278          Effect.mapError(() => failed(`can't read back ${file}`))279        )280      );281282      if (!Array.isReadonlyArrayNonEmpty(files)) {283        return yield* failed(`${input.named} leaves no file in the tree`);284      }285286      return {287        branch: `known-bad/${input.area}`,288        commit,289        files,290        message,291      } satisfies KnownBadStep;292    })293  );294295const layerRepo = (project: ProjectName, layer: LayerName) =>296  RepoName.make(`${keyOf(project)}--${layer}`);297298const decodeManifest = Schema.decodeEffect(299  Schema.fromJsonString(LayerManifest)300);301302const layersOf = (input: {303  readonly decider: Handle;304  readonly folder: string;305  readonly initFiles: SeedPlan["initFiles"];306  readonly project: ProjectName;307  readonly tracked: readonly string[];308}) =>309  Effect.gen(function* () {310    const fs = yield* FileSystem.FileSystem;311    const path = yield* Path.Path;312    const root = yield* repoRoot;313    const at = (file: string) => path.join(root, input.folder, file);314315    const names = Array.dedupe(316      input.tracked.flatMap((file) =>317        file.startsWith(LAYERS)318          ? [file.slice(LAYERS.length).split("/")[0] ?? ""]319          : []320      )321    );322323    return yield* Effect.forEach(names, (name) =>324      Effect.gen(function* () {325        const layer = yield* decoded(LayerName, "the layer name")(name);326        const prefix = `${LAYERS}${name}/`;327328        const inLayer = input.tracked329          .filter((file) => file.startsWith(prefix))330          .map((file) => file.slice(prefix.length));331332        const files = yield* Effect.forEach(inLayer, (file) =>333          fs.readFile(at(`${prefix}${file}`)).pipe(334            Effect.map((content) => ({ content, path: RepoPath.make(file) })),335            Effect.mapError(() =>336              failed(`can't read ${input.folder}/${prefix}${file}`)337            )338          )339        );340341        if (!Array.isReadonlyArrayNonEmpty(files)) {342          return yield* failed(343            `git tracks nothing under ${input.folder}/${prefix}`344          );345        }346347        const knownBad = yield* Effect.forEach(348          inLayer.flatMap((file) => {349            const area = KNOWN_BAD.exec(file)?.groups?.area;350351            return area === undefined ? [] : [{ area, file }];352          }),353          ({ area, file }) =>354            knownBadOf({355              area,356              decider: input.decider,357              initFiles: input.initFiles,358              named: `${input.folder}/${prefix}${file}`,359              patch: at(`${prefix}${file}`),360            })361        );362363        if (inLayer.includes(MANIFEST_FILE)) {364          const named = `${input.folder}/${prefix}${MANIFEST_FILE}`;365366          const raw = yield* textOf(fs, at(`${prefix}${MANIFEST_FILE}`), named);367368          const manifest = yield* decodeManifest(raw).pipe(369            Effect.mapError((error) =>370              failed(`${named} is no layer manifest: ${error.message}`)371            )372          );373374          const made = knownBad.map(({ commit }) => commit);375376          if (manifest.layer !== layer) {377            return yield* failed(378              `${named} is the manifest of ${manifest.layer}, not ${layer}`379            );380          }381382          if (383            manifest.knownBad.toSorted().join(",") !== made.toSorted().join(",")384          ) {385            return yield* failed(386              `${named} names the known-bad commits ${JSON.stringify(manifest.knownBad)}, but its patches make ${JSON.stringify(made)}: write those into knownBad in layer.ts and layer.json`387            );388          }389        }390391        return {392          files,393          knownBad,394          layer,395          repo: layerRepo(input.project, layer),396        } satisfies LayerStep;397      })398    );399  });400401export const planSeed = (dir: string) =>402  Effect.gen(function* () {403    const fs = yield* FileSystem.FileSystem;404    const path = yield* Path.Path;405    const root = yield* repoRoot;406    const folder = dir.replace(/^\.\//u, "").replace(/\/+$/u, "");407    const tracked = yield* trackedIn(root, folder);408    const at = (file: string) => path.join(root, folder, file);409410    const closed = tracked.filter((file) =>411      CLOSED_ENV.test(path.basename(file))412    );413414    if (Array.isReadonlyArrayNonEmpty(closed)) {415      return yield* failed(416        `${folder} tracks ${closed.join(", ")}: the seed never reads a closed env file; untrack it first`417      );418    }419420    const project = yield* decoded(421      ProjectName,422      "the folder name"423    )(path.basename(folder));424425    const config = yield* textOf(fs, at(PROJECT_FILE), PROJECT_FILE);426427    const decider = yield* Effect.fromOption(428      Option.fromNullishOr(WHOLE_TREE_DECIDER.exec(config)?.groups?.handle)429    ).pipe(430      Effect.mapError(() =>431        failed(`${folder}/${PROJECT_FILE} names no maintainer for "**"`)432      ),433      Effect.flatMap(decoded(Handle, "the maintainer"))434    );435436    const ratchets = [...config.matchAll(RATCHET)].flatMap(437      ({ groups }) => groups?.name ?? []438    );439440    const askFiles = tracked.filter(441      (file) => file.startsWith(ASKS) && ASK_FILE.test(file.slice(ASKS.length))442    );443444    const asks = yield* Effect.forEach(askFiles, (file) =>445      Effect.gen(function* () {446        const id = yield* decoded(447          AskId,448          "the ask id"449        )(file.slice(ASKS.length).replace(/\.ask\.ts$/u, ""));450451        const text = yield* textOf(fs, at(file), file);452453        const kind = yield* Effect.fromOption(454          Option.fromNullishOr(KIND.exec(text)?.groups?.kind)455        ).pipe(456          Effect.mapError(() =>457            failed(`${folder}/${file} calls no kinds.<kind>.ask(…)`)458          )459        );460461        const check = Option.fromNullishOr(CHECK_PATH.exec(text)?.groups?.path);462463        if (Option.isSome(check) && !tracked.includes(check.value)) {464          return yield* failed(465            `${folder}/${file} names the check ${check.value}, which git doesn't track`466          );467        }468469        const checkFiles = yield* Effect.forEach(470          Option.toArray(check),471          (checkPath) =>472            Effect.map(textOf(fs, at(checkPath), checkPath), (content) => ({473              content,474              path: RepoPath.make(checkPath),475            }))476        );477478        return {479          files: Array.prepend(checkFiles, {480            content: text,481            path: RepoPath.make(file),482          }),483          id,484          kind,485        } satisfies AskStep;486      })487    );488489    const held = new Set(490      asks.flatMap(({ files }) => files.map((file) => String(file.path)))491    );492493    // A layer's files never enter the public tree.494    const initPaths = tracked.filter(495      (file) =>496        !file.startsWith(ASKS) && !file.startsWith(LAYERS) && !held.has(file)497    );498499    const initFiles = yield* Effect.forEach(initPaths, (file) =>500      fs.readFile(at(file)).pipe(501        Effect.map((content) => ({ content, path: RepoPath.make(file) })),502        Effect.mapError(() => failed(`can't read ${folder}/${file}`))503      )504    );505506    if (!Array.isReadonlyArrayNonEmpty(initFiles)) {507      return yield* failed(`git tracks nothing under ${folder} to seed`);508    }509510    const layers = yield* layersOf({511      decider,512      folder,513      initFiles,514      project,515      tracked,516    });517518    return {519      asks,520      decider,521      initFiles,522      layers,523      project,524      ratchets,525    } satisfies SeedPlan;526  });527528export const renameSeedPlan = (plan: SeedPlan, as: ProjectName): SeedPlan => ({529  ...plan,530  copyOf: plan.copyOf ?? plan.project,531  layers: plan.layers.map((layer) => ({532    ...layer,533    repo: layerRepo(as, layer.layer),534  })),535  project: as,536});537538export const StepResult = Schema.Literals(["done", "already"]);539540export type StepResult = typeof StepResult.Type;541542const step = { result: StepResult, target: Schema.String };543544export const SeedStep = Schema.TaggedUnion({545  Init: step,546  Layer: step,547  OpenAsk: step,548  Push: step,549});550551export type SeedStep = typeof SeedStep.Type;552553export class SeedTarget extends Context.Service<554  SeedTarget,555  {556    readonly operator: Handle;557    readonly clientFor: (handle: Handle) => Layer.Layer<Client, SeedFailed>;558    readonly requireSessions: (559      handles: readonly Handle[]560    ) => Effect.Effect<void, SeedFailed>;561    readonly refsOf: (562      project: ProjectName563    ) => Effect.Effect<ReadonlyMap<string, CommitSha>, SeedFailed>;564    readonly pushInitial: (565      project: ProjectName,566      files: SeedPlan["initFiles"],567      as: Handle568    ) => Effect.Effect<CommitSha, SeedFailed>;569    readonly refsAt: (570      repo: RepoName,571      as: Handle572    ) => Effect.Effect<573      Option.Option<ReadonlyMap<string, CommitSha>>,574      SeedFailed575    >;576    readonly pathsAt: (577      repo: RepoName,578      ref: string,579      as: Handle580    ) => Effect.Effect<readonly RepoPath[], SeedFailed>;581    readonly pushCommit: (input: {582      readonly repo: RepoName;583      readonly ref: string;584      readonly files: Array.NonEmptyReadonlyArray<SeedFile>;585      readonly as: Handle;586      readonly message: string;587    }) => Effect.Effect<CommitSha, SeedFailed>;588  }589>()("seed/SeedTarget") {}590591const isRefusal = Schema.is(Refusal);592593const isProjectExists = Schema.is(ProjectExists);594595interface CallFailure {596  readonly _tag: string;597  readonly message: string;598}599600const failedCall = (call: string) => (error: CallFailure) =>601  isRefusal(error)602    ? new SeedFailed({603        reason: `${call} was refused: ${explain([error])604          .map((line) => line.trim())605          .join("; ")}`,606        refusals: [error],607      })608    : failed(`${call} got no answer from the platform: ${error.message}`);609610export const MAIN_REF = "refs/heads/main";611612export const ready = (613  plans: readonly SeedPlan[]614): Effect.Effect<void, SeedFailed, SeedTarget> =>615  Effect.flatMap(Effect.service(SeedTarget), (target) =>616    target.requireSessions([617      target.operator,618      ...plans.map(({ decider }) => decider),619    ])620  );621622export interface SeededProject {623  readonly project: ProjectName;624  readonly asks: readonly AskListing[];625  readonly refs: readonly (readonly [string, CommitSha])[];626}627628export const seeded = (629  plans: readonly SeedPlan[]630): Effect.Effect<readonly SeededProject[], SeedFailed, SeedTarget> =>631  Effect.flatMap(Effect.service(SeedTarget), (target) =>632    Effect.forEach(plans, ({ decider, project }) =>633      Effect.gen(function* () {634        const { asks } = yield* Client.use((client) =>635          client.listAsks({ project })636        ).pipe(637          Effect.provide(target.clientFor(decider)),638          Effect.mapError(failedCall(`listAsks ${project}`))639        );640641        const refs = yield* target.refsOf(project);642643        return {644          asks,645          project,646          refs: [...refs].toSorted(([one], [other]) =>647            one.localeCompare(other)648          ),649        };650      })651    )652  );653654const LAYER_WAIT = { every: Duration.seconds(1), times: 30 } as const;655656class NotMadeYet extends Schema.TaggedError<NotMadeYet>()("NotMadeYet", {657  repo: RepoName,658}) {}659660// Known-bad commits go first, so admission finds every commit the manifest names.661const seedLayer = (662  layer: LayerStep,663  decider: Handle664): Effect.Effect<SeedStep, SeedFailed, SeedTarget> =>665  Effect.gen(function* () {666    const target = yield* SeedTarget;667668    const refs = yield* target.refsAt(layer.repo, decider).pipe(669      Effect.flatMap(670        Option.match({671          onNone: () => Effect.fail(new NotMadeYet({ repo: layer.repo })),672          onSome: Effect.succeed,673        })674      ),675      Effect.retry({676        schedule: Schedule.spaced(LAYER_WAIT.every),677        times: LAYER_WAIT.times,678        while: Schema.is(NotMadeYet),679      }),680      Effect.catchTag("NotMadeYet", ({ repo }) =>681        Effect.fail(682          failed(683            `the platform never made ${repo}: does the project's config declare the layer ${layer.layer}, and is its visibility cartridge plugged in?`684          )685        )686      )687    );688689    const reported = (result: StepResult) =>690      SeedStep.cases.Layer.make({ result, target: layer.repo });691692    if (refs.has(MAIN_REF)) {693      return reported("already");694    }695696    yield* Effect.forEach(697      layer.knownBad.filter(698        ({ branch, commit }) => refs.get(`refs/heads/${branch}`) !== commit699      ),700      ({ branch, commit, files, message }) =>701        Effect.flatMap(702          target.pushCommit({703            as: decider,704            files,705            message,706            ref: `refs/heads/${branch}`,707            repo: layer.repo,708          }),709          (made) =>710            made === commit711              ? Effect.void712              : Effect.fail(713                  failed(714                    `${layer.repo}'s ${branch} came out as ${made}, not the ${commit} its manifest names`715                  )716                )717        ),718      { discard: true }719    );720721    yield* target.pushCommit({722      as: decider,723      files: layer.files,724      message: `Start ${layer.repo}`,725      ref: MAIN_REF,726      repo: layer.repo,727    });728729    return reported("done");730  });731732/** `made` runs as soon as the project exists, so a run that fails later still records it. */733export const runSeedWith = <R>(734  plan: SeedPlan,735  made: (plan: SeedPlan) => Effect.Effect<void, SeedFailed, R>736): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget | R> =>737  Effect.scoped(738    Effect.gen(function* () {739      const target = yield* SeedTarget;740      const { decider, project } = plan;741742      yield* ready([plan]);743744      const operator = Context.get(745        yield* Layer.build(target.clientFor(target.operator)),746        Client747      );748749      const asker = Context.get(750        yield* Layer.build(target.clientFor(decider)),751        Client752      );753754      const init = yield* operator.initProject({ project }).pipe(755        Effect.as<StepResult>("done"),756        Effect.catchTag("ProjectExists", (exists) =>757          plan.copyOf === undefined758            ? Effect.succeed<StepResult>("already")759            : Effect.fail(exists)760        ),761        Effect.mapError((error) =>762          isProjectExists(error) && plan.copyOf !== undefined763            ? new SeedFailed({764                reason: `${project} is taken: --as makes a fresh copy of ${plan.copyOf}, so name a project nobody has`,765                refusals: [error],766              })767            : failedCall(`initProject ${project}`)(error)768        )769      );770771      if (init === "done") {772        yield* made(plan);773      }774775      const landed = (yield* target.refsOf(project)).has(MAIN_REF);776777      const push = landed778        ? "already"779        : yield* target780            .pushInitial(project, plan.initFiles, target.operator)781            .pipe(Effect.as<StepResult>("done"));782783      const asks = yield* Effect.forEach(plan.asks, ({ files, id }) =>784        asker.showAsk({ ask: id, project }).pipe(785          Effect.as<StepResult>("already"),786          Effect.catchTag("UnknownAsk", () =>787            Effect.as(788              asker.openAsk({ ask: id, files, project }),789              "done" as const790            )791          ),792          Effect.mapError(failedCall(`openAsk ${project}/${id} as ${decider}`)),793          Effect.map((result) =>794            SeedStep.cases.OpenAsk.make({ result, target: `${project}/${id}` })795          )796        )797      );798799      const layers = yield* Effect.forEach(plan.layers, (layer) =>800        seedLayer(layer, decider)801      );802803      return [804        SeedStep.cases.Init.make({ result: init, target: project }),805        SeedStep.cases.Push.make({ result: push, target: project }),806        ...asks,807        ...layers,808      ];809    })810  );811812export const runSeed = (813  plan: SeedPlan814): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget> =>815  runSeedWith(plan, () => Effect.void);816817export interface Platform {818  readonly origin: string;819  readonly operator: Handle;820  readonly tokens: ReadonlyMap<Handle, Redacted.Redacted>;821  readonly sessionsFrom: string;822}823824const refsIn = (listed: string) =>825  Effect.map(826    Effect.forEach(827      listed.split("\n").filter((line) => line.length > 0),828      (line) => {829        const [sha = "", ref = ""] = line.split("\t");830831        return ref.length === 0832          ? Effect.fail(failed(`git ls-remote listed ${JSON.stringify(line)}`))833          : Effect.map(834              decoded(CommitSha, `the commit ls-remote lists for ${ref}`)(sha),835              (commit) => [ref, commit] as const836            );837      }838    ),839    (refs): ReadonlyMap<string, CommitSha> => new Map(refs)840  );841842const NOT_SERVED = /\bnot found\b|\b404\b/u;843844// The token reaches git through its env, never its argv.845const TOKEN_VAR = "SEED_GIT_TOKEN";846847const helperFor = (handle: Handle) =>848  `!f() { test "$1" = get || exit 0; echo username=${handle}; echo "password=$${TOKEN_VAR}"; }; f`;849850const gitEnv = (handle: Handle, token: Redacted.Redacted) => ({851  ...authorEnv(handle),852  [TOKEN_VAR]: Redacted.value(token),853});854855const clientAt = (856  origin: string,857  token: Redacted.Redacted858): Layer.Layer<Client> =>859  Layer.effect(Client)(RpcClient.make(Contracts)).pipe(860    Layer.provide(861      RpcClient.layerProtocolHttp({862        transformClient: HttpClient.mapRequest(863          HttpClientRequest.bearerToken(token)864        ),865        url: `${origin}/rpc`,866      })867    ),868    Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])869  );870871export const platformTarget = (872  platform: Platform873): Layer.Layer<874  SeedTarget,875  never,876  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path877> =>878  Layer.effect(SeedTarget)(879    Effect.gen(function* () {880      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;881      const fs = yield* FileSystem.FileSystem;882      const path = yield* Path.Path;883      const { origin } = platform;884885      const remoteOf = (repo: ProjectName | RepoName) =>886        repo.includes("/")887          ? `${origin}/${repo}.git`888          : `${origin}/${Option.getOrElse(addressOfRepo(RepoName.make(repo)), () => repo)}.git`;889890      const tokenOf = (handle: Handle) =>891        Option.fromNullishOr(892          [...platform.tokens].find(([known]) => sameHandle(known, handle))?.[1]893        );894895      const missing = (handles: Array.NonEmptyReadonlyArray<Handle>) =>896        failed(897          `the platform at ${origin} has no session for ${handles.join(", ")}: add ${handles.length === 1 ? "one" : "each"} to ${platform.sessionsFrom}, then run the seed again`898        );899900      const requireSessions = (handles: readonly Handle[]) => {901        const lacking = Array.dedupeWith(902          handles.filter((handle) => Option.isNone(tokenOf(handle))),903          sameHandle904        );905906        return Array.isReadonlyArrayNonEmpty(lacking)907          ? Effect.fail(missing(lacking))908          : Effect.void;909      };910911      const gitAs = (as: Handle, cwd: string, args: readonly string[]) =>912        Effect.flatMap(913          Effect.fromOption(tokenOf(as)).pipe(914            Effect.mapError(() => missing([as]))915          ),916          (token) =>917            runGit(spawner, cwd, args, gitEnv(as, token), [918              "-c",919              "credential.helper=",920              "-c",921              `credential.helper=${helperFor(as)}`,922            ])923        );924925      const gitOk = (as: Handle, cwd: string, args: readonly string[]) =>926        Effect.flatMap(gitAs(as, cwd, args), okOutput(args));927928      // An empty folder, so git reads no repo's config.929      const scratch = fs930        .makeTempDirectoryScoped({ prefix: "seed-" })931        .pipe(Effect.mapError(() => failed("can't make a temporary folder")));932933      const refsOf = (project: ProjectName) =>934        Effect.scoped(935          Effect.gen(function* () {936            const listed = yield* gitOk(platform.operator, yield* scratch, [937              "ls-remote",938              remoteOf(project),939            ]);940941            return yield* refsIn(listed);942          })943        );944945      const refsAt = (repo: RepoName, as: Handle) =>946        Effect.scoped(947          Effect.gen(function* () {948            const listed = yield* gitAs(as, yield* scratch, [949              "ls-remote",950              remoteOf(repo),951            ]);952953            if (listed.code === 0) {954              return Option.some(yield* refsIn(listed.stdout));955            }956957            return NOT_SERVED.test(listed.stderr)958              ? Option.none<ReadonlyMap<string, CommitSha>>()959              : yield* failed(960                  `git ls-remote ${repo} as ${as} exited ${listed.code}: ${listed.stderr.trim()}`961                );962          })963        );964965      const pathsAt = (repo: RepoName, ref: string, as: Handle) =>966        Effect.scoped(967          Effect.gen(function* () {968            const dir = yield* scratch;969970            yield* gitOk(as, dir, ["init", "--quiet"]);971            yield* gitOk(as, dir, ["fetch", "--quiet", remoteOf(repo), ref]);972973            const listed = yield* gitOk(as, dir, [974              "ls-tree",975              "-r",976              "-z",977              "--name-only",978              "FETCH_HEAD",979            ]);980981            return listed982              .split("\0")983              .filter((file) => file.length > 0)984              .map((file) => RepoPath.make(file));985          })986        );987988      const pushCommit = (input: {989        readonly repo: ProjectName | RepoName;990        readonly ref: string;991        readonly files: Array.NonEmptyReadonlyArray<SeedFile>;992        readonly as: Handle;993        readonly message: string;994      }) =>995        Effect.scoped(996          Effect.gen(function* () {997            const dir = yield* scratch;998            const { as } = input;9991000            yield* writeTree(fs, path, dir, input.files);1001            yield* gitOk(as, dir, ["init", "--quiet", "--initial-branch=main"]);1002            yield* gitOk(as, dir, ["add", "--all"]);10031004            yield* gitOk(as, dir, [1005              "commit",1006              "--quiet",1007              "--message",1008              `${input.message}\n`,1009            ]);10101011            yield* gitOk(as, dir, [1012              "push",1013              "--quiet",1014              remoteOf(input.repo),1015              `HEAD:${input.ref}`,1016            ]);10171018            return yield* decoded(1019              CommitSha,1020              "the commit git made"1021            )((yield* gitOk(as, dir, ["rev-parse", "HEAD"])).trim());1022          })1023        );10241025      // git ends a message with one newline whether given one or not.1026      const pushInitial = (1027        project: ProjectName,1028        files: SeedPlan["initFiles"],1029        as: Handle1030      ) =>1031        pushCommit({1032          as,1033          files,1034          message: `Start ${project}`,1035          ref: MAIN_REF,1036          repo: project,1037        });10381039      return SeedTarget.of({1040        clientFor: (handle) =>1041          Option.match(tokenOf(handle), {1042            onNone: () => Layer.effect(Client)(Effect.fail(missing([handle]))),1043            onSome: (token) => clientAt(origin, token),1044          }),1045        operator: platform.operator,1046        pathsAt,1047        pushCommit,1048        pushInitial,1049        refsAt,1050        refsOf,1051        requireSessions,1052      });1053    })1054  );10551056const SERVE_WORLD = "apps/platform/test/serve-world.ts";10571058const WORLD_START = Duration.seconds(60);10591060const decodeServing = Schema.decodeUnknownOption(1061  Schema.fromJsonString(Schema.Struct({ origin: Schema.String }))1062);10631064/** The stages' operator handle, so the examples get the namespace they have on a stage. */1065export const worldOperator = Handle.make("oscabriel");10661067const worldToken = (handle: Handle) =>1068  Redacted.make(`${handle.toLowerCase()}-seed-world-token-0123456789abcdef`);10691070export const servedWorld = (sessions: ReadonlyMap<Handle, Redacted.Redacted>) =>1071  Effect.gen(function* () {1072    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;1073    const root = yield* repoRoot;10741075    const child = yield* spawner1076      .spawn(1077        ChildProcess.make("bun", [SERVE_WORLD], {1078          cwd: root,1079          env: {1080            WORLD_SESSIONS: JSON.stringify(1081              Object.fromEntries(1082                [...sessions].map(([handle, token]) => [1083                  Redacted.value(token),1084                  handle,1085                ])1086              )1087            ),1088          },1089          extendEnv: true,1090        })1091      )1092      .pipe(1093        Effect.mapError((error) =>1094          failed(`bun ${SERVE_WORLD} didn't start: ${error.message}`)1095        )1096      );10971098    // Both streams are drained so the world never blocks on a full pipe.1099    const said = yield* Ref.make("");1100    const serving = yield* Deferred.make<string>();11011102    yield* Stream.decodeText(child.stderr).pipe(1103      Stream.runForEach((chunk) =>1104        Ref.update(said, (before) => `${before}${chunk}`.slice(-4000))1105      ),1106      Effect.ignore,1107      Effect.forkScoped1108    );11091110    yield* Stream.splitLines(Stream.decodeText(child.stdout)).pipe(1111      Stream.runForEach((line) =>1112        Option.match(decodeServing(line), {1113          onNone: () => Effect.void,1114          onSome: ({ origin }) => Deferred.succeed(serving, origin),1115        })1116      ),1117      Effect.ignore,1118      Effect.forkScoped1119    );11201121    const ended = child.exitCode.pipe(1122      Effect.ignore,1123      Effect.andThen(Ref.get(said)),1124      Effect.flatMap((stderr) =>1125        Effect.fail(failed(`the world ended before it served: ${stderr}`))1126      )1127    );11281129    return yield* Effect.raceFirst(Deferred.await(serving), ended).pipe(1130      Effect.timeoutOption(WORLD_START),1131      Effect.flatMap(1132        Option.match({1133          onNone: () =>1134            Effect.fail(1135              failed(1136                `the world didn't serve within ${Duration.format(WORLD_START)}`1137              )1138            ),1139          onSome: Effect.succeed,1140        })1141      )1142    );1143  });11441145export const worldTarget = (1146  people: readonly Handle[]1147): Layer.Layer<1148  SeedTarget,1149  SeedFailed,1150  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path1151> =>1152  Layer.unwrap(1153    Effect.gen(function* () {1154      const tokens = new Map(1155        [worldOperator, ...people].map((handle) => [handle, worldToken(handle)])1156      );11571158      const origin = yield* servedWorld(tokens);11591160      return platformTarget({1161        operator: worldOperator,1162        origin,1163        sessionsFrom: "the world's sessions (worldTarget's people)",1164        tokens,1165      });1166    })1167  );11681169export interface StageTokens {1170  readonly sessions: string;1171  readonly operator: string;1172}11731174const decodeSessions = Schema.decodeUnknownEffect(1175  Schema.fromJsonString(Schema.Record(Schema.String, Handle))1176);11771178export const stageTarget = (1179  origin: string,1180  tokens: StageTokens1181): Layer.Layer<1182  SeedTarget,1183  SeedFailed,1184  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path1185> =>1186  Layer.unwrap(1187    Effect.gen(function* () {1188      const operatorToken = yield* Config.Redacted(tokens.operator).pipe(1189        Effect.mapError(() =>1190          failed(1191            `no ${tokens.operator} in the environment: run the seed under \`bunx varlock run --path apps/platform/ --\``1192          )1193        )1194      );11951196      const listed = yield* Config.option(Config.String(tokens.sessions)).pipe(1197        Effect.mapError(() => failed(`${tokens.sessions} can't be read`))1198      );11991200      const sessions = yield* decodeSessions(1201        Option.getOrElse(listed, () => "{}")1202      ).pipe(1203        Effect.mapError(() =>1204          failed(`${tokens.sessions} is not a JSON object from token to handle`)1205        )1206      );12071208      const { handle } = yield* Client.use((client) => client.status({})).pipe(1209        Effect.provide(clientAt(origin, operatorToken)),1210        Effect.mapError(1211          failedCall(`status as the operator (${tokens.operator})`)1212        )1213      );12141215      return platformTarget({1216        operator: handle,1217        origin,1218        sessionsFrom: tokens.sessions,1219        // The operator's token wins, as it does on the platform.1220        tokens: new Map([1221          [handle, operatorToken],1222          ...Object.entries(sessions)1223            .filter(([, person]) => !sameHandle(person, handle))1224            .map(([token, person]) => [person, Redacted.make(token)] as const),1225        ]),1226      });1227    })1228  );