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
Provenance
- Commit
8381fc6- Tree
49bdefb- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
e6a2d4a- Parent 2
909da56
24 files changed+1384 added−39 removed
modified:apps/platform/src/adapters/do-projects.ts+3 added
89 unmodified lines9091929394959697989910068 unmodified lines89 unmodified lines claim: (caller, ask) => assumingMade(on("claim", [caller, ask])), credits: (caller, handle) => on("credits", [caller, handle]), decide: (caller, input) => assumingMade(on("decide", [caller, input])), events: (since, limit) => on("events", [since, limit]), // A name pointing at another project is the service's own // `UnknownProject`, so it crosses as the refusal it is. evidence: (caller, ref) => on("evidence", [caller, ref]), finish: (caller, input) => assumingMade(on("finish", [caller, input])), firstPusher: () => on("firstPusher", []), flagAsk: (caller, input) => assumingMade(on("flagAsk", [caller, input])), fork: (caller) => assumingMade(on("fork", [caller])),68 unmodified linesmodified:apps/platform/src/handlers.ts+13 added-1 removed
5 unmodified lines6 * `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 */16+import { EvidenceStore, LogRef } from "@repo/checks/evidence-store";17 import { envSchemaMethod } from "@repo/project/deciders";18 import { FrontPage } from "@repo/project/front-page";19 import { GatewayUrl } from "@repo/project/project";20 import type { ProjectApi } from "@repo/project/project";128 unmodified lines149 */150 export 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;160 161 /** `call` on the project named `project`; one never made is `UnknownProject`. */162 const on = <A, E>(163 project: ProjectName,45 unmodified lines209 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 linesmodified:apps/platform/src/ports.ts+3 added-3 removed
16 unmodified lines17 import type { RepoHost } from "@repo/artifacts/repo-host";18 import { RepoHostBinding } from "@repo/artifacts/repo-host/binding";19 import type { CheckRunner } from "@repo/checks/check-runner";20 import type { EvidenceStore } from "@repo/checks/evidence-store";21-import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";21+import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";22 import type { Upstream } from "@repo/git/upstream";23 import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";24 import type { FrontPage } from "@repo/project/front-page";25 import { FrontPageMemory } from "@repo/project/front-page/memory";44 unmodified lines70 * 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 */76 export const workerPorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>77 Layer.mergeAll(78 memoryFrontPage,16 unmodified lines95 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 lines102 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 linesmodified:apps/platform/src/project-shell.ts+23 added-6 removed
9 unmodified lines10 * 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 */14+import { EvidenceStore } from "@repo/checks/evidence-store";15 import { projectService } from "@repo/project/project";16 import type { ProjectApi, ProjectPorts } from "@repo/project/project";17 import { ProjectStore } from "@repo/project/project-store";18 import { ProjectStoreSqlite } from "@repo/project/project-store/sqlite";26 unmodified lines45 }46 47 /**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 */52 type 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 };61 62 /** The DO has no name, and its storage holds no project to take one from. */5 unmodified lines68 /** 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 lines86 )87 );88 89 const store = Context.get(context, ProjectStore);90+91+ /** 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+ );96+97 const made = yield* Ref.make(false);98 const built = yield* SynchronizedRef.make(Option.none<Methods>());99 100 /** Whether `initProject` has made the project; once it has, it stays made. */67 unmodified lines168 ).pipe(Effect.orDie);169 }170 171 const api = yield* service;157- const outcome = yield* Effect.exit(api[method](...args));172+ const outcome = yield* Effect.exit(withEvidence(api[method](...args)));173 174 return yield* Schema.encodeUnknownEffect(call.exit)(outcome).pipe(175 Effect.orDie176 );3 unmodified lines180 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 linesmodified:apps/platform/test/do-projects.test.ts+9 added-1 removed
1 import { describe, expect, expectTypeOf, it } from "@effect/vitest";2+import { LogRef } from "@repo/checks/evidence-store";3 import { envSchemaMethod } from "@repo/project/deciders";4 import { LandingCommand } from "@repo/project/landing";5 import type { ProjectApi } from "@repo/project/project";6 import { Projects } from "@repo/project/projects";38 unmodified lines45 46 const requestId = RequestId.make("req-none0001");47 48 /** A call's `Exit` as JSON, by its method's own schemas: equal when the outcomes are. */48-const settled = <A, E>(method: ProjectMethod, effect: Effect.Effect<A, E>) =>49+const 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 lines78 })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 linesadded: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+ */10+import { describe, expect, expectTypeOf, it } from "@effect/vitest";11+import { Brand } from "@repo/brand";12+import { CheckAt } from "@repo/checks/check-runner";13+import { EvidenceStore } from "@repo/checks/evidence-store";14+import { EvidenceStoreR2 } from "@repo/checks/evidence-store/r2";15+import type { EvidenceBucket } from "@repo/checks/evidence-store/r2";16+import { Outcome } from "@repo/protocol/domain/outcome";17+import {18+ AskId,19+ CommitSha,20+ Handle,21+ LaneName,22+ ProjectName,23+ RepoPath,24+ RequestId,25+ TreeSha,26+} from "@repo/protocol/ids";27+import { Unauthenticated } from "@repo/protocol/principal";28+import {29+ ChecksFailed,30+ NotDecider,31+ UnknownProject,32+} from "@repo/protocol/refusal";33+import { Array, Cause, Effect, Exit, Stream } from "effect";34+35+import { decodeEnv } from "../src/platform.ts";36+import { workerPorts } from "../src/ports.ts";37+import { fakeEnv } from "./fake-env.ts";38+import { coreLoopWorld } from "./world.ts";39+import type { Someone } from "./world.ts";40+41+const project = ProjectName.make("datekit");42+43+const parseIso = AskId.make("parse-iso");44+45+const redThenGreen = LaneName.make("redThenGreen");46+47+const unit = LaneName.make("unit");48+49+const sdk = `${Brand.cliPackage}/rules`;50+51+/** The project as dora first pushes it: its run block has a `unit` lane. */52+const 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+};68+69+const 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+);96+97+/**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+ */101+const unitLog = [102+ "unit: failed in 1 ms",103+ "$ run unit",104+ "unit: scripted failure",105+].join("\n");106+107+/** One object as the fake bucket keeps it. */108+interface Kept {109+ readonly text: string;110+ readonly customMetadata: Readonly<Record<string, string>>;111+}112+113+/** The stage's evidence bucket in memory, in the shape of the Worker's `EVIDENCE` binding. */114+const fakeBucket = () => {115+ const objects = new Map<string, Kept>();116+117+ const bucket: EvidenceBucket = {118+ get: (key) => {119+ const kept = objects.get(key);120+121+ 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 });127+128+ return Promise.resolve({ key });129+ },130+ };131+132+ return { bucket, objects };133+};134+135+/**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+ */140+const 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");147+148+ const made = yield* dora.initProject({ project });149+ const home = yield* doraGit.clone(made.remote);150+151+ yield* doraGit.commit(home, "Start datekit", start);152+ yield* doraGit.push(home);153+154+ yield* world.script(155+ CheckAt.cases.Commit.make({156+ commit: yield* world.composed(project, askFiles),157+ }),158+ redThenGreen,159+ ["failed", "failed"]160+ );161+162+ const opened = yield* dora.openAsk({163+ ask: parseIso,164+ files: askFiles,165+ project,166+ });167+168+ const { claim } = yield* alice.claim({ ask: parseIso, project });169+ const work = yield* aliceGit.clone(claim.remote);170+171+ 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+ });175+176+ const pushed = yield* aliceGit.push(work);177+178+ const tree = TreeSha.make(179+ yield* aliceGit.ok(work, "rev-parse", `${fix}^{tree}`)180+ );181+182+ const merged = CheckAt.cases.Tree.make({ tree });183+184+ 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+ );191+192+ yield* world.settle();193+194+ const { verdict } = yield* alice.verdict({ ask: parseIso, project });195+196+ const logRef = verdict?.lanes.find(({ lane }) => lane === unit)?.logRef ?? "";197+198+ return { aliceGit, logRef, objects, pushed, verdict, work, world };199+});200+201+/** How a read ended, success or refusal, as JSON. */202+const json = <A, E>(read: Effect.Effect<A, E>) =>203+ Effect.map(Effect.exit(read), (exit) => JSON.stringify(exit));204+205+/** Everything `who` can read over `/rpc` besides `evidence`, as JSON. */206+const everythingElse = (207+ world: Effect.Success<typeof refused>["world"],208+ who: Someone | "anonymous"209+) =>210+ Effect.gen(function* () {211+ const rpc = world.rpc(who);212+213+ 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+ });227+228+describe("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+ });232+233+ 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);238+239+ 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+ );250+251+ // 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+ );257+258+ 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;263+264+ 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+ );281+282+ 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 };288+289+ const asked = (who: Someone | "anonymous", payload = ref) =>290+ Effect.exit(world.rpc(who).evidence(payload));291+292+ // 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") });297+298+ const elsewhere = (other: string) => ({299+ project,300+ ref: logRef.replace(`${project}/`, `${other}/`),301+ });302+303+ 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+ };315+316+ const whole = { lane: unit, text: unitLog, truncated: false };317+318+ 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+ });333+334+ // 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);337+338+ if (kept !== undefined) {339+ objects.set(logRef, { ...kept, text: long });340+ }341+342+ const cut = yield* world.rpc("dora").evidence(ref);343+344+ 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+ );352+353+ 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;358+359+ // 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+ ];366+367+ // 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+ });373+374+ const again = yield* aliceGit.push(work);375+376+ // 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+ ];383+384+ const seen = [pushed.stderr, again.stderr, ...read];385+386+ 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 lines11 import { RefName, RepoHost } from "@repo/artifacts/repo-host";12 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";13 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";14 import { CheckRunner } from "@repo/checks/check-runner";15+import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";16 import { AlarmsMemory } from "@repo/project/alarms/memory";17 import { AnswerRunsInline } from "@repo/project/answer-runs/inline";18 import type { FrontPageSeed } from "@repo/project/front-page/memory";19 import { FrontPageMemory } from "@repo/project/front-page/memory";140 unmodified lines160 ).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));167 168 /**169 * The scenario's project as its initializer makes it: made, its first32 unmodified linesmodified:apps/platform/test/harness.ts+4 added-1 removed
1+import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";2 import { Upstream } from "@repo/git/upstream";3 import { FrontPageMemory } from "@repo/project/front-page/memory";4 import { Projects } from "@repo/project/projects";5 import { Contracts } from "@repo/protocol/contracts";136 unmodified lines142 143 /**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 */149 export const noProjects = Handlers.pipe(150 Layer.provide([151 Layer.succeed(4 unmodified lines156 })157 ),158 FrontPageMemory.layer({ credits: [], entries: [], projects: [] }),159 MemoryRateLimits(WorkerCaps),160+ EvidenceStoreMemory,161 ])162 );163 164 /**45 unmodified linesmodified:apps/platform/test/project-do.fixtures.ts+2 added
14 unmodified lines15 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";16 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";17 import { CheckAt } from "@repo/checks/check-runner";18 import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";19+import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";20 import { Lander } from "@repo/project/lander";21 import { LanderIsogit } from "@repo/project/lander/isogit";22 import { FinishersFromChecks } from "@repo/project/project";23 import { ProjectionMemory } from "@repo/project/projection/memory";334 unmodified lines358 export const world = Layer.mergeAll(359 alarms,360 answers,361 checker,362+ EvidenceStoreMemory,363 ProjectionMemory,364 pusher,365 rules366 ).pipe(110 unmodified linesmodified:apps/platform/test/world.ts+11 added-7 removed
13 unmodified lines14 * 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 lines29 import { RefName, RepoHost } from "@repo/artifacts/repo-host";30 import { RepoHostLocal } from "@repo/artifacts/repo-host/local";31 import type { CheckAt } from "@repo/checks/check-runner";32 import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";33+import type { EvidenceStore } from "@repo/checks/evidence-store";34 import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";35 import { UpstreamRepoHost } from "@repo/git/upstream/repo-host";36 import { AlarmsMemory } from "@repo/project/alarms/memory";37 import { AnswerRuns } from "@repo/project/answer-runs";138 unmodified lines176 `echo password=${tokens[as]}`,177 "",178 ].join("\n");179 179-export 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. */181+export interface WorldOptions {182+ readonly evidence?: Layer.Layer<EvidenceStore>;183+}184+185+export 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 lines211 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 linesmodified:docs/reference/cli.md+20 added
471 unmodified lines472 | `--note` | text | no |473 | `--project` | text | yes |474 | `--verdict` | "vouch" \| "denounce" | yes |475 476+## `myr evidence`477+478+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.479+480+```sh481+myr evidence <ref> --project <project>482+```483+484+- Contract: `evidence`485+- Reads only: yes486+- Idempotent: yes487+- Destructive: no488+- Needs approval: no489+- Surfaces: rpc, cli490+491+| Argument | Takes | Required |492+| --- | --- | --- |493+| `<ref>` | text | yes |494+| `--project` | text | yes |495+496 ## `myr env set`497 498 Set the write-only value of a sensitive env item; nobody can read it back.499 17 unmodified linesmodified:docs/reference/commands.json+38 added
1082 unmodified lines1083 "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 linesmodified:docs/reference/protocol.schema.json+49 added
3177 unmodified lines3178 "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 linesadded: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+ */13+import { Data, Effect, Layer, Option } from "effect";14+15+import { EvidenceStore, logRefOf } from "../evidence-store.ts";16+17+/**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+ */22+export 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+}35+36+/** R2 refused or never answered a call on one key: the store cannot go on. */37+class EvidenceUnreachable extends Data.TaggedError("EvidenceUnreachable")<{38+ readonly message: string;39+ readonly cause: unknown;40+}> {}41+42+/** One call on the bucket for `key`; a failure dies naming the key and the call. */43+const 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+ );54+55+export 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);73+74+ 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 line2 * 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 */9-import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";10-import { Context, Schema } from "effect";11-import type { Effect, Option } from "effect";9+import { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";10+import { Context, Option, Schema } from "effect";11+import type { Effect } from "effect";12 13 /**14 * A kept log's name: `<project>/<requestId>/<lane>#<attempt>`. It is15 * deterministic, so a replayed step overwrites its log, never adds a second15 unmodified lines31 /** The name a lane's log is kept under, whichever adapter keeps it. */32 export const logRefOf = (log: Omit<LaneLog, "text">): LogRef =>33 LogRef.make(`${log.project}/${log.requestId}/${log.lane}#${log.attempt}`);34 35+/** A log's name, read back into what it names. */36+const LogName = Schema.TemplateLiteralParser([37+ ProjectName,38+ "/",39+ RequestId,40+ "/",41+ LaneName,42+ "#",43+ Schema.Int,44+]);45+46+/**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+ */52+export 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+ );65+66 export 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
1+import { describe, expect, it } from "@effect/vitest";2+import { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";3+import type { Layer } from "effect";4+import { Cause, Effect, Exit, Option } from "effect";5+6+import { EvidenceStore, LogRef } from "../src/evidence-store.ts";7+import { EvidenceStoreR2 } from "../src/evidence-store/r2.ts";8+import type { EvidenceBucket } from "../src/evidence-store/r2.ts";9+10+/** One object as the fake bucket keeps it: its body and the options it was put with. */11+interface Kept {12+ readonly text: string;13+ readonly options: Parameters<EvidenceBucket["put"]>[2];14+}15+16+/**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+ */21+const fakeBucket = () => {22+ const objects = new Map<string, Kept>();23+24+ const bucket: EvidenceBucket = {25+ get: (key) => {26+ const kept = objects.get(key);27+28+ 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 });34+35+ return Promise.resolve({ key });36+ },37+ };38+39+ return { bucket, objects };40+};41+42+/** A bucket whose every call fails, as R2 does when it cannot be reached. */43+const brokenBucket: EvidenceBucket = {44+ get: () => Promise.reject(new Error("R2 is unreachable")),45+ put: () => Promise.reject(new Error("R2 is unreachable")),46+};47+48+const 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+};55+56+const key = "datekit/push-0123456789/unit#1";57+58+/** How a call ended, as its defect prints. */59+const printed = <A>(call: Effect.Effect<A>) =>60+ Effect.map(Effect.exit(call), (exit) =>61+ Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "it succeeded"62+ );63+64+/** The store over `bucket`, as the Worker composes it. */65+const over = (bucket: EvidenceBucket) =>66+ Effect.provide(EvidenceStoreR2(bucket) satisfies Layer.Layer<EvidenceStore>);67+68+describe("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();73+74+ return Effect.gen(function* () {75+ const store = yield* EvidenceStore;76+ const ref = yield* store.put(unitLog);77+78+ 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+ );100+101+ it.effect(102+ "overwrites a replayed attempt's log under the same key, never a second object",103+ () => {104+ const { bucket, objects } = fakeBucket();105+106+ 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" });110+111+ 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+ );123+124+ 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`;127+128+ return Effect.gen(function* () {129+ const store = yield* EvidenceStore;130+ const ref = yield* store.put({ ...unitLog, text: long });131+132+ expect(yield* store.get(ref)).toStrictEqual(Option.some(long));133+ }).pipe(over(bucket));134+ });135+136+ it.effect("has nothing under a key it never kept", () =>137+ Effect.gen(function* () {138+ const store = yield* EvidenceStore;139+140+ expect(141+ yield* store.get(LogRef.make("datekit/push-0123456789/lint#1"))142+ ).toStrictEqual(Option.none());143+ }).pipe(over(fakeBucket().bucket))144+ );145+146+ it.effect(147+ "labels each object with its project and lane, and nothing else",148+ () => {149+ const { bucket, objects } = fakeBucket();150+151+ return Effect.gen(function* () {152+ yield* (yield* EvidenceStore).put(unitLog);153+154+ expect(objects.get(key)?.options.customMetadata).toStrictEqual({155+ lane: "unit",156+ project: "datekit",157+ });158+ }).pipe(over(bucket));159+ }160+ );161+162+ 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;167+168+ const deaths = [169+ yield* printed(store.put(unitLog)),170+ yield* printed(store.get(LogRef.make(key))),171+ ];172+173+ 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 lines253 leaks(parseJson(content("docs/reference/protocol.schema.json")))254 ).toStrictEqual([]);255 });256 257- // 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()];261 262 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 });269 270 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 linesmodified:packages/project/src/project.ts+110 added-3 removed
17 unmodified lines18 import type { RepoNotFound } from "@repo/artifacts/repo-host";19 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";20 import { Brand } from "@repo/brand";21 import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";22+import { EvidenceStore, LogRef, logOfRef } from "@repo/checks/evidence-store";23 import { findRunBlock } from "@repo/checks/finder";24 import { judgeClosure } from "@repo/checks/judge";25 import { checkVersion, commandFor } from "@repo/checks/kinds";26 import { redFirstOfRuns } from "@repo/checks/red-first";9 unmodified lines36 Claim as ClaimContract,37 Credits,38 Decide,39 EnvSchemaOf,40+ EvidenceOf,41 Finish,42 FlagAsk,43 Fork,44 InitProject,61 unmodified lines106 StaleBase,107 TouchedJudge,108 UnknownAsk,109 UnknownCommit,110+ UnknownProject,111 VerifierBlocked,112 WeakCheck,113 } from "@repo/protocol/refusal";114 import type {180 unmodified lines295 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 lines457 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 lines627 * 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 */600-const checked = <A, E>(631+const 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 lines646 Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))647 )648 );649 650+/** The most of a lane's log `evidence` gives back: its last 256 KiB. */651+const EVIDENCE_TAIL = 256 * 1024;652+653+/** Whether a UTF-8 byte starts a character: it is no continuation byte (`10xxxxxx`). */654+const startsCharacter = (byte: number) => byte < 0x80 || byte >= 0xc0;655+656+/**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+ */660+const tailOf = (log: string) => {661+ const bytes = new TextEncoder().encode(log);662+663+ if (bytes.length <= EVIDENCE_TAIL) {664+ return { text: log, truncated: false };665+ }666+667+ const tail = bytes.subarray(bytes.length - EVIDENCE_TAIL);668+ const from = tail.findIndex(startsCharacter);669+670+ return {671+ text: from === -1 ? "" : new TextDecoder().decode(tail.subarray(from)),672+ truncated: true,673+ };674+};675+676 const mainRef = RefName.make("refs/heads/main");677 678 const HOUR = 3_600_000;679 2281 unmodified lines2961 2962 return Effect.succeed(field("verdict", verdict));2963 });2964 2965+ // ---------------------------------------------------------- evidence2966+2967+ /**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);2978+2979+ 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+ }2987+2988+ const { lane, requestId } = named.value;2989+ const h = yield* hydrate;2990+2991+ 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+ });2999+3000+ if (!allowed) {3001+ return yield* new NotDecider({});3002+ }3003+3004+ const kept = yield* EvidenceStore.use((logs) => logs.get(ref));3005+3006+ if (Option.isNone(kept)) {3007+ return yield* new UnknownProject({ project: name });3008+ }3009+3010+ return { lane, ...tailOf(kept.value) };3011+ });3012+3013 // ---------------------------------------------------------- deciders3014 3015 /** The decider-facing methods (221), over the same hydrate, write and helpers. */3016 const decided = deciders<Hydrated, Writes>({79 unmodified lines3096 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 linesadded: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+ */7+import { describe, expect, it } from "@effect/vitest";8+import { RefName, RepoHost } from "@repo/artifacts/repo-host";9+import { EvidenceStore, LogRef, logRefOf } from "@repo/checks/evidence-store";10+import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";11+import { CheckSpec } from "@repo/protocol/domain/check";12+import {13+ AskId,14+ LandedSha,15+ LaneName,16+ ProjectName,17+ RepoName,18+ RepoPath,19+ RequestId,20+} from "@repo/protocol/ids";21+import { Anonymous, Person } from "@repo/protocol/principal";22+import { NotDecider, UnknownProject } from "@repo/protocol/refusal";23+import { advanceTo } from "@repo/testkit/clock";24+import type { Files } from "@repo/testkit/git-client";25+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";26+import { Array, Effect, Layer, Option } from "effect";27+28+import { projectService } from "../src/project.ts";29+import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";30+31+const scenario = aProject({ people: ["bob", "carol"] }).pipe(32+ withVouches(["bob", "carol"]),33+ withAsk({ id: "parse-iso", territory: "packages/parser" })34+);35+36+const { project } = scenario;37+38+const repo = RepoName.make(project);39+40+const person = (name: string) =>41+ Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });42+43+/** The project's decider. */44+const alice = person("alice");45+46+/** The claimant whose answer failed its `unit` lane. */47+const bob = person("bob");48+49+/** Neither: vouched for, but no claimant of that answer and no decider. */50+const carol = person("carol");51+52+const parseIso = AskId.make("parse-iso");53+54+const unit = LaneName.make("unit");55+56+const requestId = RequestId.make("req-fix-0001");57+58+const mainRef = RefName.make("refs/heads/main");59+60+const start: Files = [61+ ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],62+ ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],63+];64+65+/** The ask's own files: its file in the config folder, and its check. */66+const askFiles = () => {67+ const ask = Option.getOrThrow(68+ Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)69+ );70+71+ 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+};89+90+/** The log bob's `unit` lane left on his answer's first merge. */91+const failing = [92+ "FAIL packages/parser/test/parse.test.ts > parses ISO weeks",93+ "AssertionError: expected 52 to be 53",94+].join("\n");95+96+/** The name the log is kept under. */97+const bobsLog = logRefOf({ attempt: 1, lane: unit, project, requestId });98+99+const mainTip = Effect.gen(function* () {100+ const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);101+102+ return LandedSha.make(103+ Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))104+ );105+});106+107+/**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+ */111+const answered = (text: string = failing) =>112+ Effect.gen(function* () {113+ yield* advanceTo("2026-10-07T12:00:00Z");114+115+ const api = yield* projectService(project);116+117+ yield* api.initProject(alice, {});118+119+ const first = yield* Pusher.use((pusher) =>120+ pusher.push(repo, Option.none(), start, "Start")121+ );122+123+ yield* api.recordFirstPush(alice, first);124+125+ const files = askFiles();126+ const composed = yield* composedAt(repo, yield* mainTip, files);127+128+ yield* CheckScript.use((checker) =>129+ checker.script(composed, LaneName.make("redThenGreen"), [130+ "failed",131+ "failed",132+ ])133+ );134+135+ const { landed } = yield* api.openAsk(alice, { ask: parseIso, files });136+ const { claim } = yield* api.claim(bob, parseIso);137+138+ 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+ );145+146+ yield* api.submitAnswer(bob, {147+ ask: parseIso,148+ base: landed,149+ head,150+ requestId,151+ });152+153+ yield* (yield* EvidenceStore).put({154+ attempt: 1,155+ lane: unit,156+ project,157+ requestId,158+ text,159+ });160+161+ return api;162+ });163+164+const world = Layer.merge(worldOf(scenario, "memory"), EvidenceStoreMemory);165+166+describe("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();172+173+ 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+ );182+183+ 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();188+189+ const never = logRefOf({190+ attempt: 7,191+ lane: unit,192+ project,193+ requestId: RequestId.make("req-none-0001"),194+ });195+196+ 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+ );215+216+ 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");222+223+ const elsewhere = logRefOf({224+ attempt: 1,225+ lane: unit,226+ project: other,227+ requestId,228+ });229+230+ 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+ );246+247+ 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();252+253+ const passed = logRefOf({254+ attempt: 1,255+ lane: LaneName.make("lint"),256+ project,257+ requestId,258+ });259+260+ // bob's own log's name, spelled as `logRefOf` never spells one.261+ const respelled = LogRef.make(bobsLog.replace(/#1$/u, "#01"));262+263+ 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+ );283+284+ 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);292+293+ 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+ );306+307+ 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);313+314+ 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 lines38 EnvKey,39 Handle,40 KindName,41 LandedSha,42+ LaneName,43 ProjectName,44 RepoName,45 RequestId,46 } from "./ids.ts";59 unmodified lines106 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 lines703 .annotate(NeedsApproval, true)704 .annotate(Cli, { name: "vouch" })705 .annotate(Surfaces, servedOn.vouch) {}706 707+export 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) {}736+737 export class SetEnv extends Rpc.make("setEnv", {738 error: Schema.Union([739 UnknownProject,740 NotDecider,54 unmodified lines795 Finish,796 Land,797 Fork,798 Vouch,799+ EvidenceOf,800 SetEnv801 ).middleware(Authenticated) {}802 803 /** Every contract in the group, as its handlers and clients see it. */60 unmodified linesmodified:packages/protocol/src/testing.ts+1 added
33 unmodified lines34 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 linesmodified:packages/protocol/test/fixtures/contracts.json+11 added
93 unmodified lines94 ],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 linesmodified:packages/protocol/test/contracts.test.ts+13 added-3 removed
267 unmodified lines268 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 lines406 ).toStrictEqual(table.map(({ cli, tag }) => ({ cli, tag })));407 });408 409 // 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 line416 })417 ).toStrictEqual([418 { tag: "today", visibility: "maintainers" },419 { tag: "decide", visibility: "maintainers" },420+ { tag: "evidence", visibility: "maintainers" },421 ]);422 });423 424 it("lets each contract refuse only with its own subset of refusals", () => {74 unmodified lines499 // 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 });509 501- 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()];512 513 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