Skip to content
Myr

Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI binding

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

- Protocol: ten contracts (listRefs, readTree, listPaths, readFile, log, showCommit, why on rpc and web only; projectPolicy, showProposal, draftAsk on every surface), domain/code.ts, PublicPolicy (Policy minus asks, functions, visibility), DraftState and Proposal.draft, ProposalDrafted, proposeAsk's draft flag with a check that a drafted proposal carries no files or sealed answer. Five refusals: UnknownPath, UnknownRevision, UnknownProposal, ProposalClosed, DraftInProgress. UnknownPath names its commit as `commit`, since `at` is every refusal's line pointer. - A `true`-or-absent payload field is a bare CLI switch, so `propose --draft` reads as one; `policy`, `proposal` and `ask draft` derive from the contracts. - RepoHost: Commit carries authoredAt/committedAt (Unix seconds) in every adapter and both fakes; log takes an optional offset; `tags` lists every refs/tags/* peeled to its commit (smart HTTP's peeled lines, or isomorphic-git's readCommit peel). The isomorphic-git stores now copy an annotated tag object on push. `refs` is unchanged. - Project: ProjectApi gains head, landings, forks (claim forks; the DO records no working forks) and policy, built; draftAsk, showProposal and proposeAsk's draft branch die "not built" until drafting lands. repo-names moves into @repo/project (the platform re-exports it). The code facade (@repo/project/code) has its final signatures with stub bodies; CodeCache is a Context.Reference that caches nothing by default. - Platform: both handler files serve every new contract through the facade or ProjectApi; draftAsk spends a new "draft" rate limit. `GET /` and `GET /:project/raw/*` reach stubs answering 501, both exempt from the 401. HostInfo (web URL, draft model) lives in host-info.ts, re-exported by surfaces.ts, so home.ts and surfaces.ts make no import cycle. - Wrangler: the `ai` binding, DRAFT_LIMIT (2 a minute; ids 1004/1104/1204), DRAFT_MODEL and PUBLIC_WEB_URL in all three blocks; types regenerated; the env decodes them. Local PUBLIC_WEB_URL is Vite's default port, 5173 (ASSUMPTION: apps/web sets no other). - packages/drafting skeleton: DraftedAsk, DraftContext, DraftInput, DraftFailed, the Drafter port and a scripted memory adapter, with its full dependency list so later work edits no lockfile. - Byte limits per Worker. Measured: platform entry 1,617,480 of 1,900,000; sandbox 570,420 of 1,665,000; web entry 717,922 of 1,665,000 and JavaScript 2,394,604 of 2,500,000. - import-examples: a root script whose entry says it is not built yet and exits 1, its tsconfig allowances, and its AGENTS.md line. - Tests: w9-contracts (policy over /rpc, code reads reach the facade, draft needs a person, / and raw slots open to a stale bearer), bindings (AI, DRAFT_LIMIT, vars per block), do-reads, code-facade, the RepoHost contract's commit times, log offset and peeled tags on every adapter, refusal and render rows, the contracts table and fixtures, the CLI switch, per-Worker budgets, the import-examples entry. - agent-kit's refusal guidance is unchanged: it covers answer refusals only, and the new ones file under Decision and Lookup.

authored by oscabriel · committed by oscabriel · parent 235ff53 · Browse files · 78 files+2827 added−179 removed
This commit

State

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

Diff stats

78 files+2827 added−179 removed

  • tests:+1045 added−38 removed
  • other:+1782 added−141 removed

78 files+2827 added−179 removed

This commit is too large to show whole: its files are listed by path, without their changes.

modified:apps/cli/test/surfaces.test.ts+2 added-2 removed
206 unmodified lines
207 ])208 );209 });210211 it("puts ask open and ask flag under ask, and env shape beside env set", () => {212 expect(subcommandsOf(top("ask"))).toStrictEqual(["open", "flag"]);211 it("puts ask open, ask draft and ask flag under ask, and env shape beside env set", () => {212 expect(subcommandsOf(top("ask"))).toStrictEqual(["open", "draft", "flag"]);213 expect(subcommandsOf(top("env"))).toStrictEqual(["shape", "set"]);214 });215216 it("leaves init and env set to their local commands", () => {
415 unmodified lines
modified:apps/platform/src/adapters/do-projects.ts+7 added
89 unmodified lines
90 answer: (requestId) => on("answer", [requestId]),91 claim: (caller, ask) => assumingMade(on("claim", [caller, ask])),92 credits: (caller, handle) => on("credits", [caller, handle]),93 decide: (caller, input) => assumingMade(on("decide", [caller, input])),94 draftAsk: (caller, input) => assumingMade(on("draftAsk", [caller, input])),95 events: (since, limit) => on("events", [since, limit]),96 // A name pointing at another project is the service's own97 // `UnknownProject`, so it crosses as the refusal it is.98 evidence: (caller, ref) => on("evidence", [caller, ref]),99 finish: (caller, input) => assumingMade(on("finish", [caller, input])),100 firstPusher: () => on("firstPusher", []),101 flagAsk: (caller, input) => assumingMade(on("flagAsk", [caller, input])),102 fork: (caller) => assumingMade(on("fork", [caller])),103 forks: () => on("forks", []),104 head: () => on("head", []),105 heldBackJob: (requestId) => on("heldBackJob", [requestId]),106 initProject: (caller, input) => on("initProject", [caller, input]),107 land: (caller, input) => assumingMade(on("land", [caller, input])),108 landing: (caller, sha) => assumingMade(on("landing", [caller, sha])),109 landings: (shas) => on("landings", [shas]),110 layerAccess: (caller, layer) => on("layerAccess", [caller, layer]),111 layerFacts: (caller) => on("layerFacts", [caller]),112 ledger: (caller) => assumingMade(on("ledger", [caller])),113 listAsks: (caller) => assumingMade(on("listAsks", [caller])),114 onAlarm: () => on("onAlarm", []),115 openAsk: (caller, input) => assumingMade(on("openAsk", [caller, input])),116 policy: () => on("policy", []),117 proposeAsk: (caller, input) =>118 assumingMade(on("proposeAsk", [caller, input])),119 recordAdmission: (input) => on("recordAdmission", [input]),120 recordFirstPush: (caller, head) => on("recordFirstPush", [caller, head]),
5 unmodified lines
126 release: (caller, ask) => assumingMade(on("release", [caller, ask])),127 scanForValues: (input) => on("scanForValues", [input]),128 setEnv: (caller, input) => assumingMade(on("setEnv", [caller, input])),129 showAsk: (caller, ask) => assumingMade(on("showAsk", [caller, ask])),130 showProposal: (caller, proposal) =>131 assumingMade(on("showProposal", [caller, proposal])),132 status: (caller) => assumingMade(on("status", [caller])),133 submitAnswer: (caller, input) =>134 assumingMade(on("submitAnswer", [caller, input])),135 today: (caller) => assumingMade(on("today", [caller])),
50 unmodified lines
modified:apps/platform/src/adapters/rate-limits.ts+9 added-2 removed
13 unmodified lines
1415/** How many of each kind one person may make. */16export interface Limits {17 readonly claim: number;18 readonly draft: number;19 readonly proposal: number;20}2122/**23 * What `wrangler.jsonc` lets each binding admit per person, every 60 s, in23 * every stage: `CLAIM_LIMIT` and `PROPOSAL_LIMIT`'s `simple.limit`. A binding24 * every stage: `CLAIM_LIMIT`, `DRAFT_LIMIT` and `PROPOSAL_LIMIT`'s25 * `simple.limit`. A binding26 * can't say its own limit, so a refusal reads its cap here.27 */26export const WorkerCaps = { claim: 10, proposal: 5 } as const satisfies Limits;28export const WorkerCaps = {29 claim: 10,30 draft: 2,31 proposal: 5,32} as const satisfies Limits;3334/** A refusal for one more of `kind` than `limits` allow. */35const capped = (limits: Limits, kind: Limited) =>36 new CapReached({ cap: limits[kind] });
3 unmodified lines
40 * defect: a call it could not count is not let through.41 */42export const WorkerRateLimits = (bindings: {43 readonly claim: RateLimit;44 readonly draft: RateLimit;45 readonly proposal: RateLimit;46}): Layer.Layer<RateLimits> =>47 Layer.succeed(48 RateLimits,
42 unmodified lines
modified:apps/platform/src/handlers.ts+75 added-2 removed
6 unmodified lines
7 * `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.10 * `evidence` asks the project who may read a lane's log, which it reads11 * from the stage's `EvidenceStore`. `watch` is served by `watch.ts`: live11 * from the stage's `EvidenceStore`. The code reads (`listRefs`, `readTree`,12 * `listPaths`, `readFile`, `log`, `showCommit`, `why`) run here, over the13 * Worker's `RepoHost` and the project's canonical repo (`@repo/project/code`),14 * asking the project only for main's landed commit, its landings and forks. `watch` is served by `watch.ts`: live15 * for a caller on the framed `/rpc`, replayed and ended over JSON.16 *17 * Every `remote` a caller gets back is the platform's git URL for the repo,18 * at the origin the caller reached the platform by: never a storage URL.19 */20import { RepoHost } from "@repo/artifacts/repo-host";21import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";22import {23 codeProjectOf,24 commitOf,25 fileOf,26 logOf,27 pathsOf,28 refsOf,29 treeOf,30 whyOf,31} from "@repo/project/code";32import type { CodeProject } from "@repo/project/code";33import { envSchemaMethod } from "@repo/project/deciders";34import { FrontPage } from "@repo/project/front-page";35import { GatewayUrl } from "@repo/project/project";36import type { ProjectApi } from "@repo/project/project";
14 unmodified lines
5152import { RateLimits } from "./rate-limits.ts";53import { servedFramed, watchHandler } from "./watch.ts";5455/** How many commits a page of `log` holds when the caller names no limit. */56const LOG_PAGE = 30;5758/** How many projects a call without one asks at once. */59const FAN_OUT = 8;6061/** The caller, as the `Authenticated` server side named them. */
111 unmodified lines
173 */174export const Handlers: Layer.Layer<175 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,176 never,159 Projects | FrontPage | RateLimits | EvidenceStore177 Projects | FrontPage | RateLimits | EvidenceStore | RepoHost178> = Contracts.toLayer(179 Effect.gen(function* () {180 const projects = yield* Projects;181 const frontPage = yield* FrontPage;182 const rateLimits = yield* RateLimits;183 const evidence = yield* EvidenceStore;184 const host = yield* RepoHost;185186 /** `call` on the project named `project`; one never made is `UnknownProject`. */187 const on = <A, E>(188 project: ProjectName,189 call: (api: ProjectApi) => Effect.Effect<A, E>190 ) => Effect.flatMap(projects.get(project), call);191192 /** A code read of `project`'s canonical repo, over the Worker's `RepoHost`. */193 const code = <A, E>(194 project: ProjectName,195 read: (of: CodeProject) => Effect.Effect<A, E, RepoHost>196 ) =>197 on(project, (api) =>198 read(codeProjectOf(api, project)).pipe(199 Effect.provideService(RepoHost, host)200 )201 );202203 /**204 * `call` on every project the projection lists, in name order. A205 * project the platform never made adds nothing, and so does one where206 * `call` finds nothing for the caller; any other failure is the call's.
38 unmodified lines
245 decide: ({ project, ...input }) =>246 Effect.flatMap(person, (who) =>247 on(project, (api) => api.decide(who, input))248 ),249 draftAsk: ({ project, ...input }) =>250 Effect.gen(function* () {251 const who = yield* person;252253 yield* rateLimits.check("draft", who.handle);254255 return yield* on(project, (api) => api.draftAsk(who, input));256 }),257 evidence: ({ project, ref }) =>258 Effect.flatMap(person, (who) =>259 on(project, (api) =>260 api
57 unmodified lines
318 listAsks: ({ project }) =>319 Effect.flatMap(caller, (who) =>320 on(project, (api) => api.listAsks(who))321 ),322 listPaths: ({ at, project }) =>323 code(project, (of) => pathsOf(of, Option.fromUndefinedOr(at))),324 listProjects: () =>325 Effect.map(frontPage.projects(), (listed) => ({ projects: listed })),326 listRefs: ({ project }) => code(project, refsOf),327 log: ({ at, from = 0, limit = LOG_PAGE, path, project }) =>328 code(project, (of) =>329 logOf(of, {330 at: Option.fromUndefinedOr(at),331 from,332 limit,333 path: Option.fromUndefinedOr(path),334 })335 ),336 openAsk: ({ project, ...input }) =>337 Effect.flatMap(person, (who) =>338 on(project, (api) => api.openAsk(who, input))339 ),340 projectPolicy: ({ project }) =>341 on(project, (api) =>342 Effect.map(api.policy(), (policy) =>343 Option.match(policy, {344 onNone: () => ({}),345 onSome: (evaluated) => ({ policy: evaluated }),346 })347 )348 ),349 proposeAsk: ({ project, ...input }) =>350 Effect.gen(function* () {351 const who = yield* person;352353 yield* rateLimits.check("proposal", who.handle);354355 return yield* on(project, (api) => api.proposeAsk(who, input));356 }),357 readFile: ({ at, path, project }) =>358 code(project, (of) => fileOf(of, Option.fromUndefinedOr(at), path)),359 readTree: ({ at, path, project }) =>360 code(project, (of) =>361 treeOf(of, Option.fromUndefinedOr(at), Option.fromUndefinedOr(path))362 ),363 release: ({ ask, project }) =>364 Effect.flatMap(person, (who) =>365 on(project, (api) => api.release(who, ask))366 ),
4 unmodified lines
371 showAsk: ({ ask, project }) =>372 Effect.flatMap(caller, (who) =>373 on(project, (api) => api.showAsk(who, ask))374 ),375 showCommit: ({ project, sha }) =>376 code(project, (of) => commitOf(of, sha)),377 showProposal: ({ project, proposal }) =>378 Effect.flatMap(caller, (who) =>379 on(project, (api) => api.showProposal(who, proposal))380 ),381 status: ({ project }) =>382 Effect.gen(function* () {383 const who = yield* person;384
47 unmodified lines
432 watch: (payload) =>433 Stream.unwrap(434 Effect.map(servedFramed, (live) => watchHandler(payload, { live }))435 ).pipe(Stream.provideService(Projects, projects)),436 why: ({ at, path, project }) =>437 code(project, (of) => whyOf(of, Option.fromUndefinedOr(at), path)),438 };439 })440);
added:apps/platform/src/home.ts+21 added
1/**2 * The platform's `/`: a page saying what this host serves (clone URLs, MCP,3 * agent skills, sign-in, the CLI and its releases, the web app), in HTML4 * for a browser and in Markdown for an agent. A stub until 906 lands: it5 * answers 501, naming what it read.6 */7import type { FrontPage } from "@repo/project/front-page";8import { Effect } from "effect";910import { HostInfo } from "./host-info.ts";1112export const homeResponse = (13 _request: Request14): Effect.Effect<Response, never, FrontPage | HostInfo> =>15 Effect.map(16 Effect.service(HostInfo),17 ({ draftModel }) =>18 new Response(`not built: 906 (draft model ${draftModel})`, {19 status: 501,20 })21 );
added:apps/platform/src/host-info.ts+16 added
1/**2 * What the platform's `/` says of its host beyond the request: where the3 * web app lives (`PUBLIC_WEB_URL`, none on a stage without one) and the4 * model that drafts asks (`DRAFT_MODEL`). `platformOn` provides it from5 * the decoded env; `surfaces.ts` re-exports it with the other services.6 */7import { Context } from "effect";8import type { Option } from "effect";910export class HostInfo extends Context.Service<11 HostInfo,12 {13 readonly webUrl: Option.Option<string>;14 readonly draftModel: string;15 }16>()("platform/HostInfo") {}
modified:apps/platform/src/platform.ts+20 added-3 removed
19 unmodified lines
20import { ReleaseStoreBinding } from "./releases/binding.ts";21import { Sessions } from "./sessions.ts";22import { firstOf } from "./sessions/first-of.ts";23import { sessionTable } from "./sessions/table.ts";24import { Stage } from "./surfaces.ts";24import { HostInfo, Stage } from "./surfaces.ts";25import type { Services } from "./surfaces.ts";2627/**28 * A binding the runtime hands the Worker: present, and an object. The
36 unmodified lines
65 * typed by the generated `Env`, so a binding removed from `wrangler.jsonc`66 * fails `typecheck` here and wherever it is used.67 */68export const PlatformBindings = Schema.Struct({69 /** Workers AI, which drafts asks (`DRAFT_MODEL` names the model). */70 AI: binding<Env["AI"]>("Workers AI"),71 ANSWER: binding<Env["ANSWER"]>("the Answer Workflow"),72 ARTIFACTS: binding<Env["ARTIFACTS"]>("an Artifacts namespace"),73 /**74 * The private namespace that holds every project's layer repos. Only
3 unmodified lines
78 ARTIFACTS_PRIVATE: binding<Env["ARTIFACTS_PRIVATE"]>(79 "the private Artifacts namespace"80 ),81 CLAIM_LIMIT: binding<Env["CLAIM_LIMIT"]>("a rate limit"),82 DRAFT_LIMIT: binding<Env["DRAFT_LIMIT"]>("a rate limit"),83 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),84 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),85 LOADER: binding<Env["LOADER"]>("a Worker Loader"),86 OAUTH_KV: binding<Env["OAUTH_KV"]>("a KV namespace"),
14 unmodified lines
101});102103/** The vars `wrangler.jsonc` sets in every block. */104export const PlatformVars = Schema.Struct({105 /** The Workers AI model that drafts asks: `@cf/moonshotai/kimi-k2.7-code`. */106 DRAFT_MODEL: Schema.NonEmptyString,107 LANDER_ADAPTER: LanderAdapter.pipe(108 Schema.withDecodingDefaultKey(Effect.succeed("container"))109 ),110 OPERATOR_HANDLE: Handle,111 /** The web app's own URL, which `/` links to; a stage without one links nowhere. */112 PUBLIC_WEB_URL: Schema.optionalKey(113 Schema.String.check(Schema.isPattern(/^https?:\/\//u))114 ),115 STAGE: StageName,116});117118/**
118 unmodified lines
237 );238239/**240 * The surfaces' services over `ports`: every contract's handler, sessions,232 * the CLI's releases (over `RELEASES`) and the stage from the decoded env,241 * the CLI's releases (over `RELEASES`), the stage and what `/` says of the242 * host (the web's URL, the drafter's model) from the decoded env,243 * and the ports beside them (git's routes take the same `Projects` and244 * `Upstream` the handlers do). The Worker runs them over245 * `workerPorts(config)`; the core-loop test runs the same composition over246 * its own adapters of the same ports.
5 unmodified lines
252 Layer.mergeAll(253 Handlers,254 sessionsOf(config),255 ReleaseStoreBinding(config.RELEASES),246 Layer.succeed(Stage, Stage.of({ name: config.STAGE }))256 Layer.succeed(Stage, Stage.of({ name: config.STAGE })),257 Layer.succeed(258 HostInfo,259 HostInfo.of({260 draftModel: config.DRAFT_MODEL,261 webUrl: Option.fromUndefinedOr(config.PUBLIC_WEB_URL),262 })263 )264 ).pipe(Layer.provideMerge(ports));265266/**267 * The surfaces' services from the decoded env: every contract's handler,
8 unmodified lines
modified:apps/platform/src/ports.ts+1 added
122 unmodified lines
123 // entry it follows each project's event log instead.124 Layer.succeed(ProjectSockets, Option.some(config.PROJECT)),125 WorkerRateLimits({126 claim: config.CLAIM_LIMIT,127 draft: config.DRAFT_LIMIT,128 proposal: config.PROPOSAL_LIMIT,129 }),130 EvidenceStoreR2(config.EVIDENCE)131 ).pipe(
7 unmodified lines
modified:apps/platform/src/project-calls.ts+6 added
101 unmodified lines
102 claim: callOf(MethodSchemas.claim),103 credits: callOf(MethodSchemas.credits),104 [envSchemaMethod]: callOf(MethodSchemas[envSchemaMethod]),105 decide: callOf(MethodSchemas.decide),106 draftAsk: callOf(MethodSchemas.draftAsk),107 events: callOf(MethodSchemas.events),108 evidence: callOf(MethodSchemas.evidence),109 finish: callOf(MethodSchemas.finish),110 firstPusher: callOf(MethodSchemas.firstPusher),111 flagAsk: callOf(MethodSchemas.flagAsk),112 fork: callOf(MethodSchemas.fork),113 forks: callOf(MethodSchemas.forks),114 head: callOf(MethodSchemas.head),115 heldBackJob: callOf(MethodSchemas.heldBackJob),116 initProject: callOf(MethodSchemas.initProject),117 land: callOf(MethodSchemas.land),118 landing: callOf(MethodSchemas.landing),119 landings: callOf(MethodSchemas.landings),120 layerAccess: callOf(MethodSchemas.layerAccess),121 layerFacts: callOf(MethodSchemas.layerFacts),122 ledger: callOf(MethodSchemas.ledger),123 listAsks: callOf(MethodSchemas.listAsks),124 onAlarm: callOf(MethodSchemas.onAlarm),125 openAsk: callOf(MethodSchemas.openAsk),126 policy: callOf(MethodSchemas.policy),127 proposeAsk: callOf(MethodSchemas.proposeAsk),128 recordAdmission: callOf(MethodSchemas.recordAdmission),129 recordFirstPush: callOf(MethodSchemas.recordFirstPush),130 recordHeldBack: callOf(MethodSchemas.recordHeldBack),
3 unmodified lines
134 release: callOf(MethodSchemas.release),135 scanForValues: callOf(MethodSchemas.scanForValues),136 setEnv: callOf(MethodSchemas.setEnv),137 showAsk: callOf(MethodSchemas.showAsk),138 showProposal: callOf(MethodSchemas.showProposal),139 status: callOf(MethodSchemas.status),140 submitAnswer: callOf(MethodSchemas.submitAnswer),141 today: callOf(MethodSchemas.today),142 verdict: callOf(MethodSchemas.verdict),
66 unmodified lines
modified:apps/platform/src/rate-limits.ts+2 added-2 removed
10 unmodified lines
11import type { CapReached } from "@repo/protocol/refusal";12import { Context } from "effect";13import type { Effect } from "effect";1415/** What a rate limit counts: claims, or proposals (flags among them). */16export type Limited = "claim" | "proposal";15/** What a rate limit counts: claims, proposals (flags among them), or drafts. */16export type Limited = "claim" | "proposal" | "draft";1718export class RateLimits extends Context.Service<19 RateLimits,20 {
7 unmodified lines
added:apps/platform/src/raw.ts+17 added
1/**2 * A project's raw bytes: `GET /<project>/raw/<rev>/<path…>`, from its3 * canonical repo only, under a sandboxing CSP and `nosniff` so no file runs4 * as script on this origin. A stub until 903 lands: it answers 501.5 * `rest` is everything after `raw/`, undecoded: the revision and the path.6 */7import type { RepoHost } from "@repo/artifacts/repo-host";8import type { Projects } from "@repo/project/projects";9import type { ProjectName } from "@repo/protocol/ids";10import { Effect } from "effect";1112export const rawResponse = (13 _request: Request,14 _project: ProjectName,15 _rest: string16): Effect.Effect<Response, never, RepoHost | Projects> =>17 Effect.succeed(new Response("not built: 903", { status: 501 }));
modified:apps/platform/src/repo-names.ts+9 added-84 removed
1/**2 * What a repo's name says it is: a project's canonical repo3 * `<project>`, a claim's fork `<project>--<ask>--<handle>`, or a person's4 * working fork `<project>--me--<handle>`, each handle in lowercase. `--`5 * occurs in no project or ask name, so a name splits back into its parts.6 * Pure: the gateway, the handlers and OnPush read names7 * with it.2 * What a repo's name says it is, from `@repo/project/repo-names`, where3 * the project service lists its forks by it too: the gateway, the handlers4 * and OnPush read names from here.5 */9import { forkName } from "@repo/project/claim";10import { AskId, Handle, ProjectName, RepoName } from "@repo/protocol/ids";11import { Data, Option, Schema } from "effect";1213/** What a repo is, read from its name alone. */14export type RepoKind =15 | { readonly _tag: "Canonical"; readonly project: ProjectName }16 | {17 readonly _tag: "ClaimFork";18 readonly project: ProjectName;19 readonly ask: AskId;20 /** As the name spells it: in lowercase. */21 readonly handle: Handle;22 }23 | {24 readonly _tag: "WorkingFork";25 readonly project: ProjectName;26 /** As the name spells it: in lowercase. */27 readonly handle: Handle;28 }29 | { readonly _tag: "Unknown" };3031export const RepoKind = Data.taggedEnum<RepoKind>();3233const asProject = Schema.decodeOption(ProjectName);3435const asAsk = Schema.decodeOption(AskId);3637const asHandle = Schema.decodeOption(Handle);3839/** The word that names a working fork where a claim's fork names its ask. */40const WORKING = "me";4142/** What `name` says it is; `Unknown` for any name the platform never makes. */43export const repoKind = (name: RepoName): RepoKind => {44 const [first = "", second, third, ...rest] = name.split("--");4546 const kind = Option.flatMap(47 asProject(first),48 (project): Option.Option<RepoKind> => {49 if (second === undefined) {50 return Option.some(RepoKind.Canonical({ project }));51 }5253 if (third === undefined || rest.length > 0) {54 return Option.none();55 }5657 const handle = Option.filter(58 asHandle(third),59 (spelled) => spelled === spelled.toLowerCase()60 );6162 return second === WORKING63 ? Option.map(handle, (owner) =>64 RepoKind.WorkingFork({ handle: owner, project })65 )66 : Option.map(67 Option.all({ ask: asAsk(second), handle }),68 ({ ask, handle: claimant }) =>69 RepoKind.ClaimFork({ ask, handle: claimant, project })70 );71 }72 );7374 return Option.getOrElse(kind, () => RepoKind.Unknown());75};7677/** A claim's fork: `<project>--<ask>--<handle in lowercase>`. */78export const claimForkName: (79 project: ProjectName,80 ask: AskId,81 handle: Handle82) => RepoName = forkName;8384/** A person's working fork: `<project>--me--<handle in lowercase>`. */85export const workingForkName = (project: ProjectName, handle: Handle) =>86 RepoName.make(`${project}--${WORKING}--${handle.toLowerCase()}`);6export {7 claimForkName,8 repoKind,9 RepoKind,10 workingForkName,11} from "@repo/project/repo-names";
modified:apps/platform/src/surfaces.ts+81 added-7 removed
1import { commandDocs } from "@repo/agent-kit/command-doc";2import { platformSkill } from "@repo/agent-kit/platform";3import type { RepoHost } from "@repo/artifacts/repo-host";3import { RepoHost } from "@repo/artifacts/repo-host";4import { Brand } from "@repo/brand";5import { Upstream } from "@repo/git/upstream";6import type { FrontPage } from "@repo/project/front-page";6import { FrontPage } from "@repo/project/front-page";7import { Projects } from "@repo/project/projects";8import { authenticated, bearerToken } from "@repo/protocol/authenticate";9import { Client, Contracts, surfaced } from "@repo/protocol/contracts";10import { ProjectName } from "@repo/protocol/ids";11import { toToolkit } from "@repo/protocol/mcp";12import {13 briefResources,14 skillIn,15 skillPrompt,16} from "@repo/protocol/mcp-extras";17import { Authenticated } from "@repo/protocol/principal";18import type { Person } from "@repo/protocol/principal";18import { Context, Effect, Layer, Option } from "effect";19import { Context, Effect, Layer, Option, Schema } from "effect";20import { McpProtocol, McpServer } from "effect/ai";21import {22 Headers,23 HttpRouter,
9 unmodified lines
33} from "effect/rpc";3435import { serveGit } from "./git.ts";36import type { GitServices } from "./git.ts";37import { homeResponse } from "./home.ts";38import { HostInfo } from "./host-info.ts";39import { LayerGate } from "./layer-gate.ts";40import { rawResponse } from "./raw.ts";41import { releaseRoutes } from "./releases.ts";42import type { ReleaseStore } from "./releases.ts";43import { Sessions } from "./sessions.ts";44import { isFramed } from "./watch.ts";45import { agentSkillRoutes } from "./well-known.ts";4647/** What `/` says of the host: the web app's URL and the drafter's model. */48export { HostInfo } from "./host-info.ts";4950/** Which stage this Worker serves: `/health` says so. */51export class Stage extends Context.Service<Stage, { readonly name: string }>()(52 "platform/Stage"53) {}5455/**56 * What the surfaces need from the platform: the contracts' handlers,57 * sessions, what git's paths need, the CLI's releases, the front page and51 * the repos the projects' skills are read from, and the stage.58 * the repos the projects' skills and raw files are read from, the stage,59 * and what `/` says of the host.60 */61export type Services =62 | Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>63 | Sessions64 | GitServices65 | ReleaseStore66 | FrontPage67 | RepoHost60 | Stage;68 | Stage69 | HostInfo;7071/** git's smart-HTTP paths: `/<repo>(.git)/info/refs` and the two services. */72const GIT_PATH =73 /^\/[A-Za-z0-9._-]+\/(?:info\/refs|git-upload-pack|git-receive-pack)$/u;
11 unmodified lines
85 */86const SIGN_IN_PATH = /^\/(?:authorize|signup|token|oauth(?:\/.*)?)$/u;8788/**89 * A project's raw files, `/<project>/raw/<rev>/<path…>`: no git path, whose90 * second segment is `info` or a git service, ever matches it.91 */92const RAW_PATH = /^\/[a-z0-9]+(?:-[a-z0-9]+)*\/raw\/.+$/u;9394/**95 * The CLI's install script and releases (`releases.ts`):96 * `/install.sh`, `/releases/manifest.json` and `/releases/:version/:asset`.97 */98const RELEASE_PATH =
10 unmodified lines
109 * 401: `/health`; git's, whose gateway decides who may read and push (and110 * answers an unknown credential with its own 401); the paths that tell a111 * client how to sign in, or sign it in, which may carry a stale token or an112 * OAuth client's own credential; the CLI's downloads, which anyone may98 * fetch, with whatever credential an installer happens to carry; and the99 * projects' skills, which an agent fetches the same way.113 * fetch, with whatever credential an installer happens to carry; the114 * projects' skills, which an agent fetches the same way; the host's own115 * page, `/`; and a project's raw files, which a README's images name.116 */117const isExempt = (path: string) =>118 path === "/" ||119 path === "/health" ||120 RAW_PATH.test(path) ||121 GIT_PATH.test(path) ||122 DISCOVERY_PATH.test(path) ||123 SIGN_IN_PATH.test(path) ||124 RELEASE_PATH.test(path) ||
230 unmodified lines
355 );356 })357);358359/** A route that answers with a web `Response` from `respond`, given the web request. */360const fromWeb =361 <R>(respond: (web: Request) => Effect.Effect<Response, never, R>) =>362 (request: HttpServerRequest.HttpServerRequest) =>363 HttpServerRequest.toWeb(request).pipe(364 Effect.flatMap(respond),365 Effect.map(HttpServerResponse.fromWeb),366 Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 }))367 );368369/** `/`: what this host serves, for a browser and for an agent (`home.ts`). */370const home = HttpRouter.use((router) =>371 Effect.gen(function* () {372 const services = Context.make(FrontPage, yield* FrontPage).pipe(373 Context.add(HostInfo, yield* HostInfo)374 );375376 yield* router.add(377 "GET",378 "/",379 fromWeb((web) => Effect.provide(homeResponse(web), services))380 );381 })382);383384const decodeProject = Schema.decodeUnknownOption(ProjectName);385386/** `/<project>/raw/<rev>/<path…>`: a project's raw files (`raw.ts`). */387const raw = HttpRouter.use((router) =>388 Effect.gen(function* () {389 const services = Context.make(RepoHost, yield* RepoHost).pipe(390 Context.add(Projects, yield* Projects)391 );392393 yield* router.add("GET", "/:project/raw/*", (request) =>394 Effect.gen(function* () {395 const params = yield* HttpRouter.params;396397 return yield* Option.match(decodeProject(params.project), {398 onNone: () =>399 Effect.succeed(HttpServerResponse.empty({ status: 404 })),400 onSome: (project) =>401 fromWeb((web) =>402 Effect.provide(403 rawResponse(web, project, params["*"] ?? ""),404 services405 )406 )(request),407 });408 })409 );410 })411);412413/**414 * The protected-resource document (RFC 9728), answered to anyone: where a415 * client learns that the platform is its own authorization server. The416 * authorization server's document is the sign-in provider's, which answers
51 unmodified lines
468/** The platform's fetch handler over `services`. */469export const serve = <E>(services: Layer.Layer<Services, E>) =>470 HttpRouter.toWebHandler(471 Layer.mergeAll(472 home,473 health,474 discovery,475 raw,476 git,477 mcp,478 rpc,479 releaseRoutes,
5 unmodified lines
modified:apps/platform/test/bindings.test.ts+81 added
116 unmodified lines
117 * A key that is neither here nor in `NOT_BINDINGS` fails the test: whoever118 * adds it says which it is.119 */120const BindingKinds = Schema.Struct({121 ai: Schema.optionalKey(Schema.Struct({ binding: Schema.String })),122 artifacts: Schema.optionalKey(Bound),123 d1_databases: Schema.optionalKey(Bound),124 durable_objects: Schema.optionalKey(Schema.Struct({ bindings: Named })),125 kv_namespaces: Schema.optionalKey(Bound),
53 unmodified lines
179/** What one block declares: its bindings, vars and required secrets, each sorted, and any key this test does not know. */180const declaredIn = (raw: typeof Raw.Type) =>181 Effect.map(decodeBlock(raw), (block) => ({182 bindings: sorted([183 ...(block.ai === undefined ? [] : [block.ai.binding]),184 ...(block.artifacts ?? []).map(({ binding }) => binding),185 ...(block.d1_databases ?? []).map(({ binding }) => binding),186 ...(block.durable_objects?.bindings ?? []).map(({ name }) => name),187 ...(block.kv_namespaces ?? []).map(({ binding }) => binding),
63 unmodified lines
251 ].flatMap(({ groups }) => (groups?.key === undefined ? [] : [groups.key]))252 )253);254255/** The draft limit as a stage's block declares it, under its own namespace id. */256const draftLimit = (id: string) => ({257 name: "DRAFT_LIMIT",258 namespace_id: id,259 simple: { limit: 2, period: 60 },260});261262describe("a wrangler.jsonc, read as data", () => {263 it.effect(264 "loses its comments and trailing commas, a comment between a comma and its bracket too, and keeps every string whole",265 () =>
40 unmodified lines
306 });307 }).pipe(Effect.provide(NodeServices.layer))308 );309310 // The drafter's model and the web's address are stage vars, and drafts311 // are rate-limited apart from proposals, two a minute per person.312 it.effect(313 "set the drafter's model, the web's address and the draft limit in every stage",314 () =>315 Effect.gen(function* () {316 const raw = yield* Effect.flatMap(317 fileText("wrangler.jsonc"),318 readJsonc319 );320321 const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);322323 const DraftBlock = Schema.Struct({324 ai: Schema.Struct({ binding: Schema.String }),325 ratelimits: Schema.Array(326 Schema.Struct({327 name: Schema.String,328 namespace_id: Schema.String,329 simple: Schema.Struct({330 limit: Schema.Int,331 period: Schema.Int,332 }),333 })334 ),335 vars: PlatformVars,336 });337338 const read = (block: typeof Raw.Type | undefined) =>339 Effect.map(340 Schema.decodeUnknownEffect(DraftBlock)(block),341 ({ ai, ratelimits, vars }) => ({342 ai: ai.binding,343 draftLimit: ratelimits.find(({ name }) => name === "DRAFT_LIMIT"),344 model: vars.DRAFT_MODEL,345 web: vars.PUBLIC_WEB_URL,346 })347 );348349 const model = "@cf/moonshotai/kimi-k2.7-code";350351 expect({352 demo: yield* read(env.demo),353 "dev-oscabriel": yield* read(env["dev-oscabriel"]),354 top: yield* read(raw),355 }).toStrictEqual({356 demo: {357 ai: "AI",358 draftLimit: draftLimit("1204"),359 model,360 web: "https://web-demo.oscargabriel.workers.dev",361 },362 "dev-oscabriel": {363 ai: "AI",364 draftLimit: draftLimit("1104"),365 model,366 web: "https://web-dev-oscabriel.oscargabriel.workers.dev",367 },368 top: {369 ai: "AI",370 draftLimit: draftLimit("1004"),371 model,372 web: "http://localhost:5173",373 },374 });375 }).pipe(Effect.provide(NodeServices.layer))376 );377378 it("are all the Env the Worker is given, and nothing else", () => {379 expectTypeOf<keyof Env>().toEqualTypeOf<380 Exclude<381 keyof PlatformConfig,
30 unmodified lines
412 >();413 expectTypeOf<Env["PROPOSAL_LIMIT"]>().toExtend<414 Parameters<typeof WorkerRateLimits>[0]["proposal"]415 >();416 expectTypeOf<Env["DRAFT_LIMIT"]>().toExtend<417 Parameters<typeof WorkerRateLimits>[0]["draft"]418 >();419 expectTypeOf<PlatformConfig["AI"]>().toEqualTypeOf<Env["AI"]>();420 expectTypeOf<Env["FRONT_PAGE"]>().toExtend<421 Parameters<typeof D1Client.layer>[0]["db"]422 >();423 expectTypeOf<Env["OAUTH_KV"]>().toExtend<
47 unmodified lines
modified:apps/platform/test/do-projects.test.ts+20 added-2 removed
10 unmodified lines
11 EnvKey,12 LandedSha,13 LayerName,14 ProjectName,15 ProposalId,16 RequestId,17} from "@repo/protocol/ids";18import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";19import { advanceTo } from "@repo/testkit/clock";
64 unmodified lines
84 choice: "accept",85 decision: DecisionId.make("dec-none0001"),86 })87 ),88 draftAsk: settled(89 "draftAsk",90 api.draftAsk(carol, { proposal: ProposalId.make("prop-000001") })91 ),92 [envSchemaMethod]: settled(envSchemaMethod, api[envSchemaMethod](anyone)),93 events: settled("events", api.events(0, 100)),94 evidence: settled(95 "evidence",
8 unmodified lines
104 "flagAsk",105 api.flagAsk(bob, { ask: parseIso, reason: "It names no format." })106 ),107 fork: settled("fork", api.fork(carol)),108 forks: settled("forks", api.forks()),109 head: settled("head", api.head()),110 heldBackJob: settled("heldBackJob", api.heldBackJob(requestId)),111 initProject: settled("initProject", api.initProject(alice, {})),112 land: settled(113 "land",114 api.land(bob, { base: sha, head: sha, message: "Tidy", requestId })115 ),116 landing: settled("landing", api.landing(anyone, sha)),117 landings: settled("landings", api.landings([sha])),118 layerAccess: settled("layerAccess", api.layerAccess(alice, layer)),119 layerFacts: settled("layerFacts", api.layerFacts(bob)),120 ledger: settled("ledger", api.ledger(anyone)),121 listAsks: settled("listAsks", api.listAsks(anyone)),
1 unmodified line
123 openAsk: settled(124 "openAsk",125 api.openAsk(bob, { ask: parseIso, files: askFiles() })126 ),127 policy: settled("policy", api.policy()),128 proposeAsk: settled(129 "proposeAsk",130 api.proposeAsk(carol, { want: "Parse ISO week dates." })131 ),
37 unmodified lines
169 value: Redacted.make("a-value-long-enough-0123"),170 })171 ),172 showAsk: settled("showAsk", api.showAsk(anyone, parseIso)),173 showProposal: settled(174 "showProposal",175 api.showProposal(anyone, ProposalId.make("prop-000001"))176 ),177 status: settled("status", api.status(bob)),178 submitAnswer: settled(179 "submitAnswer",180 api.submitAnswer(bob, { ask: parseIso, base: sha, head: sha, requestId })
75 unmodified lines
256 expect(Object.keys(throughDo.each).toSorted()).toStrictEqual(257 projectMethods.toSorted()258 );259 expect(throughDo).toStrictEqual(inProcess);247 // Only a step reported for an answer request that never was dies.248 expect(died).toStrictEqual(["advanceAnswer"]);260 // Only a step reported for an answer request that never was dies,261 // and the drafting stubs, until 909 builds them.262 expect(died).toStrictEqual([263 "advanceAnswer",264 "draftAsk",265 "showProposal",266 ]);267 })268 );269});
modified:apps/platform/test/fake-env.ts+4 added
148 unmodified lines
149 * one with `UnknownProject`, each noted (`callsTo`). The optional secrets150 * are absent.151 */152export const fakeEnv = (): Env => ({153 AI: untouchable("AI"),154 ANSWER: untouchable("ANSWER"),155 ARTIFACTS: untouchable("ARTIFACTS"),156 ARTIFACTS_PRIVATE: untouchable("ARTIFACTS_PRIVATE"),157 CLAIM_LIMIT: untouchable("CLAIM_LIMIT"),158 COOKIE_KEY: cookieKey,159 DRAFT_LIMIT: untouchable("DRAFT_LIMIT"),160 DRAFT_MODEL: "@cf/moonshotai/kimi-k2.7-code",161 EVIDENCE: untouchable("EVIDENCE"),162 FRONT_PAGE: untouchable("FRONT_PAGE"),163 LANDER_ADAPTER: "container",164 LOADER: untouchable("LOADER"),
4 unmodified lines
169 OPERATOR_TOKEN: operatorToken,170 PASSWORD_PEPPER: passwordPepper,171 PROJECT: fakeProjects(),172 PROPOSAL_LIMIT: untouchable("PROPOSAL_LIMIT"),173 PUBLIC_WEB_URL: "http://localhost:5173",174 RELEASES: untouchable("RELEASES"),175 SANDBOX: untouchable("SANDBOX"),176 SIGN_IN_LIMIT: untouchable("SIGN_IN_LIMIT"),177 STAGE: "local",
21 unmodified lines
modified:apps/platform/test/handlers.fixtures.ts+10 added-2 removed
134 unmodified lines
135export interface WorldOptions {136 /** What the front page reads back; nothing by default. */137 readonly frontPage?: FrontPageSeed;138 /** Claims and proposals each person may make; 100 of each by default. */139 readonly limits?: { readonly claim: number; readonly proposal: number };139 readonly limits?: {140 readonly claim: number;141 readonly draft?: number;142 readonly proposal: number;143 };144}145146const noFrontPage: FrontPageSeed = { credits: [], entries: [], projects: [] };147
16 unmodified lines
164 ).pipe(Layer.provideMerge(LanderIsogit), Layer.provideMerge(allRed))165 )166 ),167 FrontPageMemory.layer(options.frontPage ?? noFrontPage),164 MemoryRateLimits(options.limits ?? { claim: 100, proposal: 100 }),168 MemoryRateLimits({169 claim: options.limits?.claim ?? 100,170 draft: options.limits?.draft ?? 100,171 proposal: options.limits?.proposal ?? 100,172 }),173 EvidenceStoreMemory174 ).pipe(Layer.provideMerge(RepoHostMemory));175176/**
33 unmodified lines
modified:apps/platform/test/handlers.test.ts+11 added-2 removed
825 unmodified lines
826};827828describe("the Worker's rate limits", () => {829 it.effect(830 "count claims and proposals apart, per person whatever the case of their handle",830 "count claims, proposals and drafts apart, per person whatever the case of their handle",831 () =>832 Effect.gen(function* () {833 const claims = fakeLimit(2);834 const proposals = fakeLimit(1);835 const drafts = fakeLimit(1);836837 const spent = yield* RateLimits.use(({ check }) =>838 Effect.all([839 Effect.result(check("claim", Handle.make("Alice"))),
1 unmodified line
841 Effect.result(check("claim", Handle.make("alice"))),842 Effect.result(check("claim", Handle.make("bob"))),843 Effect.result(check("proposal", Handle.make("alice"))),844 Effect.result(check("proposal", Handle.make("alice"))),845 Effect.result(check("draft", Handle.make("alice"))),846 Effect.result(check("draft", Handle.make("Alice"))),847 ])848 ).pipe(849 Effect.provide(850 WorkerRateLimits({851 claim: claims.binding,852 draft: drafts.binding,853 proposal: proposals.binding,854 })855 )856 );
4 unmodified lines
861 Result.fail(new CapReached({ cap: WorkerCaps.claim })),862 Result.void,863 Result.void,864 Result.fail(new CapReached({ cap: WorkerCaps.proposal })),865 Result.void,866 Result.fail(new CapReached({ cap: WorkerCaps.draft })),867 ]);868 expect(claims.keys).toStrictEqual(["alice", "alice", "alice", "bob"]);869 expect(proposals.keys).toStrictEqual(["alice", "alice"]);870 expect(drafts.keys).toStrictEqual(["alice", "alice"]);871 })872 );873874 it.effect("die when the binding fails, rather than let a call through", () =>
5 unmodified lines
880 const spent = yield* Effect.exit(881 RateLimits.use(({ check }) =>882 check("claim", Handle.make("alice"))883 ).pipe(877 Effect.provide(WorkerRateLimits({ claim: broken, proposal: broken }))884 Effect.provide(885 WorkerRateLimits({ claim: broken, draft: broken, proposal: broken })886 )887 )888 );889890 expect(Exit.hasDies(spent)).toBeTruthy();
36 unmodified lines
modified:apps/platform/test/harness.ts+19 added-7 removed
5 unmodified lines
6import { Projects } from "@repo/project/projects";7import { Contracts } from "@repo/protocol/contracts";8import { UnknownProject } from "@repo/protocol/refusal";9import { untouchable } from "@repo/testkit/untouchable";10import { Effect, Layer, Schema } from "effect";10import { Effect, Layer, Option, Schema } from "effect";11import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";12import { RpcClient, RpcSerialization } from "effect/rpc";1314import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";15import { Handlers } from "../src/handlers.ts";16import { ReleaseStore } from "../src/releases.ts";17import { serve, Stage } from "../src/surfaces.ts";17import { HostInfo, serve, Stage } from "../src/surfaces.ts";18import type { Services } from "../src/surfaces.ts";1920/** Where every test request goes: the platform as `served` answers it. */21export const origin = "http://localhost";
112 unmodified lines
134/**135 * What a surfaces test may leave out: git's ports and the release store,136 * unused (no test here pushes, and only the releases test downloads), a137 * front page that lists no project and the repos behind it, unused (so the138 * skills index is empty), and the stage, `local`.138 * skills index is empty), the stage, `local`, and a host with no web app139 * whose drafter is `test-model`.140 */141const defaults = Layer.mergeAll(142 Layer.succeed(143 Projects,
2 unmodified lines
146 Layer.succeed(Upstream, Upstream.of({ exchange: unused("Upstream") })),147 Layer.succeed(ReleaseStore, ReleaseStore.of({ get: unused("ReleaseStore") })),148 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),149 Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),149 Layer.succeed(Stage, Stage.of({ name: "local" }))150 Layer.succeed(Stage, Stage.of({ name: "local" })),151 Layer.succeed(152 HostInfo,153 HostInfo.of({ draftModel: "test-model", webUrl: Option.none() })154 )155);156157/**158 * The contracts before any project exists, served by the platform's own159 * handlers: a call that names a project finds none (`UnknownProject`), the155 * front page lists nothing, nobody is near a rate limit, and no lane has156 * left a log.160 * front page lists nothing, nobody is near a rate limit, no lane has161 * left a log, and no repo is read.162 */163export const noProjects = Handlers.pipe(164 Layer.provide([165 Layer.succeed(
5 unmodified lines
171 ),172 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),173 MemoryRateLimits(WorkerCaps),174 EvidenceStoreMemory,175 Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),176 ])177);178179/**
3 unmodified lines
183export const served = Effect.fnUntraced(function* <E>(184 services: Layer.Layer<185 Exclude<186 Services,181 Projects | ReleaseStore | Upstream | FrontPage | RepoHost | Stage187 | Projects188 | ReleaseStore189 | Upstream190 | FrontPage191 | RepoHost192 | Stage193 | HostInfo194 >,195 E196 >197) {
39 unmodified lines
modified:apps/platform/test/mcp.test.ts+13 added
22 unmodified lines
23 DecisionId,24 Handle,25 LaneName,26 ProjectName,27 ProposalId,28 RepoPath,29 RequestId,30} from "@repo/protocol/ids";31import { CurrentPrincipal, Principal } from "@repo/protocol/principal";
367 unmodified lines
399 [EnvSchemaOf._tag]: {400 args: { project: nowhere },401 refusal: new UnknownProject({ project: nowhere }),402 },403 draftAsk: {404 args: { project: nowhere, proposal: ProposalId.make("prop-000001") },405 refusal: new UnknownProject({ project: nowhere }),406 },407 finish: {408 args: { ask: fixWeek, base, head, project, requestId },409 refusal: new NotDecider({}),410 },
28 unmodified lines
439 openAsk: {440 args: { ask: nope, files: askFiles, project },441 refusal: new NotDecider({}),442 },443 projectPolicy: {444 args: { project: nowhere },445 refusal: new UnknownProject({ project: nowhere }),446 },447 proposeAsk: {448 args: { project: nowhere, want },449 refusal: new UnknownProject({ project: nowhere }),450 },
4 unmodified lines
455 showAsk: {456 args: { ask: nope, project },457 refusal: new UnknownAsk({ ask: nope }),458 },459 showProposal: {460 args: { project: nowhere, proposal: ProposalId.make("prop-000001") },461 refusal: new UnknownProject({ project: nowhere }),462 },463 status: {464 args: { project: nowhere },465 refusal: new UnknownProject({ project: nowhere }),466 },
401 unmodified lines
added:apps/platform/test/w9-contracts.test.ts+156 added
1/**2 * The code browser's, the people page's and drafting's contracts and3 * routes, wired end to end through the platform's fetch4 * handler before their bodies exist: the policy read answers, each code5 * read reaches the façade (which names the issue that builds it), a draft6 * needs a person, and `/` and a project's raw files have their slots, open7 * to a stale credential as every public path is.8 */9import { describe, expect, it } from "@effect/vitest";10import { ProposalId } from "@repo/protocol/ids";11import { Unauthenticated } from "@repo/protocol/principal";12import { advanceTo } from "@repo/testkit/clock";13import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";14import { Cause, Effect, Exit, Layer, Option } from "effect";1516import { Handlers } from "../src/handlers.ts";17import { MemorySessions } from "../src/sessions/memory.ts";18import { seeded, worldOf } from "./handlers.fixtures.ts";19import { origin, rpcClient, served } from "./harness.ts";2021const datekit = aProject({ people: ["bob"] }).pipe(22 withVouches(["bob"]),23 withAsk({ id: "parse-iso", territory: "packages/parser" })24);2526const { project } = datekit;2728const sessions = MemorySessions.layer({});2930/** The platform over datekit's world, seeded: made, pushed to, its ask open. */31const platform = Effect.gen(function* () {32 yield* advanceTo("2026-10-07T12:00:00Z");3334 const world = yield* Layer.build(worldOf([datekit]));3536 yield* seeded(datekit).pipe(Effect.provide(world));3738 const ports = Layer.succeedContext(world);3940 return yield* served(41 Layer.mergeAll(Handlers.pipe(Layer.provide(ports)), ports, sessions)42 );43});4445/** What a call died with, as text; none when it did not die. */46const diedWith = <A, E>(call: Effect.Effect<A, E>) =>47 Effect.map(Effect.exit(call), (exit) =>48 Exit.isFailure(exit) && Cause.hasDies(exit.cause)49 ? Option.some(String(Cause.squash(exit.cause)))50 : Option.none()51 );5253describe("the code, policy and drafting contracts over /rpc", () => {54 it.effect("give anyone a project's policy, without its layers", () =>55 Effect.gen(function* () {56 const { handler } = yield* platform;57 const anyone = yield* rpcClient(handler);5859 const { policy } = yield* anyone.projectPolicy({ project });6061 expect(policy?.source).toBe("config");62 expect(policy?.deciders).toStrictEqual(datekit.policy.deciders);63 expect(Object.keys(policy ?? {})).not.toContain("visibility");64 expect(Object.keys(policy ?? {})).not.toContain("asks");65 })66 );6768 it.effect("reach the code façade, which names the issue that builds it", () =>69 Effect.gen(function* () {70 const { handler } = yield* platform;71 const anyone = yield* rpcClient(handler);7273 expect(yield* diedWith(anyone.listRefs({ project }))).toStrictEqual(74 Option.some("not built: 903")75 );76 expect(yield* diedWith(anyone.readTree({ project }))).toStrictEqual(77 Option.some("not built: 903")78 );79 })80 );8182 it.effect("refuse a draft to anyone not signed in", () =>83 Effect.gen(function* () {84 const { handler } = yield* platform;85 const anyone = yield* rpcClient(handler);8687 expect(88 yield* Effect.exit(89 anyone.draftAsk({90 project,91 proposal: ProposalId.make("prop-000001"),92 })93 )94 ).toStrictEqual(Exit.fail(new Unauthenticated()));95 })96 );97});9899describe("the host page and raw files routes", () => {100 it.effect(101 "answer / and a project's raw files from their slots, a stale bearer or not",102 () =>103 Effect.gen(function* () {104 const { fetch } = yield* platform;105106 const stale = {107 authorization: "Bearer not-a-token-the-platform-knows",108 };109110 const read = (path: string, headers: Record<string, string> = {}) =>111 Effect.flatMap(112 fetch(new Request(`${origin}${path}`, { headers })),113 (response) =>114 Effect.map(115 Effect.promise(() => response.text()),116 (text) => ({ status: response.status, text })117 )118 );119120 const raw = `/${project}/raw/${"4".repeat(40)}/README.md`;121122 expect({123 home: yield* read("/"),124 homeStale: yield* read("/", stale),125 raw: yield* read(raw),126 rawStale: yield* read(raw, stale),127 }).toStrictEqual({128 home: {129 status: 501,130 text: "not built: 906 (draft model test-model)",131 },132 homeStale: {133 status: 501,134 text: "not built: 906 (draft model test-model)",135 },136 raw: { status: 501, text: "not built: 903" },137 rawStale: { status: 501, text: "not built: 903" },138 });139 })140 );141142 it.effect("leaves git's own paths to git, beside the raw route", () =>143 Effect.gen(function* () {144 const { fetch } = yield* platform;145146 const response = yield* fetch(147 new Request(`${origin}/${project}/raw/info/refs`)148 );149150 expect(response.status).toBe(501);151 expect(yield* Effect.promise(() => response.text())).toBe(152 "not built: 903"153 );154 })155 );156});
modified:apps/platform/package.json+1 added
13 unmodified lines
14 "@repo/agent-kit": "workspace:*",15 "@repo/artifacts": "workspace:*",16 "@repo/brand": "workspace:*",17 "@repo/checks": "workspace:*",18 "@repo/drafting": "workspace:*",19 "@repo/gate": "workspace:*",20 "@repo/git": "workspace:*",21 "@repo/project": "workspace:*",22 "@repo/protocol": "workspace:*",
17 unmodified lines
modified:apps/platform/worker-configuration.d.ts+14 added-2 removed
1/* eslint-disable */2// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 8c12fe014598b33e00210997684fcc6b)2// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 850febac061bf22321125e7870cc2f45)3interface __BaseEnv_Env {4 OAUTH_KV: KVNamespace;5 EVIDENCE: R2Bucket;6 RELEASES: R2Bucket;
2 unmodified lines
9 ARTIFACTS_PRIVATE: Artifacts;10 CLAIM_LIMIT: RateLimit;11 PROPOSAL_LIMIT: RateLimit;12 SIGN_IN_LIMIT: RateLimit;13 DRAFT_LIMIT: RateLimit;14 LOADER: WorkerLoader;15 AI: Ai;16 OPERATOR_HANDLE: string;17 STAGE: string;18 LANDER_ADAPTER: string;19 DRAFT_MODEL: string;20 PUBLIC_WEB_URL: string;21 OPERATOR_TOKEN: string;22 COOKIE_KEY: string;23 PASSWORD_PEPPER: string;24 MASTER_KEY: string;
16 unmodified lines
41 ARTIFACTS_PRIVATE: Artifacts;42 CLAIM_LIMIT: RateLimit;43 PROPOSAL_LIMIT: RateLimit;44 SIGN_IN_LIMIT: RateLimit;45 DRAFT_LIMIT: RateLimit;46 LOADER: WorkerLoader;47 AI: Ai;48 OPERATOR_HANDLE: string;49 STAGE: string;50 LANDER_ADAPTER: string;51 DRAFT_MODEL: string;52 PUBLIC_WEB_URL: string;53 OPERATOR_TOKEN: string;54 COOKIE_KEY: string;55 PASSWORD_PEPPER: string;56 MASTER_KEY: string;
11 unmodified lines
68 ARTIFACTS_PRIVATE: Artifacts;69 CLAIM_LIMIT: RateLimit;70 PROPOSAL_LIMIT: RateLimit;71 SIGN_IN_LIMIT: RateLimit;72 DRAFT_LIMIT: RateLimit;73 LOADER: WorkerLoader;74 AI: Ai;75 OPERATOR_HANDLE: string;76 STAGE: string;77 LANDER_ADAPTER: string;78 DRAFT_MODEL: string;79 PUBLIC_WEB_URL: string;80 OPERATOR_TOKEN: string;81 COOKIE_KEY: string;82 PASSWORD_PEPPER: string;83 MASTER_KEY: string;
8 unmodified lines
92type StringifyValues<EnvType extends Record<string, unknown>> = {93 [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;94};95declare namespace NodeJS {84 interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "OPERATOR_HANDLE" | "STAGE" | "LANDER_ADAPTER" | "OPERATOR_TOKEN" | "COOKIE_KEY" | "PASSWORD_PEPPER" | "MASTER_KEY">> {}96 interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "OPERATOR_HANDLE" | "STAGE" | "LANDER_ADAPTER" | "DRAFT_MODEL" | "PUBLIC_WEB_URL" | "OPERATOR_TOKEN" | "COOKIE_KEY" | "PASSWORD_PEPPER" | "MASTER_KEY">> {}97}
modified:apps/platform/wrangler.jsonc+28 added
36 unmodified lines
37 "OPERATOR_HANDLE": "oscabriel",38 "STAGE": "local",39 // "container" (apps/sandbox) or "isogit" (in this Worker).40 "LANDER_ADAPTER": "container",41 // The Workers AI model that drafts asks; swap it here, no code change.42 "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",43 // The web app, which `/` links to: `vite dev`'s URL locally.44 "PUBLIC_WEB_URL": "http://localhost:5173",45 },46 "secrets": {47 // Declared in .env.schema; the user sets the values. SESSION_TOKENS is48 // optional; sign-in's cookie key and pepper are not, since accounts are
37 unmodified lines
86 { "binding": "EVIDENCE", "bucket_name": "evidence-local" },87 { "binding": "RELEASES", "bucket_name": "releases-local" },88 ],89 "worker_loaders": [{ "binding": "LOADER" }],90 // Workers AI, for the drafter (no key: the account's own).91 "ai": { "binding": "AI" },92 "services": [{ "binding": "SANDBOX", "service": "sandbox" }],93 // Namespace ids differ per stage, so one stage's counts never spend94 // another's.95 "ratelimits": [
13 unmodified lines
109 "name": "SIGN_IN_LIMIT",110 "namespace_id": "1003",111 "simple": { "limit": 5, "period": 60 },112 },113 // Drafts per person: each one is a model call and Checker runs.114 {115 "name": "DRAFT_LIMIT",116 "namespace_id": "1004",117 "simple": { "limit": 2, "period": 60 },118 },119 ],120 "triggers": {121 "events": [122 {
8 unmodified lines
131 "vars": {132 "OPERATOR_HANDLE": "oscabriel",133 "STAGE": "dev-oscabriel",134 "LANDER_ADAPTER": "container",135 "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",136 "PUBLIC_WEB_URL": "https://web-dev-oscabriel.oscargabriel.workers.dev",137 },138 "secrets": {139 "required": [140 "OPERATOR_TOKEN",
37 unmodified lines
178 { "binding": "EVIDENCE", "bucket_name": "evidence-dev-oscabriel" },179 { "binding": "RELEASES", "bucket_name": "releases-dev-oscabriel" },180 ],181 "worker_loaders": [{ "binding": "LOADER" }],182 "ai": { "binding": "AI" },183 "services": [184 { "binding": "SANDBOX", "service": "sandbox-dev-oscabriel" },185 ],186 "ratelimits": [
11 unmodified lines
198 "name": "SIGN_IN_LIMIT",199 "namespace_id": "1103",200 "simple": { "limit": 5, "period": 60 },201 },202 {203 "name": "DRAFT_LIMIT",204 "namespace_id": "1104",205 "simple": { "limit": 2, "period": 60 },206 },207 ],208 "triggers": {209 "events": [210 {
10 unmodified lines
221 "vars": {222 "OPERATOR_HANDLE": "oscabriel",223 "STAGE": "demo",224 "LANDER_ADAPTER": "container",225 "DRAFT_MODEL": "@cf/moonshotai/kimi-k2.7-code",226 "PUBLIC_WEB_URL": "https://web-demo.oscargabriel.workers.dev",227 },228 "secrets": {229 "required": [230 "OPERATOR_TOKEN",
33 unmodified lines
264 { "binding": "EVIDENCE", "bucket_name": "evidence-demo" },265 { "binding": "RELEASES", "bucket_name": "releases-demo" },266 ],267 "worker_loaders": [{ "binding": "LOADER" }],268 "ai": { "binding": "AI" },269 "services": [{ "binding": "SANDBOX", "service": "sandbox-demo" }],270 "ratelimits": [271 {272 "name": "CLAIM_LIMIT",
9 unmodified lines
282 "name": "SIGN_IN_LIMIT",283 "namespace_id": "1203",284 "simple": { "limit": 5, "period": 60 },285 },286 {287 "name": "DRAFT_LIMIT",288 "namespace_id": "1204",289 "simple": { "limit": 2, "period": 60 },290 },291 ],292 "triggers": {293 "events": [294 {
11 unmodified lines
modified:apps/web/src/client/watch.ts+1 added
77 unmodified lines
78 Judged: ({ ask }) => keys.ask(project, ask),79 Landed: () => keys.project(project),80 Lapsed: () => keys.project(project),81 LedgerAppended: () => keys.ledger(project),82 ProposalDrafted: () => keys.project(project),83 ProposalOpened: () => keys.project(project),84 Pushed: ({ ask }) => keys.ask(project, ask),85 Released: () => keys.project(project),86 Warned: ({ ask }) => keys.ask(project, ask),
48 unmodified lines
modified:apps/web/src/dev/front-page.ts+1 added
90 unmodified lines
91 Judged: () => rows,92 Landed: () => rows,93 Lapsed: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),94 LedgerAppended: () => rows,95 ProposalDrafted: () => rows,96 ProposalOpened: () => rows,97 Pushed: () => rows,98 Released: ({ ask }) => withClaims(rows, keyOf(project, ask), -1),99 Warned: () => rows,
129 unmodified lines
modified:apps/web/src/dev/handlers.ts+70 added-2 removed
6 unmodified lines
7 * projects; `status` and `today` without a project ask every project it8 * lists and merge what each says; `evidence` reads the world's lane logs.9 * Unlike the platform, nothing spends a rate limit: the world has one10 * browser at a time. Every `remote` names the origin the caller reached the11 * world by, as the platform's do.11 * world by, as the platform's do. The code reads run the same12 * `@repo/project/code` functions the platform's do, over the world's13 * `RepoHost`.14 */15import { RepoHost } from "@repo/artifacts/repo-host";16import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";17import {18 codeProjectOf,19 commitOf,20 fileOf,21 logOf,22 pathsOf,23 refsOf,24 treeOf,25 whyOf,26} from "@repo/project/code";27import type { CodeProject } from "@repo/project/code";28import { FrontPage } from "@repo/project/front-page";29import type { ProjectApi } from "@repo/project/project";30import { Projects } from "@repo/project/projects";31import { Contracts, EnvSchemaOf } from "@repo/protocol/contracts";
9 unmodified lines
41import type { Layer } from "effect";42import { HttpServerRequest } from "effect/http";43import type { Rpc, RpcGroup } from "effect/rpc";4445/** How many commits a page of `log` holds when the caller names no limit. */46const LOG_PAGE = 30;4748/** How many events `watch` reads from its project at a time. */49const EVENT_PAGE = 100;5051/** The caller, as the `Authenticated` server side named them. */
95 unmodified lines
147/** Every contract over the dev world. A missing contract is a type error here. */148export const devHandlers: Layer.Layer<149 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,150 never,134 Projects | FrontPage | EvidenceStore151 Projects | FrontPage | EvidenceStore | RepoHost152> = Contracts.toLayer(153 Effect.gen(function* () {154 const projects = yield* Projects;155 const frontPage = yield* FrontPage;156 const evidence = yield* EvidenceStore;157 const host = yield* RepoHost;158159 /** `call` on the project named `project`; one never made is `UnknownProject`. */160 const on = <A, E>(161 project: ProjectName,162 call: (api: ProjectApi) => Effect.Effect<A, E>163 ) => Effect.flatMap(projects.get(project), call);164165 /** A code read of `project`'s canonical repo, over the world's `RepoHost`. */166 const code = <A, E>(167 project: ProjectName,168 read: (of: CodeProject) => Effect.Effect<A, E, RepoHost>169 ) =>170 on(project, (api) =>171 read(codeProjectOf(api, project)).pipe(172 Effect.provideService(RepoHost, host)173 )174 );175176 /** `call` on every project the front page lists, in name order, keeping what each finds. */177 const everywhere = <A, E>(178 call: (api: ProjectApi) => Effect.Effect<Option.Option<A>, E>179 ) =>
28 unmodified lines
208 decide: ({ project, ...input }) =>209 Effect.flatMap(person, (who) =>210 on(project, (api) => api.decide(who, input))211 ),212 draftAsk: ({ project, ...input }) =>213 Effect.flatMap(person, (who) =>214 on(project, (api) => api.draftAsk(who, input))215 ),216 evidence: ({ project, ref }) =>217 Effect.flatMap(person, (who) =>218 on(project, (api) =>219 api
54 unmodified lines
274 listAsks: ({ project }) =>275 Effect.flatMap(caller, (who) =>276 on(project, (api) => api.listAsks(who))277 ),278 listPaths: ({ at, project }) =>279 code(project, (of) => pathsOf(of, Option.fromUndefinedOr(at))),280 listProjects: () =>281 Effect.map(frontPage.projects(), (listed) => ({ projects: listed })),282 listRefs: ({ project }) => code(project, refsOf),283 log: ({ at, from = 0, limit = LOG_PAGE, path, project }) =>284 code(project, (of) =>285 logOf(of, {286 at: Option.fromUndefinedOr(at),287 from,288 limit,289 path: Option.fromUndefinedOr(path),290 })291 ),292 openAsk: ({ project, ...input }) =>293 Effect.flatMap(person, (who) =>294 on(project, (api) => api.openAsk(who, input))295 ),296 projectPolicy: ({ project }) =>297 on(project, (api) =>298 Effect.map(api.policy(), (policy) =>299 Option.match(policy, {300 onNone: () => ({}),301 onSome: (evaluated) => ({ policy: evaluated }),302 })303 )304 ),305 proposeAsk: ({ project, ...input }) =>306 Effect.flatMap(person, (who) =>307 on(project, (api) => api.proposeAsk(who, input))308 ),309 readFile: ({ at, path, project }) =>310 code(project, (of) => fileOf(of, Option.fromUndefinedOr(at), path)),311 readTree: ({ at, path, project }) =>312 code(project, (of) =>313 treeOf(of, Option.fromUndefinedOr(at), Option.fromUndefinedOr(path))314 ),315 release: ({ ask, project }) =>316 Effect.flatMap(person, (who) =>317 on(project, (api) => api.release(who, ask))318 ),
4 unmodified lines
323 showAsk: ({ ask, project }) =>324 Effect.flatMap(caller, (who) =>325 on(project, (api) => api.showAsk(who, ask))326 ),327 showCommit: ({ project, sha }) =>328 code(project, (of) => commitOf(of, sha)),329 showProposal: ({ project, proposal }) =>330 Effect.flatMap(caller, (who) =>331 on(project, (api) => api.showProposal(who, proposal))332 ),333 status: ({ project }) =>334 Effect.gen(function* () {335 const who = yield* person;336
55 unmodified lines
392 ])393 )394 )395 ),396 why: ({ at, path, project }) =>397 code(project, (of) => whyOf(of, Option.fromUndefinedOr(at), path)),398 };399 })400);
modified:apps/web/package.json+1 added
41 unmodified lines
42 "@playwright/test": "1.63.0",43 "@repo/artifacts": "workspace:*",44 "@repo/checks": "workspace:*",45 "@repo/config": "workspace:*",46 "@repo/drafting": "workspace:*",47 "@repo/git": "workspace:*",48 "@repo/project": "workspace:*",49 "@repo/rules": "workspace:*",50 "@repo/testkit": "workspace:*",
12 unmodified lines
modified:packages/agent-kit/test/command-doc.test.ts+7 added-1 removed
158 unmodified lines
159 expect(160 words.filter((name) => name.startsWith("ask") || name.startsWith("env"))161 ).toStrictEqual([162 "ask",163 "ask draft",164 "ask flag",165 "ask open",166 "asks",167 "env set",168 "env shape",169 ]);169 expect(words.slice(0, 3)).toStrictEqual(["ask", "ask flag", "ask open"]);170 expect(words.slice(0, 4)).toStrictEqual([171 "ask",172 "ask draft",173 "ask flag",174 "ask open",175 ]);176 });177178 // `init` and `env set` do local work around the contract they call, so179 // their hand-written rows stand for those contracts.
5 unmodified lines
modified:packages/artifacts/src/repo-host/binding.ts+19 added-5 removed
57 unmodified lines
58 refOf,59 secondsOf,60} from "./artifacts-api.ts";61import type { Code } from "./artifacts-api.ts";62import { listRefs, pushRefs } from "./smart-http.ts";62import { listRefs, listTags, pushRefs } from "./smart-http.ts";6364/**65 * The codes a message names when the error carries none: Artifacts'66 * words, the fake's, and the code itself.
100 unmodified lines
167168const commitOf = (metadata: ArtifactsCommitMetadata) =>169 decodeCommit({170 author: metadata.author,171 authoredAt: metadata.authoredAt,172 committedAt: metadata.committedAt,173 committer: metadata.committer,174 message: metadata.message,175 parents: metadata.parents,176 sha: metadata.hash,
95 unmodified lines
272 return yield* listRefs(remote, token);273 })274 );275276/** The repo's tags over smart HTTP, peeled: the binding lists no refs. */277const tagsOf = (name: RepoName, repo: ArtifactsRepo) =>278 Effect.scoped(279 Effect.gen(function* () {280 const { remote, token } = yield* access(name, repo, "read");281282 return yield* listTags(remote, token);283 })284 );285286/**287 * After a 500 and then an already-exists or a second 500, the fork may be288 * made: it is, if it lists `main`. Otherwise it is still being made, or289 * was undone; either way the caller tries again later.
112 unmodified lines
402const log = (403 name: RepoName,404 repo: ArtifactsRepo,405 at: Revision,394 limit: number406 limit: number,407 offset: number408) =>409 Effect.gen(function* () {410 const ref = refOf(at);411 const commits: Commit[] = [];
1 unmodified line
413 while (commits.length < limit) {414 const asked = Math.min(limit - commits.length, LOG_PAGE);415416 const page = yield* call(name, () =>404 repo.log({ limit: asked, offset: commits.length, ref })417 repo.log({ limit: asked, offset: offset + commits.length, ref })418 );419420 for (const metadata of page) {421 commits.push(yield* commitOf(metadata));
74 unmodified lines
496 ),497 Effect.provideService(Fetch, fetch)498 ),499 importFrom: (name, source) => importFrom(binding, name, source),487 log: (name, at, limit) =>488 read(name, (repo) => log(name, repo, at, limit)),500 log: (name, at, limit, offset = 0) =>501 read(name, (repo) => log(name, repo, at, limit, offset)),502 mintToken: (name, scope, ttl) =>503 read(name, (repo) => mintToken(name, repo, scope, ttl)),504 push: (name, source, updates) =>505 withRepo(binding, name, (repo) =>
52 unmodified lines
558 Effect.catchTag("Thrown", asDefect)559 ),560 revokeToken: (name, id) =>561 read(name, (repo) => call(name, () => repo.revokeToken(id))),562 tags: (name) => read(name, (repo) => tagsOf(name, repo)),563 });564 });565566/**
7 unmodified lines
modified:packages/artifacts/src/repo-host/isogit-store.ts+73 added-5 removed
5 unmodified lines
6 init,7 listRefs,8 readBlob,9 readCommit,10 readTag,11 readTree,12 resolveRef,13 writeBlob,14 writeCommit,15 writeRef,16 writeTag,17 writeTree,18} from "isomorphic-git";1920import {
140 unmodified lines
161 );162 yield* keep(oid, () => writeCommit({ ...into, commit }));163 });164165/**166 * A ref's target, objects first: an annotated tag after what it names167 * (a commit, or another tag), or else a commit and its history.168 */169const copyTarget = (170 source: PushSource,171 into: GitDir,172 oid: string173): Effect.Effect<void> =>174 Effect.gen(function* () {175 const tag = yield* unlessMissing(() => readTag({ ...source, oid }));176177 if (Option.isNone(tag)) {178 yield* copyCommit(source, into, oid);179180 return;181 }182183 const present = yield* unlessMissing(() => readTag({ ...into, oid }));184185 if (Option.isSome(present)) {186 return;187 }188189 yield* copyTarget(source, into, tag.value.tag.object);190 yield* keep(oid, () => writeTag({ ...into, tag: tag.value.tag }));191 });192193/** Sets the new repo `into`'s `ref` to `source`'s `tip`, objects first. */194export const seedRef = (195 source: PushSource,196 into: GitDir,
20 unmodified lines
217 if (!Equal.equals(tip, update.from)) {218 return RefOutcome.Stale({ ref: update.ref, tip });219 }220191 yield* copyCommit(source, into, update.to);221 yield* copyTarget(source, into, update.to);222 yield* git(() =>223 writeRef({ ...into, force: true, ref: update.ref, value: update.to })224 ).pipe(Effect.orDie);225
11 unmodified lines
237 unlessMissing(() => readCommit({ ...repo, oid: sha })).pipe(238 Effect.map(239 Option.map(({ commit, oid }): Commit => ({240 author: { email: commit.author.email, name: commit.author.name },241 authoredAt: commit.author.timestamp,242 committedAt: commit.committer.timestamp,243 committer: {244 email: commit.committer.email,245 name: commit.committer.name,246 },
18 unmodified lines
265export const objectsAndRefs = (266 known: (name: RepoName) => Effect.Effect<StoredRepo, RepoNotFound>267): Pick<268 RepoHost["Service"],237 "log" | "push" | "readBlob" | "readCommit" | "readFile" | "readTree" | "refs"269 | "log"270 | "push"271 | "readBlob"272 | "readCommit"273 | "readFile"274 | "readTree"275 | "refs"276 | "tags"277> => ({239 log: (name, at, limit) =>278 log: (name, at, limit, offset = 0) =>279 Effect.gen(function* () {280 const { dir } = yield* known(name);281 const commits: Commit[] = [];282 let next = yield* resolve(dir, at);283245 while (Option.isSome(next) && commits.length < limit) {284 while (Option.isSome(next) && commits.length < offset + limit) {285 const commit = yield* commitAt(dir, next.value);286287 if (Option.isNone(commit)) {288 break;
2 unmodified lines
291 commits.push(commit.value);292 next = Option.fromNullishOr(commit.value.parents[0]);293 }294256 return commits;295 return commits.slice(offset);296 }),297 push: (name, source, updates) =>298 Effect.gen(function* () {299 const { dir, lock } = yield* known(name);
68 unmodified lines
368 );369370 return new Map(Array.getSomes(listed));371 }),372 // isomorphic-git's `readCommit` peels an annotated tag to its commit; a373 // tag naming a tree or a blob names no commit, and is left out.374 tags: (name) =>375 Effect.gen(function* () {376 const { dir } = yield* known(name);377378 const names = yield* git(() =>379 listRefs({ ...dir, filepath: "refs/tags" })380 ).pipe(Effect.orDie);381382 const listed = yield* Effect.forEach(names, (relative) =>383 Effect.gen(function* () {384 const ref = RefName.make(`refs/tags/${relative}`);385 const tip = yield* tipOf(dir, ref);386387 const peeled = yield* Option.match(tip, {388 onNone: () => Effect.succeedNone,389 onSome: (oid) => unlessMissing(() => readCommit({ ...dir, oid })),390 });391392 return Option.map(peeled, ({ oid }) => ({393 name: ref,394 sha: CommitSha.make(oid),395 }));396 })397 );398399 return Array.getSomes(listed);400 }),401});
modified:packages/artifacts/src/repo-host/rest.ts+34 added-6 removed
103 unmodified lines
104 refOf,105 secondsOf,106} from "./artifacts-api.ts";107import type { Code } from "./artifacts-api.ts";108import { listRefs, pushRefs } from "./smart-http.ts";108import { listRefs, listTags, pushRefs } from "./smart-http.ts";109110/** A refusal that names no code at all, such as a proxy's, read by status. */111const byStatus = (status: number): Option.Option<Code> =>112 Match.value(status).pipe(
81 unmodified lines
194 message: Schema.String,195 parents: Schema.Array(CommitSha),196};197198// ASSUMPTION: the REST API spells the binding's times as it spells199// `tree_hash`, in snake case, or as the binding does.200const Metadata = Schema.Union([199 Schema.Struct({ ...commitFields, tree_hash: ObjectId }),200 Schema.Struct({ ...commitFields, treeHash: ObjectId }),201 Schema.Struct({202 ...commitFields,203 authored_at: Schema.Int,204 committed_at: Schema.Int,205 tree_hash: ObjectId,206 }),207 Schema.Struct({208 ...commitFields,209 authoredAt: Schema.Int,210 committedAt: Schema.Int,211 treeHash: ObjectId,212 }),213]);214215type Metadata = typeof Metadata.Type;216
10 unmodified lines
227const decodeEntries = Schema.decodeUnknownEffect(Schema.Array(TreeEntry));228229const commitOf = (metadata: Metadata): Commit => ({230 author: metadata.author,231 ...("tree_hash" in metadata232 ? {233 authoredAt: metadata.authored_at,234 committedAt: metadata.committed_at,235 tree: metadata.tree_hash,236 }237 : {238 authoredAt: metadata.authoredAt,239 committedAt: metadata.committedAt,240 tree: metadata.treeHash,241 }),242 committer: metadata.committer,243 message: metadata.message,244 parents: metadata.parents,245 sha: metadata.hash,223 tree: "tree_hash" in metadata ? metadata.tree_hash : metadata.treeHash,246});247248// Artifacts gives canonical modes: a folder is `40000`, as git stores it, not249// `040000`, as `ls-tree` prints it and the port has it.
455 unmodified lines
705 : Effect.die(refused)706 )707 );708687 const log = (name: RepoName, at: Revision, limit: number) =>709 const log = (name: RepoName, at: Revision, limit: number, offset = 0) =>710 Effect.gen(function* () {711 const commits: Commit[] = [];712713 while (commits.length < limit) {714 const more = yield* page(715 name,716 refOf(at),695 commits.length,717 offset + commits.length,718 Math.min(limit - commits.length, LOG_PAGE)719 );720721 if (more.length === 0) {
112 unmodified lines
834 // The route takes the id alone; the repo is checked to exist, as the835 // binding's `get` does.836 revokeToken: (name, id) =>837 remoteOf(name).pipe(Effect.andThen(revoke(id))),838 tags: (name) =>839 accessOf(name, "read").pipe(840 Effect.flatMap(({ remote, token }) => listTags(remote, token)),841 Effect.catchTag("ForkInProgress", Effect.die),842 Effect.provideService(Fetch, fetch)843 ),844 });845 });846847/**
16 unmodified lines
modified:packages/artifacts/src/repo-host/smart-http.ts+43 added-1 removed
43 unmodified lines
44 RefOutcome,45 RepoName,46 RepoNotFound,47} from "../repo-host.ts";48import type { PushSource, RefUpdate } from "../repo-host.ts";48import type { PushSource, RefUpdate, Tag } from "../repo-host.ts";4950/** What isomorphic-git or a response body threw, before it is read. */51class GitFailure extends Data.TaggedError("GitFailure")<{52 readonly cause: unknown;
219 unmodified lines
272 )273 );274275/**276 * Every `refs/tags/*` the remote lists, each peeled to what it names: the277 * `^{}` line protocol v1 advertises after an annotated tag, else the tag's278 * own target.279 */280const tagsAt = (remote: string, http: HttpClient) =>281 git(() =>282 listServerRefs({283 http,284 peelTags: true,285 prefix: "refs/tags/",286 protocolVersion: 1,287 url: remote,288 })289 ).pipe(290 Effect.catchTags({291 GitFailure: ({ cause }) => Effect.die(cause),292 HostBusy: Effect.die,293 }),294 Effect.map((refs) =>295 refs.flatMap(({ oid, peeled, ref }) =>296 Option.match(Option.all([decodeRef(ref), decodeSha(peeled ?? oid)]), {297 onNone: () => [],298 onSome: ([name, sha]) => [{ name, sha }],299 })300 )301 )302 );303304/** Every tag the remote lists, peeled to its commit. */305export const listTags = (306 remote: string,307 token: Redacted.Redacted308): Effect.Effect<readonly Tag[], RepoNotFound, Fetch> =>309 Effect.scoped(310 Effect.gen(function* () {311 const name = yield* repoOf(remote);312313 return yield* tagsAt(remote, yield* httpFor(remote, token, name));314 })315 );316317/**318 * Every ref the remote lists, as `ls-remote` lists them: what reads by name319 * cannot reach.320 */321export const listRefs = (
197 unmodified lines
modified:packages/artifacts/src/repo-host.ts+20 added-2 removed
68 unmodified lines
69export const Revision = Data.taggedEnum<Revision>();7071const Person = Schema.Struct({ email: Schema.String, name: Schema.String });7273/** A commit, with when it was written and when committed, in Unix seconds. */74export const Commit = Schema.Struct({75 author: Person,76 authoredAt: Schema.Int,77 committedAt: Schema.Int,78 committer: Person,79 message: Schema.String,80 parents: Schema.Array(CommitSha),81 sha: CommitSha,
1 unmodified line
83});8485export type Commit = typeof Commit.Type;8687/** One tag: its full ref, and the commit it names, peeled. */88export interface Tag {89 readonly name: RefName;90 readonly sha: CommitSha;91}9293export type TokenScope = "read" | "write";9495export interface RepoToken {96 readonly id: string;
108 unmodified lines
205 readonly readBlob: (206 name: RepoName,207 blob: ObjectId208 ) => Effect.Effect<Option.Option<Uint8Array>, RepoNotFound>;200 /** First parents from `at`, newest first. */209 /** First parents from `at`, newest first, the first `offset` (0 when absent) skipped. */210 readonly log: (211 name: RepoName,212 at: Revision,204 limit: number213 limit: number,214 offset?: number215 ) => Effect.Effect<readonly Commit[], RepoNotFound>;216 /** Every ref, as `ls-remote` lists them, custom refs included. */217 readonly refs: (218 name: RepoName219 ) => Effect.Effect<ReadonlyMap<RefName, CommitSha>, RepoNotFound>;220 /**221 * Every `refs/tags/*`, each peeled to the commit it names: an annotated222 * tag's ref names a tag object, which `readCommit` cannot read.223 * `refs` keeps what git lists.224 */225 readonly tags: (226 name: RepoName227 ) => Effect.Effect<readonly Tag[], RepoNotFound>;228 readonly push: (229 name: RepoName,230 source: PushSource,231 updates: Array.NonEmptyReadonlyArray<RefUpdate>
3 unmodified lines
modified:packages/artifacts/test/fake-rest.ts+9 added-4 removed
261 unmodified lines
262 const prefix = `${apiBase}/accounts/${options.accountId}/artifacts/namespaces/${options.namespace}`;263 const forkFailures = yield* Ref.make(options.forkFailures ?? 0);264 const tokens = yield* Ref.make<ReadonlyMap<string, Minted>>(new Map());265266 // `RepoHost`'s commits carry no times, so the fake reports the epoch.266 // The times the host read from the commit itself.267 const metadataOf = (commit: Commit) => {268 const fields = {269 author: commit.author,270 committer: commit.committer,
2 unmodified lines
273 parents: commit.parents,274 };275276 return options.casing === "camel"277 ? { ...fields, authoredAt: 0, committedAt: 0, treeHash: commit.tree }277 ? {278 ...fields,279 authoredAt: commit.authoredAt,280 committedAt: commit.committedAt,281 treeHash: commit.tree,282 }283 : {284 ...fields,280 authored_at: 0,281 committed_at: 0,285 authored_at: commit.authoredAt,286 committed_at: commit.committedAt,287 tree_hash: commit.tree,288 };289 };290
289 unmodified lines
modified:packages/artifacts/test/repo-host-contract.ts+181 added-1 removed
1import { describe, expect, it } from "@effect/vitest";2import { RepoPath } from "@repo/protocol/ids";2import { CommitSha, RepoPath } from "@repo/protocol/ids";3import { gitClient } from "@repo/testkit/git-client";4import { DateTime, Duration, Effect, Option, Redacted } from "effect";5import type { Layer } from "effect";6import { readCommit, writeCommit, writeTag } from "isomorphic-git";78import {9 BranchName,10 ObjectId,
4 unmodified lines
15 RepoName,16 RepoNotFound,17 Revision,18} from "../src/repo-host.ts";19import type { Commit } from "../src/repo-host.ts";20import { memoryFs } from "../src/repo-host/memory-fs.ts";2122const main = RefName.make("refs/heads/main");23
7 unmodified lines
3132/** No object in any repo here has this id. */33const absent = ObjectId.make("0".repeat(40));3435/** When a commit was written, and when committed: two different instants. */36const authored = 1_700_000_000;3738const committed = 1_700_000_500;3940/** The test client's repo, which a push takes objects from. */41type Source = Parameters<RepoHost["Service"]["push"]>[1];4243/**44 * A commit on `parent`'s tree written by hand, so its author and committer45 * times differ (the test client stamps both alike).46 */47const timedCommit = (source: Source, parent: CommitSha) =>48 Effect.gen(function* () {49 const { commit } = yield* Effect.promise(() =>50 readCommit({ ...source, oid: parent })51 );5253 const oid = yield* Effect.promise(() =>54 writeCommit({55 ...source,56 commit: {57 author: {58 email: "author@example.com",59 name: "Author",60 timestamp: authored,61 timezoneOffset: 0,62 },63 committer: {64 email: "committer@example.com",65 name: "Committer",66 timestamp: committed,67 timezoneOffset: -120,68 },69 message: "timed\n",70 parent: [parent],71 tree: commit.tree,72 },73 })74 );7576 return CommitSha.make(oid);77 });7879/** When a commit was written and committed, as a store read it. */80const times = (commit: Commit) => ({81 authoredAt: commit.authoredAt,82 committedAt: commit.committedAt,83});8485/** An annotated tag object naming `commit`; its id, as a push sends it. */86const annotatedTag = (source: Source, name: string, commit: CommitSha) =>87 Effect.map(88 Effect.promise(() =>89 writeTag({90 ...source,91 tag: {92 message: `${name}\n`,93 object: commit,94 tag: name,95 tagger: {96 email: "tagger@example.com",97 name: "Tagger",98 timestamp: committed,99 timezoneOffset: 0,100 },101 type: "commit",102 },103 })104 ),105 // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.106 (oid) => CommitSha.make(oid)107 );108109/** What an adapter's run of the suite adds to the shared cases. */110export interface RepoHostSuite {111 /**112 * The URL `importFrom` reads the repo `name` from, as this adapter's
261 unmodified lines
374 ).toStrictEqual([]);375 }).pipe(Effect.provide(host))376 );377378 it.effect("reads when a commit was written and when committed", () =>379 Effect.gen(function* () {380 const repos = yield* RepoHost;381 const client = yield* gitClient(memoryFs());382 const first = yield* client.commit("first", [["a", "1"]]);383 const timed = yield* timedCommit(client.source, first);384 const name = RepoName.make("times");385386 yield* repos.create(name);387 yield* repos.push(name, client.source, [388 { from: Option.none(), ref: main, to: timed },389 ]);390391 expect(392 Option.map(yield* repos.readCommit(name, timed), times)393 ).toStrictEqual(394 Option.some({ authoredAt: authored, committedAt: committed })395 );396 expect(397 (yield* repos.log(398 name,399 Revision.Branch({ name: BranchName.make("main") }),400 10401 )).map(times)402 ).toStrictEqual([403 { authoredAt: authored, committedAt: committed },404 { authoredAt: 1_791_300_000, committedAt: 1_791_300_000 },405 ]);406 }).pipe(Effect.provide(host))407 );408409 it.effect("logs from an offset, skipping the newest commits", () =>410 Effect.gen(function* () {411 const repos = yield* RepoHost;412 const client = yield* gitClient(memoryFs());413 const first = yield* client.commit("first", [["a", "1"]]);414 const second = yield* client.commit("second", [["a", "2"]], [first]);415 const third = yield* client.commit("third", [["a", "3"]], [second]);416 const name = RepoName.make("offsets");417418 yield* repos.create(name);419 yield* repos.push(name, client.source, [420 { from: Option.none(), ref: main, to: third },421 ]);422423 const tip = Revision.Branch({ name: BranchName.make("main") });424425 const shas = (limit: number, offset?: number) =>426 repos427 .log(name, tip, limit, offset)428 .pipe(Effect.map((commits) => commits.map(({ sha }) => sha)));429430 expect(yield* shas(10, 1)).toStrictEqual([second, first]);431 expect(yield* shas(1, 1)).toStrictEqual([second]);432 expect(yield* shas(10, 3)).toStrictEqual([]);433 expect(yield* shas(10, 0)).toStrictEqual([third, second, first]);434 }).pipe(Effect.provide(host))435 );436437 // An annotated tag names a tag object, which no commit read can read:438 // `tags` peels each to its commit, while `refs` keeps what git lists.439 it.effect("lists every tag peeled to its commit", () =>440 Effect.gen(function* () {441 const repos = yield* RepoHost;442 const client = yield* gitClient(memoryFs());443 const first = yield* client.commit("first", [["a", "1"]]);444 const second = yield* client.commit("second", [["a", "2"]], [first]);445 const annotated = yield* annotatedTag(client.source, "v1.0.0", first);446 const name = RepoName.make("tagged");447 const v1 = RefName.make("refs/tags/v1.0.0");448 const light = RefName.make("refs/tags/light");449450 yield* repos.create(name);451 yield* repos.push(name, client.source, [452 { from: Option.none(), ref: main, to: second },453 ]);454 expect(yield* repos.tags(name)).toStrictEqual([]);455 yield* repos.push(name, client.source, [456 { from: Option.none(), ref: v1, to: annotated },457 ]);458 yield* repos.push(name, client.source, [459 { from: Option.none(), ref: light, to: second },460 ]);461462 const tags = yield* repos.tags(name);463464 expect(465 tags.toSorted((one, other) => one.name.localeCompare(other.name))466 ).toStrictEqual([467 { name: light, sha: second },468 { name: v1, sha: first },469 ]);470 expect((yield* repos.refs(name)).get(v1)).toBe(annotated);471 expect(472 yield* Effect.forEach(tags, ({ sha }) =>473 Effect.map(repos.readCommit(name, sha), Option.isSome)474 )475 ).toStrictEqual([true, true]);476 expect(477 yield* Effect.flip(repos.tags(RepoName.make("missing")))478 ).toStrictEqual(new RepoNotFound({ name: RepoName.make("missing") }));479 }).pipe(Effect.provide(host))480 );481482 // Artifacts refuses `--atomic`, so landing pushes main by itself and483 // treats each ref's outcome on its own.484 it.effect("applies each ref's compare-and-swap on its own", () =>485 Effect.gen(function* () {
190 unmodified lines
modified:packages/artifacts/test/rest.test.ts+2 added
653 unmodified lines
654655 expect(commit).toStrictEqual(656 Option.some({657 author: { email: "answerer@example.com", name: "Answerer" },658 authoredAt: 1_791_300_000,659 committedAt: 1_791_300_000,660 committer: { email: "answerer@example.com", name: "Answerer" },661 message: "first",662 parents: [],663 sha: first,
37 unmodified lines
modified:packages/config/test/scripts.test.ts+21 added-13 removed
1/**2 * The demo-readiness scripts: a maintainer types `bun run swarm`,3 * `bun run seed` or `bun run release`, and each runs one entry file that3 * `bun run seed`, `bun run release` or `bun run import-examples`, and each4 * runs one entry file that5 * exists, so the work that builds them fills an entry without touching a6 * root file.7 */8import { NodeServices } from "@effect/platform-node";
28 unmodified lines
37 };38 });3940describe("the demo-readiness scripts", () => {40 it.live("swarm, seed and release each run one entry file that exists", () =>41 Effect.gen(function* () {42 expect({43 release: yield* entryOf("release"),44 seed: yield* entryOf("seed"),45 swarm: yield* entryOf("swarm"),46 }).toStrictEqual({47 release: { command: "bun scripts/release.ts", exists: true },48 seed: { command: "bun scripts/seed.ts", exists: true },49 swarm: { command: "bun scripts/swarm.ts", exists: true },50 });51 }).pipe(Effect.provide(NodeServices.layer))41 it.live(42 "swarm, seed, release and import-examples each run one entry file that exists",43 () =>44 Effect.gen(function* () {45 expect({46 "import-examples": yield* entryOf("import-examples"),47 release: yield* entryOf("release"),48 seed: yield* entryOf("seed"),49 swarm: yield* entryOf("swarm"),50 }).toStrictEqual({51 "import-examples": {52 command: "bun scripts/import-examples.ts",53 exists: true,54 },55 release: { command: "bun scripts/release.ts", exists: true },56 seed: { command: "bun scripts/seed.ts", exists: true },57 swarm: { command: "bun scripts/swarm.ts", exists: true },58 });59 }).pipe(Effect.provide(NodeServices.layer))60 );61});
modified:packages/config/test/web-wiring.test.ts+14 added-1 removed
18 unmodified lines
19 stages,20 subdomainFile,21 WorkersDev,22} from "../../../infra/stages.ts";23import { workers } from "../../../scripts/startup-budget.ts";23import { budgets, workers } from "../../../scripts/startup-budget.ts";24import { repoRoot } from "./root.ts";2526/** A file under the repo root, as text, once its presence is asserted. */27const presentText = (file: string) =>
190 unmodified lines
218describe("the byte alarm", () => {219 it("measures the web Worker", () => {220 expect(workers.map(({ dir }) => dir)).toContain("apps/web");221 });222223 // Each Worker grows on its own, so each has limits of its own: the224 // platform's at the ceiling the code browser and drafting land under.225 it("holds each Worker it measures to limits of its own", () => {226 expect(budgets).toStrictEqual({227 "apps/platform": { entry: 1_900_000, javascript: 2_500_000 },228 "apps/sandbox": { entry: 1_665_000, javascript: 2_500_000 },229 "apps/web": { entry: 1_665_000, javascript: 2_500_000 },230 });231 expect(Object.keys(budgets).toSorted()).toStrictEqual(232 workers.map(({ dir }) => dir).toSorted()233 );234 });235});236237describe("the examples", () => {238 it.effect(
18 unmodified lines
added:packages/drafting/src/drafter/memory.ts+49 added
1/**2 * The `Drafter` in memory: each call takes the next answer from a script3 * (a drafted ask, or the failure to give), and every input is kept for the4 * test to read (`DraftsAsked`). A call past the script's end is the test's5 * defect.6 */7import { Context, Effect, Layer, Ref, Schema } from "effect";89import { DraftFailed } from "../drafted.ts";10import type { DraftedAsk, DraftInput } from "../drafted.ts";11import { Drafter } from "../drafter.ts";1213const isFailure = Schema.is(DraftFailed);1415/** What the memory drafter was asked, in order. */16export class DraftsAsked extends Context.Service<17 DraftsAsked,18 { readonly inputs: Effect.Effect<readonly DraftInput[]> }19>()("drafting/DraftsAsked") {}2021/** A drafter that answers `script` in order, one entry per call. */22export const DrafterMemory = (23 script: readonly (DraftedAsk | DraftFailed)[]24): Layer.Layer<Drafter | DraftsAsked> =>25 Layer.effectContext(26 Effect.gen(function* () {27 const left = yield* Ref.make(script);28 const asked = yield* Ref.make<readonly DraftInput[]>([]);2930 const draft = (input: DraftInput) =>31 Effect.gen(function* () {32 yield* Ref.update(asked, (all) => [...all, input]);3334 const [next, ...rest] = yield* Ref.get(left);3536 if (next === undefined) {37 return yield* Effect.die("the memory drafter's script ran out");38 }3940 yield* Ref.set(left, rest);4142 return isFailure(next) ? yield* next : next;43 });4445 return Context.make(Drafter, Drafter.of({ draft })).pipe(46 Context.add(DraftsAsked, DraftsAsked.of({ inputs: Ref.get(asked) }))47 );48 })49 );
added:packages/drafting/src/drafted.ts+88 added
1/**2 * What drafting reads and writes. The model returns `DraftedAsk`, fields3 * only: code renders the ask file from them, so only the test file is the4 * model's own text. `DraftContext` is what it reads, from the canonical5 * repo at the landed commit (never a layer's), and `DraftInput` one6 * attempt's question. `DraftFailed` stays inside the run: it is no public7 * refusal.8 */9import { AtLeastOne } from "@repo/protocol/domain/common";10import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";11import { Schema } from "effect";1213/** A string the model writes, bounded so no reply fills the Worker. */14const Text = Schema.NonEmptyString.check(Schema.isMaxLength(4000));1516/** One ask, drafted: only `fix` asks are drafted. */17export const DraftedAsk = Schema.Struct({18 context: Schema.optionalKey(Schema.Array(Text)),19 current: Schema.optionalKey(Text),20 /** Becomes `<config>/asks/<id>.ask.ts`. */21 id: AskId,22 kind: Schema.Literal("fix"),23 outOfScope: Schema.optionalKey(Schema.Array(Text)),24 /** Shown to the decider as evidence; never landed. */25 rationale: Schema.String.check(Schema.isMaxLength(4000)),26 /** The files an answer may change. */27 territory: Schema.NonEmptyArray(RepoPath),28 /** The ask's check: a test that fails on main by an assertion. */29 test: Schema.Struct({30 path: RepoPath,31 source: Schema.NonEmptyString.check(Schema.isMaxLength(100_000)),32 }),33 /** One testable sentence. */34 want: Text,35});3637export type DraftedAsk = typeof DraftedAsk.Type;3839/** One file the drafter reads, as text. */40export const ContextFile = Schema.Struct({41 content: Schema.String,42 path: RepoPath,43});4445export type ContextFile = typeof ContextFile.Type;4647/**48 * What a draft reads: the project's public policy as a short digest, and49 * the files picked from its canonical tree at the landed commit.50 */51export const DraftContext = Schema.Struct({52 at: LandedSha,53 files: Schema.Array(ContextFile),54 policy: Schema.String,55 project: ProjectName,56});5758export type DraftContext = typeof DraftContext.Type;5960/** One attempt's question: the want, what it reads, and what went wrong before. */61export const DraftInput = Schema.Struct({62 attempt: AtLeastOne,63 context: DraftContext,64 /** The last attempt's refusal and its output's tail, for the next to mend. */65 feedback: Schema.optionalKey(Schema.String),66 /** A decider's or the proposer's note on what to do differently. */67 note: Schema.optionalKey(Schema.String),68 territory: Schema.optionalKey(Schema.NonEmptyString),69 want: Schema.NonEmptyString,70});7172export type DraftInput = typeof DraftInput.Type;7374/**75 * The model gave no draft: its reply was no JSON, or not the schema's, it76 * was rate-limited, or it failed.77 */78export class DraftFailed extends Schema.TaggedError<DraftFailed>()(79 "DraftFailed",80 {81 reason: Schema.Literals([82 "unparseable",83 "schema",84 "rate-limited",85 "model-error",86 ]),87 }88) {}
added:packages/drafting/src/drafter.ts+19 added
1/**2 * The `Drafter` port: the platform's agent that drafts an ask from a want.3 * Adapters: `/memory` (a scripted queue, for tests and the web's dev world)4 * and `/binding` (Workers AI through the `AI` binding).5 */6import { Context } from "effect";7import type { Effect } from "effect";89import type { DraftFailed, DraftedAsk, DraftInput } from "./drafted.ts";1011export class Drafter extends Context.Service<12 Drafter,13 {14 /** One attempt: the drafted ask's fields, or why the model gave none. */15 readonly draft: (16 input: DraftInput17 ) => Effect.Effect<DraftedAsk, DraftFailed>;18 }19>()("drafting/Drafter") {}
added:packages/drafting/test/memory.test.ts+57 added
1import { describe, expect, it } from "@effect/vitest";2import { AskId, LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";3import { Effect } from "effect";45import { DraftFailed } from "../src/drafted.ts";6import type { DraftedAsk, DraftInput } from "../src/drafted.ts";7import { Drafter } from "../src/drafter.ts";8import { DrafterMemory, DraftsAsked } from "../src/drafter/memory.ts";910const drafted: DraftedAsk = {11 id: AskId.make("iso-week"),12 kind: "fix",13 rationale: "The parser has no week dates.",14 territory: [RepoPath.make("src/parse.ts")],15 test: {16 path: RepoPath.make("test/iso-week.test.ts"),17 source: 'it("parses", () => expect(parse("2026-W01")).toBe(1));\n',18 },19 want: "An ISO week date parses to the Monday of that week.",20};2122const input = (attempt: number): DraftInput => ({23 attempt,24 context: {25 at: LandedSha.make("4".repeat(40)),26 files: [],27 policy: "kinds: fix",28 project: ProjectName.make("datekit"),29 },30 want: "Parse ISO week dates.",31});3233describe("the memory drafter", () => {34 it.effect(35 "answers its script in order, failures too, and keeps every input",36 () =>37 Effect.gen(function* () {38 const drafter = yield* Drafter;39 const failed = new DraftFailed({ reason: "schema" });4041 const first = yield* Effect.flip(drafter.draft(input(1)));42 const second = yield* drafter.draft(input(2));4344 expect(first).toStrictEqual(failed);45 expect(second).toStrictEqual(drafted);46 expect(47 (yield* DraftsAsked.use(({ inputs }) => inputs)).map(48 ({ attempt }) => attempt49 )50 ).toStrictEqual([1, 2]);51 }).pipe(52 Effect.provide(53 DrafterMemory([new DraftFailed({ reason: "schema" }), drafted])54 )55 )56 );57});
added:packages/drafting/package.json+28 added
1{2 "name": "@repo/drafting",3 "private": true,4 "type": "module",5 "exports": {6 "./*": "./src/*.ts"7 },8 "scripts": {9 "typecheck": "tsc --noEmit -p tsconfig.json",10 "test": "vitest run"11 },12 "dependencies": {13 "@repo/artifacts": "workspace:*",14 "@repo/brand": "workspace:*",15 "@repo/project": "workspace:*",16 "@repo/protocol": "workspace:*",17 "effect": "catalog:"18 },19 "devDependencies": {20 "@cloudflare/workers-types": "5.20261006.1",21 "@effect/vitest": "catalog:",22 "@repo/config": "workspace:*",23 "@repo/rules": "workspace:*",24 "@repo/testkit": "workspace:*",25 "typescript": "catalog:",26 "vitest": "catalog:"27 }28}
added:packages/drafting/tsconfig.json+8 added
1{2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "allowImportingTsExtensions": true,5 "types": ["@cloudflare/workers-types"]6 },7 "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]8}
added:packages/drafting/vitest.config.ts+1 added
1export { preset as default } from "@repo/config/vitest";
added:packages/project/src/code/cache.ts+24 added
1/**2 * The code reads' cache: what an object id names never changes, so a read3 * keyed by `<repo>:<kind>:<object id>` (a tree, a blob, a commit, a commit's4 * diff, a blame at a commit) is read once. A `Context.Reference` whose5 * default caches nothing, so every host composes before one is given; the6 * platform gives one held in a layer (no module-level state, principle 6).7 * `main` is never a key: it resolves through the project's record on every8 * call.9 */10import { Context } from "effect";11import type { Effect } from "effect";1213/** The code reads, each kept by its key once read. */14export interface CodeReads {15 /** `read`, or what it gave before for `key`. */16 readonly through: <A, E, R>(17 key: string,18 read: Effect.Effect<A, E, R>19 ) => Effect.Effect<A, E, R>;20}2122export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {23 defaultValue: () => ({ through: (_key, read) => read }),24});
modified:packages/project/src/projection-d1/projection.ts+1 added
177 unmodified lines
178 sql`UPDATE projects SET posture = ${entry.to}179 WHERE project = ${project} AND ${next}`,180 ]181 : [],182 ProposalDrafted: () => [],183 ProposalOpened: () => [],184 Pushed: () => [],185 Released: ({ ask }) => [claims(ask, -1)],186 Warned: () => [],
78 unmodified lines
added:packages/project/src/code.ts+122 added
1/**2 * A project's code as its readers browse it, read from its canonical repo3 * only (no payload names a repo, so no fork or layer can be named, principle4 * 7): refs, trees, every path, files, the first-parent log, a commit's diff5 * and why each line is there. Host-free: both the platform's handlers and6 * the web's dev world call these with the `RepoHost` they run on, and7 * consult the project's record only for main's landed commit, its landings8 * and its forks (`CodeProject`). Reads by object id go through `CodeCache`.9 *10 * Stubs until 903 (every read but `whyOf`) and 912 (`whyOf`) land; the11 * signatures are final.12 */13import type { RepoHost } from "@repo/artifacts/repo-host";14import type {15 CommitDiff,16 CommitView,17 ForkRef,18 PathList,19 RefsView,20 Rev,21 FileView,22 TreeListing,23 WhyView,24} from "@repo/protocol/domain/code";25import type { LandingView } from "@repo/protocol/domain/landing";26import { RepoName } from "@repo/protocol/ids";27import type {28 CommitSha,29 LandedSha,30 ProjectName,31 RepoPath,32} from "@repo/protocol/ids";33import type {34 UnknownCommit,35 UnknownPath,36 UnknownRevision,37} from "@repo/protocol/refusal";38import { Effect, Option } from "effect";3940import type { ProjectApi } from "./project.ts";4142/** What the code reads take from a project's record, beside its canonical repo. */43export interface CodeProject {44 /** The project's canonical repo: never a fork's or a layer's. */45 readonly repo: RepoName;46 /** Main's landed commit; none before the first push. */47 readonly head: Effect.Effect<Option.Option<LandedSha>>;48 /** The landings among `shas`, so a forged trailer never reads as one. */49 readonly landings: (50 shas: readonly CommitSha[]51 ) => Effect.Effect<readonly LandingView[]>;52 readonly forks: Effect.Effect<readonly ForkRef[]>;53}5455/** The code reads' view of `project`, through its `ProjectApi`. */56export const codeProjectOf = (57 api: ProjectApi,58 project: ProjectName59): CodeProject => ({60 forks: api.forks(),61 head: Effect.map(api.head(), ({ landed }) => Option.fromUndefinedOr(landed)),62 landings: api.landings,63 repo: RepoName.make(project),64});6566const notBuilt = (issue: string) => Effect.die(`not built: ${issue}`);6768/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */69export const refsOf = (70 _project: CodeProject71): Effect.Effect<RefsView, never, RepoHost> => notBuilt("903");7273/** One folder at `at` (main when none), folders first, with its README. */74export const treeOf = (75 _project: CodeProject,76 _at: Option.Option<Rev>,77 _path: Option.Option<RepoPath>78): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>79 notBuilt("903");8081/** Every file path at `at`, up to the cap. */82export const pathsOf = (83 _project: CodeProject,84 _at: Option.Option<Rev>85): Effect.Effect<PathList, UnknownRevision, RepoHost> => notBuilt("903");8687/** One file at `at`: its text, or that it is binary or too large. */88export const fileOf = (89 _project: CodeProject,90 _at: Option.Option<Rev>,91 _path: RepoPath92): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>93 notBuilt("903");9495/** A page of first-parent commits from `at`, each landing with its record. */96export const logOf = (97 _project: CodeProject,98 _input: {99 readonly at: Option.Option<Rev>;100 readonly path: Option.Option<RepoPath>;101 readonly from: number;102 readonly limit: number;103 }104): Effect.Effect<105 { readonly commits: readonly CommitView[]; readonly next?: number },106 UnknownRevision,107 RepoHost108> => notBuilt("903");109110/** One commit and the files it changed against its first parent. */111export const commitOf = (112 _project: CodeProject,113 _sha: CommitSha114): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> => notBuilt("903");115116/** Why each line of a file at `at` is there. */117export const whyOf = (118 _project: CodeProject,119 _at: Option.Option<Rev>,120 _path: RepoPath121): Effect.Effect<WhyView, UnknownRevision | UnknownPath, RepoHost> =>122 notBuilt("912");
modified:packages/project/src/deciders.ts+2 added
227 unmodified lines
228 /** A proposal for a new ask, and the decision that puts it to its deciders. */229 readonly proposeAsk: (230 caller: Person,231 input: {232 /** Have the platform's agent draft the ask's files. */233 readonly draft?: true;234 readonly files?: Array.NonEmptyReadonlyArray<ComposedFile>;235 readonly sealed?: { readonly head: CommitSha };236 readonly territory?: string;237 readonly want: string;
1850 unmodified lines
modified:packages/project/src/project.ts+155 added-11 removed
61 unmodified lines
62import {63 Claim as ClaimContract,64 Credits,65 Decide,66 DraftAsk,67 EnvSchemaOf,68 EvidenceOf,69 Finish,70 FlagAsk,
7 unmodified lines
78 ProposeAsk,79 Release,80 SetEnv,81 ShowAsk,82 ShowProposal,83 Status,84 SubmitAnswer,85 TodayOf,86 VerdictOf,
7 unmodified lines
94import type { AnswerView, LaneResult } from "@repo/protocol/domain/answer";95import type { Ask, AskListing } from "@repo/protocol/domain/ask";96import { CheckSpec } from "@repo/protocol/domain/check";97import type { ClaimView } from "@repo/protocol/domain/claim";98import { ForkRef } from "@repo/protocol/domain/code";99import { RefNameText } from "@repo/protocol/domain/common";97import type { Evidence } from "@repo/protocol/domain/common";100import type { ConfigFile, Evidence } from "@repo/protocol/domain/common";101import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";102import { DecisionSubject } from "@repo/protocol/domain/decision";103import type { Choice, Decision } from "@repo/protocol/domain/decision";104import { ProjectEvent } from "@repo/protocol/domain/event";105import type { AskKind } from "@repo/protocol/domain/kind";103import type { LandingView } from "@repo/protocol/domain/landing";106import { LandingView } from "@repo/protocol/domain/landing";107import { Outcome } from "@repo/protocol/domain/outcome";108import type { StageName } from "@repo/protocol/domain/outcome";106import { Policy } from "@repo/protocol/domain/policy";109import { Policy, PublicPolicy } from "@repo/protocol/domain/policy";110import type { Proposal } from "@repo/protocol/domain/proposal";111import {112 AskId,113 CommitSha,114 EnvKey,115 Handle,116 LandedSha,117 LayerName,118 ProposalId,119 RepoName,120 RepoPath,121 RequestId,122 TreeSha,123 sameHandle,124} from "@repo/protocol/ids";121import type {122 DecisionId,123 LaneName,124 ProjectName,125 ProposalId,126} from "@repo/protocol/ids";125import type { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";126import { Person, Principal } from "@repo/protocol/principal";127import {128 AskFull,129 DirectPush,
16 unmodified lines
146 AskBlocked,147 CapReached,148 ClaimLapsed,149 Denounced,150 DraftInProgress,151 ProposalClosed,152 UnknownProposal,153 OutOfScope,154 PrivatePathInPublicTree,155 ReachedInternals,156 RepoBusy,
226 unmodified lines
383 readonly landing: (384 caller: Principal,385 sha: CommitSha386 ) => Effect.Effect<{ readonly landing: LandingView }, UnknownCommit>;387 /** Where main has landed: none before the first push. */388 readonly head: () => Effect.Effect<{ readonly landed?: LandedSha }>;389 /**390 * The landings among `shas` (at most `MAX_LANDINGS`), in their order: a391 * commit the platform did not land, imported history among them, has none.392 */393 readonly landings: (394 shas: readonly CommitSha[]395 ) => Effect.Effect<readonly LandingView[]>;396 /** Every claim's fork, with its ask, claimant and the claim's state. */397 readonly forks: () => Effect.Effect<readonly ForkRef[]>;398 /**399 * The policy at the landed commit as anyone may read it (no layers, no400 * function-valued rules, no asks); none until it has evaluated.401 */402 readonly policy: () => Effect.Effect<Option.Option<PublicPolicy>>;403 /**404 * The public face of a proposal: its state, its draft's, and the files it405 * holds until a decider accepts it.406 */407 readonly showProposal: (408 caller: Principal,409 proposal: ProposalId410 ) => Effect.Effect<411 { readonly files: readonly ConfigFile[]; readonly proposal: Proposal },412 UnknownProposal413 >;414 /**415 * Has the platform's agent draft an open proposal's ask, or draft it416 * again with a note, for its proposer or a decider of its paths.417 */418 readonly draftAsk: (419 caller: Person,420 input: { readonly note?: string; readonly proposal: ProposalId }421 ) => Effect.Effect<422 { readonly proposal: Proposal },423 UnknownProposal | ProposalClosed | NotDecider | DraftInProgress | CapReached424 >;425 /**426 * The log a failing lane left, by the name its verdict gives it427 * (`LaneResult.logRef`), for the project's deciders and the claimant428 * of the answer the name points at. A name `logRefOf` never makes, or one429 * that points at another project, is `UnknownProject` for anyone; past
154 unmodified lines
584 input: { readonly text: string } | { readonly blob: Uint8Array }585 ) => Effect.Effect<Option.Option<EnvKey>>;586}587588/** The most commits one `landings` call looks up: a log page's, or a blame's batch. */589export const MAX_LANDINGS = 100;590591/** The schemas one method's arguments (in order), success and failure cross a boundary with. */592export interface MethodSchema {593 readonly args: readonly Schema.Top[];594 readonly error: Schema.Top;
41 unmodified lines
636 args: [Person, Decide.payloadSchema.mapFields(Struct.omit(["project"]))],637 error: Decide.errorSchema,638 success: Decide.successSchema,639 },640 draftAsk: {641 args: [Person, DraftAsk.payloadSchema.mapFields(Struct.omit(["project"]))],642 error: DraftAsk.errorSchema,643 success: DraftAsk.successSchema,644 },645 events: {646 args: [Schema.Int, Schema.Int],647 error: Schema.Never,648 success: Schema.Array(
24 unmodified lines
673 args: [Person],674 error: Fork.errorSchema,675 success: Fork.successSchema,676 },677 forks: { args: [], error: Schema.Never, success: Schema.Array(ForkRef) },678 head: {679 args: [],680 error: Schema.Never,681 success: Schema.Struct({ landed: Schema.optionalKey(LandedSha) }),682 },683 heldBackJob: {684 args: [RequestId],685 error: Schema.Never,686 success: Schema.Option(HeldBackJob),
15 unmodified lines
702 args: [Principal, CommitSha],703 error: LandingOf.errorSchema,704 success: LandingOf.successSchema,705 },706 landings: {707 args: [Schema.Array(CommitSha).check(Schema.isMaxLength(MAX_LANDINGS))],708 error: Schema.Never,709 success: Schema.Array(LandingView),710 },711 layerAccess: {712 args: [Principal, LayerName],713 error: Schema.Never,714 success: Schema.Option(LayerAccess),
21 unmodified lines
736 ],737 error: OpenAsk.errorSchema,738 success: OpenAsk.successSchema,739 },740 policy: {741 args: [],742 error: Schema.Never,743 success: Schema.Option(PublicPolicy),744 },745 proposeAsk: {746 args: [747 Person,748 // The check reads only `draft`, `files` and `sealed`, which it keeps.684 ProposeAsk.payloadSchema.mapFields(Struct.omit(["project"])),749 ProposeAsk.payloadSchema.mapFields(Struct.omit(["project"]), {750 unsafePreserveChecks: true,751 }),752 ],753 error: ProposeAsk.errorSchema,754 success: ProposeAsk.successSchema,755 },
54 unmodified lines
810 args: [Principal, AskId],811 error: ShowAsk.errorSchema,812 success: ShowAsk.successSchema,813 },814 showProposal: {815 args: [Principal, ProposalId],816 error: ShowProposal.errorSchema,817 success: ShowProposal.successSchema,818 },819 status: {820 args: [Person],821 error: Status.errorSchema,822 // The contract adds the caller's handle at the platform's edge; a project
120 unmodified lines
943 Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))944 )945 );946947/** A policy as anyone may read it: without its layers, function-valued rules and asks. */948const publicPolicy = (policy: Policy): PublicPolicy =>949 Struct.omit(policy, ["asks", "functions", "visibility"]);950951/** A claim's fork, as the refs page lists it. */952const listedFork = (claim: Live, state: ClaimView["state"]) =>953 Option.some<ForkRef>({954 ask: claim.ask,955 handle: claim.claimant,956 kind: "claim",957 repo: claim.fork,958 state,959 });960961/** Where a claim stands, as its fork's listing says it; an open ask has no fork. */962const forkOf = (state: ClaimState): Option.Option<ForkRef> =>963 ClaimState.match(state, {964 Answered: (claim) => listedFork(claim, "answered"),965 Lapsed: (claim) => listedFork(claim, "lapsed"),966 Live: (claim) => listedFork(claim, "live"),967 Open: () => Option.none(),968 Released: (claim) => listedFork(claim, "released"),969 Warned: (claim) => listedFork(claim, "warned"),970 });971972/** What a stub answers until the issue that builds it lands. */973const notBuilt = (issue: string) => Effect.die(`not built: ${issue}`);974975/** The most of a lane's log `evidence` gives back: its last 256 KiB. */976const EVIDENCE_TAIL = 256 * 1024;977978/** Whether a UTF-8 byte starts a character: it is no continuation byte (`10xxxxxx`). */
4034 unmodified lines
5013 MethodSchemas.decide,5014 [caller, input],5015 decided.decide(api, caller, input)5016 ),5017 draftAsk: (caller, input) =>5018 checked(MethodSchemas.draftAsk, [caller, input], notBuilt("909")),5019 events: (since, limit) =>5020 checked(5021 MethodSchemas.events,5022 [since, limit],
28 unmodified lines
5051 decided.flagAsk(api, caller, input)5052 ),5053 fork: (caller) =>5054 checked(MethodSchemas.fork, [caller], decided.fork(api, caller)),5055 forks: () =>5056 checked(5057 MethodSchemas.forks,5058 [],5059 Effect.map(hydrate, (h) =>5060 Array.getSomes(h.claims.map(({ state }) => forkOf(state)))5061 )5062 ),5063 head: () =>5064 checked(5065 MethodSchemas.head,5066 [],5067 Effect.map(hydrate, (h) =>5068 Option.match(5069 Option.flatMapNullishOr(h.project, ({ landed }) => landed),5070 { onNone: () => ({}), onSome: (landed) => ({ landed }) }5071 )5072 )5073 ),5074 heldBackJob: (requestId) =>5075 checked(5076 MethodSchemas.heldBackJob,5077 [requestId],
21 unmodified lines
5099 onSome: (landing) => Effect.succeed({ landing }),5100 })5101 )5102 ),5103 landings: (shas) =>5104 checked(5105 MethodSchemas.landings,5106 [shas],5107 Effect.map(5108 Effect.forEach(Array.dedupe(shas), (sha) => store.landing(sha)),5109 Array.getSomes5110 )5111 ),5112 layerAccess: (caller, layer) =>5113 checked(5114 MethodSchemas.layerAccess,5115 [caller, layer],
25 unmodified lines
5141 MethodSchemas.openAsk,5142 [caller, input],5143 write(api, openBody(caller, input))5144 ),5145 policy: () =>5146 checked(5147 MethodSchemas.policy,5148 [],5149 Effect.map(hydrate, (h) => Option.map(h.policy, publicPolicy))5150 ),5151 proposeAsk: (caller, input) =>5152 checked(5153 MethodSchemas.proposeAsk,5154 [caller, input],5155 input.draft === true5156 ? notBuilt("909")5019 decided.proposeAsk(api, caller, input)5157 : decided.proposeAsk(api, caller, input)5158 ),5159 recordAdmission: (input) =>5160 checked(5161 MethodSchemas.recordAdmission,
77 unmodified lines
5239 onSome: (ask) => Effect.succeed({ ask, brief: briefOf(ask) }),5240 })5241 )5242 ),5243 showProposal: (caller, proposal) =>5244 checked(5245 MethodSchemas.showProposal,5246 [caller, proposal],5247 notBuilt("909")5248 ),5249 status: (caller) =>5250 checked(MethodSchemas.status, [caller], statusOf(caller)),5251 submitAnswer: (caller, input) =>5252 checked(
18 unmodified lines
added:packages/project/src/repo-names.ts+87 added
1/**2 * What a repo's name says it is: a project's canonical repo3 * `<project>`, a claim's fork `<project>--<ask>--<handle>`, or a person's4 * working fork `<project>--me--<handle>`, each handle in lowercase. `--`5 * occurs in no project or ask name, so a name splits back into its parts.6 * Pure: the platform's gateway, handlers and OnPush read names with it, and7 * a project lists its forks by it.8 */9import { AskId, Handle, ProjectName, RepoName } from "@repo/protocol/ids";10import { Data, Option, Schema } from "effect";1112import { forkName } from "./claim.ts";1314/** What a repo is, read from its name alone. */15export type RepoKind =16 | { readonly _tag: "Canonical"; readonly project: ProjectName }17 | {18 readonly _tag: "ClaimFork";19 readonly project: ProjectName;20 readonly ask: AskId;21 /** As the name spells it: in lowercase. */22 readonly handle: Handle;23 }24 | {25 readonly _tag: "WorkingFork";26 readonly project: ProjectName;27 /** As the name spells it: in lowercase. */28 readonly handle: Handle;29 }30 | { readonly _tag: "Unknown" };3132export const RepoKind = Data.taggedEnum<RepoKind>();3334const asProject = Schema.decodeOption(ProjectName);3536const asAsk = Schema.decodeOption(AskId);3738const asHandle = Schema.decodeOption(Handle);3940/** The word that names a working fork where a claim's fork names its ask. */41const WORKING = "me";4243/** What `name` says it is; `Unknown` for any name the platform never makes. */44export const repoKind = (name: RepoName): RepoKind => {45 const [first = "", second, third, ...rest] = name.split("--");4647 const kind = Option.flatMap(48 asProject(first),49 (project): Option.Option<RepoKind> => {50 if (second === undefined) {51 return Option.some(RepoKind.Canonical({ project }));52 }5354 if (third === undefined || rest.length > 0) {55 return Option.none();56 }5758 const handle = Option.filter(59 asHandle(third),60 (spelled) => spelled === spelled.toLowerCase()61 );6263 return second === WORKING64 ? Option.map(handle, (owner) =>65 RepoKind.WorkingFork({ handle: owner, project })66 )67 : Option.map(68 Option.all({ ask: asAsk(second), handle }),69 ({ ask, handle: claimant }) =>70 RepoKind.ClaimFork({ ask, handle: claimant, project })71 );72 }73 );7475 return Option.getOrElse(kind, () => RepoKind.Unknown());76};7778/** A claim's fork: `<project>--<ask>--<handle in lowercase>`. */79export const claimForkName: (80 project: ProjectName,81 ask: AskId,82 handle: Handle83) => RepoName = forkName;8485/** A person's working fork: `<project>--me--<handle in lowercase>`. */86export const workingForkName = (project: ProjectName, handle: Handle) =>87 RepoName.make(`${project}--${WORKING}--${handle.toLowerCase()}`);
added:packages/project/test/code-facade.test.ts+110 added
1/**2 * The code façade both handler files call: a project's code read from its3 * canonical repo alone, with main resolved through the project's record.4 * Until 903 and 912 land, each read names the issue that builds it.5 */6import { describe, expect, it } from "@effect/vitest";7import { RepoHost } from "@repo/artifacts/repo-host";8import type { ProjectApi } from "@repo/project/project";9import {10 CommitSha,11 LandedSha,12 ProjectName,13 RepoPath,14} from "@repo/protocol/ids";15import { untouchable } from "@repo/testkit/untouchable";16import { Cause, Effect, Exit, Option } from "effect";1718import {19 codeProjectOf,20 commitOf,21 fileOf,22 logOf,23 pathsOf,24 refsOf,25 treeOf,26 whyOf,27} from "../src/code.ts";28import { CodeCache } from "../src/code/cache.ts";2930const project = ProjectName.make("datekit");3132const landed = LandedSha.make("4".repeat(40));3334const sha = CommitSha.make("4".repeat(40));3536const path = RepoPath.make("README.md");3738/** A project's record, as the façade reads it: only these three. */39const api = untouchable<ProjectApi>("ProjectApi", {40 forks: () => Effect.succeed([]),41 head: () => Effect.succeed({ landed }),42 landings: () => Effect.succeed([]),43});4445const code = codeProjectOf(api, project);4647/** What a stub died with, as text; none when it did not die. */48const diedWith = <A, E>(effect: Effect.Effect<A, E, RepoHost>) =>49 Effect.map(50 Effect.exit(51 Effect.provideService(52 effect,53 RepoHost,54 untouchable<RepoHost["Service"]>("RepoHost")55 )56 ),57 (exit) =>58 Exit.isFailure(exit) && Cause.hasDies(exit.cause)59 ? Option.some(String(Cause.squash(exit.cause)))60 : Option.none()61 );6263describe("a project's code, read through the façade", () => {64 it.effect(65 "reads the canonical repo, with main from the project's record",66 () =>67 Effect.gen(function* () {68 expect(code.repo).toBe(project);69 expect(yield* code.head).toStrictEqual(Option.some(landed));70 expect(yield* code.forks).toStrictEqual([]);71 })72 );7374 it.effect("caches nothing until a cache is given", () =>75 Effect.gen(function* () {76 const cache = yield* CodeCache;77 let reads = 0;7879 const read = Effect.sync(() => {80 reads += 1;8182 return reads;83 });8485 expect(yield* cache.through("datekit:tree:x", read)).toBe(1);86 expect(yield* cache.through("datekit:tree:x", read)).toBe(2);87 })88 );8990 it.effect("names the issue that builds each read", () =>91 Effect.gen(function* () {92 const none = Option.none();9394 expect(95 yield* Effect.all([96 diedWith(refsOf(code)),97 diedWith(treeOf(code, none, none)),98 diedWith(pathsOf(code, none)),99 diedWith(fileOf(code, none, path)),100 diedWith(logOf(code, { at: none, from: 0, limit: 30, path: none })),101 diedWith(commitOf(code, sha)),102 diedWith(whyOf(code, none, path)),103 ])104 ).toStrictEqual([105 ...Array.from({ length: 6 }, () => Option.some("not built: 903")),106 Option.some("not built: 912"),107 ]);108 })109 );110});
added:packages/project/test/do-reads.test.ts+151 added
1/**2 * The four small reads the code browser and the people page take from a3 * project's record: where main has landed, which commits are landings,4 * which forks exist, and the policy as anyone may read it.5 */6import { describe, expect, it } from "@effect/vitest";7import { Brand } from "@repo/brand";8import { CheckSpec } from "@repo/protocol/domain/check";9import { CommitSha, LaneName, RepoName, RepoPath } from "@repo/protocol/ids";10import { Person } from "@repo/protocol/principal";11import { advanceTo } from "@repo/testkit/clock";12import type { Files } from "@repo/testkit/git-client";13import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";14import { Array, Effect, Layer, Option } from "effect";1516import { NoEnv } from "../src/env-port.ts";17import { projectService } from "../src/project.ts";18import { NoVisibility } from "../src/visibility-port.ts";19import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";2021const scenario = aProject({ people: ["bob"] }).pipe(22 withVouches(["bob"]),23 withAsk({ id: "parse-iso", territory: "packages/parser" })24);2526const { project } = scenario;2728const repo = RepoName.make(project);2930const alice = Person.make({ handle: scenario.initializer });3132const bob = Person.make({33 handle: scenario.people.get("bob") ?? scenario.initializer,34});3536const start: Files = [37 ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],38 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],39];4041const parseIso = Option.getOrThrow(42 Array.findFirst(scenario.policy.asks, (ask) => ask.id === "parse-iso")43);4445const askFiles = Array.make(46 { content: 'export default "parse-iso";\n', path: parseIso.file },47 {48 content: [49 'import { expect, it } from "vitest";',50 'import { parser } from "../src/parser.ts";',51 "",52 'it("parse-iso", () => {',53 ' expect(parser(" 2026 ")).toStrictEqual("2026");',54 "});",55 "",56 ].join("\n"),57 path: CheckSpec.guards.RedThenGreen(parseIso.check)58 ? parseIso.check.path59 : RepoPath.make(`${Brand.configDir}/checks/parse-iso.test.ts`),60 }61);6263/** A commit that is no landing: imported history, say. */64const imported = CommitSha.make("b".repeat(40));6566const read = Effect.gen(function* () {67 yield* advanceTo("2026-10-07T12:00:00Z");6869 const api = yield* projectService(project);7071 yield* api.initProject(alice, {});7273 const before = {74 forks: yield* api.forks(),75 head: yield* api.head(),76 policy: yield* api.policy(),77 };7879 const first = yield* Pusher.use((pusher) =>80 pusher.push(repo, Option.none(), start, "Start")81 );8283 const { landed: adopted } = yield* api.recordFirstPush(alice, first);84 const composed = yield* composedAt(repo, adopted, askFiles);8586 yield* CheckScript.use((checker) =>87 checker.script(composed, LaneName.make("redThenGreen"), [88 "failed",89 "failed",90 ])91 );9293 const { landed } = yield* api.openAsk(alice, {94 ask: parseIso.id,95 files: askFiles,96 });9798 const { claim } = yield* api.claim(bob, parseIso.id);99100 return {101 adopted,102 after: {103 forks: yield* api.forks(),104 head: yield* api.head(),105 landings: yield* api.landings([landed, imported]),106 policy: yield* api.policy(),107 },108 before,109 claim,110 landed,111 };112});113114const world = Layer.mergeAll(worldOf(scenario, "memory"), NoVisibility, NoEnv);115116describe("a project's reads for its code and its people", () => {117 it.effect(118 "say where main landed, which commits are landings, the forks and the public policy",119 () =>120 Effect.map(read.pipe(Effect.provide(world)), (got) => {121 expect(got.before).toStrictEqual({122 forks: [],123 head: {},124 policy: Option.none(),125 });126 expect(got.after.head).toStrictEqual({ landed: got.landed });127 // The ask's opening landed on the adoption; the other commit is none.128 expect(129 got.after.landings.map(({ parent, sha }) => ({ parent, sha }))130 ).toStrictEqual([{ parent: got.adopted, sha: got.landed }]);131 expect(got.after.forks).toStrictEqual([132 {133 ask: parseIso.id,134 handle: bob.handle,135 kind: "claim",136 repo: got.claim.fork,137 state: "live",138 },139 ]);140141 const policy = Option.getOrThrow(got.after.policy);142143 expect({144 deciders: policy.deciders,145 hidden: ["asks", "functions", "visibility"].filter(146 (key) => key in policy147 ),148 }).toStrictEqual({ deciders: scenario.policy.deciders, hidden: [] });149 })150 );151});
added:packages/protocol/src/domain/code.ts+192 added
1/**2 * A project's code as its readers browse it: refs, trees, files, commits3 * and "why" per line, each read from the project's canonical repo only (no4 * payload names a repo). Every read names the 40-hex commit it resolved5 * to (`at`), so any page can become a permalink.6 */7import { Schema } from "effect";89import {10 AskId,11 BlobSha,12 CommitSha,13 Handle,14 LandedSha,15 ProjectName,16 RepoName,17 RepoPath,18 TreeSha,19} from "../ids.ts";20import { ClaimState } from "./claim.ts";21import { LandingView } from "./landing.ts";2223/** A tag's name, as `refs/tags/<name>` spells it: `v1.2.0`, `@changesets/cli@2.27.1`. */24export const TagName = Schema.NonEmptyString.check(25 Schema.isMaxLength(255)26).pipe(Schema.brand("TagName"));2728export type TagName = typeof TagName.Type;2930/**31 * A revision as a reader names it: `main` (the landed commit), a full32 * 40-hex commit id, or a tag's name. Decoded into one of the three where33 * it is read; anything else is `UnknownRevision`.34 */35export const Rev = Schema.String.check(36 Schema.isMinLength(1),37 Schema.isMaxLength(255)38);3940export type Rev = typeof Rev.Type;4142/** One tag, peeled to the commit it names. */43export const TagRef = Schema.Struct({ name: TagName, sha: CommitSha });4445export type TagRef = typeof TagRef.Type;4647/**48 * One fork of the project: a claim's (`<project>--<ask>--<handle>`), with49 * its ask and the claim's state, or a person's working fork.50 */51export const ForkRef = Schema.Struct({52 ask: Schema.optionalKey(AskId),53 handle: Handle,54 kind: Schema.Literals(["claim", "working"]),55 repo: RepoName,56 state: Schema.optionalKey(ClaimState),57});5859export type ForkRef = typeof ForkRef.Type;6061/** A project's refs as a reader sees them: main's landed commit, its tags and its forks. */62export const RefsView = Schema.Struct({63 forks: Schema.Array(ForkRef),64 landed: Schema.optionalKey(LandedSha),65 project: ProjectName,66 tags: Schema.Array(TagRef),67});6869export type RefsView = typeof RefsView.Type;7071/** One entry of a directory. */72export const CodeEntry = Schema.Struct({73 mode: Schema.String,74 name: Schema.NonEmptyString,75 path: RepoPath,76 sha: Schema.String,77 type: Schema.Literals(["blob", "tree", "submodule", "symlink"]),78});7980export type CodeEntry = typeof CodeEntry.Type;8182/** One directory at one commit: folders first, then by name, and its README when it has one. */83export const TreeListing = Schema.Struct({84 at: CommitSha,85 entries: Schema.Array(CodeEntry),86 /** Absent for the root. */87 path: Schema.optionalKey(RepoPath),88 readme: Schema.optionalKey(Schema.Struct({ path: RepoPath, sha: BlobSha })),89});9091export type TreeListing = typeof TreeListing.Type;9293/** Every file path at one commit, for a file tree; `truncated` past the cap. */94export const PathList = Schema.Struct({95 at: CommitSha,96 paths: Schema.Array(RepoPath),97 truncated: Schema.Boolean,98});99100export type PathList = typeof PathList.Type;101102/**103 * One file at one commit. `text` is absent for a binary file and for one104 * past the size cap (`truncated`).105 */106export const FileView = Schema.Struct({107 at: CommitSha,108 binary: Schema.Boolean,109 path: RepoPath,110 sha: BlobSha,111 size: Schema.Int,112 text: Schema.optionalKey(Schema.String),113 truncated: Schema.Boolean,114});115116export type FileView = typeof FileView.Type;117118/** Who wrote or committed a commit, and when. */119export const Signature = Schema.Struct({120 at: Schema.DateTimeUtcFromString,121 email: Schema.String,122 name: Schema.String,123});124125export type Signature = typeof Signature.Type;126127/**128 * One commit as a reader sees it. `landing` is the platform's own record of129 * it, when it is a landing: a trailer in an imported commit never makes one.130 */131export const CommitView = Schema.Struct({132 author: Signature,133 body: Schema.String,134 committer: Signature,135 landing: Schema.optionalKey(LandingView),136 parents: Schema.Array(CommitSha),137 sha: CommitSha,138 subject: Schema.String,139 trailers: Schema.Array(140 Schema.Struct({ key: Schema.String, value: Schema.String })141 ),142 tree: TreeSha,143});144145export type CommitView = typeof CommitView.Type;146147/** One file a commit changed, against its first parent. */148export const ChangedFile = Schema.Struct({149 after: Schema.optionalKey(BlobSha),150 before: Schema.optionalKey(BlobSha),151 binary: Schema.Boolean,152 newText: Schema.optionalKey(Schema.String),153 oldText: Schema.optionalKey(Schema.String),154 path: RepoPath,155 status: Schema.Literals(["added", "modified", "deleted"]),156});157158export type ChangedFile = typeof ChangedFile.Type;159160/** A commit and what it changed; past the caps, paths only and `truncated`. */161export const CommitDiff = Schema.Struct({162 commit: CommitView,163 files: Schema.Array(ChangedFile),164 truncated: Schema.Boolean,165});166167export type CommitDiff = typeof CommitDiff.Type;168169/** Lines `start` to `end` (1-based, inclusive) came in with commit `sha`. */170export const WhyRange = Schema.Struct({171 end: Schema.Int,172 sha: CommitSha,173 start: Schema.Int,174});175176export type WhyRange = typeof WhyRange.Type;177178/**179 * Why each line of a file is there: the first-parent commit that brought180 * it, and that commit's landing when it is one. Lines older than the walk181 * reached go to `stoppedAt`.182 */183export const WhyView = Schema.Struct({184 at: CommitSha,185 commits: Schema.Array(CommitView),186 landings: Schema.Array(LandingView),187 path: RepoPath,188 ranges: Schema.Array(WhyRange),189 stoppedAt: Schema.optionalKey(CommitSha),190});191192export type WhyView = typeof WhyView.Type;
modified:packages/protocol/src/domain/event.ts+2 added
28 unmodified lines
29 Landed: { ...stamp, landing: LandingView },30 /** A claim lapsed: no push for too long. */31 Lapsed: { ...stamp, ask: AskId },32 LedgerAppended: { ...stamp, entry: LedgerEntry },33 /** A proposal's draft settled: ready for a decider, or failed. */34 ProposalDrafted: { ...stamp, proposal: ProposalId, ready: Schema.Boolean },35 ProposalOpened: { ...stamp, proposal: ProposalId },36 Pushed: { ...stamp, ask: AskId, head: CommitSha },37 /** A claim was released. */38 Released: { ...stamp, ask: AskId },
5 unmodified lines
modified:packages/protocol/src/domain/policy.ts+11 added
108 unmodified lines
109110export type Policy = typeof Policy.Type;111112/**113 * A policy as anyone may read it: the evaluated config folder without its114 * layers (the ledger shows those, and keeps the cartridge removable), its115 * function-valued rules and its asks (`listAsks` lists them).116 */117export const PublicPolicy = Policy.mapFields(118 Struct.omit(["asks", "functions", "visibility"])119);120121export type PublicPolicy = typeof PublicPolicy.Type;122123/**124 * An ask as its file in the config folder states it: the platform adds its125 * project, when and in which landing it opened, and its state.126 */127export const AskInput = Ask.mapFields(
70 unmodified lines
modified:packages/protocol/src/domain/proposal.ts+27 added
2 unmodified lines
3import {4 AskId,5 CommitSha,6 Handle,7 LaneName,8 ProjectName,9 ProposalId,10 RepoName,11 RepoPath,12} from "../ids.ts";13import { AtLeastOne } from "./common.ts";1415/** Where a proposal stands; an open one expires unless a decider accepts it. */16export const ProposalState = Schema.Literals([17 "open",
4 unmodified lines
2223export type ProposalState = typeof ProposalState.Type;2425/**26 * Where the platform's draft of a proposal's ask stands: drafting, ready27 * (its check failed on main red first, in `lane`, the way `signature`28 * says), or failed after its attempts, with the last refusal's tag.29 */30export const DraftState = Schema.TaggedUnion({31 Drafting: { round: AtLeastOne, startedAt: Schema.DateTimeUtcFromString },32 Failed: {33 attempts: AtLeastOne,34 model: Schema.NonEmptyString,35 refusal: Schema.NonEmptyString,36 round: AtLeastOne,37 },38 Ready: {39 attempts: AtLeastOne,40 model: Schema.NonEmptyString,41 red: Schema.Struct({ lane: LaneName, signature: Schema.NonEmptyString }),42 round: AtLeastOne,43 },44});4546export type DraftState = typeof DraftState.Type;4748/**49 * A proposal: a request to open an ask, from anyone not denounced, that50 * expires unless a decider accepts it. It may carry a sealed answer, judged51 * after the ask opens without the decider reading its diff.52 */53export const Proposal = Schema.Struct({54 /** The platform's draft of its ask, when the proposer asked for one. */55 draft: Schema.optionalKey(DraftState),56 expiresAt: Schema.DateTimeUtcFromString,57 /** The proposed ask file and its check, held until the proposal is accepted. */58 files: Schema.Array(RepoPath),59 /** The existing ask this proposal flags, instead of a new one. */
14 unmodified lines
modified:packages/protocol/src/cli.ts+23 added-3 removed
173 unmodified lines
174}175176interface FieldSpec {177 readonly description: string | undefined;178 readonly kind: "string" | "number" | "boolean" | "literals" | "json";178 readonly kind:179 | "string"180 | "number"181 | "boolean"182 | "switch"183 | "literals"184 | "json";185 readonly literals: readonly string[];186 readonly optional: boolean;187}188
42 unmodified lines
231 return { description, kind: "json", literals: [], optional };232 }233 }234235 // A field that is `true` or absent is a switch: named, it is on.236 if (SchemaAST.isLiteral(ast) && ast.literal === true) {237 return { description, kind: "switch", literals: [], optional };238 }239240 const literal = literalOf(ast);241242 if (literal !== undefined) {243 return { description, kind: "literals", literals: [literal], optional };
18 unmodified lines
262 : [];263264/** Whether a person must give the field: a switch is off unless named. */265const isRequired = (spec: FieldSpec) =>255 !spec.optional && spec.kind !== "boolean";266 !spec.optional && spec.kind !== "boolean" && spec.kind !== "switch";267268const jsonFlag = (name: string, field: Plain) =>269 Flag.String(name).pipe(270 Flag.withSchema(Schema.fromJsonString(field)),
7 unmodified lines
278 number: (name) => Flag.Finite(name),279 // The field's own schema checks the text, so a malformed value is refused280 // by the parser, naming its flag, before anything is called.281 string: (name, field) => Flag.String(name).pipe(Flag.withSchema(field)),282 // On when named; left out of the payload otherwise.283 switch: (name) =>284 Flag.Boolean(name).pipe(285 Flag.withDefault(false),286 Flag.map((on) => (on ? true : undefined))287 ),288} satisfies Record<289 FieldSpec["kind"],290 (name: string, field: Plain, spec: FieldSpec) => Flag.Flag<unknown>291>;
24 unmodified lines
316317 const described =318 help === undefined ? base : base.pipe(Flag.withDescription(help));319303 return (spec.optional || fallback !== undefined) && spec.kind !== "boolean"320 return (spec.optional || fallback !== undefined) &&321 spec.kind !== "boolean" &&322 spec.kind !== "switch"323 ? described.pipe(Flag.optional, Flag.map(Option.getOrUndefined))324 : described;325};326
8 unmodified lines
335 json: (name, field) => schemaArgument(name, field, "JSON"),336 literals: (name, _field, spec) => Argument.Literals(name, spec.literals),337 number: (name) => Argument.Finite(name),338 string: (name) => Argument.String(name),339 switch: (name, field) => schemaArgument(name, field, "true"),340} satisfies Record<341 FieldSpec["kind"],342 (name: string, field: Plain, spec: FieldSpec) => Argument.Argument<unknown>343>;
342 unmodified lines
modified:packages/protocol/src/contracts.ts+283 added-3 removed
20 unmodified lines
21 Verdict,22} from "./domain/answer.ts";23import { Ask, AskListing, Reserve } from "./domain/ask.ts";24import { ClaimView } from "./domain/claim.ts";25import {26 CommitDiff,27 CommitView,28 PathList,29 RefsView,30 Rev,31 FileView,32 TreeListing,33 WhyView,34} from "./domain/code.ts";25import { ConfigFile } from "./domain/common.ts";35import { ConfigFile, NoneOrMore } from "./domain/common.ts";36import { Choice, Decision, Today } from "./domain/decision.ts";37import { EnvSchemaView } from "./domain/env.ts";38import { ProjectEvent } from "./domain/event.ts";39import { FrontPageEntry, ProjectListing } from "./domain/front-page.ts";40import { LandingView } from "./domain/landing.ts";41import { PublicPolicy } from "./domain/policy.ts";42import { Proposal } from "./domain/proposal.ts";43import { CreditSummary } from "./domain/record.ts";44import { Ledger } from "./domain/visibility.ts";45import {
5 unmodified lines
51 KindName,52 LandedSha,53 LaneName,54 ProjectName,55 ProposalId,56 RepoName,57 RepoPath,58 RequestId,59} from "./ids.ts";60import { Authenticated } from "./principal.ts";61import {
2 unmodified lines
64 CapReached,65 ClaimLapsed,66 DecisionClosed,67 Denounced,68 DraftInProgress,69 ImportFailed,70 IncompleteBrief,71 NotClaimed,72 NotDecider,
2 unmodified lines
75 NotVouched,76 OutOfScope,77 PrivatePathInPublicTree,78 ProjectExists,79 ProposalClosed,80 ReachedInternals,81 RepoBusy,82 StaleBase,83 TouchedJudge,84 UnknownAsk,85 UnknownCommit,86 UnknownDecision,87 UnknownEnvItem,88 UnknownPath,89 UnknownProject,90 UnknownProposal,91 UnknownRevision,92 ValueTooShort,93 VerifierBlocked,94 WeakCheck,95 Weakened,
27 unmodified lines
123const servedOn = {124 claim: ["rpc", "mcp", "cli"],125 credits: SurfaceName.literals,126 decide: SurfaceName.literals,127 draftAsk: SurfaceName.literals,128 [envSchemaTag]: SurfaceName.literals,129 // A log may hold text an agent's transcript should not carry: never MCP.130 evidence: ["rpc", "cli"],131 finish: ["rpc", "mcp", "cli"],
4 unmodified lines
136 land: ["rpc", "mcp", "cli"],137 landing: SurfaceName.literals,138 ledger: SurfaceName.literals,139 listAsks: SurfaceName.literals,140 // The code reads: git already reads code locally, so no command or tool.141 listPaths: ["rpc", "web"],142 listProjects: SurfaceName.literals,143 listRefs: ["rpc", "web"],144 log: ["rpc", "web"],145 openAsk: ["rpc", "mcp", "cli"],146 projectPolicy: SurfaceName.literals,147 proposeAsk: SurfaceName.literals,148 readFile: ["rpc", "web"],149 readTree: ["rpc", "web"],150 release: ["rpc", "mcp", "cli"],151 // A value must never pass through an agent's transcript, so never MCP.152 setEnv: ["rpc", "cli"],153 showAsk: SurfaceName.literals,154 showCommit: ["rpc", "web"],155 showProposal: SurfaceName.literals,156 status: SurfaceName.literals,157 submitAnswer: ["rpc", "mcp", "cli"],158 today: SurfaceName.literals,159 verdict: SurfaceName.literals,160 vouch: ["rpc", "mcp", "cli"],161 // A stream has no tool or command form.162 watch: ["rpc", "web"],163 why: ["rpc", "web"],164} as const satisfies Record<string, readonly SurfaceName[]>;165166/**167 * The payload of a contract that takes nothing: an object with no keys. An
236 unmodified lines
404 .annotate(Destructive, false)405 .annotate(NeedsApproval, false)406 .annotate(Surfaces, servedOn.watch) {}407408// --- Code reads (the canonical repo only; git reads it locally too) --------409410export class ListRefs extends Rpc.make("listRefs", {411 error: UnknownProject,412 payload: { project: ProjectName },413 success: RefsView,414})415 .annotate(416 Description,417 "List a project's refs: main's landed commit, its tags peeled to their commits, and its forks."418 )419 .annotate(Audience, "public")420 .annotate(Visibility, "public")421 .annotate(ReadOnly, true)422 .annotate(Idempotent, true)423 .annotate(Destructive, false)424 .annotate(NeedsApproval, false)425 .annotate(Surfaces, servedOn.listRefs) {}426427export class ReadTree extends Rpc.make("readTree", {428 error: Schema.Union([UnknownProject, UnknownRevision, UnknownPath]),429 payload: {430 /** `main`, a commit or a tag; main's landed commit when absent. */431 at: Schema.optionalKey(Rev),432 /** The folder; the root when absent. */433 path: Schema.optionalKey(RepoPath),434 project: ProjectName,435 },436 success: TreeListing,437})438 .annotate(439 Description,440 "List one folder of a project at a revision, folders first, with its README when it has one."441 )442 .annotate(Audience, "public")443 .annotate(Visibility, "public")444 .annotate(ReadOnly, true)445 .annotate(Idempotent, true)446 .annotate(Destructive, false)447 .annotate(NeedsApproval, false)448 .annotate(Surfaces, servedOn.readTree) {}449450export class ListPaths extends Rpc.make("listPaths", {451 error: Schema.Union([UnknownProject, UnknownRevision]),452 payload: { at: Schema.optionalKey(Rev), project: ProjectName },453 success: PathList,454})455 .annotate(456 Description,457 "List every file path in a project at a revision, up to a cap."458 )459 .annotate(Audience, "public")460 .annotate(Visibility, "public")461 .annotate(ReadOnly, true)462 .annotate(Idempotent, true)463 .annotate(Destructive, false)464 .annotate(NeedsApproval, false)465 .annotate(Surfaces, servedOn.listPaths) {}466467export class ReadFile extends Rpc.make("readFile", {468 error: Schema.Union([UnknownProject, UnknownRevision, UnknownPath]),469 payload: {470 at: Schema.optionalKey(Rev),471 path: RepoPath,472 project: ProjectName,473 },474 success: FileView,475})476 .annotate(477 Description,478 "Read one file of a project at a revision: its text, or that it is binary or too large to show."479 )480 .annotate(Audience, "public")481 .annotate(Visibility, "public")482 .annotate(ReadOnly, true)483 .annotate(Idempotent, true)484 .annotate(Destructive, false)485 .annotate(NeedsApproval, false)486 .annotate(Surfaces, servedOn.readFile) {}487488export class LogOf extends Rpc.make("log", {489 error: Schema.Union([UnknownProject, UnknownRevision]),490 payload: {491 at: Schema.optionalKey(Rev),492 /** How many commits to skip: a page's `next`. */493 from: Schema.optionalKey(NoneOrMore),494 /** 30 when absent. */495 limit: Schema.optionalKey(496 Schema.Int.check(Schema.isBetween({ maximum: 100, minimum: 1 }))497 ),498 /** Only the commits that changed this path. */499 path: Schema.optionalKey(RepoPath),500 project: ProjectName,501 },502 success: Schema.Struct({503 commits: Schema.Array(CommitView),504 /** Where the next page starts; absent on the last. */505 next: Schema.optionalKey(NoneOrMore),506 }),507})508 .annotate(509 Description,510 "List a project's commits along first parents from a revision, newest first, each landing with its ask, people and verdict."511 )512 .annotate(Audience, "public")513 .annotate(Visibility, "public")514 .annotate(ReadOnly, true)515 .annotate(Idempotent, true)516 .annotate(Destructive, false)517 .annotate(NeedsApproval, false)518 .annotate(Surfaces, servedOn.log) {}519520export class ShowCommit extends Rpc.make("showCommit", {521 error: Schema.Union([UnknownProject, UnknownCommit]),522 payload: { project: ProjectName, sha: CommitSha },523 success: CommitDiff,524})525 .annotate(526 Description,527 "Show one commit of a project and the files it changed against its first parent."528 )529 .annotate(Audience, "public")530 .annotate(Visibility, "public")531 .annotate(ReadOnly, true)532 .annotate(Idempotent, true)533 .annotate(Destructive, false)534 .annotate(NeedsApproval, false)535 .annotate(Surfaces, servedOn.showCommit) {}536537export class WhyOf extends Rpc.make("why", {538 error: Schema.Union([UnknownProject, UnknownRevision, UnknownPath]),539 payload: {540 at: Schema.optionalKey(Rev),541 path: RepoPath,542 project: ProjectName,543 },544 success: WhyView,545})546 .annotate(547 Description,548 "Say why each line of a file is there: the commit that brought it, and the landing, ask and people behind that commit."549 )550 .annotate(Audience, "public")551 .annotate(Visibility, "public")552 .annotate(ReadOnly, true)553 .annotate(Idempotent, true)554 .annotate(Destructive, false)555 .annotate(NeedsApproval, false)556 .annotate(Surfaces, servedOn.why) {}557558export class PolicyOf extends Rpc.make("projectPolicy", {559 error: UnknownProject,560 payload: { project: ProjectName },561 success: Schema.Struct({562 /** Absent while the config folder at the landed commit has not evaluated. */563 policy: Schema.optionalKey(PublicPolicy),564 }),565})566 .annotate(567 Description,568 "Show a project's evaluated config folder at its landed commit: who decides which paths, its vouches, caps, budget and claim timing."569 )570 .annotate(Audience, "public")571 .annotate(Visibility, "public")572 .annotate(ReadOnly, true)573 .annotate(Idempotent, true)574 .annotate(Destructive, false)575 .annotate(NeedsApproval, false)576 .annotate(Cli, { name: "policy" })577 .annotate(Surfaces, servedOn.projectPolicy) {}578579export class ShowProposal extends Rpc.make("showProposal", {580 error: Schema.Union([UnknownProject, UnknownProposal]),581 payload: { project: ProjectName, proposal: ProposalId },582 success: Schema.Struct({583 /** The files the proposal holds until a decider accepts it. */584 files: Schema.Array(ConfigFile),585 proposal: Proposal,586 }),587})588 .annotate(589 Description,590 "Show one proposal, its draft's state and the ask files it holds."591 )592 .annotate(Audience, "public")593 .annotate(Visibility, "public")594 .annotate(ReadOnly, true)595 .annotate(Idempotent, true)596 .annotate(Destructive, false)597 .annotate(NeedsApproval, false)598 .annotate(Cli, { name: "proposal", positional: ["proposal"] })599 .annotate(Surfaces, servedOn.showProposal) {}600601// --- Writes -----------------------------------------------------------------602603export class InitProject extends Rpc.make("initProject", {604 error: Schema.Union([ProjectExists, ImportFailed]),
59 unmodified lines
664 .annotate(NeedsApproval, true)665 .annotate(Cli, { name: "ask open", positional: ["ask"] })666 .annotate(Surfaces, servedOn.openAsk) {}667668/**669 * A drafted proposal brings no files and no sealed answer: the platform's670 * agent writes the ask's files.671 */672const draftsAlone = Schema.makeFilter(673 (payload: {674 readonly draft?: true;675 readonly files?: unknown;676 readonly sealed?: unknown;677 }) =>678 payload.draft === undefined ||679 (payload.files === undefined && payload.sealed === undefined)680 ? true681 : "a drafted proposal carries neither files nor a sealed answer"682);683684export class ProposeAsk extends Rpc.make("proposeAsk", {685 // `NotVouched` under the `all` mode, or for a sealed answer from someone686 // unvouched under `forCode` (a vouch admits sealed answers).687 error: Schema.Union([UnknownProject, Denounced, CapReached, NotVouched]),450 payload: {688 payload: Schema.Struct({689 /** Have the platform's agent draft the ask's files from the want. */690 draft: Schema.optionalKey(Schema.Literal(true)),691 files: Schema.optionalKey(Schema.NonEmptyArray(ConfigFile)),692 project: ProjectName,693 /** A sealed answer: the commit in the caller's working fork that answers it. */694 sealed: Schema.optionalKey(Schema.Struct({ head: CommitSha })),695 territory: Schema.optionalKey(Schema.NonEmptyString),696 want: Schema.NonEmptyString,457 },697 }).check(draftsAlone),698 success: Schema.Struct({ proposal: Proposal }),699})700 .annotate(701 Description,
7 unmodified lines
709 .annotate(NeedsApproval, false)710 .annotate(Cli, { name: "propose" })711 .annotate(Surfaces, servedOn.proposeAsk) {}712713export class DraftAsk extends Rpc.make("draftAsk", {714 error: Schema.Union([715 UnknownProject,716 UnknownProposal,717 ProposalClosed,718 NotDecider,719 DraftInProgress,720 CapReached,721 ]),722 payload: {723 /** What the draft should do differently, for the agent to read. */724 note: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2000))),725 project: ProjectName,726 proposal: ProposalId,727 },728 success: Schema.Struct({ proposal: Proposal }),729})730 .annotate(731 Description,732 "Have the platform's agent draft, or draft again, an open proposal's ask and its failing check; the proposer or a decider may ask."733 )734 .annotate(Audience, "signedIn")735 .annotate(Visibility, "public")736 .annotate(ReadOnly, false)737 .annotate(Idempotent, false)738 .annotate(Destructive, false)739 .annotate(NeedsApproval, false)740 .annotate(Cli, { name: "ask draft", positional: ["proposal"] })741 .annotate(Surfaces, servedOn.draftAsk) {}742743export class FlagAsk extends Rpc.make("flagAsk", {744 error: Schema.Union([UnknownProject, UnknownAsk, Denounced, CapReached]),745 payload: {746 ask: AskId,
308 unmodified lines
1055 TodayOf,1056 LedgerOf,1057 EnvSchemaOf,1058 Watch,1059 ListRefs,1060 ReadTree,1061 ListPaths,1062 ReadFile,1063 LogOf,1064 ShowCommit,1065 WhyOf,1066 PolicyOf,1067 ShowProposal,1068 InitProject,1069 OpenAsk,1070 ProposeAsk,1071 DraftAsk,1072 FlagAsk,1073 Decide,1074 Claim,1075 Release,
70 unmodified lines
modified:packages/protocol/src/refusal.ts+47 added-1 removed
6 unmodified lines
7 CommitSha,8 DecisionId,9 EnvKey,10 ProjectName,11 ProposalId,12 RepoPath,13} from "./ids.ts";14import { Posture } from "./posture.ts";15
299 unmodified lines
315 "DecisionClosed",316 { ...Final, ...nextIs(cli("today")), decision: DecisionId }317) {}318319/** The proposal was accepted, declined or expired, so nothing more is drafted for it. */320export class ProposalClosed extends Schema.TaggedError<ProposalClosed>()(321 "ProposalClosed",322 { ...Final, ...nextIs(cli("today")), proposal: ProposalId }323) {}324325/** The platform is drafting this proposal's ask already; its page says when it settles. */326export class DraftInProgress extends Schema.TaggedError<DraftInProgress>()(327 "DraftInProgress",328 { ...Retryable, proposal: ProposalId }329) {330 static readonly of = (proposal: ProposalId) =>331 new DraftInProgress({ next: cli("proposal", proposal), proposal });332}333334// Lookup335336/** No project has this name. */337export class UnknownProject extends Schema.TaggedError<UnknownProject>()(
19 unmodified lines
357 "UnknownDecision",358 { ...Final, ...nextIs(cli("today")), decision: DecisionId }359) {}360361/**362 * The project has no file or folder at this path at this commit. The363 * commit is `commit`: `at` points at a line, as on every refusal.364 */365export class UnknownPath extends Schema.TaggedError<UnknownPath>()(366 "UnknownPath",367 { ...Final, ...nextIs("git ls-tree"), commit: CommitSha, path: RepoPath }368) {}369370/** Neither `main`, a commit the project holds, nor one of its tags. */371export class UnknownRevision extends Schema.TaggedError<UnknownRevision>()(372 "UnknownRevision",373 { ...Final, ...nextIs("git ls-remote"), rev: Schema.String }374) {}375376/** The project has no proposal with this id. */377export class UnknownProposal extends Schema.TaggedError<UnknownProposal>()(378 "UnknownProposal",379 { ...Final, ...nextIs(cli("today")), proposal: ProposalId }380) {}381382// Setup383384/** A project with this name already exists. */385export class ProjectExists extends Schema.TaggedError<ProjectExists>()(
76 unmodified lines
462 SecretInOutput,463 UnstatedRequirement,464] as const;465429const decision = [PostureChange, NotDecider, DecisionClosed] as const;466const decision = [467 PostureChange,468 NotDecider,469 DecisionClosed,470 ProposalClosed,471 DraftInProgress,472] as const;473474const lookup = [475 UnknownProject,476 UnknownAsk,477 UnknownCommit,478 UnknownDecision,479 UnknownPath,480 UnknownRevision,481 UnknownProposal,482] as const;483484const setup = [ProjectExists, ImportFailed] as const;485
36 unmodified lines
modified:packages/protocol/src/render.ts+9 added
31 unmodified lines
32 Denounced: () =>33 "this project's vouch file denounces you, so it takes no claims or proposals from you",34 DirectPush: ({ ref }) =>35 `main moves only by a landing, so ${ref} takes no direct push; push your answer to your claim's fork`,36 DraftInProgress: ({ proposal }) =>37 `the platform is already drafting ${proposal}'s ask`,38 Flake: ({ lane }) =>39 `the ${lane} checks failed, then passed on the same tree; the platform will run them again`,40 HeldBackFailed: ({ area, suite }) =>41 `a held-back check failed in ${area}, suite ${suite}`,
15 unmodified lines
57 `landing would change the posture from ${from} to ${to}, which takes a decider`,58 PrivatePathInPublicTree: ({ paths }) =>59 `would put held-back paths in a public tree: ${list(paths)}; those paths belong to a layer, so remove them from the answer`,60 ProjectExists: ({ project }) => `a project named ${project} already exists`,61 ProposalClosed: ({ proposal }) =>62 `${proposal} was already accepted, declined or expired`,63 ReachedInternals: ({ from, to }) =>64 `${from} reaches into ${to}, which its module does not export; import it through that module's public exports instead`,65 RepoBusy: () => "the repo was busy with another push",66 SecretInOutput: ({ item, where }) =>
9 unmodified lines
76 UnknownAsk: ({ ask }) => `this project has no ask named ${ask}`,77 UnknownCommit: ({ sha }) => `this project has no commit ${sha}`,78 UnknownDecision: ({ decision }) => `this project has no decision ${decision}`,79 UnknownEnvItem: ({ key }) => `the env shape has no item ${key}`,80 UnknownPath: ({ commit, path }) =>81 `${short(commit)} has no file or folder at ${path}`,82 UnknownProject: ({ project }) => `no project is named ${project}`,83 UnknownProposal: ({ proposal }) => `this project has no proposal ${proposal}`,84 UnknownRevision: ({ rev }) =>85 `${rev} is neither main, a commit this project holds, nor one of its tags`,86 UnstatedRequirement: ({ area }) =>87 `a held-back check in ${area} enforces something no public clause states`,88 ValueTooShort: ({ key, minimum }) =>89 `the value for ${key} is shorter than the ${minimum} characters it needs`,
69 unmodified lines
modified:packages/protocol/src/testing.ts+10 added
31 unmodified lines
32export const unanswered = Contracts.toLayer({33 claim: uncalled,34 credits: uncalled,35 decide: uncalled,36 draftAsk: uncalled,37 // Keyed by the class: lint keeps "shape" out of code names.38 [EnvSchemaOf._tag]: uncalled,39 evidence: uncalled,40 finish: uncalled,
4 unmodified lines
45 land: uncalled,46 landing: uncalled,47 ledger: uncalled,48 listAsks: uncalled,49 listPaths: uncalled,50 listProjects: uncalled,51 listRefs: uncalled,52 log: uncalled,53 openAsk: uncalled,54 projectPolicy: uncalled,55 proposeAsk: uncalled,56 readFile: uncalled,57 readTree: uncalled,58 release: uncalled,59 setEnv: uncalled,60 showAsk: uncalled,61 showCommit: uncalled,62 showProposal: uncalled,63 status: uncalled,64 submitAnswer: uncalled,65 today: uncalled,66 verdict: uncalled,67 vouch: uncalled,68 watch: uncalled,69 why: uncalled,70});
modified:packages/protocol/test/fixtures/contracts.jsonnot shown

Its text is not shown, modified.

modified:packages/protocol/test/cli.test.ts+42 added-1 removed
20 unmodified lines
21 Decide,22 ListAsks,23 ListProjects,24 OpenAsk,25 ProposeAsk,26 ShowAsk,27 SubmitAnswer,28} from "../src/contracts.ts";29import { Outcome } from "../src/domain/outcome.ts";
4 unmodified lines
34 KindName,35 ProjectName,36 RequestId,37} from "../src/ids.ts";37import { AskFull, DecisionClosed, StaleBase } from "../src/refusal.ts";38import {39 AskFull,40 CapReached,41 DecisionClosed,42 StaleBase,43} from "../src/refusal.ts";44import { asTester, unanswered } from "../src/testing.ts";45import { ask, base, main, path } from "./examples.ts";4647const head = CommitSha.make("3333333333333333333333333333333333333333");
283 unmodified lines
331 ]);332 })333 );334335 // A field that is `true` or absent takes a bare switch: `--draft`.336 it.effect(337 "takes a switch as on when named, and leaves it out otherwise",338 () =>339 Effect.gen(function* () {340 const proposed = yield* Ref.make<readonly unknown[]>([]);341342 const propose = (args: readonly string[]) =>343 run(344 Layer.mergeAll(345 unanswered,346 Contracts.toLayerHandler("proposeAsk", (payload) =>347 Ref.update(proposed, (all) => [...all, payload]).pipe(348 Effect.andThen(Effect.fail(new CapReached({ cap: 2 })))349 )350 )351 ),352 (output) =>353 toCommand(ProposeAsk, Effect.service(Client), { output }),354 ["--project", project, "--want", "Parse ISO weeks.", ...args]355 );356357 yield* propose(["--draft"]);358 yield* propose([]);359360 expect(yield* Ref.get(proposed)).toStrictEqual([361 { draft: true, project, want: "Parse ISO weeks." },362 { project, want: "Parse ISO weeks." },363 ]);364 })365 );366367 it("takes the last word of a two-word name as its own", () => {368 const output = Effect.succeed<CommandOutput>({369 plan: () => Effect.void,370 refused: () => Effect.void,
226 unmodified lines
597 "credits",598 "today",599 "ledger",600 "env shape",601 "policy",602 "proposal",603 "ask open",604 "propose",605 "ask draft",606 "ask flag",607 "decide",608 "claim",609 "release",
23 unmodified lines
modified:packages/protocol/test/contracts.test.ts+122 added-2 removed
16 unmodified lines
17} from "../src/annotations.ts";18import {19 Contracts,20 partsOf,21 ProposeAsk,22 SetEnv,23 surfaced,24 Watch,25} from "../src/contracts.ts";
106 unmodified lines
132 on: "RW",133 tag: "watch",134 },135 {136 audience: "public",137 cli: "none",138 errors: ["UnknownProject"],139 flags: "RI",140 on: "RW",141 tag: "listRefs",142 },143 {144 audience: "public",145 cli: "none",146 errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],147 flags: "RI",148 on: "RW",149 tag: "readTree",150 },151 {152 audience: "public",153 cli: "none",154 errors: ["UnknownProject", "UnknownRevision"],155 flags: "RI",156 on: "RW",157 tag: "listPaths",158 },159 {160 audience: "public",161 cli: "none",162 errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],163 flags: "RI",164 on: "RW",165 tag: "readFile",166 },167 {168 audience: "public",169 cli: "none",170 errors: ["UnknownProject", "UnknownRevision"],171 flags: "RI",172 on: "RW",173 tag: "log",174 },175 {176 audience: "public",177 cli: "none",178 errors: ["UnknownProject", "UnknownCommit"],179 flags: "RI",180 on: "RW",181 tag: "showCommit",182 },183 {184 audience: "public",185 cli: "none",186 errors: ["UnknownProject", "UnknownRevision", "UnknownPath"],187 flags: "RI",188 on: "RW",189 tag: "why",190 },191 {192 audience: "public",193 cli: "policy",194 errors: ["UnknownProject"],195 flags: "RI",196 on: "RMCW",197 tag: "projectPolicy",198 },199 {200 audience: "public",201 cli: "proposal <proposal>",202 errors: ["UnknownProject", "UnknownProposal"],203 flags: "RI",204 on: "RMCW",205 tag: "showProposal",206 },207 {208 audience: "signedIn",209 cli: "init",210 errors: ["ProjectExists", "ImportFailed"],211 flags: "A",
26 unmodified lines
238 tag: "proposeAsk",239 },240 {241 audience: "signedIn",242 cli: "ask draft <proposal>",243 errors: [244 "UnknownProject",245 "UnknownProposal",246 "ProposalClosed",247 "NotDecider",248 "DraftInProgress",249 "CapReached",250 ],251 flags: "",252 on: "RMCW",253 tag: "draftAsk",254 },255 {256 audience: "signedIn",257 cli: "ask flag <ask>",258 errors: ["UnknownProject", "UnknownAsk", "Denounced", "CapReached"],259 flags: "",260 on: "RMC",
118 unmodified lines
379 tag: "setEnv",380 },381] as const;382383/** Whether `proposeAsk` takes `payload`: `Some` when it decodes. */384const decodes = (payload: typeof Schema.Json.Type) =>385 Schema.decodeUnknownOption(ProposeAsk.payloadSchema)(payload)._tag;386387/** The code reads: on RPC and the web only (git reads code locally). */388type CodeRead =389 | "listPaths"390 | "listRefs"391 | "log"392 | "readFile"393 | "readTree"394 | "showCommit"395 | "why";396397/** Each surface's letter in the table's Surfaces column. */398const letterOf = {399 cli: "C",400 mcp: "M",
177 unmodified lines
578 expect(JSON.stringify(decoded)).toContain('"value":"<redacted>"');579 expect(JSON.stringify(decoded)).not.toContain(encoded.value);580 });581582 // The platform's agent writes a drafted proposal's files, so one that583 // brings its own, or a sealed answer, is refused at the boundary.584 it("takes a drafted proposal with no files and no sealed answer", () => {585 const want = { project: "datekit", want: "Parse ISO weeks." };586587 const files = [{ content: "x", path: "config/asks/a.ask.ts" }];588589 const sealed = { head: "3".repeat(40) };590591 expect([592 decodes({ ...want, draft: true }),593 decodes({ ...want, draft: true, files }),594 decodes({ ...want, draft: true, sealed }),595 decodes({ ...want, files }),596 decodes({ ...want, draft: false }),597 ]).toStrictEqual(["Some", "None", "None", "Some", "None"]);598 });599600 it("streams a project's events from watch", () => {601 expect(RpcSchema.isStreamSchema(Watch.successSchema)).toBeTruthy();602 expect(Watch.successSchema.success).toBe(ProjectEvent);603 });
15 unmodified lines
619 // annotations come from, so a tool or command the type names exists.620 it("types each surface's group as the contracts on it", () => {621 expectTypeOf<TagOn<"rpc">>().toEqualTypeOf<Contract["_tag"]>();622 expectTypeOf<TagOn<"mcp">>().toEqualTypeOf<503 Exclude<Contract["_tag"], "evidence" | "setEnv" | "watch">623 Exclude<Contract["_tag"], CodeRead | "evidence" | "setEnv" | "watch">624 >();625 expectTypeOf<TagOn<"cli">>().toEqualTypeOf<506 Exclude<Contract["_tag"], "watch">626 Exclude<Contract["_tag"], CodeRead | "watch">627 >();628 });629630 it("never gives MCP a stream, a contract that carries a write-only value, or a lane's log", () => {
11 unmodified lines
modified:packages/protocol/test/examples.ts+13 added
4 unmodified lines
5 CommitSha,6 DecisionId,7 EnvKey,8 ProjectName,9 ProposalId,10 RepoPath,11} from "../src/ids.ts";12import {13 AskBlocked,
4 unmodified lines
18 ClaimLapsed,19 DecisionClosed,20 Denounced,21 DirectPush,22 DraftInProgress,23 Flake,24 HeldBackFailed,25 ImportFailed,26 IncompleteBrief,
7 unmodified lines
34 OutOfScope,35 PostureChange,36 PrivatePathInPublicTree,37 ProjectExists,38 ProposalClosed,39 ReachedInternals,40 RepoBusy,41 SecretInOutput,42 StaleBase,
2 unmodified lines
45 UnknownAsk,46 UnknownCommit,47 UnknownDecision,48 UnknownEnvItem,49 UnknownPath,50 UnknownProject,51 UnknownProposal,52 UnknownRevision,53 UnstatedRequirement,54 ValueTooShort,55 VerifierBlocked,56 WeakCheck,
14 unmodified lines
71const decision = DecisionId.make("dec-000001");7273const key = EnvKey.make("PAYMENTS_KEY");7475const proposal = ProposalId.make("prop-000001");7677// One of each member, in the union's order.78export const examples: readonly Refusal[] = [79 NotClaimed.of(ask),80 ClaimLapsed.of(ask),
39 unmodified lines
120 new UnstatedRequirement({ area: "parser" }),121 new PostureChange({ from: "open", to: "openCore" }),122 new NotDecider({}),123 new DecisionClosed({ decision }),124 new ProposalClosed({ proposal }),125 DraftInProgress.of(proposal),126 new UnknownProject({ project }),127 new UnknownAsk({ ask }),128 new UnknownCommit({ sha: main }),129 new UnknownDecision({ decision }),130 new UnknownPath({ commit: main, path }),131 new UnknownRevision({ rev: "v9.9.9" }),132 new UnknownProposal({ proposal }),133 new ProjectExists({ project }),134 new ImportFailed({ reason: "the repo needs a sign-in to read" }),135 new UnknownEnvItem({ key }),136 new NotSensitive({ key }),
2 unmodified lines
modified:packages/protocol/test/refusal.test.tsnot shown

Its text is not shown, modified.

modified:packages/protocol/test/render.test.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/src/fake-artifacts-binding.tsnot shown

Its text is not shown, modified.

modified:packages/testkit/test/fake-artifacts-binding.test.tsnot shown

Its text is not shown, modified.

modified:scripts/lib/swarm/views/counter.tsnot shown

Its text is not shown, modified.

added:scripts/import-examples.tsnot shown

Its text is not shown, added.

modified:scripts/startup-budget.tsnot shown

Its text is not shown, modified.

modified:AGENTS.md+1 added
64 unmodified lines
65- `bootstrap -- --stage <stage>`: makes a stage's Cloudflare resources; a second run creates nothing, and `--dry-run` only prints the plan.66- `deploy -- --stage <stage>`: the one way to deploy. It runs `verify`, deploys the three Workers with Wrangler, reads the push trigger back, then runs `smoke`.67- `smoke -- --stage <stage>`: read-only probes against a live stage. `--loop` then runs the whole core loop on a throwaway project, `smoke-<run>`, through the CLI and git, and refuses `demo`.68- `seed`: puts the two example projects on a platform (`--world node` on this machine, or `--stage <stage>`); a second run changes nothing. `--only <example> --as <name>` seeds a fresh copy under another name, and refuses a taken one.69- `import-examples -- --stage <stage>`: imports the open-source repos the code browser is previewed on, one at a time, onto a stage other than `demo`, each recorded in the ledger as kept. Until its body lands it says so and exits 1.70- `swarm -- --stage <stage> --project <name>`: plans six fictional contributors, on four harnesses, against one split family on a stage, claims each one's ask, prepares a workspace with a clone of its fork outside the checkout, starts each harness headless on the brief and sends every refusal back into the same session, at most three times, then writes the run's summary; `--view herdr` runs them in herdr panes beside a counter, and `--dry-run` only prints the plan.71- `release -- --build | --upload --stage <stage> | --publish`: builds the CLI's npm package and two binaries, uploads a release to the stage's own bucket, which the platform serves, and leaves `npm publish` to a person: under an agent it prints the command instead.7273## Nouns
73 unmodified lines
modified:bun.lock+23 added
59 unmodified lines
60 "@repo/agent-kit": "workspace:*",61 "@repo/artifacts": "workspace:*",62 "@repo/brand": "workspace:*",63 "@repo/checks": "workspace:*",64 "@repo/drafting": "workspace:*",65 "@repo/gate": "workspace:*",66 "@repo/git": "workspace:*",67 "@repo/project": "workspace:*",68 "@repo/protocol": "workspace:*",
64 unmodified lines
133 "@playwright/test": "1.63.0",134 "@repo/artifacts": "workspace:*",135 "@repo/checks": "workspace:*",136 "@repo/config": "workspace:*",137 "@repo/drafting": "workspace:*",138 "@repo/git": "workspace:*",139 "@repo/project": "workspace:*",140 "@repo/rules": "workspace:*",141 "@repo/testkit": "workspace:*",
83 unmodified lines
225 "typescript": "catalog:",226 "vitest": "catalog:",227 },228 },229 "packages/drafting": {230 "name": "@repo/drafting",231 "dependencies": {232 "@repo/artifacts": "workspace:*",233 "@repo/brand": "workspace:*",234 "@repo/project": "workspace:*",235 "@repo/protocol": "workspace:*",236 "effect": "catalog:",237 },238 "devDependencies": {239 "@cloudflare/workers-types": "5.20261006.1",240 "@effect/vitest": "catalog:",241 "@repo/config": "workspace:*",242 "@repo/rules": "workspace:*",243 "@repo/testkit": "workspace:*",244 "typescript": "catalog:",245 "vitest": "catalog:",246 },247 },248 "packages/gate": {249 "name": "@repo/gate",250 "dependencies": {251 "@repo/protocol": "workspace:*",
648 unmodified lines
900 "@repo/cli": ["@repo/cli@workspace:apps/cli"],901902 "@repo/config": ["@repo/config@workspace:packages/config"],903904 "@repo/drafting": ["@repo/drafting@workspace:packages/drafting"],905906 "@repo/gate": ["@repo/gate@workspace:packages/gate"],907908 "@repo/git": ["@repo/git@workspace:packages/git"],909
1535 unmodified lines
modified:package.json+1 added
29 unmodified lines
30 "bootstrap": "varlock run --path infra/ -- bun infra/bootstrap.ts",31 "deploy": "bun infra/deploy.ts",32 "smoke": "bun scripts/smoke.ts",33 "seed": "bun scripts/seed.ts",34 "import-examples": "bun scripts/import-examples.ts",35 "swarm": "bun scripts/swarm.ts",36 "release": "bun scripts/release.ts",37 "verify": "bun run lockfile:check && bun run check && bun run typecheck && bun run test && bun run brand:check && bun run bytes:check"38 },
20 unmodified lines
modified:tsconfig.base.jsonnot shown

Its text is not shown, modified.