Skip to content
Myr

Merge build/613-answer-held-back-and-guards: an answer is judged by the sealed suite it was pinned to, lands with a Held-back: trailer, and can't carry layer content or a stored value

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

authored by oscabriel · committed by oscabriel · parents 2894306, 903a9e6 · Browse files · 9 files+2209 added−84 removed
This commit

State

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

Diff stats

9 files+2209 added−84 removed

  • tests:+1396 added−0 removed
  • other:+813 added−84 removed

9 files+2209 added−84 removed

modified:apps/platform/src/adapters/check-runner-sandbox.ts+60 added-2 removed
added:apps/platform/src/visibility/held-back.ts+158 added
1/**2 * The visibility cartridge's landing guards (W6 613; OSR §5.4): the3 * no-write-down guards the `Answer` Workflow runs on an answer's merged4 * change set before any check, provided as its `LandingGuards` port.5 *6 * - `PrivatePathInPublicTree`: a path in any layer's path set, as the7 * project gives it (`layerFacts`). It names exactly which paths collide8 * only when everyone accountable for the answer reads every layer;9 * anyone else hears every path they added or modified (602's10 * `privatePaths`), so the refusal is no map of the layers.11 * - `LayerContentInPublicTree`: an added blob identical to a blob of a12 * layer the answerer or a finisher reads (602's `writeDown`). Only the13 * blobs of layers they read are compared, read here from the private14 * namespace (`LayerRepos`) at the layer's `main`; for anyone else the15 * guard says nothing, never an oracle on a layer's content.16 *17 * Nothing here names a layer's paths or content in a refusal or a log.18 */19import type { Fetch } from "@repo/artifacts/fetch";20import { ObjectId, RefName } from "@repo/artifacts/repo-host";21import type { RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";22import type { ProjectApi } from "@repo/project/project";23import { Projects } from "@repo/project/projects";24import type { Layer as LayerDeclaration } from "@repo/protocol/domain/visibility";25import { BlobSha, RepoName, RepoPath } from "@repo/protocol/ids";26import type { Handle } from "@repo/protocol/ids";27import { Anonymous, Person } from "@repo/protocol/principal";28import { privatePaths, writeDown } from "@repo/visibility/guards";29import { LayerRepos } from "@repo/visibility/layer-repos";30import { Effect, Layer, Option } from "effect";3132import type { PlatformConfig } from "../platform.ts";33import { LandingGuards } from "../workflows/answer/guards.ts";34import type { GuardInput } from "../workflows/answer/guards.ts";35import { layerRepos } from "./layer-repos.ts";3637const mainRef = RefName.make("refs/heads/main");3839/** A layer's repo: as declared, or `<project>--<layer>` (spec §4.5). */40const repoOf = (project: string, layer: LayerDeclaration) =>41 layer.repo ?? RepoName.make(`${project}--${layer.name}`);4243/** Every blob under `tree` in `repo`, at any depth. */44const blobsUnder = (45 host: RepoHost["Service"],46 repo: RepoName,47 tree: string48): Effect.Effect<readonly BlobSha[], RepoNotFound> =>49 Effect.flatMap(host.readTree(repo, ObjectId.make(tree)), (entries) =>50 Effect.map(51 Effect.forEach(52 Option.getOrElse(entries, () => []),53 (entry) =>54 entry.type === "tree"55 ? blobsUnder(host, repo, entry.sha)56 : Effect.succeed(57 entry.type === "blob" ? [BlobSha.make(entry.sha)] : []58 )59 ),60 (nested) => nested.flat()61 )62 );6364/** The blobs a layer's repo holds on `main`; none for a layer with no repo yet. */65const layerBlobs = (host: RepoHost["Service"], repo: RepoName) =>66 Effect.gen(function* () {67 const tip = (yield* host.refs(repo)).get(mainRef);6869 if (tip === undefined) {70 return [];71 }7273 const commit = yield* host.readCommit(repo, tip);7475 return Option.isNone(commit)76 ? []77 : yield* blobsUnder(host, repo, commit.value.tree);78 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeed([])));7980/** Whether `handle` may read `layer`: its readers and writers. */81const reads = (api: ProjectApi, handle: Handle, layer: LayerDeclaration) =>82 Effect.map(83 api.layerAccess(Person.make({ handle }), layer.name),84 (access) => Option.isSome(access) && access.value !== "none"85 );8687/** The guards on one answer's merged change set, over its project and the private namespace. */88const guardsOver =89 (repos: RepoHost["Service"], projects: Projects["Service"]) =>90 (input: GuardInput) =>91 Effect.gen(function* () {92 const api = yield* projects.get(input.project).pipe(Effect.orDie);93 const people = [input.answerer, ...input.finishers];9495 const { layers } = yield* api96 .ledger(Anonymous.make({}))97 .pipe(Effect.orDie);9899 const facts = yield* api.layerFacts(100 Person.make({ handle: input.answerer })101 );102103 const access = yield* Effect.forEach(layers, (layer) =>104 Effect.map(105 Effect.forEach(people, (handle) => reads(api, handle, layer)),106 (each) => ({ each, layer })107 )108 );109110 const readable = access.filter(({ each }) => each.some(Boolean));111112 const readsAll =113 access.length > 0 && access.every(({ each }) => each.every(Boolean));114115 const blobs = yield* Effect.forEach(readable, ({ layer }) =>116 layerBlobs(repos, repoOf(input.project, layer))117 );118119 return [120 ...Option.toArray(121 privatePaths({122 changes: input.changes,123 layerPaths: new Set(124 facts.layerPaths.map((path) => RepoPath.make(path))125 ),126 pusherCanRead: readsAll,127 })128 ),129 ...Option.toArray(130 writeDown({131 changes: input.changes,132 layerBlobs: new Set(blobs.flat()),133 readerCanReadLayer: readable.length > 0,134 })135 ),136 ];137 });138139/** The landing guards over the project's layers, as `LayerRepos` holds them. */140export const LandingGuardsLive: Layer.Layer<141 never,142 never,143 LayerRepos | Projects144> = Layer.effect(145 LandingGuards,146 Effect.gen(function* () {147 const repos = yield* LayerRepos;148 const projects = yield* Projects;149150 return Option.some({ check: guardsOver(repos, projects) });151 })152);153154/** The landing guards for one stage, over its private namespace (`ARTIFACTS_PRIVATE`). */155export const heldBackLive = (156 config: PlatformConfig157): Layer.Layer<never, never, Fetch | Projects> =>158 LandingGuardsLive.pipe(Layer.provide(layerRepos(config)));
modified:apps/platform/src/visibility/live.ts+11 added-4 removed
added:apps/platform/src/workflows/answer/guards.ts+198 added
1/**2 * The `Answer` Workflow's landing guards (W6; OSR §5.4, VL §8.6): before3 * any check runs on an answer's merged tree, the tree is checked again for4 * what may never enter a public tree, as it stands now (a layer may have5 * grown since the push was admitted at stage 1):6 *7 * - a path in a layer's path set: `PrivatePathInPublicTree`;8 * - a file whose blob is a layer's blob, only when the answerer or a9 * finisher reads that layer (only they could have copied it; on anyone10 * else the guard would be an oracle): `LayerContentInPublicTree`;11 * - a file holding a stored write-only value, by the project's own scan12 * (`ProjectApi.scanForValues`, where the values are; never in the13 * sandbox): the item is quarantined, for the deciders alone.14 *15 * The layer guards need the layers' contents, which only the visibility16 * cartridge reaches, so they sit behind `LandingGuards`, a port whose17 * default is no guards at all: without the cartridge there are no layers18 * and no stored values, and the program takes no guards step (its steps19 * are the ones it always took).20 */21import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";22import type { Change } from "@repo/project/landing";23import { LandingState } from "@repo/project/landing";24import { Projects } from "@repo/project/projects";25import { AskKind } from "@repo/protocol/domain/kind";26import { EnvKey } from "@repo/protocol/ids";27import type {28 Handle,29 ProjectName,30 RequestId,31 TreeSha,32} from "@repo/protocol/ids";33import { Refusal } from "@repo/protocol/refusal";34import type {35 LayerContentInPublicTree,36 PrivatePathInPublicTree,37} from "@repo/protocol/refusal";38import { Array, Context, Effect, Option, Schema } from "effect";3940import { StepRunner } from "../step.ts";4142/** One answer's merged change set, and the people accountable for it. */43export interface GuardInput {44 readonly project: ProjectName;45 readonly answerer: Handle;46 /** Deciders whose finish put commits of their own on the answer. */47 readonly finishers: readonly Handle[];48 readonly changes: readonly Change[];49}5051/** The no-write-down guards on a merged change set, as the visibility cartridge runs them. */52export interface LayerGuardsPort {53 readonly check: (54 input: GuardInput55 ) => Effect.Effect<56 readonly (PrivatePathInPublicTree | LayerContentInPublicTree)[]57 >;58}5960/**61 * How the Workflow reaches the layer guards: none by default, a platform62 * without typed visibility. The visibility cartridge provides them63 * (`apps/platform/src/visibility/held-back.ts`).64 */65export const LandingGuards = Context.Reference<Option.Option<LayerGuardsPort>>(66 "platform/LandingGuards",67 { defaultValue: () => Option.none() }68);6970/** What the guards step came to, kept as its value: no names but public ones. */71export const GuardRun = Schema.TaggedUnion({72 /** An added blob could not be read: the guards try again later, never counted. */73 Blocked: { attempt: Schema.Int },74 /** The guards' refusals, and the items whose stored value an added file holds. */75 Guarded: {76 finish: AskKind.fields.finish,77 quarantined: Schema.Array(EnvKey),78 refusals: Schema.Array(Refusal),79 },80 /** The answer no longer waits on checks of this tree. */81 Moved: {},82});8384export type GuardRun = typeof GuardRun.Type;8586/**87 * Whether the guards let the tree on to its checks: only when they ran on88 * it and found nothing. A blocked run waits, and a moved one stops.89 */90export const passes = (run: GuardRun): boolean =>91 GuardRun.guards.Guarded(run) &&92 run.refusals.length === 0 &&93 run.quarantined.length === 0;9495/** Files the answer puts into the public tree: added, or modified to a new blob. */96const written = (changes: readonly Change[]) =>97 Array.dedupe(98 changes.flatMap(({ after, status }) =>99 status === "deleted" || after === undefined ? [] : [after]100 )101 );102103/**104 * The guards on `tree`, as the answer's run stands: the cartridge's layer105 * guards over its change set and the people accountable for it, then each106 * blob it writes, read from its fork, through the project's scan.107 */108const guarded = (109 params: { readonly project: ProjectName; readonly requestId: RequestId },110 tree: TreeSha,111 port: LayerGuardsPort112): Effect.Effect<GuardRun, never, Projects | RepoHost> =>113 Effect.gen(function* () {114 const api = yield* Projects.use((projects) =>115 projects.get(params.project)116 ).pipe(Effect.orDie);117118 const run = yield* api.answer(params.requestId);119120 const found = Option.flatMap(run, (each) =>121 LandingState.guards.Checking(each.state) && each.state.tree === tree122 ? Option.some({ finish: each.finish, state: each.state })123 : Option.none()124 );125126 if (Option.isNone(found)) {127 return GuardRun.cases.Moved.make({});128 }129130 const { finish, state } = found.value;131 const { request } = state;132133 const refusals = yield* port.check({134 answerer: request.answerer,135 changes: state.changes,136 finishers: request.credits137 .filter(({ role }) => role === "Finished-by")138 .map(({ handle }) => handle),139 project: params.project,140 });141142 const host = yield* RepoHost;143144 // A fork the platform cannot read leaves its files unscanned: the guards145 // try again later, and never let the tree by. An id no blob in the fork146 // has is a submodule's pointer, a commit in another repo (`tree-diff`):147 // it brings no content of its own into the tree, so there is none to scan.148 const read = yield* Effect.option(149 Effect.forEach(written(state.changes), (blob) =>150 host.readBlob(request.fork, ObjectId.make(blob))151 )152 );153154 if (Option.isNone(read)) {155 return GuardRun.cases.Blocked.make({ attempt: state.attempt });156 }157158 const held = yield* Effect.forEach(Array.getSomes(read.value), (blob) =>159 api.scanForValues({ blob })160 );161162 return GuardRun.cases.Guarded.make({163 finish,164 quarantined: Array.dedupe(Array.getSomes(held)),165 refusals,166 });167 });168169/**170 * The guards on the tree the answer waits to have checked, as a durable171 * step named for the attempt; none when no cartridge provides them.172 */173export const guards = (174 params: { readonly project: ProjectName; readonly requestId: RequestId },175 tree: TreeSha,176 attempt: number177): Effect.Effect<178 Option.Option<GuardRun>,179 never,180 Projects | RepoHost | StepRunner181> =>182 Effect.gen(function* () {183 const plugged = yield* LandingGuards;184185 if (Option.isNone(plugged)) {186 return Option.none();187 }188189 const { step } = yield* StepRunner;190191 return Option.some(192 yield* step(193 `guards#${attempt}`,194 GuardRun,195 guarded(params, tree, plugged.value)196 )197 );198 });
modified:apps/platform/src/workflows/answer/held-back.ts+121 added-23 removed
1/**2 * The `Answer` Workflow's held-back step (W6 609; spec §5 step 7 (d)): once3 * an answer's public checks pass on the merged tree, the sealed suite its2 * The `Answer` Workflow's held-back step (W6; spec §5 step 7 (d)): once an3 * answer's public checks pass on the merged tree, the sealed suite its4 * claim was pinned to judges it, one bit per area (spec D17). The project5 * decides everything through `ProjectApi`: the job (`heldBackJob`, the6 * layer's files read at the pinned commit), and the judgement of the area7 * bits (`recordHeldBack`: `HeldBackFailed`, `AttemptsExhausted`, or the6 * layer's files read at the pinned commit by the platform, so no layer7 * route or token reaches the sandbox), and the judgement of the area bits8 * (`recordHeldBack`: `HeldBackFailed`, `AttemptsExhausted`, or the9 * `Held-back:` trailer it keeps for the landing). Only answers whose run10 * says `sealed` take this step, so a platform without typed visibility runs11 * the same steps it always did.12 *12 * Until the Checker takes a sealed suite (605 reshapes the `CheckJob`'s13 * held-back part, 613 fills it here), an answer the project holds a suite14 * for is refused `VerifierBlocked` rather than landed unjudged by it.13 * The suite runs in a job of its own, with no public lane beside it: the14 * public lanes passed in their own jobs, and answer code run again beside15 * the sealed files could carry bits about them that no attempt counts. Only16 * the area bits leave the step: no lane, no log, no duration.17 *18 * A held-back result carries over to a later check of the same request only19 * when the answer's `PatchId` and the pinned suite are unchanged (SYN §920 * #12): a main that moved under a passing answer re-runs its public lanes21 * on the new merged tree, never its sealed suite.22 */23import { CheckAt, CheckRunner } from "@repo/checks/check-runner";24import { patchId } from "@repo/git/patch-id";25import { runBlockOf } from "@repo/project/answer-runs";26import type { AnswerRun } from "@repo/project/answer-runs";27import { noRunEnv } from "@repo/project/env-port";28import { LandingState } from "@repo/project/landing";29import { Projects } from "@repo/project/projects";30import type { HeldBackJob } from "@repo/project/visibility-port";31import { HeldBackResult } from "@repo/protocol/domain/answer";18import type { ProjectName, RequestId } from "@repo/protocol/ids";19import { Refusal, VerifierBlocked } from "@repo/protocol/refusal";32import { PatchId, SuiteRoot } from "@repo/protocol/ids";33import type { ProjectName, RequestId, TreeSha } from "@repo/protocol/ids";34import { Refusal } from "@repo/protocol/refusal";35import { Effect, Option, Schema } from "effect";3637import { StepRunner } from "../step.ts";3824/** What the held-back step came to: the refusals it earned, and the area bits for the verdict. */25export const HeldBackRun = Schema.Struct({26 refusals: Schema.Array(Refusal),27 results: Schema.Array(HeldBackResult),39/** What the held-back step came to, kept as its value: area bits and roots only. */40export const HeldBackRun = Schema.TaggedUnion({41 /** The Checker could not run the suite: tried again later, never counted. */42 Blocked: { attempt: Schema.Int },43 /** The suite judged the tree: its area bits, what they earned, and what they judged. */44 Judged: {45 patchId: PatchId,46 refusals: Schema.Array(Refusal),47 results: Schema.Array(HeldBackResult),48 suite: SuiteRoot,49 },50 /** Nothing sealed judges the answer, or it no longer waits on checks of this tree. */51 Unsealed: {},52});5354export type HeldBackRun = typeof HeldBackRun.Type;5556/** A held-back run that judged a tree. */57export type Judged = Extract<HeldBackRun, { readonly _tag: "Judged" }>;5859/** A held-back step with nothing to judge. */33export const unsealed: HeldBackRun = { refusals: [], results: [] };60export const unsealed: HeldBackRun = HeldBackRun.cases.Unsealed.make({});6162/**63 * The area bits of the sealed suite on `tree`: the earlier run's when it64 * judged the same patch by the same suite, else a fresh run in a job of65 * the suite alone.66 */67const areaBits = (input: {68 readonly earlier: Option.Option<Judged>;69 readonly job: HeldBackJob;70 readonly patch: PatchId;71 readonly run: AnswerRun;72 readonly tree: TreeSha;73}) =>74 Option.match(75 Option.filter(76 input.earlier,77 ({ patchId: patched, suite }) =>78 patched === input.patch && suite === input.job.suite79 ),80 {81 onNone: () =>82 Effect.flatMap(runBlockOf(input.run), (block) =>83 CheckRunner.use((runner) =>84 runner.run({85 ...(input.run.env ?? noRunEnv),86 at: CheckAt.cases.Tree.make({ tree: input.tree }),87 heldBack: input.job,88 lanes: [],89 project: input.run.state.request.project,90 repo: input.run.state.request.fork,91 run: block,92 })93 )94 ).pipe(Effect.map(({ heldBack }) => heldBack)),95 onSome: ({ results }) => Effect.succeed(results),96 }97 );9899/**100 * The sealed suite's run for one checked tree, as a durable step named for101 * the attempt: a replay reads its record back, and the project counts the38 * attempt once per tree whatever runs again.102 * attempt once per tree whatever runs again (principle 8). `earlier` is103 * the last run this request's Workflow judged, which carries over to an104 * unchanged patch under an unchanged suite.105 */106export const heldBack = (107 params: { readonly project: ProjectName; readonly requestId: RequestId },42 attempt: number43): Effect.Effect<HeldBackRun, never, Projects | StepRunner> =>108 tree: TreeSha,109 attempt: number,110 earlier: Option.Option<Judged>111): Effect.Effect<HeldBackRun, never, CheckRunner | Projects | StepRunner> =>112 Effect.flatMap(StepRunner, ({ step }) =>113 step(114 `held-back#${attempt}`,115 HeldBackRun,
1 unmodified line
117 const api = yield* Projects.use((projects) =>118 projects.get(params.project)119 ).pipe(Effect.orDie);120121 const run = yield* api.answer(params.requestId);122123 const checking = Option.flatMap(run, (found) =>124 LandingState.guards.Checking(found.state) && found.state.tree === tree125 ? Option.some({ found, state: found.state })126 : Option.none()127 );128129 if (Option.isNone(checking)) {130 return unsealed;131 }132133 const { found, state } = checking.value;134 const job = yield* api.heldBackJob(params.requestId);13555 return Option.match(job, {56 onNone: () => unsealed,57 onSome: (): HeldBackRun => ({58 refusals: [new VerifierBlocked({})],59 results: [],60 }),136 if (Option.isNone(job)) {137 return unsealed;138 }139140 const patch = yield* patchId(state.changes);141142 const results = yield* areaBits({143 earlier,144 job: job.value,145 patch,146 run: found,147 tree,148 }).pipe(Effect.option);149150 if (Option.isNone(results)) {151 return HeldBackRun.cases.Blocked.make({ attempt: state.attempt });152 }153154 return HeldBackRun.cases.Judged.make({155 patchId: patch,156 refusals: yield* api.recordHeldBack(params.requestId, results.value),157 results: results.value,158 suite: job.value.suite,159 });160 })161 )162 );
modified:apps/platform/src/workflows/answer/lanes.ts+64 added-25 removed
2 unmodified lines
3 * cheap stage (the static lanes) and then the checks (the ask's own check4 * and every other project lane), always on the exact tree the merge made.5 * A lane whose checker never got going gets one fresh run; every lane that6 * did not pass keeps its log through `EvidenceStore`, and only the name it7 * is kept under travels on. The gate classifies each failure against the8 * same lane on main (`gate.classifyFailure`).7 * is kept under travels on, unless the project's scan finds a stored8 * write-only value in it: that log is never kept, and its lane says9 * `withheld` (W6 613). The gate classifies each failure against the same10 * lane on main (`gate.classifyFailure`).11 *12 * The merged tree is checked in the answer's fork, where `Lander.merge`13 * keeps it (under `${Brand.refsPrefix}merge/<tree>`), so a merge needs no14 * write token on the canonical repo; main is checked in the canonical repo.
17 unmodified lines
32import { MeasuredCount, runBlockOf } from "@repo/project/answer-runs";33import type { AnswerRun } from "@repo/project/answer-runs";34import { noRunEnv, RunEnv } from "@repo/project/env-port";35import { LandingState } from "@repo/project/landing";34import {35 HeldBackResult,36 LaneOutcome,37 LaneResult,38} from "@repo/protocol/domain/answer";36import { Projects } from "@repo/project/projects";37import { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";38import { CheckSpec } from "@repo/protocol/domain/check";39import { AskKind } from "@repo/protocol/domain/kind";40import { RunBlock } from "@repo/protocol/domain/run";41import {
90 unmodified lines
132 Ran: {133 checked: Checked,134 /** The cheap stage's: each ratchet's count on the merged tree, per territory. */135 counts: Schema.optionalKey(Schema.Array(MeasuredCount)),137 heldBack: Schema.Array(HeldBackResult),136 lanes: Schema.Array(LaneRun),137 /** The cheap stage's: a ratchet whose command printed no count the platform can read. */138 uncounted: Schema.optionalKey(RatchetName),139 },
55 unmodified lines
195 )196 ),197 ].join("\n");198199/**200 * Where a lane's log is said to be when it was not kept because it held a201 * stored write-only value (W6 613; VL §8.6): the lane's refusal stands, its202 * log is never put in the evidence store, and nothing names the item.203 */204export const withheld = "withheld";205206const isTrouble = (result: LaneOutcome) =>207 result === "flaked" || result === "blocked";208209/** Each lane's result and evidence in a run, by lane. */
237 unmodified lines
447 });448449/**450 * One stage's lanes on the merged tree `tree`: run, a troubled lane run446 * once more, and each lane that did not pass at first logged. The log's447 * name counts the answer's merges (`#1` on its first main), so a replayed448 * step keeps its log under the same name and a re-merge gets a new one.449 * The cheap stage counts the ratchets too.451 * once more, and each lane that did not pass at first logged, unless its452 * log holds a stored value. The log's name counts the answer's merges453 * (`#1` on its first main), so a replayed step keeps its log under the454 * same name and a re-merge gets a new one. The cheap stage counts the455 * ratchets too.456 */457export const runStage = (458 run: AnswerRun,459 tree: TreeSha,460 stage: Stage455): Effect.Effect<StageRun, never, CheckRunner | EvidenceStore> =>461): Effect.Effect<StageRun, never, CheckRunner | EvidenceStore | Projects> =>462 Option.match(checkedOf(run, tree), {463 onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),464 onSome: (checked) =>465 Effect.gen(function* () {466 const runner = yield* CheckRunner;467 const evidence = yield* EvidenceStore;468 const lanes = lanesFor(run, stage);469470 // The project scans each log for its stored values before it leaves471 // the run, where the values are (VL §8.6); never the sandbox.472 const api = yield* Projects.use((projects) =>473 projects.get(checked.project)474 ).pipe(Effect.orDie);475476 const scan = (text: string) => api.scanForValues({ text });477478 const remerges = LandingState.guards.Checking(run.state)479 ? run.state.remerges480 : 0;481482 const counting = stage === "cheap" && run.counts !== undefined;483484 if (!Array.isReadonlyArrayNonEmpty(lanes) && !counting) {471 return StageRun.cases.Ran.make({ checked, heldBack: [], lanes: [] });485 return StageRun.cases.Ran.make({ checked, lanes: [] });486 }487488 const block = yield* runBlockOf(checked);489
15 unmodified lines
505506 if (!Array.isReadonlyArrayNonEmpty(lanes)) {507 return StageRun.cases.Ran.make({508 checked,495 heldBack: [],509 lanes: [],510 ...counts,511 });512 }
16 unmodified lines
529 if (standing.first.result === "passed") {530 return Effect.succeed(judged);531 }532533 const text = laneLog(standing.stands, standing.said);534535 return Effect.flatMap(scan(text), (found) =>536 Option.match(found, {537 onNone: () =>520 return Effect.map(521 evidence.put({522 attempt: remerges + 1,523 lane: lane.lane,524 project: checked.project,525 requestId: checked.requestId,526 text: laneLog(standing.stands, standing.said),527 }),528 (logRef) => ({ ...judged, result: { ...judged.result, logRef } })538 Effect.map(539 evidence.put({540 attempt: remerges + 1,541 lane: lane.lane,542 project: checked.project,543 requestId: checked.requestId,544 text,545 }),546 (logRef) => ({547 ...judged,548 result: { ...judged.result, logRef },549 })550 ),551 onSome: (item) =>552 Effect.as(553 Effect.logWarning(554 "a lane's log held a stored write-only value; it was not kept"555 ).pipe(556 Effect.annotateLogs({557 item,558 lane: lane.lane,559 project: checked.project,560 requestId: checked.requestId,561 })562 ),563 {564 ...judged,565 result: { ...judged.result, logRef: withheld },566 }567 ),568 })569 );570 });571572 return StageRun.cases.Ran.make({573 checked,534 heldBack: firstRun.heldBack,574 lanes: laneRuns,575 ...counts,576 });577 }).pipe(
79 unmodified lines
modified:apps/platform/src/workflows/answer/program.ts+201 added-30 removed
41 unmodified lines
42 LandingEffect,43 outcomeOf,44} from "@repo/project/landing";45import { Projects } from "@repo/project/projects";46import { LaneOutcome } from "@repo/protocol/domain/answer";47import type { Verdict } from "@repo/protocol/domain/answer";46import { LaneOutcome, Verdict } from "@repo/protocol/domain/answer";47import type { Outcome } from "@repo/protocol/domain/outcome";48import { CommitSha } from "@repo/protocol/ids";50import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";49import type {50 EnvKey,51 LaneName,52 ProjectName,53 RequestId,54} from "@repo/protocol/ids";55import { VerifierBlocked } from "@repo/protocol/refusal";56import {57 Array,58 Cause,
2 unmodified lines
61 Match,62 Option,63 Schedule,64 Schema,65 Struct,66} from "effect";6768import type { AnswerParams } from "../../answer-runs.ts";69import { writeVerdictNote } from "../notes.ts";70import { StepRunner } from "../step.ts";71import type { StepRetry } from "../step.ts";72import { guards, GuardRun, passes } from "./guards.ts";67import { heldBack, unsealed } from "./held-back.ts";73import { heldBack, HeldBackRun, unsealed } from "./held-back.ts";74import type { Judged } from "./held-back.ts";75import {76 laneOnMain,77 refusalsOf,78 runStage,
99 unmodified lines
178 Effect.flatMap(projectOf(project), (api) => api.answer(requestId));179180/**181 * The port call `effect` names, run as W2's in-process run runs it175 * (`runStep`), on the answer's run as its project holds it now; `None`176 * when the run no longer waits on `call`.182 * (`runStep`), on the answer's run as its project holds it now (as183 * `prepare` hands it on); `None` when the run no longer waits on `call`.184 */185const portCall = (186 params: AnswerParams,187 call: Call<"Land" | "Merge">,181 effect: LandingEffect188 effect: LandingEffect,189 prepare: (run: AnswerRun) => Effect.Effect<AnswerRun, never, Projects> = (190 run191 ) => Effect.succeed(run)192) =>193 Effect.flatMap(load(params), (run) =>194 Option.isSome(run) && waitsOn(run.value, call)185 ? runStep(run.value, effect)195 ? Effect.flatMap(prepare(run.value), (ready) => runStep(ready, effect))196 : Effect.succeedNone197 );198199/** A verdict as its note holds it: JSON. */200const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));201202/**203 * The stored write-only value `verdict`'s note would carry, by its item:204 * the project scans the note before it leaves the run (VL §8.6). Only the205 * platform's log hears which item, never the value.206 */207const leakIn = (params: AnswerParams, verdict: Verdict, where: string) =>208 Effect.gen(function* () {209 const text = yield* Effect.orDie(encodeVerdict(verdict));210 const api = yield* projectOf(params.project);211 const found = yield* api.scanForValues({ text });212213 if (Option.isSome(found)) {214 yield* Effect.logWarning(215 "an answer's verdict note held a stored write-only value; it was not written"216 ).pipe(217 Effect.annotateLogs({218 item: found.value,219 project: params.project,220 requestId: params.requestId,221 where,222 })223 );224 }225226 return found;227 });228229/**230 * The run as its land takes it: the verdict `Lander.land` writes as the231 * landed commit's note on canonical is left off when it holds a stored232 * value, so the landing writes no note; the verdict stands in the project.233 */234const withSafeNote = (params: AnswerParams) => (run: AnswerRun) =>235 run.verdict === undefined236 ? Effect.succeed(run)237 : Effect.map(leakIn(params, run.verdict, "canonical"), (leaked) =>238 Option.isSome(leaked) ? Struct.omit(run, ["verdict"]) : run239 );240241/** The answer's head merged onto the main the call names. */242const merge = (params: AnswerParams, call: Call<"Merge">) =>243 portCall(244 params,
16 unmodified lines
261 Effect.flatMap(262 portCall(263 params,264 call,213 LandingEffect.Land({ main: call.main, tree: call.tree })265 LandingEffect.Land({ main: call.main, tree: call.tree }),266 withSafeNote(params)267 ),268 (given) =>269 Option.isSome(given) && LandingCommand.$is("Busy")(given.value.command)270 ? Effect.fail(new LandBusy({ attempt: given.value.command.attempt }))
59 unmodified lines
330 [new VerifierBlocked({})]331 )332 : Effect.succeed([]);333334/** What a port step came to: its report, and the held-back run it judged, if any. */335interface Ran {336 readonly given: Option.Option<Reported>;337 readonly judged: Option.Option<Judged>;338}339340const ranOnly = (given: Option.Option<Reported>): Ran => ({341 given,342 judged: Option.none(),343});344345/**282 * The checks on the exact merged tree: the cheap stage (its lanes, and the283 * ratchets' counts), then, if it passed, the ask's own check and every284 * other project lane, then, if those passed and a held-back suite judges285 * the answer, its held-back run (step 7 (d), `held-back.ts`). The first346 * An answer that adds a file holding a stored write-only value, until its347 * deciders can be asked: the run refuses it as the platform's trouble348 * (`VerifierBlocked`, which names nothing, so the scan is no oracle on349 * which item a guess matched), and only the platform's log says which350 * items, never a value. The `SecretInTree` decision on the deciders' Today351 * that should hold it instead (`AwaitingDecision` for its answerer) is the352 * project service's to open.353 */354const quarantine = (355 params: AnswerParams,356 items: readonly EnvKey[]357): Effect.Effect<readonly VerifierBlocked[]> =>358 Array.isReadonlyArrayEmpty(items)359 ? Effect.succeed([])360 : Effect.as(361 Effect.logWarning(362 "an answer adds a file holding a stored write-only value"363 ).pipe(364 Effect.annotateLogs({365 items: items.join(","),366 project: params.project,367 requestId: params.requestId,368 })369 ),370 [new VerifierBlocked({})]371 );372373/** The checks reported refused before any lane ran: the landing guards' refusals. */374const guardedOut = (375 params: AnswerParams,376 call: Call<"RunChecks">,377 run: Extract<GuardRun, { readonly _tag: "Guarded" }>378) =>379 Effect.map(quarantine(params, run.quarantined), (quarantined): Ran =>380 ranOnly(381 reported(382 LandingCommand.Checked({383 decisions: [],384 finish: run.finish,385 refusals: [...run.refusals, ...quarantined],386 tree: call.tree,387 }),388 { heldBack: [], lanes: [] }389 )390 )391 );392393/**394 * The checks on the exact merged tree: first the landing guards (when the395 * visibility cartridge provides them, `guards.ts`), then the cheap stage396 * (its lanes, and the ratchets' counts), then, if it passed, the ask's own397 * check and every other project lane, then, if those passed and a398 * held-back suite judges the answer, its held-back run (step 7 (d),399 * `held-back.ts`; `earlier` carries over to an unchanged patch). The first400 * stage that refuses ends them, with its refusals and its lanes. The counts401 * go to the project with the report, which judges them against its402 * baselines (spec §5 step 7 (b)) and opens the decisions a reasoned escape403 * asks for (step 7 (e)).404 */405const checks = (406 params: AnswerParams,407 call: Call<"RunChecks">,294 attempt: number295): Effect.Effect<Option.Option<Reported>, never, AnswerPorts> =>408 attempt: number,409 earlier: Option.Option<Judged>410): Effect.Effect<Ran, never, AnswerPorts> =>411 Effect.gen(function* () {412 const guarded = yield* guards(params, call.tree, attempt);413414 if (Option.isSome(guarded) && !passes(guarded.value)) {415 return yield* GuardRun.match(guarded.value, {416 Blocked: ({ attempt: at }) =>417 Effect.succeed(418 ranOnly(reported(LandingCommand.Blocked({ attempt: at })))419 ),420 Guarded: (run) => guardedOut(params, call, run),421 Moved: () => Effect.succeed(ranOnly(Option.none())),422 });423 }424425 const ran = yield* stage(params, call.tree, "cheap", attempt);426427 const cheap = {428 ...ran,
11 unmodified lines
440 judged !== undefined &&441 StageRun.guards.Ran(judged.ran) &&442 judged.refusals.length === 0 &&443 judged.ran.checked.sealed === true316 ? yield* heldBack(params, attempt)444 ? yield* heldBack(params, call.tree, attempt, earlier)445 : unsealed;446447 const counts = StageRun.guards.Ran(cheap.ran)448 ? Option.fromUndefinedOr(cheap.ran.counts)449 : Option.none();450451 if (HeldBackRun.guards.Blocked(sealed)) {452 return ranOnly(453 reported(LandingCommand.Blocked({ attempt: sealed.attempt }))454 );455 }456457 const held = HeldBackRun.guards.Judged(sealed)458 ? Option.some(sealed)459 : Option.none();460323 return StageRun.match(last.ran, {461 const given = StageRun.match(last.ran, {462 Blocked: ({ attempt: at }) =>463 reported(LandingCommand.Blocked({ attempt: at })),464 Moved: () => Option.none(),327 Ran: ({ checked, heldBack: areas, lanes }) =>465 Ran: ({ checked, lanes }) =>466 reported(467 LandingCommand.Checked({468 decisions: [],469 finish: checked.finish,332 refusals: [...last.refusals, ...sealed.refusals],470 refusals: [471 ...last.refusals,472 ...Option.match(held, {473 onNone: () => [],474 onSome: ({ refusals }) => refusals,475 }),476 ],477 tree: call.tree,478 }),479 {336 heldBack: [...areas, ...sealed.results],480 heldBack: Option.match(held, {481 onNone: () => [],482 onSome: ({ results }) => results,483 }),484 lanes: [485 ...(judged !== undefined && StageRun.guards.Ran(cheap.ran)486 ? cheap.ran.lanes487 : []),
5 unmodified lines
493 }),494 }495 ),496 });497498 return { given, judged: held };499 });500501/**502 * A port step's report given to the project, and the calls to run next.
75 unmodified lines
578 }579580 const { fork, verdict } = judged.value;581582 // The note leaves the run for the answer's fork: a note that holds a583 // stored value is not written; the verdict stands in the project.584 if (Option.isSome(yield* leakIn(params, verdict, "fork"))) {585 return Noted.cases.Unwritten.make({ reason: "SecretInOutput" });586 }587588 const written = yield* writeVerdictNote({589 fork,590 head: verdict.head,591 verdict,
40 unmodified lines
632/** The port call a step runs, under its name. */633const portStep = (634 params: AnswerParams,635 call: Call<"Land" | "Merge" | "RunChecks">,481 attempt: number482): Effect.Effect<Option.Option<Reported>, never, AnswerPorts> =>636 attempt: number,637 earlier: Option.Option<Judged>638): Effect.Effect<Ran, never, AnswerPorts> =>639 Effect.flatMap(StepRunner, ({ step }) =>640 Match.valueTags(call, {641 Land: (landing) =>642 step(
3 unmodified lines
646 landRetry647 ).pipe(648 Effect.catchTag("LandBusy", ({ attempt: at }) =>649 Effect.succeed(reported(LandingCommand.Busy({ attempt: at })))494 )650 ),651 Effect.map(ranOnly)652 ),653 Merge: (merging) =>497 step(`merge#${attempt}`, Reporting, merge(params, merging)),498 RunChecks: (checking) => checks(params, checking, attempt),654 Effect.map(655 step(`merge#${attempt}`, Reporting, merge(params, merging)),656 ranOnly657 ),658 RunChecks: (checking) => checks(params, checking, attempt, earlier),659 })660 );661662const nameOf = {
1 unmodified line
664 Merge: "merge",665 RunChecks: "checks",666} as const satisfies Record<keyof Attempts, string>;667508/** Runs the calls `at` names, one after another, until none is left. */668/**669 * Runs the calls `at` names, one after another, until none is left.670 * `earlier` is the last held-back run of this Workflow, which carries over671 * to a later check of an unchanged patch.672 */673const carry = (674 params: AnswerParams,675 at: Steps,512 attempts: Attempts676 attempts: Attempts,677 earlier: Option.Option<Judged>678): Effect.Effect<Outcome, never, AnswerPorts> =>679 Effect.gen(function* () {680 // A retry is the project's to start, at its alarm.681 if (at.effects.some(NextStep.guards.Retry)) {
9 unmodified lines
691 return at.outcome;692 }693694 const attempt = attempts[call._tag] + 1;530 const given = yield* portStep(params, call, attempt);695 const { given, judged } = yield* portStep(params, call, attempt, earlier);696 const { step } = yield* StepRunner;697698 const next = yield* step(699 `record:${nameOf[call._tag]}#${attempt}`,
4 unmodified lines
704 if (Option.isNone(given)) {705 return next.outcome;706 }707543 return yield* carry(params, next, { ...attempts, [call._tag]: attempt });708 return yield* carry(709 params,710 next,711 { ...attempts, [call._tag]: attempt },712 Option.orElse(judged, () => earlier)713 );714 });715716/**717 * Carries one admitted answer as far as it goes now: merged onto main,
17 unmodified lines
735 {736 effects: callsOf(nextSteps(run.value)),737 outcome: outcomeOf(run.value.state),738 },569 { Land: 0, Merge: 0, RunChecks: 0 }739 { Land: 0, Merge: 0, RunChecks: 0 },740 Option.none()741 );742743 yield* notes(params, outcome);744
2 unmodified lines
added:apps/platform/test/visibility/held-back.fixtures.ts+398 added
1/**2 * datekit with a maintainers layer whose sealed suite has areas `export`3 * (two checks) and `parser` (one), over the Answer Workflow's world4 * (`../workflows/answer.fixtures.ts`): the project service sees fakes of5 * the two visibility ports (612's and 614's are built beside this issue),6 * the Checker answers held-back jobs from a script of failing areas, the7 * layer's repo lives in a `LayerRepos` of its own, and the cartridge's8 * landing guards (`src/visibility/held-back.ts`) are plugged in over them.9 *10 * The fakes keep to the ports' contracts: the visibility port pins every11 * claim to one suite, reads the suite's files for its job, counts failed12 * held-back runs per claim (the third is `AttemptsExhausted`) and gives13 * 602's trailer value when every area passed; the env port keeps a value14 * `setEnv` stored, and scans with 610's scanner.15 */16import { RefName, RepoHost } from "@repo/artifacts/repo-host";17import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";18import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";19import { CheckRunner } from "@repo/checks/check-runner";20import type { CheckJob, CheckRun } from "@repo/checks/check-runner";21import { noEnv, ProjectEnv } from "@repo/project/env-port";22import type { EnvPort } from "@repo/project/env-port";23import type { AttemptRow } from "@repo/project/project-store/rows";24import { noVisibility, ProjectVisibility } from "@repo/project/visibility-port";25import type {26 HeldBackJob,27 VisibilityPort,28} from "@repo/project/visibility-port";29import type { HeldBackResult } from "@repo/protocol/domain/answer";30import type { Policy } from "@repo/protocol/domain/policy";31import {32 AreaName,33 CommitSha,34 LayerName,35 RepoName,36 RepoPath,37 SuiteRoot,38} from "@repo/protocol/ids";39import { Principal } from "@repo/protocol/principal";40import {41 AttemptsExhausted,42 HeldBackFailed,43 VerifierBlocked,44} from "@repo/protocol/refusal";45import { gitClient } from "@repo/testkit/git-client";46import { heldBackValue } from "@repo/visibility/commitment";47import { LayerRepos } from "@repo/visibility/layer-repos";48import { scanBytes, scanText } from "@repo/visibility/leak-scan";49import type { Watched } from "@repo/visibility/leak-scan";50import {51 Array,52 Context,53 DateTime,54 Effect,55 Layer,56 Option,57 Redacted,58 Ref,59 Schema,60} from "effect";6162import { LandingGuardsLive } from "../../src/visibility/held-back.ts";63import { alice, project, worldWith } from "../workflows/answer.fixtures.ts";6465export const maintainers = LayerName.make("maintainers");6667export const layerRepo = RepoName.make(`${project}--maintainers`);6869export const exportArea = AreaName.make("export");7071export const parserArea = AreaName.make("parser");7273/** One sealed check, as the layer holds it. */74interface SealedFile {75 readonly area: AreaName;76 readonly path: RepoPath;77 readonly content: string;78}7980/** The suite: two checks in `export`, one in `parser`. */81export const sealedFiles: readonly SealedFile[] = [82 {83 area: exportArea,84 content:85 'it("escapes a title", () => expect(svg("<")).toContain("&lt;"));\n',86 path: RepoPath.make("checks/held-back/export/escape.test.ts"),87 },88 {89 area: exportArea,90 content: 'it("keeps a link", () => expect(svg("a")).toContain("href"));\n',91 path: RepoPath.make("checks/held-back/export/link.test.ts"),92 },93 {94 area: parserArea,95 content:96 'it("reads a week", () => expect(parse("2026-W41")).toBeDefined());\n',97 path: RepoPath.make("checks/held-back/parser/week.test.ts"),98 },99];100101/** The layer commit the suite is pinned at. */102export const layerAt = CommitSha.make("e".repeat(40));103104/** The suite's root, as 612 publishes it. */105export const suiteRoot = SuiteRoot.make(`sha256:${"3f".repeat(32)}`);106107/** The run block's `test` with each sealed check's path filled. */108const testCommand = (path: RepoPath) => `bun test ${path}`;109110const encoder = new TextEncoder();111112/** The job `heldBackJob` gives for every pinned claim. */113export const heldBackJob: HeldBackJob = {114 areas: [exportArea, parserArea],115 at: layerAt,116 files: sealedFiles.map(({ area, content, path }) => ({117 area,118 content: encoder.encode(content),119 path,120 })),121 runs: sealedFiles.map(({ area, path }) => ({122 area,123 command: testCommand(path),124 path,125 })),126 suite: suiteRoot,127};128129/** How many failed held-back runs a claim may have before its area is spent. */130const ATTEMPTS = 3;131132const isoWeek = "2026-W41";133134/** When a spent area opens again: the fake's week ends on its Monday. */135export const resetsAt = DateTime.makeUnsafe("2026-10-12T00:00:00Z");136137const attemptsOn = (138 rows: readonly AttemptRow[],139 claim: { readonly ask: string; readonly claimant: string },140 area: AreaName141) =>142 rows143 .filter(144 (row) =>145 row.ask === claim.ask &&146 row.claimant === claim.claimant &&147 row.area === area148 )149 .reduce((sum, row) => sum + row.count, 0);150151// ------------------------------------------------------------------ the fakes152153/** What a test changes in the fakes as it goes, and reads back. */154export class Sealed extends Context.Service<155 Sealed,156 {157 /** Whether the Checker cannot run the next held-back jobs at all. */158 readonly blocked: Ref.Ref<boolean>;159 /** The areas whose held-back checks fail in the next held-back jobs. */160 readonly failing: Ref.Ref<ReadonlySet<AreaName>>;161 /** Every held-back job the Checker was given, in order. */162 readonly jobs: Ref.Ref<readonly CheckJob[]>;163 /** The layers' path set (its files), as stage 1 and the landing guards read it. */164 readonly layerPaths: Ref.Ref<ReadonlySet<RepoPath>>;165 /** How often the visibility port judged a held-back run. */166 readonly judged: Effect.Effect<number>;167 }168>()("test/Sealed") {}169170/**171 * The visibility port over the test's handle: one layer, `maintainers`,172 * read and written by the deciders (alice); every claim pinned to173 * `suiteRoot`; the suite's job; failed runs counted per claim in174 * `attempts` rows, the third one spent.175 */176const visibilityOver = (177 sealed: Sealed["Service"],178 judged: { count: number }179): VisibilityPort => ({180 ...noVisibility,181 access: (who, layer) =>182 layer === maintainers183 ? Option.some(184 Principal.guards.Person(who) && who.handle === alice.handle185 ? "write"186 : "none"187 )188 : Option.none(),189 heldBackJob: () => Effect.succeed(Option.some(heldBackJob)),190 judgeHeldBack: (input, snapshot) => {191 judged.count += 1;192193 const failed = input.results.filter(({ passed, total }) => passed < total);194195 const counted = failed.map((result) => ({196 count: attemptsOn(snapshot.attempts, input, result.area) + 1,197 result,198 }));199200 return {201 refusals: counted.map(({ count, result }) =>202 count >= ATTEMPTS203 ? new AttemptsExhausted({ area: result.area, resetsAt })204 : new HeldBackFailed({ area: result.area, suite: result.suite })205 ),206 trailer: Array.isReadonlyArrayEmpty(failed)207 ? heldBackValue({ areas: heldBackJob.areas, results: input.results })208 : Option.none(),209 writes: {210 attempts: counted.map(({ count, result }): AttemptRow => ({211 area: result.area,212 ask: input.ask,213 claimant: input.claimant,214 count,215 week: isoWeek,216 })),217 },218 };219 },220 layerPaths: () => Ref.get(sealed.layerPaths),221 ledger: (named) => ({222 entries: [],223 layers: [224 {225 audience: "maintainers",226 disclose: "sealed",227 holds: ["checks"],228 name: maintainers,229 readers: "deciders",230 reason: "Sealed checks hold answers to the ask's words.",231 repo: layerRepo,232 writers: "deciders",233 },234 ],235 posture: "open",236 postureLabel: "Open with sealed evidence",237 project: named,238 }),239 pinSuite: () => Option.some({ at: layerAt, suite: suiteRoot }),240 readableLayers: (who) =>241 Principal.guards.Person(who) && who.handle === alice.handle242 ? new Set([maintainers])243 : new Set(),244});245246/** What the fake env keeps of a value: the value itself, which only a fake may. */247const KeptValue = Schema.Struct({ fake: Schema.String });248249/**250 * The env port: a decider's value kept as it was given (only a fake keeps251 * a value it could read back), and 610's scanner over every kept value.252 */253const envPort: EnvPort = {254 ...noEnv,255 scan: (scanned, snapshot) =>256 Effect.sync(() => {257 const watched = snapshot.envValues.flatMap((row) =>258 Option.toArray(259 Option.map(260 Schema.decodeUnknownOption(KeptValue)(row.sealed),261 ({ fake }): Watched => ({262 key: row.key,263 value: Redacted.make(fake),264 })265 )266 )267 );268269 return "text" in scanned270 ? scanText(scanned.text, watched)271 : scanBytes(scanned.blob, watched);272 }),273 set: (input) =>274 Effect.succeed({275 result: { key: input.key, setAt: input.now, setBy: input.by.handle },276 writes: {277 envValues: [278 {279 key: input.key,280 sealed: { fake: Redacted.value(input.value) },281 setAt: input.now,282 setBy: input.by.handle,283 },284 ],285 },286 }),287};288289/** The two ports' fakes, and the test's handle on them. */290const fakes = Layer.effectContext(291 Effect.gen(function* () {292 const judged = { count: 0 };293294 const sealed: Sealed["Service"] = {295 blocked: yield* Ref.make(false),296 failing: yield* Ref.make<ReadonlySet<AreaName>>(new Set()),297 jobs: yield* Ref.make<readonly CheckJob[]>([]),298 judged: Effect.sync(() => judged.count),299 layerPaths: yield* Ref.make<ReadonlySet<RepoPath>>(300 new Set(sealedFiles.map(({ path }) => path))301 ),302 };303304 return Context.make(ProjectVisibility, visibilityOver(sealed, judged)).pipe(305 Context.add(ProjectEnv, envPort),306 Context.add(Sealed, sealed)307 );308 })309);310311/** One area's bits in a held-back job: one check fails in each failing area. */312const bitsOf = (313 job: HeldBackJob,314 failing: ReadonlySet<AreaName>315): readonly HeldBackResult[] =>316 job.areas.map((area) => {317 const total = job.runs.filter((each) => each.area === area).length;318319 return {320 area,321 passed: failing.has(area) ? total - 1 : total,322 suite: job.suite,323 total,324 };325 });326327/**328 * The world's Checker, with held-back jobs answered from the failing areas329 * and recorded; every other job goes to the scripted one.330 */331const sealedChecker = Layer.effect(332 CheckRunner,333 Effect.gen(function* () {334 const inner = yield* CheckRunner;335 const sealed = yield* Sealed;336337 return CheckRunner.of({338 run: (job) =>339 job.heldBack === undefined340 ? inner.run(job)341 : Effect.gen(function* () {342 yield* Ref.update(sealed.jobs, (all) => [...all, job]);343344 if (yield* Ref.get(sealed.blocked)) {345 return yield* new VerifierBlocked({});346 }347348 const failing = yield* Ref.get(sealed.failing);349350 return {351 durationMs: 7,352 evidence: [],353 heldBack: bitsOf(heldBackJob, failing),354 lanes: [],355 } satisfies CheckRun;356 }),357 });358 })359);360361const mainRef = RefName.make("refs/heads/main");362363/** The layer's repo, holding the suite on `main`, in a private host of its own. */364const layerRepos = Layer.effect(365 LayerRepos,366 Effect.gen(function* () {367 const host = yield* RepoHost;368 const client = yield* gitClient(memoryFs());369370 yield* host.create(layerRepo).pipe(Effect.orDie);371372 const commit = yield* client.commit(373 "Seal the suite",374 sealedFiles.map(({ content, path }) => [path, content] as const),375 []376 );377378 yield* host379 .push(layerRepo, client.source, [380 { from: Option.none(), ref: mainRef, to: commit },381 ])382 .pipe(Effect.orDie);383384 return LayerRepos.of(host);385 })386).pipe(Layer.provide(Layer.fresh(RepoHostMemory)));387388/**389 * The Answer Workflow's world with the visibility cartridge's parts390 * plugged in over it: the fakes, the layer's repo, the sealed Checker and391 * the cartridge's landing guards.392 */393export const sealedWorld = (given: Policy) =>394 Layer.mergeAll(sealedChecker, LandingGuardsLive).pipe(395 Layer.provideMerge(worldWith(given)),396 Layer.provideMerge(layerRepos),397 Layer.provideMerge(fakes)398 );
added:apps/platform/test/visibility/held-back.test.ts+998 added
1/**2 * The `Answer` Workflow judged by the sealed suite its claim was pinned to3 * (W6 613; spec §5 steps 7 (d) and 8): its held-back step, the landing4 * guards before any check, and the scans that keep a stored value out of5 * what leaves a run, over the Answer Workflow's world with the visibility6 * cartridge's parts plugged in (`held-back.fixtures.ts`).7 *8 * A stored value in an added file is quarantined as a refusal that names9 * nothing (`VerifierBlocked`) until the project service can open the10 * `SecretInTree` decision that should hold it for the deciders.11 */12import { describe, expect, it } from "@effect/vitest";13import { ObjectId, RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";14import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";15import { CheckAt, CheckRunner, shaOf } from "@repo/checks/check-runner";16import type { CheckJob } from "@repo/checks/check-runner";17import { CheckExit } from "@repo/checks/check-runner/wire";18import type { CheckWire } from "@repo/checks/check-runner/wire";19import { EvidenceKept } from "@repo/checks/evidence-store/memory";20import { parseTrailers } from "@repo/git/trailers";21import { AnswerView, Verdict } from "@repo/protocol/domain/answer";22import type { HeldBackResult } from "@repo/protocol/domain/answer";23import { Command } from "@repo/protocol/domain/common";24import { ProjectEvent } from "@repo/protocol/domain/event";25import { Outcome } from "@repo/protocol/domain/outcome";26import {27 EnvKey,28 LandedSha,29 LaneName,30 RepoName,31 RepoPath,32 RequestId,33 SuiteRoot,34 TreeSha,35} from "@repo/protocol/ids";36import type { CommitSha } from "@repo/protocol/ids";37import {38 AttemptsExhausted,39 ChecksFailed,40 HeldBackFailed,41 LayerContentInPublicTree,42 PrivatePathInPublicTree,43 VerifierBlocked,44} from "@repo/protocol/refusal";45import type { Files } from "@repo/testkit/git-client";46import { untouchable } from "@repo/testkit/untouchable";47import {48 Array,49 Effect,50 Exit,51 Layer,52 Option,53 Redacted,54 Ref,55 Schema,56 Struct,57} from "effect";5859import { CheckRunnerSandbox } from "../../src/adapters/check-runner-sandbox.ts";60import type { SandboxBinding } from "../../src/adapters/check-runner-sandbox.ts";61import { decodeEnv } from "../../src/platform.ts";62import { workerPorts } from "../../src/ports.ts";63import { LandingGuards } from "../../src/workflows/answer/guards.ts";64import { withheld } from "../../src/workflows/answer/lanes.ts";65import { runAnswer } from "../../src/workflows/answer/program.ts";66import { notesRef } from "../../src/workflows/notes.ts";67import { memoSteps } from "../../src/workflows/step.ts";68import type { StepRunner } from "../../src/workflows/step.ts";69import { fakeEnv } from "../fake-env.ts";70import {71 admitted,72 alice,73 askLane,74 bob,75 bobFork,76 changed,77 Checker,78 finishRequired,79 fixed,80 LanderCalls,81 lexPath,82 logged,83 mainMoved,84 mainTip,85 openedFiles,86 parseIso,87 parsePath,88 policy,89 project,90 Pusher,91 repo,92 scriptProjectLanes,93 Started,94 verdictOf,95} from "../workflows/answer.fixtures.ts";96import type { Admitted } from "../workflows/answer.fixtures.ts";97import {98 exportArea,99 heldBackJob,100 maintainers,101 parserArea,102 resetsAt,103 sealedFiles,104 Sealed,105 sealedWorld,106 suiteRoot,107} from "./held-back.fixtures.ts";108109/** The program run for `answer` over a fresh step record. */110const run = (answer: Admitted) =>111 Effect.flatMap(memoSteps(), (steps) =>112 runAnswer({ project, requestId: answer.requestId }).pipe(113 Effect.provide(steps)114 )115 );116117/** Every public lane on `at` passes: the ask's check and every project lane. */118const allGreen = (at: CheckAt) =>119 Effect.andThen(120 scriptProjectLanes(at, { result: "passed" }),121 Checker.use((script) => script.script(at, askLane, [{ result: "passed" }]))122 );123124/** The held-back checks of `areas` fail from now on, one check in each. */125const failing = (...areas: readonly (typeof exportArea)[]) =>126 Sealed.use(({ failing: next }) => Ref.set(next, new Set(areas)));127128const decodeVerdict = Schema.decodeUnknownEffect(129 Schema.fromJsonString(Verdict)130);131132/** The verdict note on `commit` in `at`, read as plain git finds it. */133const noteIn = (at: RepoName, commit: CommitSha) =>134 Effect.gen(function* () {135 const host = yield* RepoHost;136 const tip = (yield* host.refs(at).pipe(Effect.orDie)).get(notesRef);137138 if (tip === undefined) {139 return Option.none();140 }141142 const notes = Option.getOrThrow(143 yield* host.readCommit(at, tip).pipe(Effect.orDie)144 );145146 const entries = Option.getOrThrow(147 yield* host.readTree(at, notes.tree).pipe(Effect.orDie)148 );149150 const entry = entries.find(({ name }) => name === commit);151152 if (entry === undefined) {153 return Option.none();154 }155156 const blob = Option.getOrThrow(157 yield* host.readBlob(at, ObjectId.make(entry.sha)).pipe(Effect.orDie)158 );159160 return Option.some(161 yield* decodeVerdict(new TextDecoder().decode(blob)).pipe(Effect.orDie)162 );163 });164165/** The verdict note on `head` in bob's fork. */166const noteOn = (head: CommitSha) => noteIn(bobFork, head);167168/**169 * bob's next answer on the same claim: `files` pushed on his fork's last170 * head, and submitted; its merged tree's public lanes all pass.171 */172const answerAgain = (answer: Admitted, files: Files) =>173 Effect.gen(function* () {174 const head = yield* Pusher.use((each) =>175 each.push(bobFork, Option.some(answer.head), files)176 );177178 const merged = yield* LanderCalls.use((calls) =>179 calls.preview({180 base: answer.opened,181 fork: bobFork,182 head,183 main: answer.opened,184 repo,185 })186 );187188 const receipt = yield* answer.api.submitAnswer(bob, {189 ask: parseIso,190 base: answer.opened,191 head,192 requestId: RequestId.make(`push-${head}`),193 });194195 yield* allGreen(merged);196197 return { ...answer, head, merged, requestId: receipt.requestId };198 }).pipe(Effect.orDie);199200describe("the held-back step", () => {201 it.effect(202 "refuses an answer whose public checks pass and whose export check fails, in its verdict, its note and status, and lands nothing",203 () =>204 Effect.gen(function* () {205 const answer = yield* admitted();206207 yield* allGreen(answer.merged);208 yield* failing(exportArea);209210 const outcome = yield* run(answer);211 const { answers } = yield* answer.api.status(bob);212213 const refused = Outcome.cases.Refused.make({214 refusals: [215 new HeldBackFailed({ area: exportArea, suite: suiteRoot }),216 ],217 });218219 expect(outcome).toStrictEqual(refused);220 expect(221 Option.map(222 yield* verdictOf(answer.api),223 ({ outcome: judged }) => judged224 )225 ).toStrictEqual(Option.some(refused));226 expect(227 Option.map(yield* noteOn(answer.head), ({ outcome: noted }) => noted)228 ).toStrictEqual(Option.some(refused));229 expect(answers.map((each) => each.outcome)).toStrictEqual([refused]);230 expect(yield* mainTip).toBe(answer.opened);231 }).pipe(Effect.provide(sealedWorld(policy)))232 );233234 it.effect(235 "counts one attempt per held-back run, however often the Workflow is replayed or its steps run twice",236 () =>237 Effect.gen(function* () {238 const answer = yield* admitted();239240 yield* allGreen(answer.merged);241 yield* failing(exportArea);242243 const steps = yield* memoSteps();244245 const over = (record: Layer.Layer<StepRunner>) =>246 runAnswer({ project, requestId: answer.requestId }).pipe(247 Effect.provide(record)248 );249250 const twice = Layer.unwrap(251 Effect.map(memoSteps(), (memo) => logged(memo, { twice: true }))252 );253254 const outcomes = [255 yield* over(twice),256 yield* over(steps),257 yield* over(steps),258 ];259260 const second = yield* answerAgain(261 answer,262 changed(263 fixed,264 parsePath,265 "export const parse = (s) => ({ year: 2026, s });\n"266 )267 );268269 expect(outcomes).toStrictEqual([outcomes[0], outcomes[0], outcomes[0]]);270 expect(yield* Sealed.use(({ judged }) => judged)).toBe(1);271 // The next answer on the claim is its second failure, not its third.272 expect(yield* run(second)).toStrictEqual(273 Outcome.cases.Refused.make({274 refusals: [275 new HeldBackFailed({ area: exportArea, suite: suiteRoot }),276 ],277 })278 );279 }).pipe(Effect.provide(sealedWorld(policy)))280 );281282 it.effect(283 "carries a passing held-back result over a moved main to the re-merged tree, whose public lanes run again",284 () =>285 Effect.gen(function* () {286 const answer = yield* admitted();287288 yield* allGreen(answer.merged);289290 const moved = yield* mainMoved(291 answer.opened,292 changed(293 openedFiles,294 lexPath,295 "export const lex = (s) => s.split(/ +/);\n"296 )297 );298299 const remerged = yield* LanderCalls.use(({ preview }) =>300 preview({301 base: answer.opened,302 fork: bobFork,303 head: answer.head,304 main: moved,305 repo,306 })307 );308309 yield* allGreen(remerged);310311 const outcome = yield* run(answer);312 const tip = yield* mainTip;313 const sealedJobs = yield* Sealed.use(({ jobs }) => Ref.get(jobs));314 const { landing } = yield* answer.api.landing(bob, tip);315316 const publicTrees = yield* Checker.use(({ jobs }) =>317 Effect.map(jobs, (all) =>318 Array.dedupe(319 all320 .filter(({ at }) => CheckAt.guards.Tree(at))321 .map(({ at }) => shaOf(at))322 )323 )324 );325326 expect(outcome).toStrictEqual(Outcome.cases.Landed.make({ sha: tip }));327 expect(publicTrees).toStrictEqual([328 shaOf(answer.merged),329 shaOf(remerged),330 ]);331 expect(sealedJobs.map(({ at }) => at)).toStrictEqual([answer.merged]);332 expect(landing.heldBackTrailer).toBe(333 `Held-back: export 2/2 @ ${suiteRoot}; parser 1/1 @ ${suiteRoot}`334 );335 }).pipe(Effect.provide(sealedWorld(policy)))336 );337338 it.effect(339 "waits, counting nothing, when the Checker cannot run the suite",340 () =>341 Effect.gen(function* () {342 const answer = yield* admitted();343344 yield* allGreen(answer.merged);345 yield* Sealed.use(({ blocked }) => Ref.set(blocked, true));346347 const outcome = yield* run(answer);348349 expect(outcome).toStrictEqual(350 Outcome.cases.Checking.make({ stage: "checks" })351 );352 expect(yield* Sealed.use(({ judged }) => judged)).toBe(0);353 expect(yield* mainTip).toBe(answer.opened);354 }).pipe(Effect.provide(sealedWorld(policy)))355 );356357 it.effect(358 "spends the area on the claim's third failed run: AttemptsExhausted",359 () =>360 Effect.gen(function* () {361 const first = yield* admitted();362363 yield* allGreen(first.merged);364 yield* failing(exportArea);365366 const outcomes = [yield* run(first)];367368 const second = yield* answerAgain(369 first,370 changed(371 fixed,372 parsePath,373 "export const parse = (s) => ({ year: 2026, s });\n"374 )375 );376377 outcomes.push(yield* run(second));378379 const third = yield* answerAgain(380 second,381 changed(382 fixed,383 parsePath,384 "export const parse = (s) => ({ year: 2026, t: s });\n"385 )386 );387388 outcomes.push(yield* run(third));389390 expect(391 outcomes.map((outcome) =>392 Outcome.guards.Refused(outcome)393 ? outcome.refusals.map(({ _tag }) => _tag)394 : outcome._tag395 )396 ).toStrictEqual([397 ["HeldBackFailed"],398 ["HeldBackFailed"],399 ["AttemptsExhausted"],400 ]);401 expect(outcomes[2]).toStrictEqual(402 Outcome.cases.Refused.make({403 refusals: [new AttemptsExhausted({ area: exportArea, resetsAt })],404 })405 );406 expect(yield* mainTip).toBe(first.opened);407 }).pipe(Effect.provide(sealedWorld(policy)))408 );409410 it.effect(411 "lands an answer that passes every area with the Held-back trailer, from a job that carried the suite and nothing of the layer's",412 () =>413 Effect.gen(function* () {414 const answer = yield* admitted();415416 yield* allGreen(answer.merged);417418 const outcome = yield* run(answer);419 const tip = yield* mainTip;420 const host = yield* RepoHost;421422 const commit = Option.getOrThrow(423 yield* host.readCommit(repo, tip).pipe(Effect.orDie)424 );425426 const { landing } = yield* answer.api.landing(bob, LandedSha.make(tip));427 const jobs = yield* Sealed.use(({ jobs: given }) => Ref.get(given));428 const value = `export 2/2 @ ${suiteRoot}; parser 1/1 @ ${suiteRoot}`;429430 expect(outcome).toStrictEqual(431 Outcome.cases.Landed.make({ sha: LandedSha.make(tip) })432 );433 expect(434 parseTrailers(commit.message).filter(({ key }) => key === "Held-back")435 ).toStrictEqual([{ key: "Held-back", value }]);436 expect(landing.heldBackTrailer).toBe(`Held-back: ${value}`);437 expect(438 jobs.map((job) => ({439 at: job.at,440 files: job.heldBack?.files.map(({ area, path }) => [area, path]),441 lanes: job.lanes,442 repo: job.repo,443 suite: job.heldBack?.suite,444 }))445 ).toStrictEqual([446 {447 at: answer.merged,448 files: sealedFiles.map(({ area, path }) => [area, path]),449 lanes: [],450 repo: bobFork,451 suite: suiteRoot,452 },453 ]);454 // No layer repo, route or token: only the files, read by the platform.455 expect(JSON.stringify(jobs)).not.toContain(maintainers);456 }).pipe(Effect.provide(sealedWorld(policy)))457 );458});459460/** A file in the ask's territory holding a sealed check's bytes, blob for blob. */461const copied = RepoPath.make("packages/parser/src/copied.ts");462463const copiedContent = sealedFiles[0]?.content ?? "";464465/** Every Checker job on the merged tree `at`. */466const jobsOn = (at: CheckAt) =>467 Checker.use(({ jobs }) =>468 Effect.map(jobs, (all) => all.filter((job) => shaOf(job.at) === shaOf(at)))469 );470471const encoder = new TextEncoder();472473/** The git id of a blob holding `text`. */474const blobIdOf = (text: string) =>475 Effect.map(476 Effect.promise(() =>477 crypto.subtle.digest(478 "SHA-1",479 encoder.encode(`blob ${encoder.encode(text).length}\0${text}`)480 )481 ),482 (digest) =>483 ObjectId.make(484 [...new Uint8Array(digest)]485 .map((byte) => byte.toString(16).padStart(2, "0"))486 .join("")487 )488 );489490/**491 * The world's host, with each blob read from bob's fork going through492 * `read` (given the read the host would make), as the Workflow sees it.493 */494const forkReads = (495 read: (496 id: ObjectId,497 given: Effect.Effect<Option.Option<Uint8Array>, RepoNotFound>498 ) => Effect.Effect<Option.Option<Uint8Array>, RepoNotFound>499) =>500 Effect.map(Effect.service(RepoHost), (host) =>501 RepoHost.of({502 ...host,503 readBlob: (name, id) =>504 name === bobFork505 ? read(id, host.readBlob(name, id))506 : host.readBlob(name, id),507 })508 );509510describe("the landing guards", () => {511 it.effect(512 "are plugged into the Worker's ports with the cartridge, and nowhere without it",513 () =>514 Effect.gen(function* () {515 const config = yield* decodeEnv(fakeEnv()).pipe(Effect.orDie);516517 const plugged = yield* Effect.scoped(518 Effect.flatMap(Layer.build(workerPorts(config)), (ports) =>519 Effect.provideContext(Effect.service(LandingGuards), ports)520 )521 );522523 expect(Option.isSome(plugged)).toBeTruthy();524 expect(Option.isSome(yield* Effect.service(LandingGuards))).toBeFalsy();525 })526 );527528 it.effect(529 "refuse a push that adds a layer's path at stage 1, before any check runs",530 () =>531 Effect.gen(function* () {532 const answer = yield* admitted();533 const escape = "checks/held-back/export/escape.test.ts";534535 const head = yield* Pusher.use((each) =>536 each.push(537 bobFork,538 Option.some(answer.head),539 changed(fixed, escape, 'it("escapes", () => {});\n')540 )541 );542543 const refusals = yield* answer.api.recordPush({544 after: head,545 before: Option.some(answer.head),546 eventId: "push-escape",547 pusher: bob,548 ref: "refs/heads/main",549 repo: bobFork,550 });551552 expect(refusals.map(({ _tag }) => _tag)).toContain(553 "PrivatePathInPublicTree"554 );555 expect(yield* Started.use(({ ids }) => ids)).toStrictEqual([556 answer.requestId,557 ]);558 }).pipe(Effect.provide(sealedWorld(policy)))559 );560561 it.effect(562 "refuse an admitted answer whose path a layer took since, before any check runs, naming all the answerer's paths to one who cannot read it",563 () =>564 Effect.gen(function* () {565 const taken = RepoPath.make("packages/parser/src/sealed.ts");566567 const answer = yield* admitted(568 changed(fixed, taken, "export const sealed = 1;\n")569 );570571 yield* allGreen(answer.merged);572 yield* Sealed.use(({ layerPaths }) =>573 Ref.update(layerPaths, (paths) => new Set([...paths, taken]))574 );575576 expect(yield* run(answer)).toStrictEqual(577 Outcome.cases.Refused.make({578 refusals: [579 new PrivatePathInPublicTree({ paths: [parsePath, taken] }),580 ],581 })582 );583 expect(yield* jobsOn(answer.merged)).toStrictEqual([]);584 expect(yield* mainTip).toBe(answer.opened);585 }).pipe(Effect.provide(sealedWorld(policy)))586 );587588 it.effect(589 "refuse a finish whose finisher reads the layer and adds a file holding a layer's blob: LayerContentInPublicTree",590 () =>591 Effect.gen(function* () {592 const answer = yield* admitted();593594 yield* allGreen(answer.merged);595596 expect(yield* run(answer)).toStrictEqual(597 Outcome.cases.AwaitingFinish.make({})598 );599600 const finished = yield* Pusher.use((each) =>601 each.push(602 bobFork,603 Option.some(answer.head),604 changed(fixed, copied, copiedContent)605 )606 );607608 const receipt = yield* answer.api609 .finish(alice, {610 ask: parseIso,611 base: answer.opened,612 head: finished,613 requestId: RequestId.make(`finish-${finished}`),614 })615 .pipe(Effect.orDie);616617 expect(618 yield* runAnswer({ project, requestId: receipt.requestId }).pipe(619 Effect.provide(yield* memoSteps())620 )621 ).toStrictEqual(622 Outcome.cases.Refused.make({623 refusals: [new LayerContentInPublicTree({ paths: [copied] })],624 })625 );626 }).pipe(Effect.provide(sealedWorld(finishRequired)))627 );628629 it.effect(630 "say nothing of a layer's content to an answerer who cannot read it: the same file lands",631 () =>632 Effect.gen(function* () {633 const answer = yield* admitted(changed(fixed, copied, copiedContent));634635 yield* allGreen(answer.merged);636637 const outcome = yield* run(answer);638639 expect(outcome).toStrictEqual(640 Outcome.cases.Landed.make({ sha: yield* mainTip })641 );642 }).pipe(Effect.provide(sealedWorld(policy)))643 );644645 it.effect(646 "wait, running no check and counting nothing, when the answer's fork cannot be read for the files it writes",647 () =>648 Effect.gen(function* () {649 const answer = yield* admitted();650651 yield* allGreen(answer.merged);652653 const host = yield* forkReads(() =>654 Effect.fail(new RepoNotFound({ name: bobFork }))655 );656657 const outcome = yield* run(answer).pipe(658 Effect.provideService(RepoHost, host)659 );660661 expect(outcome).toStrictEqual(662 Outcome.cases.Checking.make({ stage: "checks" })663 );664 expect(yield* jobsOn(answer.merged)).toStrictEqual([]);665 expect(yield* mainTip).toBe(answer.opened);666 }).pipe(Effect.provide(sealedWorld(policy)))667 );668669 it.effect(670 "scan nothing for a change no blob in the fork holds, a submodule's pointer, and let the answer on",671 () =>672 Effect.gen(function* () {673 const content = "a pointer to a commit in another repo\n";674675 const answer = yield* admitted(676 changed(fixed, "packages/parser/src/tz", content)677 );678679 yield* allGreen(answer.merged);680681 const pointer = yield* blobIdOf(content);682683 const host = yield* forkReads((id, given) =>684 id === pointer ? Effect.succeedNone : given685 );686687 const outcome = yield* run(answer).pipe(688 Effect.provideService(RepoHost, host)689 );690691 expect(outcome).toStrictEqual(692 Outcome.cases.Landed.make({ sha: yield* mainTip })693 );694 }).pipe(Effect.provide(sealedWorld(policy)))695 );696});697698/** datekit's `SENTRY_AUTH_TOKEN`, as a decider stores it. */699const sentry = EnvKey.make("SENTRY_AUTH_TOKEN");700701const token = "sntrys_0a1b2c3d4e5f6a7b8c9d";702703/** alice stores datekit's Sentry token: a write-only value. */704const stored = (answer: Admitted) =>705 answer.api706 .setEnv(alice, { key: sentry, value: Redacted.make(token) })707 .pipe(Effect.orDie);708709/**710 * Everything the answerer reads of their answer, as text: its status, its711 * verdict, the note on its head, and the project's events.712 */713const answererReads = (answer: Admitted) =>714 Effect.gen(function* () {715 const status = yield* answer.api.status(bob);716 const verdict = yield* verdictOf(answer.api);717 const note = yield* noteOn(answer.head);718 const events = yield* answer.api.events(0, 1000);719720 return JSON.stringify([721 yield* Schema.encodeEffect(Schema.toCodecJson(Schema.Array(AnswerView)))(722 status.answers723 ),724 yield* Schema.encodeEffect(Schema.toCodecJson(Schema.Option(Verdict)))(725 verdict726 ),727 yield* Schema.encodeEffect(Schema.toCodecJson(Schema.Option(Verdict)))(728 note729 ),730 yield* Schema.encodeEffect(731 Schema.toCodecJson(Schema.Array(ProjectEvent))732 )(events.map(({ event }) => event)),733 ]);734 }).pipe(Effect.orDie);735736describe("a stored value where it must not be", () => {737 it.effect(738 "quarantines an answer that adds a file holding a stored value: no check runs, it never lands, and nothing its answerer reads names the item",739 () =>740 Effect.gen(function* () {741 const answer = yield* admitted(742 changed(743 fixed,744 "packages/parser/src/report.ts",745 `export const dsn = "https://${token}@sentry.io/1";\n`746 )747 );748749 yield* stored(answer);750 yield* allGreen(answer.merged);751752 const outcome = yield* run(answer);753 const read = yield* answererReads(answer);754755 // Until the project can open the deciders' `SecretInTree` decision756 // (and the answer waits, `AwaitingDecision`), a refusal naming nothing.757 expect(outcome).toStrictEqual(758 Outcome.cases.Refused.make({ refusals: [new VerifierBlocked({})] })759 );760 expect(yield* jobsOn(answer.merged)).toStrictEqual([]);761 expect(yield* mainTip).toBe(answer.opened);762 expect(read).not.toContain(sentry);763 expect(read).not.toContain(token);764 }).pipe(Effect.provide(sealedWorld(policy)))765 );766767 it.effect(768 "keeps a lane log holding a stored value out of the evidence: its lane still refuses, under a withheld log, and nothing its answerer reads names the item",769 () =>770 Effect.gen(function* () {771 const answer = yield* admitted();772 const unit = LaneName.make("unit");773774 yield* stored(answer);775 yield* allGreen(answer.merged);776 yield* Checker.use((script) =>777 Effect.andThen(778 script.script(answer.merged, unit, [779 {780 result: "failed",781 signature: `reports: AssertionError: expected "${token}" to be redacted`,782 },783 ]),784 script.script(785 CheckAt.cases.Commit.make({ commit: answer.opened }),786 unit,787 [{ result: "passed" }]788 )789 )790 );791792 const outcome = yield* run(answer);793 const puts = yield* EvidenceKept.use((kept) => kept.puts);794 const read = yield* answererReads(answer);795796 expect(outcome).toStrictEqual(797 Outcome.cases.Refused.make({798 refusals: [799 new ChecksFailed({800 lane: unit,801 logRef: withheld,802 next: "bun run test",803 }),804 ],805 })806 );807 expect(puts).toStrictEqual([]);808 expect(read).not.toContain(sentry);809 expect(read).not.toContain(token);810 }).pipe(Effect.provide(sealedWorld(policy)))811 );812813 it.effect(814 "writes no verdict note that would carry a stored value, on the fork or on the landed commit, and the answer lands as it would",815 () =>816 Effect.gen(function* () {817 const answer = yield* admitted();818819 yield* stored(answer);820 yield* allGreen(answer.merged);821822 const outcome = yield* run(answer);823 const tip = yield* mainTip;824825 expect(outcome).toStrictEqual(Outcome.cases.Landed.make({ sha: tip }));826 expect(yield* noteOn(answer.head)).toStrictEqual(Option.none());827 expect(yield* noteIn(repo, tip)).toStrictEqual(Option.none());828 }).pipe(829 Effect.provide(830 sealedWorld({831 ...policy,832 run: {833 ...policy.run,834 // A decider's slip: the value in a lane's command, which every verdict quotes.835 checks: {836 ...policy.run.checks,837 [LaneName.make("unit")]: Command.make(838 `SENTRY_AUTH_TOKEN=${token} bun run test`839 ),840 },841 },842 })843 )844 )845 );846});847848/** A fork the adapter clones from, in a store of its own. */849const sandboxFork = RepoName.make("datekit--parse-iso--bob");850851/** A held-back job, as the held-back step sends it: the suite alone. */852const sealedJob: CheckJob = {853 at: CheckAt.cases.Tree.make({ tree: TreeSha.make("5".repeat(40)) }),854 heldBack: heldBackJob,855 lanes: [],856 placeholders: [],857 project,858 proxies: [],859 repo: sandboxFork,860 run: policy.run,861};862863/** The bits a sandbox that ran `job`'s suite reports when every check passed. */864const allPassed: readonly HeldBackResult[] = [865 { area: exportArea, passed: 2, suite: suiteRoot, total: 2 },866 { area: parserArea, passed: 1, suite: suiteRoot, total: 1 },867];868869/**870 * `CheckRunnerSandbox` over a sandbox that answers every job with871 * `heldBack` as its area bits, and keeps each wire it was sent, encoded.872 */873const overSandbox = (heldBack: readonly HeldBackResult[]) =>874 Effect.gen(function* () {875 const sent: (typeof CheckWire.Encoded)[] = [];876877 const exit = yield* Schema.encodeEffect(CheckExit)(878 Exit.succeed({ durationMs: 9, evidence: [], heldBack, lanes: [] })879 ).pipe(Effect.orDie);880881 const sandbox = untouchable<SandboxBinding>("SANDBOX", {882 check: (wire) => {883 sent.push(wire);884885 return Promise.resolve(exit);886 },887 });888889 yield* RepoHost.use((host) => host.create(sandboxFork)).pipe(Effect.orDie);890891 const runner = yield* Effect.service(CheckRunner).pipe(892 Effect.provide(CheckRunnerSandbox(sandbox))893 );894895 return { runner, sent };896 });897898describe("a held-back job through the sandbox", () => {899 it.effect(900 "sends the suite's files as base64 beside one read token on the answer's fork, and hands back its area bits",901 () =>902 Effect.gen(function* () {903 const { runner, sent } = yield* overSandbox(allPassed);904 const ran = yield* runner.run(sealedJob).pipe(Effect.orDie);905 const remote = yield* RepoHost.use((host) => host.remote(sandboxFork));906907 expect(ran.heldBack).toStrictEqual(allPassed);908 expect(909 sent.map(({ clone, job }) => ({910 files: job.heldBack?.files.map(({ contentBase64, path }) => ({911 contentBase64,912 path,913 })),914 url: clone.url,915 }))916 ).toStrictEqual([917 {918 files: sealedFiles.map(({ content, path }) => ({919 contentBase64: btoa(content),920 path,921 })),922 url: remote,923 },924 ]);925 expect(JSON.stringify(sent)).not.toContain(maintainers);926 }).pipe(Effect.provide(Layer.fresh(RepoHostMemory)))927 );928929 it.effect(930 "takes one bit per area from a suite that names an area twice, as the Checker counts them",931 () =>932 Effect.gen(function* () {933 const { runner } = yield* overSandbox(allPassed);934935 const ran = yield* Effect.exit(936 runner.run({937 ...sealedJob,938 heldBack: {939 ...heldBackJob,940 areas: [exportArea, parserArea, exportArea],941 },942 })943 );944945 expect(Exit.map(ran, ({ heldBack }) => heldBack)).toStrictEqual(946 Exit.succeed(allPassed)947 );948 }).pipe(Effect.provide(Layer.fresh(RepoHostMemory)))949 );950951 it.effect(952 "refuses area bits that do not answer the job it sent: VerifierBlocked, never a bit an answer earned",953 () =>954 Effect.gen(function* () {955 const otherSuite = SuiteRoot.make(`sha256:${"0".repeat(64)}`);956957 const wrong: readonly {958 readonly job: CheckJob;959 readonly bits: readonly HeldBackResult[];960 }[] = [961 // An area left out.962 { bits: allPassed.slice(0, 1), job: sealedJob },963 // Another suite's bits.964 {965 bits: allPassed.map((each) => ({ ...each, suite: otherSuite })),966 job: sealedJob,967 },968 // More checks passed than the area has.969 {970 bits: allPassed.map((each) => ({971 ...each,972 passed: each.total + 1,973 })),974 job: sealedJob,975 },976 // A count that is not the area's.977 {978 bits: allPassed.map((each) => ({ ...each, total: each.total + 1 })),979 job: sealedJob,980 },981 // Bits for a job that sent no suite.982 { bits: allPassed, job: Struct.omit(sealedJob, ["heldBack"]) },983 ];984985 const outcomes = yield* Effect.forEach(wrong, ({ bits, job }) =>986 Effect.gen(function* () {987 const { runner } = yield* overSandbox(bits);988989 return yield* Effect.exit(runner.run(job));990 }).pipe(Effect.provide(Layer.fresh(RepoHostMemory)))991 );992993 expect(outcomes).toStrictEqual(994 wrong.map(() => Exit.fail(new VerifierBlocked({})))995 );996 })997 );998});