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
Provenance
- Commit
c3d7b1b- Tree
427b687- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
2894306- Parent 2
903a9e6
9 files changed+2209 added−84 removed
modified:apps/platform/src/adapters/check-runner-sandbox.ts+60 added-2 removed
2 unmodified lines345678910111213141516171819202122233 unmodified lines27282930313221333435363720 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710811 unmodified lines120121122123691241251261271281291302 unmodified lines * Checker through the `SANDBOX` service binding, with one read token on the * repo it clones from and nothing else. The Checker's container never sees * the token (W3 315); its outcome comes back as the port's own `CheckRun` or * `VerifierBlocked`. * * A job's sealed suite (W6 605, 613) crosses as the platform read it: the * layer's files under the sealed areas, base64 on the wire, and one run per * sealed check. No layer repo, route or token goes with it, so the only * token is still the one on the answer's fork. Its area bits come back * decoded and held to the job that asked for them: one per area the job * sent, under the job's suite, each counting that area's checks. Bits that * answer some other job are the platform's trouble (`VerifierBlocked`), * never a result an answer earned. */import { RepoHost } from "@repo/artifacts/repo-host";import { CheckRunner } from "@repo/checks/check-runner";import type { CheckJob, CheckRun } from "@repo/checks/check-runner";import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";import type { BundleExit, BundleWire,3 unmodified lines LandWire, MergeExit, MergeWire,} from "@repo/project/lander/wire";import type { HeldBackResult } from "@repo/protocol/domain/answer";import { VerifierBlocked } from "@repo/protocol/refusal";import { Effect, Layer } from "effect";import { Array, Effect, Layer } from "effect";
import { sandboxJob, withRemote } from "./sandbox-credentials.ts";
/**20 unmodified lines wire: typeof BundleWire.Encoded ) => Promise<typeof BundleExit.Encoded>;}
/** * Whether `bits` are the area bits of `job`'s suite: each area it sent, * once and in order, as the Checker counts them (`areaBits`). */const answersJob = (job: CheckJob, bits: readonly HeldBackResult[]) => { const suite = job.heldBack;
if (suite === undefined) { return bits.length === 0; }
const areas = Array.dedupe(suite.areas);
return ( bits.length === areas.length && areas.every((area, index) => { const each = bits[index]; const total = suite.runs.filter((run) => run.area === area).length;
return ( each !== undefined && each.area === area && each.suite === suite.suite && each.total === total && each.passed >= 0 && each.passed <= total ); }) );};
/** A run whose area bits answer `job`, or `VerifierBlocked` with one log line naming nothing sealed. */const heldTo = (job: CheckJob) => (ran: CheckRun) => answersJob(job, ran.heldBack) ? Effect.succeed(ran) : Effect.logError("sandbox job blocked").pipe( Effect.annotateLogs({ failure: "held-back bits do not answer the job", method: "check", }), Effect.andThen(Effect.fail(new VerifierBlocked({}))) );
export const CheckRunnerSandbox = ( sandbox: SandboxBinding): Layer.Layer<CheckRunner, never, RepoHost> => Layer.effect(11 unmodified lines remotes: [clone], send: (wire) => sandbox.check(wire), wire: CheckWire, }) ).pipe(Effect.provideService(RepoHost, host)), ).pipe( Effect.flatMap(heldTo(job)), Effect.provideService(RepoHost, host) ), }); }) );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+ */19+import type { Fetch } from "@repo/artifacts/fetch";20+import { ObjectId, RefName } from "@repo/artifacts/repo-host";21+import type { RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";22+import type { ProjectApi } from "@repo/project/project";23+import { Projects } from "@repo/project/projects";24+import type { Layer as LayerDeclaration } from "@repo/protocol/domain/visibility";25+import { BlobSha, RepoName, RepoPath } from "@repo/protocol/ids";26+import type { Handle } from "@repo/protocol/ids";27+import { Anonymous, Person } from "@repo/protocol/principal";28+import { privatePaths, writeDown } from "@repo/visibility/guards";29+import { LayerRepos } from "@repo/visibility/layer-repos";30+import { Effect, Layer, Option } from "effect";31+32+import type { PlatformConfig } from "../platform.ts";33+import { LandingGuards } from "../workflows/answer/guards.ts";34+import type { GuardInput } from "../workflows/answer/guards.ts";35+import { layerRepos } from "./layer-repos.ts";36+37+const mainRef = RefName.make("refs/heads/main");38+39+/** A layer's repo: as declared, or `<project>--<layer>` (spec §4.5). */40+const repoOf = (project: string, layer: LayerDeclaration) =>41+ layer.repo ?? RepoName.make(`${project}--${layer.name}`);42+43+/** Every blob under `tree` in `repo`, at any depth. */44+const 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+ );63+64+/** The blobs a layer's repo holds on `main`; none for a layer with no repo yet. */65+const layerBlobs = (host: RepoHost["Service"], repo: RepoName) =>66+ Effect.gen(function* () {67+ const tip = (yield* host.refs(repo)).get(mainRef);68+69+ if (tip === undefined) {70+ return [];71+ }72+73+ const commit = yield* host.readCommit(repo, tip);74+75+ return Option.isNone(commit)76+ ? []77+ : yield* blobsUnder(host, repo, commit.value.tree);78+ }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeed([])));79+80+/** Whether `handle` may read `layer`: its readers and writers. */81+const 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+ );86+87+/** The guards on one answer's merged change set, over its project and the private namespace. */88+const 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];94+95+ const { layers } = yield* api96+ .ledger(Anonymous.make({}))97+ .pipe(Effect.orDie);98+99+ const facts = yield* api.layerFacts(100+ Person.make({ handle: input.answerer })101+ );102+103+ 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+ );109+110+ const readable = access.filter(({ each }) => each.some(Boolean));111+112+ const readsAll =113+ access.length > 0 && access.every(({ each }) => each.every(Boolean));114+115+ const blobs = yield* Effect.forEach(readable, ({ layer }) =>116+ layerBlobs(repos, repoOf(input.project, layer))117+ );118+119+ 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+ });138+139+/** The landing guards over the project's layers, as `LayerRepos` holds them. */140+export 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;149+150+ return Option.some({ check: guardsOver(repos, projects) });151+ })152+);153+154+/** The landing guards for one stage, over its private namespace (`ARTIFACTS_PRIVATE`). */155+export 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
1234545678910111213141516171819182021222322242526272829/** * The visibility cartridge, whole (W6 609; SYN cut line 5): the gateway's * layer repos (`layers.ts`), the project service's visibility state * (`state.ts`) and env (`env.ts`), for one stage's config, over the * platform's own ports. `ports.ts` plugs it in by one marked line; * (`state.ts`) and env (`env.ts`), and the `Answer` Workflow's landing * guards (`held-back.ts`), for one stage's config, over the platform's own * ports. `ports.ts` plugs it in by one marked line; * deleting that line, this folder, `@repo/visibility` and the * `ARTIFACTS_PRIVATE` binding leaves the platform without typed visibility * (`packages/config/test/cartridge.test.ts` lists what to delete). */import { Layer } from "effect";
import type { PlatformConfig } from "../platform.ts";import type { WorkerPorts } from "../ports.ts";import { envLive } from "./env.ts";import { heldBackLive } from "./held-back.ts";import { layersLive } from "./layers.ts";import { stateLive } from "./state.ts";
/** The cartridge's layer for one stage's config, filling `LayerGate`, `ProjectVisibility` and `ProjectEnv`. *//** The cartridge's layer for one stage's config, filling `LayerGate`, `ProjectVisibility`, `ProjectEnv` and `LandingGuards`. */export const live = ( config: PlatformConfig): Layer.Layer<never, never, WorkerPorts> => Layer.mergeAll(layersLive(config), stateLive(config), envLive(config)); Layer.mergeAll( layersLive(config), stateLive(config), envLive(config), heldBackLive(config) );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+ */21+import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";22+import type { Change } from "@repo/project/landing";23+import { LandingState } from "@repo/project/landing";24+import { Projects } from "@repo/project/projects";25+import { AskKind } from "@repo/protocol/domain/kind";26+import { EnvKey } from "@repo/protocol/ids";27+import type {28+ Handle,29+ ProjectName,30+ RequestId,31+ TreeSha,32+} from "@repo/protocol/ids";33+import { Refusal } from "@repo/protocol/refusal";34+import type {35+ LayerContentInPublicTree,36+ PrivatePathInPublicTree,37+} from "@repo/protocol/refusal";38+import { Array, Context, Effect, Option, Schema } from "effect";39+40+import { StepRunner } from "../step.ts";41+42+/** One answer's merged change set, and the people accountable for it. */43+export 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+}50+51+/** The no-write-down guards on a merged change set, as the visibility cartridge runs them. */52+export interface LayerGuardsPort {53+ readonly check: (54+ input: GuardInput55+ ) => Effect.Effect<56+ readonly (PrivatePathInPublicTree | LayerContentInPublicTree)[]57+ >;58+}59+60+/**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+ */65+export const LandingGuards = Context.Reference<Option.Option<LayerGuardsPort>>(66+ "platform/LandingGuards",67+ { defaultValue: () => Option.none() }68+);69+70+/** What the guards step came to, kept as its value: no names but public ones. */71+export 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+});83+84+export type GuardRun = typeof GuardRun.Type;85+86+/**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+ */90+export const passes = (run: GuardRun): boolean =>91+ GuardRun.guards.Guarded(run) &&92+ run.refusals.length === 0 &&93+ run.quarantined.length === 0;94+95+/** Files the answer puts into the public tree: added, or modified to a new blob. */96+const written = (changes: readonly Change[]) =>97+ Array.dedupe(98+ changes.flatMap(({ after, status }) =>99+ status === "deleted" || after === undefined ? [] : [after]100+ )101+ );102+103+/**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+ */108+const 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);117+118+ const run = yield* api.answer(params.requestId);119+120+ 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+ );125+126+ if (Option.isNone(found)) {127+ return GuardRun.cases.Moved.make({});128+ }129+130+ const { finish, state } = found.value;131+ const { request } = state;132+133+ 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+ });141+142+ const host = yield* RepoHost;143+144+ // 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+ );153+154+ if (Option.isNone(read)) {155+ return GuardRun.cases.Blocked.make({ attempt: state.attempt });156+ }157+158+ const held = yield* Effect.forEach(Array.getSomes(read.value), (blob) =>159+ api.scanForValues({ blob })160+ );161+162+ return GuardRun.cases.Guarded.make({163+ finish,164+ quarantined: Array.dedupe(Array.getSomes(held)),165+ refusals,166+ });167+ });168+169+/**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+ */173+export 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;184+185+ if (Option.isNone(plugged)) {186+ return Option.none();187+ }188+189+ const { step } = yield* StepRunner;190+191+ 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 */23+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";24+import { patchId } from "@repo/git/patch-id";25+import { runBlockOf } from "@repo/project/answer-runs";26+import type { AnswerRun } from "@repo/project/answer-runs";27+import { noRunEnv } from "@repo/project/env-port";28+import { LandingState } from "@repo/project/landing";29 import { Projects } from "@repo/project/projects";30+import type { HeldBackJob } from "@repo/project/visibility-port";31 import { HeldBackResult } from "@repo/protocol/domain/answer";18-import type { ProjectName, RequestId } from "@repo/protocol/ids";19-import { Refusal, VerifierBlocked } from "@repo/protocol/refusal";32+import { PatchId, SuiteRoot } from "@repo/protocol/ids";33+import type { ProjectName, RequestId, TreeSha } from "@repo/protocol/ids";34+import { Refusal } from "@repo/protocol/refusal";35 import { Effect, Option, Schema } from "effect";36 37 import { StepRunner } from "../step.ts";38 24-/** What the held-back step came to: the refusals it earned, and the area bits for the verdict. */25-export 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. */40+export 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 });53 54 export type HeldBackRun = typeof HeldBackRun.Type;55 56+/** A held-back run that judged a tree. */57+export type Judged = Extract<HeldBackRun, { readonly _tag: "Judged" }>;58+59 /** A held-back step with nothing to judge. */33-export const unsealed: HeldBackRun = { refusals: [], results: [] };60+export const unsealed: HeldBackRun = HeldBackRun.cases.Unsealed.make({});61 62 /**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+ */67+const 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+ );98+99+/**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 */106 export 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 line117 const api = yield* Projects.use((projects) =>118 projects.get(params.project)119 ).pipe(Effect.orDie);120 121+ const run = yield* api.answer(params.requestId);122+123+ 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+ );128+129+ if (Option.isNone(checking)) {130+ return unsealed;131+ }132+133+ const { found, state } = checking.value;134 const job = yield* api.heldBackJob(params.requestId);135 55- 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+ }139+140+ const patch = yield* patchId(state.changes);141+142+ const results = yield* areaBits({143+ earlier,144+ job: job.value,145+ patch,146+ run: found,147+ tree,148+ }).pipe(Effect.option);149+150+ if (Option.isNone(results)) {151+ return HeldBackRun.cases.Blocked.make({ attempt: state.attempt });152+ }153+154+ 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 lines3 * 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 lines32 import { MeasuredCount, runBlockOf } from "@repo/project/answer-runs";33 import type { AnswerRun } from "@repo/project/answer-runs";34 import { noRunEnv, RunEnv } from "@repo/project/env-port";35 import { LandingState } from "@repo/project/landing";34-import {35- HeldBackResult,36- LaneOutcome,37- LaneResult,38-} from "@repo/protocol/domain/answer";36+import { Projects } from "@repo/project/projects";37+import { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";38 import { CheckSpec } from "@repo/protocol/domain/check";39 import { AskKind } from "@repo/protocol/domain/kind";40 import { RunBlock } from "@repo/protocol/domain/run";41 import {90 unmodified lines132 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 lines195 )196 ),197 ].join("\n");198 199+/**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+ */204+export const withheld = "withheld";205+206 const isTrouble = (result: LaneOutcome) =>207 result === "flaked" || result === "blocked";208 209 /** Each lane's result and evidence in a run, by lane. */237 unmodified lines447 });448 449 /**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 */457 export 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);469 470+ // 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);475+476+ const scan = (text: string) => api.scanForValues({ text });477+478 const remerges = LandingState.guards.Checking(run.state)479 ? run.state.remerges480 : 0;481 482 const counting = stage === "cheap" && run.counts !== undefined;483 484 if (!Array.isReadonlyArrayNonEmpty(lanes) && !counting) {471- return StageRun.cases.Ran.make({ checked, heldBack: [], lanes: [] });485+ return StageRun.cases.Ran.make({ checked, lanes: [] });486 }487 488 const block = yield* runBlockOf(checked);489 15 unmodified lines505 506 if (!Array.isReadonlyArrayNonEmpty(lanes)) {507 return StageRun.cases.Ran.make({508 checked,495- heldBack: [],509 lanes: [],510 ...counts,511 });512 }16 unmodified lines529 if (standing.first.result === "passed") {530 return Effect.succeed(judged);531 }532 533+ const text = laneLog(standing.stands, standing.said);534+535+ 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 });571 572 return StageRun.cases.Ran.make({573 checked,534- heldBack: firstRun.heldBack,574 lanes: laneRuns,575 ...counts,576 });577 }).pipe(79 unmodified linesmodified:apps/platform/src/workflows/answer/program.ts+201 added-30 removed
41 unmodified lines42 LandingEffect,43 outcomeOf,44 } from "@repo/project/landing";45 import { Projects } from "@repo/project/projects";46-import { LaneOutcome } from "@repo/protocol/domain/answer";47-import type { Verdict } from "@repo/protocol/domain/answer";46+import { LaneOutcome, Verdict } from "@repo/protocol/domain/answer";47 import type { Outcome } from "@repo/protocol/domain/outcome";48 import { CommitSha } from "@repo/protocol/ids";50-import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";49+import type {50+ EnvKey,51+ LaneName,52+ ProjectName,53+ RequestId,54+} from "@repo/protocol/ids";55 import { VerifierBlocked } from "@repo/protocol/refusal";56 import {57 Array,58 Cause,2 unmodified lines61 Match,62 Option,63 Schedule,64 Schema,65+ Struct,66 } from "effect";67 68 import type { AnswerParams } from "../../answer-runs.ts";69 import { writeVerdictNote } from "../notes.ts";70 import { StepRunner } from "../step.ts";71 import type { StepRetry } from "../step.ts";72+import { guards, GuardRun, passes } from "./guards.ts";67-import { heldBack, unsealed } from "./held-back.ts";73+import { heldBack, HeldBackRun, unsealed } from "./held-back.ts";74+import type { Judged } from "./held-back.ts";75 import {76 laneOnMain,77 refusalsOf,78 runStage,99 unmodified lines178 Effect.flatMap(projectOf(project), (api) => api.answer(requestId));179 180 /**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 */185 const 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 );198 199+/** A verdict as its note holds it: JSON. */200+const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));201+202+/**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+ */207+const 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 });212+213+ 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+ }225+226+ return found;227+ });228+229+/**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+ */234+const 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+ );240+241 /** The answer's head merged onto the main the call names. */242 const merge = (params: AnswerParams, call: Call<"Merge">) =>243 portCall(244 params,16 unmodified lines261 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 lines330 [new VerifierBlocked({})]331 )332 : Effect.succeed([]);333 334+/** What a port step came to: its report, and the held-back run it judged, if any. */335+interface Ran {336+ readonly given: Option.Option<Reported>;337+ readonly judged: Option.Option<Judged>;338+}339+340+const ranOnly = (given: Option.Option<Reported>): Ran => ({341+ given,342+ judged: Option.none(),343+});344+345 /**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+ */354+const 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+ );372+373+/** The checks reported refused before any lane ran: the landing guards' refusals. */374+const 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+ );392+393+/**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 */405 const 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);413+414+ 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+ }424+425 const ran = yield* stage(params, call.tree, "cheap", attempt);426 427 const cheap = {428 ...ran,11 unmodified lines440 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;446 447 const counts = StageRun.guards.Ran(cheap.ran)448 ? Option.fromUndefinedOr(cheap.ran.counts)449 : Option.none();450 451+ if (HeldBackRun.guards.Blocked(sealed)) {452+ return ranOnly(453+ reported(LandingCommand.Blocked({ attempt: sealed.attempt }))454+ );455+ }456+457+ const held = HeldBackRun.guards.Judged(sealed)458+ ? Option.some(sealed)459+ : Option.none();460+323- 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 lines493 }),494 }495 ),496 });497+498+ return { given, judged: held };499 });500 501 /**502 * A port step's report given to the project, and the calls to run next.75 unmodified lines578 }579 580 const { fork, verdict } = judged.value;581 582+ // 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+ }587+588 const written = yield* writeVerdictNote({589 fork,590 head: verdict.head,591 verdict,40 unmodified lines632 /** The port call a step runs, under its name. */633 const 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 lines646 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 );661 662 const nameOf = {1 unmodified line664 Merge: "merge",665 RunChecks: "checks",666 } as const satisfies Record<keyof Attempts, string>;667 508-/** 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+ */673 const 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 lines691 return at.outcome;692 }693 694 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;697 698 const next = yield* step(699 `record:${nameOf[call._tag]}#${attempt}`,4 unmodified lines704 if (Option.isNone(given)) {705 return next.outcome;706 }707 543- 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 });715 716 /**717 * Carries one admitted answer as far as it goes now: merged onto main,17 unmodified lines735 {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 );742 743 yield* notes(params, outcome);744 2 unmodified linesadded: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+ */16+import { RefName, RepoHost } from "@repo/artifacts/repo-host";17+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";18+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";19+import { CheckRunner } from "@repo/checks/check-runner";20+import type { CheckJob, CheckRun } from "@repo/checks/check-runner";21+import { noEnv, ProjectEnv } from "@repo/project/env-port";22+import type { EnvPort } from "@repo/project/env-port";23+import type { AttemptRow } from "@repo/project/project-store/rows";24+import { noVisibility, ProjectVisibility } from "@repo/project/visibility-port";25+import type {26+ HeldBackJob,27+ VisibilityPort,28+} from "@repo/project/visibility-port";29+import type { HeldBackResult } from "@repo/protocol/domain/answer";30+import type { Policy } from "@repo/protocol/domain/policy";31+import {32+ AreaName,33+ CommitSha,34+ LayerName,35+ RepoName,36+ RepoPath,37+ SuiteRoot,38+} from "@repo/protocol/ids";39+import { Principal } from "@repo/protocol/principal";40+import {41+ AttemptsExhausted,42+ HeldBackFailed,43+ VerifierBlocked,44+} from "@repo/protocol/refusal";45+import { gitClient } from "@repo/testkit/git-client";46+import { heldBackValue } from "@repo/visibility/commitment";47+import { LayerRepos } from "@repo/visibility/layer-repos";48+import { scanBytes, scanText } from "@repo/visibility/leak-scan";49+import type { Watched } from "@repo/visibility/leak-scan";50+import {51+ Array,52+ Context,53+ DateTime,54+ Effect,55+ Layer,56+ Option,57+ Redacted,58+ Ref,59+ Schema,60+} from "effect";61+62+import { LandingGuardsLive } from "../../src/visibility/held-back.ts";63+import { alice, project, worldWith } from "../workflows/answer.fixtures.ts";64+65+export const maintainers = LayerName.make("maintainers");66+67+export const layerRepo = RepoName.make(`${project}--maintainers`);68+69+export const exportArea = AreaName.make("export");70+71+export const parserArea = AreaName.make("parser");72+73+/** One sealed check, as the layer holds it. */74+interface SealedFile {75+ readonly area: AreaName;76+ readonly path: RepoPath;77+ readonly content: string;78+}79+80+/** The suite: two checks in `export`, one in `parser`. */81+export const sealedFiles: readonly SealedFile[] = [82+ {83+ area: exportArea,84+ content:85+ 'it("escapes a title", () => expect(svg("<")).toContain("<"));\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+];100+101+/** The layer commit the suite is pinned at. */102+export const layerAt = CommitSha.make("e".repeat(40));103+104+/** The suite's root, as 612 publishes it. */105+export const suiteRoot = SuiteRoot.make(`sha256:${"3f".repeat(32)}`);106+107+/** The run block's `test` with each sealed check's path filled. */108+const testCommand = (path: RepoPath) => `bun test ${path}`;109+110+const encoder = new TextEncoder();111+112+/** The job `heldBackJob` gives for every pinned claim. */113+export 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+};128+129+/** How many failed held-back runs a claim may have before its area is spent. */130+const ATTEMPTS = 3;131+132+const isoWeek = "2026-W41";133+134+/** When a spent area opens again: the fake's week ends on its Monday. */135+export const resetsAt = DateTime.makeUnsafe("2026-10-12T00:00:00Z");136+137+const 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);150+151+// ------------------------------------------------------------------ the fakes152+153+/** What a test changes in the fakes as it goes, and reads back. */154+export 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") {}169+170+/**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+ */176+const 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;192+193+ const failed = input.results.filter(({ passed, total }) => passed < total);194+195+ const counted = failed.map((result) => ({196+ count: attemptsOn(snapshot.attempts, input, result.area) + 1,197+ result,198+ }));199+200+ 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+});245+246+/** What the fake env keeps of a value: the value itself, which only a fake may. */247+const KeptValue = Schema.Struct({ fake: Schema.String });248+249+/**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+ */253+const 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+ );268+269+ 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+};288+289+/** The two ports' fakes, and the test's handle on them. */290+const fakes = Layer.effectContext(291+ Effect.gen(function* () {292+ const judged = { count: 0 };293+294+ 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+ };303+304+ return Context.make(ProjectVisibility, visibilityOver(sealed, judged)).pipe(305+ Context.add(ProjectEnv, envPort),306+ Context.add(Sealed, sealed)307+ );308+ })309+);310+311+/** One area's bits in a held-back job: one check fails in each failing area. */312+const 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;318+319+ return {320+ area,321+ passed: failing.has(area) ? total - 1 : total,322+ suite: job.suite,323+ total,324+ };325+ });326+327+/**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+ */331+const sealedChecker = Layer.effect(332+ CheckRunner,333+ Effect.gen(function* () {334+ const inner = yield* CheckRunner;335+ const sealed = yield* Sealed;336+337+ 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]);343+344+ if (yield* Ref.get(sealed.blocked)) {345+ return yield* new VerifierBlocked({});346+ }347+348+ const failing = yield* Ref.get(sealed.failing);349+350+ return {351+ durationMs: 7,352+ evidence: [],353+ heldBack: bitsOf(heldBackJob, failing),354+ lanes: [],355+ } satisfies CheckRun;356+ }),357+ });358+ })359+);360+361+const mainRef = RefName.make("refs/heads/main");362+363+/** The layer's repo, holding the suite on `main`, in a private host of its own. */364+const layerRepos = Layer.effect(365+ LayerRepos,366+ Effect.gen(function* () {367+ const host = yield* RepoHost;368+ const client = yield* gitClient(memoryFs());369+370+ yield* host.create(layerRepo).pipe(Effect.orDie);371+372+ const commit = yield* client.commit(373+ "Seal the suite",374+ sealedFiles.map(({ content, path }) => [path, content] as const),375+ []376+ );377+378+ yield* host379+ .push(layerRepo, client.source, [380+ { from: Option.none(), ref: mainRef, to: commit },381+ ])382+ .pipe(Effect.orDie);383+384+ return LayerRepos.of(host);385+ })386+).pipe(Layer.provide(Layer.fresh(RepoHostMemory)));387+388+/**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+ */393+export 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+ */12+import { describe, expect, it } from "@effect/vitest";13+import { ObjectId, RepoHost, RepoNotFound } from "@repo/artifacts/repo-host";14+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";15+import { CheckAt, CheckRunner, shaOf } from "@repo/checks/check-runner";16+import type { CheckJob } from "@repo/checks/check-runner";17+import { CheckExit } from "@repo/checks/check-runner/wire";18+import type { CheckWire } from "@repo/checks/check-runner/wire";19+import { EvidenceKept } from "@repo/checks/evidence-store/memory";20+import { parseTrailers } from "@repo/git/trailers";21+import { AnswerView, Verdict } from "@repo/protocol/domain/answer";22+import type { HeldBackResult } from "@repo/protocol/domain/answer";23+import { Command } from "@repo/protocol/domain/common";24+import { ProjectEvent } from "@repo/protocol/domain/event";25+import { Outcome } from "@repo/protocol/domain/outcome";26+import {27+ EnvKey,28+ LandedSha,29+ LaneName,30+ RepoName,31+ RepoPath,32+ RequestId,33+ SuiteRoot,34+ TreeSha,35+} from "@repo/protocol/ids";36+import type { CommitSha } from "@repo/protocol/ids";37+import {38+ AttemptsExhausted,39+ ChecksFailed,40+ HeldBackFailed,41+ LayerContentInPublicTree,42+ PrivatePathInPublicTree,43+ VerifierBlocked,44+} from "@repo/protocol/refusal";45+import type { Files } from "@repo/testkit/git-client";46+import { untouchable } from "@repo/testkit/untouchable";47+import {48+ Array,49+ Effect,50+ Exit,51+ Layer,52+ Option,53+ Redacted,54+ Ref,55+ Schema,56+ Struct,57+} from "effect";58+59+import { CheckRunnerSandbox } from "../../src/adapters/check-runner-sandbox.ts";60+import type { SandboxBinding } from "../../src/adapters/check-runner-sandbox.ts";61+import { decodeEnv } from "../../src/platform.ts";62+import { workerPorts } from "../../src/ports.ts";63+import { LandingGuards } from "../../src/workflows/answer/guards.ts";64+import { withheld } from "../../src/workflows/answer/lanes.ts";65+import { runAnswer } from "../../src/workflows/answer/program.ts";66+import { notesRef } from "../../src/workflows/notes.ts";67+import { memoSteps } from "../../src/workflows/step.ts";68+import type { StepRunner } from "../../src/workflows/step.ts";69+import { fakeEnv } from "../fake-env.ts";70+import {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";96+import type { Admitted } from "../workflows/answer.fixtures.ts";97+import {98+ exportArea,99+ heldBackJob,100+ maintainers,101+ parserArea,102+ resetsAt,103+ sealedFiles,104+ Sealed,105+ sealedWorld,106+ suiteRoot,107+} from "./held-back.fixtures.ts";108+109+/** The program run for `answer` over a fresh step record. */110+const run = (answer: Admitted) =>111+ Effect.flatMap(memoSteps(), (steps) =>112+ runAnswer({ project, requestId: answer.requestId }).pipe(113+ Effect.provide(steps)114+ )115+ );116+117+/** Every public lane on `at` passes: the ask's check and every project lane. */118+const allGreen = (at: CheckAt) =>119+ Effect.andThen(120+ scriptProjectLanes(at, { result: "passed" }),121+ Checker.use((script) => script.script(at, askLane, [{ result: "passed" }]))122+ );123+124+/** The held-back checks of `areas` fail from now on, one check in each. */125+const failing = (...areas: readonly (typeof exportArea)[]) =>126+ Sealed.use(({ failing: next }) => Ref.set(next, new Set(areas)));127+128+const decodeVerdict = Schema.decodeUnknownEffect(129+ Schema.fromJsonString(Verdict)130+);131+132+/** The verdict note on `commit` in `at`, read as plain git finds it. */133+const 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);137+138+ if (tip === undefined) {139+ return Option.none();140+ }141+142+ const notes = Option.getOrThrow(143+ yield* host.readCommit(at, tip).pipe(Effect.orDie)144+ );145+146+ const entries = Option.getOrThrow(147+ yield* host.readTree(at, notes.tree).pipe(Effect.orDie)148+ );149+150+ const entry = entries.find(({ name }) => name === commit);151+152+ if (entry === undefined) {153+ return Option.none();154+ }155+156+ const blob = Option.getOrThrow(157+ yield* host.readBlob(at, ObjectId.make(entry.sha)).pipe(Effect.orDie)158+ );159+160+ return Option.some(161+ yield* decodeVerdict(new TextDecoder().decode(blob)).pipe(Effect.orDie)162+ );163+ });164+165+/** The verdict note on `head` in bob's fork. */166+const noteOn = (head: CommitSha) => noteIn(bobFork, head);167+168+/**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+ */172+const 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+ );177+178+ 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+ );187+188+ const receipt = yield* answer.api.submitAnswer(bob, {189+ ask: parseIso,190+ base: answer.opened,191+ head,192+ requestId: RequestId.make(`push-${head}`),193+ });194+195+ yield* allGreen(merged);196+197+ return { ...answer, head, merged, requestId: receipt.requestId };198+ }).pipe(Effect.orDie);199+200+describe("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();206+207+ yield* allGreen(answer.merged);208+ yield* failing(exportArea);209+210+ const outcome = yield* run(answer);211+ const { answers } = yield* answer.api.status(bob);212+213+ const refused = Outcome.cases.Refused.make({214+ refusals: [215+ new HeldBackFailed({ area: exportArea, suite: suiteRoot }),216+ ],217+ });218+219+ 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+ );233+234+ 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();239+240+ yield* allGreen(answer.merged);241+ yield* failing(exportArea);242+243+ const steps = yield* memoSteps();244+245+ const over = (record: Layer.Layer<StepRunner>) =>246+ runAnswer({ project, requestId: answer.requestId }).pipe(247+ Effect.provide(record)248+ );249+250+ const twice = Layer.unwrap(251+ Effect.map(memoSteps(), (memo) => logged(memo, { twice: true }))252+ );253+254+ const outcomes = [255+ yield* over(twice),256+ yield* over(steps),257+ yield* over(steps),258+ ];259+260+ const second = yield* answerAgain(261+ answer,262+ changed(263+ fixed,264+ parsePath,265+ "export const parse = (s) => ({ year: 2026, s });\n"266+ )267+ );268+269+ 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+ );281+282+ 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();287+288+ yield* allGreen(answer.merged);289+290+ const moved = yield* mainMoved(291+ answer.opened,292+ changed(293+ openedFiles,294+ lexPath,295+ "export const lex = (s) => s.split(/ +/);\n"296+ )297+ );298+299+ 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+ );308+309+ yield* allGreen(remerged);310+311+ 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);315+316+ 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+ );325+326+ 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+ );337+338+ it.effect(339+ "waits, counting nothing, when the Checker cannot run the suite",340+ () =>341+ Effect.gen(function* () {342+ const answer = yield* admitted();343+344+ yield* allGreen(answer.merged);345+ yield* Sealed.use(({ blocked }) => Ref.set(blocked, true));346+347+ const outcome = yield* run(answer);348+349+ 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+ );356+357+ it.effect(358+ "spends the area on the claim's third failed run: AttemptsExhausted",359+ () =>360+ Effect.gen(function* () {361+ const first = yield* admitted();362+363+ yield* allGreen(first.merged);364+ yield* failing(exportArea);365+366+ const outcomes = [yield* run(first)];367+368+ const second = yield* answerAgain(369+ first,370+ changed(371+ fixed,372+ parsePath,373+ "export const parse = (s) => ({ year: 2026, s });\n"374+ )375+ );376+377+ outcomes.push(yield* run(second));378+379+ const third = yield* answerAgain(380+ second,381+ changed(382+ fixed,383+ parsePath,384+ "export const parse = (s) => ({ year: 2026, t: s });\n"385+ )386+ );387+388+ outcomes.push(yield* run(third));389+390+ 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+ );409+410+ 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();415+416+ yield* allGreen(answer.merged);417+418+ const outcome = yield* run(answer);419+ const tip = yield* mainTip;420+ const host = yield* RepoHost;421+422+ const commit = Option.getOrThrow(423+ yield* host.readCommit(repo, tip).pipe(Effect.orDie)424+ );425+426+ 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}`;429+430+ 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+});459+460+/** A file in the ask's territory holding a sealed check's bytes, blob for blob. */461+const copied = RepoPath.make("packages/parser/src/copied.ts");462+463+const copiedContent = sealedFiles[0]?.content ?? "";464+465+/** Every Checker job on the merged tree `at`. */466+const jobsOn = (at: CheckAt) =>467+ Checker.use(({ jobs }) =>468+ Effect.map(jobs, (all) => all.filter((job) => shaOf(job.at) === shaOf(at)))469+ );470+471+const encoder = new TextEncoder();472+473+/** The git id of a blob holding `text`. */474+const 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+ );489+490+/**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+ */494+const 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+ );509+510+describe("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);516+517+ const plugged = yield* Effect.scoped(518+ Effect.flatMap(Layer.build(workerPorts(config)), (ports) =>519+ Effect.provideContext(Effect.service(LandingGuards), ports)520+ )521+ );522+523+ expect(Option.isSome(plugged)).toBeTruthy();524+ expect(Option.isSome(yield* Effect.service(LandingGuards))).toBeFalsy();525+ })526+ );527+528+ 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";534+535+ 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+ );542+543+ 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+ });551+552+ 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+ );560+561+ 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");566+567+ const answer = yield* admitted(568+ changed(fixed, taken, "export const sealed = 1;\n")569+ );570+571+ yield* allGreen(answer.merged);572+ yield* Sealed.use(({ layerPaths }) =>573+ Ref.update(layerPaths, (paths) => new Set([...paths, taken]))574+ );575+576+ 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+ );587+588+ 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();593+594+ yield* allGreen(answer.merged);595+596+ expect(yield* run(answer)).toStrictEqual(597+ Outcome.cases.AwaitingFinish.make({})598+ );599+600+ const finished = yield* Pusher.use((each) =>601+ each.push(602+ bobFork,603+ Option.some(answer.head),604+ changed(fixed, copied, copiedContent)605+ )606+ );607+608+ 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);616+617+ 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+ );628+629+ 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));634+635+ yield* allGreen(answer.merged);636+637+ const outcome = yield* run(answer);638+639+ expect(outcome).toStrictEqual(640+ Outcome.cases.Landed.make({ sha: yield* mainTip })641+ );642+ }).pipe(Effect.provide(sealedWorld(policy)))643+ );644+645+ 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();650+651+ yield* allGreen(answer.merged);652+653+ const host = yield* forkReads(() =>654+ Effect.fail(new RepoNotFound({ name: bobFork }))655+ );656+657+ const outcome = yield* run(answer).pipe(658+ Effect.provideService(RepoHost, host)659+ );660+661+ 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+ );668+669+ 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";674+675+ const answer = yield* admitted(676+ changed(fixed, "packages/parser/src/tz", content)677+ );678+679+ yield* allGreen(answer.merged);680+681+ const pointer = yield* blobIdOf(content);682+683+ const host = yield* forkReads((id, given) =>684+ id === pointer ? Effect.succeedNone : given685+ );686+687+ const outcome = yield* run(answer).pipe(688+ Effect.provideService(RepoHost, host)689+ );690+691+ expect(outcome).toStrictEqual(692+ Outcome.cases.Landed.make({ sha: yield* mainTip })693+ );694+ }).pipe(Effect.provide(sealedWorld(policy)))695+ );696+});697+698+/** datekit's `SENTRY_AUTH_TOKEN`, as a decider stores it. */699+const sentry = EnvKey.make("SENTRY_AUTH_TOKEN");700+701+const token = "sntrys_0a1b2c3d4e5f6a7b8c9d";702+703+/** alice stores datekit's Sentry token: a write-only value. */704+const stored = (answer: Admitted) =>705+ answer.api706+ .setEnv(alice, { key: sentry, value: Redacted.make(token) })707+ .pipe(Effect.orDie);708+709+/**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+ */713+const 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);719+720+ 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);735+736+describe("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+ );748+749+ yield* stored(answer);750+ yield* allGreen(answer.merged);751+752+ const outcome = yield* run(answer);753+ const read = yield* answererReads(answer);754+755+ // 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+ );766+767+ 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");773+774+ 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+ );791+792+ const outcome = yield* run(answer);793+ const puts = yield* EvidenceKept.use((kept) => kept.puts);794+ const read = yield* answererReads(answer);795+796+ 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+ );812+813+ 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();818+819+ yield* stored(answer);820+ yield* allGreen(answer.merged);821+822+ const outcome = yield* run(answer);823+ const tip = yield* mainTip;824+825+ 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+});847+848+/** A fork the adapter clones from, in a store of its own. */849+const sandboxFork = RepoName.make("datekit--parse-iso--bob");850+851+/** A held-back job, as the held-back step sends it: the suite alone. */852+const 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+};862+863+/** The bits a sandbox that ran `job`'s suite reports when every check passed. */864+const allPassed: readonly HeldBackResult[] = [865+ { area: exportArea, passed: 2, suite: suiteRoot, total: 2 },866+ { area: parserArea, passed: 1, suite: suiteRoot, total: 1 },867+];868+869+/**870+ * `CheckRunnerSandbox` over a sandbox that answers every job with871+ * `heldBack` as its area bits, and keeps each wire it was sent, encoded.872+ */873+const overSandbox = (heldBack: readonly HeldBackResult[]) =>874+ Effect.gen(function* () {875+ const sent: (typeof CheckWire.Encoded)[] = [];876+877+ const exit = yield* Schema.encodeEffect(CheckExit)(878+ Exit.succeed({ durationMs: 9, evidence: [], heldBack, lanes: [] })879+ ).pipe(Effect.orDie);880+881+ const sandbox = untouchable<SandboxBinding>("SANDBOX", {882+ check: (wire) => {883+ sent.push(wire);884+885+ return Promise.resolve(exit);886+ },887+ });888+889+ yield* RepoHost.use((host) => host.create(sandboxFork)).pipe(Effect.orDie);890+891+ const runner = yield* Effect.service(CheckRunner).pipe(892+ Effect.provide(CheckRunnerSandbox(sandbox))893+ );894+895+ return { runner, sent };896+ });897+898+describe("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));906+907+ 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+ );928+929+ 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);934+935+ const ran = yield* Effect.exit(936+ runner.run({937+ ...sealedJob,938+ heldBack: {939+ ...heldBackJob,940+ areas: [exportArea, parserArea, exportArea],941+ },942+ })943+ );944+945+ expect(Exit.map(ran, ({ heldBack }) => heldBack)).toStrictEqual(946+ Exit.succeed(allPassed)947+ );948+ }).pipe(Effect.provide(Layer.fresh(RepoHostMemory)))949+ );950+951+ 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)}`);956+957+ 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+ ];984+985+ const outcomes = yield* Effect.forEach(wrong, ({ bits, job }) =>986+ Effect.gen(function* () {987+ const { runner } = yield* overSandbox(bits);988+989+ return yield* Effect.exit(runner.run(job));990+ }).pipe(Effect.provide(Layer.fresh(RepoHostMemory)))991+ );992+993+ expect(outcomes).toStrictEqual(994+ wrong.map(() => Exit.fail(new VerifierBlocked({})))995+ );996+ })997+ );998+});