Skip to content
Myr

Merge branch 'build/910-draft-workflow'

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

authored by oscabriel · committed by oscabriel · parents bbe1442, d40eb00 · Browse files · 20 files+2273 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+2273 added−35 removed

  • tests:+1128 added−3 removed
  • other:+1145 added−32 removed

20 files+2273 added−35 removed

added:apps/platform/src/adapters/draft-runs-workflow.ts+75 added
modified:apps/platform/src/workflows/answer.ts+53 added-5 removed
added:apps/platform/src/workflows/draft-steps.ts+53 added
modified:apps/platform/src/answer-runs.ts+55 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/** A modulus for `tagOf`: the Mersenne prime 2^31 - 1, so every step stays a safe integer. */68const TAG_MODULUS = 2_147_483_647;6970/** A polynomial hash of `text`'s code points, in base 36: a short, stable tag for a name cut short. */71const tagOf = (text: string) => {72 let hash = 0;7374 for (const unit of text) {75 hash = (hash * 31 + (unit.codePointAt(0) ?? 0)) % TAG_MODULUS;76 }7778 return hash.toString(36);79};8081/**82 * The instance a draft's round runs as: one per project, proposal and83 * round. The proposal and round are kept whole: a project name too long for84 * the engine's id is cut, and tagged with a hash of the whole name, so no85 * two rounds share an instance (a complete one is never run again).86 */87export const draftId = (88 params: Pick<DraftParams, "project" | "proposal" | "round">89) => {90 const suffix = `-${params.proposal}-r${params.round}`;91 const whole = `draft-${params.project}${suffix}`;9293 if (whole.length <= ID_LENGTH) {94 return whole;95 }9697 const tag = `-${tagOf(params.project)}`;9899 return `${whole.slice(0, ID_LENGTH - tag.length - suffix.length)}${tag}${suffix}`;100};
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+682 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 ProjectName,30 ProposalId,31 RepoName,32 RepoPath,33} from "@repo/protocol/ids";34import { Anonymous, Person } from "@repo/protocol/principal";35import { CapReached } from "@repo/protocol/refusal";36import { advanceTo } from "@repo/testkit/clock";37import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";38import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";3940import { DraftRunsWorkflow } from "../../src/adapters/draft-runs-workflow.ts";41import type { DraftWorkflow } from "../../src/adapters/draft-runs-workflow.ts";42import { DraftParams, draftId } from "../../src/answer-runs.ts";43import { Handlers } from "../../src/handlers.ts";44import type { PlatformConfig } from "../../src/platform.ts";45import { runDraftWorkflow } from "../../src/workflows/answer.ts";46import type { EngineSteps } from "../../src/workflows/draft-steps.ts";47import { draftSteps } from "../../src/workflows/draft-steps.ts";48import { memoSteps, StepRunner } from "../../src/workflows/step.ts";49import type { StepRetry } from "../../src/workflows/step.ts";50import { as, seeded, worldOf } from "../handlers.fixtures.ts";51import { Checker, Pusher, worldWith } from "./answer.fixtures.ts";5253/** What the engine is handed with each step. */54type EngineConfig = Parameters<EngineSteps["do"]>[1];5556/** datekit, decided by alice, with carol vouched and one `fix` ask she may want drafted. */57const scenario = aProject({ people: ["carol"] }).pipe(58 withVouches(["carol"]),59 withAsk({ id: "parse-week", territory: "." })60);6162const { policy, project } = scenario;6364const repo = RepoName.make(project);6566const alice = Person.make({ handle: scenario.initializer });6768const carol = Person.make({69 handle: scenario.people.get("carol") ?? scenario.initializer,70});7172const redThenGreen = LaneName.make("redThenGreen");7374const model = "@cf/moonshotai/kimi-k2.7-code";7576const want = "Parse an ISO week date such as 2026-W41";7778const proposal = ProposalId.make("prop-000001");7980const params = DraftParams.make({ project, proposal, round: 1 });8182const start = [83 ["package.json", '{ "name": "datekit", "type": "module" }\n'],84 ["src/parse.ts", "export const parse = (s) => ({});\n"],85] as const;8687/** A draft of the scenario's ask whose test says `assertion`. */88const draftOf = (assertion: string, id = "parse-week"): DraftedAsk => ({89 id: AskId.make(id),90 kind: "fix",91 rationale: `${id}: parseWeek is missing, so its test fails by an assertion`,92 territory: [RepoPath.make("src/parse.ts")],93 test: {94 path: RepoPath.make(`test/${id}.test.ts`),95 source: [96 'import { expect, it } from "bun:test";',97 'import { parse } from "../src/parse.ts";',98 "",99 `it("${id}", () => {`,100 ` ${assertion}`,101 "});",102 "",103 ].join("\n"),104 },105 want,106});107108/** A test that passes on main, so its draft is not red first. */109const passing = draftOf("expect(parse('2026-W41')).toStrictEqual({});");110111/** A second test that passes on main. */112const passingToo = draftOf("expect(parse('2026-W42')).toStrictEqual({});");113114/** A test that fails on main by its assertion. */115const red = draftOf("expect(parse('2026-W41').week).toBe(41);");116117/** A draft of an ask the project's rules do not state. */118const unstated = draftOf(119 "expect(parse('2026-W41').week).toBe(41);",120 "parse-month"121);122123/** carol proposes the want with a draft, on datekit's first push. */124const proposed = Effect.gen(function* () {125 yield* advanceTo("2026-10-08T12:00:00Z");126127 const api = yield* Projects.use((each) => each.create(project)).pipe(128 Effect.orDie129 );130131 yield* api.initProject(alice, {}).pipe(Effect.orDie);132133 const first = yield* Pusher.use((each) =>134 each.push(repo, Option.none(), start)135 );136137 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);138139 // The project's first proposal: `proposal`.140 yield* api141 .proposeAsk(carol, { draft: true, territory: "src/parse.ts", want })142 .pipe(Effect.orDie);143144 return { api, main: LandedSha.make(first) };145});146147/** `drafted`'s files composed onto `main`, its check scripted to end `runs` there. */148const scripted = (149 main: LandedSha,150 drafted: DraftedAsk,151 result: "passed" | "failed"152) =>153 Effect.gen(function* () {154 const { commit } = yield* Lander.use((lander) =>155 lander.compose({ files: draftedFiles(drafted), main, repo })156 ).pipe(Effect.orDie);157158 yield* Checker.use((script) =>159 script.script(CheckAt.cases.Commit.make({ commit }), redThenGreen, [160 result === "passed"161 ? { result }162 : { result, signature: "redThenGreen: expected 41, got undefined" },163 ])164 );165 });166167/** The proposal's draft state, as anyone reads it. */168const draftOfProposal = (api: ProjectApi) =>169 Effect.map(170 Effect.orDie(api.showProposal(Anonymous.make({}), proposal)),171 ({ proposal: shown }) => shown.draft172 );173174/** alice's open-proposal decisions on Today. */175const proposalDecisions = (api: ProjectApi) =>176 Effect.map(Effect.orDie(api.today(alice)), ({ decisions }) =>177 decisions.filter(({ subject }) =>178 DecisionSubject.guards.OpenProposal(subject)179 )180 );181182const asked = DraftsAsked.use(({ inputs }) => inputs);183184/** The world, the memory drafter scripted with `script`, and the platform's model. */185const worldDrafting = (script: Parameters<typeof DrafterMemory>[0]) =>186 Layer.mergeAll(187 worldWith(policy),188 DrafterMemory(script),189 Layer.succeed(DraftModel, model)190 );191192describe("a draft's run, over steps that replay", () => {193 it.effect(194 "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",195 () =>196 Effect.gen(function* () {197 const { api, main } = yield* proposed;198199 yield* scripted(main, passing, "passed");200 yield* scripted(main, red, "failed");201202 const steps = yield* memoSteps();203204 yield* draftSteps(params).pipe(Effect.provide(steps));205206 const inputs = yield* asked;207 const decisions = yield* proposalDecisions(api);208209 expect({210 attempts: inputs.map(({ attempt }) => attempt),211 decisions: decisions.length,212 draft: yield* draftOfProposal(api),213 firstFeedback: inputs[0]?.feedback,214 redFirst: decisions[0]?.evidence.find(215 ({ label }) => label === "red first"216 )?.value,217 refusedWith: inputs[1]?.feedback?.split("\n")[0]?.split(":")[0],218 }).toStrictEqual({219 attempts: [1, 2],220 decisions: 1,221 draft: DraftState.cases.Ready.make({222 attempts: 2,223 model,224 red: {225 lane: redThenGreen,226 signature: "redThenGreen: expected 41, got undefined",227 },228 round: 1,229 }),230 firstFeedback: undefined,231 redFirst: `${redThenGreen}: redThenGreen: expected 41, got undefined`,232 refusedWith: "NotRedFirst",233 });234235 // The finished instance, run again: every step reads its record.236 yield* draftSteps(params).pipe(Effect.provide(steps));237238 expect({239 asked: (yield* asked).length,240 decisions: (yield* proposalDecisions(api)).length,241 }).toStrictEqual({ asked: 2, decisions: 1 });242 }).pipe(Effect.provide(worldDrafting([passing, red])))243 );244245 it.effect(246 "settles Failed with the last refusal's tag once three attempts are refused",247 () =>248 Effect.gen(function* () {249 const { api, main } = yield* proposed;250251 yield* scripted(main, passing, "passed");252 yield* scripted(main, passingToo, "passed");253254 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));255256 expect({257 asked: (yield* asked).length,258 decisions: (yield* proposalDecisions(api)).length,259 draft: yield* draftOfProposal(api),260 }).toStrictEqual({261 asked: 3,262 decisions: 1,263 draft: DraftState.cases.Failed.make({264 attempts: 3,265 model,266 refusal: "IncompleteBrief",267 round: 1,268 }),269 });270 }).pipe(Effect.provide(worldDrafting([passing, passingToo, unstated])))271 );272273 it.effect(274 "retries a rate-limited model as a step, without spending an attempt",275 () =>276 Effect.gen(function* () {277 const { api, main } = yield* proposed;278279 yield* scripted(main, red, "failed");280281 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));282283 expect({284 asked: (yield* asked).map(({ attempt }) => attempt),285 draft: yield* draftOfProposal(api),286 }).toStrictEqual({287 asked: [1, 1],288 draft: DraftState.cases.Ready.make({289 attempts: 1,290 model,291 red: {292 lane: redThenGreen,293 signature: "redThenGreen: expected 41, got undefined",294 },295 round: 1,296 }),297 });298 }).pipe(299 Effect.provide(300 worldDrafting([new DraftFailed({ reason: "rate-limited" }), red])301 )302 )303 );304305 it.effect(306 "spends the attempt of a model still rate-limited once its step's retries are spent, and a replay ends the same way",307 () =>308 Effect.gen(function* () {309 const { api, main } = yield* proposed;310311 yield* scripted(main, red, "failed");312313 const steps = yield* memoSteps();314315 yield* draftSteps(params).pipe(Effect.provide(steps));316317 const settled = {318 asked: (yield* asked).map(({ attempt }) => attempt),319 draft: yield* draftOfProposal(api),320 feedback: (yield* asked)[5]?.feedback,321 };322323 // The finished instance, run again: `draft-1` is thrown again,324 // unrun, and its `gave-up` record says what the first run made of it.325 yield* draftSteps(params).pipe(Effect.provide(steps));326327 expect({328 replayed: {329 asked: (yield* asked).length,330 draft: yield* draftOfProposal(api),331 },332 settled,333 }).toStrictEqual({334 replayed: { asked: 6, draft: settled.draft },335 settled: {336 asked: [1, 1, 1, 1, 1, 2],337 draft: DraftState.cases.Ready.make({338 attempts: 2,339 model,340 red: {341 lane: redThenGreen,342 signature: "redThenGreen: expected 41, got undefined",343 },344 round: 1,345 }),346 feedback:347 "Your reply gave no draft (rate-limited): answer with one JSON object that matches the schema, and nothing else.",348 },349 });350 }).pipe(351 Effect.provide(352 worldDrafting([353 ...Array.replicate(new DraftFailed({ reason: "rate-limited" }), 5),354 red,355 ])356 )357 )358 );359360 it.effect(361 "tells the next attempt the model erred, not that it was rate-limited, when the drafter dies",362 () =>363 Effect.gen(function* () {364 const { api } = yield* proposed;365366 yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));367368 const inputs = yield* asked;369370 expect({371 asked: inputs.map(({ attempt }) => attempt),372 draft: yield* draftOfProposal(api),373 feedback: inputs[1]?.feedback,374 }).toStrictEqual({375 asked: [1, 2, 3],376 draft: DraftState.cases.Failed.make({377 attempts: 3,378 model,379 refusal: "IncompleteBrief",380 round: 1,381 }),382 feedback:383 "Your reply gave no draft (model-error): answer with one JSON object that matches the schema, and nothing else.",384 });385 }).pipe(Effect.provide(worldDrafting([])))386 );387388 it.effect(389 "ends the round Failed with VerifierBlocked, asking no other draft, when the Checker stays blocked past the rehearsal's retries",390 () =>391 Effect.gen(function* () {392 const { api } = yield* proposed;393394 // Nothing scripted for the draft's commit: the Checker cannot run it.395 const steps = yield* memoSteps();396397 yield* draftSteps(params).pipe(Effect.provide(steps));398 yield* draftSteps(params).pipe(Effect.provide(steps));399400 expect({401 asked: (yield* asked).length,402 decisions: (yield* proposalDecisions(api)).length,403 draft: yield* draftOfProposal(api),404 }).toStrictEqual({405 asked: 1,406 decisions: 1,407 draft: DraftState.cases.Failed.make({408 attempts: 1,409 model,410 refusal: "VerifierBlocked",411 round: 1,412 }),413 });414 }).pipe(Effect.provide(worldDrafting([red])))415 );416417 it.effect(418 "stops after its context when the proposal is gone: no attempt, no settling",419 () =>420 Effect.gen(function* () {421 yield* proposed;422423 const names = yield* Ref.make<readonly string[]>([]);424425 const memo = Context.get(426 yield* Layer.build(yield* memoSteps()),427 StepRunner428 );429430 const logged = StepRunner.of({431 step: (name, schema, effect, retry?: StepRetry) =>432 Effect.andThen(433 Ref.update(names, (all) => [...all, name]),434 memo.step(name, schema, effect, retry)435 ),436 });437438 yield* draftSteps(439 DraftParams.make({440 project,441 proposal: ProposalId.make("prop-000009"),442 round: 1,443 })444 ).pipe(Effect.provideService(StepRunner, logged));445446 expect({447 asked: (yield* asked).length,448 names: yield* Ref.get(names),449 }).toStrictEqual({ asked: 0, names: ["context"] });450 }).pipe(Effect.provide(worldDrafting([])))451 );452});453454/** A fake `ANSWER` binding: each instance made and restarted, every instance in `status`. */455const fakeWorkflow = (status: InstanceStatus["status"]) => {456 const made: string[] = [];457 const restarted: string[] = [];458459 const workflow: DraftWorkflow = {460 create: ({ id }) => {461 if (made.includes(id)) {462 return Promise.reject(new Error(`instance ${id} already exists`));463 }464465 made.push(id);466467 return Promise.resolve({ id });468 },469 get: (id) =>470 Promise.resolve({471 id,472 restart: () => {473 restarted.push(id);474475 return Promise.resolve();476 },477 status: () => Promise.resolve({ status }),478 }),479 };480481 return { made, restarted, workflow };482};483484describe("the Workflow's draft runs", () => {485 it.effect(486 "starts one instance per round: a second start finds it, and a run still going is left alone",487 () =>488 Effect.gen(function* () {489 const fake = fakeWorkflow("running");490491 const starting = DraftRuns.pipe(492 Effect.flatMap((runs) =>493 runs.start({ note: "keep it small", project, proposal, round: 1 })494 ),495 Effect.provide(DraftRunsWorkflow(fake.workflow))496 );497498 yield* starting;499 yield* starting;500501 expect({502 made: fake.made,503 restarted: fake.restarted,504 }).toStrictEqual({505 made: [`draft-${project}-${proposal}-r1`],506 restarted: [],507 });508509 expect(draftId(params)).toBe(`draft-${project}-${proposal}-r1`);510 })511 );512513 it("keeps every round of a long-named project's proposals its own instance, within the engine's 100 characters", () => {514 const long = ProjectName.make(`${"a-long-project-name".repeat(6)}x`);515 const longToo = ProjectName.make(`${"a-long-project-name".repeat(6)}y`);516 const other = ProposalId.make("prop-000002");517518 const rounds = [519 { project: long, proposal, round: 1 },520 { project: long, proposal, round: 2 },521 { project: long, proposal: other, round: 1 },522 { project: longToo, proposal, round: 1 },523 ];524525 const ids = rounds.map(draftId);526527 expect({528 distinct: new Set(ids).size,529 fit: ids.every(530 (id) => id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u.test(id)531 ),532 named: rounds.every((round, at) =>533 (ids[at] ?? "").endsWith(`-${round.proposal}-r${round.round}`)534 ),535 }).toStrictEqual({ distinct: 4, fit: true, named: true });536 });537538 it.effect(539 "starts an errored round's instance again, and never a complete one, which would ask the model again",540 () =>541 Effect.gen(function* () {542 const errored = fakeWorkflow("errored");543 const complete = fakeWorkflow("complete");544545 const twice = (workflow: DraftWorkflow) =>546 DraftRuns.pipe(547 Effect.flatMap((runs) =>548 Effect.andThen(549 runs.start({ project, proposal, round: 1 }),550 runs.start({ project, proposal, round: 1 })551 )552 ),553 Effect.provide(DraftRunsWorkflow(workflow))554 );555556 yield* twice(errored.workflow);557 yield* twice(complete.workflow);558559 expect({560 complete: complete.restarted,561 errored: errored.restarted,562 }).toStrictEqual({563 complete: [],564 errored: [`draft-${project}-${proposal}-r1`],565 });566 })567 );568569 it.effect(570 "gives the engine a 10-minute timeout on each step, and the rate-limit retries on the model's",571 () =>572 Effect.gen(function* () {573 const { main } = yield* proposed;574575 yield* scripted(main, red, "failed");576577 const configs: (readonly [string, EngineConfig])[] = [];578 const kept = new Map<string, Schema.Json>();579580 const engine: EngineSteps = {581 do: (name, config, body) => {582 configs.push([name, config]);583584 const found = kept.get(name);585586 return found === undefined587 ? body().then((value) => {588 kept.set(name, value);589590 return value;591 })592 : Promise.resolve(found);593 },594 };595596 const ports = yield* Effect.context<Projects | Drafter | RepoHost>();597598 const payload = yield* Schema.encodeEffect(DraftParams)(params);599600 yield* Effect.promise(() =>601 runDraftWorkflow(Layer.succeedContext(ports), payload, engine)602 );603604 expect(configs.map(([name]) => name)).toStrictEqual([605 "context",606 "draft-1",607 "rehearse-1",608 "settle",609 ]);610611 expect({612 draft: new Map(configs).get("draft-1"),613 rehearse: new Map(configs).get("rehearse-1"),614 }).toStrictEqual({615 draft: {616 retries: { backoff: "exponential", delay: 15_000, limit: 4 },617 timeout: "10 minutes",618 },619 rehearse: {620 retries: { backoff: "exponential", delay: 60_000, limit: 3 },621 timeout: "10 minutes",622 },623 });624625 expect(626 configs.filter(([, config]) => config.timeout !== "10 minutes")627 ).toStrictEqual([]);628 }).pipe(Effect.provide(worldDrafting([red])))629 );630631 it("takes the Worker's bindings as the generated Env types them", () => {632 expectTypeOf<Env["ANSWER"]>().toExtend<633 Parameters<typeof DraftRunsWorkflow>[0]634 >();635 expectTypeOf<PlatformConfig["AI"]>().toExtend<AiLike>();636 });637});638639describe("proposing with a draft", () => {640 it.effect(641 "spends the person's draft limit first: past it, CapReached, while a proposal without a draft still goes through",642 () =>643 Effect.gen(function* () {644 yield* advanceTo("2026-10-08T12:00:00Z");645 yield* seeded(scenario);646647 const asCarol = yield* as("carol");648649 const drafted = yield* asCarol.proposeAsk({650 draft: true,651 project,652 want,653 });654655 const past = yield* Effect.flip(656 asCarol.proposeAsk({ draft: true, project, want })657 );658659 const plain = yield* asCarol.proposeAsk({ project, want });660661 expect({662 drafted: drafted.proposal.draft?._tag,663 past,664 plain: plain.proposal.draft,665 }).toStrictEqual({666 drafted: "Drafting",667 past: new CapReached({ cap: 1 }),668 plain: undefined,669 });670 }).pipe(671 Effect.provide(672 Handlers.pipe(673 Layer.provideMerge(674 worldOf([scenario], {675 limits: { claim: 5, draft: 1, proposal: 5 },676 })677 )678 )679 )680 )681 );682});
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+369 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 // A model still rate-limited once the retries are spent, or a250 // drafter that died: either way a spent attempt, said as it was.251 Effect.catchCause((cause) =>252 step(253 `draft-${attempt}:gave-up`,254 Attempted,255 Effect.succeed(256 Attempted.cases.Spent.make({257 reason: Option.match(Cause.findErrorOption(cause), {258 onNone: () => "model-error" as const,259 onSome: ({ reason }) => reason,260 }),261 })262 )263 )264 )265 );266267 if (Attempted.guards.Spent(tried)) {268 feedback = Option.some(spentText(tried.reason));269 last = noDraft(tried.reason);270271 continue;272 }273274 const { drafted } = tried;275 const files = draftedFiles(drafted);276277 // A Checker still blocked (or a main still moving) once the278 // retries are spent ends the round: another draft would not help.279 const gaveUp = (cause: Cause.Cause<Refusal>) =>280 step(281 `rehearse-${attempt}:gave-up`,282 Rehearsal,283 Effect.succeed(284 Rehearsal.cases.Refused.make({285 diagnosis: "Blocked",286 excerpt: "",287 refusal: Option.getOrElse(288 Cause.findErrorOption(cause),289 (): Refusal => new VerifierBlocked({})290 ),291 })292 )293 ).pipe(Effect.map((rehearsal) => ({ blocked: true, rehearsal })));294295 const rehearsed = yield* step(296 `rehearse-${attempt}`,297 Rehearsal,298 Effect.flatMap(project, (api) => api.rehearseOpen(files)).pipe(299 Effect.catchTag("UnknownProject", () =>300 Effect.fail(new VerifierBlocked({}))301 )302 ),303 blockedRetry304 ).pipe(305 Effect.map((rehearsal) => ({ blocked: false, rehearsal })),306 Effect.catchCause(gaveUp)307 );308309 if (Rehearsal.guards.Red(rehearsed.rehearsal)) {310 return DraftResult.cases.Red.make({311 attempts: attempt,312 files,313 lane: rehearsed.rehearsal.lane,314 model,315 rationale: drafted.rationale,316 signature: rehearsed.rehearsal.signature,317 });318 }319320 const refused = rehearsed.rehearsal;321322 last = refused.refusal;323324 if (rehearsed.blocked) {325 return DraftResult.cases.Failed.make({326 attempts: attempt,327 model,328 refusal: last,329 });330 }331332 feedback = Option.some(333 feedbackText({334 diagnosis: refused.diagnosis,335 excerpt: refused.excerpt,336 refusal: refused.refusal,337 })338 );339 }340341 return DraftResult.cases.Failed.make({342 attempts: DRAFT_ROUNDS,343 model,344 refusal: last,345 });346 });347348 const result: Option.Option<DraftResult> = yield* Prepared.match(prepared, {349 Gone: () => Effect.succeedNone,350 NoFix: () =>351 Effect.succeedSome(352 DraftResult.cases.Failed.make({353 attempts: 1,354 model,355 refusal: new IncompleteBrief({ missing: ["kinds.fix"] }),356 })357 ),358 Ready: (ready) => Effect.asSome(attempts(ready)),359 });360361 if (Option.isSome(result)) {362 yield* settle(result.value);363 }364 }).pipe(365 Effect.annotateLogs({366 proposal: params.proposal,367 round: String(params.round),368 })369 );
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