Skip to content
Myr

Run a proposal's draft durably as a Draft round of the Answer Workflow

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- packages/drafting/src/run.ts: `runDraft(params, steps)`, the round as named steps shared by the Workflow and the inline run: `context` (the open proposal, files picked from the canonical repo at the landed SHA and recorded, so a replay reads nothing), up to three `draft-<n>` (the model's draft recorded as JSON, so a replay never calls the model) and `rehearse-<n>` (red first, no landing), then `settle`. A refusal feeds the next attempt as protocol/render says it, with diagnosis and output tail. A project without `fix` settles Failed{IncompleteBrief} with no model call. - Retries: `rate-limited` is a step retry ({4, 15 s, exponential}) and no spent attempt; VerifierBlocked/StaleBase {3, 60 s, exponential}. A spent step's outcome is recorded in `<step>:gave-up` (OnPush's `settle` pattern), so a replay that finds the engine's kept failure converges; a rehearsal still blocked ends the round Failed, since redrafting cannot help. - The model a round names comes from `DraftModel` (a Context.Reference, default `memory`): the Drafter port carries none; the platform gives `DRAFT_MODEL`. - apps/platform: `DraftParams` (tagged `Draft`, the note travelling with it) in `WorkflowParams`, `draftId` = draft-<project>-<proposal>-r<round>; `Answer.run` dispatches it to `workflows/draft-steps.ts`, with every draft step handed `timeout: "10 minutes"` (`timedSteps`, so step.ts stays as it is). No Workflow, binding, DO or class added or renamed. - `adapters/draft-runs-workflow.ts`: create-or-restart over ANSWER, but a `complete` instance is never restarted (that would ask the model again for a settled round); `ports.ts` provides it in every port set, and `draftPorts` (DrafterWorkersAi(AI, DRAFT_MODEL)) only to draft rounds, so WorkerPorts and the test world keep their shape. - handlers.ts: `proposeAsk` with `draft` spends the draft rate limit before the proposal limit (CapReached past it); `draftAsk` already did. - `draft-runs/inline.ts`: the same program in process; `withDraftRunsInline` ties a Projects layer to its own runs. `draft-runs/canned.ts`: the canned `parse-ordinal` draft, red on any src/parse.ts lacking parseOrdinal. The web's dev world and the Node world (serve-world.ts) draft with it offline; datekit's dev policy.json states that ask, unopened. - smoke: `--loop --draft` proposes with --draft on the throwaway project, polls `proposal <id>` until settled, accepts as the operator, and checks the opening landing has Assisted-by, Asked-by the proposer and Ask:; it prints model, attempts and time. `--draft` without `--loop` is refused (DraftNeedsLoop) before any request. - Tests: packages/drafting/test/run.test.ts (no fix kind: no model call); apps/platform/test/workflows/draft.test.ts (NotRedFirst fed to attempt 2, one decision, Ready{attempts: 2}, a replay asks 2 not 4; three refusals settle Failed with the last tag; rate-limited retried as a step; a gone proposal stops after context; one instance per round; errored restarts, complete never; the engine's timeouts and retries; the draft limit); core-loop.test.ts (propose with draft, the inline run, accept, Asked-by, Decided-by and Assisted-by verified); dev-backend.test.ts (a dev-world draft Ready, its decision joining Today); smoke-loop.test.ts (--draft against the Node world; --draft without --loop refused, no request). - Platform entry +13,505 bytes (1,645,355 to 1,658,860 of 1,900,000). - ASSUMPTION: in the seeded dev world the draft's decision waits on ines-v's Today as overflow (seeded decisions expire first), so the dev test asserts the overflow, not a shown card.

authored by oscabriel · committed by oscabriel · parent bbe1442 · Browse files · 20 files+2087 added−35 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

20 files+2087 added−35 removed

  • tests:+981 added−3 removed
  • other:+1106 added−32 removed

20 files+2087 added−35 removed

added:apps/platform/src/adapters/draft-runs-workflow.ts+75 added
modified:apps/platform/src/workflows/answer.ts+47 added-5 removed
added:apps/platform/src/workflows/draft-steps.ts+53 added
modified:apps/platform/src/answer-runs.ts+29 added-2 removed
7 unmodified lines
8 * For the admission of a layer push's sealed checks:9 * admission runs as steps of the same Workflow under its own tagged10 * params, so typed visibility adds no Workflow binding. Its instance id is11 * `admissionId`, so a push admitted twice runs once.12 *13 * For one round of a proposal's draft: the run (`@repo/drafting/run`) is14 * steps of the same Workflow under params tagged `Draft`, so drafting adds15 * no Workflow binding (W9-D14). Its instance id is `draftId`, one per16 * project, proposal and round, so a round started twice runs once.17 */18import { DraftParams as DraftRun } from "@repo/project/draft-runs";19import {20 CommitSha,21 LayerName,22 ProjectName,
16 unmodified lines
39});4041export type AdmissionParams = typeof AdmissionParams.Type;4237/** Every run the `Answer` Workflow takes: an admission's, or an answer's. */38export const WorkflowParams = Schema.Union([AdmissionParams, AnswerParams]);43/**44 * One round of a proposal's draft: its project, proposal and round, and the45 * note the round was asked with, which travels with the run.46 */47export const DraftParams = Schema.TaggedStruct("Draft", DraftRun.fields);4849export type DraftParams = typeof DraftParams.Type;5051/** Every run the `Answer` Workflow takes: an admission's, a draft's, or an answer's. */52export const WorkflowParams = Schema.Union([53 AdmissionParams,54 DraftParams,55 AnswerParams,56]);5758export type WorkflowParams = typeof WorkflowParams.Type;5960/** How long a Workflow instance id may be. */61const ID_LENGTH = 100;6263/** The instance an admission runs as: one per project, layer and pushed head. */64export const admissionId = (params: AdmissionParams) =>65 `admit-${params.project}-${params.layer}-${params.head}`.slice(0, ID_LENGTH);6667/** The instance a draft's round runs as: one per project, proposal and round. */68export const draftId = (69 params: Pick<DraftParams, "project" | "proposal" | "round">70) =>71 `draft-${params.project}-${params.proposal}-r${params.round}`.slice(72 0,73 ID_LENGTH74 );
modified:apps/platform/src/handlers.ts+8 added-1 removed
4 unmodified lines
5 * the caller `Authenticated` named; the cross-project reads (`listProjects`,6 * `frontPage`, `credits`) come from the front-page projection; `status` and7 * `today` without a project ask every project the projection lists and8 * merge what each says. `claim`, `proposeAsk` and `flagAsk` spend the9 * caller's rate limit first, so a call past it reaches no project.9 * caller's rate limit first, so a call past it reaches no project; a10 * proposal with a draft, and `draftAsk`, spend the draft limit too.11 * `evidence` asks the project who may read a lane's log, which it reads12 * from the stage's `EvidenceStore`. The code reads (`listRefs`, `readTree`,13 * `listPaths`, `readFile`, `log`, `showCommit`, `why`) run here, over the14 * Worker's `RepoHost` and the project's canonical repo (`@repo/project/code`),
335 unmodified lines
350 proposeAsk: ({ project, ...input }) =>351 Effect.gen(function* () {352 const who = yield* person;353354 // A draft spends the draft limit (model calls and Checker runs)355 // first, then the proposal limit, as any proposal does.356 if (input.draft === true) {357 yield* rateLimits.check("draft", who.handle);358 }359360 yield* rateLimits.check("proposal", who.handle);361362 return yield* on(project, (api) => api.proposeAsk(who, input));363 }),
84 unmodified lines
modified:apps/platform/src/ports.ts+22 added-3 removed
24 unmodified lines
25import { RepoHostBinding } from "@repo/artifacts/repo-host/binding";26import type { CheckRunner } from "@repo/checks/check-runner";27import type { EvidenceStore } from "@repo/checks/evidence-store";28import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";29import type { Drafter } from "@repo/drafting/drafter";30import { DrafterWorkersAi } from "@repo/drafting/drafter/binding";31import { DraftModel } from "@repo/drafting/run";32import type { Upstream } from "@repo/git/upstream";33import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";34import { CodeCacheLive } from "@repo/project/code/cache";35import type { FrontPage } from "@repo/project/front-page";
11 unmodified lines
47import { Layer, Option } from "effect";4849import { CheckRunnerSandbox } from "./adapters/check-runner-sandbox.ts";50import { DoProjects } from "./adapters/do-projects.ts";51import { DraftRunsWorkflow } from "./adapters/draft-runs-workflow.ts";52import { WorkerFetch } from "./adapters/fetch.ts";53import { LanderSandbox } from "./adapters/lander-sandbox.ts";54import { WorkerRateLimits } from "./adapters/rate-limits.ts";55import * as cartridges from "./cartridges.ts";
55 unmodified lines
111 * its binding, git's upstream and every repo read over it, each project's112 * Durable Object, the sandbox's Checker, the Lander `LANDER_ADAPTER` names,113 * config folders evaluated in the Worker Loader, the front114 * page in D1, the rate limits, lane logs in the `EVIDENCE` bucket,111 * and the `PROJECT` namespace again for `watch`'s relay of each project's112 * socket.115 * the `PROJECT` namespace again for `watch`'s relay of each project's116 * socket, and each proposal's draft rounds as runs of the `Answer`117 * Workflow.118 */119const corePorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>120 Layer.mergeAll(121 memoryFrontPage,
23 unmodified lines
145 }),146 EvidenceStoreR2(config.EVIDENCE),147 // The code reads' cache, one per isolate: a `Context.Reference`, so148 // without this entry every read goes to Artifacts.144 CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy)149 CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy),150 // A `Context.Reference`: without this entry a draft proposal starts no151 // run, and stays drafting.152 DraftRunsWorkflow(config.ANSWER)153 ).pipe(154 Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)),155 Layer.provideMerge(WorkerFetch)156 );157158/** The ports for one stage's env, with every cartridge the platform plugs in. */159export const workerPorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>160 plugIn(config, corePorts(config), Object.values(cartridges));161162/**163 * What a draft's run needs beside the Worker's ports: the drafter over164 * Workers AI, asking `DRAFT_MODEL`, which a settled round names. Only the165 * `Answer` Workflow's draft rounds take it.166 */167export const draftPorts = (config: PlatformConfig): Layer.Layer<Drafter> =>168 Layer.merge(169 DrafterWorkersAi(config.AI, config.DRAFT_MODEL),170 Layer.succeed(DraftModel, config.DRAFT_MODEL)171 );
added:apps/platform/test/workflows/draft.test.ts+535 added
1/**2 * A draft's run as the `Answer` Workflow takes it (W9-D14): the program's3 * steps over memory steps that record and replay as the engine does4 * (`memoSteps`), the memory drafter scripted per attempt, and a project in5 * memory whose rehearsals run on the scripted Checker. The Workflow's own6 * start (`DraftRunsWorkflow`) is held to create-or-restart over a fake7 * binding, and the engine is handed each draft step's timeout.8 */9import { describe, expect, expectTypeOf, it } from "@effect/vitest";10import type { RepoHost } from "@repo/artifacts/repo-host";11import { CheckAt } from "@repo/checks/check-runner";12import { DraftFailed } from "@repo/drafting/drafted";13import type { DraftedAsk } from "@repo/drafting/drafted";14import type { Drafter } from "@repo/drafting/drafter";15import type { AiLike } from "@repo/drafting/drafter/binding";16import { DrafterMemory, DraftsAsked } from "@repo/drafting/drafter/memory";17import { draftedFiles } from "@repo/drafting/render";18import { DraftModel } from "@repo/drafting/run";19import { DraftRuns } from "@repo/project/draft-runs";20import { Lander } from "@repo/project/lander";21import type { ProjectApi } from "@repo/project/project";22import { Projects } from "@repo/project/projects";23import { DecisionSubject } from "@repo/protocol/domain/decision";24import { DraftState } from "@repo/protocol/domain/proposal";25import {26 AskId,27 LandedSha,28 LaneName,29 ProposalId,30 RepoName,31 RepoPath,32} from "@repo/protocol/ids";33import { Anonymous, Person } from "@repo/protocol/principal";34import { CapReached } from "@repo/protocol/refusal";35import { advanceTo } from "@repo/testkit/clock";36import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";37import { Context, Effect, Layer, Option, Ref, Schema } from "effect";3839import { DraftRunsWorkflow } from "../../src/adapters/draft-runs-workflow.ts";40import type { DraftWorkflow } from "../../src/adapters/draft-runs-workflow.ts";41import { DraftParams, draftId } from "../../src/answer-runs.ts";42import { Handlers } from "../../src/handlers.ts";43import type { PlatformConfig } from "../../src/platform.ts";44import { runDraftWorkflow } from "../../src/workflows/answer.ts";45import type { EngineSteps } from "../../src/workflows/draft-steps.ts";46import { draftSteps } from "../../src/workflows/draft-steps.ts";47import { memoSteps, StepRunner } from "../../src/workflows/step.ts";48import type { StepRetry } from "../../src/workflows/step.ts";49import { as, seeded, worldOf } from "../handlers.fixtures.ts";50import { Checker, Pusher, worldWith } from "./answer.fixtures.ts";5152/** What the engine is handed with each step. */53type EngineConfig = Parameters<EngineSteps["do"]>[1];5455/** datekit, decided by alice, with carol vouched and one `fix` ask she may want drafted. */56const scenario = aProject({ people: ["carol"] }).pipe(57 withVouches(["carol"]),58 withAsk({ id: "parse-week", territory: "." })59);6061const { policy, project } = scenario;6263const repo = RepoName.make(project);6465const alice = Person.make({ handle: scenario.initializer });6667const carol = Person.make({68 handle: scenario.people.get("carol") ?? scenario.initializer,69});7071const redThenGreen = LaneName.make("redThenGreen");7273const model = "@cf/moonshotai/kimi-k2.7-code";7475const want = "Parse an ISO week date such as 2026-W41";7677const proposal = ProposalId.make("prop-000001");7879const params = DraftParams.make({ project, proposal, round: 1 });8081const start = [82 ["package.json", '{ "name": "datekit", "type": "module" }\n'],83 ["src/parse.ts", "export const parse = (s) => ({});\n"],84] as const;8586/** A draft of the scenario's ask whose test says `assertion`. */87const draftOf = (assertion: string, id = "parse-week"): DraftedAsk => ({88 id: AskId.make(id),89 kind: "fix",90 rationale: `${id}: parseWeek is missing, so its test fails by an assertion`,91 territory: [RepoPath.make("src/parse.ts")],92 test: {93 path: RepoPath.make(`test/${id}.test.ts`),94 source: [95 'import { expect, it } from "bun:test";',96 'import { parse } from "../src/parse.ts";',97 "",98 `it("${id}", () => {`,99 ` ${assertion}`,100 "});",101 "",102 ].join("\n"),103 },104 want,105});106107/** A test that passes on main, so its draft is not red first. */108const passing = draftOf("expect(parse('2026-W41')).toStrictEqual({});");109110/** A second test that passes on main. */111const passingToo = draftOf("expect(parse('2026-W42')).toStrictEqual({});");112113/** A test that fails on main by its assertion. */114const red = draftOf("expect(parse('2026-W41').week).toBe(41);");115116/** A draft of an ask the project's rules do not state. */117const unstated = draftOf(118 "expect(parse('2026-W41').week).toBe(41);",119 "parse-month"120);121122/** carol proposes the want with a draft, on datekit's first push. */123const proposed = Effect.gen(function* () {124 yield* advanceTo("2026-10-08T12:00:00Z");125126 const api = yield* Projects.use((each) => each.create(project)).pipe(127 Effect.orDie128 );129130 yield* api.initProject(alice, {}).pipe(Effect.orDie);131132 const first = yield* Pusher.use((each) =>133 each.push(repo, Option.none(), start)134 );135136 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);137138 // The project's first proposal: `proposal`.139 yield* api140 .proposeAsk(carol, { draft: true, territory: "src/parse.ts", want })141 .pipe(Effect.orDie);142143 return { api, main: LandedSha.make(first) };144});145146/** `drafted`'s files composed onto `main`, its check scripted to end `runs` there. */147const scripted = (148 main: LandedSha,149 drafted: DraftedAsk,150 result: "passed" | "failed"151) =>152 Effect.gen(function* () {153 const { commit } = yield* Lander.use((lander) =>154 lander.compose({ files: draftedFiles(drafted), main, repo })155 ).pipe(Effect.orDie);156157 yield* Checker.use((script) =>158 script.script(CheckAt.cases.Commit.make({ commit }), redThenGreen, [159 result === "passed"160 ? { result }161 : { result, signature: "redThenGreen: expected 41, got undefined" },162 ])163 );164 });165166/** The proposal's draft state, as anyone reads it. */167const draftOfProposal = (api: ProjectApi) =>168 Effect.map(169 Effect.orDie(api.showProposal(Anonymous.make({}), proposal)),170 ({ proposal: shown }) => shown.draft171 );172173/** alice's open-proposal decisions on Today. */174const proposalDecisions = (api: ProjectApi) =>175 Effect.map(Effect.orDie(api.today(alice)), ({ decisions }) =>176 decisions.filter(({ subject }) =>177 DecisionSubject.guards.OpenProposal(subject)178 )179 );180181const asked = DraftsAsked.use(({ inputs }) => inputs);182183/** The world, the memory drafter scripted with `script`, and the platform's model. */184const worldDrafting = (script: Parameters<typeof DrafterMemory>[0]) =>185 Layer.mergeAll(186 worldWith(policy),187 DrafterMemory(script),188 Layer.succeed(DraftModel, model)189 );190191describe("a draft's run, over steps that replay", () => {192 it.effect(193 "feeds attempt 1's NotRedFirst into attempt 2, puts up one decision with the red-first evidence, and a replay asks the model nothing more",194 () =>195 Effect.gen(function* () {196 const { api, main } = yield* proposed;197198 yield* scripted(main, passing, "passed");199 yield* scripted(main, red, "failed");200201 const steps = yield* memoSteps();202203 yield* draftSteps(params).pipe(Effect.provide(steps));204205 const inputs = yield* asked;206 const decisions = yield* proposalDecisions(api);207208 expect({209 attempts: inputs.map(({ attempt }) => attempt),210 decisions: decisions.length,211 draft: yield* draftOfProposal(api),212 firstFeedback: inputs[0]?.feedback,213 redFirst: decisions[0]?.evidence.find(214 ({ label }) => label === "red first"215 )?.value,216 refusedWith: inputs[1]?.feedback?.split("\n")[0]?.split(":")[0],217 }).toStrictEqual({218 attempts: [1, 2],219 decisions: 1,220 draft: DraftState.cases.Ready.make({221 attempts: 2,222 model,223 red: {224 lane: redThenGreen,225 signature: "redThenGreen: expected 41, got undefined",226 },227 round: 1,228 }),229 firstFeedback: undefined,230 redFirst: `${redThenGreen}: redThenGreen: expected 41, got undefined`,231 refusedWith: "NotRedFirst",232 });233234 // The finished instance, run again: every step reads its record.235 yield* draftSteps(params).pipe(Effect.provide(steps));236237 expect({238 asked: (yield* asked).length,239 decisions: (yield* proposalDecisions(api)).length,240 }).toStrictEqual({ asked: 2, decisions: 1 });241 }).pipe(Effect.provide(worldDrafting([passing, red])))242 );243244 it.effect(245 "settles Failed with the last refusal's tag once three attempts are refused",246 () =>247 Effect.gen(function* () {248 const { api, main } = yield* proposed;249250 yield* scripted(main, passing, "passed");251 yield* scripted(main, passingToo, "passed");252253 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));254255 expect({256 asked: (yield* asked).length,257 decisions: (yield* proposalDecisions(api)).length,258 draft: yield* draftOfProposal(api),259 }).toStrictEqual({260 asked: 3,261 decisions: 1,262 draft: DraftState.cases.Failed.make({263 attempts: 3,264 model,265 refusal: "IncompleteBrief",266 round: 1,267 }),268 });269 }).pipe(Effect.provide(worldDrafting([passing, passingToo, unstated])))270 );271272 it.effect(273 "retries a rate-limited model as a step, without spending an attempt",274 () =>275 Effect.gen(function* () {276 const { api, main } = yield* proposed;277278 yield* scripted(main, red, "failed");279280 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));281282 expect({283 asked: (yield* asked).map(({ attempt }) => attempt),284 draft: yield* draftOfProposal(api),285 }).toStrictEqual({286 asked: [1, 1],287 draft: DraftState.cases.Ready.make({288 attempts: 1,289 model,290 red: {291 lane: redThenGreen,292 signature: "redThenGreen: expected 41, got undefined",293 },294 round: 1,295 }),296 });297 }).pipe(298 Effect.provide(299 worldDrafting([new DraftFailed({ reason: "rate-limited" }), red])300 )301 )302 );303304 it.effect(305 "stops after its context when the proposal is gone: no attempt, no settling",306 () =>307 Effect.gen(function* () {308 yield* proposed;309310 const names = yield* Ref.make<readonly string[]>([]);311312 const memo = Context.get(313 yield* Layer.build(yield* memoSteps()),314 StepRunner315 );316317 const logged = StepRunner.of({318 step: (name, schema, effect, retry?: StepRetry) =>319 Effect.andThen(320 Ref.update(names, (all) => [...all, name]),321 memo.step(name, schema, effect, retry)322 ),323 });324325 yield* draftSteps(326 DraftParams.make({327 project,328 proposal: ProposalId.make("prop-000009"),329 round: 1,330 })331 ).pipe(Effect.provideService(StepRunner, logged));332333 expect({334 asked: (yield* asked).length,335 names: yield* Ref.get(names),336 }).toStrictEqual({ asked: 0, names: ["context"] });337 }).pipe(Effect.provide(worldDrafting([])))338 );339});340341/** A fake `ANSWER` binding: each instance made and restarted, every instance in `status`. */342const fakeWorkflow = (status: InstanceStatus["status"]) => {343 const made: string[] = [];344 const restarted: string[] = [];345346 const workflow: DraftWorkflow = {347 create: ({ id }) => {348 if (made.includes(id)) {349 return Promise.reject(new Error(`instance ${id} already exists`));350 }351352 made.push(id);353354 return Promise.resolve({ id });355 },356 get: (id) =>357 Promise.resolve({358 id,359 restart: () => {360 restarted.push(id);361362 return Promise.resolve();363 },364 status: () => Promise.resolve({ status }),365 }),366 };367368 return { made, restarted, workflow };369};370371describe("the Workflow's draft runs", () => {372 it.effect(373 "starts one instance per round: a second start finds it, and a run still going is left alone",374 () =>375 Effect.gen(function* () {376 const fake = fakeWorkflow("running");377378 const starting = DraftRuns.pipe(379 Effect.flatMap((runs) =>380 runs.start({ note: "keep it small", project, proposal, round: 1 })381 ),382 Effect.provide(DraftRunsWorkflow(fake.workflow))383 );384385 yield* starting;386 yield* starting;387388 expect({389 made: fake.made,390 restarted: fake.restarted,391 }).toStrictEqual({392 made: [`draft-${project}-${proposal}-r1`],393 restarted: [],394 });395396 expect(draftId(params)).toBe(`draft-${project}-${proposal}-r1`);397 })398 );399400 it.effect(401 "starts an errored round's instance again, and never a complete one, which would ask the model again",402 () =>403 Effect.gen(function* () {404 const errored = fakeWorkflow("errored");405 const complete = fakeWorkflow("complete");406407 const twice = (workflow: DraftWorkflow) =>408 DraftRuns.pipe(409 Effect.flatMap((runs) =>410 Effect.andThen(411 runs.start({ project, proposal, round: 1 }),412 runs.start({ project, proposal, round: 1 })413 )414 ),415 Effect.provide(DraftRunsWorkflow(workflow))416 );417418 yield* twice(errored.workflow);419 yield* twice(complete.workflow);420421 expect({422 complete: complete.restarted,423 errored: errored.restarted,424 }).toStrictEqual({425 complete: [],426 errored: [`draft-${project}-${proposal}-r1`],427 });428 })429 );430431 it.effect(432 "gives the engine a 10-minute timeout on each step, and the rate-limit retries on the model's",433 () =>434 Effect.gen(function* () {435 const { main } = yield* proposed;436437 yield* scripted(main, red, "failed");438439 const configs: (readonly [string, EngineConfig])[] = [];440 const kept = new Map<string, Schema.Json>();441442 const engine: EngineSteps = {443 do: (name, config, body) => {444 configs.push([name, config]);445446 const found = kept.get(name);447448 return found === undefined449 ? body().then((value) => {450 kept.set(name, value);451452 return value;453 })454 : Promise.resolve(found);455 },456 };457458 const ports = yield* Effect.context<Projects | Drafter | RepoHost>();459460 const payload = yield* Schema.encodeEffect(DraftParams)(params);461462 yield* Effect.promise(() =>463 runDraftWorkflow(Layer.succeedContext(ports), payload, engine)464 );465466 expect(configs.map(([name]) => name)).toStrictEqual([467 "context",468 "draft-1",469 "rehearse-1",470 "settle",471 ]);472473 expect(new Map(configs).get("draft-1")).toStrictEqual({474 retries: { backoff: "exponential", delay: 15_000, limit: 4 },475 timeout: "10 minutes",476 });477478 expect(479 configs.filter(([, config]) => config.timeout !== "10 minutes")480 ).toStrictEqual([]);481 }).pipe(Effect.provide(worldDrafting([red])))482 );483484 it("takes the Worker's bindings as the generated Env types them", () => {485 expectTypeOf<Env["ANSWER"]>().toExtend<486 Parameters<typeof DraftRunsWorkflow>[0]487 >();488 expectTypeOf<PlatformConfig["AI"]>().toExtend<AiLike>();489 });490});491492describe("proposing with a draft", () => {493 it.effect(494 "spends the person's draft limit first: past it, CapReached, while a proposal without a draft still goes through",495 () =>496 Effect.gen(function* () {497 yield* advanceTo("2026-10-08T12:00:00Z");498 yield* seeded(scenario);499500 const asCarol = yield* as("carol");501502 const drafted = yield* asCarol.proposeAsk({503 draft: true,504 project,505 want,506 });507508 const past = yield* Effect.flip(509 asCarol.proposeAsk({ draft: true, project, want })510 );511512 const plain = yield* asCarol.proposeAsk({ project, want });513514 expect({515 drafted: drafted.proposal.draft?._tag,516 past,517 plain: plain.proposal.draft,518 }).toStrictEqual({519 drafted: "Drafting",520 past: new CapReached({ cap: 1 }),521 plain: undefined,522 });523 }).pipe(524 Effect.provide(525 Handlers.pipe(526 Layer.provideMerge(527 worldOf([scenario], {528 limits: { claim: 5, draft: 1, proposal: 5 },529 })530 )531 )532 )533 )534 );535});
modified:apps/platform/test/core-loop.test.ts+145 added-1 removed
6 unmodified lines
7 * that lands nothing new. Every step goes through a surface: git's output,8 * or a contract over `/rpc`.9 */10import { describe, expect, it } from "@effect/vitest";11import type { RepoHost } from "@repo/artifacts/repo-host";12import { Brand } from "@repo/brand";13import { CheckAt } from "@repo/checks/check-runner";14import { draftRunsInline } from "@repo/drafting/draft-runs/inline";15import type { InlinePorts } from "@repo/drafting/draft-runs/inline";16import type { DraftedAsk } from "@repo/drafting/drafted";17import { DrafterMemory } from "@repo/drafting/drafter/memory";18import { draftedFiles } from "@repo/drafting/render";19import type { Projects } from "@repo/project/projects";20import { DecisionSubject } from "@repo/protocol/domain/decision";21import { Outcome } from "@repo/protocol/domain/outcome";22import {23 AskId,24 LandedSha,
9 unmodified lines
34 OutOfScope,35 StaleBase,36} from "@repo/protocol/refusal";37import { explain } from "@repo/protocol/render";30import { Array, Effect } from "effect";38import { Array, Context, Deferred, Effect, Layer } from "effect";3940import { pushRequestId } from "../src/adapters/custody.ts";41import { coreLoopWorld } from "./world.ts";42
453 unmodified lines
496 });497 }),498 60_000499 );500501 it.live(502 "a want proposed with a draft runs in process, goes to the decider with its red-first evidence, and opens on accept with Assisted-by beside the people's credits",503 () =>504 Effect.gen(function* () {505 const drafted: DraftedAsk = {506 id: AskId.make("parse-day"),507 kind: "fix",508 rationale: "parse reads no day, so the test fails by its assertion",509 territory: [RepoPath.make("src/parse.ts")],510 test: {511 path: RepoPath.make("test/parse-day.test.ts"),512 source: [513 'import { expect, it } from "bun:test";',514 'import { parse } from "../src/parse.ts";',515 "",516 'it("parse reads the day of an ISO date", () => {',517 ' expect(Reflect.get(parse("2026-10-07"), "day")).toBe(7);',518 "});",519 "",520 ].join("\n"),521 },522 want: "parse reads the day of an ISO date",523 };524525 // The rounds the Project DOs start run in process, on the Worker's526 // ports and the memory drafter, once the world hands them over.527 const ready = yield* Deferred.make<Context.Context<InlinePorts>>();528 const drafter = yield* Layer.build(DrafterMemory([drafted]));529530 const world = yield* coreLoopWorld({531 plugIn: () => ({532 project: draftRunsInline(Deferred.await(ready)),533 worker: Layer.effectDiscard(534 Effect.gen(function* () {535 const ports = yield* Effect.context<Projects | RepoHost>();536537 yield* Deferred.succeed(ready, Context.merge(ports, drafter));538 })539 ),540 }),541 });542543 const dora = world.rpc("dora");544 const alice = world.rpc("alice");545 const doraGit = world.git("dora");546547 const made = yield* dora.initProject({ project });548 const home = yield* doraGit.clone(made.remote);549550 yield* doraGit.commit(home, "Start datekit", start);551 yield* doraGit.push(home);552553 // The drafted files fail on main twice the same way.554 yield* world.script(555 CheckAt.cases.Commit.make({556 commit: yield* world.composed(project, draftedFiles(drafted)),557 }),558 redThenGreen,559 ["failed", "failed"]560 );561562 const proposed = yield* alice.proposeAsk({563 draft: true,564 project,565 want: drafted.want,566 });567568 const { decisions } = yield* dora.today({ project });569570 const decision = yield* Effect.fromOption(571 Array.findFirst(572 decisions,573 ({ subject }) =>574 DecisionSubject.guards.OpenProposal(subject) &&575 subject.proposal === proposed.proposal.id576 )577 );578579 const shown = yield* alice.showProposal({580 project,581 proposal: proposed.proposal.id,582 });583584 yield* dora.decide({585 choice: "accept",586 decision: decision.id,587 project,588 });589590 const { asks } = yield* alice.listAsks({ project });591592 yield* doraGit.ok(home, "fetch", "--quiet", "origin");593594 expect({595 asks: asks.map(({ ask, claimed }) => ({ ask, claimed })),596 draft: shown.proposal.draft?._tag,597 files: yield* doraGit.ok(598 home,599 "show",600 "--format=",601 "--name-only",602 "origin/main"603 ),604 proposed: proposed.proposal.draft?._tag,605 redFirst: decision.evidence.some(606 ({ label, value }) =>607 label === "red first" && value.startsWith(`${redThenGreen}: `)608 ),609 trailers: (yield* doraGit.ok(610 home,611 "log",612 "-1",613 "--format=%(trailers:only)",614 "origin/main"615 ))616 .split("\n")617 // Who it credits and which agents it discloses: every `-by` trailer.618 .filter((line) => /^[A-Za-z-]+-by: /u.test(line)),619 }).toStrictEqual({620 asks: [{ ask: drafted.id, claimed: false }],621 draft: "Ready",622 files: draftedFiles(drafted)623 .map(({ path }) => path)624 .join("\n"),625 proposed: "Drafting",626 redFirst: true,627 trailers: [628 `Asked-by: ${credited("alice")}`,629 `Decided-by: ${credited("dora")}`,630 `Assisted-by: ${Brand.cli}-drafter:memory (verified)`,631 ],632 });633 }),634 60_000635 );636});
modified:apps/platform/test/serve-world.ts+40 added-1 removed
22 unmodified lines
23 * project that declares a layer gets its repo there, and its maintainers24 * clone and push it through the gateway. The `Answer` Workflow25 * the cartridge starts an admission on keeps the instance and runs26 * nothing: the world carries no Workflow.27 * - A proposal made with a draft is drafted in process as it is made28 * (`@repo/drafting`'s inline runs, over the Worker's ports), by the29 * memory drafter scripted with the canned draft, whose test fails on any30 * `src/parse.ts` without a `parseOrdinal`: so smoke's `--loop --draft`31 * sees a draft go red first and open on accept with no model.32 *33 * The seed's `--world node` runs it (`scripts/lib/seed.ts`) and34 * reaches it over HTTP and git, as it reaches a stage. A process, not an35 * import: apps never import apps, and no file outside the platform imports
4 unmodified lines
40import type { RepoHost } from "@repo/artifacts/repo-host";41import { CheckRunner, shaOf } from "@repo/checks/check-runner";42import type { CheckAt } from "@repo/checks/check-runner";43import { CheckRunnerLocal } from "@repo/checks/check-runner/local";44import { cannedDrafter } from "@repo/drafting/draft-runs/canned";45import { draftRunsInline } from "@repo/drafting/draft-runs/inline";46import type { InlinePorts } from "@repo/drafting/draft-runs/inline";47import type { Drafter } from "@repo/drafting/drafter";48import { Projects } from "@repo/project/projects";49import { VerifierBlocked } from "@repo/protocol/refusal";50import { git } from "@repo/testkit/git";51import { untouchable } from "@repo/testkit/untouchable";52import {53 Console,54 Context,55 Deferred,56 Duration,57 Effect,58 FileSystem,59 Layer,
119 unmodified lines
179 worker: all,180 };181 };182183/**184 * `plugIn` with draft runs in process beside it: each Project DO starts its185 * rounds inline, on the Worker's ports (which the Worker's side hands over186 * once built) and `drafter`.187 */188const withDrafts = (189 plugIn: PlugIn,190 ready: Deferred.Deferred<Context.Context<InlinePorts>>,191 drafter: Context.Context<Drafter>192): PlugIn => ({193 project: Layer.merge(194 plugIn.project ?? Layer.empty,195 draftRunsInline(Deferred.await(ready))196 ),197 worker: Layer.merge(198 plugIn.worker ?? Layer.empty,199 Layer.effectDiscard(200 Effect.flatMap(Effect.context<Projects | RepoHost>(), (ports) =>201 Deferred.succeed(ready, Context.merge(drafter, ports))202 )203 )204 ),205});206207/** How long after the last round the world carries queued answer runs again. */208const CARRY_EVERY = Duration.millis(250);209210const serve = Effect.gen(function* () {
10 unmodified lines
221 const { decodeEnv } = yield* Effect.promise(222 () => import("../src/platform.ts")223 );224225 const drafter = yield* Layer.build(cannedDrafter);226 const ready = yield* Deferred.make<Context.Context<InlinePorts>>();227 const plugged = cartridgesOver(cartridges, decodeEnv);228229 const world = yield* coreLoopWorld({230 checker: localChecker,192 plugIn: cartridgesOver(cartridges, decodeEnv),231 plugIn: (aside) => withDrafts(plugged(aside), ready, drafter),232 sessions,233 });234235 // The Answer Workflow's stand-in: the queued runs, carried every
21 unmodified lines
modified:apps/web/src/dev/examples.ts+23 added-2 removed
14 unmodified lines
15 * A project's rules are its committed `policy.json`, the config folder the16 * `/json` rules evaluator reads, with every ask it will open stated there;17 * an ask opens when a decider lands its files. Each ask file is written18 * from the ask `policy.json` states, as the SDK call a maintainer writes,19 * so the two never disagree.19 * so the two never disagree. datekit's `policy.json` also states the ask20 * the dev world's drafter drafts, which only an accepted draft opens.21 */22import { Brand } from "@repo/brand";23import { cannedDraft } from "@repo/drafting/draft-runs/canned";24import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";25import { Command, SymbolName } from "@repo/protocol/domain/common";26import type { AskKind } from "@repo/protocol/domain/kind";27import { PolicyInput } from "@repo/protocol/domain/policy";
242 unmodified lines
270 want: "diffInDays counts calendar days across a daylight-saving change.",271 }),272];273274/**275 * The ask the dev world's drafter drafts for any want (`cannedDraft`),276 * stated beside datekit's own so the `/json` rules evaluator finds it once277 * a draft's files are composed; nobody opens it in the seed. A decider who278 * accepts the draft opens it.279 */280const draftedAsk: StatedAsk = {281 askedBy: datekitPeople.decider,282 blockedBy: [],283 brief: { current: cannedDraft.current, want: cannedDraft.want },284 check: encodeCheck(285 CheckSpec.cases.RedThenGreen.make({ path: cannedDraft.test.path })286 ),287 file: `${dir}/asks/${cannedDraft.id}.ask.ts`,288 id: cannedDraft.id,289 kind: cannedDraft.kind,290 territory: { module: ".", paths: [...cannedDraft.territory] },291};292293const library: Files = new Map([294 [295 "README.md",296 [
106 unmodified lines
403 ],404 [405 `${dir}/policy.json`,406 policyJson({386 asks: datekitAsks.map(({ stated }) => stated),407 asks: [...datekitAsks.map(({ stated }) => stated), draftedAsk],408 deciders: [409 { handles: [datekitPeople.decider], paths: "**" },410 { handles: [datekitPeople.zones], paths: "src/tz.ts" },411 ],
284 unmodified lines
modified:apps/web/src/dev/world.ts+9 added-3 removed
4 unmodified lines
5 * Lander does the trusted Lander's work over them (`lander.ts`); the6 * Checker is scripted (`checker.ts`); rules are read from each project's7 * committed `policy.json` (`/json`); answers run in process; alarms are8 * recorded and never fire; the front page is folded from the projection's9 * rows (`front-page.ts`); lane logs are kept in memory. One clock, set by10 * the seed, is the world's time (`clock.ts`).9 * rows (`front-page.ts`); lane logs are kept in memory. A proposal made10 * with a draft is drafted in process as it is made, by the memory drafter11 * scripted with the canned draft (`@repo/drafting/draft-runs/canned`),12 * and goes red first on the scripted Checker. One clock, set by the seed,13 * is the world's time (`clock.ts`).14 */15import type { RepoHost } from "@repo/artifacts/repo-host";16import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";17import type { EvidenceStore } from "@repo/checks/evidence-store";18import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";19import { cannedDrafter } from "@repo/drafting/draft-runs/canned";20import { withDraftRunsInline } from "@repo/drafting/draft-runs/inline";21import { AlarmsMemory } from "@repo/project/alarms/memory";22import { AnswerRunsInline } from "@repo/project/answer-runs/inline";23import type { FrontPage } from "@repo/project/front-page";24import { FinishersFromChecks } from "@repo/project/project";
12 unmodified lines
37/** Every port a project needs but its store, shared by every project in the world. */38const ports = Layer.mergeAll(39 AlarmsMemory,40 AnswerRunsInline,41 cannedDrafter,42 DevProjection,43 RulesEvaluatorJson.pipe(Layer.provide(FinishersFromChecks))44).pipe(45 Layer.provideMerge(Layer.mergeAll(DevChecker, DevLander)),
7 unmodified lines
53 */54export const devWorld: Layer.Layer<55 Projects | FrontPage | EvidenceStore | RepoHost | DevClock56> = Layer.mergeAll(DevFrontPage, EvidenceStoreMemory).pipe(51 Layer.provideMerge(ProjectsMemory),57 Layer.provideMerge(withDraftRunsInline(ProjectsMemory)),58 Layer.provideMerge(ports),59 Layer.provideMerge(devClockAt(devStart)),60 Layer.fresh61);
modified:apps/web/test/dev-backend.test.ts+62 added
3 unmodified lines
4 * minutes from one fixed start (so a page looks the same on every machine5 * and every run), and an answer that landed with its credit.6 */7import { describe, expect, it } from "@effect/vitest";8import { Brand } from "@repo/brand";9import { Client, Contracts } from "@repo/protocol/contracts";10import { ProjectEvent } from "@repo/protocol/domain/event";11import { Handle, ProjectName } from "@repo/protocol/ids";12import {
271 unmodified lines
284 expect([climbed?.status, climbed?.text]).toStrictEqual([404, ""]);285 })286 );287});288289/**290 * bram proposes a want for datekit with a draft, and what follows: the291 * proposal as anyone reads it, and ines-v's Today before and after.292 */293const drafted = inFreshWorld((as) =>294 Effect.gen(function* () {295 const anyone = yield* clientOf(as());296 const ines = yield* clientOf(as(decider));297 const bram = yield* clientOf(as(contributor));298 const project = ProjectName.make("datekit");299 const before = yield* ines.today({ project });300301 const { proposal } = yield* bram.proposeAsk({302 draft: true,303 project,304 want: "datekit reads ordinal dates such as 2026-280.",305 });306307 const shown = yield* anyone.showProposal({308 project,309 proposal: proposal.id,310 });311312 return {313 after: yield* ines.today({ project }),314 before,315 proposed: proposal,316 shown,317 };318 })319);320321describe("a draft in the dev world", seededWorlds, () => {322 it.live(323 "is drafted as it is proposed, red first on the scripted Checker, and its decision joins the decider's Today",324 () =>325 Effect.gen(function* () {326 const { after, before, proposed, shown } = yield* drafted;327328 // The seeded decisions expire first and fill the day's budget, so329 // the draft's decision waits on Today as its overflow.330 expect({331 files: shown.files.map(({ path }) => path),332 overflow: [before.overflow, after.overflow],333 proposed: proposed.draft?._tag,334 ready: shown.proposal.draft?._tag,335 shown: after.decisions.map(({ id }) => id),336 }).toStrictEqual({337 files: [338 `${Brand.configDir}/asks/parse-ordinal.ask.ts`,339 "test/asks/parse-ordinal.test.ts",340 ],341 overflow: [0, 1],342 proposed: "Drafting",343 ready: "Ready",344 shown: before.decisions.map(({ id }) => id),345 });346 })347 );348});
modified:packages/config/test/smoke-loop.test.ts+91 added-1 removed
27 unmodified lines
28import {29 DemoStageRefused,30 smokeLoop,31} from "../../../scripts/lib/smoke/loop.ts";32import { main } from "../../../scripts/smoke.ts";32import { DraftNeedsLoop, main } from "../../../scripts/smoke.ts";33import { Brand } from "../../brand/src/index.ts";34import { Handle } from "../../protocol/src/ids.ts";3536const decider = Handle.make("ines-v");
224 unmodified lines
261 });262 }).pipe(Effect.provide(NodeServices.layer))263 );264});265266describe("smokeLoop --draft, against the Node world", () => {267 it.live(268 "after the loop, the answerer's want is drafted red first by the memory drafter, the decider accepts it, and the ask opens disclosing the drafter beside the asker",269 () =>270 Effect.gen(function* () {271 const fs = yield* FileSystem.FileSystem;272 const path = yield* Path.Path;273 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "smoke-910-" });274275 const report = yield* Effect.scoped(276 Effect.gen(function* () {277 const origin = yield* servedWorld(278 new Map([279 [decider, tokens.decider],280 [answerer, tokens.answerer],281 ])282 );283284 return yield* smokeLoop({285 answerer: tokens.answerer,286 decider: tokens.decider,287 draft: true,288 origin,289 run: "r2",290 stage: "node",291 });292 })293 ).pipe(294 Effect.provideService(LedgerFile, path.join(dir, "created.jsonl"))295 );296297 expect({298 attempts: report.draft?.attempts,299 model: report.draft?.model,300 steps: report.timings.map(({ step }) => step).slice(-3),301 timed: (report.draft?.ms ?? -1) >= 0,302 trailers: report.draft?.trailers.filter((trailer) =>303 /^(?:Ask|Asked-by|Assisted-by):/u.test(trailer)304 ),305 }).toStrictEqual({306 attempts: 1,307 model: "memory",308 steps: ["draft-propose", "draft-ready", "draft-accept"],309 timed: true,310 trailers: [311 `Asked-by: ${credited("bram")}`,312 `Assisted-by: ${Brand.cli}-drafter:memory (verified)`,313 "Ask: smoke-r2/parse-ordinal",314 ],315 });316 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),317 240_000318 );319});320321describe("smoke --draft without --loop", () => {322 it.live(323 "is refused with DraftNeedsLoop before any request or process: only the loop has a project to draft on",324 () =>325 Effect.gen(function* () {326 const fetched: string[] = [];327 const spawner = yield* refusing;328329 const result = yield* main([330 "--stage",331 "dev-oscabriel",332 "--draft",333 ]).pipe(334 Effect.provide(spawner.layer),335 Effect.provideService(FetchHttpClient.Fetch, (input) => {336 fetched.push(new Request(input).url);337338 return Promise.reject(new Error("smoke --draft fetched"));339 }),340 Effect.result341 );342343 expect({344 fetched,345 result,346 spawned: yield* spawner.asked,347 }).toStrictEqual({348 fetched: [],349 result: Result.fail(new DraftNeedsLoop({ flag: "--draft" })),350 spawned: [],351 });352 }).pipe(Effect.provide(NodeServices.layer))353 );354});
added:packages/drafting/src/draft-runs/canned.ts+47 added
1/**2 * The draft the worlds without a model give every proposal drafted in them3 * (the web's dev world, the platform's Node world): an ask for a reader of4 * ordinal dates in `src/parse.ts`, whose test fails on main by its5 * assertion wherever that file has none, in datekit and in smoke's6 * throwaway project alike. So `bun run dev` and `smoke --loop --draft`7 * show a draft end to end, offline.8 */9import { AskId, RepoPath } from "@repo/protocol/ids";10import { Array } from "effect";11import type { Layer } from "effect";1213import type { DraftedAsk } from "../drafted.ts";14import type { Drafter } from "../drafter.ts";15import { DrafterMemory } from "../drafter/memory.ts";16import type { DraftsAsked } from "../drafter/memory.ts";1718/** How many drafts a world gives before its drafter's script runs out. */19const CANNED_DRAFTS = 64;2021export const cannedDraft = {22 current: "src/parse.ts reads no ordinal date.",23 id: AskId.make("parse-ordinal"),24 kind: "fix",25 rationale:26 "src/parse.ts exports no parseOrdinal, so the test fails by its assertion on main.",27 territory: [RepoPath.make("src/parse.ts")],28 test: {29 path: RepoPath.make("test/asks/parse-ordinal.test.ts"),30 source: [31 'import { expect, test } from "bun:test";',32 "",33 'import * as parsing from "../../src/parse.ts";',34 "",35 'test("parse.ts exports parseOrdinal, for dates such as 2026-280", () => {',36 ' expect(typeof Reflect.get(parsing, "parseOrdinal")).toBe("function");',37 "});",38 "",39 ].join("\n"),40 },41 want: "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.",42} satisfies DraftedAsk;4344/** The memory drafter, scripted with the canned draft for every attempt a world makes. */45export const cannedDrafter: Layer.Layer<Drafter | DraftsAsked> = DrafterMemory(46 Array.replicate(cannedDraft, CANNED_DRAFTS)47);
added:packages/drafting/src/draft-runs/inline.ts+105 added
1/**2 * `DraftRuns` in process, for tests and the worlds that run without a3 * Workflow engine (the web's dev world, the platform's Node world): `start`4 * runs the round's program (`runDraft`) at once, to its settling, as5 * `@repo/project`'s `AnswerRunsInline` runs an answer's steps. Each step runs6 * once, its failures retried as its retries say, without waiting; nothing7 * is recorded, since nothing replays. A round already under way is not8 * started twice, and a run that dies is logged: the proposal stays9 * drafting, and its proposer may draft it again.10 *11 * The run reaches the project through `Projects`, which is built over the12 * project services that start runs: so the runs take their ports when a13 * round starts (`draftRunsInline`), and `withDraftRunsInline` ties the knot14 * for a `Projects` layer, handing its runs the `Projects` it builds.15 */16import type { RepoHost } from "@repo/artifacts/repo-host";17import { DraftRuns } from "@repo/project/draft-runs";18import type { DraftParams } from "@repo/project/draft-runs";19import { Projects } from "@repo/project/projects";20import { Context, Deferred, Effect, Layer, Ref } from "effect";2122import type { Drafter } from "../drafter.ts";23import { runDraft } from "../run.ts";24import type { DraftSteps } from "../run.ts";2526/** What a round runs on. */27export type InlinePorts = Projects | Drafter | RepoHost;2829/** Steps run once each, in process: a failure retried as its retries say, at once. */30const inlineSteps: DraftSteps = {31 step: (_name, _schema, effect, retry) =>32 Effect.retry(effect, { times: retry?.limit ?? 0 }),33};3435/** One round's key: its project, proposal and round. */36const keyOf = ({ project, proposal, round }: DraftParams) =>37 `${project}/${proposal}/${round}`;3839/** `DraftRuns` that run each round in process, on the ports `portsOf` gives when it starts. */40export const draftRunsInline = (41 portsOf: Effect.Effect<Context.Context<InlinePorts>>42): Layer.Layer<never> =>43 Layer.effect(44 DraftRuns,45 Effect.gen(function* () {46 const running = yield* Ref.make<ReadonlySet<string>>(new Set());4748 const claimRun = (key: string) =>49 Ref.modify(running, (under) =>50 under.has(key) ? [false, under] : [true, new Set(under).add(key)]51 );5253 const endRun = (key: string) =>54 Ref.update(running, (under) => {55 const rest = new Set(under);5657 rest.delete(key);5859 return rest;60 });6162 return {63 start: (params) =>64 Effect.gen(function* () {65 const key = keyOf(params);6667 if (!(yield* claimRun(key))) {68 return;69 }7071 yield* runDraft(params, inlineSteps).pipe(72 Effect.provideContext(yield* portsOf),73 Effect.catchCause((cause) =>74 Effect.logWarning("a draft's run died", cause)75 ),76 Effect.ensuring(endRun(key))77 );78 }),79 };80 })81 );8283/**84 * `projects` with in-process draft runs: every project service it builds85 * starts its rounds through `draftRunsInline`, which reaches the projects86 * through the `Projects` this layer builds.87 */88export const withDraftRunsInline = <E, R>(89 projects: Layer.Layer<Projects, E, R>90): Layer.Layer<Projects, E, R | Drafter | RepoHost> =>91 Layer.effectContext(92 Effect.gen(function* () {93 const ready = yield* Deferred.make<Context.Context<InlinePorts>>();9495 const built = yield* Layer.build(96 projects.pipe(Layer.provide(draftRunsInline(Deferred.await(ready))))97 );9899 const around = yield* Effect.context<Drafter | RepoHost>();100101 yield* Deferred.succeed(ready, Context.merge(around, built));102103 return Context.make(Projects, Context.get(built, Projects));104 })105 );
added:packages/drafting/src/run.ts+362 added
1/**2 * One draft run, as a program over named steps (W9-D14): the platform's3 * `Answer` Workflow runs it with durable steps (`apps/platform`'s4 * `workflows/draft-steps.ts`), and `draft-runs/inline.ts` runs it in5 * process, so both reach the same end.6 *7 * - `context`: the project's open proposal (`draftContext`), and the files8 * the drafter reads, picked from the canonical repo at the landed commit9 * and read there (never a layer's repo). The step records them, so a10 * replay reads nothing. A project with no `fix` kind settles at once,11 * `Failed{IncompleteBrief}`, with no model call.12 * - for each attempt n, at most `DRAFT_ROUNDS`: `draft-<n>`, the model's13 * draft, recorded as `DraftedAsk`, so a replay never asks the model14 * again; then `rehearse-<n>`, its files rehearsed as `accept` would open15 * them (`rehearseOpen`). `Red` ends the round; `Refused` becomes the next16 * attempt's feedback (the refusal as `protocol/render` says it, the17 * diagnosis and the output's tail). A draft the model could not give is18 * a spent attempt, except `rate-limited`, which the step retries.19 * - `settle`: the round's end, told to the project (`draftSettled`), which20 * ignores a round no longer current.21 *22 * A step whose retries are spent is kept failed by the engine and thrown23 * again, unrun, in every replay, where its typed failure is gone: so what24 * the program makes of it is recorded as a value in a step of its own25 * (`<step>:gave-up`), which every replay reads back.26 */27import { RepoHost, Revision } from "@repo/artifacts/repo-host";28import { DraftResult, DRAFT_ROUNDS, Rehearsal } from "@repo/project/draft-runs";29import type { DraftParams } from "@repo/project/draft-runs";30import { Projects } from "@repo/project/projects";31import { RepoName, RepoPath } from "@repo/protocol/ids";32import type { Refusal } from "@repo/protocol/refusal";33import { IncompleteBrief, VerifierBlocked } from "@repo/protocol/refusal";34import { Cause, Context, Effect, Option, Record, Schema } from "effect";3536import { askTestFolderOf, pickFiles } from "./context.ts";37import { DraftContext, DraftedAsk, DraftFailed } from "./drafted.ts";38import type { DraftInput } from "./drafted.ts";39import { Drafter } from "./drafter.ts";40import { feedbackText, policyDigest } from "./prompt.ts";41import { draftedFiles } from "./render.ts";4243/** How often, and how far apart, a failed step runs again before it is spent. */44export interface StepRetry {45 readonly limit: number;46 readonly delayMs: number;47 readonly backoff: "constant" | "linear" | "exponential";48}4950/**51 * The steps a run takes: each named, its value recorded by `schema`, and52 * run once per run (a replay reads the record back). A failure is retried53 * per `retry`, and once spent fails the step.54 */55export interface DraftSteps {56 readonly step: <A, I, E, R>(57 name: string,58 schema: Schema.Codec<A, I>,59 effect: Effect.Effect<A, E, R>,60 retry?: StepRetry61 ) => Effect.Effect<A, E, R>;62}6364/**65 * The model the drafter asks, as a settled round names it (`drafted by`,66 * and the accepted landing's `Assisted-by:`). The platform gives its67 * `DRAFT_MODEL`; a world with the memory drafter keeps the default.68 */69export const DraftModel = Context.Reference<string>("drafting/DraftModel", {70 defaultValue: () => "memory",71});7273/** A rate-limited model is asked again, further apart each time. */74export const rateLimitedRetry: StepRetry = {75 backoff: "exponential",76 delayMs: 15_000,77 limit: 4,78};7980/** A Checker that could not run, or a main that moved, is rehearsed again. */81export const blockedRetry: StepRetry = {82 backoff: "exponential",83 delayMs: 60_000,84 limit: 3,85};8687/** What `context` records: what the attempts read, or why the round has none. */88const Prepared = Schema.TaggedUnion({89 /** The proposal is closed or gone: nothing to draft or settle. */90 Gone: {},91 /** The project has no `fix` kind, the only kind drafted. */92 NoFix: {},93 Ready: {94 context: DraftContext,95 territory: Schema.optionalKey(Schema.NonEmptyString),96 want: Schema.NonEmptyString,97 },98});99100type Prepared = typeof Prepared.Type;101102/** What `draft-<n>` records: the model's draft, or why it gave none. */103const Attempted = Schema.TaggedUnion({104 Drafted: { drafted: DraftedAsk },105 Spent: { reason: DraftFailed.fields.reason },106});107108type Attempted = typeof Attempted.Type;109110/** The kind a draft is: W9 drafts `fix` asks only (W9-D13). */111const draftedKind = "fix";112113/** A proposal's territory as the paths whose files the drafter reads. */114const territoryPaths = (territory: string | undefined) =>115 (territory ?? "")116 .split(/[\s,]+/u)117 .map((path) => path.replace(/(?:\/\*\*)?\/*$/u, ""))118 .filter((path) => path !== "" && path !== ".")119 .map((path) => RepoPath.make(path));120121const decoder = new TextDecoder();122123/** `{ [key]: value }` when `value` is there, else no key at all. */124const field = <K extends string, A>(125 key: K,126 value: Option.Option<A>127): Partial<Record<K, A>> =>128 Option.match(value, {129 onNone: () => ({}),130 onSome: (present) => Record.singleton(key, present),131 });132133/** What the next attempt is told when the model gave no draft. */134const spentText = (reason: string) =>135 `Your reply gave no draft (${reason}): answer with one JSON object that matches the schema, and nothing else.`;136137/** The refusal a round that never rehearsed ends with: no draft, and why. */138const noDraft = (reason: string): Refusal =>139 new IncompleteBrief({ missing: [`a draft (${reason})`] });140141/** Runs one round of a proposal's draft to its settling, over `steps`. */142export const runDraft = (143 params: DraftParams,144 steps: DraftSteps145): Effect.Effect<void, never, Projects | Drafter | RepoHost> =>146 Effect.gen(function* () {147 const { step } = steps;148 const projects = yield* Projects;149 const drafter = yield* Drafter;150 const host = yield* RepoHost;151 const model = yield* DraftModel;152 const project = projects.get(params.project);153154 const prepare = Effect.gen(function* () {155 const api = yield* project;156 const data = yield* api.draftContext(params.proposal, params.round);157158 if (!data.policy.kinds.some(({ name }) => name === draftedKind)) {159 return Prepared.cases.NoFix.make({});160 }161162 const repo = RepoName.make(data.project);163164 const read = (path: RepoPath) =>165 host.readFile(repo, Revision.Commit({ sha: data.at }), path).pipe(166 Effect.map(167 Option.match({168 onNone: () => "",169 onSome: (bytes) => decoder.decode(bytes),170 })171 ),172 Effect.catchTag("RepoNotFound", () => Effect.succeed(""))173 );174175 const files = yield* pickFiles(176 data.paths,177 { territory: territoryPaths(data.territory), want: data.want },178 read179 );180181 return Prepared.cases.Ready.make({182 context: {183 at: data.at,184 files,185 policy: policyDigest(data.policy, askTestFolderOf(files)),186 project: data.project,187 },188 ...field("territory", Option.fromUndefinedOr(data.territory)),189 want: data.want,190 });191 }).pipe(192 Effect.catchTags({193 ProposalClosed: () => Effect.succeed(Prepared.cases.Gone.make({})),194 UnknownProject: () => Effect.succeed(Prepared.cases.Gone.make({})),195 UnknownProposal: () => Effect.succeed(Prepared.cases.Gone.make({})),196 })197 );198199 const prepared: Prepared = yield* step("context", Prepared, prepare);200201 const settle = (result: DraftResult) =>202 step(203 "settle",204 Schema.Boolean,205 project.pipe(206 Effect.flatMap((api) =>207 api.draftSettled(params.proposal, params.round, result)208 ),209 Effect.as(true),210 Effect.catchTag("UnknownProject", () => Effect.succeed(false))211 )212 );213214 /** Up to `DRAFT_ROUNDS` attempts, each fed the last one's failure. */215 const attempts = (216 ready: Extract<Prepared, { readonly _tag: "Ready" }>217 ): Effect.Effect<DraftResult> =>218 Effect.gen(function* () {219 let feedback = Option.none<string>();220 let last: Refusal = noDraft("none given");221222 for (let attempt = 1; attempt <= DRAFT_ROUNDS; attempt += 1) {223 const input: DraftInput = {224 attempt,225 context: ready.context,226 ...field("feedback", feedback),227 ...field("note", Option.fromUndefinedOr(params.note)),228 ...field("territory", Option.fromUndefinedOr(ready.territory)),229 want: ready.want,230 };231232 const tried: Attempted = yield* step(233 `draft-${attempt}`,234 Attempted,235 drafter.draft(input).pipe(236 Effect.map((drafted) =>237 Attempted.cases.Drafted.make({ drafted })238 ),239 Effect.catchTag("DraftFailed", (failed) =>240 failed.reason === "rate-limited"241 ? Effect.fail(failed)242 : Effect.succeed(243 Attempted.cases.Spent.make({ reason: failed.reason })244 )245 )246 ),247 rateLimitedRetry248 ).pipe(249 Effect.catchCause(() =>250 step(251 `draft-${attempt}:gave-up`,252 Attempted,253 Effect.succeed(254 Attempted.cases.Spent.make({ reason: "rate-limited" })255 )256 )257 )258 );259260 if (Attempted.guards.Spent(tried)) {261 feedback = Option.some(spentText(tried.reason));262 last = noDraft(tried.reason);263264 continue;265 }266267 const { drafted } = tried;268 const files = draftedFiles(drafted);269270 // A Checker still blocked (or a main still moving) once the271 // retries are spent ends the round: another draft would not help.272 const gaveUp = (cause: Cause.Cause<Refusal>) =>273 step(274 `rehearse-${attempt}:gave-up`,275 Rehearsal,276 Effect.succeed(277 Rehearsal.cases.Refused.make({278 diagnosis: "Blocked",279 excerpt: "",280 refusal: Option.getOrElse(281 Cause.findErrorOption(cause),282 (): Refusal => new VerifierBlocked({})283 ),284 })285 )286 ).pipe(Effect.map((rehearsal) => ({ blocked: true, rehearsal })));287288 const rehearsed = yield* step(289 `rehearse-${attempt}`,290 Rehearsal,291 Effect.flatMap(project, (api) => api.rehearseOpen(files)).pipe(292 Effect.catchTag("UnknownProject", () =>293 Effect.fail(new VerifierBlocked({}))294 )295 ),296 blockedRetry297 ).pipe(298 Effect.map((rehearsal) => ({ blocked: false, rehearsal })),299 Effect.catchCause(gaveUp)300 );301302 if (Rehearsal.guards.Red(rehearsed.rehearsal)) {303 return DraftResult.cases.Red.make({304 attempts: attempt,305 files,306 lane: rehearsed.rehearsal.lane,307 model,308 rationale: drafted.rationale,309 signature: rehearsed.rehearsal.signature,310 });311 }312313 const refused = rehearsed.rehearsal;314315 last = refused.refusal;316317 if (rehearsed.blocked) {318 return DraftResult.cases.Failed.make({319 attempts: attempt,320 model,321 refusal: last,322 });323 }324325 feedback = Option.some(326 feedbackText({327 diagnosis: refused.diagnosis,328 excerpt: refused.excerpt,329 refusal: refused.refusal,330 })331 );332 }333334 return DraftResult.cases.Failed.make({335 attempts: DRAFT_ROUNDS,336 model,337 refusal: last,338 });339 });340341 const result: Option.Option<DraftResult> = yield* Prepared.match(prepared, {342 Gone: () => Effect.succeedNone,343 NoFix: () =>344 Effect.succeedSome(345 DraftResult.cases.Failed.make({346 attempts: 1,347 model,348 refusal: new IncompleteBrief({ missing: ["kinds.fix"] }),349 })350 ),351 Ready: (ready) => Effect.asSome(attempts(ready)),352 });353354 if (Option.isSome(result)) {355 yield* settle(result.value);356 }357 }).pipe(358 Effect.annotateLogs({359 proposal: params.proposal,360 round: String(params.round),361 })362 );
added:packages/drafting/test/run.test.ts+108 added
1/**2 * The draft run's program over a fake step runner: the steps it names, and3 * what it settles, with the project and the drafter faked at their ports.4 */5import { describe, expect, it } from "@effect/vitest";6import { RepoHost } from "@repo/artifacts/repo-host";7import { DraftResult } from "@repo/project/draft-runs";8import type { DraftContextData } from "@repo/project/draft-runs";9import type { ProjectApi } from "@repo/project/project";10import { Projects } from "@repo/project/projects";11import { PublicPolicy } from "@repo/protocol/domain/policy";12import { ProposalId } from "@repo/protocol/ids";13import { IncompleteBrief } from "@repo/protocol/refusal";14import { aProject } from "@repo/testkit/scenarios";15import { untouchable } from "@repo/testkit/untouchable";16import { Effect, Layer, Ref, Schema, Struct } from "effect";1718import { DrafterMemory, DraftsAsked } from "../src/drafter/memory.ts";19import { DraftModel, runDraft } from "../src/run.ts";20import type { DraftSteps } from "../src/run.ts";2122const scenario = aProject();2324const proposal = ProposalId.make("prop-000001");2526/** The scenario's policy as anyone reads it, with no `fix` kind. */27const withoutFix = Schema.decodeSync(PublicPolicy)(28 Schema.encodeSync(PublicPolicy)({29 ...Struct.omit(scenario.policy, ["asks", "functions", "visibility"]),30 kinds: scenario.policy.kinds.filter(({ name }) => name !== "fix"),31 })32);3334const context: DraftContextData = {35 at: scenario.landed,36 paths: [],37 policy: withoutFix,38 project: scenario.project,39 proposal,40 round: 1,41 want: "Parse an ISO week date such as 2026-W41",42};4344describe(runDraft, () => {45 it.effect(46 "settles Failed with IncompleteBrief, and never asks the drafter, when the project has no fix kind",47 () =>48 Effect.gen(function* () {49 const names = yield* Ref.make<readonly string[]>([]);5051 const settled = yield* Ref.make<52 readonly (readonly [number, DraftResult])[]53 >([]);5455 const steps: DraftSteps = {56 step: (name, _schema, effect) =>57 Effect.andThen(58 Ref.update(names, (all) => [...all, name]),59 effect60 ),61 };6263 const api = untouchable<ProjectApi>("the project", {64 draftContext: () => Effect.succeed(context),65 draftSettled: (_proposal, round, result) =>66 Ref.update(settled, (all) => [...all, [round, result] as const]),67 });6869 yield* runDraft(70 { project: scenario.project, proposal, round: 1 },71 steps72 ).pipe(73 Effect.provide(74 Layer.mergeAll(75 Layer.succeed(Projects, {76 create: () => Effect.die("no project is made"),77 get: () => Effect.succeed(api),78 }),79 Layer.succeed(80 RepoHost,81 untouchable<RepoHost["Service"]>("RepoHost")82 ),83 Layer.succeed(DraftModel, "@cf/test/model")84 )85 )86 );8788 expect({89 asked: yield* DraftsAsked.use(({ inputs }) => inputs),90 names: yield* Ref.get(names),91 settled: yield* Ref.get(settled),92 }).toStrictEqual({93 asked: [],94 names: ["context", "settle"],95 settled: [96 [97 1,98 DraftResult.cases.Failed.make({99 attempts: 1,100 model: "@cf/test/model",101 refusal: new IncompleteBrief({ missing: ["kinds.fix"] }),102 }),103 ],104 ],105 });106 }).pipe(Effect.provide(DrafterMemory([])))107 );108});
modified:scripts/lib/smoke/core-loop.ts+197 added-1 removed
15 unmodified lines
16import { Brand } from "@repo/brand";17import { AnswerView } from "@repo/protocol/domain/answer";18import { Ask } from "@repo/protocol/domain/ask";19import { ClaimView } from "@repo/protocol/domain/claim";20import { Decision, DecisionSubject } from "@repo/protocol/domain/decision";21import { Outcome } from "@repo/protocol/domain/outcome";22import { DraftState, Proposal } from "@repo/protocol/domain/proposal";23import { Envelope } from "@repo/protocol/envelope";24import { AskId, CommitSha, Handle, LandedSha } from "@repo/protocol/ids";23import type { ProjectName } from "@repo/protocol/ids";25import type { ProjectName, ProposalId } from "@repo/protocol/ids";26import { explain } from "@repo/protocol/render";27import {28 Array,29 Config,
19 unmodified lines
49 "out-of-scope",50 "answer",51 "landing",52 "verdict-note",53 "draft-propose",54 "draft-ready",55 "draft-accept",56]);5758export type LoopStep = typeof LoopStep.Type;59
750 unmodified lines
810 )811 )812 )813 );814815// ------------------------------------------------------------------ drafts816817/** What the loop's draft proposal wants: a reader of ordinal dates beside `parse`. */818const DRAFT_WANT =819 "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.";820821const Proposed = Schema.Struct({ proposal: Proposal });822823const Shown = Schema.Struct({ proposal: Proposal });824825/** Proposes the draft's want as `proposer`, with `--draft`: the proposal, drafting. */826export const proposeDraft = (proposer: LoopPerson, project: ProjectName) =>827 Effect.map(828 cli(829 "draft-propose",830 proposer,831 ["propose", "--project", project, "--want", DRAFT_WANT, "--draft"],832 Proposed833 ),834 ({ proposal }) => proposal.id835 );836837/** The draft is still being drafted. */838class StillDrafting extends Schema.TaggedError<StillDrafting>()(839 "StillDrafting",840 {}841) {}842843/** A draft that went red first: the model that drafted it, and its attempts. */844export interface DraftReady {845 readonly model: string;846 readonly attempts: number;847}848849/**850 * Asks `<cli> proposal <id>` as `reader` until the draft is settled: ready,851 * or the step fails with the last refusal a failed draft names.852 */853export const awaitDraft = (input: {854 readonly reader: LoopPerson;855 readonly project: ProjectName;856 readonly proposal: ProposalId;857 readonly patience: Patience;858}) =>859 Effect.gen(function* () {860 const { project, proposal, reader } = input;861862 /** Where the draft stands: settled, or still drafting, which is asked again. */863 const settled = (864 shown: Proposal865 ): Effect.Effect<DraftState, LoopFailed | StillDrafting> =>866 Option.match(Option.fromUndefinedOr(shown.draft), {867 onNone: () =>868 Effect.fail(869 failed("draft-ready", `the proposal ${proposal} has no draft`)870 ),871 onSome: (state) =>872 DraftState.guards.Drafting(state)873 ? Effect.fail(new StillDrafting())874 : Effect.succeed(state),875 });876877 const draft = yield* cli(878 "draft-ready",879 reader,880 ["proposal", proposal, "--project", project],881 Shown882 ).pipe(883 Effect.flatMap(({ proposal: shown }) => settled(shown)),884 Effect.retry({885 schedule: Schedule.spaced(input.patience.every).pipe(886 Schedule.upTo({ duration: input.patience.within })887 ),888 while: Schema.is(StillDrafting),889 }),890 Effect.catchTag("StillDrafting", () =>891 Effect.fail(892 failed(893 "draft-ready",894 `the proposal ${proposal} was still drafting after ${Duration.format(input.patience.within)}`895 )896 )897 )898 );899900 if (DraftState.guards.Ready(draft)) {901 return {902 attempts: draft.attempts,903 model: draft.model,904 } satisfies DraftReady;905 }906907 return yield* failed(908 "draft-ready",909 DraftState.guards.Failed(draft)910 ? `the draft of ${proposal} failed after ${draft.attempts} attempts, last refused ${draft.refusal}`911 : `the proposal ${proposal} is still drafting`912 );913 });914915const TodayIs = Schema.Struct({ decisions: Schema.Array(Decision) });916917const Decided = Schema.Struct({ decision: Decision });918919/**920 * Accepts the drafted proposal as `decider`, from their Today, and reads921 * the landing that opened its ask on main, fetched from the platform at922 * `origin` into the repo at `dir`: its923 * trailers, which must disclose the drafter (`Assisted-by:`) and credit924 * `proposer` as its asker.925 */926export const acceptDraft = (input: {927 readonly decider: LoopPerson;928 readonly proposer: Handle;929 readonly project: ProjectName;930 readonly proposal: ProposalId;931 readonly dir: string;932 readonly origin: string;933}) =>934 Effect.gen(function* () {935 const { decider, dir, project, proposal } = input;936937 const { decisions } = yield* cli(938 "draft-accept",939 decider,940 ["today", "--project", project],941 TodayIs942 );943944 const decision = yield* Effect.fromOption(945 Array.findFirst(946 decisions,947 ({ subject }) =>948 DecisionSubject.guards.OpenProposal(subject) &&949 subject.proposal === proposal950 )951 ).pipe(952 Effect.mapError(() =>953 failed(954 "draft-accept",955 `${decider.handle}'s Today holds no decision on ${proposal}`956 )957 )958 );959960 yield* cli(961 "draft-accept",962 decider,963 [964 "decide",965 "--project",966 project,967 "--decision",968 decision.id,969 "--choice",970 "accept",971 "--yes",972 ],973 Decided974 );975976 yield* gitOk("draft-accept", decider, dir, [977 "fetch",978 "--quiet",979 `${input.origin}/${project}.git`,980 "refs/heads/main",981 ]);982983 const trailers = (yield* gitOk("draft-accept", decider, dir, [984 "log",985 "-1",986 "--format=%(trailers:only,unfold)",987 "FETCH_HEAD",988 ]))989 .split("\n")990 .filter((line) => line.length > 0);991992 const missing = [993 "Assisted-by: ",994 `Asked-by: ${input.proposer} `,995 "Ask: ",996 ].filter((prefix) => !trailers.some((line) => line.startsWith(prefix)));997998 return missing.length === 0999 ? trailers1000 : yield* failed(1001 "draft-accept",1002 `the landing that opened ${proposal}'s ask lacks ${missing.map((prefix) => prefix.trim()).join(" and ")}: its trailers are ${trailers.join("; ") || "none"}`1003 );1004 });
modified:scripts/lib/smoke/loop.ts+83 added-11 removed
13 unmodified lines
14 * 7. `landing`: it lands on main, with the answerer as author, the platform15 * as committer, and the `Asked-by` and `Signed-off-by` trailers;16 * 8. `verdict-note`: its verdict note is on the answer's head in the fork.17 *18 * With `draft`, three more steps on the same project:19 *20 * 9. `draft-propose`: the answerer proposes a want with `--draft`;21 * 10. `draft-ready`: `proposal <id>` until the platform's agent has22 * drafted it, red first (a failed draft fails the step);23 * 11. `draft-accept`: the decider accepts it from Today, and the landing24 * that opened its ask discloses the drafter (`Assisted-by:`) and25 * credits the answerer as its asker.26 *27 * Each step is timed and printed as it passes; the first that fails ends28 * the run. The throwaway project, its repo and the claim's fork are written29 * to the throwaway ledger (`infra/created.ts`, by `smoke`) as soon as each30 * exists. It never runs on `demo`: a throwaway project would show on the
17 unmodified lines
48import { recordCreated } from "../../../infra/created.ts";49import type { Created } from "../../../infra/created.ts";50import { declaredStage, resources } from "../../../infra/stages.ts";51import {52 acceptDraft,53 awaitDraft,54 awaitLanding,55 claimAsk,56 initProject,57 LoopFailed,58 openAsk,59 personAt,60 proposeDraft,61 pushAnswer,62 pushOutOfScope,63 readLanding,64 readVerdictNote,
17 unmodified lines
82 readonly step: LoopStep;83 readonly ms: number;84}8586/** A drafted ask the loop accepted: the model, its attempts, and its landing's trailers. */87export interface DraftReport {88 readonly model: string;89 readonly attempts: number;90 /** From the proposal to the draft settled, in ms. */91 readonly ms: number;92 readonly trailers: readonly string[];93}9495/** A loop that passed: what each step found, and how long each took. */96export interface SmokeLoopReport {97 readonly project: ProjectName;98 /** The refusals git printed for the out-of-territory push: `OutOfScope` among them. */
5 unmodified lines
104 /** Every trailer of the landing commit, as git prints them. */105 readonly trailers: readonly string[];106 readonly noteFound: boolean;107 readonly timings: readonly StepTiming[];108 /** With `draft`, the drafted ask it accepted. */109 readonly draft?: DraftReport;110}111112/** What one loop runs on, and as whom. */113export interface LoopInput {
8 unmodified lines
122 /** Claims the ask and pushes the answer. */123 readonly answerer: Redacted.Redacted;124 /** How the loop waits for the landing: every 2 s, for up to 10 minutes, unless given. */125 readonly patience?: Patience;126 /** Also propose with a draft, wait for it, and accept it (`--draft`). */127 readonly draft?: boolean;128}129130const PATIENCE: Patience = {131 every: Duration.seconds(2),
217 unmodified lines
349 stage,350 "verdict-note"351 )(readVerdictNote({ answerer, dir: work, head }));352328 return {353 const timings = [354 people,355 init,356 opened,357 claimed,358 refused,359 answered,360 landing,361 noted,362 ];363364 const report = {365 author: read.author,366 committer: read.committer,367 landed,368 noteFound: true,369 project,370 refusedWith,335 timings: [336 people,337 init,338 opened,339 claimed,340 refused,341 answered,342 landing,343 noted,344 ],371 timings,372 trailers: read.trailers,373 };374375 if (input.draft !== true) {376 return report;377 }378379 const [proposal, proposed] = yield* timed(380 stage,381 "draft-propose"382 )(proposeDraft(answerer, project));383384 const [ready, drafted] = yield* timed(385 stage,386 "draft-ready"387 )(388 awaitDraft({389 patience: input.patience ?? PATIENCE,390 project,391 proposal,392 reader: answerer,393 })394 );395396 const [trailers, accepted] = yield* timed(397 stage,398 "draft-accept"399 )(400 acceptDraft({401 decider,402 dir: `${dir}/start`,403 origin,404 project,405 proposal,406 proposer: answerer.handle,407 })408 );409410 return {411 ...report,412 draft: {413 ...ready,414 ms: proposed.ms + drafted.ms,415 trailers,416 },417 timings: [...timings, proposed, drafted, accepted],418 };419 }).pipe(Effect.scoped);
modified:scripts/smoke.ts+46 added-4 removed
25 unmodified lines
26 * bun scripts/smoke.ts --stage dev-oscabriel --loop27 *28 * `--loop` refuses `--stage demo` before anything else: the throwaway would29 * show on the front page the user records.30 *31 * `--loop --draft` also has the platform's agent draft an ask on the32 * throwaway project: the answerer proposes a want with `--draft`, the loop33 * waits for the draft to go red first, and the decider accepts it; the34 * landing that opens the ask must disclose the drafter (`Assisted-by:`).35 * It prints the model, the attempts and the time. `--draft` without36 * `--loop` is refused before any request.37 */38import { BunRuntime, BunServices } from "@effect/platform-bun";39import { Handle, sameHandle } from "@repo/protocol/ids";40import {
16 unmodified lines
57 subdomainFile,58} from "../infra/stages.ts";59import { DemoStageRefused, LoopFailed, smokeLoop } from "./lib/smoke/loop.ts";6061/** `--draft` was given without `--loop`: only the loop has a project to draft on. */62export class DraftNeedsLoop extends Schema.TaggedError<DraftNeedsLoop>()(63 "DraftNeedsLoop",64 { flag: Schema.Literal("--draft") }65) {66 override get message() {67 return `${this.flag} drafts an ask on the loop's throwaway project: run it with --loop`;68 }69}7071export {72 NoOrigin,73 platformProbes,74 probes,
107 unmodified lines
182 const run = yield* runName;183184 yield* Console.log(`smoke ${stage}: loop smoke-${run} at ${origin}`);185169 const report = yield* smokeLoop({ ...tokens, origin, run, stage });186 const report = yield* smokeLoop({187 ...tokens,188 draft: argv.includes("--draft"),189 origin,190 run,191 stage,192 });193194 const total = report.timings.reduce((sum, { ms }) => sum + ms, 0);195196 yield* Console.log(197 `smoke ${stage}: loop passed in ${total} ms: ${report.project} landed ${report.landed.slice(0, 12)} by ${report.author}, refused first with ${report.refusedWith.join(", ")}; trailers ${report.trailers.join("; ")}`198 );199200 if (report.draft !== undefined) {201 const { attempts, model, ms, trailers } = report.draft;202203 yield* Console.log(204 `smoke ${stage}: draft by ${model} went red first in ${attempts} of 3 attempts, ${ms} ms from proposal to draft; its ask opened with ${trailers.join("; ")}`205 );206 }207 });208209/**178 * `bun scripts/smoke.ts --stage <s> [--loop] …`: the probes, and with179 * `--loop` the core loop after them.210 * `bun scripts/smoke.ts --stage <s> [--loop [--draft]] …`: the probes, and211 * with `--loop` the core loop after them; `--draft` alone is refused.212 */213export const main = (argv: readonly string[]) =>182 argv.includes("--loop") ? loopMain(argv) : probeMain(argv);214 Effect.gen(function* () {215 if (argv.includes("--loop")) {216 return yield* loopMain(argv);217 }218219 if (argv.includes("--draft")) {220 return yield* new DraftNeedsLoop({ flag: "--draft" });221 }222223 return yield* probeMain(argv);224 });225226if (import.meta.main) {227 BunRuntime.runMain(228 Effect.gen(function* () {229 const args = yield* (yield* Stdio.Stdio).args;
5 unmodified lines