Skip to content
Myr

Merge build/418-evidence-logs: a failing lane's log is kept, and the answerer and the deciders can read it

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

authored by oscabriel · committed by oscabriel · parents e6a2d4a, 909da56 · Browse files · 24 files+1384 added−39 removed
This commit

State

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

Diff stats

24 files+1384 added−39 removed

  • tests:+965 added−19 removed
  • other:+419 added−20 removed

24 files+1384 added−39 removed

modified:apps/platform/src/adapters/do-projects.ts+3 added
modified:apps/platform/src/handlers.ts+13 added-1 removed
5 unmodified lines
6 * `frontPage`, `credits`) come from the front-page projection; `status` and7 * `today` without a project ask every project the projection lists and8 * merge what each says. `claim`, `proposeAsk` and `flagAsk` spend the9 * caller's rate limit first, so a call past it reaches no project.10 * `evidence` asks the project who may read a lane's log, which it reads11 * from the stage's `EvidenceStore`.12 *13 * Every `remote` a caller gets back is the platform's git URL for the repo,14 * at the origin the caller reached the platform by: never a storage URL.15 */16import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";17import { envSchemaMethod } from "@repo/project/deciders";18import { FrontPage } from "@repo/project/front-page";19import { GatewayUrl } from "@repo/project/project";20import type { ProjectApi } from "@repo/project/project";
128 unmodified lines
149 */150export const Handlers: Layer.Layer<151 Rpc.ToHandler<RpcGroup.Rpcs<typeof Contracts>>,152 never,150 Projects | FrontPage | RateLimits153 Projects | FrontPage | RateLimits | EvidenceStore154> = Contracts.toLayer(155 Effect.gen(function* () {156 const projects = yield* Projects;157 const frontPage = yield* FrontPage;158 const rateLimits = yield* RateLimits;159 const evidence = yield* EvidenceStore;160161 /** `call` on the project named `project`; one never made is `UnknownProject`. */162 const on = <A, E>(163 project: ProjectName,
45 unmodified lines
209 decide: ({ project, ...input }) =>210 Effect.flatMap(person, (who) =>211 on(project, (api) => api.decide(who, input))212 ),213 evidence: ({ project, ref }) =>214 Effect.flatMap(person, (who) =>215 on(project, (api) =>216 api217 .evidence(who, LogRef.make(ref))218 .pipe(Effect.provideService(EvidenceStore, evidence))219 )220 ),221 [EnvSchemaOf._tag]: ({ project }) =>222 Effect.flatMap(caller, (who) =>223 on(project, (api) => api[envSchemaMethod](who))224 ),
144 unmodified lines
modified:apps/platform/src/ports.ts+3 added-3 removed
16 unmodified lines
17import type { RepoHost } from "@repo/artifacts/repo-host";18import { RepoHostBinding } from "@repo/artifacts/repo-host/binding";19import type { CheckRunner } from "@repo/checks/check-runner";20import type { EvidenceStore } from "@repo/checks/evidence-store";21import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";21import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";22import type { Upstream } from "@repo/git/upstream";23import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";24import type { FrontPage } from "@repo/project/front-page";25import { FrontPageMemory } from "@repo/project/front-page/memory";
44 unmodified lines
70 * The ports for one stage's env: Artifacts through its binding, git's71 * upstream and every repo read over it, each project's Durable Object, the72 * sandbox's Checker, the Lander `LANDER_ADAPTER` names (spec §8 D6), config73 * folders evaluated in the Worker Loader, the front page in D1, the rate74 * limits, and evidence in memory until W4 418 moves it to `EVIDENCE`.74 * limits, and lane logs in the `EVIDENCE` bucket (W4 418).75 */76export const workerPorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>77 Layer.mergeAll(78 memoryFrontPage,
16 unmodified lines
95 WorkerRateLimits({96 claim: config.CLAIM_LIMIT,97 proposal: config.PROPOSAL_LIMIT,98 }),99 EvidenceStoreMemory99 EvidenceStoreR2(config.EVIDENCE)100 ).pipe(101 Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)),102 Layer.provideMerge(WorkerFetch)103 );
modified:apps/platform/src/project-calls.ts+1 added
101 unmodified lines
102 credits: callOf(MethodSchemas.credits),103 [envSchemaMethod]: callOf(MethodSchemas[envSchemaMethod]),104 decide: callOf(MethodSchemas.decide),105 events: callOf(MethodSchemas.events),106 evidence: callOf(MethodSchemas.evidence),107 finish: callOf(MethodSchemas.finish),108 firstPusher: callOf(MethodSchemas.firstPusher),109 flagAsk: callOf(MethodSchemas.flagAsk),110 fork: callOf(MethodSchemas.fork),
83 unmodified lines
modified:apps/platform/src/project-shell.ts+23 added-6 removed
9 unmodified lines
10 * before `initProject` with `UnknownProject`, runs the method, and answers11 * its `Exit` encoded, so a refusal stays a refusal and never becomes a12 * defect at the boundary.13 */14import { EvidenceStore } from "@repo/checks/evidence-store";15import { projectService } from "@repo/project/project";16import type { ProjectApi, ProjectPorts } from "@repo/project/project";17import { ProjectStore } from "@repo/project/project-store";18import { ProjectStoreSqlite } from "@repo/project/project-store/sqlite";
26 unmodified lines
45}4647/**48 * The service's methods as one table, each over its own arguments: what a48 * call indexed by a method name runs.49 * call indexed by a method name runs. A method may read lane logs50 * (`evidence`), so each runs with the stage's `EvidenceStore`.51 */52type Methods = {53 readonly [M in ProjectMethod]: (54 ...args: Readonly<ArgsOf<M>>55 ) => Effect.Effect<56 Effect.Success<ReturnType<ProjectApi[M]>>,55 Effect.Error<ReturnType<ProjectApi[M]>>57 Effect.Error<ReturnType<ProjectApi[M]>>,58 EvidenceStore59 >;60};6162/** The DO has no name, and its storage holds no project to take one from. */
5 unmodified lines
68 /** The DO's name, when the Worker made its id with `idFromName`. */69 readonly name: ProjectName | undefined;70 /** SQL over the DO's own storage; sqlite-node in tests. */71 readonly sql: Layer.Layer<SqlClient>;69 /** Every port the service runs on but its store. */70 readonly ports: Layer.Layer<Exclude<ProjectPorts, ProjectStore>>;72 /**73 * Every port the service runs on but its store, and where lane logs are74 * kept, which `evidence` reads.75 */76 readonly ports: Layer.Layer<77 Exclude<ProjectPorts, ProjectStore> | EvidenceStore78 >;79}): Effect.Effect<ProjectShell, never, Scope.Scope> =>80 Effect.gen(function* () {81 const context = yield* Layer.build(82 Layer.merge(
3 unmodified lines
86 )87 );8889 const store = Context.get(context, ProjectStore);9091 /** A method's run, with the stage's lane logs to read. */92 const withEvidence = Effect.provideService(93 EvidenceStore,94 Context.get(context, EvidenceStore)95 );9697 const made = yield* Ref.make(false);98 const built = yield* SynchronizedRef.make(Option.none<Methods>());99100 /** Whether `initProject` has made the project; once it has, it stays made. */
67 unmodified lines
168 ).pipe(Effect.orDie);169 }170171 const api = yield* service;157 const outcome = yield* Effect.exit(api[method](...args));172 const outcome = yield* Effect.exit(withEvidence(api[method](...args)));173174 return yield* Schema.encodeUnknownEffect(call.exit)(outcome).pipe(175 Effect.orDie176 );
3 unmodified lines
180 alarm: () =>181 Effect.gen(function* () {182 // A DO no project was made in has nothing to wake for.183 if (yield* isMade) {169 yield* Effect.flatMap(service, (api) => api.onAlarm());184 yield* Effect.flatMap(service, (api) =>185 withEvidence(api.onAlarm())186 );187 }188 }),189 call: (request) =>190 Effect.flatMap(
5 unmodified lines
modified:apps/platform/test/do-projects.test.ts+9 added-1 removed
1import { describe, expect, expectTypeOf, it } from "@effect/vitest";2import { LogRef } from "@repo/checks/evidence-store";3import { envSchemaMethod } from "@repo/project/deciders";4import { LandingCommand } from "@repo/project/landing";5import type { ProjectApi } from "@repo/project/project";6import { Projects } from "@repo/project/projects";
38 unmodified lines
4546const requestId = RequestId.make("req-none0001");4748/** A call's `Exit` as JSON, by its method's own schemas: equal when the outcomes are. */48const settled = <A, E>(method: ProjectMethod, effect: Effect.Effect<A, E>) =>49const settled = <A, E, R>(50 method: ProjectMethod,51 effect: Effect.Effect<A, E, R>52) =>53 Effect.exit(effect).pipe(54 Effect.flatMap((exit) =>55 Schema.encodeUnknownEffect(ProjectCalls[method].exit)(exit)56 ),
21 unmodified lines
78 })79 ),80 [envSchemaMethod]: settled(envSchemaMethod, api[envSchemaMethod](anyone)),81 events: settled("events", api.events(0, 100)),82 evidence: settled(83 "evidence",84 api.evidence(alice, LogRef.make(`${project}/${requestId}/unit#1`))85 ),86 finish: settled(87 "finish",88 api.finish(bob, { ask: parseIso, base: sha, head: sha, requestId })89 ),
132 unmodified lines
added:apps/platform/test/evidence.test.ts+398 added
1/**2 * A failing lane's log, kept and read through the platform (W4 418): the3 * Answer Workflow keeps the log of alice's failing `unit` lane in the4 * stage's evidence bucket (an R2 fake here, through `EvidenceStoreR2`, as5 * the Worker composes it), her refusal names only where it is kept, and6 * `evidence` over `/rpc` gives it to her and to dora, the project's7 * decider, and to nobody else. The world is the core loop's (`world.ts`):8 * the platform's own fetch handler with real git.9 */10import { describe, expect, expectTypeOf, it } from "@effect/vitest";11import { Brand } from "@repo/brand";12import { CheckAt } from "@repo/checks/check-runner";13import { EvidenceStore } from "@repo/checks/evidence-store";14import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";15import type { EvidenceBucket } from "@repo/checks/evidence-store/r2";16import { Outcome } from "@repo/protocol/domain/outcome";17import {18 AskId,19 CommitSha,20 Handle,21 LaneName,22 ProjectName,23 RepoPath,24 RequestId,25 TreeSha,26} from "@repo/protocol/ids";27import { Unauthenticated } from "@repo/protocol/principal";28import {29 ChecksFailed,30 NotDecider,31 UnknownProject,32} from "@repo/protocol/refusal";33import { Array, Cause, Effect, Exit, Stream } from "effect";3435import { decodeEnv } from "../src/platform.ts";36import { workerPorts } from "../src/ports.ts";37import { fakeEnv } from "./fake-env.ts";38import { coreLoopWorld } from "./world.ts";39import type { Someone } from "./world.ts";4041const project = ProjectName.make("datekit");4243const parseIso = AskId.make("parse-iso");4445const redThenGreen = LaneName.make("redThenGreen");4647const unit = LaneName.make("unit");4849const sdk = `${Brand.cliPackage}/rules`;5051/** The project as dora first pushes it: its run block has a `unit` lane. */52const start = {53 [`${Brand.configDir}/project.ts`]: [54 `import { kinds, project } from "${sdk}";`,55 ``,56 `export default project({`,57 ` kinds: [kinds.fix],`,58 ` run: { checks: { unit: "bun test" }, test: "bun test {path}" },`,59 `});`,60 ``,61 ].join("\n"),62 [`${Brand.configDir}/vouched.td`]: "alice\nbob\n",63 "README.md": "datekit: dates, parsed\n",64 "package.json": '{ "name": "datekit", "private": true }\n',65 "src/parse.ts":66 "export const parse = (iso: string) => ({ month: 0, year: 0 });\n",67};6869const askFiles = Array.make(70 {71 content: [72 `import { kinds, territory } from "${sdk}";`,73 ``,74 `export default kinds.fix.ask({`,75 ` path: "test/${parseIso}.test.ts",`,76 ` territory: territory.paths("src/parse.ts"),`,77 ` want: "parse reads the year of an ISO date",`,78 `});`,79 ``,80 ].join("\n"),81 path: RepoPath.make(`${Brand.configDir}/asks/${parseIso}.ask.ts`),82 },83 {84 content: [85 `import { expect, it } from "bun:test";`,86 `import { parse } from "../src/parse.ts";`,87 ``,88 `it("parse reads the year of an ISO date", () => {`,89 ` expect(parse("2026-10-07").year).toBe(2026);`,90 `});`,91 ``,92 ].join("\n"),93 path: RepoPath.make(`test/${parseIso}.test.ts`),94 }95);9697/**98 * The log the platform keeps of a `unit` lane the Checker failed: what the99 * run said of the lane, since a scripted run has no output of its own.100 */101const unitLog = [102 "unit: failed in 1 ms",103 "$ run unit",104 "unit: scripted failure",105].join("\n");106107/** One object as the fake bucket keeps it. */108interface Kept {109 readonly text: string;110 readonly customMetadata: Readonly<Record<string, string>>;111}112113/** The stage's evidence bucket in memory, in the shape of the Worker's `EVIDENCE` binding. */114const fakeBucket = () => {115 const objects = new Map<string, Kept>();116117 const bucket: EvidenceBucket = {118 get: (key) => {119 const kept = objects.get(key);120121 return Promise.resolve(122 kept === undefined ? null : { text: () => Promise.resolve(kept.text) }123 );124 },125 put: (key, text, { customMetadata }) => {126 objects.set(key, { customMetadata, text });127128 return Promise.resolve({ key });129 },130 };131132 return { bucket, objects };133};134135/**136 * dora makes datekit and opens parse-iso; alice claims it and answers in137 * scope, and on the merged tree her ask's check passes and `unit` fails,138 * while `unit` passes on main: the answer is refused `ChecksFailed`.139 */140const refused = Effect.gen(function* () {141 const { bucket, objects } = fakeBucket();142 const world = yield* coreLoopWorld({ evidence: EvidenceStoreR2(bucket) });143 const dora = world.rpc("dora");144 const alice = world.rpc("alice");145 const doraGit = world.git("dora");146 const aliceGit = world.git("alice");147148 const made = yield* dora.initProject({ project });149 const home = yield* doraGit.clone(made.remote);150151 yield* doraGit.commit(home, "Start datekit", start);152 yield* doraGit.push(home);153154 yield* world.script(155 CheckAt.cases.Commit.make({156 commit: yield* world.composed(project, askFiles),157 }),158 redThenGreen,159 ["failed", "failed"]160 );161162 const opened = yield* dora.openAsk({163 ask: parseIso,164 files: askFiles,165 project,166 });167168 const { claim } = yield* alice.claim({ ask: parseIso, project });169 const work = yield* aliceGit.clone(claim.remote);170171 const fix = yield* aliceGit.commit(work, "Read the year", {172 "src/parse.ts":173 "export const parse = (iso: string) => ({ month: 0, year: Number(iso.slice(0, 4)) });\n",174 });175176 const pushed = yield* aliceGit.push(work);177178 const tree = TreeSha.make(179 yield* aliceGit.ok(work, "rev-parse", `${fix}^{tree}`)180 );181182 const merged = CheckAt.cases.Tree.make({ tree });183184 yield* world.script(merged, redThenGreen, ["passed"]);185 yield* world.script(merged, unit, ["failed"]);186 yield* world.script(187 CheckAt.cases.Commit.make({ commit: CommitSha.make(opened.landed) }),188 unit,189 ["passed"]190 );191192 yield* world.settle();193194 const { verdict } = yield* alice.verdict({ ask: parseIso, project });195196 const logRef = verdict?.lanes.find(({ lane }) => lane === unit)?.logRef ?? "";197198 return { aliceGit, logRef, objects, pushed, verdict, work, world };199});200201/** How a read ended, success or refusal, as JSON. */202const json = <A, E>(read: Effect.Effect<A, E>) =>203 Effect.map(Effect.exit(read), (exit) => JSON.stringify(exit));204205/** Everything `who` can read over `/rpc` besides `evidence`, as JSON. */206const everythingElse = (207 world: Effect.Success<typeof refused>["world"],208 who: Someone | "anonymous"209) =>210 Effect.gen(function* () {211 const rpc = world.rpc(who);212213 return [214 yield* json(rpc.listProjects({})),215 yield* json(rpc.frontPage({})),216 yield* json(rpc.listAsks({ project })),217 yield* json(rpc.showAsk({ ask: parseIso, project })),218 yield* json(rpc.verdict({ ask: parseIso, project })),219 yield* json(rpc.credits({ handle: Handle.make("alice") })),220 yield* json(rpc.ledger({ project })),221 yield* json(rpc.envShape({ project })),222 yield* json(rpc.status({ project })),223 yield* json(rpc.today({ project })),224 yield* json(Stream.runCollect(rpc.watch({ project }))),225 ];226 });227228describe("a failing lane's log, through the platform", () => {229 it("takes the Worker's EVIDENCE binding as its bucket", () => {230 expectTypeOf<Env["EVIDENCE"]>().toExtend<EvidenceBucket>();231 });232233 it.effect(234 "keeps the Worker's lane logs in its EVIDENCE bucket, not in memory",235 () =>236 Effect.gen(function* () {237 const config = yield* decodeEnv(fakeEnv()).pipe(Effect.orDie);238239 const exit = yield* Effect.exit(240 EvidenceStore.use((store) =>241 store.put({242 attempt: 1,243 lane: unit,244 project,245 requestId: RequestId.make("req-fix-0001"),246 text: unitLog,247 })248 ).pipe(Effect.provide(workerPorts(config)))249 );250251 // The fake env's EVIDENCE throws when touched: the store reached it.252 expect(253 Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "it kept the log"254 ).toContain("could not put datekit/req-fix-0001/unit#1");255 })256 );257258 it.live(259 "keeps the log of a lane that failed, and the refusal names only where",260 () =>261 Effect.gen(function* () {262 const { logRef, objects, verdict } = yield* refused;263264 expect({265 kept: objects.get(logRef),266 outcome: verdict?.outcome,267 }).toStrictEqual({268 kept: {269 customMetadata: { lane: "unit", project: "datekit" },270 text: unitLog,271 },272 outcome: Outcome.cases.Refused.make({273 refusals: [274 new ChecksFailed({ lane: unit, logRef, next: "run unit" }),275 ],276 }),277 });278 }),279 60_000280 );281282 it.live(283 "gives the log to the answer's claimant and to a decider, and refuses everyone else",284 () =>285 Effect.gen(function* () {286 const { logRef, objects, world } = yield* refused;287 const ref = { project, ref: logRef };288289 const asked = (who: Someone | "anonymous", payload = ref) =>290 Effect.exit(world.rpc(who).evidence(payload));291292 // A name pointing at another project: a real one bob makes, and one293 // nobody made, both read as that project unknown.294 yield* world295 .rpc("bob")296 .initProject({ project: ProjectName.make("burrow") });297298 const elsewhere = (other: string) => ({299 project,300 ref: logRef.replace(`${project}/`, `${other}/`),301 });302303 const read = {304 alice: yield* asked("alice"),305 anonymous: yield* asked("anonymous"),306 bob: yield* asked("bob"),307 dora: yield* asked("dora"),308 ghost: yield* asked("dora", {309 project: ProjectName.make("ghost"),310 ref: logRef.replace(`${project}/`, "ghost/"),311 }),312 inBurrow: yield* asked("dora", elsewhere("burrow")),313 inGhost: yield* asked("dora", elsewhere("ghost")),314 };315316 const whole = { lane: unit, text: unitLog, truncated: false };317318 expect(read).toStrictEqual({319 alice: Exit.succeed(whole),320 anonymous: Exit.fail(new Unauthenticated()),321 bob: Exit.fail(new NotDecider({})),322 dora: Exit.succeed(whole),323 ghost: Exit.fail(324 new UnknownProject({ project: ProjectName.make("ghost") })325 ),326 inBurrow: Exit.fail(327 new UnknownProject({ project: ProjectName.make("burrow") })328 ),329 inGhost: Exit.fail(330 new UnknownProject({ project: ProjectName.make("ghost") })331 ),332 });333334 // A log over 256 KiB comes back as its last 256 KiB.335 const long = `${"x".repeat(300 * 1024)}\n${unitLog}`;336 const kept = objects.get(logRef);337338 if (kept !== undefined) {339 objects.set(logRef, { ...kept, text: long });340 }341342 const cut = yield* world.rpc("dora").evidence(ref);343344 expect({345 bytes: new TextEncoder().encode(cut.text).length,346 isTail: long.endsWith(cut.text),347 truncated: cut.truncated,348 }).toStrictEqual({ bytes: 256 * 1024, isTail: true, truncated: true });349 }),350 60_000351 );352353 it.live(354 "never puts the log in another /rpc response or in git's remote: lines",355 () =>356 Effect.gen(function* () {357 const { aliceGit, pushed, work, world } = yield* refused;358359 // Read first: the refused answer is still alice's latest.360 const read = [361 ...(yield* everythingElse(world, "alice")),362 ...(yield* everythingElse(world, "bob")),363 ...(yield* everythingElse(world, "dora")),364 ...(yield* everythingElse(world, "anonymous")),365 ];366367 // Then alice tries again: this push's remote: lines are printed368 // while the refused answer's log is kept, unlike her first push's.369 yield* aliceGit.commit(work, "Read the year, trimmed", {370 "src/parse.ts":371 "export const parse = (iso: string) => ({ month: 0, year: Number(iso.slice(0, 4).trim()) });\n",372 });373374 const again = yield* aliceGit.push(work);375376 // The log whole, as JSON escapes it, and its one line no other377 // record of the run holds: the failure's signature.378 const needles = [379 unitLog,380 JSON.stringify(unitLog).slice(1, -1),381 "unit: scripted failure",382 ];383384 const seen = [pushed.stderr, again.stderr, ...read];385386 expect({387 again: {388 exitCode: again.exitCode,389 reached: again.stderr.includes("remote:"),390 },391 leaks: seen.filter((text) =>392 needles.some((needle) => text.includes(needle))393 ),394 }).toStrictEqual({ again: { exitCode: 0, reached: true }, leaks: [] });395 }),396 60_000397 );398});
modified:apps/platform/test/handlers.fixtures.ts+3 added-1 removed
10 unmodified lines
11import { RefName, RepoHost } from "@repo/artifacts/repo-host";12import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";13import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";14import { CheckRunner } from "@repo/checks/check-runner";15import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";16import { AlarmsMemory } from "@repo/project/alarms/memory";17import { AnswerRunsInline } from "@repo/project/answer-runs/inline";18import type { FrontPageSeed } from "@repo/project/front-page/memory";19import { FrontPageMemory } from "@repo/project/front-page/memory";
140 unmodified lines
160 ).pipe(Layer.provideMerge(LanderIsogit), Layer.provideMerge(allRed))161 )162 ),163 FrontPageMemory.layer(options.frontPage ?? noFrontPage),163 MemoryRateLimits(options.limits ?? { claim: 100, proposal: 100 })164 MemoryRateLimits(options.limits ?? { claim: 100, proposal: 100 }),165 EvidenceStoreMemory166 ).pipe(Layer.provideMerge(RepoHostMemory));167168/**169 * The scenario's project as its initializer makes it: made, its first
32 unmodified lines
modified:apps/platform/test/harness.ts+4 added-1 removed
1import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";2import { Upstream } from "@repo/git/upstream";3import { FrontPageMemory } from "@repo/project/front-page/memory";4import { Projects } from "@repo/project/projects";5import { Contracts } from "@repo/protocol/contracts";
136 unmodified lines
142143/**144 * The contracts before any project exists, served by the platform's own145 * handlers: a call that names a project finds none (`UnknownProject`), the145 * front page lists nothing, and nobody is near a rate limit.146 * front page lists nothing, nobody is near a rate limit, and no lane has147 * left a log.148 */149export const noProjects = Handlers.pipe(150 Layer.provide([151 Layer.succeed(
4 unmodified lines
156 })157 ),158 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),159 MemoryRateLimits(WorkerCaps),160 EvidenceStoreMemory,161 ])162);163164/**
45 unmodified lines
modified:apps/platform/test/project-do.fixtures.ts+2 added
14 unmodified lines
15import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";16import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";17import { CheckAt } from "@repo/checks/check-runner";18import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";19import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";20import { Lander } from "@repo/project/lander";21import { LanderIsogit } from "@repo/project/lander/isogit";22import { FinishersFromChecks } from "@repo/project/project";23import { ProjectionMemory } from "@repo/project/projection/memory";
334 unmodified lines
358export const world = Layer.mergeAll(359 alarms,360 answers,361 checker,362 EvidenceStoreMemory,363 ProjectionMemory,364 pusher,365 rules366).pipe(
110 unmodified lines
modified:apps/platform/test/world.ts+11 added-7 removed
13 unmodified lines
14 * queued in process.15 * - `CheckRunner` is W2's `/memory`, scripted by the test; `Lander` is W2's16 * `/isogit`; `RulesEvaluator` is W2's `/bun`, over the config folder as17 * committed; the front page, the rate limits and the evidence are kept in18 * memory.18 * memory, the evidence unless the test gives the world its own store.19 *20 * `settle` carries every queued answer run: 304's `runAnswer` over the same21 * ports, its steps kept in memory, as the Answer Workflow runs it over the22 * engine's. People are `dora` (who makes the project, so its decider),
6 unmodified lines
29import { RefName, RepoHost } from "@repo/artifacts/repo-host";30import { RepoHostLocal } from "@repo/artifacts/repo-host/local";31import type { CheckAt } from "@repo/checks/check-runner";32import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";33import type { EvidenceStore } from "@repo/checks/evidence-store";34import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";35import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";36import { AlarmsMemory } from "@repo/project/alarms/memory";37import { AnswerRuns } from "@repo/project/answer-runs";
138 unmodified lines
176 `echo password=${tokens[as]}`,177 "",178 ].join("\n");179179export const coreLoopWorld = (): Effect.Effect<180 CoreLoopWorld,181 never,182 Scope.Scope183> =>180/** What a test may set in its world: where lane logs are kept, in memory by default. */181export interface WorldOptions {182 readonly evidence?: Layer.Layer<EvidenceStore>;183}184185export const coreLoopWorld = (186 options: WorldOptions = {}187): Effect.Effect<CoreLoopWorld, never, Scope.Scope> =>188 Effect.gen(function* () {189 const node = yield* Layer.build(NodeServices.layer);190 const fs = Context.get(node, FileSystem.FileSystem);191 const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);
19 unmodified lines
211 UpstreamRepoHost,212 LanderIsogit,213 CheckRunnerMemory.layer(script),214 RulesEvaluatorBun.pipe(Layer.provide(FinishersFromChecks)),211 EvidenceStoreMemory,215 options.evidence ?? EvidenceStoreMemory,216 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),217 ProjectionMemory,218 MemoryRateLimits(WorkerCaps)219 ).pipe(
234 unmodified lines
modified:docs/reference/cli.md+20 added
471 unmodified lines
472| `--note` | text | no |473| `--project` | text | yes |474| `--verdict` | "vouch" \| "denounce" | yes |475476## `myr evidence`477478Show the log a failing lane left, by the logRef its verdict names, to the answer's own claimant and the project's deciders only; the last 256 KiB.479480```sh481myr evidence <ref> --project <project>482```483484- Contract: `evidence`485- Reads only: yes486- Idempotent: yes487- Destructive: no488- Needs approval: no489- Surfaces: rpc, cli490491| Argument | Takes | Required |492| --- | --- | --- |493| `<ref>` | text | yes |494| `--project` | text | yes |495496## `myr env set`497498Set the write-only value of a sensitive env item; nobody can read it back.499
17 unmodified lines
modified:docs/reference/commands.json+38 added
1082 unmodified lines
1083 "cli"1084 ]1085 },1086 {1087 "contract": "evidence",1088 "description": "Show the log a failing lane left, by the logRef its verdict names, to the answer's own claimant and the project's deciders only; the last 256 KiB.",1089 "destructive": false,1090 "idempotent": true,1091 "name": "evidence",1092 "needsApproval": false,1093 "path": [1094 "evidence"1095 ],1096 "payloadSchema": {1097 "additionalProperties": true,1098 "properties": {1099 "project": {1100 "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",1101 "type": "string"1102 },1103 "ref": {1104 "minLength": 1,1105 "type": "string"1106 }1107 },1108 "required": [1109 "project",1110 "ref"1111 ],1112 "type": "object"1113 },1114 "positional": [1115 "ref"1116 ],1117 "readOnly": true,1118 "source": "projected",1119 "surfaces": [1120 "rpc",1121 "cli"1122 ]1123 },1124 {1125 "contract": "setEnv",1126 "description": "Set the write-only value of a sensitive env item; nobody can read it back.",1127 "destructive": false,1128 "idempotent": true,
42 unmodified lines
modified:docs/reference/protocol.schema.json+49 added
3177 unmodified lines
3178 "project"3179 ],3180 "type": "object"3181 },3182 "evidence.error": {3183 "anyOf": [3184 {3185 "$ref": "#/$defs/UnknownProjectEncoded"3186 },3187 {3188 "$ref": "#/$defs/NotDeciderEncoded"3189 }3190 ]3191 },3192 "evidence.payload": {3193 "additionalProperties": true,3194 "properties": {3195 "project": {3196 "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",3197 "type": "string"3198 },3199 "ref": {3200 "minLength": 1,3201 "type": "string"3202 }3203 },3204 "required": [3205 "project",3206 "ref"3207 ],3208 "type": "object"3209 },3210 "evidence.success": {3211 "additionalProperties": true,3212 "properties": {3213 "lane": {3214 "pattern": "^[a-z][a-zA-Z0-9-]*$",3215 "type": "string"3216 },3217 "text": {3218 "type": "string"3219 },3220 "truncated": {3221 "type": "boolean"3222 }3223 },3224 "required": [3225 "lane",3226 "text",3227 "truncated"3228 ],3229 "type": "object"3230 },3231 "finish.error": {3232 "anyOf": [3233 {3234 "$ref": "#/$defs/UnknownProjectEncoded"
8475 unmodified lines
added:packages/checks/src/evidence-store/r2.ts+85 added
1/**2 * `EvidenceStore` over an R2 bucket: the stage's `evidence-<stage>` (spec3 * §4.4), so a lane's log outlives the isolate that ran its check. Each log4 * is one object, its key the log's own name (`logRefOf`), its body the text5 * whole, labelled with its project and lane and nothing else. Putting a log6 * again under the same name replaces it, so a replayed step converges7 * (principle 8).8 *9 * R2 is reached only through promises; each enters through10 * `Effect.tryPromise`, and a bucket that cannot be reached is a defect that11 * names the key, never the text: a log is for its readers alone.12 */13import { Data, Effect, Layer, Option } from "effect";1415import { EvidenceStore, logRefOf } from "../evidence-store.ts";1617/**18 * The part of an R2 bucket binding the store uses. Structural, so the Worker19 * passes its `EVIDENCE` binding itself; a type test holds `R2Bucket` to it20 * (`apps/platform/test/evidence.test.ts`).21 */22export interface EvidenceBucket {23 readonly put: (24 key: string,25 value: string,26 options: {27 readonly httpMetadata: { readonly contentType: string };28 readonly customMetadata: Record<string, string>;29 }30 ) => Promise<{ readonly key: string } | null>;31 readonly get: (32 key: string33 ) => Promise<{ readonly text: () => Promise<string> } | null>;34}3536/** R2 refused or never answered a call on one key: the store cannot go on. */37class EvidenceUnreachable extends Data.TaggedError("EvidenceUnreachable")<{38 readonly message: string;39 readonly cause: unknown;40}> {}4142/** One call on the bucket for `key`; a failure dies naming the key and the call. */43const reach = <A>(call: "get" | "put", key: string, run: () => Promise<A>) =>44 Effect.orDie(45 Effect.tryPromise({46 catch: (cause) =>47 new EvidenceUnreachable({48 cause,49 message: `the evidence bucket could not ${call} ${key}`,50 }),51 try: run,52 })53 );5455export const EvidenceStoreR2 = (56 bucket: EvidenceBucket57): Layer.Layer<EvidenceStore> =>58 Layer.succeed(59 EvidenceStore,60 EvidenceStore.of({61 get: (ref) =>62 Effect.flatMap(63 reach("get", ref, () => bucket.get(ref)),64 (found) =>65 Option.match(Option.fromNullishOr(found), {66 onNone: () => Effect.succeedNone,67 onSome: (object) =>68 Effect.asSome(reach("get", ref, () => object.text())),69 })70 ),71 put: (log) => {72 const ref = logRefOf(log);7374 return Effect.as(75 reach("put", ref, () =>76 bucket.put(ref, log.text, {77 customMetadata: { lane: log.lane, project: log.project },78 httpMetadata: { contentType: "text/plain; charset=utf-8" },79 })80 ),81 ref82 );83 },84 })85 );
modified:packages/checks/src/evidence-store.ts+39 added-7 removed
1 unmodified line
2 * The `EvidenceStore` port: where a lane's raw log goes, so a3 * `LaneResult.logRef` (and a `ChecksFailed.logRef`) names something real and4 * the log itself never travels to an answerer (spec §2.3 `LaneResult`).5 *6 * Adapters: `/memory` here, for tests and the Worker until W4 418 adds the7 * R2 adapter over the `evidence-<stage>` bucket (spec §4.4).6 * Adapters: `/memory`, for tests and the web's dev backend, and `/r2` over7 * the stage's `evidence-<stage>` bucket (spec §4.4), which the Worker runs.8 */9import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";10import { Context, Schema } from "effect";11import type { Effect, Option } from "effect";9import { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";10import { Context, Option, Schema } from "effect";11import type { Effect } from "effect";1213/**14 * A kept log's name: `<project>/<requestId>/<lane>#<attempt>`. It is15 * deterministic, so a replayed step overwrites its log, never adds a second
15 unmodified lines
31/** The name a lane's log is kept under, whichever adapter keeps it. */32export const logRefOf = (log: Omit<LaneLog, "text">): LogRef =>33 LogRef.make(`${log.project}/${log.requestId}/${log.lane}#${log.attempt}`);3435/** A log's name, read back into what it names. */36const LogName = Schema.TemplateLiteralParser([37 ProjectName,38 "/",39 RequestId,40 "/",41 LaneName,42 "#",43 Schema.Int,44]);4546/**47 * What a log's name points at: `logRefOf` read backwards, or `None` for a48 * name it never makes. None of its parts holds a `/` or a `#`; the attempt49 * reads as a number (`#01`, `#1.0` and `#+1` all read as 1), so a name is50 * kept only when `logRefOf` spells it back the same.51 */52export const logOfRef = (ref: string): Option.Option<Omit<LaneLog, "text">> =>53 Option.filter(54 Option.map(55 Schema.decodeUnknownOption(LogName)(ref),56 ([project, , requestId, , lane, , attempt]) => ({57 attempt,58 lane,59 project,60 requestId,61 })62 ),63 (log) => logRefOf(log) === ref64 );6566export class EvidenceStore extends Context.Service<67 EvidenceStore,68 {69 /** Keeps the log, replacing any kept under the same name. */70 readonly put: (log: LaneLog) => Effect.Effect<LogRef>;71 /**41 * A kept log, for deciders only: callers check the audience; the port42 * does not.72 * A kept log, for its answer's claimant and the project's deciders73 * only: callers check who asks (`ProjectApi.evidence`); the port does74 * not.75 */76 readonly get: (ref: LogRef) => Effect.Effect<Option.Option<string>>;77 }78>()("checks/EvidenceStore") {}
added:packages/checks/test/evidence-store-r2.test.ts+182 added
1import { describe, expect, it } from "@effect/vitest";2import { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";3import type { Layer } from "effect";4import { Cause, Effect, Exit, Option } from "effect";56import { EvidenceStore, LogRef } from "../src/evidence-store.ts";7import { EvidenceStoreR2 } from "../src/evidence-store/r2.ts";8import type { EvidenceBucket } from "../src/evidence-store/r2.ts";910/** One object as the fake bucket keeps it: its body and the options it was put with. */11interface Kept {12 readonly text: string;13 readonly options: Parameters<EvidenceBucket["put"]>[2];14}1516/**17 * An R2 bucket in memory, in the shape the Worker's `EVIDENCE` binding has:18 * `put` keeps a body under its key, replacing any there, and `get` answers19 * the body or `null`.20 */21const fakeBucket = () => {22 const objects = new Map<string, Kept>();2324 const bucket: EvidenceBucket = {25 get: (key) => {26 const kept = objects.get(key);2728 return Promise.resolve(29 kept === undefined ? null : { text: () => Promise.resolve(kept.text) }30 );31 },32 put: (key, text, options) => {33 objects.set(key, { options, text });3435 return Promise.resolve({ key });36 },37 };3839 return { bucket, objects };40};4142/** A bucket whose every call fails, as R2 does when it cannot be reached. */43const brokenBucket: EvidenceBucket = {44 get: () => Promise.reject(new Error("R2 is unreachable")),45 put: () => Promise.reject(new Error("R2 is unreachable")),46};4748const unitLog = {49 attempt: 1,50 lane: LaneName.make("unit"),51 project: ProjectName.make("datekit"),52 requestId: RequestId.make("push-0123456789"),53 text: "FAIL test/parse.test.ts > parses ISO weeks\nexpected 52 to be 53",54};5556const key = "datekit/push-0123456789/unit#1";5758/** How a call ended, as its defect prints. */59const printed = <A>(call: Effect.Effect<A>) =>60 Effect.map(Effect.exit(call), (exit) =>61 Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "it succeeded"62 );6364/** The store over `bucket`, as the Worker composes it. */65const over = (bucket: EvidenceBucket) =>66 Effect.provide(EvidenceStoreR2(bucket) satisfies Layer.Layer<EvidenceStore>);6768describe("EvidenceStore over an R2 bucket", () => {69 it.effect(70 "keeps a lane's log under its project, request, lane and attempt, as plain text",71 () => {72 const { bucket, objects } = fakeBucket();7374 return Effect.gen(function* () {75 const store = yield* EvidenceStore;76 const ref = yield* store.put(unitLog);7778 expect({79 got: yield* store.get(ref),80 kept: [...objects].map(([name, { options, text }]) => ({81 contentType: options.httpMetadata.contentType,82 name,83 text,84 })),85 ref,86 }).toStrictEqual({87 got: Option.some(unitLog.text),88 kept: [89 {90 contentType: "text/plain; charset=utf-8",91 name: key,92 text: unitLog.text,93 },94 ],95 ref: key,96 });97 }).pipe(over(bucket));98 }99 );100101 it.effect(102 "overwrites a replayed attempt's log under the same key, never a second object",103 () => {104 const { bucket, objects } = fakeBucket();105106 return Effect.gen(function* () {107 const store = yield* EvidenceStore;108 const first = yield* store.put(unitLog);109 const replayed = yield* store.put({ ...unitLog, text: "replayed" });110111 expect({112 got: yield* store.get(first),113 keys: [...objects.keys()],114 refs: [first, replayed],115 }).toStrictEqual({116 got: Option.some("replayed"),117 keys: [key],118 refs: [key, key],119 });120 }).pipe(over(bucket));121 }122 );123124 it.effect("keeps a log over 1 MiB whole, and gives it back whole", () => {125 const { bucket } = fakeBucket();126 const long = `${"x".repeat(1024 * 1024)}\nexpected 52 to be 53`;127128 return Effect.gen(function* () {129 const store = yield* EvidenceStore;130 const ref = yield* store.put({ ...unitLog, text: long });131132 expect(yield* store.get(ref)).toStrictEqual(Option.some(long));133 }).pipe(over(bucket));134 });135136 it.effect("has nothing under a key it never kept", () =>137 Effect.gen(function* () {138 const store = yield* EvidenceStore;139140 expect(141 yield* store.get(LogRef.make("datekit/push-0123456789/lint#1"))142 ).toStrictEqual(Option.none());143 }).pipe(over(fakeBucket().bucket))144 );145146 it.effect(147 "labels each object with its project and lane, and nothing else",148 () => {149 const { bucket, objects } = fakeBucket();150151 return Effect.gen(function* () {152 yield* (yield* EvidenceStore).put(unitLog);153154 expect(objects.get(key)?.options.customMetadata).toStrictEqual({155 lane: "unit",156 project: "datekit",157 });158 }).pipe(over(bucket));159 }160 );161162 it.effect(163 "dies naming the key, never the log, when the bucket cannot be reached",164 () =>165 Effect.gen(function* () {166 const store = yield* EvidenceStore;167168 const deaths = [169 yield* printed(store.put(unitLog)),170 yield* printed(store.get(LogRef.make(key))),171 ];172173 expect(deaths.map((death) => death.includes(key))).toStrictEqual([174 true,175 true,176 ]);177 expect(178 deaths.some((death) => death.includes("expected 52"))179 ).toBeFalsy();180 }).pipe(over(brokenBucket))181 );182});
modified:packages/config/test/gen.test.ts+7 added-6 removed
252 unmodified lines
253 leaks(parseJson(content("docs/reference/protocol.schema.json")))254 ).toStrictEqual([]);255 });256257 // A stream has no tool form, and a write-only value must never pass258 // through an agent's transcript.259 it("lists only the tools MCP serves: no watch, no setEnv", () => {257 // A stream has no tool form, and a write-only value or a lane's log258 // must never pass through an agent's transcript.259 it("lists only the tools MCP serves: no watch, no setEnv, no evidence", () => {260 const tools = [...sections(content("docs/reference/mcp-tools.md")).keys()];261262 expect(tools).toContain("listProjects");263 expect(tools).toContain("submitAnswer");264 expect(tools).not.toContain("watch");265 expect(tools).not.toContain("setEnv");266 expect(tools).toHaveLength(contracts.length - 2);264 expect(265 ["watch", "setEnv", "evidence"].filter((tag) => tools.includes(tag))266 ).toStrictEqual([]);267 expect(tools).toHaveLength(contracts.length - 3);268 });269270 it("gives every MCP tool's input and output schema, with no leak in either", () => {271 const reference = content("docs/reference/mcp-tools.md");
124 unmodified lines
modified:packages/project/src/project.ts+110 added-3 removed
17 unmodified lines
18import type { RepoNotFound } from "@repo/artifacts/repo-host";19import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";20import { Brand } from "@repo/brand";21import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";22import { EvidenceStore, LogRef, logOfRef } from "@repo/checks/evidence-store";23import { findRunBlock } from "@repo/checks/finder";24import { judgeClosure } from "@repo/checks/judge";25import { checkVersion, commandFor } from "@repo/checks/kinds";26import { redFirstOfRuns } from "@repo/checks/red-first";
9 unmodified lines
36 Claim as ClaimContract,37 Credits,38 Decide,39 EnvSchemaOf,40 EvidenceOf,41 Finish,42 FlagAsk,43 Fork,44 InitProject,
61 unmodified lines
106 StaleBase,107 TouchedJudge,108 UnknownAsk,109 UnknownCommit,110 UnknownProject,111 VerifierBlocked,112 WeakCheck,113} from "@repo/protocol/refusal";114import type {
180 unmodified lines
295 readonly landing: (296 caller: Principal,297 sha: CommitSha298 ) => Effect.Effect<{ readonly landing: LandingView }, UnknownCommit>;299 /**300 * The log a failing lane left, by the name its verdict gives it (spec301 * §2.3 `LaneResult.logRef`), for the project's deciders and the claimant302 * of the answer the name points at. A name `logRefOf` never makes, or one303 * that points at another project, is `UnknownProject` for anyone; past304 * that, anyone else is `NotDecider` whether or not a log is kept under the305 * name, and a reader allowed in finds no log kept as `UnknownProject`306 * too. A log over 256 KiB comes back as its last 256 KiB, where a307 * failure prints. The log is read from the `EvidenceStore` the call runs308 * with (the stage's bucket), outside the project's lock.309 */310 readonly evidence: (311 caller: Principal,312 ref: LogRef313 ) => Effect.Effect<314 {315 readonly lane: LaneName;316 readonly text: string;317 readonly truncated: boolean;318 },319 NotDecider | UnknownProject,320 EvidenceStore321 >;322 readonly events: (323 since: number,324 limit: number325 ) => Effect.Effect<
131 unmodified lines
457 success: Schema.Array(458 Schema.Struct({ event: ProjectEvent, seq: Schema.Int })459 ),460 },461 evidence: {462 args: [Principal, LogRef],463 error: EvidenceOf.errorSchema,464 success: EvidenceOf.successSchema,465 },466 finish: {467 args: [Person, Finish.payloadSchema.mapFields(Struct.omit(["project"]))],468 error: Finish.errorSchema,469 success: Finish.successSchema,
157 unmodified lines
627 * schema's type side: a value that is not one is the caller's defect, since628 * the boundary that decoded it would have refused it) and the check that its629 * success encodes.630 */600const checked = <A, E>(631const checked = <A, E, R>(632 schemas: MethodSchema,633 args: readonly unknown[],603 run: Effect.Effect<A, E>604): Effect.Effect<A, E> =>634 run: Effect.Effect<A, E, R>635): Effect.Effect<A, E, R> =>636 Effect.forEach(637 schemas.args,638 (schema, index) =>639 Effect.orDie(
6 unmodified lines
646 Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))647 )648 );649650/** The most of a lane's log `evidence` gives back: its last 256 KiB. */651const EVIDENCE_TAIL = 256 * 1024;652653/** Whether a UTF-8 byte starts a character: it is no continuation byte (`10xxxxxx`). */654const startsCharacter = (byte: number) => byte < 0x80 || byte >= 0xc0;655656/**657 * A log as `evidence` gives it back: whole up to 256 KiB, else its last658 * 256 KiB, where a failure prints, cut between characters, never inside one.659 */660const tailOf = (log: string) => {661 const bytes = new TextEncoder().encode(log);662663 if (bytes.length <= EVIDENCE_TAIL) {664 return { text: log, truncated: false };665 }666667 const tail = bytes.subarray(bytes.length - EVIDENCE_TAIL);668 const from = tail.findIndex(startsCharacter);669670 return {671 text: from === -1 ? "" : new TextDecoder().decode(tail.subarray(from)),672 truncated: true,673 };674};675676const mainRef = RefName.make("refs/heads/main");677678const HOUR = 3_600_000;679
2281 unmodified lines
29612962 return Effect.succeed(field("verdict", verdict));2963 });29642965 // ---------------------------------------------------------- evidence29662967 /**2968 * Who may read the log named `ref`, and then the log: the name must2969 * point at this project (anything else is that project unknown, as a2970 * name nobody made is); then the caller must decide here, or be the2971 * claimant of the answer it points at (`NotDecider` otherwise, whether2972 * or not a log is kept, so the reply tells no one which logs exist);2973 * then the log must be kept.2974 */2975 const evidenceOf = (caller: Principal, ref: LogRef) =>2976 Effect.gen(function* () {2977 const named = logOfRef(ref);29782979 if (Option.isNone(named) || named.value.project !== name) {2980 return yield* new UnknownProject({2981 project: Option.match(named, {2982 onNone: () => name,2983 onSome: ({ project }) => project,2984 }),2985 });2986 }29872988 const { lane, requestId } = named.value;2989 const h = yield* hydrate;29902991 const allowed = Principal.match(caller, {2992 Anonymous: () => false,2993 Person: ({ handle }) =>2994 Option.exists(h.policy, (policy) => isDecider(policy, handle)) ||2995 Option.exists(findAnswer(h, requestId), ({ row }) =>2996 sameHandle(row.answerer, handle)2997 ),2998 });29993000 if (!allowed) {3001 return yield* new NotDecider({});3002 }30033004 const kept = yield* EvidenceStore.use((logs) => logs.get(ref));30053006 if (Option.isNone(kept)) {3007 return yield* new UnknownProject({ project: name });3008 }30093010 return { lane, ...tailOf(kept.value) };3011 });30123013 // ---------------------------------------------------------- deciders30143015 /** The decider-facing methods (221), over the same hydrate, write and helpers. */3016 const decided = deciders<Hydrated, Writes>({
79 unmodified lines
3096 Effect.map(store.eventsSince(since, limit), (rows) =>3097 rows.map(({ event, seq }) => ({ event, seq }))3098 )3099 ),3100 evidence: (caller, ref) =>3101 checked(MethodSchemas.evidence, [caller, ref], evidenceOf(caller, ref)),3102 finish: (caller, input) =>3103 checked(3104 MethodSchemas.finish,3105 [caller, input],
123 unmodified lines
added:packages/project/test/evidence.test.ts+325 added
1/**2 * Who may read a failing lane's log (`ProjectApi.evidence`): the claimant of3 * the answer the log's name points at, and the project's deciders. Anyone4 * else hears `NotDecider` whatever the name, and a name that points at5 * another project is `UnknownProject`, so no reply tells which logs exist.6 */7import { describe, expect, it } from "@effect/vitest";8import { RefName, RepoHost } from "@repo/artifacts/repo-host";9import { EvidenceStore, LogRef, logRefOf } from "@repo/checks/evidence-store";10import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";11import { CheckSpec } from "@repo/protocol/domain/check";12import {13 AskId,14 LandedSha,15 LaneName,16 ProjectName,17 RepoName,18 RepoPath,19 RequestId,20} from "@repo/protocol/ids";21import { Anonymous, Person } from "@repo/protocol/principal";22import { NotDecider, UnknownProject } from "@repo/protocol/refusal";23import { advanceTo } from "@repo/testkit/clock";24import type { Files } from "@repo/testkit/git-client";25import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";26import { Array, Effect, Layer, Option } from "effect";2728import { projectService } from "../src/project.ts";29import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";3031const scenario = aProject({ people: ["bob", "carol"] }).pipe(32 withVouches(["bob", "carol"]),33 withAsk({ id: "parse-iso", territory: "packages/parser" })34);3536const { project } = scenario;3738const repo = RepoName.make(project);3940const person = (name: string) =>41 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });4243/** The project's decider. */44const alice = person("alice");4546/** The claimant whose answer failed its `unit` lane. */47const bob = person("bob");4849/** Neither: vouched for, but no claimant of that answer and no decider. */50const carol = person("carol");5152const parseIso = AskId.make("parse-iso");5354const unit = LaneName.make("unit");5556const requestId = RequestId.make("req-fix-0001");5758const mainRef = RefName.make("refs/heads/main");5960const start: Files = [61 ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],62 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],63];6465/** The ask's own files: its file in the config folder, and its check. */66const askFiles = () => {67 const ask = Option.getOrThrow(68 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)69 );7071 return Array.make(72 { content: `export default "${parseIso}";\n`, path: ask.file },73 {74 content: [75 `import { expect, it } from "vitest";`,76 `import { parser } from "../src/parser.ts";`,77 ``,78 `it("${parseIso}", () => {`,79 ` expect(parser("2026-10-07")).toStrictEqual({ year: 2026 });`,80 `});`,81 ``,82 ].join("\n"),83 path: CheckSpec.guards.RedThenGreen(ask.check)84 ? ask.check.path85 : RepoPath.make("test/parse-iso.test.ts"),86 }87 );88};8990/** The log bob's `unit` lane left on his answer's first merge. */91const failing = [92 "FAIL packages/parser/test/parse.test.ts > parses ISO weeks",93 "AssertionError: expected 52 to be 53",94].join("\n");9596/** The name the log is kept under. */97const bobsLog = logRefOf({ attempt: 1, lane: unit, project, requestId });9899const mainTip = Effect.gen(function* () {100 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);101102 return LandedSha.make(103 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))104 );105});106107/**108 * alice makes the project and opens parse-iso; bob claims it and answers109 * under `requestId`; the answer's `unit` lane left `text` under its name.110 */111const answered = (text: string = failing) =>112 Effect.gen(function* () {113 yield* advanceTo("2026-10-07T12:00:00Z");114115 const api = yield* projectService(project);116117 yield* api.initProject(alice, {});118119 const first = yield* Pusher.use((pusher) =>120 pusher.push(repo, Option.none(), start, "Start")121 );122123 yield* api.recordFirstPush(alice, first);124125 const files = askFiles();126 const composed = yield* composedAt(repo, yield* mainTip, files);127128 yield* CheckScript.use((checker) =>129 checker.script(composed, LaneName.make("redThenGreen"), [130 "failed",131 "failed",132 ])133 );134135 const { landed } = yield* api.openAsk(alice, { ask: parseIso, files });136 const { claim } = yield* api.claim(bob, parseIso);137138 const head = yield* Pusher.use((pusher) =>139 pusher.push(claim.fork, Option.some(landed), [140 ...start.filter(([path]) => !path.startsWith("packages/parser/")),141 ["packages/parser/src/parse.ts", "export const parse = () => 2026;\n"],142 ...files.map(({ content, path }) => [path, content] as const),143 ])144 );145146 yield* api.submitAnswer(bob, {147 ask: parseIso,148 base: landed,149 head,150 requestId,151 });152153 yield* (yield* EvidenceStore).put({154 attempt: 1,155 lane: unit,156 project,157 requestId,158 text,159 });160161 return api;162 });163164const world = Layer.merge(worldOf(scenario, "memory"), EvidenceStoreMemory);165166describe("reading a failing lane's log", () => {167 it.effect(168 "gives the answer's claimant and the project's deciders the log, whole",169 () =>170 Effect.gen(function* () {171 const api = yield* answered();172173 expect({174 alice: yield* api.evidence(alice, bobsLog),175 bob: yield* api.evidence(bob, bobsLog),176 }).toStrictEqual({177 alice: { lane: unit, text: failing, truncated: false },178 bob: { lane: unit, text: failing, truncated: false },179 });180 }).pipe(Effect.provide(world))181 );182183 it.effect(184 "refuses everyone else NotDecider, whether or not a log is kept under the name",185 () =>186 Effect.gen(function* () {187 const api = yield* answered();188189 const never = logRefOf({190 attempt: 7,191 lane: unit,192 project,193 requestId: RequestId.make("req-none-0001"),194 });195196 expect(197 yield* Effect.forEach(198 [199 api.evidence(carol, bobsLog),200 api.evidence(carol, never),201 api.evidence(Anonymous.make({}), bobsLog),202 // bob is the claimant of his own answer only.203 api.evidence(bob, never),204 ],205 Effect.flip206 )207 ).toStrictEqual([208 new NotDecider({}),209 new NotDecider({}),210 new NotDecider({}),211 new NotDecider({}),212 ]);213 }).pipe(Effect.provide(world))214 );215216 it.effect(217 "refuses a name that points at another project as that project unknown, for anyone",218 () =>219 Effect.gen(function* () {220 const api = yield* answered();221 const other = ProjectName.make("burrow");222223 const elsewhere = logRefOf({224 attempt: 1,225 lane: unit,226 project: other,227 requestId,228 });229230 expect(231 yield* Effect.forEach(232 [233 api.evidence(alice, elsewhere),234 api.evidence(bob, elsewhere),235 api.evidence(carol, elsewhere),236 ],237 Effect.flip238 )239 ).toStrictEqual([240 new UnknownProject({ project: other }),241 new UnknownProject({ project: other }),242 new UnknownProject({ project: other }),243 ]);244 }).pipe(Effect.provide(world))245 );246247 it.effect(248 "refuses a name that is no log's, or names no kept log, as nothing in the project",249 () =>250 Effect.gen(function* () {251 const api = yield* answered();252253 const passed = logRefOf({254 attempt: 1,255 lane: LaneName.make("lint"),256 project,257 requestId,258 });259260 // bob's own log's name, spelled as `logRefOf` never spells one.261 const respelled = LogRef.make(bobsLog.replace(/#1$/u, "#01"));262263 expect(264 yield* Effect.forEach(265 [266 api.evidence(alice, LogRef.make("not a log's name")),267 api.evidence(carol, LogRef.make("not a log's name")),268 api.evidence(alice, respelled),269 api.evidence(carol, respelled),270 api.evidence(alice, passed),271 ],272 Effect.flip273 )274 ).toStrictEqual([275 new UnknownProject({ project }),276 new UnknownProject({ project }),277 new UnknownProject({ project }),278 new UnknownProject({ project }),279 new UnknownProject({ project }),280 ]);281 }).pipe(Effect.provide(world))282 );283284 it.effect(285 "gives a log over 256 KiB as its last 256 KiB, where the failure prints",286 () =>287 Effect.gen(function* () {288 const tail = "AssertionError: expected 52 to be 53\n";289 const long = `${"x".repeat(300 * 1024)}${tail}`;290 const api = yield* answered(long);291 const read = yield* api.evidence(bob, bobsLog);292293 expect({294 bytes: new TextEncoder().encode(read.text).length,295 endsWithFailure: read.text.endsWith(tail),296 isTail: long.endsWith(read.text),297 truncated: read.truncated,298 }).toStrictEqual({299 bytes: 256 * 1024,300 endsWithFailure: true,301 isTail: true,302 truncated: true,303 });304 }).pipe(Effect.provide(world))305 );306307 it.effect("cuts a long log between characters, never inside one", () =>308 Effect.gen(function* () {309 // Each "é" is two bytes, so 256 KiB from the end falls inside one.310 const long = `${"é".repeat(150 * 1024)}x`;311 const api = yield* answered(long);312 const read = yield* api.evidence(alice, bobsLog);313314 expect({315 bytes: new TextEncoder().encode(read.text).length,316 isTail: long.endsWith(read.text),317 truncated: read.truncated,318 }).toStrictEqual({319 bytes: 256 * 1024 - 1,320 isTail: true,321 truncated: true,322 });323 }).pipe(Effect.provide(world))324 );325});
modified:packages/protocol/src/contracts.ts+34 added
37 unmodified lines
38 EnvKey,39 Handle,40 KindName,41 LandedSha,42 LaneName,43 ProjectName,44 RepoName,45 RequestId,46} from "./ids.ts";
59 unmodified lines
106 claim: ["rpc", "mcp", "cli"],107 credits: SurfaceName.literals,108 decide: SurfaceName.literals,109 [envSchemaTag]: SurfaceName.literals,110 // A log may hold text an agent's transcript should not carry: never MCP.111 evidence: ["rpc", "cli"],112 finish: ["rpc", "mcp", "cli"],113 flagAsk: ["rpc", "mcp", "cli"],114 fork: ["rpc", "mcp", "cli"],115 frontPage: SurfaceName.literals,
587 unmodified lines
703 .annotate(NeedsApproval, true)704 .annotate(Cli, { name: "vouch" })705 .annotate(Surfaces, servedOn.vouch) {}706707export class EvidenceOf extends Rpc.make("evidence", {708 error: Schema.Union([UnknownProject, NotDecider]),709 payload: {710 project: ProjectName,711 /** The `logRef` a verdict's lane or a `ChecksFailed` refusal names. */712 ref: Schema.NonEmptyString,713 },714 success: Schema.Struct({715 lane: LaneName,716 /** The log's tail: its last 256 KiB, where a failure prints. */717 text: Schema.String,718 /** Whether the log was longer than the tail given back. */719 truncated: Schema.Boolean,720 }),721})722 .annotate(723 Description,724 "Show the log a failing lane left, by the logRef its verdict names, to the answer's own claimant and the project's deciders only; the last 256 KiB."725 )726 // The handler lets in the answer's claimant and the project's deciders.727 .annotate(Audience, "signedIn")728 // A log is for its answerer and the deciders: no cache keeps it.729 .annotate(Visibility, "maintainers")730 .annotate(ReadOnly, true)731 .annotate(Idempotent, true)732 .annotate(Destructive, false)733 .annotate(NeedsApproval, false)734 .annotate(Cli, { name: "evidence", positional: ["ref"] })735 .annotate(Surfaces, servedOn.evidence) {}736737export class SetEnv extends Rpc.make("setEnv", {738 error: Schema.Union([739 UnknownProject,740 NotDecider,
54 unmodified lines
795 Finish,796 Land,797 Fork,798 Vouch,799 EvidenceOf,800 SetEnv801).middleware(Authenticated) {}802803/** Every contract in the group, as its handlers and clients see it. */
60 unmodified lines
modified:packages/protocol/src/testing.ts+1 added
33 unmodified lines
34 credits: uncalled,35 decide: uncalled,36 // Keyed by the class: lint keeps "shape" out of code names.37 [EnvSchemaOf._tag]: uncalled,38 evidence: uncalled,39 finish: uncalled,40 flagAsk: uncalled,41 fork: uncalled,42 frontPage: uncalled,
18 unmodified lines
modified:packages/protocol/test/fixtures/contracts.json+11 added
93 unmodified lines
94 ],95 "project": "datekit"96 }97 },98 "evidence": {99 "payload": {100 "project": "datekit",101 "ref": "datekit/push-1111111111111111111111111111111111111111-alice/unit#1"102 },103 "success": {104 "lane": "unit",105 "text": "FAIL test/parse.test.ts > parses ISO weeks\nexpected 52 to be 53",106 "truncated": false107 }108 },109 "finish": {110 "payload": {111 "ask": "iso-week",112 "base": "1111111111111111111111111111111111111111",
602 unmodified lines
modified:packages/protocol/test/contracts.test.ts+13 added-3 removed
267 unmodified lines
268 on: "RMC",269 tag: "vouch",270 },271 {272 audience: "signedIn",273 cli: "evidence <ref>",274 errors: ["UnknownProject", "NotDecider"],275 flags: "RI",276 on: "RC",277 tag: "evidence",278 },279 {280 audience: "decider",281 cli: "env set",282 errors: [283 "UnknownProject",
122 unmodified lines
406 ).toStrictEqual(table.map(({ cli, tag }) => ({ cli, tag })));407 });408409 // Web caching reads it: no cache may keep a response for maintainers.402 it("sets each contract's visibility explicitly, keeping only a decider's Today and decisions to maintainers", () => {410 it("sets each contract's visibility explicitly, keeping only a decider's Today and decisions, and a lane's log, to maintainers", () => {411 expect(412 contracts.flatMap((rpc) => {413 const visibility = Context.getOrUndefined(rpc.annotations, Visibility);414
1 unmodified line
416 })417 ).toStrictEqual([418 { tag: "today", visibility: "maintainers" },419 { tag: "decide", visibility: "maintainers" },420 { tag: "evidence", visibility: "maintainers" },421 ]);422 });423424 it("lets each contract refuse only with its own subset of refusals", () => {
74 unmodified lines
499 // annotations come from, so a tool or command the type names exists.500 it("types each surface's group as the contracts on it", () => {501 expectTypeOf<TagOn<"rpc">>().toEqualTypeOf<Contract["_tag"]>();502 expectTypeOf<TagOn<"mcp">>().toEqualTypeOf<494 Exclude<Contract["_tag"], "setEnv" | "watch">503 Exclude<Contract["_tag"], "evidence" | "setEnv" | "watch">504 >();505 expectTypeOf<TagOn<"cli">>().toEqualTypeOf<506 Exclude<Contract["_tag"], "watch">507 >();508 });509501 it("never gives MCP a stream, or a contract that carries a write-only value", () => {510 it("never gives MCP a stream, a contract that carries a write-only value, or a lane's log", () => {511 const mcp = [...surfaced("mcp").requests.values()];512513 expect(mcp.map(({ _tag }) => _tag)).not.toContain("setEnv");514 expect(mcp.map(({ _tag }) => _tag)).not.toContain("evidence");515 expect(516 mcp.flatMap((rpc) =>517 RpcSchema.isStreamSchema(rpc.successSchema) ? [rpc._tag] : []518 )
3 unmodified lines