Skip to content
Myr

core-loop.ts

This file

Path

scripts/lib/smoke/core-loop.ts

915 lines · 22.9 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 1–4why, one step back
1import { Brand } from "@repo/brand";
2import { AnswerView } from "@repo/protocol/domain/answer";3import { Ask } from "@repo/protocol/domain/ask";4import { ClaimView } from "@repo/protocol/domain/claim";

Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f

line 5why, one step back
5import { Decision, DecisionSubject } from "@repo/protocol/domain/decision";

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

line 6why, one step back
6import { Outcome } from "@repo/protocol/domain/outcome";

Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f

line 7why, one step back
7import { DraftState, Proposal } from "@repo/protocol/domain/proposal";

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

line 8why, one step back
8import { Envelope } from "@repo/protocol/envelope";

Merge build/1007oscabrielbefore adoption77fa97a

lines 9–16why, one step back
9import {
10 AskId,11 CommitSha,12 Handle,13 LandedSha,14 ProjectName,15} from "@repo/protocol/ids";16import type { ProposalId } from "@repo/protocol/ids";

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 17–42why, one step back
17import { explain } from "@repo/protocol/render";
18import {19 Array,20 Config,21 Duration,22 Effect,23 FileSystem,24 Option,25 Redacted,26 Schedule,27 Schema,28 Stream,29} from "effect";30import { ChildProcess, ChildProcessSpawner } from "effect/process";3132import { cliEntry, personEnv } from "../swarm/workspace.ts";3334export const LoopStep = Schema.Literals([35 "people",36 "init",37 "open-ask",38 "claim",39 "out-of-scope",40 "answer",41 "landing",42 "verdict-note",

Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f

lines 43–45why, one step back
43 "draft-propose",
44 "draft-ready",45 "draft-accept",

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 46–49why, one step back
46]);
4748export type LoopStep = typeof LoopStep.Type;49

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 50why, one step back
50// Never holds a token.

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 51–124why, one step back
51export class LoopFailed extends Schema.TaggedError<LoopFailed>()("LoopFailed", {
52 reason: Schema.String,53 step: LoopStep,54}) {55 override get message() {56 return `${this.step}: ${this.reason}`;57 }58}5960const sdk = `${Brand.cliPackage}/rules`;6162export const ASK = AskId.make("parse-year");6364const SOURCE = "src/parse.ts";6566const CHECK = `test/${ASK}.test.ts`;6768const README =69 "A throwaway project smoke's core loop makes, answers and lands.\n";7071const startFiles = (answerer: Handle) => ({72 [`${Brand.configDir}/project.ts`]: [73 `import { kinds, project } from "${sdk}";`,74 "",75 "export default project({",76 " kinds: [kinds.fix],",77 ' run: { checks: {}, test: "bun test {path}" },',78 "});",79 "",80 ].join("\n"),81 [`${Brand.configDir}/vouched.td`]: `${answerer}\n`,82 "README.md": README,83 "package.json": '{ "name": "smoke", "private": true }\n',84 [SOURCE]: "export const parse = (iso: string) => ({ iso, year: 0 });\n",85});8687const askFiles = [88 {89 content: [90 `import { kinds, territory } from "${sdk}";`,91 "",92 "export default kinds.fix.ask({",93 ` path: "${CHECK}",`,94 ` territory: territory.paths("${SOURCE}"),`,95 ' want: "parse reads the year of an ISO date",',96 "});",97 "",98 ].join("\n"),99 path: `${Brand.configDir}/asks/${ASK}.ask.ts`,100 },101 {102 content: [103 'import { expect, it } from "bun:test";',104 "",105 `import { parse } from "../${SOURCE}";`,106 "",107 'it("parse reads the year of an ISO date", () => {',108 ' expect(parse("2026-10-13").year).toBe(2026);',109 "});",110 "",111 ].join("\n"),112 path: CHECK,113 },114] as const;115116const yearRead =117 "export const parse = (iso: string) => ({ iso, year: Number(iso.slice(0, 4)) });\n";118119interface Ran {120 readonly code: number;121 readonly stdout: string;122 readonly stderr: string;123}124

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 125why, one step back
125// A cold Checker runs an ask's check twice.

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 126–271why, one step back
126const PATIENCE = Duration.minutes(10);
127128export interface LoopPerson {129 readonly handle: Handle;130 readonly home: string;131 readonly env: Readonly<Record<string, string | undefined>>;132 readonly token: Redacted.Redacted;133}134135const failed = (step: LoopStep, reason: string) =>136 new LoopFailed({ reason, step });137138const scrubbed = (text: string, tokens: readonly Redacted.Redacted[]) => {139 let clean = text;140141 for (const token of tokens) {142 clean = clean.replaceAll(Redacted.value(token), "<redacted>");143 }144145 return clean;146};147148const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>149 bytes.pipe(Stream.decodeText(), Stream.mkString);150151const run = (152 step: LoopStep,153 person: Pick<LoopPerson, "env" | "token">,154 command: string,155 args: readonly string[],156 cwd?: string157): Effect.Effect<Ran, LoopFailed, ChildProcessSpawner.ChildProcessSpawner> =>158 Effect.scoped(159 Effect.gen(function* () {160 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;161162 const child = yield* spawner.spawn(163 ChildProcess.make(command, args, {164 cwd,165 env: { ...person.env },166 extendEnv: true,167 stdin: "ignore",168 })169 );170171 const [stdout, stderr, code] = yield* Effect.all(172 [textOf(child.stdout), textOf(child.stderr), child.exitCode],173 { concurrency: "unbounded" }174 );175176 return { code: Number(code), stderr, stdout };177 })178 ).pipe(179 Effect.mapError(({ message }) =>180 failed(181 step,182 `${command} didn't run: ${scrubbed(message, [person.token])}`183 )184 ),185 Effect.timeoutOrElse({186 duration: PATIENCE,187 orElse: () =>188 Effect.fail(189 failed(190 step,191 `${command} ${args[0] ?? ""} took longer than ${Duration.format(PATIENCE)}`192 )193 ),194 })195 );196197const gitOk = (198 step: LoopStep,199 person: LoopPerson,200 cwd: string,201 args: readonly string[]202) =>203 Effect.flatMap(run(step, person, "git", args, cwd), (ran) =>204 ran.code === 0205 ? Effect.succeed(ran.stdout.trim())206 : Effect.fail(207 failed(208 step,209 scrubbed(210 `git ${args.join(" ")} exited ${ran.code}: ${ran.stderr.trim()}`,211 [person.token]212 )213 )214 )215 );216217const cli = <A, I>(218 step: LoopStep,219 person: Pick<LoopPerson, "env" | "token">,220 args: readonly string[],221 data: Schema.Codec<A, I>,222 cwd?: string223) =>224 Effect.gen(function* () {225 const ran = yield* run(226 step,227 person,228 "bun",229 [cliEntry, ...args, "--json"],230 cwd231 );232233 const said = scrubbed(234 (ran.stderr.trim() === "" ? ran.stdout : ran.stderr).trim().slice(0, 800),235 [person.token]236 );237238 const envelope = yield* Schema.decodeEffect(239 Schema.fromJsonString(Envelope(data))240 )(ran.stdout.trim()).pipe(241 Effect.mapError(() =>242 failed(243 step,244 `${Brand.cli} ${args.join(" ")} exited ${ran.code} without its JSON: ${said}`245 )246 )247 );248249 return envelope.ok250 ? envelope.data251 : yield* failed(252 step,253 `${Brand.cli} ${args[0] ?? ""} was refused: ${explain(254 envelope.refusals255 )256 .map((line) => line.trim())257 .join("; ")}`258 );259 });260261const helperShim = [262 "#!/bin/sh",263 `# ${Brand.gitCredentialHelper} for smoke's core loop: this repo's CLI from source, under Bun.`,264 `exec bun '${cliEntry.replaceAll("'", `'\\''`)}' credential "$@"`,265 "",266].join("\n");267268const SHIM_MODE = 0o755;269270const HOME_MODE = 0o700;271

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 272why, one step back
272// A gitconfig of their own, so nothing of this machine's git or CLI config answers instead.

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 273–401why, one step back
273export const personAt = (input: {
274 readonly home: string;275 readonly origin: string;276 readonly token: Redacted.Redacted;277}): Effect.Effect<278 LoopPerson,279 LoopFailed,280 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem281> =>282 Effect.gen(function* () {283 const fs = yield* FileSystem.FileSystem;284 const { home, origin, token } = input;285 const bin = `${home}/bin`;286 const gitconfig = `${home}/gitconfig`;287288 yield* Effect.gen(function* () {289 yield* fs.makeDirectory(`${home}/config`, {290 mode: HOME_MODE,291 recursive: true,292 });293 yield* fs.makeDirectory(bin, { recursive: true });294295 const helper = `${bin}/${Brand.gitCredentialHelper}`;296297 yield* fs.writeFileString(helper, helperShim, { mode: SHIM_MODE });298 yield* fs.chmod(helper, SHIM_MODE);299 }).pipe(300 Effect.mapError(({ message }) =>301 failed("people", `a person's folder: ${message}`)302 )303 );304305 const path = yield* Config.String("PATH").pipe(306 Config.withDefault(""),307 Effect.orElseSucceed(() => "")308 );309310 const env = {311 ...personEnv({312 configHome: `${home}/config`,313 platformUrl: origin,314 token,315 }),316 [`${Brand.slug.toUpperCase()}_PROFILE`]: undefined,317 GIT_CONFIG_GLOBAL: gitconfig,318 GIT_CONFIG_NOSYSTEM: "1",319 GIT_EDITOR: ":",320 GIT_TERMINAL_PROMPT: "0",321 PATH: path === "" ? bin : `${bin}:${path}`,322 };323324 const { handle } = yield* cli(325 "people",326 { env, token },327 ["status"],328 Schema.Struct({ handle: Handle })329 );330331 yield* fs332 .writeFileString(333 gitconfig,334 [335 "[user]",336 `\tname = ${handle}`,337 `\temail = ${handle}@example.com`,338 "[commit]",339 "\tgpgsign = false",340 `[credential "${origin}"]`,341 "\thelper =",342 `\thelper = ${Brand.slug}`,343 "\tuseHttpPath = true",344 "",345 ].join("\n")346 )347 .pipe(348 Effect.mapError(({ message }) =>349 failed("people", `${handle}'s gitconfig: ${message}`)350 )351 );352353 return { env, handle, home, token };354 });355356const writeFiles = (357 step: LoopStep,358 dir: string,359 files: Readonly<Record<string, string>>360) =>361 Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>362 Effect.forEach(363 Object.entries(files),364 ([path, content]) =>365 Effect.gen(function* () {366 const at = `${dir}/${path}`;367368 yield* fs.makeDirectory(at.slice(0, at.lastIndexOf("/")), {369 recursive: true,370 });371 yield* fs.writeFileString(at, content);372 }).pipe(373 Effect.mapError(({ message }) =>374 failed(step, `writing ${path}: ${message}`)375 )376 ),377 { discard: true }378 )379 );380381const commit = (382 step: LoopStep,383 person: LoopPerson,384 cwd: string,385 message: string,386 files: Readonly<Record<string, string>>387) =>388 Effect.gen(function* () {389 yield* writeFiles(step, cwd, files);390 yield* gitOk(step, person, cwd, ["add", "--all"]);391 yield* gitOk(step, person, cwd, [392 "commit",393 "--quiet",394 "--message",395 message,396 ]);397398 return CommitSha.make(399 yield* gitOk(step, person, cwd, ["rev-parse", "HEAD"])400 );401 });

Merge build/1007oscabrielbefore adoption77fa97a

lines 402–417why, one step back
402
403const Listed = Schema.Struct({404 projects: Schema.Array(Schema.Struct({ project: ProjectName })),405});406407export const projectIsFree = (person: LoopPerson, project: ProjectName) =>408 Effect.flatMap(cli("init", person, ["projects"], Listed), ({ projects }) =>409 projects.some((listed) => listed.project === project)410 ? Effect.fail(411 failed(412 "init",413 `${project} is on the platform already, so nothing was made or recorded: a run a second later takes another name`414 )415 )416 : Effect.void417 );

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 418–585why, one step back
418
419const Inited = Schema.Struct({420 pushed: Schema.Boolean,421 remote: Schema.NonEmptyString,422});423424export const initProject = (input: {425 readonly decider: LoopPerson;426 readonly answerer: Handle;427 readonly project: ProjectName;428 readonly dir: string;429}) =>430 Effect.gen(function* () {431 const { decider, dir, project } = input;432433 yield* writeFiles("init", dir, startFiles(input.answerer));434 yield* gitOk("init", decider, dir, [435 "init",436 "--quiet",437 "--initial-branch=main",438 ]);439 yield* gitOk("init", decider, dir, ["add", "--all"]);440 yield* gitOk("init", decider, dir, [441 "commit",442 "--quiet",443 "--message",444 `Start ${project}`,445 ]);446447 const made = yield* cli(448 "init",449 decider,450 ["init", "--project", project, "--yes"],451 Inited,452 dir453 );454455 return made.pushed456 ? made457 : yield* failed(458 "init",459 `${Brand.cli} init made ${project} but pushed nothing`460 );461 });462463const Opened = Schema.Struct({ ask: Ask, landed: LandedSha });464465export const openAsk = (decider: LoopPerson, project: ProjectName) =>466 cli(467 "open-ask",468 decider,469 [470 "ask",471 "open",472 ASK,473 "--project",474 project,475 "--files",476 JSON.stringify(askFiles),477 "--yes",478 ],479 Opened480 );481482const Claimed = Schema.Struct({ claim: ClaimView });483484export const claimAsk = (answerer: LoopPerson, project: ProjectName) =>485 Effect.map(486 cli("claim", answerer, ["claim", ASK, "--project", project], Claimed),487 ({ claim }) => claim488 );489490// Each refusal's first line among git's `remote:` lines, as `render` writes491// it: `remote: OutOfScope: …`.492const REFUSAL_LINE = /^remote: (?<tag>[A-Z][A-Za-z]+): /gmu;493494export const refusalTags = (stderr: string): readonly string[] =>495 [...stderr.matchAll(REFUSAL_LINE)].flatMap(({ groups }) =>496 groups?.tag === undefined ? [] : [groups.tag]497 );498499export const pushOutOfScope = (input: {500 readonly answerer: LoopPerson;501 readonly claim: ClaimView;502 readonly dir: string;503}) =>504 Effect.gen(function* () {505 const { answerer, claim, dir } = input;506507 yield* gitOk("out-of-scope", answerer, answerer.home, [508 "clone",509 "--quiet",510 claim.remote,511 dir,512 ]);513514 yield* commit("out-of-scope", answerer, dir, "Read the year, and say so", {515 "README.md": `${README}It reads years now.\n`,516 [SOURCE]: yearRead,517 });518519 const pushed = yield* run(520 "out-of-scope",521 answerer,522 "git",523 ["push", "origin", "HEAD:main"],524 dir525 );526527 const tags = refusalTags(pushed.stderr);528529 return pushed.code !== 0 && tags.includes("OutOfScope")530 ? tags531 : yield* failed(532 "out-of-scope",533 scrubbed(534 `a push outside ${ASK}'s territory exited ${pushed.code}${tags.length === 0 ? " with no refusal" : `, refused ${tags.join(", ")}`}, not OutOfScope: ${pushed.stderr.trim()}`,535 [answerer.token]536 )537 );538 });539540export const pushAnswer = (answerer: LoopPerson, dir: string) =>541 Effect.gen(function* () {542 const head = yield* commit(543 "answer",544 answerer,545 dir,546 "Leave the readme alone",547 {548 "README.md": README,549 }550 );551552 const pushed = yield* run(553 "answer",554 answerer,555 "git",556 ["push", "origin", "HEAD:main"],557 dir558 );559560 return pushed.code === 0561 ? head562 : yield* failed(563 "answer",564 scrubbed(565 `the fixed answer's push exited ${pushed.code}: ${pushed.stderr.trim()}`,566 [answerer.token]567 )568 );569 });570571const Status = Schema.Struct({ answers: Schema.Array(AnswerView) });572573class StillChecking extends Schema.TaggedError<StillChecking>()(574 "StillChecking",575 {}576) {}577578export interface Patience {579 readonly every: Duration.Duration;580 readonly within: Duration.Duration;581}582583const outcomeLine = (outcome: Outcome) =>584 Outcome.match(outcome, {585 AwaitingDecision: ({ decision }) => `waits on the decision ${decision}`,

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

line 586why, one step back
586 AwaitingFinish: () => "waits for a maintainer's finish",

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 587–693why, one step back
587 Checking: ({ stage }) => `is still being checked at ${stage}`,
588 Landed: ({ sha }) => `landed as ${sha}`,589 Refused: ({ refusals }) =>590 `was refused: ${explain(refusals)591 .map((line) => line.trim())592 .join("; ")}`,593 WaitingOnParent: ({ ask }) => `waits for its parent ask ${ask} to land`,594 });595596export const awaitLanding = (input: {597 readonly answerer: LoopPerson;598 readonly project: ProjectName;599 readonly head: CommitSha;600 readonly patience: Patience;601}) =>602 Effect.gen(function* () {603 const { answerer, head, project } = input;604605 const outcome = yield* cli(606 "landing",607 answerer,608 ["status", "--project", project],609 Status610 ).pipe(611 Effect.flatMap(({ answers }) =>612 Option.match(613 Array.findLast(answers, (answer) => answer.head === head),614 {615 onNone: () => Effect.fail(new StillChecking()),616 onSome: ({ outcome: now }) =>617 Outcome.guards.Checking(now)618 ? Effect.fail(new StillChecking())619 : Effect.succeed(now),620 }621 )622 ),623 Effect.retry({624 schedule: Schedule.spaced(input.patience.every).pipe(625 Schedule.upTo({ duration: input.patience.within })626 ),627 while: Schema.is(StillChecking),628 }),629 Effect.catchTag("StillChecking", () =>630 Effect.fail(631 failed(632 "landing",633 `the answer at ${head} was still being checked after ${Duration.format(input.patience.within)}`634 )635 )636 )637 );638639 return Outcome.guards.Landed(outcome)640 ? outcome.sha641 : yield* failed(642 "landing",643 `the answer at ${head} ${outcomeLine(outcome)}`644 );645 });646647export interface LandingRead {648 readonly author: string;649 readonly committer: string;650 readonly trailers: readonly string[];651}652653export const readLanding = (input: {654 readonly answerer: LoopPerson;655 readonly dir: string;656 readonly origin: string;657 readonly project: ProjectName;658 readonly landed: LandedSha;659}) =>660 Effect.gen(function* () {661 const { answerer, dir, landed } = input;662663 yield* gitOk("landing", answerer, dir, [664 "fetch",665 "--quiet",666 `${input.origin}/${input.project}.git`,667 "refs/heads/main",668 ]);669670 const main = yield* gitOk("landing", answerer, dir, [671 "rev-parse",672 "FETCH_HEAD",673 ]);674675 if (main !== landed) {676 return yield* failed(677 "landing",678 `${input.project}'s main is at ${main}, not the landing ${landed}`679 );680 }681682 const [author = "", committer = "", ...trailers] = (yield* gitOk(683 "landing",684 answerer,685 dir,686 ["log", "-1", "--format=%an%n%cn%n%(trailers:only,unfold)", landed]687 ))688 .split("\n")689 .filter((line) => line.length > 0);690691 return { author, committer, trailers } satisfies LandingRead;692 });693

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 694why, one step back
694// `@repo/git/notes`' `notesRef`.

Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed weboscabrielbefore adoption030c4d6

lines 695–742why, one step back
695const NOTES = `refs/notes/${Brand.slug}`;
696697const NOTE_WAIT = { every: Duration.seconds(1), times: 30 } as const;698699class NoNoteYet extends Schema.TaggedError<NoNoteYet>()("NoNoteYet", {}) {}700701export const readVerdictNote = (input: {702 readonly answerer: LoopPerson;703 readonly dir: string;704 readonly head: CommitSha;705}) =>706 Effect.gen(function* () {707 const { answerer, dir, head } = input;708709 const fetched = yield* run(710 "verdict-note",711 answerer,712 "git",713 ["fetch", "--quiet", "origin", `+${NOTES}:${NOTES}`],714 dir715 );716717 const shown = yield* run(718 "verdict-note",719 answerer,720 "git",721 ["notes", `--ref=${NOTES}`, "show", head],722 dir723 );724725 return fetched.code === 0 && shown.code === 0 && shown.stdout.trim() !== ""726 ? shown.stdout.trim()727 : yield* new NoNoteYet();728 }).pipe(729 Effect.retry({730 schedule: Schedule.spaced(NOTE_WAIT.every),731 times: NOTE_WAIT.times,732 while: Schema.is(NoNoteYet),733 }),734 Effect.catchTag("NoNoteYet", () =>735 Effect.fail(736 failed(737 "verdict-note",738 `no verdict note on ${input.head} in the fork after ${NOTE_WAIT.times} s`739 )740 )741 )742 );

Merge branch 'build/910-draft-workflow'oscabrielbefore adoptiona0c8f4f

lines 743–915why, one step back
743
744const DRAFT_WANT =745 "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.";746747const Proposed = Schema.Struct({ proposal: Proposal });748749const Shown = Schema.Struct({ proposal: Proposal });750751export const proposeDraft = (proposer: LoopPerson, project: ProjectName) =>752 Effect.map(753 cli(754 "draft-propose",755 proposer,756 ["propose", "--project", project, "--want", DRAFT_WANT, "--draft"],757 Proposed758 ),759 ({ proposal }) => proposal.id760 );761762class StillDrafting extends Schema.TaggedError<StillDrafting>()(763 "StillDrafting",764 {}765) {}766767export interface DraftReady {768 readonly model: string;769 readonly attempts: number;770}771772export const awaitDraft = (input: {773 readonly reader: LoopPerson;774 readonly project: ProjectName;775 readonly proposal: ProposalId;776 readonly patience: Patience;777}) =>778 Effect.gen(function* () {779 const { project, proposal, reader } = input;780781 const settled = (782 shown: Proposal783 ): Effect.Effect<DraftState, LoopFailed | StillDrafting> =>784 Option.match(Option.fromUndefinedOr(shown.draft), {785 onNone: () =>786 Effect.fail(787 failed("draft-ready", `the proposal ${proposal} has no draft`)788 ),789 onSome: (state) =>790 DraftState.guards.Drafting(state)791 ? Effect.fail(new StillDrafting())792 : Effect.succeed(state),793 });794795 const draft = yield* cli(796 "draft-ready",797 reader,798 ["proposal", proposal, "--project", project],799 Shown800 ).pipe(801 Effect.flatMap(({ proposal: shown }) => settled(shown)),802 Effect.retry({803 schedule: Schedule.spaced(input.patience.every).pipe(804 Schedule.upTo({ duration: input.patience.within })805 ),806 while: Schema.is(StillDrafting),807 }),808 Effect.catchTag("StillDrafting", () =>809 Effect.fail(810 failed(811 "draft-ready",812 `the proposal ${proposal} was still drafting after ${Duration.format(input.patience.within)}`813 )814 )815 )816 );817818 if (DraftState.guards.Ready(draft)) {819 return {820 attempts: draft.attempts,821 model: draft.model,822 } satisfies DraftReady;823 }824825 return yield* failed(826 "draft-ready",827 DraftState.guards.Failed(draft)828 ? `the draft of ${proposal} failed after ${draft.attempts} attempts, last refused ${draft.refusal}`829 : `the proposal ${proposal} is still drafting`830 );831 });832833const TodayIs = Schema.Struct({ decisions: Schema.Array(Decision) });834835const Decided = Schema.Struct({ decision: Decision });836837export const acceptDraft = (input: {838 readonly decider: LoopPerson;839 readonly proposer: Handle;840 readonly project: ProjectName;841 readonly proposal: ProposalId;842 readonly dir: string;843 readonly origin: string;844}) =>845 Effect.gen(function* () {846 const { decider, dir, project, proposal } = input;847848 const { decisions } = yield* cli(849 "draft-accept",850 decider,851 ["today", "--project", project],852 TodayIs853 );854855 const decision = yield* Effect.fromOption(856 Array.findFirst(857 decisions,858 ({ subject }) =>859 DecisionSubject.guards.OpenProposal(subject) &&860 subject.proposal === proposal861 )862 ).pipe(863 Effect.mapError(() =>864 failed(865 "draft-accept",866 `${decider.handle}'s Today holds no decision on ${proposal}`867 )868 )869 );870871 yield* cli(872 "draft-accept",873 decider,874 [875 "decide",876 "--project",877 project,878 "--decision",879 decision.id,880 "--choice",881 "accept",882 "--yes",883 ],884 Decided885 );886887 yield* gitOk("draft-accept", decider, dir, [888 "fetch",889 "--quiet",890 `${input.origin}/${project}.git`,891 "refs/heads/main",892 ]);893894 const trailers = (yield* gitOk("draft-accept", decider, dir, [895 "log",896 "-1",897 "--format=%(trailers:only,unfold)",898 "FETCH_HEAD",899 ]))900 .split("\n")901 .filter((line) => line.length > 0);902903 const missing = [904 "Assisted-by: ",905 `Asked-by: ${input.proposer} `,906 "Ask: ",907 ].filter((prefix) => !trailers.some((line) => line.startsWith(prefix)));908909 return missing.length === 0910 ? trailers911 : yield* failed(912 "draft-accept",913 `the landing that opened ${proposal}'s ask lacks ${missing.map((prefix) => prefix.trim()).join(" and ")}: its trailers are ${trailers.join("; ") || "none"}`914 );915 });