Skip to content
Myr

Merge observability into main

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

authored by oscabriel · committed by oscabriel · parents caedd21, 987d77e · Browse files · 89 files+2829 added−158 removed
This commit

State

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

Diff stats

89 files+2829 added−158 removed

  • tests:+1482 added−14 removed
  • other:+1347 added−144 removed

89 files+2829 added−158 removed

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

modified:apps/cli/test/local/env-set-live.test.ts+1 added-1 removed
716 unmodified lines
717 ),718 }).toStrictEqual({719 event: true,720 logged: [721 `["a write-only value was set"] {"by":"ines-v","key":"${token}"}`,721 `["a write-only value was set"] {"project":"${project}","by":"ines-v","key":"${token}"}`,722 ],723 printed: true,724 replies: 1,725 rows: [
112 unmodified lines
modified:apps/platform/src/adapters/custody.ts+32 added-7 removed
9 unmodified lines
10import type { Person } from "@repo/protocol/principal";11import { ClaimLapsed, DirectPush, NotClaimed } from "@repo/protocol/refusal";12import type { Refusal } from "@repo/protocol/refusal";13import { receiptLine } from "@repo/protocol/render";14import { annotateInvocation, refusedWith } from "@repo/telemetry/spans";15import type { InvocationIds } from "@repo/telemetry/spans";16import { Array, Effect, Option, Result } from "effect";1718import type { LayerTarget } from "../layer-gate.ts";19import { RepoKind } from "../repo-names.ts";
141 unmodified lines
161 if (Option.isNone(claim)) {162 return [NotClaimed.of(ask)];163 }164165 const requestId = pushRequestId(person.handle, head);166167 yield* annotateInvocation({ requestId });168169 const submitted = yield* Effect.result(164 api.submitAnswer(person, {165 ask,166 base: claim.value.base,167 head,168 requestId: pushRequestId(person.handle, head),169 })170 api.submitAnswer(person, { ask, base: claim.value.base, head, requestId })171 );172173 if (Result.isFailure(submitted)) {174 return [submitted.failure];
64 unmodified lines
239 pusher: pusher.handle,240 target: kind._tag,241});242243// What Issues shows beside a push's failure: the project and ask it reached,244// the tip it carried to main and the tags it was refused with.245const targetIds = (kind: RepoKind): InvocationIds =>246 RepoKind.$match(kind, {247 Canonical: ({ project }) => ({ project }),248 ClaimFork: ({ ask, project }) => ({ ask, project }),249 Unknown: () => ({}),250 WorkingFork: ({ project }) => ({ project }),251 });252253const judged =254 (commands: readonly Command[]) => (refusals: readonly Refusal[]) =>255 annotateInvocation({256 ...Option.match(mainTip(commands), {257 onNone: () => ({}),258 onSome: ({ head }) => ({ sha: head }),259 }),260 ...refusedWith(refusals),261 });262263// `admit` stays synchronous: the gateway's body locks the moment the fiber yields.264const annotated = (custody: Custody["Service"], annotations: PushAnnotations) =>265 Custody.of({266 admit: (repo, commands) =>246 custody.admit(repo, commands).pipe(Effect.annotateLogs(annotations)),267 custody268 .admit(repo, commands)269 .pipe(Effect.tap(judged(commands)), Effect.annotateLogs(annotations)),270 review: (repo, commands) =>271 custody272 .review(repo, commands)273 .pipe(274 Effect.tap(judged(commands)),275 Effect.annotateLogs(annotations),276 Effect.withSpan("custody.review", { attributes: annotations })277 ),278 });
18 unmodified lines
297298 const projects = yield* Projects;299 const annotations = annotationsOf(pusher, kind, audit);300301 yield* annotateInvocation(targetIds(kind));302 yield* Effect.logInfo("a push reached custody").pipe(303 Effect.annotateLogs(annotations)304 );305
54 unmodified lines
modified:apps/platform/src/adapters/sandbox-credentials.ts+4 added-1 removed
4 unmodified lines
5 TokenScope,6} from "@repo/artifacts/repo-host";7import type { Remote } from "@repo/checks/check-runner/wire";8import { VerifierBlocked } from "@repo/protocol/refusal";9import { unquoted } from "@repo/telemetry/defects";10import {11 Cause,12 Data,13 Duration,
101 unmodified lines
115 readonly remotes: readonly Remote[];116 readonly send: (encoded: WI) => Promise<X>;117}118119// A job's defect is logged by its name and frames alone: a Checker's may120// quote a sealed file's path.121const settle = <A, E>(122 method: SandboxMethod,123 remotes: readonly Remote[],124 exit: Exit.Exit<A, E>
2 unmodified lines
127 ? Effect.succeed(exit.value)128 : Option.match(Cause.findErrorOption(exit.cause), {129 onNone: () =>130 blocked(method, {128 detail: scrub(Cause.pretty(exit.cause), remotes),131 detail: scrub(Cause.pretty(unquoted(exit.cause)), remotes),132 failure: "defect",133 }),134 onSome: (refusal): Effect.Effect<never, E> => Effect.fail(refusal),135 });
30 unmodified lines
modified:apps/platform/src/auth/provider.ts+5 added-3 removed
49 unmodified lines
50 context: ExecutionContext51) => Promise<Response>;5253// Each origin's server is made on its first request and kept: a Worker is reached only on its own hostnames.54export const oauthProvider = <E>(54export const oauthProvider = <E, TE = never>(55 services: Layer.Layer<GoogleServices, E>,56 platformFetch: PlatformFetch56 platformFetch: PlatformFetch,57 telemetry?: Layer.Layer<never, TE>58) => {59 const { dispose, handler } = buildHandler(59 Layer.mergeAll(signInRoutes, googleRoutes).pipe(Layer.provide(services))60 Layer.mergeAll(signInRoutes, googleRoutes).pipe(Layer.provide(services)),61 telemetry62 );6364 const servers = new Map<string, OAuthAuthorizationServer<OAuthEnv>>();65
93 unmodified lines
modified:apps/platform/src/workflows/answer/program.ts+34 added-2 removed
19 unmodified lines
20 outcomeOf,21} from "@repo/project/landing";22import { Projects } from "@repo/project/projects";23import { LaneOutcome, Verdict } from "@repo/protocol/domain/answer";24import type { Outcome } from "@repo/protocol/domain/outcome";24import type { Outcome, StageName } from "@repo/protocol/domain/outcome";25import { CommitSha } from "@repo/protocol/ids";26import type {27 EnvKey,28 LaneName,29 ProjectName,30 RequestId,31} from "@repo/protocol/ids";32import { VerifierBlocked } from "@repo/protocol/refusal";33import type { Refusal } from "@repo/protocol/refusal";34import {35 Array,36 Cause,37 Data,
238 unmodified lines
276 readonly given: Option.Option<Reported>;277 readonly judged: Option.Option<Judged>;278}279280/** The checks stage runs only when the cheap one refused nothing, and the held-back one only when neither did. */281const refusingStage = (input: {282 readonly checked: boolean;283 readonly held: readonly Refusal[];284 readonly last: readonly Refusal[];285}): Option.Option<StageName> => {286 if (input.held.length > 0) {287 return Option.some("heldBack");288 }289290 if (input.last.length > 0) {291 return Option.some(input.checked ? "checks" : "cheap");292 }293294 return Option.none();295};296297const ranOnly = (given: Option.Option<Reported>): Ran => ({298 given,299 judged: Option.none(),300});
32 unmodified lines
333 finish: run.finish,334 refusals: [...run.refusals, ...quarantined],335 tree: call.tree,336 }),337 // The landing guards hold the shape of the tree, as stage 1 does a push's.319 { heldBack: [], lanes: [] }338 { heldBack: [], lanes: [], stage: "shape" }339 )340 )341 );342
52 unmodified lines
395 const held = HeldBackRun.guards.Judged(sealed)396 ? Option.some(sealed)397 : Option.none();398399 const refusedAt = refusingStage({400 checked: judged !== undefined,401 held: Option.match(held, {402 onNone: () => [],403 onSome: ({ refusals }) => refusals,404 }),405 last: last.refusals,406 });407408 const given = StageRun.match(last.ran, {409 Blocked: ({ attempt: at }) =>410 reported(LandingCommand.Blocked({ attempt: at })),411 Moved: () => Option.none(),
25 unmodified lines
437 ...Option.match(counts, {438 onNone: () => ({}),439 onSome: (ratchets) => ({ ratchets }),440 }),441 ...Option.match(refusedAt, {442 onNone: () => ({}),443 onSome: (refusing) => ({ stage: refusing }),444 }),445 }446 ),447 });448
211 unmodified lines
modified:apps/platform/src/workflows/on-push/facts.ts+1 added-1 removed
13 unmodified lines
14import type { OnPushEvent } from "./event.ts";1516const platform = Person.make({ handle: platformHandle });1718const projectOf = (kind: RepoKind): Option.Option<ProjectName> =>18export const projectOf = (kind: RepoKind): Option.Option<ProjectName> =>19 RepoKind.$match(kind, {20 Canonical: ({ project }) => Option.some(project),21 ClaimFork: ({ project }) => Option.some(project),22 Unknown: () => Option.none(),
76 unmodified lines
modified:apps/platform/src/workflows/answer.ts+43 added-11 removed
2 unmodified lines
3import type { RepoHost } from "@repo/artifacts/repo-host";4import type { Drafter } from "@repo/drafting/drafter";5import type { Projects } from "@repo/project/projects";6import { Outcome } from "@repo/protocol/domain/outcome";7import { annotateInvocation, refusedWith } from "@repo/telemetry/spans";8import type { InvocationIds } from "@repo/telemetry/spans";9import { WorkflowEntrypoint } from "cloudflare:workers";10import type { WorkflowEvent } from "cloudflare:workers";11import { Effect, Layer, Schema } from "effect";1213import type { WorkflowParams } from "../answer-runs.ts";14import { AdmissionParams, AnswerParams, DraftParams } from "../answer-runs.ts";15import { decodeEnv } from "../platform.ts";14import { draftPorts, workerPorts } from "../ports.ts";16import { draftPorts, telemetryOf, workerPorts } from "../ports.ts";17import { admissionSteps } from "./admission-steps.ts";18import { runAnswer } from "./answer/program.ts";19import type { AnswerPorts } from "./answer/program.ts";20import { draftSteps, timedSteps } from "./draft-steps.ts";21import type { EngineSteps } from "./draft-steps.ts";22import { instance, invocation } from "./instance.ts";23import { workflowSteps } from "./step.ts";24import type { StepRunner, WorkflowSteps } from "./step.ts";2526export const OutcomeJson = Schema.toCodecJson(Outcome);2728export type OutcomeEncoded = typeof OutcomeJson.Encoded;2930// What Issues shows beside a run that ended: the SHA it landed, or what refused it.31const outcomeIds = (outcome: Outcome): InvocationIds =>32 Outcome.match(outcome, {33 AwaitingDecision: () => ({}),34 AwaitingFinish: () => ({}),35 Checking: () => ({}),36 Landed: ({ sha }) => ({ sha }),37 Refused: ({ refusals }) => refusedWith(refusals),38 WaitingOnParent: () => ({}),39 });4041export const runWorkflow = <E>(42 ports: Layer.Layer<Exclude<AnswerPorts, StepRunner>, E>,43 payload: typeof AnswerParams.Encoded,44 steps: WorkflowSteps45): Promise<OutcomeEncoded> =>46 Effect.runPromise(47 Effect.gen(function* () {48 const params = yield* Schema.decodeEffect(AnswerParams)(payload);35 const outcome = yield* runAnswer(params);4937 return yield* Schema.encodeEffect(OutcomeJson)(outcome);50 return yield* runAnswer(params).pipe(51 Effect.tap((outcome) => annotateInvocation(outcomeIds(outcome))),52 Effect.flatMap(Schema.encodeEffect(OutcomeJson)),53 invocation({ project: params.project, requestId: params.requestId })54 );55 }).pipe(56 instance("Answer.run"),57 Effect.provide(Layer.merge(ports, workflowSteps(steps))),58 Effect.orDie59 )60 );
4 unmodified lines
65 steps: WorkflowSteps66): Promise<null> =>67 Effect.runPromise(68 Effect.gen(function* () {51 yield* admissionSteps(52 yield* Schema.decodeEffect(AdmissionParams)(payload)53 );69 const params = yield* Schema.decodeEffect(AdmissionParams)(payload);7055 return null;71 return yield* admissionSteps(params).pipe(72 Effect.as(null),73 invocation({ project: params.project, sha: params.head })74 );75 }).pipe(76 instance("Admission.run"),77 Effect.provide(Layer.merge(ports, workflowSteps(steps))),78 Effect.orDie79 )80 );
4 unmodified lines
85 steps: EngineSteps86): Promise<null> =>87 Effect.runPromise(88 Effect.gen(function* () {69 yield* draftSteps(yield* Schema.decodeEffect(DraftParams)(payload));89 const params = yield* Schema.decodeEffect(DraftParams)(payload);9071 return null;91 return yield* draftSteps(params).pipe(92 Effect.as(null),93 invocation({ project: params.project })94 );95 }).pipe(96 instance("Draft.run"),97 Effect.provide(Layer.merge(ports, workflowSteps(timedSteps(steps)))),98 Effect.orDie99 )100 );
16 unmodified lines
117 if (drafts(payload)) {118 return runDraftWorkflow(119 Layer.unwrap(120 Effect.map(config, (decoded) =>97 Layer.merge(workerPorts(decoded), draftPorts(decoded))121 Layer.mergeAll(122 workerPorts(decoded),123 draftPorts(decoded),124 telemetryOf(decoded)125 )126 )127 ),128 payload,129 step130 );131 }132105 const ports = Layer.unwrap(Effect.map(config, workerPorts));133 const ports = Layer.unwrap(134 Effect.map(config, (decoded) =>135 Layer.merge(workerPorts(decoded), telemetryOf(decoded))136 )137 );138139 return admits(payload)140 ? runAdmission(ports, payload, step)141 : runWorkflow(ports, payload, step);
2 unmodified lines
added:apps/platform/src/workflows/instance.ts+19 added
1// What every Workflow instance runs under. The engine logs nothing of a run2// that rejects and traces no Workflow, so the instance's own span is the3// trace's only view into it, and its defects are reported here, once.4import { reportDefects } from "@repo/telemetry/defects";5import { withInvocation } from "@repo/telemetry/spans";6import type { InvocationIds } from "@repo/telemetry/spans";7import { Effect } from "effect";89/** The whole instance, its params' decoding included. */10export const instance =11 (name: string) =>12 <A, E, R>(program: Effect.Effect<A, E, R>): Effect.Effect<A, never, R> =>13 program.pipe(Effect.orDie, reportDefects, Effect.withSpan(name));1415/** The run its params name: a defect's report carries the ids, as each line does. */16export const invocation =17 (ids: InvocationIds) =>18 <A, E, R>(program: Effect.Effect<A, E, R>): Effect.Effect<A, never, R> =>19 program.pipe(Effect.orDie, reportDefects, withInvocation(ids));
modified:apps/platform/src/workflows/on-push.ts+25 added-7 removed
1// The class name is frozen.2import type { PushReport } from "@repo/project/project";3import type { Projects } from "@repo/project/projects";4import { Anonymous, Person } from "@repo/protocol/principal";5import { annotateInvocation, refusedWith } from "@repo/telemetry/spans";6import { WorkflowEntrypoint } from "cloudflare:workers";7import type { WorkflowEvent, WorkflowStep } from "cloudflare:workers";8import { Data, Effect, Layer, Option, Schema } from "effect";910import { decodeEnv } from "../platform.ts";10import { workerPorts } from "../ports.ts";11import { RepoKind } from "../repo-names.ts";11import { telemetryOf, workerPorts } from "../ports.ts";12import { RepoKind, repoKind } from "../repo-names.ts";13import { instance, invocation } from "./instance.ts";14import { classifyPush, PushVerdict } from "./on-push/classify.ts";15import { isZero, OnPushEvent } from "./on-push/event.ts";14import { factsOf, projectFor } from "./on-push/facts.ts";16import { factsOf, projectFor, projectOf } from "./on-push/facts.ts";17import { StepRunner, workflowSteps } from "./step.ts";18import type { StepRetry, WorkflowSteps } from "./step.ts";1920const Recorded = Schema.Array(Schema.String);
29 unmodified lines
50 : Anonymous.make({});5152 const refusals = yield* api.recordPush(reportOf(event, pusher));5354 yield* annotateInvocation(refusedWith(refusals));5556 return refusals.map(({ _tag }) => _tag);57 });5859class LooksStray extends Data.TaggedError("LooksStray") {}
50 unmodified lines
110 Effect.gen(function* () {111 const event = yield* Schema.decodeEffect(OnPushEvent)(params);112 const config = yield* decodeEnv(env);113110 const verdict = yield* runOnPush(event).pipe(111 Effect.provide(Layer.merge(workerPorts(config), workflowSteps(steps)))112 );114 const ids = Option.match(projectOf(repoKind(event.source.repoName)), {115 onNone: () => ({ sha: event.payload.after }),116 onSome: (project) => ({ project, sha: event.payload.after }),117 });118114 return yield* Effect.orDie(Schema.encodeEffect(PushVerdict)(verdict));119 // A payload or an env that does not decode fails the instance as its own120 // typed error, before the run starts; only the run's defects are reported.121 return yield* runOnPush(event).pipe(122 Effect.flatMap(Schema.encodeEffect(PushVerdict)),123 invocation(ids),124 instance("OnPush.run"),125 Effect.provide(126 Layer.mergeAll(127 workerPorts(config),128 telemetryOf(config),129 workflowSteps(steps)130 )131 )132 );133 });134135export class OnPush extends WorkflowEntrypoint<136 Env,
9 unmodified lines
modified:apps/platform/src/workflows/step.ts+31 added-7 removed
1import { Context, Effect, Layer, Option, Ref, Schema } from "effect";1import { Cause, Context, Effect, Layer, Option, Ref, Schema } from "effect";23export interface WorkflowStepRetries {4 readonly limit: number;5 readonly delay: number;
38 unmodified lines
44 limit: retry.limit,45 },46 };4748// A step's name carries its attempt and the SHA it ran on (`cheap#2`,49// `main:<sha>:<lane>`): the span is named by its kind alone, and carries the50// whole name as `step`.51const stepSpan = (name: string) =>52 Effect.withSpan(`Workflow.${name.split(/[:#]/u)[0] ?? name}`, {53 attributes: { step: name },54 });5556const durableStep =57 (steps: WorkflowSteps) =>58 <A, I, E, R>(59 name: string,
4 unmodified lines
64 Effect.gen(function* () {65 const json = Schema.toCodecJson(schema);66 const context = yield* Effect.context<R>();67 const failed = yield* Ref.make(Option.none<E>());68 // The engine hands back only what the body threw: a defect's cause, as69 // it died, keeps the mark that another side (a Project DO) reported it.70 const died = yield* Ref.make(Option.none<Cause.Cause<E>>());7172 // Spanned inside the engine's step, so a replay that reads a kept value opens none.73 const run = effect.pipe(74 Effect.tapError((failure) => Ref.set(failed, Option.some(failure))),75 Effect.tapCauseIf(Cause.hasDies, (cause) =>76 Ref.set(died, Option.some(cause))77 ),78 Effect.flatMap((value) =>79 Effect.orDie(Schema.encodeEffect(json)(value))65 )80 ),81 stepSpan(name)82 );8384 const recorded = yield* Effect.tryPromise(() =>85 steps.do(name, configOf(retry), () =>86 Effect.runPromiseWith(context)(run)87 )88 ).pipe(89 Effect.catch((error) =>74 Effect.flatMap(Ref.get(failed), (last) =>75 Option.match(last, {76 onNone: () => Effect.die(error),77 onSome: (failure) => Effect.fail(failure),78 })90 Effect.flatMap(91 Effect.all([Ref.get(failed), Ref.get(died)]),92 ([last, defect]) =>93 Option.match(last, {94 onNone: () =>95 Option.match(defect, {96 // What the engine threw (a replay's, or its own), so a97 // defect is reported by its own name.98 onNone: () => Effect.die(error.cause),99 onSome: Effect.failCause,100 }),101 onSome: (failure) => Effect.fail(failure),102 })103 )104 )105 );106
59 unmodified lines
modified:apps/platform/src/git.ts+7 added-1 removed
244 unmodified lines
245 auditOf(request.headers)246 )247 : refuseAll;248249 const response = yield* gateway(request).pipe(249 const served = gateway(request).pipe(250 Effect.provideService(Custody, custody)251 );252253 const response = yield* route.endpoint === "git-receive-pack"254 ? served.pipe(255 Effect.withSpan("Gateway.push", { attributes: { target: kind._tag } })256 )257 : served;258259 return yield* withNotices(response, yield* Ref.get(notices));260 });261262export const serveGit = (
10 unmodified lines
modified:apps/platform/src/platform.ts+1 added
61 unmodified lines
62 EMAIL: binding<Env["EMAIL"]>("Email Service's send_email"),63 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),64 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),65 LOADER: binding<Env["LOADER"]>("a Worker Loader"),66 METRICS: binding<Env["METRICS"]>("an Analytics Engine dataset"),67 OAUTH_KV: binding<Env["OAUTH_KV"]>("a KV namespace"),68 ON_PUSH: binding<Env["ON_PUSH"]>("the OnPush Workflow"),69 PROJECT: binding<Env["PROJECT"]>("the Project Durable Object"),70 PROPOSAL_LIMIT: binding<Env["PROPOSAL_LIMIT"]>("a rate limit"),
125 unmodified lines
modified:apps/platform/src/ports.ts+26 added-1 removed
15 unmodified lines
16import type { FrontPage } from "@repo/project/front-page";17import { FrontPageMemory } from "@repo/project/front-page/memory";18import type { Lander } from "@repo/project/lander";19import { LanderIsogit } from "@repo/project/lander/isogit";20import { MetricsBinding } from "@repo/project/metrics/binding";21import { FinishersFromChecks } from "@repo/project/project";22import type { Projection } from "@repo/project/projection";23import { ProjectDescriptionsD1 } from "@repo/project/projection-d1/descriptions";24import { FrontPageD1 } from "@repo/project/projection-d1/front-page";
2 unmodified lines
27import { ProjectionMemory } from "@repo/project/projection/memory";28import type { Projects } from "@repo/project/projects";29import type { RulesEvaluator } from "@repo/rules/rules-evaluator";30import { RulesEvaluatorWorker } from "@repo/rules/rules-evaluator/worker";31import { Telemetry } from "@repo/telemetry/telemetry";32import { tracing } from "cloudflare:workers";30import { Layer, Option } from "effect";33import { Layer, Option, Redacted } from "effect";3435import { CheckRunnerSandbox } from "./adapters/check-runner-sandbox.ts";36import { DoProjects } from "./adapters/do-projects.ts";37import { DraftRunsWorkflow } from "./adapters/draft-runs-workflow.ts";
70 unmodified lines
108 }),109 EvidenceStoreR2(config.EVIDENCE),110 CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy),111 CodeStoreR2(config.CODE_CACHE),112 MetricsBinding(config.METRICS),113 // Without this entry a draft proposal starts no run, and stays drafting.114 DraftRunsWorkflow(config.ANSWER)115 ).pipe(116 Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)),
2 unmodified lines
119120export const workerPorts = (config: PlatformConfig): Layer.Layer<WorkerPorts> =>121 plugIn(config, corePorts(config), Object.values(cartridges));122123// Every secret the env holds, a session table's tokens each on its own.124const secretsOf = (config: PlatformConfig): readonly Redacted.Redacted[] => [125 config.COOKIE_KEY,126 config.MASTER_KEY,127 config.OPERATOR_TOKEN,128 config.PASSWORD_PEPPER,129 ...Option.toArray(Option.fromUndefinedOr(config.GOOGLE_CLIENT_SECRET)),130 ...Option.match(Option.fromUndefinedOr(config.SESSION_TOKENS), {131 onNone: () => [],132 onSome: (table) =>133 Object.keys(Redacted.value(table)).map((token) => Redacted.make(token)),134 }),135];136137// The JSON logger, defect reporting and spans of every runtime the Worker138// starts: its routers, each Project DO and each Workflow instance. A defect139// is kept by its name and frames alone: the visibility cartridge runs here,140// and a defect's text may name a layer's repo or quote a sealed path.141export const telemetryOf = (config: PlatformConfig): Layer.Layer<never> =>142 Telemetry({ defects: "name", secrets: secretsOf(config), tracing });143144export const draftPorts = (config: PlatformConfig): Layer.Layer<Drafter> =>145 Layer.merge(146 DrafterWorkersAi(config.AI, config.DRAFT_MODEL),147 Layer.succeed(DraftModel, config.DRAFT_MODEL)
1 unmodified line
modified:apps/platform/src/project-calls.ts+9 added-3 removed
2 unmodified lines
3import type { ProjectApi } from "@repo/project/project";4import { ProjectName } from "@repo/protocol/ids";5import { Person, Principal } from "@repo/protocol/principal";6import { UnknownProject } from "@repo/protocol/refusal";7import { Effect, Record, Schema } from "effect";8import type { Exit } from "effect";7import { reportedElsewhere } from "@repo/telemetry/defects";8import { Effect, Exit, Record, Schema } from "effect";910export type ProjectMethod = keyof ProjectApi;1112export type ArgsOf<M extends ProjectMethod> = Parameters<ProjectApi[M]>;
146 unmodified lines
159 reply: ExitEncoded160): Effect.Effect<SuccessOf<M>, ErrorOf<M>> =>161 Schema.decodeEffect(ProjectCalls[method].exit)(reply).pipe(162 Effect.orDie,163 // The Project DO reported its defects, with their stacks, before it replied.163 Effect.flatten164 Effect.flatMap(165 Exit.match({166 onFailure: (cause) => Effect.failCause(reportedElsewhere(cause)),167 onSuccess: Effect.succeed,168 })169 )170 );
modified:apps/platform/src/project-do.ts+13 added-12 removed
9 unmodified lines
10import type { AlarmStorage } from "./adapters/alarms.ts";11import { AnswerRunsWorkflow } from "./adapters/answer-runs-workflow.ts";12import { decodeEnv } from "./platform.ts";13import type { InvalidEnv, PlatformConfig } from "./platform.ts";14import { workerPorts } from "./ports.ts";14import { telemetryOf, workerPorts } from "./ports.ts";15import type { CallRequest, ExitEncoded } from "./project-calls.ts";16import { projectShell } from "./project-shell.ts";17import type { ProjectShell } from "./project-shell.ts";18import { closeEnd, watchRequest, watchRoom } from "./watch.ts";
24 unmodified lines
43 }),44 ProjectSkillGenerator45 );4647// Every call and alarm runs with the Worker's telemetry, migrations included.48const shellOf = (ctx: DurableObjectState, env: Env) =>48 Layer.effect(49 Shell,50 Effect.gen(function* () {51 const config = yield* decodeEnv(env);5249 Layer.unwrap(50 Effect.map(decodeEnv(env), (config) => {51 const name = Option.flatMap(52 Schema.decodeUnknownOption(ProjectKey)(ctx.id.name),53 nameOfKey54 );5556 return Layer.effect(57 Shell,58 return yield* projectShell({59 name: Option.getOrUndefined(name),60 ports: doPorts({ config, name, storage: ctx.storage }),61 // The storage itself, not `storage.sql`: transactions run through it.62 sql: SqliteClient.layer({ storage: ctx.storage }),63 });58 projectShell({59 name: Option.getOrUndefined(name),60 ports: doPorts({ config, name, storage: ctx.storage }),61 // The storage itself, not `storage.sql`: transactions run through it.62 sql: SqliteClient.layer({ storage: ctx.storage }),63 })64 ).pipe(Layer.provideMerge(telemetryOf(config)));65 })66 );6768export class Project extends DurableObject<Env> {
59 unmodified lines
modified:apps/platform/src/project-shell.ts+21 added-10 removed
3 unmodified lines
4import { ProjectStore } from "@repo/project/project-store";5import { ProjectStoreSqlite } from "@repo/project/project-store/sqlite";6import type { ProjectName } from "@repo/protocol/ids";7import { UnknownProject } from "@repo/protocol/refusal";8import { withInvocation } from "@repo/telemetry/spans";9import {10 Context,11 Effect,12 ErrorReporter,13 Exit,14 Layer,15 Option,16 Ref,
122 unmodified lines
139140 const api = yield* service;141 const outcome = yield* Effect.exit(withEvidence(api[method](...args)));142143 // The reply carries a defect without its stack, and the caller reports it no144 // more: it is reported here, where the stack is.145 if (Exit.isFailure(outcome)) {146 yield* ErrorReporter.report(outcome.cause);147 }148149 return yield* Schema.encodeUnknownEffect(call.exit)(outcome).pipe(150 Effect.orDie151 );144 });152 }).pipe(Effect.withSpan(`Project.${method}`));153154 const named = withInvocation(155 input.name === undefined ? {} : { project: input.name }156 );157158 return {147 alarm: () =>148 Effect.gen(function* () {149 if (yield* isMade) {150 yield* Effect.flatMap(service, (api) =>151 withEvidence(api.onAlarm())152 );153 }154 }),159 alarm: Effect.fn("Project.alarm")(function* () {160 if (yield* isMade) {161 yield* Effect.flatMap(service, (api) =>162 withEvidence(api.onAlarm())163 ).pipe(named);164 }165 }),166 call: (request) =>167 Effect.flatMap(168 Schema.decodeEffect(CallRequest)(request).pipe(Effect.orDie),158 ({ method }) => serve(method, request)169 ({ method }) => named(serve(method, request))170 ),171 };172 });
modified:apps/platform/src/router-build.ts+20 added-3 removed
11 unmodified lines
12 Layer,13 Scheduler,14 Scope,15} from "effect";16import { constTrue } from "effect/Function";17import type { HttpServerRequest } from "effect/http";17import { HttpEffect, HttpRouter } from "effect/http";18import { HttpEffect, HttpMiddleware, HttpRouter } from "effect/http";1920export class RouterBuildAwaited extends Data.TaggedError("RouterBuildAwaited")<{21 readonly message: string;22}> {}2324// The runtime traces each request itself, with its URL; effect's own25// `http.server` span would be a second, carrying the query and the client's26// address.27const UntracedRequests = Layer.succeed(28 HttpMiddleware.TracerDisabledWhen,29 constTrue30);3132type RequestNeeds<A, R> = Exclude<33 | HttpRouter.Request.Only<"Requires", R>34 | HttpRouter.Request.Only<"GlobalRequires", R>,35 A | Scope.Scope | HttpServerRequest.HttpServerRequest
7 unmodified lines
43 | HttpRouter.Request<"Requires", unknown>44 | HttpRouter.Request<"GlobalRequires", unknown>45 | HttpRouter.Request<"Error", unknown>46 | HttpRouter.Request<"GlobalError", unknown>,47 TE = never,48>(39 appLayer: Layer.Layer<A, E, R>49 appLayer: Layer.Layer<A, E, R>,50 // Every request runs with it, and a request's defect is reported through it.51 telemetry: Layer.Layer<never, TE> = Layer.empty52) => {53 const scope = Scope.makeUnsafe();5455 // SAFETY: what `R` adds to `HttpRouter` are `HttpRouter.Request` markers,
7 unmodified lines
63 E64 >;65 /* oxlint-enable typescript/no-unsafe-type-assertion */6667 const observed = Layer.provideMerge(68 routed,69 Layer.merge(telemetry, UntracedRequests)70 );7172 // `runSyncExit`'s own scheduler would ride along in any context a layer captures73 // while built, so the build runs on the default one; `runSyncExit` still drains what74 // it schedules before it returns.75 const built = Effect.runSyncExit(59 Layer.buildWithScope(routed, scope).pipe(76 Layer.buildWithScope(observed, scope).pipe(77 Effect.provideService(78 Scheduler.Scheduler,79 Scheduler.Scheduler.defaultValue()80 )
40 unmodified lines
modified:apps/platform/src/surfaces.ts+6 added-2 removed
365 unmodified lines
366 }367 })368);369370export const serve = <E>(services: Layer.Layer<Services, E>) =>370export const serve = <E, TE = never>(371 services: Layer.Layer<Services, E>,372 telemetry?: Layer.Layer<never, TE>373) =>374 buildHandler(375 Layer.mergeAll(376 home,377 health,
4 unmodified lines
382 rpc,383 releaseRoutes,384 agentSkillRoutes,385 identifyCaller383 ).pipe(Layer.provide(services))386 ).pipe(Layer.provide(services)),387 telemetry388 );
modified:apps/platform/src/worker.ts+6 added-2 removed
1 unmodified line
2import { Effect, Layer } from "effect";34import { oauthProvider, signInServices } from "./auth/provider.ts";5import { decodeEnv, platformOf } from "./platform.ts";6import { telemetryOf } from "./ports.ts";7import { serve } from "./surfaces.ts";89export { Project } from "./project-do.ts";10
4 unmodified lines
15// Built at module load, touching no binding. Both routers' builds await nothing, so16// no request ever waits on a build another request started.17const config = Effect.runSyncExit(decodeEnv(env));1818const platform = serve(Layer.unwrap(Effect.map(config, platformOf)));19const telemetry = Layer.unwrap(Effect.map(config, telemetryOf));2021const platform = serve(Layer.unwrap(Effect.map(config, platformOf)), telemetry);2223const { handler } = oauthProvider(24 Layer.unwrap(Effect.map(config, signInServices)),22 (request) => platform.handler(request)25 (request) => platform.handler(request),26 telemetry27);2829export default handler;
modified:apps/platform/test/visibility/env-values.test.ts+2 added-2 removed
341 unmodified lines
342 })343 );344345 it.effect(346 "is in no response body, log line, row or event, while the set is logged by key and setter",346 "is in no response body, log line, row or event, while the set is logged by project, key and setter",347 () =>348 Effect.gen(function* () {349 const kept = keptFresh();350 const { stored } = yield* settingTheToken(kept);
3 unmodified lines
354 kept.logged.filter((line) =>355 line.includes('"a write-only value was set"')356 )357 ).toStrictEqual([358 `["a write-only value was set"] {"by":"ines-v","key":"SENTRY_AUTH_TOKEN"} `,358 `["a write-only value was set"] {"project":"ines-v/datekit","by":"ines-v","key":"SENTRY_AUTH_TOKEN"} `,359 ]);360 expect({361 bodies: kept.bodies.filter((body) => body.includes(value)),362 events: JSON.stringify(stored.events).includes(value),
11 unmodified lines
modified:apps/platform/test/visibility/held-back.test.ts+6 added-1 removed
61 unmodified lines
62 askLane,63 bob,64 bobFork,65 changed,66 checkedStages,67 Checker,68 finishRequired,69 fixed,70 LanderCalls,
136 unmodified lines
207 expect(208 Option.map(yield* noteOn(answer.head), ({ outcome: noted }) => noted)209 ).toStrictEqual(Option.some(refused));210 expect(answers.map((each) => each.outcome)).toStrictEqual([refused]);210 expect(yield* mainTip).toBe(answer.opened);211 expect({212 main: yield* mainTip,213 stages: yield* checkedStages,214 }).toStrictEqual({ main: answer.opened, stages: ["heldBack"] });215 }).pipe(Effect.provide(sealedWorld(policy)))216 );217218 it.effect(
337 unmodified lines
556 })557 );558 expect(yield* jobsOn(answer.merged)).toStrictEqual([]);559 expect(yield* mainTip).toBe(answer.opened);560 expect(yield* checkedStages).toStrictEqual(["shape"]);561 }).pipe(Effect.provide(sealedWorld(policy)))562 );563564 it.effect(
389 unmodified lines
modified:apps/platform/test/workflows/answer.fixtures.ts+10 added-1 removed
9 unmodified lines
10import { Lander } from "@repo/project/lander";11import type { MergeJob } from "@repo/project/lander";12import { LanderIsogit } from "@repo/project/lander/isogit";13import { LanderJob } from "@repo/project/lander/memory";14import type { LandingCommand } from "@repo/project/landing";14import { LandingCommand } from "@repo/project/landing";15import { FinishersFromChecks } from "@repo/project/project";16import type { ProjectApi } from "@repo/project/project";17import { ProjectionMemory } from "@repo/project/projection/memory";18import { Projects } from "@repo/project/projects";
301 unmodified lines
320 DoCalls,321 { readonly advances: Effect.Effect<readonly Advance[]> }322>()("test/DoCalls") {}323324/** The stage each `Checked` report the project heard names. */325export const checkedStages = DoCalls.use(({ advances }) =>326 Effect.map(advances, (all) =>327 all328 .filter(({ command }) => LandingCommand.$is("Checked")(command))329 .map(({ report }) => report?.stage)330 )331);332333const projects = Layer.effectContext(334 Effect.gen(function* () {335 const inner = yield* Projects;336 const advances = yield* Ref.make<readonly Advance[]>([]);
238 unmodified lines
modified:apps/platform/test/workflows/answer.test.ts+33 added
45 unmodified lines
46 askLane,47 bob,48 bobFork,49 changed,50 checkedStages,51 Checker,52 DoCalls,53 finishRequired,54 LanderCalls,
405 unmodified lines
460 expect(yield* namesOf(steps)).not.toContain("checks#1");461 }).pipe(Effect.provide(world))462 );463464 it.effect("3. names cheap, in its report, when a cheap lane refuses", () =>465 Effect.gen(function* () {466 const answer = yield* admitted();467468 yield* failsOnMerged(answer, lint, "lint: no-unused-vars", "passed");469 yield* run(answer, yield* freshSteps());470471 expect(yield* checkedStages).toStrictEqual(["cheap"]);472 }).pipe(Effect.provide(world))473 );474475 it.effect(476 "3. names checks, in its report, when a lane after the cheap ones refuses",477 () =>478 Effect.gen(function* () {479 const answer = yield* admitted();480481 yield* failsOnMerged(answer, unit, "unit: expected 2", "passed");482 yield* run(answer, yield* freshSteps());483484 expect(yield* checkedStages).toStrictEqual(["checks"]);485 }).pipe(Effect.provide(world))486 );487488 it.effect("3. names no stage, in its report, when nothing refused", () =>489 Effect.gen(function* () {490 yield* run(yield* cleanAnswer, yield* freshSteps());491492 expect(yield* checkedStages).toStrictEqual([undefined]);493 }).pipe(Effect.provide(world))494 );495496 it.effect(497 "4. a land that finds main moved is merged again, checked again on the new tree, and lands",498 () =>499 Effect.gen(function* () {500 const answer = yield* cleanAnswer;
499 unmodified lines
modified:apps/platform/test/bindings.test.ts+47 added
1 unmodified line
2import type { D1Client } from "@effect/sql-d1";3import { describe, expect, expectTypeOf, it } from "@effect/vitest";4import type { RepoHostBinding } from "@repo/artifacts/repo-host/binding";5import type { CodeStoreR2 } from "@repo/project/code-store/binding";6import type { MetricsBinding } from "@repo/project/metrics/binding";7import type { RulesEvaluatorWorker } from "@repo/rules/rules-evaluator/worker";8import {9 Array,10 Effect,
88 unmodified lines
99const Named = Schema.Array(Schema.Struct({ name: Schema.String }));100101const BindingKinds = Schema.Struct({102 ai: Schema.optionalKey(Schema.Struct({ binding: Schema.String })),103 analytics_engine_datasets: Schema.optionalKey(Bound),104 artifacts: Schema.optionalKey(Bound),105 d1_databases: Schema.optionalKey(Bound),106 durable_objects: Schema.optionalKey(Schema.Struct({ bindings: Named })),107 kv_namespaces: Schema.optionalKey(Bound),
19 unmodified lines
127 "observability",128 "preview_urls",129 "secrets",130 "triggers",131 "upload_source_maps",132 "vars",133 "workers_dev",134]);135
22 unmodified lines
158const declaredIn = (raw: typeof Raw.Type) =>159 Effect.map(decodeBlock(raw), (block) => ({160 bindings: sorted([161 ...(block.ai === undefined ? [] : [block.ai.binding]),162 ...(block.analytics_engine_datasets ?? []).map(({ binding }) => binding),163 ...(block.artifacts ?? []).map(({ binding }) => binding),164 ...(block.d1_databases ?? []).map(({ binding }) => binding),165 ...(block.durable_objects?.bindings ?? []).map(({ name }) => name),166 ...(block.kv_namespaces ?? []).map(({ binding }) => binding),
225 unmodified lines
392 });393 }).pipe(Effect.provide(NodeServices.layer))394 );395396 it.effect(397 "write domain metrics to each block's own dataset, so no stage's counts mix with another's",398 () =>399 Effect.gen(function* () {400 const raw = yield* Effect.flatMap(401 fileText("wrangler.jsonc"),402 readJsonc403 );404405 const { env = {} } = yield* Schema.decodeUnknownEffect(Staged)(raw);406407 const Datasets = Schema.Struct({408 analytics_engine_datasets: Schema.Array(409 Schema.Struct({ binding: Schema.String, dataset: Schema.String })410 ),411 });412413 const datasets = (block: typeof Raw.Type | undefined) =>414 Effect.map(415 Schema.decodeUnknownEffect(Datasets)(block),416 ({ analytics_engine_datasets }) => analytics_engine_datasets417 );418419 expect({420 demo: yield* datasets(env.demo),421 "dev-oscabriel": yield* datasets(env["dev-oscabriel"]),422 prod: yield* datasets(env.prod),423 top: yield* datasets(raw),424 }).toStrictEqual({425 demo: [{ binding: "METRICS", dataset: "metrics_demo" }],426 "dev-oscabriel": [427 { binding: "METRICS", dataset: "metrics_dev_oscabriel" },428 ],429 prod: [{ binding: "METRICS", dataset: "metrics_prod" }],430 top: [{ binding: "METRICS", dataset: "metrics_local" }],431 });432 }).pipe(Effect.provide(NodeServices.layer))433 );434435 it("are all the Env the Worker is given, and nothing else", () => {436 expectTypeOf<keyof Env>().toEqualTypeOf<437 Exclude<438 keyof PlatformConfig,
50 unmodified lines
489 >();490 expectTypeOf<PlatformConfig["CODE_CACHE"]>().toEqualTypeOf<491 Env["CODE_CACHE"]492 >();493 expectTypeOf<Env["METRICS"]>().toExtend<494 Parameters<typeof MetricsBinding>[0]495 >();496 expectTypeOf<PlatformConfig["METRICS"]>().toEqualTypeOf<Env["METRICS"]>();497 });498499 it("type the sandbox service binding by the entrypoint the platform calls", () => {500 // If the generated `Env` ever types `SANDBOX`'s methods, or turns `any`, this fails:
40 unmodified lines
modified:apps/platform/test/fake-env.ts+1 added
132 unmodified lines
133 FRONT_PAGE: untouchable("FRONT_PAGE"),134 LANDER_ADAPTER: "container",135 LOADER: untouchable("LOADER"),136 MASTER_KEY: masterKey,137 METRICS: untouchable("METRICS"),138 OAUTH_KV: untouchable("OAUTH_KV"),139 ON_PUSH: untouchable("ON_PUSH"),140 OPERATOR_HANDLE: "oscabriel",141 OPERATOR_TOKEN: operatorToken,
22 unmodified lines
modified:apps/platform/test/sandbox-adapters.test.ts+27 added
626 unmodified lines
627 },628 ]);629 })630 );631632 it.effect(633 "logs a defect from the far side by its name and frames alone, since a Checker's may quote a sealed file's path",634 () =>635 Effect.gen(function* () {636 const sealed = "tests/sealed/parse.test.ts";637638 const { lander } = yield* world({639 binding: (sandbox) => ({640 ...sandbox,641 merge: () =>642 Promise.resolve(643 Schema.encodeSync(MergeExit)(644 Exit.die(new Error(`no file at ${sealed}`))645 )646 ),647 }),648 });649650 const { lines } = yield* withLogs(lander.merge(mergeJob));651652 expect(653 lines.map(({ annotations }) => annotations.detail)654 ).toStrictEqual([expect.stringMatching(/^Error: <withheld>/u)]);655 expect(JSON.stringify(lines)).not.toContain(sealed);656 })657 );658});659660describe("a sandbox job's tokens", () => {661 it.effect("are each revoked once their job has ended", () =>
78 unmodified lines
added:apps/platform/test/telemetry.test.ts+355 added
1import { describe, expect, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import { CheckRunner } from "@repo/checks/check-runner";4import { EvidenceStore } from "@repo/checks/evidence-store";5import { Lander } from "@repo/project/lander";6import { LandingCommand } from "@repo/project/landing";7import { Projects } from "@repo/project/projects";8import { LandedSha, RequestId } from "@repo/protocol/ids";9import { VerifierBlocked } from "@repo/protocol/refusal";10import { recordingConsole } from "@repo/telemetry/logger/memory";11import { recordingTracing, ROOT } from "@repo/telemetry/spans/memory";12import { Telemetry } from "@repo/telemetry/telemetry";13import { untouchable } from "@repo/testkit/untouchable";14import { Effect, Exit, Layer, Redacted, Schema } from "effect";15import { HttpRouter } from "effect/http";1617import { DoProjects } from "../src/adapters/do-projects.ts";18import { PlatformEnv } from "../src/platform.ts";19import { telemetryOf } from "../src/ports.ts";20import { buildHandler } from "../src/router-build.ts";21import { runWorkflow } from "../src/workflows/answer.ts";22import { instance, invocation } from "../src/workflows/instance.ts";23import { StepRunner, workflowSteps } from "../src/workflows/step.ts";24import { fakeEnv } from "./fake-env.ts";25import {26 alice,27 bob,28 namespaceOf,29 parseIso,30 project,31 world,32} from "./project-do.fixtures.ts";3334const telemetry = () => {35 const console = recordingConsole();36 const recording = recordingTracing();3738 return {39 console,40 layer: Layer.merge(41 Telemetry({ secrets: [], tracing: recording.tracing }),42 console.layer43 ),44 recording,45 };46};4748const origin = "https://platform.test";4950const requestId = RequestId.make("req-none0001");5152const routes = HttpRouter.use((router) =>53 Effect.gen(function* () {54 yield* router.add(55 "GET",56 "/dies",57 Effect.die(new Error("the store is gone"))58 );59 yield* router.add("GET", "/refuses", Effect.fail(new VerifierBlocked({})));60 })61);6263describe("a platform router", () => {64 it.effect(65 "reports a route's defect once, at Error, and never a route's typed failure",66 () =>67 Effect.gen(function* () {68 const { console, layer } = telemetry();69 const { dispose, handler } = buildHandler(routes, layer);7071 const statuses = yield* Effect.forEach(["dies", "refuses"], (path) =>72 Effect.promise(() => handler(new Request(`${origin}/${path}`))).pipe(73 Effect.map(({ status }) => status)74 )75 );7677 yield* Effect.promise(dispose);7879 expect(statuses).toStrictEqual([500, 500]);80 expect(console.errors()).toHaveLength(1);81 expect(console.errors()[0]).toHaveProperty(82 "cause",83 expect.stringMatching(/^Error: the store is gone\n\s+at /u)84 );85 })86 );87});8889const platformConfig = (env: Readonly<Record<string, string>> = {}) =>90 Schema.decodeUnknownEffect(PlatformEnv)({ ...fakeEnv(), ...env }).pipe(91 Effect.orDie92 );9394describe("the Worker's telemetry", () => {95 it.effect(96 "takes every secret the env holds out of each line it logs, each session token included",97 () =>98 Effect.gen(function* () {99 const session = "session-token-0123456789abcdef0123456789";100101 const config = yield* platformConfig({102 SESSION_TOKENS: JSON.stringify({ [session]: "alice" }),103 });104105 const secrets = [106 config.COOKIE_KEY,107 config.MASTER_KEY,108 config.OPERATOR_TOKEN,109 config.PASSWORD_PEPPER,110 ].map((secret) => Redacted.value(secret));111112 const held = `held ${[...secrets, session].join(" ")}`;113 const console = recordingConsole();114115 const { dispose, handler } = buildHandler(116 HttpRouter.use((router) =>117 router.add(118 "GET",119 "/dies",120 Effect.logWarning(held).pipe(121 Effect.andThen(Effect.die(new Error(held)))122 )123 )124 ),125 Layer.merge(telemetryOf(config), console.layer)126 );127128 yield* Effect.promise(() => handler(new Request(`${origin}/dies`)));129 yield* Effect.promise(dispose);130131 const logged = JSON.stringify(console.written());132133 expect(console.errors()).toHaveLength(1);134 expect(135 [...secrets, session].filter((secret) => logged.includes(secret))136 ).toStrictEqual([]);137 expect(logged).toContain("held <redacted> <redacted>");138 })139 );140141 it.effect(142 "keeps a defect by its name and frames alone, a route's and a Project DO's, since its text may name a layer's repo",143 () =>144 Effect.gen(function* () {145 const config = yield* platformConfig();146 const repo = "alice--datekit--private";147 const console = recordingConsole();148 const layer = Layer.merge(telemetryOf(config), console.layer);149150 const { dispose, handler } = buildHandler(151 HttpRouter.use((router) =>152 router.add(153 "GET",154 "/dies",155 Effect.die(new Error(`the layer repo ${repo} has no commit`))156 )157 ),158 layer159 );160161 yield* Effect.promise(() => handler(new Request(`${origin}/dies`)));162 yield* Effect.promise(dispose);163164 const { namespace } = yield* namespaceOf.pipe(Effect.provide(layer));165166 yield* Effect.gen(function* () {167 const made = yield* (yield* Projects).create(project);168169 yield* made.initProject(alice, {});170 yield* Effect.exit(171 made.advanceAnswer(172 requestId,173 LandingCommand.Start({ main: LandedSha.make("a".repeat(40)) })174 )175 );176 }).pipe(Effect.provide(DoProjects(namespace)));177178 const logged = JSON.stringify(console.written());179180 const withheld = /^Error: <withheld>\n\s+at /u;181182 expect(console.errors()).toMatchObject([183 { message: "Error: <withheld>" },184 { message: "Error: <withheld>", project },185 ]);186 expect(console.errors()[0]).toHaveProperty(187 "cause",188 expect.stringMatching(withheld)189 );190 expect(console.errors()[1]).toHaveProperty(191 "cause",192 expect.stringMatching(withheld)193 );194 expect(195 [repo, requestId].filter((text) => logged.includes(text))196 ).toStrictEqual([]);197 }).pipe(Effect.provide(world))198 );199});200201describe("a Project DO call", () => {202 it.effect(203 "reports its defect once, in the DO, by its project, and its caller reports it no more",204 () =>205 Effect.gen(function* () {206 const durable = telemetry();207 const caller = telemetry();208209 const { namespace } = yield* namespaceOf.pipe(210 Effect.provide(durable.layer)211 );212213 const refused = yield* Effect.gen(function* () {214 const projects = yield* Projects;215 const made = yield* projects.create(project);216217 yield* made.initProject(alice, {});218 yield* Effect.exit(219 made220 .advanceAnswer(221 requestId,222 LandingCommand.Start({ main: LandedSha.make("a".repeat(40)) })223 )224 .pipe(Effect.withErrorReporting)225 );226227 return yield* Effect.flip(228 made.claim(bob, parseIso).pipe(Effect.withErrorReporting)229 );230 }).pipe(231 Effect.provide(Layer.merge(DoProjects(namespace), caller.layer))232 );233234 expect(refused._tag).toBe("UnknownAsk");235 expect(caller.console.errors()).toStrictEqual([]);236 expect(durable.console.errors()).toHaveLength(1);237 expect(durable.console.errors()[0]).toMatchObject({238 message: "Error: no answer request req-none0001",239 project,240 });241 expect(242 durable.recording243 .spans()244 .flatMap(({ name }) => (name.startsWith("Project.") ? [name] : []))245 ).toStrictEqual([246 "Project.listAsks",247 "Project.initProject",248 "Project.advanceAnswer",249 "Project.claim",250 ]);251 }).pipe(Effect.provide(world))252 );253});254255describe("a Workflow instance", () => {256 it.effect(257 "reports a Project DO's defect, met inside a step, no more: the DO reported it",258 () =>259 Effect.gen(function* () {260 const durable = telemetry();261 const caller = telemetry();262263 const { namespace } = yield* namespaceOf.pipe(264 Effect.provide(durable.layer)265 );266267 // An engine whose step rejects as the body did, as a step past its retries does.268 const engine = workflowSteps({ do: (_name, _config, body) => body() });269270 const exit = yield* Effect.gen(function* () {271 const made = yield* (yield* Projects).create(project);272273 yield* made.initProject(alice, {});274275 return yield* StepRunner.use(({ step }) =>276 step(277 "advance",278 Schema.Null,279 made280 .advanceAnswer(281 requestId,282 LandingCommand.Start({ main: LandedSha.make("a".repeat(40)) })283 )284 .pipe(Effect.as(null))285 )286 );287 }).pipe(288 invocation({ project, requestId }),289 instance("Answer.run"),290 Effect.provide(291 Layer.mergeAll(DoProjects(namespace), engine, caller.layer)292 ),293 Effect.exit294 );295296 expect(Exit.isFailure(exit)).toBeTruthy();297 expect(caller.console.errors()).toStrictEqual([]);298 expect(durable.console.errors()).toMatchObject([299 { message: "Error: no answer request req-none0001", project },300 ]);301 }).pipe(Effect.provide(world))302 );303304 it.effect(305 "reports its defect once, by its project and request, and still rejects",306 () =>307 Effect.gen(function* () {308 const { console, layer, recording } = telemetry();309310 const ports = Layer.mergeAll(311 Layer.succeed(312 CheckRunner,313 untouchable<CheckRunner["Service"]>("CheckRunner")314 ),315 Layer.succeed(316 EvidenceStore,317 untouchable<EvidenceStore["Service"]>("EvidenceStore")318 ),319 Layer.succeed(Lander, untouchable<Lander["Service"]>("Lander")),320 Layer.succeed(Projects, untouchable<Projects["Service"]>("Projects")),321 Layer.succeed(RepoHost, untouchable<RepoHost["Service"]>("RepoHost")),322 layer323 );324325 const rejected = yield* Effect.flip(326 Effect.tryPromise(() =>327 runWorkflow(328 ports,329 { project, requestId },330 { do: (_name, _config, body) => body() }331 )332 )333 );334335 expect(rejected.cause).toHaveProperty("name", "TouchedError");336 expect(console.errors()).toHaveLength(1);337 expect(console.errors()[0]).toMatchObject({338 message: "TouchedError: a test touched Projects.get",339 project,340 requestId,341 });342 expect(343 Object.fromEntries(recording.spans()[0]?.attributes ?? [])344 ).toStrictEqual({345 project,346 requestId,347 });348 expect(recording.spans().map(({ name }) => name)).toStrictEqual([349 ROOT,350 "Answer.run",351 "Workflow.load",352 ]);353 })354 );355});
modified:apps/platform/test/worker-init.test.ts+28 added
4 unmodified lines
5import { FrontPage } from "@repo/project/front-page";6import { Lander, Rebuild } from "@repo/project/lander";7import type { LandJob } from "@repo/project/lander";8import { LandExit } from "@repo/project/lander/wire";9import { MetricPoint, Metrics } from "@repo/project/metrics";10import {11 CommitSha,12 Handle,13 LandedSha,
254 unmodified lines
268 expect(prepared).toHaveLength(1);269 expect(prepared[0]).toContain("FROM front_page");270 })271 );272273 it.effect("write domain metrics to the METRICS dataset", () =>274 Effect.gen(function* () {275 const written: AnalyticsEngineDataPoint[] = [];276277 const dataset = untouchable<AnalyticsEngineDataset>("METRICS", {278 writeDataPoint: (point) => {279 if (point !== undefined) {280 written.push(point);281 }282 },283 });284285 const config = yield* decodeEnv({286 ...fakeEnv(),287 METRICS: dataset,288 }).pipe(Effect.orDie);289290 yield* Metrics.use((metrics) =>291 metrics.write([MetricPoint.cases.Landed.make({ project: datekit })])292 ).pipe(Effect.provide(workerPorts(config)));293294 expect(written).toStrictEqual([295 { blobs: ["Landed"], doubles: [1], indexes: ["alice/datekit"] },296 ]);297 })298 );299});300301const pageOf = (response: Response) =>302 Effect.map(
183 unmodified lines
modified:apps/platform/test/workers-shim.ts+3 added
32 unmodified lines
33 }34}3536export const env = fakeEnv();3738// Outside workerd no invocation is traced: every span is a no-op.39export { untracedTracing as tracing } from "@repo/telemetry/spans/memory";
modified:apps/platform/package.json+1 added
19 unmodified lines
20 "@repo/git": "workspace:*",21 "@repo/project": "workspace:*",22 "@repo/protocol": "workspace:*",23 "@repo/rules": "workspace:*",24 "@repo/telemetry": "workspace:*",25 "@repo/visibility": "workspace:*",26 "effect": "catalog:"27 },28 "devDependencies": {
12 unmodified lines
modified:apps/platform/worker-configuration.d.ts+5 added-1 removed
1/* eslint-disable */2// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 5f88662c53523b45be0f8663dff97280)2// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 3413a7934fb786b8fe12df930db7223d)3interface __BaseEnv_Env {4 OAUTH_KV: KVNamespace;5 EVIDENCE: R2Bucket;6 RELEASES: R2Bucket;7 CODE_CACHE: R2Bucket;8 FRONT_PAGE: D1Database;9 EMAIL: SendEmail;10 METRICS: AnalyticsEngineDataset;11 ARTIFACTS: Artifacts;12 ARTIFACTS_PRIVATE: Artifacts;13 CLAIM_LIMIT: RateLimit;14 PROPOSAL_LIMIT: RateLimit;
26 unmodified lines
41 RELEASES: R2Bucket;42 CODE_CACHE: R2Bucket;43 FRONT_PAGE: D1Database;44 EMAIL: SendEmail;45 METRICS: AnalyticsEngineDataset;46 ARTIFACTS: Artifacts;47 ARTIFACTS_PRIVATE: Artifacts;48 CLAIM_LIMIT: RateLimit;49 PROPOSAL_LIMIT: RateLimit;
21 unmodified lines
71 RELEASES: R2Bucket;72 CODE_CACHE: R2Bucket;73 FRONT_PAGE: D1Database;74 EMAIL: SendEmail;75 METRICS: AnalyticsEngineDataset;76 ARTIFACTS: Artifacts;77 ARTIFACTS_PRIVATE: Artifacts;78 CLAIM_LIMIT: RateLimit;79 PROPOSAL_LIMIT: RateLimit;
21 unmodified lines
101 RELEASES: R2Bucket;102 CODE_CACHE: R2Bucket;103 FRONT_PAGE: D1Database;104 EMAIL: SendEmail;105 METRICS: AnalyticsEngineDataset;106 ARTIFACTS: Artifacts;107 ARTIFACTS_PRIVATE: Artifacts;108 CLAIM_LIMIT: RateLimit;109 PROPOSAL_LIMIT: RateLimit;
27 unmodified lines
modified:apps/platform/wrangler.jsonc+42 added-2 removed
24 unmodified lines
25 // that restores its name after minifying: about 130 KB of the entry.26 // Nothing here reads a name at run time: Effect's tagged errors27 // set `name` from their tag, services are keyed by strings, and the28 // runtime finds Durable Objects, Workflows and entrypoints by export name,29 // which minifying keeps. A stack trace shows minified function names.29 // which minifying keeps. A stack trace shows minified names and positions.30 // The uploaded source maps take an uncaught exception's stack back to the31 // source, but a defect the platform reports itself is logged as thrown:32 // the same commit's `wrangler deploy --dry-run --outdir` gives the map to33 // read it by (README, Observability).34 "keep_names": false,35 "upload_source_maps": true,36 "workers_dev": true,37 "preview_urls": false,38 // Every invocation's logs and trace, unsampled, and Issues, which groups39 // what failed. The runtime's own spans record each Durable Object SQL40 // statement's bound values and each fetch's full URL, so these traces hold41 // the Project DO's layer names and repos and sealed values (never a plain42 // one). The maintainer keeps them in the account's trace store alone: no43 // `destinations`, and no Issues automation sends the platform's anywhere44 // (principle 7).45 // Unlike bindings, wrangler gives `observability` and `upload_source_maps`46 // to every stage that does not set its own47 // (packages/config/test/observability.test.ts holds each stage to them).48 "observability": {49 "enabled": true,50 "logs": {51 "enabled": true,52 "head_sampling_rate": 1,53 "invocation_logs": true,54 },55 "traces": { "enabled": true, "head_sampling_rate": 1 },33 "observability": { "enabled": true },56 "issues": { "enabled": true },57 },58 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Project"] }],59 "vars": {60 // Until sign-in exists, one operator holds a session.61 "OPERATOR_HANDLE": "oscabriel",
55 unmodified lines
117 "send_email": [{ "name": "EMAIL" }],118 "worker_loaders": [{ "binding": "LOADER" }],119 // Workers AI, for the drafter (no key: the account's own).120 "ai": { "binding": "AI" },121 // Domain metrics (landings, refusals, lanes, waits, drafts) in Workers122 // Analytics Engine, one dataset per stage so no stage's counts mix with123 // another's. A dataset is made by its first write, so bootstrap makes none;124 // its name takes `_`, since SQL reads it as a table.125 "analytics_engine_datasets": [126 { "binding": "METRICS", "dataset": "metrics_local" },127 ],128 "services": [{ "binding": "SANDBOX", "service": "sandbox" }],129 // Namespace ids differ per stage, so one stage's counts never spend130 // another's.131 "ratelimits": [
85 unmodified lines
217 ],218 "send_email": [{ "name": "EMAIL" }],219 "worker_loaders": [{ "binding": "LOADER" }],220 "ai": { "binding": "AI" },221 "analytics_engine_datasets": [222 { "binding": "METRICS", "dataset": "metrics_dev_oscabriel" },223 ],224 "services": [225 { "binding": "SANDBOX", "service": "sandbox-dev-oscabriel" },226 ],227 "ratelimits": [
80 unmodified lines
308 ],309 "send_email": [{ "name": "EMAIL" }],310 "worker_loaders": [{ "binding": "LOADER" }],311 "ai": { "binding": "AI" },312 "analytics_engine_datasets": [313 { "binding": "METRICS", "dataset": "metrics_demo" },314 ],315 "services": [{ "binding": "SANDBOX", "service": "sandbox-demo" }],316 "ratelimits": [317 {318 "name": "CLAIM_LIMIT",
83 unmodified lines
402 ],403 "send_email": [{ "name": "EMAIL" }],404 "worker_loaders": [{ "binding": "LOADER" }],405 "ai": { "binding": "AI" },406 "analytics_engine_datasets": [407 { "binding": "METRICS", "dataset": "metrics_prod" },408 ],409 "services": [{ "binding": "SANDBOX", "service": "sandbox-prod" }],410 "ratelimits": [411 {412 "name": "CLAIM_LIMIT",
33 unmodified lines
modified:apps/sandbox/src/checker/run.ts+4 added-1 removed
602 unmodified lines
603 });604605 const key = plan.find(Phase.$is("Snapshot"))?.key ?? lockfileHash;606607 // Each phase its own span, named by its tag alone: a lane's command or a608 // sealed check's area never names one.609 const ran = yield* Effect.forEach(plan, (phase) =>610 Effect.logInfo("checker phase").pipe(611 Effect.annotateLogs({ phase: phase._tag }),612 Effect.andThen(
26 unmodified lines
639 onNone: () => Effect.succeed([]),640 onSome: (part) => Effect.as(writeHeldBack(job, part), []),641 }),642 })641 )643 ),644 Effect.withSpan(`Checker.${phase._tag}`)645 )646 );647648 const exits = yield* Ref.get(job.exits);
40 unmodified lines
modified:apps/sandbox/src/lander/run.ts+4 added
197 unmodified lines
198 env,199 timeoutMs: step.remote === undefined ? LOCAL_MS : REMOTE_MS,200 })201 .pipe(202 // By its subcommand alone: an argument may be a remote's URL.203 Effect.withSpan("Lander.git", {204 attributes: { step: subcommandOf(step) },205 }),206 Effect.catchTag("BoxFailed", ({ reason }) => blocked(step, reason))207 );208209 const expected =
661 unmodified lines
modified:apps/sandbox/src/checker.ts+30 added-3 removed
1// Each check job gets a Checker of its own (a unique id). A Checker named2// `snapshots:<project>` never starts a container: it only keeps that3// project's snapshot ids.4import { CheckAt } from "@repo/checks/check-runner";5import type { CheckRun } from "@repo/checks/check-runner";6import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";7import { keyOf } from "@repo/protocol/ids";8import { VerifierBlocked } from "@repo/protocol/refusal";9import { DurableObject } from "cloudflare:workers";9import { Effect, Exit, Layer, Option, Schema } from "effect";10import { Effect, Exit, Layer, Option, Redacted, Schema } from "effect";1112import { SdkBox } from "./box/sdk.ts";13import { envPlanOf } from "./checker/env.ts";14import { WorkerCheckLogs } from "./checker/logs/worker.ts";15import { blocked, check } from "./checker/run.ts";16import { hasGateways, SdkChecker } from "./checker/sdk.ts";17import { answerJob } from "./job.ts";18import type { Job } from "./job.ts";19import { jobTelemetry } from "./telemetry.ts";2021const DEFAULT_IMAGE = "checker:default";2223const CHECK_IMAGE = "check";2425/** oxlint's JS plugins reserve about 6 GiB of address space per thread; smaller sizes abort. */26export const checkInstance = "standard-3";2728export const checkJob: Job<29 CheckWire,30 typeof CheckWire.Encoded,31 CheckRun,32 VerifierBlocked,33 typeof CheckExit.Encoded34> = {35 // A defect may quote a sealed file's path: its span keeps its name alone,36 // and the platform's report of it its name and frames.37 defects: "name",38 exit: CheckExit,39 ids: ({ job }) => ({40 project: job.project,41 sha: CheckAt.match(job.at, {42 Commit: ({ commit }): string => commit,43 Tree: ({ tree }): string => tree,44 }),45 }),46 name: "Checker.check",47 tokens: ({ clone }) => [clone.token],48 wire: CheckWire,49};5051export class Checker extends DurableObject<Env> {52 check(wire: typeof CheckWire.Encoded): Promise<typeof CheckExit.Encoded> {27 return answerJob(CheckWire, CheckExit, (job) => this.#checked(job))(wire);53 return answerJob(checkJob, (job) => this.#checked(job))(wire);54 }5556 snapshotOf(key: string): string | null {57 return this.ctx.storage.kv.get<string>(key) ?? null;
101 unmodified lines
159 )160 ),161 Effect.orElseSucceed(() => Exit.fail(new VerifierBlocked({}))),162 Effect.flatMap(Schema.encodeEffect(CheckExit)),137 Effect.orDie163 Effect.orDie,164 Effect.provide(jobTelemetry([Redacted.make(wire.clone.token)]))165 )166 );
modified:apps/sandbox/src/job.ts+53 added-13 removed
1import { withInvocation } from "@repo/telemetry/spans";2import type { InvocationIds } from "@repo/telemetry/spans";3import type { TelemetryOptions } from "@repo/telemetry/telemetry";4import { Effect, Schema } from "effect";2import type { Exit } from "effect";5import type { Exit, Layer, Redacted } from "effect";67import { jobTelemetry } from "./telemetry.ts";89/** A job the platform sends: its wire, its reply and what it shows of itself. */10export interface Job<W, WI, A, E, X> {11 /** Its span: Workers do not trace a container, so this is the trace's view of it. */12 readonly name: string;13 readonly wire: Schema.Codec<W, WI>;14 readonly exit: Schema.Codec<Exit.Exit<A, E>, X>;15 /** What Issues shows beside it: ids only, never a repo or a path. */16 readonly ids: (job: W) => InvocationIds;17 /** The tokens it carries, which nothing it logs or traces may. */18 readonly tokens: (job: W) => readonly Redacted.Redacted[];19 /** What its spans keep of a defect: its name alone where sealed files are near. */20 readonly defects: NonNullable<TelemetryOptions["defects"]>;21}2223/** The telemetry a job runs with, given its tokens and what its spans keep of a defect. */24export type JobTelemetry = (25 tokens: readonly Redacted.Redacted[],26 defects: NonNullable<TelemetryOptions["defects"]>27) => Layer.Layer<never>;2829// A defect is no report of the sandbox's own: it crosses in the job's Exit,30// and the platform reports it there, once, by its name and frames, with the31// job's tokens scrubbed.4export const answerJob =32export const answered =33 <W, WI, A, E, X>(6 wire: Schema.Codec<W, WI>,7 exit: Schema.Codec<Exit.Exit<A, E>, X>,8 run: (job: W) => Effect.Effect<A, E>34 job: Job<W, WI, A, E, X>,35 run: (wire: W) => Effect.Effect<A, E>,36 telemetry: JobTelemetry = jobTelemetry37 ) =>10 (encoded: WI): Promise<X> =>11 Effect.runPromise(12 Schema.decodeEffect(wire)(encoded).pipe(13 Effect.orDie,14 Effect.flatMap(run),15 Effect.exit,16 Effect.flatMap((outcome) =>17 Effect.orDie(Schema.encodeEffect(exit)(outcome))38 (encoded: WI): Effect.Effect<X> =>39 Schema.decodeEffect(job.wire)(encoded).pipe(40 Effect.orDie,41 Effect.flatMap((decoded) =>42 run(decoded).pipe(43 Effect.withSpan(job.name),44 withInvocation(job.ids(decoded)),45 Effect.provide(telemetry(job.tokens(decoded), job.defects))46 )47 ),48 Effect.exit,49 Effect.flatMap((outcome) =>50 Effect.orDie(Schema.encodeEffect(job.exit)(outcome))51 )52 );5354export const answerJob =55 <W, WI, A, E, X>(56 job: Job<W, WI, A, E, X>,57 run: (wire: W) => Effect.Effect<A, E>58 ) =>59 (encoded: WI): Promise<X> =>60 Effect.runPromise(answered(job, run)(encoded));6162export const notBuilt = <E>(job: string, blocked: E) =>63 Effect.logWarning("sandbox job not built").pipe(64 Effect.annotateLogs({ job, reason: "not built" }),65 Effect.andThen(Effect.fail(blocked))
1 unmodified line
modified:apps/sandbox/src/lander.ts+44 added-6 removed
19 unmodified lines
20import { bundleRules, compose, land, merge } from "./lander/run.ts";2122export const landImage = "land";2324// A Lander job names no repo: a repo's name is no id (AGENTS.md principle 7).25export const landerJobs = (26 box: Layer.Layer<Box>,27 turn: Semaphore.Semaphore28) => {29 const inBox = <A, E>(job: Effect.Effect<A, E, Box>) =>30 job.pipe(Effect.provide(box), Semaphore.withPermit(turn));3132 return {32 bundleRules: answerJob(BundleWire, BundleExit, (wire) =>33 inBox(bundleRules(wire))33 bundleRules: answerJob(34 {35 defects: "whole",36 exit: BundleExit,37 ids: ({ job }) => ({ sha: job.at }),38 name: "Lander.bundleRules",39 tokens: ({ main }) => [main.token],40 wire: BundleWire,41 },42 (wire) => inBox(bundleRules(wire))43 ),35 compose: answerJob(ComposeWire, ComposeExit, (wire) =>36 inBox(compose(wire))44 compose: answerJob(45 {46 defects: "whole",47 exit: ComposeExit,48 ids: ({ job }) => ({ sha: job.main }),49 name: "Lander.compose",50 tokens: ({ main }) => [main.token],51 wire: ComposeWire,52 },53 (wire) => inBox(compose(wire))54 ),38 land: answerJob(LandWire, LandExit, (wire) => inBox(land(wire))),39 merge: answerJob(MergeWire, MergeExit, (wire) => inBox(merge(wire))),55 land: answerJob(56 {57 defects: "whole",58 exit: LandExit,59 ids: ({ job }) => ({ requestId: job.requestId, sha: job.main }),60 name: "Lander.land",61 tokens: ({ fork, main }) =>62 fork === undefined ? [main.token] : [main.token, fork.token],63 wire: LandWire,64 },65 (wire) => inBox(land(wire))66 ),67 merge: answerJob(68 {69 defects: "whole",70 exit: MergeExit,71 ids: ({ job }) => ({ sha: job.head }),72 name: "Lander.merge",73 tokens: ({ fork, main }) => [main.token, fork.token],74 wire: MergeWire,75 },76 (wire) => inBox(merge(wire))77 ),78 };79};8081/** On the default `lite` (1/16 vCPU) one landing took 32 s. */
81 unmodified lines
added:apps/sandbox/src/telemetry.ts+12 added
1// The sandbox's telemetry: its JSON logger and its spans, over the Worker's2// own `tracing`. The env holds no secret; a job's tokens are the secrets its3// lines must never carry, so each job runs with its own.4import { Telemetry } from "@repo/telemetry/telemetry";5import type { TelemetryOptions } from "@repo/telemetry/telemetry";6import { tracing } from "cloudflare:workers";7import type { Layer, Redacted } from "effect";89export const jobTelemetry = (10 tokens: readonly Redacted.Redacted[],11 defects: TelemetryOptions["defects"] = "whole"12): Layer.Layer<never> => Telemetry({ defects, secrets: tokens, tracing });
modified:apps/sandbox/test/held-back.test.ts+2 added-1 removed
32 unmodified lines
33import { TestClock } from "effect/testing";34import { expectTypeOf } from "vitest";3536import { Box, BoxFailed } from "../src/box.ts";37import { checkJob } from "../src/checker.ts";38import { REGISTRIES } from "../src/checker/network.ts";39import { check, REPO, roomFor } from "../src/checker/run.ts";40import { answerJob } from "../src/job.ts";41import { exited, fakeChecker } from "./fake-box.ts";
627 unmodified lines
669 path: SEALED[0]?.path,670 });671672 const outcome = yield* Effect.promise(() =>672 answerJob(CheckWire, CheckExit, (decoded) =>673 answerJob(checkJob, (decoded) =>674 check(decoded).pipe(Effect.provide(fake.layer))675 )(encoded)676 ).pipe(Effect.flatMap(Schema.decodeEffect(CheckExit)));677
13 unmodified lines
added:apps/sandbox/test/telemetry.test.ts+161 added
1import { describe, expect, it } from "@effect/vitest";2import { CheckAt } from "@repo/checks/check-runner";3import type { CheckWire } from "@repo/checks/check-runner/wire";4import { BundleExit, BundleWire } from "@repo/project/lander/wire";5import type { ConfigBundle } from "@repo/project/lander/wire";6import { Command, Hostname } from "@repo/protocol/domain/common";7import { RunBlock } from "@repo/protocol/domain/run";8import {9 CommitSha,10 LaneName,11 LandedSha,12 ProjectName,13 RepoName,14} from "@repo/protocol/ids";15import { VerifierBlocked } from "@repo/protocol/refusal";16import { recordingConsole } from "@repo/telemetry/logger/memory";17import { recordingTracing, ROOT } from "@repo/telemetry/spans/memory";18import { Telemetry } from "@repo/telemetry/telemetry";19import { Cause, Effect, Exit, Layer, Redacted, Schema } from "effect";2021import { checkJob } from "../src/checker.ts";22import { answered } from "../src/job.ts";23import type { Job } from "../src/job.ts";2425const token = "art_v1_0123456789abcdef0123456789abcdef";2627const sealedPath = "checks/held-back/parser/week-54.test.ts";2829const sha = CommitSha.make("a".repeat(40));3031const project = ProjectName.make("oscabriel/datekit");3233const checkWire: CheckWire = {34 clone: {35 token: Redacted.make(token),36 url: "https://0123abcd.artifacts.cloudflare.net/git/public/datekit.git",37 },38 job: {39 at: CheckAt.cases.Commit.make({ commit: sha }),40 lanes: [{ command: "bun test", lane: LaneName.make("unit") }],41 placeholders: [],42 project,43 proxies: [],44 repo: RepoName.make("datekit"),45 run: RunBlock.make({46 checks: { [LaneName.make("unit")]: Command.make("bun test") },47 setup: Command.make("bun install"),48 setupEgress: [Hostname.make("npm.pkg.github.com")],49 test: Command.make("bun test {path}"),50 }),51 },52};5354const observed = <W, WI, A, E, X>(55 job: Job<W, WI, A, E, X>,56 wire: W,57 run: (decoded: W) => Effect.Effect<A, E>58) =>59 Effect.gen(function* () {60 const console = recordingConsole();61 const recording = recordingTracing();62 const encoded = yield* Schema.encodeEffect(job.wire)(wire);6364 const exit = yield* answered(job, run, (tokens, defects) =>65 Layer.merge(66 Telemetry({ defects, secrets: tokens, tracing: recording.tracing }),67 console.layer68 )69 )(encoded).pipe(Effect.flatMap(Schema.decodeEffect(job.exit)));7071 return { console, exit, spans: recording.spans() };72 });7374describe("a sandbox job", () => {75 it.effect(76 "hands its defect to the platform in its Exit and reports none itself",77 () =>78 Effect.gen(function* () {79 const { console, exit } = yield* observed(checkJob, checkWire, () =>80 Effect.die(new Error("the container is gone"))81 );8283 expect(Exit.isFailure(exit) && Cause.hasDies(exit.cause)).toBeTruthy();84 expect(console.errors()).toStrictEqual([]);85 })86 );8788 it.effect(89 "names its project and SHA on the invocation's root span, and its own span by the job",90 () =>91 Effect.gen(function* () {92 const { spans } = yield* observed(checkJob, checkWire, () =>93 Effect.fail(new VerifierBlocked({}))94 );9596 expect([97 spans.map(({ name }) => name),98 Object.fromEntries(spans[0]?.attributes ?? []),99 spans[1]?.exceptions,100 ]).toStrictEqual([101 [ROOT, "Checker.check"],102 { project, sha },103 [{ name: "VerifierBlocked" }],104 ]);105 })106 );107108 it.effect(109 "keeps a Checker's defect off its spans but by name: its text may quote a sealed path",110 () =>111 Effect.gen(function* () {112 const { spans } = yield* observed(checkJob, checkWire, () =>113 Effect.die(new TypeError(`no file at ${sealedPath}`))114 );115116 expect(spans[1]?.exceptions).toStrictEqual([{ name: "TypeError" }]);117 })118 );119120 it.effect("carries none of its tokens in a line it logs", () =>121 Effect.gen(function* () {122 const bundle: Job<123 typeof BundleWire.Type,124 typeof BundleWire.Encoded,125 typeof ConfigBundle.Type,126 VerifierBlocked,127 typeof BundleExit.Encoded128 > = {129 defects: "whole",130 exit: BundleExit,131 ids: ({ job }) => ({ sha: job.at }),132 name: "Lander.bundleRules",133 tokens: ({ main }) => [main.token],134 wire: BundleWire,135 };136137 const { console } = yield* observed(138 bundle,139 {140 job: { at: LandedSha.make(sha), repo: RepoName.make("datekit") },141 main: checkWire.clone,142 },143 () =>144 Effect.logWarning(`git said: bad credentials ${token}`).pipe(145 Effect.andThen(Effect.fail(new VerifierBlocked({})))146 )147 );148149 expect(console.written()).toStrictEqual([150 {151 line: {152 level: "WARN",153 message: "git said: bad credentials <redacted>",154 sha,155 },156 method: "warn",157 },158 ]);159 })160 );161});
modified:apps/sandbox/test/workers-shim.ts+3 added
21 unmodified lines
22 }23}2425export const env = fakeEnv();2627// Outside workerd no invocation is traced: every span is a no-op.28export { untracedTracing as tracing } from "@repo/telemetry/spans/memory";
modified:apps/sandbox/package.json+1 added
13 unmodified lines
14 "@repo/git": "workspace:*",15 "@repo/project": "workspace:*",16 "@repo/protocol": "workspace:*",17 "@repo/rules": "workspace:*",18 "@repo/telemetry": "workspace:*",19 "effect": "catalog:"20 },21 "devDependencies": {22 "@cloudflare/workers-types": "5.20261006.1",
9 unmodified lines
modified:apps/sandbox/wrangler.jsonc+29 added-1 removed
13 unmodified lines
14 "compatibility_date": "2026-10-05",15 // The Sandbox SDK's `Files` needs it.16 "compatibility_flags": ["nodejs_compat"],17 "minify": true,18 // A stack trace in the logs, or an Issue, names the source.19 "upload_source_maps": true,20 "workers_dev": false,21 "preview_urls": false,22 // The Worker's own: every invocation's logs and trace, unsampled, and23 // Issues. Every stage inherits it; a container's logs are its own, below.24 "observability": {25 "enabled": true,26 "logs": {27 "enabled": true,28 "head_sampling_rate": 1,29 "invocation_logs": true,30 },31 "traces": { "enabled": true, "head_sampling_rate": 1 },20 "observability": { "enabled": true },32 "issues": { "enabled": true },33 },34 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Checker", "Lander"] }],35 "durable_objects": {36 "bindings": [37 { "name": "CHECKER", "class_name": "Checker" },
2 unmodified lines
40 },41 // Untrusted answer code runs in a Checker; the Lander runs only git and42 // Bun. One container per Durable Object, which picks its instance size when43 // it starts it (`ctx.container.start`).44 //45 // A container's own logs are off in a Checker: held-back checks run there,46 // and nothing a sealed check writes may reach a log (principle 7). They are47 // on in the Lander, which reads and writes only the public namespace's48 // repos (canonical and forks), never a layer, and hands git its token in49 // env, never in a URL or an argument. Each stage sets both again: a50 // container that leaves `observability` out keeps whatever it last had.51 "containers": [52 {53 "class_name": "Checker",54 "scheduling_policy": "durable_object",55 "observability": { "enabled": false },56 "images": { "check": { "dockerfile": "./images/check.Dockerfile" } },57 },58 {59 "class_name": "Lander",60 "scheduling_policy": "durable_object",61 "observability": { "enabled": true },62 // The repo root, so the image can carry the sdk for `bundleRules`63 // (land.Dockerfile.dockerignore admits only what it copies).64 "images": {65 "land": {
14 unmodified lines
80 "containers": [81 {82 "class_name": "Checker",83 "scheduling_policy": "durable_object",84 "observability": { "enabled": false },85 "images": {86 "check": { "dockerfile": "./images/check.Dockerfile" },87 },88 },89 {90 "class_name": "Lander",91 "scheduling_policy": "durable_object",92 "observability": { "enabled": true },93 "images": {94 "land": {95 "dockerfile": "./images/land.Dockerfile",96 "build_context": "../..",
12 unmodified lines
109 "containers": [110 {111 "class_name": "Checker",112 "scheduling_policy": "durable_object",113 "observability": { "enabled": false },114 "images": {115 "check": { "dockerfile": "./images/check.Dockerfile" },116 },117 },118 {119 "class_name": "Lander",120 "scheduling_policy": "durable_object",121 "observability": { "enabled": true },122 "images": {123 "land": {124 "dockerfile": "./images/land.Dockerfile",125 "build_context": "../..",
12 unmodified lines
138 "containers": [139 {140 "class_name": "Checker",141 "scheduling_policy": "durable_object",142 "observability": { "enabled": false },143 "images": {144 "check": { "dockerfile": "./images/check.Dockerfile" },145 },146 },147 {148 "class_name": "Lander",149 "scheduling_policy": "durable_object",150 "observability": { "enabled": true },151 "images": {152 "land": {153 "dockerfile": "./images/land.Dockerfile",154 "build_context": "../..",
7 unmodified lines
modified:apps/web/wrangler.jsonc+13 added-2 removed
23 unmodified lines
24 "compatibility_date": "2026-10-05",25 "compatibility_flags": ["nodejs_compat"],26 "workers_dev": true,27 "preview_urls": false,28 // Every invocation's logs and trace, unsampled, and Issues. Every stage29 // inherits it, as it does the source maps below.30 "observability": {31 "enabled": true,32 "logs": {33 "enabled": true,34 "head_sampling_rate": 1,35 "invocation_logs": true,36 },37 "traces": { "enabled": true, "head_sampling_rate": 1 },28 "observability": { "enabled": true },38 "issues": { "enabled": true },39 },40 // The server build is minified (vite.config.ts); its source maps let a30 // stack trace in the logs name the source.41 // stack trace in the logs, or an Issue, name the source.42 "upload_source_maps": true,43 "services": [{ "binding": "PLATFORM", "service": "platform" }],44 "vars": {45 // Where a browser reaches the platform itself: its sign-in pages and
34 unmodified lines
modified:infra/.env.schema+10 added-1 removed
12 unmodified lines
13CLOUDFLARE_ACCOUNT_ID=1415# An API token for ops calls and infra scripts: the "Read all resources"16# template plus Account › Artifacts › Edit. Writes anywhere else, deploys17# included, go through `wrangler login`, never this token.17# included, go through `wrangler login`, never this token. Its Account ›18# Account Analytics › Read lets smoke read a deploy's Workers Logs through19# the SQL API (`--since`); without it, every deploy's smoke fails.20# @required @sensitive21# @docs(https://developers.cloudflare.com/fundamentals/api/get-started/create-token/)22CLOUDFLARE_API_TOKEN=2324# Where a stage's alerts are sent: one address, entered as each alert's25# email destination. A person makes the alerts by hand (README, Alerts), so26# bootstrap only says whether this is set, and never shows it.27# @type=email28# @docs(https://developers.cloudflare.com/notifications/notification-available/)29ALERT_EMAIL=3031# Telemetry stays off for every tool run through varlock here.32DO_NOT_TRACK=133CF_SEND_TELEMETRY=034
6 unmodified lines
added:infra/alerts.ts+138 added
1// A stage's alerts, as data: Cloudflare Custom Alerts (beta), each a SQL API2// query run on a schedule and judged by a threshold or an anomaly. A person3// makes them by hand: the Notifications API lists the `custom_analytics`4// alert type but documents none of its fields, and nothing in cf or the API5// takes a custom alert's query, so bootstrap prints each for the dashboard6// (README, Alerts), makes none, and records none in the ledger. Every query7// counts rows by Worker; none reads a log's text, a path or a layer8// (principle 7).9import { Data, Duration } from "effect";1011import { ERRORED, quoted, workersOf } from "./logs.ts";12import { resources } from "./stages.ts";13import type { Stage } from "./stages.ts";1415export type Detection = Data.TaggedEnum<{16 // The query's value over the evaluation window reaches `atLeast`.17 Threshold: { readonly atLeast: number };18 // The value is `sensitivity` standard deviations above the baseline19 // window's, and at least `minimum`: a spike, never a drop.20 Spike: {21 readonly baseline: Duration.Duration;22 readonly sensitivity: number;23 readonly minimum: number;24 };25}>;2627export const Detection = Data.taggedEnum<Detection>();2829export const alertKinds = [30 "errors",31 "issue spike",32 "container failures",33 "refusal spike",34] as const;3536export interface Alert {37 readonly kind: (typeof alertKinds)[number];38 readonly name: string;39 // One numeric column named `value`, and no time filter: the alert's40 // Automatic time range is its evaluation window.41 readonly query: string;42 readonly window: Duration.Duration;43 readonly detection: Detection;44}4546// What the apps log at error level when a sandbox job's container never47// answered: the platform when a job comes back blocked, and the sandbox when48// a Checker can't be reached. `alerts.test.ts` holds each to its source.49export const CONTAINER_FAILURES = [50 "sandbox job blocked",51 "the Checker could not be reached",52] as const;5354// The metrics dataset's layout, as the platform's writer55// (`packages/project/src/metrics/binding.ts`) lays it out: its first blob is56// the point's kind, `Refused` for one refusal. `alerts.test.ts` holds it to57// the writer.58export const REFUSED = "blob1 = 'Refused'";5960const within = (column: string, values: readonly string[]) =>61 `${column} IN (${values.map(quoted).join(", ")})`;6263export const alerts = (stage: Stage, account: string): readonly Alert[] => {64 const { metrics, platform, sandbox } = resources(stage);65 // A custom alert's SQL names its account. Smoke's names none: the SQL API66 // refuses a query that names one beside the request's own scope.67 const scoped = `accountTag = ${quoted(account)}`;6869 const failed = CONTAINER_FAILURES.map(70 (line) => `message LIKE ${quoted(`%${line}%`)}`71 ).join(" OR ");7273 return [74 ...workersOf(stage).map((worker): Alert => ({75 detection: Detection.Threshold({ atLeast: 5 }),76 kind: "errors",77 name: `${worker} errors`,78 query: `SELECT count() AS value FROM logs.workersLogs WHERE ${scoped} AND scriptName = ${quoted(worker)} AND ${ERRORED}`,79 window: Duration.minutes(15),80 })),81 {82 detection: Detection.Spike({83 baseline: Duration.hours(2),84 minimum: 3,85 sensitivity: 3,86 }),87 kind: "issue spike",88 name: `${stage} issue spike`,89 query: `SELECT count() AS value FROM logs.issues WHERE ${scoped} AND ${within("scriptName", workersOf(stage))}`,90 window: Duration.minutes(10),91 },92 {93 detection: Detection.Threshold({ atLeast: 3 }),94 kind: "container failures",95 name: `${stage} container failures`,96 query: `SELECT count() AS value FROM logs.workersLogs WHERE ${scoped} AND ${within("scriptName", [platform, sandbox])} AND level = 'error' AND (${failed})`,97 window: Duration.minutes(30),98 },99 {100 detection: Detection.Spike({101 baseline: Duration.hours(6),102 minimum: 5,103 sensitivity: 3,104 }),105 kind: "refusal spike",106 name: `${stage} refusal spike`,107 query: `SELECT count() AS value FROM events.analyticsEngine."${metrics}" WHERE ${scoped} AND ${REFUSED}`,108 window: Duration.minutes(15),109 },110 ];111};112113const detected = ({ detection, window }: Alert) =>114 Detection.$match(detection, {115 Spike: ({ baseline, minimum, sensitivity }) =>116 `anomaly detection on spikes, evaluation window ${Duration.format(window)}, baseline window ${Duration.format(baseline)}, sensitivity ${sensitivity}, minimum event count ${minimum}`,117 Threshold: ({ atLeast }) =>118 `threshold, value >= ${atLeast}, evaluation window ${Duration.format(window)}`,119 });120121// The destination is named, never shown: `addressed` says whether infra's122// env sets it.123export const alertLines = (124 stage: Stage,125 all: readonly Alert[],126 addressed: boolean127): readonly string[] => [128 `bootstrap ${stage}: make these ${all.length} alerts by hand, as Custom Alerts in the dashboard: no API takes a custom alert's query yet (README, Alerts)`,129 `bootstrap ${stage}: each is custom SQL with an Automatic time range, sent to ${130 addressed131 ? "ALERT_EMAIL's address"132 : "ALERT_EMAIL's address, which infra/.env.local does not set yet"133 }`,134 ...all.flatMap((alert) => [135 ` ${alert.name}: ${detected(alert)}`,136 ` ${alert.query}`,137 ]),138];
modified:infra/bootstrap.ts+21 added-1 removed
1// Usage: bun run bootstrap -- --stage <stage> [--dry-run | --check-triggers]2// Idempotent: creates only what is missing, and never deletes.2// Idempotent: creates only what is missing, and never deletes. Either run3// ends by printing the stage's alerts, which a person makes by hand.4import { BunRuntime, BunServices } from "@effect/platform-bun";5import {6 Config,7 Console,
9 unmodified lines
17} from "effect";18import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";19import { ChildProcess, ChildProcessSpawner } from "effect/process";2021import { alertLines, alerts } from "./alerts.ts";22import { schemaItems } from "./env-schema.ts";23import type { SchemaItem } from "./env-schema.ts";24import { blankJsonc, pathKey, valueSpans } from "./jsonc.ts";25import type { JsonPath, Span } from "./jsonc.ts";
515 unmodified lines
541 )542 : Effect.fail(new MissingSecrets({ names: missing, stage }));543 });544545// Where the alerts are sent, by name: `alertLines` never shows the address.546const Destination = Config.option(Config.String("ALERT_EMAIL"));547548const alertPlan = (credentials: Credentials, stage: Stage) =>549 Effect.gen(function* () {550 const destination = yield* Destination.pipe(Effect.orDie);551552 yield* Console.log(553 alertLines(554 stage,555 alerts(stage, credentials.accountId),556 Option.isSome(destination)557 ).join("\n")558 );559 });560561const dryRun = (root: string, credentials: Credentials, stage: Stage) =>562 Effect.gen(function* () {563 const steps = plan(stage, yield* readExisting(root, credentials, stage));564565 yield* Console.log(planLines(stage, steps).join("\n"));566 yield* alertPlan(credentials, stage);567 });568569const make = (root: string, credentials: Credentials, stage: Stage) =>570 Effect.gen(function* () {
50 unmodified lines
621 () => `${JSON.stringify(result, null, 2)}\n`622 );623624 yield* secrets(root, credentials, stage);625 yield* alertPlan(credentials, stage);626627 yield* Console.log(628 `bootstrap ${stage}: created ${steps.length}; next: bun run deploy -- --stage ${stage}`629 );
26 unmodified lines
modified:infra/deploy.ts+34 added-5 removed
1// Usage: bun run deploy -- --stage <stage>2// Runs verify, deploys sandbox, platform and web, checks the push trigger, then3// smoke, which also reads the stage's logs since the first upload began.3// smoke. Refused while `infra/.recording` exists, before any flag is read.4// Refused while `infra/.recording` exists, before any flag is read.5// `STAGE_SECRETS_FILE` passes only the items `apps/platform/.env.schema`6// declares, to the platform step alone; no value is ever printed.7import { BunRuntime, BunServices } from "@effect/platform-bun";8import {9 Config,10 ConfigProvider,11 Console,12 DateTime,13 Effect,14 FileSystem,15 Option,16 Path,
66 unmodified lines
83 ],84 }),85 });8687const verify: Step = {88 args: ["run", "verify"],89 command: "bun",90 cwd: "",91 name: "verify",92};9394// Every step after verify. `since` is when the first upload began: smoke95// fails on any error the stage's Workers logged from then on, read with96// infra's credentials, so it runs through varlock as bootstrap does.97const stepsOf = (98 stage: Stage,99 options: {100 readonly web: boolean;101 readonly platformEnv: Readonly<Record<string, string>>;102 readonly since: DateTime.Utc;103 }104): readonly Step[] => {105 const hosts = hostArgs(stage);106107 return [95 { args: ["run", "verify"], command: "bun", cwd: "", name: "verify" },108 {109 args: ["deploy", "--env", stage],110 command: bin("apps/sandbox", "wrangler"),111 cwd: "apps/sandbox",
32 unmodified lines
144 cwd: "",145 name: "triggers",146 },147 {136 args: ["scripts/smoke.ts", "--stage", stage],137 command: "bun",148 args: [149 "run",150 "--path",151 "infra/",152 "--",153 "bun",154 "scripts/smoke.ts",155 "--stage",156 stage,157 "--since",158 DateTime.formatIso(options.since),159 ],160 command: "node_modules/.bin/varlock",161 cwd: "",162 name: "smoke",163 },164 ];
129 unmodified lines
294 .pipe(Effect.orDie);295296 const platformEnv = yield* platformSecrets(root);297298 yield* runStep(root, stage, verify);299300 // Smoke reads the logs from here: an error logged while verify ran is301 // the replaced version's, never this deploy's.302 const since = yield* DateTime.now;303304 yield* Effect.forEach(276 stepsOf(stage, { platformEnv, web }),305 stepsOf(stage, { platformEnv, since, web }),306 (step) => runStep(root, stage, step),307 { discard: true }308 );309
13 unmodified lines
added:infra/logs.ts+30 added
1// The stage's Workers Logs, read through Cloudflare's SQL API: smoke counts2// a deploy's errors with it, and the alerts in `alerts.ts` watch the same3// rows. Every query here reads counts by Worker, never a log's text, so4// nothing a log holds reaches a terminal or an alert.5import { resources } from "./stages.ts";6import type { Stage } from "./stages.ts";78export const SQL_API = "https://api.cloudflare.com/client/v4/analytics/sql";910// What reads a dataset through the SQL API: the token infra/.env.schema names11// needs it on the account CLOUDFLARE_ACCOUNT_ID names.12export const ANALYTICS_READ = "Account › Account Analytics › Read";1314// A Workers Logs row that is an error: an uncaught exception, whose `error`15// is set, or a line logged at error level. A typed refusal is the product16// working and is never logged at error level, so none counts.17export const ERRORED = "(level = 'error' OR error != '')";1819export const quoted = (text: string) => `'${text.replaceAll("'", "''")}'`;2021export const workersOf = (stage: Stage): readonly string[] => {22 const { platform, sandbox, web } = resources(stage);2324 return [platform, sandbox, web];25};2627// One row per Worker that logged an error, `{ scriptName, errors }`; the28// time range goes beside the query, so no instant is written into its text.29export const errorsQuery = (workers: readonly string[]) =>30 `SELECT scriptName, count() AS errors FROM logs.workersLogs WHERE scriptName IN (${workers.map(quoted).join(", ")}) AND ${ERRORED} GROUP BY scriptName`;
modified:infra/smoke.ts+169 added-2 removed
1import { UnknownProject } from "@repo/protocol/refusal";2import {3 Config,4 Console,5 DateTime,6 Duration,7 Effect,8 Option,9 Result,10 Schedule,11 Schema,12} from "effect";13import type { Redacted } from "effect";14import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";1516import { ANALYTICS_READ, errorsQuery, SQL_API, workersOf } from "./logs.ts";17import {18 flagValue,19 platformOrigin,20 recordedSubdomain,
53 unmodified lines
74}[];7576export const probes = [...platformProbes, ...webProbes] as const;7774export const Probe = Schema.Literals(probes);78// Run after every other probe, and only when smoke is told when the deploy began.79export const logProbes = ["worker-logs"] as const;8081export const Probe = Schema.Literals([...probes, ...logProbes]);8283export type Probe = typeof Probe.Type;8485const MISSING = "oscabriel/no-such-project";86
3 unmodified lines
90const SETTLING = Duration.seconds(30);9192const ASK_AGAIN = Duration.seconds(1);9394// Workers Logs reach the SQL API some seconds after the invocation, so the95// logs are read this long after the probes, whose own errors then count.96const INGESTION = Duration.seconds(30);9798export class SmokeFailed extends Schema.TaggedError<SmokeFailed>()(99 "SmokeFailed",100 {101 failures: Schema.Array(
307 unmodified lines
409 )410 );411};412413// What reading the stage's logs needs: the instant the deploy's first upload414// began, the Workers to read, and infra's credentials.415export interface LogsCheck {416 readonly since: DateTime.Utc;417 readonly workers: readonly string[];418 readonly accountId: string;419 readonly token: Redacted.Redacted;420 // The SQL API's endpoint; a test points it at a fake.421 readonly api?: string;422 readonly ingestion?: Duration.Input;423}424425const decodeErrors = Schema.decodeUnknownEffect(426 Schema.fromJsonString(427 Schema.Struct({428 data: Schema.Array(429 Schema.Struct({ errors: Schema.Int, scriptName: Schema.String })430 ),431 })432 )433);434435// How the API refuses the credentials, as seen live: 400 (error 9106) for a436// token it can't authenticate, and 422 naming the account tag for an account437// the token can't read; 401 and 403 are its usual answers to a missing438// permission.439const refusedCredentials = (status: number, text: string) =>440 status === 400 ||441 status === 401 ||442 status === 403 ||443 (status === 422 && text.includes("account or zone tag"));444445// The API's own first line, which names what it could not run.446const unread = (label: string, status: number, text: string) => {447 const said = text.split("\n")[0]?.trim().slice(0, 200) ?? "";448449 if (refusedCredentials(status, text)) {450 return `${label} answered ${status}: CLOUDFLARE_API_TOKEN needs ${ANALYTICS_READ} on the account CLOUDFLARE_ACCOUNT_ID names`;451 }452453 return said === ""454 ? `${label} answered ${status}`455 : `${label} answered ${status}: ${said}`;456};457458const workerLogs = (check: LogsCheck) =>459 Effect.gen(function* () {460 const label = "POST /analytics/sql for the stage's Workers Logs";461 const since = DateTime.formatIso(check.since);462463 const { status, text } = yield* send(464 label,465 HttpClientRequest.bodyJsonUnsafe(466 HttpClientRequest.post(check.api ?? SQL_API),467 {468 query: errorsQuery(check.workers),469 scope: { accountTag: check.accountId },470 time_range: { start: since },471 }472 ).pipe(HttpClientRequest.bearerToken(check.token))473 );474475 if (status !== 200) {476 return yield* new Missed({477 reason: unread(label, status, text),478 transient: serverError(status),479 });480 }481482 const { data } = yield* decodeErrors(text).pipe(483 missing(`${label} answered 200 without {"data":[{scriptName, errors}]}`)484 );485486 const logged = check.workers.flatMap((worker) => {487 const errors = data488 .filter(({ scriptName }) => scriptName === worker)489 .reduce((sum, row) => sum + row.errors, 0);490491 return errors > 0 ? [`${worker} ${errors}`] : [];492 });493494 return yield* logged.length === 0495 ? Effect.void496 : Effect.fail(497 new Missed({498 reason: `exceptions or error-level lines since ${since}: ${logged.join(", ")}`,499 })500 );501 });502503const timed = <A>(504 probe: Probe,505 run: Effect.Effect<A, Missed, HttpClient.HttpClient>,506 settling: Duration.Input
20 unmodified lines
527 options: {528 readonly stage?: Stage;529 readonly settling?: Duration.Input;530 readonly web?: string;531 readonly logs?: LogsCheck;532 } = {}533): Effect.Effect<SmokeReport, SmokeFailed, HttpClient.HttpClient> =>534 Effect.gen(function* () {535 const settling = options.settling ?? SETTLING;
39 unmodified lines
575 ] as const,576 ([probe, run]) => timed(probe, run, settling)577 );578579 const { logs } = options;580581 const read =582 logs === undefined583 ? []584 : [585 yield* Effect.sleep(logs.ingestion ?? INGESTION).pipe(586 Effect.andThen(timed("worker-logs", workerLogs(logs), settling))587 ),588 ];589590 const runs: readonly {591 readonly probe: Probe;592 readonly elapsedMs: number;593 readonly outcome: Result.Result<unknown, Missed>;481 }[] = [first, ...rest];594 }[] = [first, ...rest, ...read];595596 const failures = runs.flatMap(({ outcome, probe }) =>597 Result.isFailure(outcome)598 ? [{ probe, reason: outcome.failure.reason }]
41 unmodified lines
640 return `no --url, and ${this.file} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${this.stage} first`;641 }642}643644export class BadSince extends Schema.TaggedError<BadSince>()("BadSince", {645 given: Schema.String,646}) {647 override get message() {648 return `--since ${this.given} is not an ISO 8601 instant, as 2026-10-13T12:00:00.000Z`;649 }650}651652export class NoLogCredentials extends Schema.TaggedError<NoLogCredentials>()(653 "NoLogCredentials",654 {}655) {656 override readonly message =657 "--since reads the stage's Workers Logs with infra's credentials, and CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN is not set: run smoke as the deploy does, through bunx varlock run --path infra/ --";658}659660const Credentials = Config.all({661 accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),662 token: Config.Redacted("CLOUDFLARE_API_TOKEN"),663});664665const decodeSince = Schema.decodeUnknownOption(Schema.DateTimeUtcFromString);666667const logsOf = (argv: readonly string[], stage: Stage) =>668 Option.match(flagValue(argv, "--since"), {669 onNone: () => Effect.succeedNone,670 onSome: (given) =>671 Effect.gen(function* () {672 const since = yield* Effect.fromOption(decodeSince(given)).pipe(673 Effect.mapError(() => new BadSince({ given }))674 );675676 const { accountId, token } = yield* Credentials.pipe(677 Effect.mapError(() => new NoLogCredentials())678 );679680 return Option.some({681 accountId,682 since,683 token,684 workers: workersOf(stage),685 } satisfies LogsCheck);686 }),687 });688689interface Origins {690 readonly platform: string;691 readonly web: Option.Option<string>;692}
23 unmodified lines
716export const main = (argv: readonly string[]) =>717 Effect.gen(function* () {718 const stage = yield* stageOf(argv);719 const origins = yield* originsOf(argv, stage);720 const logs = yield* logsOf(argv, stage);721722 yield* Console.log(723 `smoke ${stage}: ${origins.platform}${Option.match(origins.web, {724 onNone: () => "",725 onSome: (web) => ` and ${web}`,726 })}${Option.match(logs, {727 onNone: () => "",728 onSome: ({ since }) =>729 `, then its Workers' logs since ${DateTime.formatIso(since)}`,730 })}`731 );732733 const report = yield* smoke(origins.platform, {
1 unmodified line
735 ...Option.match(origins.web, {736 onNone: () => ({}),737 onSome: (web) => ({ web }),738 }),739 ...Option.match(logs, {740 onNone: () => ({}),741 onSome: (check) => ({ logs: check }),742 }),743 }).pipe(744 Effect.tapError(({ failures }) =>745 Effect.forEach(746 failures,
24 unmodified lines
modified:infra/stages.ts+6 added
63 unmodified lines
64 readonly oauth: string;65 readonly evidence: string;66 readonly releases: string;67 readonly codeCache: string;68 // Workers Analytics Engine's domain metrics: made by its first write, so69 // bootstrap makes none, and named with `_`, since SQL reads it as a table.70 // The platform's `METRICS` binding writes it, and the refusal alert71 // (`alerts.ts`) reads it.72 readonly metrics: string;73 readonly answer: string;74 readonly onPush: string;75}76
2 unmodified lines
79 codeCache: `code-cache-${stage}`,80 evidence: `evidence-${stage}`,81 frontPage: `front-page-${stage}`,82 layers: `layers-${stage}`,83 metrics: `metrics_${stage.replaceAll("-", "_")}`,84 oauth: `oauth-${stage}`,85 onPush: `on-push-${stage}`,86 platform: `platform-${stage}`,87 projects: `projects-${stage}`,
90 unmodified lines
added:packages/config/test/alerts.test.ts+229 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { MetricPoint } from "@repo/project/metrics";4import { dataPointOf } from "@repo/project/metrics/binding";5import { ProjectName } from "@repo/protocol/ids";6import { Duration, Effect, Option } from "effect";78import {9 alertKinds,10 alertLines,11 alerts,12 CONTAINER_FAILURES,13 Detection,14 REFUSED,15} from "../../../infra/alerts.ts";16import type { Alert } from "../../../infra/alerts.ts";17import { ERRORED, errorsQuery, workersOf } from "../../../infra/logs.ts";18import { resources, stages } from "../../../infra/stages.ts";19import { textOf } from "./root.ts";2021const ACCOUNT = "0123456789abcdef0123456789abcdef";2223const everyStage = stages.flatMap((stage) =>24 alerts(stage, ACCOUNT).map((alert) => ({ alert, stage }))25);2627// The one dataset a query reads: what follows its `FROM`.28const datasetOf = ({ query }: Alert) =>29 /\bFROM (?<dataset>\S+)/u.exec(query)?.groups?.dataset ?? "";3031describe("a stage's alerts", () => {32 it("watch each Worker for errors, and the stage for an issue spike, failing containers and a refusal spike", () => {33 expect(34 alerts("demo", ACCOUNT).map(({ kind, name }) => `${kind}: ${name}`)35 ).toStrictEqual([36 "errors: platform-demo errors",37 "errors: sandbox-demo errors",38 "errors: web-demo errors",39 "issue spike: demo issue spike",40 "container failures: demo container failures",41 "refusal spike: demo refusal spike",42 ]);43 expect(44 stages.map((stage) =>45 [...new Set(alerts(stage, ACCOUNT).map(({ kind }) => kind))].join(",")46 )47 ).toStrictEqual(stages.map(() => alertKinds.join(",")));48 });4950 it("ask what a custom alert's SQL must: one numeric `value` from one dataset, the account named, no time filter and no trailing semicolon", () => {51 expect(52 everyStage.flatMap(({ alert, stage }) => {53 const { query } = alert;5455 const kept =56 query.startsWith("SELECT count() AS value FROM ") &&57 query.includes(`accountTag = '${ACCOUNT}'`) &&58 !query.includes("timestamp") &&59 !query.trimEnd().endsWith(";") &&60 query.split(/\bFROM\b/u).length === 2;6162 return kept ? [] : [`${stage}: ${alert.name}`];63 })64 ).toStrictEqual([]);65 });6667 it("read the Workers Logs, Issues and metrics of their own stage alone, never a layer's or another stage's", () => {68 expect(69 everyStage.flatMap(({ alert, stage }) => {70 const others = stages.flatMap((other) =>71 other === stage ? [] : [...workersOf(other), resources(other).metrics]72 );7374 // A name in the SQL is a quoted string or a quoted dataset.75 const strays = [resources(stage).layers, ...others].filter(76 (name) =>77 alert.query.includes(`'${name}'`) ||78 alert.query.includes(`"${name}"`)79 );8081 return strays.length === 082 ? []83 : [`${alert.name}: ${strays.join(",")}`];84 })85 ).toStrictEqual([]);86 expect(alerts("prod", ACCOUNT).map(datasetOf)).toStrictEqual([87 "logs.workersLogs",88 "logs.workersLogs",89 "logs.workersLogs",90 "logs.issues",91 "logs.workersLogs",92 'events.analyticsEngine."metrics_prod"',93 ]);94 });9596 it("count an error as smoke does: the Worker alerts and smoke's logs check share one predicate", () => {97 const workerAlerts = alerts("dev-oscabriel", ACCOUNT).filter(98 ({ kind }) => kind === "errors"99 );100101 expect({102 alerts: workerAlerts.map(({ query }) => query.endsWith(ERRORED)),103 smoke: errorsQuery(workersOf("dev-oscabriel")).includes(ERRORED),104 }).toStrictEqual({ alerts: [true, true, true], smoke: true });105 });106107 it("read refusals from the stage's metrics dataset, the one its platform's `METRICS` binding writes", () => {108 expect(109 stages.map((stage) =>110 alerts(stage, ACCOUNT)111 .filter(({ kind }) => kind === "refusal spike")112 .map(datasetOf)113 )114 ).toStrictEqual(115 stages.map((stage) => [116 `events.analyticsEngine."${resources(stage).metrics}"`,117 ])118 );119 });120121 it("count a refusal as the platform's writer lays it out: a row whose first blob is a Refused point's kind", () => {122 const { blobs } = dataPointOf(123 MetricPoint.cases.Refused.make({124 project: ProjectName.make("alice/datekit"),125 stage: "shape",126 tag: "OutOfScope",127 })128 );129130 expect(REFUSED).toBe(`blob1 = '${blobs[0] ?? ""}'`);131 });132133 it("give each anomaly a baseline of at least six windows and at most a day, over a window of at least a minute", () => {134 expect(135 everyStage.flatMap(({ alert }) => {136 const baselined = Detection.$match(alert.detection, {137 Spike: ({ baseline }) =>138 Duration.isGreaterThanOrEqualTo(139 baseline,140 Duration.times(alert.window, 6)141 ) && Duration.isLessThanOrEqualTo(baseline, Duration.hours(24)),142 Threshold: () => true,143 });144145 return baselined &&146 Duration.isGreaterThanOrEqualTo(alert.window, Duration.minutes(1))147 ? []148 : [alert.name];149 })150 ).toStrictEqual([]);151 });152});153154describe("the container failures they watch for", () => {155 it.effect(156 "are the lines the apps log at error level when a sandbox job's container never answered",157 () =>158 Effect.gen(function* () {159 const sources = yield* Effect.forEach(160 [161 "apps/platform/src/adapters/sandbox-credentials.ts",162 "apps/sandbox/src/checker.ts",163 ],164 textOf165 );166167 const text = sources.flatMap(Option.toArray).join("\n");168169 expect(170 CONTAINER_FAILURES.map((line) => ({171 line,172 logged: text.includes(`Effect.logError("${line}")`),173 }))174 ).toStrictEqual(175 CONTAINER_FAILURES.map((line) => ({ line, logged: true }))176 );177 }).pipe(Effect.provide(NodeServices.layer))178 );179});180181describe("what bootstrap prints of them", () => {182 it("says they are made by hand, and gives each one's detection and SQL for the dashboard", () => {183 const lines = alertLines(184 "demo",185 alerts("demo", ACCOUNT).filter(({ kind }) => kind !== "errors"),186 true187 );188189 expect(lines).toStrictEqual([190 "bootstrap demo: make these 3 alerts by hand, as Custom Alerts in the dashboard: no API takes a custom alert's query yet (README, Alerts)",191 "bootstrap demo: each is custom SQL with an Automatic time range, sent to ALERT_EMAIL's address",192 " demo issue spike: anomaly detection on spikes, evaluation window 10m, baseline window 2h, sensitivity 3, minimum event count 3",193 ` SELECT count() AS value FROM logs.issues WHERE accountTag = '${ACCOUNT}' AND scriptName IN ('platform-demo', 'sandbox-demo', 'web-demo')`,194 " demo container failures: threshold, value >= 3, evaluation window 30m",195 ` SELECT count() AS value FROM logs.workersLogs WHERE accountTag = '${ACCOUNT}' AND scriptName IN ('platform-demo', 'sandbox-demo') AND level = 'error' AND (message LIKE '%sandbox job blocked%' OR message LIKE '%the Checker could not be reached%')`,196 " demo refusal spike: anomaly detection on spikes, evaluation window 15m, baseline window 6h, sensitivity 3, minimum event count 5",197 ` SELECT count() AS value FROM events.analyticsEngine."metrics_demo" WHERE accountTag = '${ACCOUNT}' AND blob1 = 'Refused'`,198 ]);199 });200201 it("names where they go without showing it, and says when it is not set", () => {202 const [, set] = alertLines("prod", alerts("prod", ACCOUNT), true);203 const [, unset] = alertLines("prod", alerts("prod", ACCOUNT), false);204205 expect({ set, unset }).toStrictEqual({206 set: "bootstrap prod: each is custom SQL with an Automatic time range, sent to ALERT_EMAIL's address",207 unset:208 "bootstrap prod: each is custom SQL with an Automatic time range, sent to ALERT_EMAIL's address, which infra/.env.local does not set yet",209 });210 });211});212213describe("the README", () => {214 it.effect("tells a person how to make every kind of alert by hand", () =>215 Effect.gen(function* () {216 const readme = Option.getOrElse(yield* textOf("README.md"), () => "");217 const start = readme.indexOf("### Alerts");218 const end = readme.indexOf("\n## ", start);219 const section = start === -1 ? "" : readme.slice(start, end);220221 expect({222 dryRun: section.includes(223 "bun run bootstrap -- --stage <stage> --dry-run"224 ),225 kinds: alertKinds.filter((kind) => !section.includes(`**${kind}**`)),226 }).toStrictEqual({ dryRun: true, kinds: [] });227 }).pipe(Effect.provide(NodeServices.layer))228 );229});
modified:packages/config/test/bootstrap.test.ts+5 added
32 unmodified lines
33 return yield* fs.readFileString(path.join(yield* repoRoot, file));34 }).pipe(Effect.provide(NodeServices.layer));3536const PlatformStage = Schema.Struct({37 analytics_engine_datasets: Schema.Tuple([38 Schema.Struct({ dataset: Schema.String }),39 ]),40 artifacts: Schema.Array(41 Schema.Struct({ binding: Schema.String, namespace: Schema.String })42 ),43 d1_databases: Schema.Tuple([
80 unmodified lines
124 const names = resources(stage);125126 return {127 frontPage: names.frontPage,128 metrics: names.metrics,129 namespaces: [names.projects, names.layers],130 onPush: [names.onPush, names.onPush],131 platform: names.platform,132 projects: [names.projects, names.projects],
7 unmodified lines
140 const block = platform.env[stage];141142 return {143 frontPage: block?.d1_databases[0].database_name,144 metrics: block?.analytics_engine_datasets[0].dataset,145 namespaces: block?.artifacts.map(({ namespace }) => namespace),146 onPush: [147 block?.triggers.events[0].targets[0].workflow_name,148 block?.workflows.find(({ binding }) => binding === "ON_PUSH")
437 unmodified lines
modified:packages/config/test/deploy.test.ts+53 added-4 removed
2 unmodified lines
3import { Brand } from "@repo/brand";4import {5 Console,6 ConfigProvider,7 DateTime,8 Effect,9 FileSystem,10 Layer,11 Option,12 Path,13 Ref,14 Result,15 Schema,16 Sink,17 Stream,18} from "effect";19import { ChildProcess, ChildProcessSpawner } from "effect/process";
11 unmodified lines
31 readonly command: string;32 readonly args: readonly string[];33 readonly cwd: string;34 readonly env: Readonly<Record<string, string | undefined>>;35 // When it was spawned, in epoch milliseconds.36 readonly at: number;37}3839const recording = (exitOf: (spawned: Spawned) => number) =>40 Effect.gen(function* () {
8 unmodified lines
49 }5051 const call: Spawned = {52 args: command.args,53 at: DateTime.toEpochMillis(yield* DateTime.now),54 command: path.basename(command.command),55 cwd: path.relative(root, command.options.cwd ?? root),56 env: command.options.env ?? {},57 };
54 unmodified lines
112113 return { result, spawned: yield* fake.spawned };114 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));115116// The instant smoke reads the logs since is the run's own, so a line shows117// where it goes; "hands smoke the instant…" holds its value.118const line = ({ args, command, cwd }: Spawned) =>111 `${cwd === "" ? "." : cwd}$ ${[command, ...args].join(" ")}`;119 `${cwd === "" ? "." : cwd}$ ${[120 command,121 ...args.map((arg, index) =>122 args[index - 1] === "--since" ? "<since>" : arg123 ),124 ].join(" ")}`;125126describe("a deploy without a known stage", () => {127 it.live(128 "fails with NoStage and spawns nothing when no --stage is given",
41 unmodified lines
170 "apps/platform$ varlock-wrangler deploy --env dev-oscabriel",171 "apps/web$ bun run build",172 "apps/web$ wrangler deploy --env dev-oscabriel",173 ".$ bun run bootstrap --stage dev-oscabriel --check-triggers",161 ".$ bun scripts/smoke.ts --stage dev-oscabriel",174 ".$ varlock run --path infra/ -- bun scripts/smoke.ts --stage dev-oscabriel --since <since>",175 ]);176 })177 );178
68 unmodified lines
247 expect(spawned).toHaveLength(7);248 })249 );250251 it.live(252 "hands smoke the instant the first upload began, after verify, so an error the replaced version logged during verify never fails it",253 () =>254 Effect.gen(function* () {255 const { result, spawned } = yield* run(["--stage", "dev-oscabriel"]);256 const [verify, sandbox] = spawned;257 const smoke = spawned.at(-1);258259 const since = Option.map(260 Schema.decodeUnknownOption(Schema.DateTimeUtcFromString)(261 smoke?.args.at(-1)262 ),263 DateTime.toEpochMillis264 );265266 expect(Result.isSuccess(result)).toBeTruthy();267 expect({268 flag: smoke?.args.at(-2),269 since: Option.isSome(since),270 verifiedFirst: Option.exists(271 since,272 (at) => (verify?.at ?? Infinity) <= at273 ),274 withTheUpload: Option.exists(275 since,276 (at) => at <= (sandbox?.at ?? -Infinity)277 ),278 }).toStrictEqual({279 flag: "--since",280 since: true,281 verifiedFirst: true,282 withTheUpload: true,283 });284 })285 );286287 it.live("turns Wrangler's metrics off in every command it spawns", () =>288 Effect.gen(function* () {289 const { spawned } = yield* run(["--stage", "dev-oscabriel"]);290
188 unmodified lines
479 "apps/platform$ varlock-wrangler deploy --env demo",480 "apps/web$ bun run build",481 "apps/web$ wrangler deploy --env demo",482 ".$ bun run bootstrap --stage demo --check-triggers",434 ".$ bun scripts/smoke.ts --stage demo",483 ".$ varlock run --path infra/ -- bun scripts/smoke.ts --stage demo --since <since>",484 ]);485 expect(486 spawned.map(({ env }) =>487 ["MASTER_KEY", "OPERATOR_TOKEN"].filter((name) => name in env)
26 unmodified lines
514 `apps/platform$ varlock-wrangler deploy --env prod --domain ${git} --var PUBLIC_WEB_URL:https://${Brand.domain}`,515 "apps/web$ bun run build",516 `apps/web$ wrangler deploy --env prod --domain ${Brand.domain} --domain www.${Brand.domain} --var PUBLIC_PLATFORM_URL:https://${git}`,517 ".$ bun run bootstrap --stage prod --check-triggers",469 ".$ bun scripts/smoke.ts --stage prod",518 ".$ varlock run --path infra/ -- bun scripts/smoke.ts --stage prod --since <since>",519 ]);520 })521 );522
22 unmodified lines
added:packages/config/test/observability.test.ts+194 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Effect, FileSystem, Path, Schema } from "effect";45import { blankJsonc } from "../../../infra/jsonc.ts";6import { stages } from "../../../infra/stages.ts";7import { repoRoot } from "./root.ts";89const WORKERS = ["platform", "sandbox", "web"] as const;1011type Worker = (typeof WORKERS)[number];1213const Container = Schema.Struct({14 class_name: Schema.String,15 observability: Schema.optionalKey(Schema.Unknown),16});1718const Block = Schema.Struct({19 containers: Schema.optionalKey(Schema.Array(Container)),20 observability: Schema.optionalKey(Schema.Unknown),21 upload_source_maps: Schema.optionalKey(Schema.Boolean),22});2324type Block = typeof Block.Type;2526const Wrangler = Schema.fromJsonString(27 Schema.Struct({28 ...Block.fields,29 env: Schema.Record(Schema.String, Block),30 })31);3233// What a Worker keeps of each invocation: its logs, its own line among them,34// and its Issues, none sampled away and none left unkept.35const Recorded = Schema.Struct({36 enabled: Schema.Literal(true),37 issues: Schema.Struct({ enabled: Schema.Literal(true) }),38 logs: Schema.Struct({39 enabled: Schema.Literal(true),40 head_sampling_rate: Schema.Literal(1),41 invocation_logs: Schema.Literal(true),42 persist: Schema.optionalKey(Schema.Literal(true)),43 }),44});4546const isRecorded = Schema.is(Recorded);4748// Its trace: every invocation's, kept in the account.49const unsampled = {50 enabled: Schema.Literal(true),51 head_sampling_rate: Schema.Literal(1),52 persist: Schema.optionalKey(Schema.Literal(true)),53};5455const Traces = {56 // Sent nowhere: a destination would take it out of the account.57 kept: Schema.Struct({58 traces: Schema.Struct({59 ...unsampled,60 destinations: Schema.optionalKey(Schema.Never),61 }),62 }),63 unsampled: Schema.Struct({ traces: Schema.Struct(unsampled) }),64};6566// The runtime's own spans record each Durable Object SQL statement's bound67// values and each fetch's full URL, so the platform's traces hold layer68// names and repos and sealed values. The maintainer keeps them, in the69// account's own trace store alone (principle 7).70const TRACING: Readonly<Record<Worker, keyof typeof Traces>> = {71 platform: "kept",72 sandbox: "unsampled",73 web: "unsampled",74};7576const LOCAL = "local";7778/** The top level is stage `local`, never deployed; each deployed stage is an `env` block. */79const named = [LOCAL, ...stages] as const;8081interface Staged {82 readonly worker: Worker;83 readonly stage: (typeof named)[number];84 readonly top: Block;85 readonly block: Block | undefined;86}8788const wranglerOf = (worker: Worker) =>89 Effect.gen(function* () {90 const fs = yield* FileSystem.FileSystem;91 const path = yield* Path.Path;92 const file = path.join(yield* repoRoot, `apps/${worker}/wrangler.jsonc`);93 const text = yield* fs.readFileString(file);9495 return yield* Schema.decodeEffect(Wrangler)(blankJsonc(text));96 });9798const everyStage = Effect.map(99 Effect.forEach(WORKERS, (worker) =>100 Effect.map(wranglerOf(worker), (top) =>101 named.map((stage): Staged => ({102 block: stage === LOCAL ? top : top.env[stage],103 stage,104 top,105 worker,106 }))107 )108 ),109 (all) => all.flat()110).pipe(Effect.provide(NodeServices.layer));111112// Wrangler gives a stage the top level's `observability` and113// `upload_source_maps` unless the stage sets its own, but never its114// `containers`: a stage without them declares none.115const inherited = <K extends "observability" | "upload_source_maps">(116 { block, top }: Staged,117 key: K118) => block?.[key] ?? top[key];119120const each = <A>(all: readonly Staged[], read: (staged: Staged) => A) =>121 Object.fromEntries(122 all.map((staged) => [`${staged.worker} ${staged.stage}`, read(staged)])123 );124125describe("every Worker, in every stage", () => {126 it.effect("logs each invocation and reports its Issues, unsampled", () =>127 Effect.gen(function* () {128 const all = yield* everyStage;129130 expect(131 each(all, (staged) => isRecorded(inherited(staged, "observability")))132 ).toStrictEqual(each(all, () => true));133 })134 );135136 it.effect(137 "traces each invocation, unsampled, and sends the platform's nowhere",138 () =>139 Effect.gen(function* () {140 const all = yield* everyStage;141142 expect(143 each(all, (staged) =>144 Schema.is(Traces[TRACING[staged.worker]])(145 inherited(staged, "observability")146 )147 )148 ).toStrictEqual(each(all, () => true));149 })150 );151152 it.effect(153 "uploads its source maps, so an uncaught exception's stack names the source",154 () =>155 Effect.gen(function* () {156 const all = yield* everyStage;157158 expect(159 each(all, (staged) => inherited(staged, "upload_source_maps"))160 ).toStrictEqual(each(all, () => true));161 })162 );163});164165// A held-back check's sealed files and output are in a Checker's container,166// so its own logs stay off (principle 7). Every container says what it keeps:167// one that leaves `observability` out keeps what its application last had.168describe("every container, in every stage", () => {169 it.effect(170 "is a Checker with its logs off or a Lander with them on, set in the stage itself",171 () =>172 Effect.gen(function* () {173 const all = yield* everyStage;174175 const declared = Object.fromEntries(176 all.flatMap(({ block, stage, worker }) =>177 (block?.containers ?? []).map(178 ({ class_name, observability }) =>179 [`${worker} ${stage} ${class_name}`, observability] as const180 )181 )182 );183184 expect(declared).toStrictEqual(185 Object.fromEntries(186 named.flatMap((stage) => [187 [`sandbox ${stage} Checker`, { enabled: false }],188 [`sandbox ${stage} Lander`, { enabled: true }],189 ])190 )191 );192 })193 );194});
modified:packages/config/test/recording.test.ts+5 added-2 removed
150 unmodified lines
151 yield* tempLock152 );153154 expect(Result.isSuccess(result)).toBeTruthy();155 // The instant smoke reads the logs since is the run's own.156 expect(157 spawned.map((line) => line.replace(/--since \S+$/u, "--since <since>"))155 expect(spawned).toStrictEqual([158 ).toStrictEqual([159 ".$ bun run verify",160 "apps/sandbox$ wrangler deploy --env dev-oscabriel",161 "apps/platform$ varlock-wrangler deploy --env dev-oscabriel",162 "apps/web$ bun run build",163 "apps/web$ wrangler deploy --env dev-oscabriel",164 ".$ bun run bootstrap --stage dev-oscabriel --check-triggers",162 ".$ bun scripts/smoke.ts --stage dev-oscabriel",165 ".$ varlock run --path infra/ -- bun scripts/smoke.ts --stage dev-oscabriel --since <since>",166 ]);167 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))168 );169});
56 unmodified lines
modified:packages/config/test/smoke.test.ts+268 added-1 removed
1import { NodeHttpServer, NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Context, Effect, Layer, Option, Result, Schema } from "effect";3import {4 ConfigProvider,5 Context,6 DateTime,7 Effect,8 Layer,9 Option,10 Redacted,11 Result,12 Schema,13} from "effect";14import {15 FetchHttpClient,16 HttpServer,17 HttpServerRequest,18 HttpServerResponse,19} from "effect/http";2021import { workersOf } from "../../../infra/logs.ts";22import { AGENT_BUDGET_MS, agentProbes } from "../../../infra/smoke.ts";23import { NoStage, UnknownStage } from "../../../infra/stages.ts";24import {25 BadSince,26 logProbes,27 main,28 NoLogCredentials,29 NoOrigin,30 platformProbes,31 probes,32 smoke,33 SmokeFailed,34 webProbes,35} from "../../../scripts/smoke.ts";36import type { LogsCheck } from "../../../scripts/smoke.ts";3738interface Reply {39 readonly status: number;40 readonly body?: string;
4 unmodified lines
45interface Seen {46 readonly method: string;47 readonly path: string;48 readonly authorized: boolean;49 readonly authorization: string;50 readonly body: string;51}5253const ListAsksCall = Schema.fromJsonString(
87 unmodified lines
141 const request = yield* HttpServerRequest.HttpServerRequest;142 const url = new URL(request.url, "http://localhost");143144 const reply = answer({145 authorization: request.headers.authorization ?? "",146 authorized: request.headers.authorization !== undefined,147 body: yield* Effect.orDie(request.text),148 method: request.method,149 path: url.pathname,
486 unmodified lines
636 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))637 );638});639640// A SQL API answer, as seen live: rows, their count and the scan's statistics.641const rowsOf = (642 data: readonly { readonly scriptName: string; readonly errors: number }[]643): Reply => ({644 body: JSON.stringify({645 data,646 rows: data.length,647 statistics: { bytes_read: 0, elapsed_ms: 24, rows_read: 0 },648 }),649 status: 200,650});651652const ACCOUNT = "0123456789abcdef0123456789abcdef";653654const SINCE = "2026-10-13T12:00:00.000Z";655656const checkAt = (sql: string): LogsCheck => ({657 accountId: ACCOUNT,658 api: `${sql}/analytics/sql`,659 ingestion: 0,660 since: DateTime.makeUnsafe(SINCE),661 token: Redacted.make("token-from-infra-env"),662 workers: workersOf("dev-oscabriel"),663});664665// Only what the test sets, whatever the shell running the tests has.666const withEnv = (env: Readonly<Record<string, string>>) =>667 Effect.provideService(668 ConfigProvider.ConfigProvider,669 ConfigProvider.fromEnv({ env })670 );671672const logsFailures = (result: Result.Result<unknown, SmokeFailed>) =>673 Result.isFailure(result)674 ? result.failure.failures.filter(({ probe }) => probe === "worker-logs")675 : [];676677describe("smoke reads the stage's logs after a deploy", () => {678 it.live(679 "asks the SQL API, after every probe, for each of the stage's Workers' errors since the deploy began, and passes when there are none",680 () =>681 Effect.gen(function* () {682 const asked: string[] = [];683 const read: Seen[] = [];684685 const origin = yield* fakePlatform((seen) => {686 asked.push(`platform ${seen.path}`);687688 return healthy(seen);689 });690691 const sql = yield* fakePlatform((seen) => {692 asked.push(`sql ${seen.path}`);693 read.push(seen);694695 return rowsOf([]);696 });697698 const report = yield* smoke(origin, { logs: checkAt(sql) });699700 expect({701 last: asked.at(-1),702 probes: report.probes.map(({ probe }) => probe),703 read: read.map(({ authorization, body, method, path }) => ({704 authorization,705 body,706 method,707 path,708 })),709 }).toStrictEqual({710 last: "sql /analytics/sql",711 probes: [...platformProbes, ...logProbes],712 read: [713 {714 authorization: "Bearer token-from-infra-env",715 body: JSON.stringify({716 query:717 "SELECT scriptName, count() AS errors FROM logs.workersLogs WHERE scriptName IN ('platform-dev-oscabriel', 'sandbox-dev-oscabriel', 'web-dev-oscabriel') AND (level = 'error' OR error != '') GROUP BY scriptName",718 scope: { accountTag: ACCOUNT },719 time_range: { start: SINCE },720 }),721 method: "POST",722 path: "/analytics/sql",723 },724 ],725 });726 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))727 );728729 it.live("fails naming each Worker that logged an error, and how many", () =>730 Effect.gen(function* () {731 const origin = yield* fakePlatform(healthy);732733 const sql = yield* fakePlatform(() =>734 rowsOf([735 { errors: 1, scriptName: "web-dev-oscabriel" },736 { errors: 3, scriptName: "platform-dev-oscabriel" },737 ])738 );739740 const result = yield* Effect.result(741 smoke(origin, { logs: checkAt(sql) })742 );743744 expect(745 Result.isFailure(result) ? result.failure.failures : []746 ).toStrictEqual([747 {748 probe: "worker-logs",749 reason: `exceptions or error-level lines since ${SINCE}: platform-dev-oscabriel 3, web-dev-oscabriel 1`,750 },751 ]);752 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))753 );754755 // Each as the live API answered it: a token it can't authenticate, one756 // without the permission, and one that can't see the account.757 it.live.each([758 {759 body: '{"success":false,"errors":[{"code":9106,"message":"Authentication failed (status: 400)"}],"messages":[],"result":null}',760 status: 400,761 },762 { body: "Forbidden", status: 403 },763 {764 body: "Input was invalid: The account or zone tag is invalid or unknown",765 status: 422,766 },767 ])(768 "names the permission it needs when the API answers $status to infra's token",769 ({ body, status }) =>770 Effect.gen(function* () {771 const origin = yield* fakePlatform(healthy);772773 const sql = yield* fakePlatform(() => ({774 body,775 contentType: "text/plain",776 status,777 }));778779 const result = yield* Effect.result(780 smoke(origin, { logs: checkAt(sql) })781 );782783 expect(logsFailures(result)).toStrictEqual([784 {785 probe: "worker-logs",786 reason: `POST /analytics/sql for the stage's Workers Logs answered ${status}: CLOUDFLARE_API_TOKEN needs Account › Account Analytics › Read on the account CLOUDFLARE_ACCOUNT_ID names`,787 },788 ]);789 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))790 );791792 it.live("names the API's own words for a query it can't run", () =>793 Effect.gen(function* () {794 const origin = yield* fakePlatform(healthy);795796 const sql = yield* fakePlatform(() => ({797 body: "Input was invalid: Schema error: No field named level.\nValid fields are …",798 contentType: "text/plain",799 status: 422,800 }));801802 const result = yield* Effect.result(803 smoke(origin, { logs: checkAt(sql) })804 );805806 expect(logsFailures(result)).toStrictEqual([807 {808 probe: "worker-logs",809 reason:810 "POST /analytics/sql for the stage's Workers Logs answered 422: Input was invalid: Schema error: No field named level.",811 },812 ]);813 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))814 );815816 it.live(817 "asks again while the SQL API answers with a server error, and passes once it settles",818 () =>819 Effect.gen(function* () {820 const origin = yield* fakePlatform(healthy);821 const asked = { sql: 0 };822823 const sql = yield* fakePlatform(() => {824 asked.sql += 1;825826 return asked.sql === 1 ? { status: 503 } : rowsOf([]);827 });828829 const report = yield* smoke(origin, {830 logs: checkAt(sql),831 settling: "10 seconds",832 });833834 expect({835 asked,836 probes: report.probes.map(({ probe }) => probe),837 }).toStrictEqual({838 asked: { sql: 2 },839 probes: [...platformProbes, ...logProbes],840 });841 }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer))842 );843});844845describe("the smoke command", () => {846 it.live("refuses without a stage it knows, before it probes anything", () =>847 Effect.gen(function* () {848 const seen: string[] = [];
53 unmodified lines
902 );903 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))904 );905906 it.live(907 "refuses --since without infra's credentials, or with an instant it can't read, before it probes anything",908 () =>909 Effect.gen(function* () {910 const seen: string[] = [];911912 const origin = yield* fakePlatform((request) => {913 seen.push(request.path);914915 return healthy(request);916 });917918 const argv = ["--stage", "dev-oscabriel", "--url", origin];919920 expect({921 bad: yield* Effect.flip(922 main([...argv, "--since", "yesterday"]).pipe(923 withEnv({924 CLOUDFLARE_ACCOUNT_ID: ACCOUNT,925 CLOUDFLARE_API_TOKEN: "token-from-infra-env",926 })927 )928 ),929 bare: yield* Effect.flip(930 main([...argv, "--since", SINCE]).pipe(withEnv({}))931 ),932 seen,933 }).toStrictEqual({934 bad: new BadSince({ given: "yesterday" }),935 bare: new NoLogCredentials(),936 seen: [],937 });938 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))939 );940941 it("says what --since needs, naming infra's credentials and never a value", () => {942 expect({943 bad: new BadSince({ given: "yesterday" }).message,944 bare: new NoLogCredentials().message,945 }).toStrictEqual({946 bad: "--since yesterday is not an ISO 8601 instant, as 2026-10-13T12:00:00.000Z",947 bare: "--since reads the stage's Workers Logs with infra's credentials, and CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN is not set: run smoke as the deploy does, through bunx varlock run --path infra/ --",948 });949 });950951 it("says to bootstrap first when neither --url nor bootstrap's record names the origin", () => {952 const failed = new NoOrigin({953 file: "infra/workers-dev.json",954 stage: "demo",
7 unmodified lines
modified:packages/gate/src/gate.ts+31 added-10 removed
1/**2 * Stops after the first stage that refuses, so a push never pays for a stage3 * past its cheapest problem.4 */5import type { StageName } from "@repo/protocol/domain/outcome";6import type { Refusal } from "@repo/protocol/refusal";7import { Array, Effect, Option } from "effect";89import type { PushFacts } from "./facts.ts";10import type { Stage } from "./stage.ts";11import { parse } from "./stages/parse.ts";12import { scan } from "./stages/shape.ts";1314/** What the first stage that refused a push refused it for. */15export interface StageRefusal {16 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;17 readonly stage: StageName;18}1913export const runGate = <R>(20export const refusingStage = <R>(21 stages: readonly Stage<R>[],22 facts: PushFacts16): Effect.Effect<17 Option.Option<Array.NonEmptyReadonlyArray<Refusal>>,18 never,19 R20> =>23): Effect.Effect<Option.Option<StageRefusal>, never, R> =>24 Effect.gen(function* () {25 for (const stage of stages) {23 const refusals = yield* stage.run(facts);26 const refusals = yield* stage27 .run(facts)28 .pipe(Effect.withSpan(`Gate.${stage.name}`));2930 if (Array.isReadonlyArrayNonEmpty(refusals)) {26 return Option.some(27 stage.accumulate ? refusals : Array.of(Array.headNonEmpty(refusals))28 );31 return Option.some({32 refusals: stage.accumulate33 ? refusals34 : Array.of(Array.headNonEmpty(refusals)),35 stage: stage.name,36 });37 }38 }3940 return Option.none();41 });4243export const runGate = <R>(44 stages: readonly Stage<R>[],45 facts: PushFacts46): Effect.Effect<47 Option.Option<Array.NonEmptyReadonlyArray<Refusal>>,48 never,49 R50> =>51 Effect.map(52 refusingStage(stages, facts),53 Option.map(({ refusals }) => refusals)54 );5556export const pushStages: readonly Stage<never>[] = [parse, scan];
modified:packages/gate/test/gate.test.ts+49 added-1 removed
2 unmodified lines
3import { NotClaimed, OutOfScope, TouchedJudge } from "@repo/protocol/refusal";4import type { Refusal } from "@repo/protocol/refusal";5import { Effect, Option } from "effect";67import { pushStages, runGate } from "../src/gate.ts";7import { pushStages, refusingStage, runGate } from "../src/gate.ts";8import type { Stage } from "../src/stage.ts";9import { ask, modified, testFacts, wire } from "./facts.ts";1011const wired = (answer: Option.Option<readonly Refusal[]>) =>
77 unmodified lines
89 expect(wired(answer)).toStrictEqual(Option.some(wire([outside, judged])));90 })91 );92});9394describe(refusingStage, () => {95 it.effect("names parse when parse refuses the push", () =>96 Effect.gen(function* () {97 const refused = yield* refusingStage(98 pushStages,99 testFacts({100 changes: modified("docs/guide.md"),101 claim: Option.none(),102 })103 );104105 expect(Option.map(refused, ({ stage }) => stage)).toStrictEqual(106 Option.some("parse")107 );108 })109 );110111 it.effect(112 "names shape, with every refusal it gave, when parse lets the push through",113 () =>114 Effect.gen(function* () {115 const refused = yield* refusingStage(116 pushStages,117 testFacts({118 changes: modified("docs/guide.md", ".github/workflows/ci.yml"),119 })120 );121122 expect(123 Option.map(refused, ({ refusals, stage }) => ({124 refusals: wire(refusals),125 stage,126 }))127 ).toStrictEqual(128 Option.some({ refusals: wire([outside, judged]), stage: "shape" })129 );130 })131 );132133 it.effect("names no stage when every stage lets the push through", () =>134 Effect.gen(function* () {135 expect(yield* refusingStage(pushStages, testFacts())).toStrictEqual(136 Option.none()137 );138 })139 );140});
added:packages/project/src/metrics/binding.ts+85 added
1/**2 * Workers Analytics Engine: one row per point in the stage's own dataset,3 * sampled by project. A query reads a point by its columns:4 *5 * | point | blob1 | blob2 | blob3 | blob4 | double1 | double2 |6 * | -------------- | -------------- | --------------- | ------- | ----- | ------------ | ---------- |7 * | `Landed` | `Landed` | | | | 1 | |8 * | `Refused` | `Refused` | the refusal tag | stage | area | 1 | |9 * | `LaneRan` | `LaneRan` | lane | result | | `durationMs` | |10 * | `ChecksWaited` | `ChecksWaited` | | | | `waitedMs` | |11 * | `Drafted` | `Drafted` | ready or failed | | | `latencyMs` | `attempts` |12 *13 * `index1` is the project's name, cut to the 96 bytes an index holds.14 */15import { Data, Effect, Layer } from "effect";1617import { MetricPoint, Metrics } from "../metrics.ts";1819/** Mutable arrays, as the binding's own type takes them. */20export interface DataPoint {21 readonly blobs: string[];22 readonly doubles: number[];23 readonly indexes: string[];24}2526/** Structural, so the package needs no Workers types. */27export interface DatasetLike {28 readonly writeDataPoint: (point: DataPoint) => void;29}3031/** A project's name is ASCII, so its first 96 characters are its first 96 bytes. */32const INDEX_BYTES = 96;3334const columns = (35 blobs: readonly string[],36 doubles: readonly number[]37): Pick<DataPoint, "blobs" | "doubles"> => ({38 blobs: [...blobs],39 doubles: [...doubles],40});4142export const dataPointOf = (point: MetricPoint): DataPoint => {43 const { blobs, doubles } = MetricPoint.match(point, {44 ChecksWaited: ({ waitedMs }) => columns([], [waitedMs]),45 Drafted: ({ attempts, latencyMs, ready }) =>46 columns([ready ? "ready" : "failed"], [latencyMs, attempts]),47 Landed: () => columns([], [1]),48 LaneRan: ({ durationMs, lane, result }) =>49 columns([lane, result], [durationMs]),50 Refused: ({ area, stage, tag }) => columns([tag, stage, area ?? ""], [1]),51 });5253 return {54 blobs: [point._tag, ...blobs],55 doubles,56 indexes: [point.project.slice(0, INDEX_BYTES)],57 };58};5960class MetricRefused extends Data.TaggedError("MetricRefused")<{61 readonly cause: unknown;62}> {}6364export const MetricsBinding = (dataset: DatasetLike) =>65 Layer.succeed(Metrics, {66 write: (points) =>67 Effect.forEach(68 points,69 (point) =>70 Effect.try({71 catch: (cause) => new MetricRefused({ cause }),72 try: () => {73 dataset.writeDataPoint(dataPointOf(point));74 },75 }).pipe(76 Effect.catchTag("MetricRefused", ({ cause }) =>77 Effect.logWarning(78 `the metrics dataset refused a ${point._tag} point`,79 cause80 )81 )82 ),83 { discard: true }84 ),85 });
added:packages/project/src/metrics/memory.ts+20 added
1import { Context, Effect, Layer, Ref } from "effect";23import { Metrics } from "../metrics.ts";4import type { MetricPoint } from "../metrics.ts";56export class MetricsWritten extends Context.Service<7 MetricsWritten,8 { readonly points: Effect.Effect<readonly MetricPoint[]> }9>()("project/MetricsWritten") {}1011/** Keeps every point in the order it was written. */12export const MetricsMemory = Layer.effectContext(13 Effect.gen(function* () {14 const written = yield* Ref.make<readonly MetricPoint[]>([]);1516 return Context.make(Metrics, {17 write: (points) => Ref.update(written, (kept) => [...kept, ...points]),18 }).pipe(Context.add(MetricsWritten, { points: Ref.get(written) }));19 })20);
modified:packages/project/src/project-store/memory.ts+12 added-6 removed
157 unmodified lines
158 });159160 return ProjectStore.of({161 ackOutbox: (ids) =>162 SynchronizedRef.update(ref, (state) => {162 SynchronizedRef.modify(ref, (state) => {163 const kept = new Map(rowsIn(state, Tables.outbox));164 const taken: string[] = [];165166 for (const id of ids) {166 kept.delete(keyOf(Tables.outbox, { id }));167 if (kept.delete(keyOf(Tables.outbox, { id }))) {168 taken.push(id);169 }170 }171169 return {170 ...state,171 tables: new Map(state.tables).set(Tables.outbox.name, kept),172 };172 return [173 taken,174 {175 ...state,176 tables: new Map(state.tables).set(Tables.outbox.name, kept),177 },178 ] as const;179 }),180 commit: (writes) =>181 SynchronizedRef.modifyEffect(ref, (state) => {182 const duplicatePushEvents = seenIn(state, writes);
56 unmodified lines
modified:packages/project/src/project-store/sqlite.ts+8 added-3 removed
25 unmodified lines
26const EventIds = Schema.Array(Schema.Struct({ event_id: Schema.String }));2728const decodeEventIds = Schema.decodeUnknownEffect(EventIds);2930const OutboxIds = Schema.Array(Schema.Struct({ id: Schema.String }));3132const decodeOutboxIds = Schema.decodeUnknownEffect(OutboxIds);3334const LastSeq = Schema.Tuple([Schema.Struct({ last: Schema.Int })]);3536const decodeLastSeq = Schema.decodeUnknownEffect(LastSeq);37
89 unmodified lines
127128 return ProjectStore.of({129 ackOutbox: (ids) =>130 Array.isReadonlyArrayNonEmpty(ids)127 ? sql`DELETE FROM outbox WHERE ${sql.in("id", ids)}`.pipe(128 Effect.asVoid,131 ? sql`DELETE FROM outbox WHERE ${sql.in("id", ids)} RETURNING id`.pipe(132 Effect.flatMap(decodeOutboxIds),133 Effect.map(Array.map(({ id }) => id)),134 Effect.orDie135 )131 : Effect.void,136 : Effect.succeed([]),137 commit: (writes) =>138 sql139 .withTransaction(140 Effect.gen(function* () {
68 unmodified lines
modified:packages/project/src/answer-runs.ts+3 added-1 removed
7 unmodified lines
8import { RatchetSpec } from "@repo/protocol/domain/check";9import { Choice } from "@repo/protocol/domain/decision";10import { AskKind } from "@repo/protocol/domain/kind";11import type { LandingView } from "@repo/protocol/domain/landing";12import { Outcome } from "@repo/protocol/domain/outcome";12import { Outcome, StageName } from "@repo/protocol/domain/outcome";13import { RunBlock } from "@repo/protocol/domain/run";14import { Territory } from "@repo/protocol/domain/territory";15import {16 AskId,
100 unmodified lines
117 pending: Schema.optionalKey(118 Schema.Array(Schema.Literals(["mirror", "notes"]))119 ),120 ratchets: Schema.optionalKey(Schema.Array(MeasuredCount)),121 /** The stage whose refusals a `Checked` report carries: absent when it carries none, or from a run that ran every lane at once. */122 stage: Schema.optionalKey(StageName),123});124125export type AnswerReport = typeof AnswerReport.Type;126
37 unmodified lines
modified:packages/project/src/deciders.ts+34 added-1 removed
114 unmodified lines
115 outcomeOf,116 transition,117} from "./landing.ts";118import type { Request, Step } from "./landing.ts";119import { draftRow, OutboxBody, outboxRow, startRow } from "./outbox.ts";119import { MetricPoint, millisBetween } from "./metrics.ts";120import {121 draftRow,122 measuredRow,123 OutboxBody,124 outboxRow,125 startRow,126} from "./outbox.ts";127import type {128 AnswerRow,129 BudgetDayRow,130 ClaimRow,
303 unmodified lines
434 model,435 verified: true,436});437438/** A round from its start to its settle: the proposal names its start while it drafts. */439const draftedPoints = (440 proposal: Proposal,441 result: DraftResult,442 now: DateTime.Utc443): readonly MetricPoint[] =>444 proposal.draft !== undefined && DraftState.guards.Drafting(proposal.draft)445 ? [446 MetricPoint.cases.Drafted.make({447 attempts: result.attempts,448 latencyMs: millisBetween(proposal.draft.startedAt, now),449 project: proposal.project,450 ready: DraftResult.guards.Red(result),451 }),452 ]453 : [];454455const assistedBy = (evidence: readonly Evidence[]): readonly AgentTrailer[] =>456 Option.toArray(457 Option.map(458 Array.findFirst(evidence, ({ label }) => label === draftedByLabel),
469 unmodified lines
928929 writes.proposals.set(settled.id, settled);930 emitted(writes, moved.value.effects);931932 // A settle moves only the round still drafting, so a replayed one counts nothing.933 writes.outbox.push(934 ...(yield* measuredRow(935 `drafted:${settled.id}:r${input.round}`,936 draftedPoints(proposal, input.result, now),937 now938 ))939 );940941 // The drafted files may lie under other maintainers than the want did.942 const decidedBy = decidersOn(943 live.policy,944 pathsOf(live.policy, settled.files, territory),
1269 unmodified lines
added:packages/project/src/metrics.ts+82 added
1/**2 * The facts the platform counts and times: landings, refusals, check lanes,3 * the wait before an answer's checks start, and draft rounds. A point names4 * public things only (a project, a refusal's tag and area, a stage, a lane)5 * and numbers: never a path, a layer, a held-back check, a command, a log or6 * a value. The project writes each one to its outbox in the same commit as7 * the fact it counts, keyed by that fact, so a replayed call writes none.8 */9import { LaneOutcome } from "@repo/protocol/domain/answer";10import type { LaneResult } from "@repo/protocol/domain/answer";11import { StageName } from "@repo/protocol/domain/outcome";12import {13 ShownRefusal,14 shownRefusal,15} from "@repo/protocol/domain/recent-landing";16import { LaneName, ProjectName } from "@repo/protocol/ids";17import type { Refusal } from "@repo/protocol/refusal";18import { Context, DateTime, Effect, Schema } from "effect";1920const Millis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));2122export const MetricPoint = Schema.TaggedUnion({23 /** How long an answer waited, from its submission, before its checks started. */24 ChecksWaited: { project: ProjectName, waitedMs: Millis },25 /** A draft round, from its start to its settle. */26 Drafted: {27 attempts: Schema.Int,28 latencyMs: Millis,29 project: ProjectName,30 ready: Schema.Boolean,31 },32 /** A commit the platform landed on a project's main. */33 Landed: { project: ProjectName },34 /** One check lane's run on an answer's merged tree, as the Checker timed it. */35 LaneRan: {36 durationMs: Millis,37 lane: LaneName,38 project: ProjectName,39 result: LaneOutcome,40 },41 /** One refusal of an answer: its tag, its area when it names one, and the stage that gave it. */42 Refused: { ...ShownRefusal.fields, project: ProjectName, stage: StageName },43});4445export type MetricPoint = typeof MetricPoint.Type;4647export interface MetricsApi {48 /** Fire and forget: a point the store cannot take is dropped with a warning, never retried. */49 readonly write: (points: readonly MetricPoint[]) => Effect.Effect<void>;50}5152/** The default writes nothing, so a world with no dataset counts nothing. */53export const Metrics = Context.Reference<MetricsApi>("project/Metrics", {54 defaultValue: () => ({ write: () => Effect.void }),55});5657export const refusedPoints = (58 project: ProjectName,59 stage: StageName,60 refusals: readonly Refusal[]61): readonly MetricPoint[] =>62 refusals.map((refusal) =>63 MetricPoint.cases.Refused.make({ ...shownRefusal(refusal), project, stage })64 );6566/** The lane's name, result and time alone: its command and log stay with the verdict. */67export const lanePoints = (68 project: ProjectName,69 lanes: readonly LaneResult[]70): readonly MetricPoint[] =>71 lanes.map(({ durationMs, lane, result }) =>72 MetricPoint.cases.LaneRan.make({73 durationMs: Math.max(durationMs, 0),74 lane,75 project,76 result,77 })78 );7980/** Never below zero: two instants a clock gave in order may still read backwards. */81export const millisBetween = (from: DateTime.Utc, to: DateTime.Utc): number =>82 Math.max(DateTime.toEpochMillis(to) - DateTime.toEpochMillis(from), 0);
modified:packages/project/src/outbox.ts+45 added-1 removed
15 unmodified lines
16import type { AnswerQueue } from "./answer-runs.ts";17import { DraftParams, DraftRuns } from "./draft-runs.ts";18import { Lander, Rebuild } from "./lander.ts";19import { backoff } from "./landing.ts";20import { MetricPoint, Metrics } from "./metrics.ts";21import type { OutboxRow } from "./project-store/rows.ts";22import { Projection, ProjectedEvent } from "./projection.ts";23import { ProjectVisibility, VisibilityEffect } from "./visibility-port.ts";24
20 unmodified lines
45 Schema.TaggedStruct("StartAnswer", { requestId: RequestId }),46 Schema.TaggedStruct("Bookkeeping", { job: LandAgain }),47 Schema.TaggedStruct("Visibility", { effect: VisibilityEffect }),48 Schema.TaggedStruct("StartDraft", DraftParams.fields),49 Schema.TaggedStruct("Measured", {50 points: Schema.NonEmptyArray(MetricPoint),51 }),52]).pipe(Schema.toTaggedUnion("_tag"));5354export type OutboxBody = typeof OutboxBody.Type;55
42 unmodified lines
98 OutboxBody.cases.StartDraft.make(params),99 at100 );101102/**103 * Written in the commit that holds the fact, under an id the fact alone104 * names, so a replay that changes nothing writes no row and the same fact105 * kept twice is one row.106 */107export const measuredRow = (108 fact: string,109 points: readonly MetricPoint[],110 at: DateTime.Utc111): Effect.Effect<readonly OutboxRow[]> =>112 Array.isReadonlyArrayNonEmpty(points)113 ? Effect.map(114 outboxRow(115 `measured:${fact}`,116 OutboxBody.cases.Measured.make({ points }),117 at118 ),119 Array.of120 )121 : Effect.succeed([]);122123export const isDue = (row: OutboxRow, now: DateTime.Utc) =>124 DateTime.isLessThanOrEqualTo(row.notBefore, now);125126export interface OutboxRun {
64 unmodified lines
191// Answer runs go last: they may run long, and settle their own rows.192export const runOutbox = (193 rows: readonly OutboxRow[],194 queue: AnswerQueue,170 now: DateTime.Utc195 now: DateTime.Utc,196 // Takes rows out of the store before they run, naming those it still held.197 claim: (ids: readonly string[]) => Effect.Effect<readonly string[]>198): Effect.Effect<199 OutboxRun,200 never,201 AnswerRuns | Lander | Projection | RepoHost
50 unmodified lines
252 ran(row, true, now)253 )254 );255256 const metrics = yield* Metrics;257258 // A point is written at most once, and never retried: the dataset adds259 // every point it takes. Its row leaves the store first, so of a call's260 // settle and the alarm's, both holding it, only the one that took it261 // writes its points.262 const taken = new Set(263 yield* claim(of("Measured").map(({ row }) => row.id))264 );265266 const measured = yield* Effect.forEach(267 of("Measured").filter(({ row }) => taken.has(row.id)),268 ({ body, row }) =>269 Effect.as(metrics.write(body.points), ran(row, true, now))270 );271272 const runs = yield* Effect.forEach(of("StartAnswer"), ({ body, row }) =>273 Effect.as(274 AnswerRuns.use((answers) => answers.start(body.requestId, queue)),275 ran(row, true, now)
5 unmodified lines
281 ...forks,282 ...kept,283 ...planned,284 ...drafts,285 ...measured,286 ...runs,287 ]);288 });
modified:packages/project/src/project-store.ts+7 added-1 removed
81 unmodified lines
82 */83export class ProjectStore extends Context.Service<84 ProjectStore,85 {86 readonly ackOutbox: (ids: readonly string[]) => Effect.Effect<void>;86 /**87 * Takes out the outbox rows it still holds of `ids`, and names them: of88 * two acks of one row, only the first takes it.89 */90 readonly ackOutbox: (91 ids: readonly string[]92 ) => Effect.Effect<readonly string[]>;93 readonly commit: (writes: ProjectWrites) => Effect.Effect<Committed>;94 readonly eventsSince: (95 seq: number,96 limit: number
13 unmodified lines
modified:packages/project/src/project.tsnot shown

Its text is not shown, modified.

added:packages/project/test/metrics.test.tsnot shown

Its text is not shown, added.

modified:packages/project/test/project-store.contract.tsnot shown

Its text is not shown, modified.

added:packages/telemetry/src/logger/memory.tsnot shown

Its text is not shown, added.

added:packages/telemetry/src/spans/binding.tsnot shown

Its text is not shown, added.

added:packages/telemetry/src/spans/memory.tsnot shown

Its text is not shown, added.

added:packages/telemetry/src/defects.tsnot shown

Its text is not shown, added.

added:packages/telemetry/src/logger.tsnot shown

Its text is not shown, added.

added:packages/telemetry/src/spans.tsnot shown

Its text is not shown, added.

added:packages/telemetry/src/telemetry.tsnot shown

Its text is not shown, added.

added:packages/telemetry/test/defects.test.tsnot shown

Its text is not shown, added.

added:packages/telemetry/test/logger.test.tsnot shown

Its text is not shown, added.

added:packages/telemetry/test/spans.test.tsnot shown

Its text is not shown, added.

added:packages/telemetry/package.jsonnot shown

Its text is not shown, added.

added:packages/telemetry/tsconfig.jsonnot shown

Its text is not shown, added.

added:packages/telemetry/vitest.config.tsnot shown

Its text is not shown, added.

modified:scripts/smoke.tsnot shown

Its text is not shown, modified.

modified:AGENTS.md+10 added-10 removed
11 unmodified lines
1213| # | Principle | Held by |14| --- | --- | --- |15| 1 | **Encode lessons in structure; prose is the last rung.** When a mistake repeats, make it unrepresentable, then a lint or a test. | No fence |16| 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | The Effect diagnostics at error in `tsconfig.base.json`; `anti-slop/no-unknown-parameters`, `anti-slop/no-widen-then-assert` and `anti-slop/require-safety-comment-for-type-assertion`; `apps/platform/test/platform.test.ts` (a bad env fails at start, decoded once in `apps/platform/src/platform.ts`); `apps/platform/test/bindings.test.ts` (the decoded bindings, vars and secrets equal each wrangler.jsonc block's, the `AI` binding, `DRAFT_LIMIT`, `DRAFT_MODEL`, `PUBLIC_WEB_URL` and the code store's `CODE_CACHE` among them, and each port's factory takes its binding as the generated Env types it, without a cast); `packages/project/test/code-history.test.ts` (a kept code-history value is decoded with Schema when read, and one that no longer decodes is computed again); `packages/project/test/code.test.ts` (a kept commit that no longer decodes is computed again); `apps/web/test/dev-fixtures.test.ts` (the dev world's fixture record is decoded through the protocol's schemas when the world is built, so every case reads only a record that decodes); `apps/web/test/server-params.test.ts` (a project route's server handler is handed the project's full name once, as Start's params parse it, never parsed again); `apps/web/test/theme.test.ts` (the theme preference is decoded with Schema when read from `localStorage`, and a value it never wrote, or storage the browser refuses, reads as the system's own) |17| 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` and `packages/protocol/test/render.test.ts` (every tag, the code reads' and drafting's `UnknownPath`, `UnknownRevision`, `UnknownProposal`, `ProposalClosed` and `DraftInProgress` included; a limit's refusal names its kind and its wait, and a ref outside `refs/heads/` reads as one the platform writes); `packages/agent-kit/test/full-llms.test.ts` (every tag in the union has a row in `/llms-full.txt`); `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`; `packages/gate/test/shape.test.ts` (one push hears every stage-1 refusal at once); `apps/platform/test/mcp.test.ts` (each refusing MCP contract comes back as its exact refusal, `draftAsk`, `showProposal` and a code read's `UnknownPath` included); `apps/platform/test/workflows/draft.test.ts` (past the draft limit, `CapReached`); `apps/cli/test/policy.test.ts`; `apps/cli/test/local/check.test.ts` (the local check gives the gateway's stage-1 refusals for the same commit); `packages/protocol/test/exit-code.test.ts` (each tag's CLI exit code is pinned, 75 exactly when it is retryable); `packages/config/test/legacy-projects.test.ts` (the same alias rule for a project's address: the forty projects made before owners keep their keys as aliases of their full names, the two examples and the import plan's, each key and each name once) |16| 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | The Effect diagnostics at error in `tsconfig.base.json`; `anti-slop/no-unknown-parameters`, `anti-slop/no-widen-then-assert` and `anti-slop/require-safety-comment-for-type-assertion`; `apps/platform/test/platform.test.ts` (a bad env fails at start, decoded once in `apps/platform/src/platform.ts`); `apps/platform/test/bindings.test.ts` (the decoded bindings, vars and secrets equal each wrangler.jsonc block's, the `AI` binding, `DRAFT_LIMIT`, `DRAFT_MODEL`, `PUBLIC_WEB_URL`, the code store's `CODE_CACHE` and each stage's own metrics dataset, `METRICS`, among them, and each port's factory takes its binding as the generated Env types it, without a cast); `packages/project/test/code-history.test.ts` (a kept code-history value is decoded with Schema when read, and one that no longer decodes is computed again); `packages/project/test/code.test.ts` (a kept commit that no longer decodes is computed again); `apps/web/test/dev-fixtures.test.ts` (the dev world's fixture record is decoded through the protocol's schemas when the world is built, so every case reads only a record that decodes); `apps/web/test/server-params.test.ts` (a project route's server handler is handed the project's full name once, as Start's params parse it, never parsed again); `apps/web/test/theme.test.ts` (the theme preference is decoded with Schema when read from `localStorage`, and a value it never wrote, or storage the browser refuses, reads as the system's own) |17| 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` and `packages/protocol/test/render.test.ts` (every tag, the code reads' and drafting's `UnknownPath`, `UnknownRevision`, `UnknownProposal`, `ProposalClosed` and `DraftInProgress` included; a limit's refusal names its kind and its wait, and a ref outside `refs/heads/` reads as one the platform writes); `packages/agent-kit/test/full-llms.test.ts` (every tag in the union has a row in `/llms-full.txt`); `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`; `packages/gate/test/shape.test.ts` (one push hears every stage-1 refusal at once); `apps/platform/test/mcp.test.ts` (each refusing MCP contract comes back as its exact refusal, `draftAsk`, `showProposal` and a code read's `UnknownPath` included); `apps/platform/test/workflows/draft.test.ts` (past the draft limit, `CapReached`); `apps/cli/test/policy.test.ts`; `apps/cli/test/local/check.test.ts` (the local check gives the gateway's stage-1 refusals for the same commit); `packages/protocol/test/exit-code.test.ts` (each tag's CLI exit code is pinned, 75 exactly when it is retryable); `packages/telemetry/test/defects.test.ts` (a refusal is never reported as an error, and a defect is reported once, at Error, with its cause and stack, however many boundaries it crosses), with `apps/platform/test/telemetry.test.ts` (the routers, a Project DO call and a Workflow instance each report a defect once, and neither the DO's caller nor a Workflow step that met it reports it again) and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's defect is the platform's to report); `packages/config/test/legacy-projects.test.ts` (the same alias rule for a project's address: the forty projects made before owners keep their keys as aliases of their full names, the two examples and the import plan's, each key and each name once) |18| 4 | **One schema, many surfaces.** Change `packages/protocol`; every surface derives from it. Projections live only in `apps/*/src/surfaces.ts`. The CLI's command list is `commandDocs` in `@repo/agent-kit`, which the platform's skill, the CLI's MCP prompt and the web's `llms.txt` all read. | `apps/cli/test/commands-doc.test.ts` (the command list against the real CLI's commands, flags and positionals, `policy`, `ask draft` and `proposal` included); `packages/protocol/test/mcp.test.ts` (every MCP tool's schemas, with no JSON Schema leak, the policy and drafting contracts included; the five capped code reads are tools, `showCommit` and `listPaths` are not); `packages/agent-kit/test/install-channels.test.ts` and `apps/web/test/agents.test.tsx` (every snippet, command and link on the Install page is `@repo/agent-kit`'s, and the old `/agents` answers a 301 to `/install`); `packages/agent-kit/test/docs.test.ts` and `apps/web/test/docs.test.tsx` (the `/docs` pages name only the CLI's commands with flags each takes and link only to pages that exist, the reference lists every command, refusal, event, MCP tool, limit, endpoint and imported project from its source, and the web draws each page and its Markdown from that one text); `apps/web/test/llms.test.ts` (`/` and `/<project>` asked for Markdown answer with the `llms.txt` texts, and their HTML names that Markdown as an alternate); `packages/agent-kit/test/full-llms.test.ts` (one `ProjectEvent` line per tag); `apps/platform/test/home.test.ts` (the platform's `/` in Markdown is the web's `llms.txt`, one text from `@repo/agent-kit`); `packages/protocol/test/project-name.test.ts` (`ProjectName` is the one parser of a project's name for every surface: lowercase, a legacy key read as its full name, encoded only in the full form, and a key that reads back to its name); per-package `allowedUnstableApis` with `unstableApiUsage` at error |19| 5 | **The name lives only in `packages/brand`.** Internal packages use `@repo/*`. DO classes, Workflows, queues and databases carry job names. | `brand:check` (`scripts/brand.ts`, tested by `packages/brand/test/leaks.test.ts`); `apps/web/test/shell.test.tsx` (the footer's wordmark is `Brand.domain`, read from `@repo/brand`, never typed) |20| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/platform/test/router-build.test.ts` (both handlers are built when the Worker module loads, with no binding touched, and a layer that awaits a promise while it is built is refused there); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build, and no chunk every page preloads holds the Markdown renderer, under a gzip ceiling); `packages/config/test/cartridge.test.ts` (the visibility cartridge is plugged in by one marked line and reached by nothing else, so removing it is a deletion); `packages/drafting/test/memory.test.ts` (the `Drafter` port's `/memory` adapter, `packages/drafting/src/drafter/memory.ts`) and `packages/drafting/test/binding.test.ts` (its Workers AI adapter over the `AI` binding); `apps/platform/test/mailer.test.ts` (sign-in's `Mailer` port, its `/memory` adapter and its Email Service adapter over the `EMAIL` binding); `packages/project/test/code-store.test.ts` (the `CodeStore` port's `/memory` adapter, `packages/project/src/code-store/memory.ts`, and its R2 adapter over `CODE_CACHE`, whose failures are misses, never the read's); `apps/platform/test/code-reads.test.ts` and `apps/web/test/dev-backend.test.ts` (the platform and the web's dev world answer the code reads and raw files alike, both through `@repo/project/code`); `packages/project/test/standing-posture.test.ts` (one helper, `withStandingPosture`, gives a listing each project's own posture, for the platform and the web's dev world alike, through the `StandingPostures` port whose default keeps nothing; its D1 adapter is the platform's); `packages/project/test/description.test.ts` and `packages/project/test/description-d1.test.ts` (the `ProjectDescriptions` port's `/memory` adapter, `packages/project/src/description/memory.ts`, and its D1 adapter, whose unreadable rows and missing table are misses); `apps/web/test/seeded.test.tsx` (a loader's read seeds a registry of its own page and leaves the registry every request shares as it was); `apps/web/test/shell.test.tsx` (no plain anchor between the web's pages: every link is the router's). No fence: import direction and module-level state |21| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `packages/drafting/test/prompt.test.ts` (a draft's prompt never carries a layer's name, repo, reason or paths); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `packages/protocol/test/fork-address.test.ts` (a fork's address is a closed parse that never joins text into a ref path), with `packages/project/test/code.test.ts` and `apps/platform/test/code-reads.test.ts` (a fork is read only at the address of a claim fork the project lists, and a layer's repo, an unlisted fork or a repo's name is `UnknownRevision`); `packages/protocol/test/recent-landing.test.ts` and `packages/project/test/recent-landings-d1.test.ts` (a kept refusal is its tag and area alone); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing's latest landings name each by its project, and a refused answer by its tag and its area alone, never a check's name, suite, lane, path or log) and `apps/web/test/explore.test.tsx` (each project's card shows the posture its listing gives); `apps/web/test/ledger.test.tsx` (the Visibility tab's ledger adds no path, check name or file name, and the tab's views import nothing from the visibility cartridge) and `apps/web/test/env.test.tsx` (its Environment shows no value and no control to set or read one, and the old `/env` and `/ledger` answer a 301 to the tab); `apps/web/test/home.test.tsx`, `apps/web/test/today.test.tsx` and `apps/web/test/edge-cache.test.ts` (`/inbox` is read with the reader's own session and kept by no cache, and the old `/home` and `/today` answer a 301 to it); `apps/web/test/theme.test.ts` and `apps/web/test/settings.test.tsx` (the theme preference lives in `localStorage` and never in a cookie, so it makes no page personal); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies, and every sign-in form shown again escapes what the person typed); `apps/platform/test/oauth.test.ts` (no account is written, and no grant given, until its email is proved by a mailed code, and a password reset reads the same for an address no account has); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |22| 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`; `apps/platform/test/workflows/draft.test.ts` (a replayed draft round asks the model nothing more, and each round is its own instance); `packages/project/test/code.test.ts` (code reads cached by object id, only once finished, while `main` resolves every time, and a commit's diff kept by its SHA without its landing); `packages/project/test/drafting.model.test.ts` (a settle of a stale round changes nothing); `packages/project/test/import.test.ts` (a retried import adopts the repo it made, and a retried import keeps its source); `packages/project/test/code-history.test.ts` (a why and a path's history are kept by commit, path hash and algorithm version, and the store, a step from a kept ancestor and a whole walk agree); `packages/config/test/smoke-loop.test.ts` (smoke's throwaway project is in the ledger before init makes it, and a taken name stops before anything is made); `apps/web/test/events.test.ts` (the web's fold of a project's events gives the same map when an event is heard twice or out of order, and a replay that already holds a landing stamps nothing); `packages/project/test/standing-posture.test.ts` (a kept posture is read again only for the project whose event the projection applied, or once its instant has come); `packages/project/test/recent-landings-d1.test.ts` (the same rows heard again change nothing, and at most `RECENT_LANDINGS_CAP` rows are kept); `packages/project/test/description.test.ts` (a landed project is read once while its last landing stands). No fence: one push deduped by (repo, sha) across the gateway's record and OnPush's |23| 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Off limits: `effect/unstable/*`, v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `no-restricted-imports` |20| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/platform/test/router-build.test.ts` (both handlers are built when the Worker module loads, with no binding touched, and a layer that awaits a promise while it is built is refused there); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build, and no chunk every page preloads holds the Markdown renderer, under a gzip ceiling); `packages/config/test/cartridge.test.ts` (the visibility cartridge is plugged in by one marked line and reached by nothing else, so removing it is a deletion); `packages/drafting/test/memory.test.ts` (the `Drafter` port's `/memory` adapter, `packages/drafting/src/drafter/memory.ts`) and `packages/drafting/test/binding.test.ts` (its Workers AI adapter over the `AI` binding); `apps/platform/test/mailer.test.ts` (sign-in's `Mailer` port, its `/memory` adapter and its Email Service adapter over the `EMAIL` binding); `packages/project/test/code-store.test.ts` (the `CodeStore` port's `/memory` adapter, `packages/project/src/code-store/memory.ts`, and its R2 adapter over `CODE_CACHE`, whose failures are misses, never the read's); `packages/project/test/metrics.test.ts` (the `Metrics` port's `/memory` adapter, `packages/project/src/metrics/memory.ts`, and its Analytics Engine adapter over `METRICS`, which drops a point the dataset refuses and fails nothing; `apps/platform/test/worker-init.test.ts` writes through the Worker's own ports); `apps/platform/test/code-reads.test.ts` and `apps/web/test/dev-backend.test.ts` (the platform and the web's dev world answer the code reads and raw files alike, both through `@repo/project/code`); `packages/project/test/standing-posture.test.ts` (one helper, `withStandingPosture`, gives a listing each project's own posture, for the platform and the web's dev world alike, through the `StandingPostures` port whose default keeps nothing; its D1 adapter is the platform's); `packages/project/test/description.test.ts` and `packages/project/test/description-d1.test.ts` (the `ProjectDescriptions` port's `/memory` adapter, `packages/project/src/description/memory.ts`, and its D1 adapter, whose unreadable rows and missing table are misses); `apps/web/test/seeded.test.tsx` (a loader's read seeds a registry of its own page and leaves the registry every request shares as it was); `apps/web/test/shell.test.tsx` (no plain anchor between the web's pages: every link is the router's); `packages/telemetry/test/spans.test.ts` (the spans port: Effect's `Tracer`, bridged onto a Worker's `tracing` by `packages/telemetry/src/spans/binding.ts`, with its `/memory` adapter, `packages/telemetry/src/spans/memory.ts`, on which every span opens under the invocation's root, a sibling of the runtime's own, and an ended span is traced no more, as in workerd; only a Worker's composition imports `tracing` from `cloudflare:workers`). No fence: import direction and module-level state |21| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `packages/config/test/observability.test.ts` (a Checker's container logs are off in every stage, and every container sets its own; the platform's traces are kept in the account and sent to no destination, since the runtime's own spans record each Project DO statement's bound values and each fetch's full URL); `packages/config/test/alerts.test.ts` (an alert's query counts rows of its own stage's Workers and datasets, never a layer's or another stage's); `packages/telemetry/test/spans.test.ts` (a span carries only the listed ids onto a trace, never a repo, a path or a query, and Issues reads ids alone), `packages/telemetry/test/logger.test.ts` and `packages/telemetry/test/defects.test.ts` (no line, report or span carries a Worker secret or a write-only value), with `apps/platform/test/telemetry.test.ts` (every secret the platform's env decodes, each session token included, and a route's or a Project DO's defect kept by its name and frames alone, since its text may name a layer's repo), `apps/platform/test/sandbox-adapters.test.ts` (a sandbox job's defect logged by its name and frames alone), and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's lines carry none of its tokens, and a Checker's span keeps a defect by its name alone, since its text may quote a sealed path); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `packages/drafting/test/prompt.test.ts` (a draft's prompt never carries a layer's name, repo, reason or paths); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `packages/protocol/test/fork-address.test.ts` (a fork's address is a closed parse that never joins text into a ref path), with `packages/project/test/code.test.ts` and `apps/platform/test/code-reads.test.ts` (a fork is read only at the address of a claim fork the project lists, and a layer's repo, an unlisted fork or a repo's name is `UnknownRevision`); `packages/protocol/test/recent-landing.test.ts` and `packages/project/test/recent-landings-d1.test.ts` (a kept refusal is its tag and area alone); `packages/project/test/metrics.test.ts` (a metric names a project, a refusal's tag and area, a stage and a lane, with numbers: never a path, a command, a log or a held-back check); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing's latest landings name each by its project, and a refused answer by its tag and its area alone, never a check's name, suite, lane, path or log) and `apps/web/test/explore.test.tsx` (each project's card shows the posture its listing gives); `apps/web/test/ledger.test.tsx` (the Visibility tab's ledger adds no path, check name or file name, and the tab's views import nothing from the visibility cartridge) and `apps/web/test/env.test.tsx` (its Environment shows no value and no control to set or read one, and the old `/env` and `/ledger` answer a 301 to the tab); `apps/web/test/home.test.tsx`, `apps/web/test/today.test.tsx` and `apps/web/test/edge-cache.test.ts` (`/inbox` is read with the reader's own session and kept by no cache, and the old `/home` and `/today` answer a 301 to it); `apps/web/test/theme.test.ts` and `apps/web/test/settings.test.tsx` (the theme preference lives in `localStorage` and never in a cookie, so it makes no page personal); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies, and every sign-in form shown again escapes what the person typed); `apps/platform/test/oauth.test.ts` (no account is written, and no grant given, until its email is proved by a mailed code, and a password reset reads the same for an address no account has); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |22| 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`; `apps/platform/test/workflows/draft.test.ts` (a replayed draft round asks the model nothing more, and each round is its own instance); `packages/project/test/code.test.ts` (code reads cached by object id, only once finished, while `main` resolves every time, and a commit's diff kept by its SHA without its landing); `packages/project/test/drafting.model.test.ts` (a settle of a stale round changes nothing); `packages/project/test/import.test.ts` (a retried import adopts the repo it made, and a retried import keeps its source); `packages/project/test/code-history.test.ts` (a why and a path's history are kept by commit, path hash and algorithm version, and the store, a step from a kept ancestor and a whole walk agree); `packages/config/test/smoke-loop.test.ts` (smoke's throwaway project is in the ledger before init makes it, and a taken name stops before anything is made); `apps/web/test/events.test.ts` (the web's fold of a project's events gives the same map when an event is heard twice or out of order, and a replay that already holds a landing stamps nothing); `packages/project/test/standing-posture.test.ts` (a kept posture is read again only for the project whose event the projection applied, or once its instant has come); `packages/project/test/recent-landings-d1.test.ts` (the same rows heard again change nothing, and at most `RECENT_LANDINGS_CAP` rows are kept); `packages/project/test/description.test.ts` (a landed project is read once while its last landing stands); `packages/project/test/metrics.test.ts` (each landing, refusal, checked lane, wait before checks and draft round is written at most once, from the outbox of the commit that keeps it, however often its push, report or settle is heard, and when a call's settle and the alarm's both hold its row), with `packages/project/test/project-store.contract.ts` (of two acks of one outbox row, only the first takes it). No fence: one push deduped by (repo, sha) across the gateway's record and OnPush's |23| 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Effect marks its unstable modules (`effect/http`, `effect/sql`, `effect/observability` and the rest) in place, with no `effect/unstable/*` path: one is off limits outside the paths its package's allow-list names. Off limits too: v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `unstableApiUsage` at error, with per-path `allowedUnstableApis` in `tsconfig.base.json`; `no-restricted-imports` |24| 10 | **Escapes need a reason.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries its reason after `--`, and is added only where no idiomatic code does the job. | `check` fails on an unused directive. No fence: the reason |25| 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`), and refuses every deploy while `infra/.recording` is there (`packages/config/test/recording.test.ts`) |25| 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after, which fails on any exception or error-level line the stage's Workers logged since the first upload, or on a token that can't read them (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`), and refuses every deploy while `infra/.recording` is there (`packages/config/test/recording.test.ts`) |26| 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | `globalTimers` and `globalTimersInEffect`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts` (model tests over effect/Arbitrary histories, each seen catching its planted bug); `packages/project/test/drafting.model.test.ts` (a proposal's `DraftCommand.DraftStarted` and `DraftSettled` over generated histories; a Ready round's files survive a later failed round); `apps/platform/test/project-do.test.ts`. No fence: `Effect.sleep` and `Effect.delay` in `packages/project/src` |2728## Verify29
31 unmodified lines
61- `lockfile:check`: fails when `bun.lock` is out of date with the manifests.62- `prepare`: runs on `bun install` and patches TypeScript with the Effect language service.63- `env:check`: shows the env with its values redacted.64- `ops -- <command>`: runs cf with the ops credentials (see Boundaries).65- `bootstrap -- --stage <stage>`: makes a stage's Cloudflare resources; a second run creates nothing, and `--dry-run` only prints the plan.66- `deploy -- --stage <stage>`: the one way to deploy. It runs `verify`, deploys the three Workers with Wrangler, reads the push trigger back, then runs `smoke`. `prod` is served on the brand's own domain (the web at the apex, the platform at `git.`), which `infra/stages.ts` names and the deploy passes to Wrangler, so the name stays out of `wrangler.jsonc`.67- `smoke -- --stage <stage>`: read-only probes against a live stage. `--loop` then runs the whole core loop on a throwaway project, `smoke-<run>`, through the CLI and git, and refuses `demo` and `prod`.65- `bootstrap -- --stage <stage>`: makes a stage's Cloudflare resources; a second run creates nothing, and `--dry-run` only prints the plan. Either run ends by printing the stage's alerts (`infra/alerts.ts`), which a person makes by hand in the dashboard: no API takes a custom alert's query yet.66- `deploy -- --stage <stage>`: the one way to deploy. It runs `verify`, deploys the three Workers with Wrangler, reads the push trigger back, then runs `smoke` with infra's credentials and `--since` the first upload. `prod` is served on the brand's own domain (the web at the apex, the platform at `git.`), which `infra/stages.ts` names and the deploy passes to Wrangler, so the name stays out of `wrangler.jsonc`.67- `smoke -- --stage <stage>`: read-only probes against a live stage. `--since <instant>` then reads the stage's Workers Logs through the SQL API, with infra's credentials (Account Analytics Read), and fails on any exception or error-level line since then. `--loop` then runs the whole core loop on a throwaway project, `smoke-<run>`, through the CLI and git, and refuses `demo` and `prod`.68- `seed`: puts the two example projects on a platform (`--world node` on this machine, or `--stage <stage>`); a second run changes nothing. `--only <example> --as <name>` seeds a fresh copy under another name, and refuses a taken one. It refuses `prod`, as `swarm` does: their projects and people are fictional.69- `import-examples -- --stage <stage>`: imports the open-source repos the code browser is previewed on, one at a time, onto a stage (`demo` included, with its reason in the stage's record), each recorded in the ledger as kept; `--tags` backfills the tags Artifacts' import leaves out, `--only <name>` imports one, and `--world node` imports onto this machine.70- `swarm -- --stage <stage> --project <name>`: plans six fictional contributors, on four harnesses, against one split family on a stage, claims each one's ask, prepares a workspace with a clone of its fork outside the checkout, starts each harness headless on the brief and sends every refusal back into the same session, at most three times, then writes the run's summary; `--view herdr` runs them in herdr panes beside a counter, and `--dry-run` only prints the plan.71- `release -- --build | --upload --stage <stage> | --publish`: builds the CLI's npm package and two binaries, uploads a release to the stage's own bucket, which the platform serves, and leaves `npm publish` to a person: under an agent it prints the command instead.
68 unmodified lines
modified:bun.lock+18 added
9 unmodified lines
10 "@oxlint/plugins": "1.87.0",11 "@repo/agent-kit": "workspace:*",12 "@repo/artifacts": "workspace:*",13 "@repo/brand": "workspace:*",14 "@repo/project": "workspace:*",15 "@repo/protocol": "workspace:*",16 "cf": "1.0.0-beta.12",17 "effect": "catalog:",18 "oxfmt": "0.72.0",
48 unmodified lines
67 "@repo/git": "workspace:*",68 "@repo/project": "workspace:*",69 "@repo/protocol": "workspace:*",70 "@repo/rules": "workspace:*",71 "@repo/telemetry": "workspace:*",72 "@repo/visibility": "workspace:*",73 "effect": "catalog:",74 },75 "devDependencies": {
18 unmodified lines
94 "@repo/git": "workspace:*",95 "@repo/project": "workspace:*",96 "@repo/protocol": "workspace:*",97 "@repo/rules": "workspace:*",98 "@repo/telemetry": "workspace:*",99 "effect": "catalog:",100 },101 "devDependencies": {102 "@cloudflare/workers-types": "5.20261006.1",
259 unmodified lines
362 "typescript": "catalog:",363 "vitest": "catalog:",364 },365 },366 "packages/telemetry": {367 "name": "@repo/telemetry",368 "dependencies": {369 "effect": "catalog:",370 },371 "devDependencies": {372 "@effect/vitest": "catalog:",373 "@repo/config": "workspace:*",374 "@repo/protocol": "workspace:*",375 "typescript": "catalog:",376 "vitest": "catalog:",377 },378 },379 "packages/testkit": {380 "name": "@repo/testkit",381 "dependencies": {382 "@effect/platform-node": "4.0.1",
569 unmodified lines
952 "@repo/sandbox": ["@repo/sandbox@workspace:apps/sandbox"],953954 "@repo/sdk": ["@repo/sdk@workspace:packages/sdk"],955956 "@repo/telemetry": ["@repo/telemetry@workspace:packages/telemetry"],957958 "@repo/testkit": ["@repo/testkit@workspace:packages/testkit"],959960 "@repo/visibility": ["@repo/visibility@workspace:packages/visibility"],961
1695 unmodified lines
modified:package.json+1 added
41 unmodified lines
42 "@oxlint/plugins": "1.87.0",43 "@repo/agent-kit": "workspace:*",44 "@repo/artifacts": "workspace:*",45 "@repo/brand": "workspace:*",46 "@repo/project": "workspace:*",47 "@repo/protocol": "workspace:*",48 "cf": "1.0.0-beta.12",49 "effect": "catalog:",50 "oxfmt": "0.72.0",
9 unmodified lines
modified:README.md+42 added
53 unmodified lines
54```5556[AGENTS.md](AGENTS.md) covers secrets, smoke, seeding, releases and teardown, and its principles table names the check that holds each rule.5758### Observability5960Each stage keeps, for every invocation of all three Workers and unsampled:6162- **Logs**: one JSON object per line, its ids (`project`, `requestId`, `lane` and the rest) fields to filter on, in Workers Logs. A typed refusal is the product working and is never logged as an error; a defect is logged once, at error level, with its stack.63- **Issues**: exceptions, failed invocations and error-level lines, grouped; each line keeps its ids.64- **Traces**, in all three. The runtime's own spans record each Durable Object SQL statement's bound values and each fetch's full URL, so the platform's traces hold the Project Durable Object's layer rows and sealed values (never a plain value). They stay in the account's own trace store, kept seven days: the platform's traces have no export destination, and no Issues automation sends them anywhere.65- **Query strings**, unredacted, so `?service=` on git and `?since=` on watch stay readable. A sign-in callback's one-time `code` and `state` show too.66- **Source maps**, uploaded by each deploy. Cloudflare remaps an uncaught exception's stack with them, but a defect the platform reports itself is logged as thrown, minified, and by its name and frames alone, never its text. To read its frames, build the deployed commit's map with `bunx wrangler deploy --dry-run --outdir <dir> --env <stage>` in `apps/platform`.67- **Metrics**: landings, refusals by tag and stage, checked lanes, the wait before checks and draft rounds, written by the platform's `METRICS` binding to the stage's Workers Analytics Engine dataset, `metrics_<stage>` with `_` for `-`. `packages/project/src/metrics/binding.ts` lays out its columns.6869A Checker container's own logs are off, since held-back checks run there; the Lander's are on. Nothing the code itself logs, traces or counts names a layer, a held-back check, a path or a value (principle 7); only the runtime's own platform spans above do.7071Read them in the dashboard, under each Worker's Observability tab and under Issues, or through the SQL API with `bun run ops`. Its token needs Account › Account Analytics › Read, and so does smoke: after a deploy it fails on any exception or error-level line the stage's Workers logged since the first upload, naming each Worker and its count.7273```sh74# Errors by Worker since an instant75bun run ops -- analytics sql post --scope-account-tag <account id> \76 --time-range-start 2026-10-13T00:00:00Z \77 --query "SELECT scriptName, count() AS errors FROM logs.workersLogs WHERE scriptName IN ('platform-demo', 'sandbox-demo', 'web-demo') AND (level = 'error' OR error != '') GROUP BY scriptName"7879# Refusals by tag and stage80bun run ops -- analytics sql post --scope-account-tag <account id> \81 --query "SELECT blob2 AS tag, blob3 AS stage, count() AS refusals FROM events.analyticsEngine.\"metrics_demo\" WHERE blob1 = 'Refused' GROUP BY tag, stage ORDER BY refusals DESC"82```8384`bun run ops -- analytics sql introspection get --account-tag <account id> --include-columns --include-wae` lists the datasets and their columns.8586### Alerts8788Each stage has six alerts, declared in `infra/alerts.ts` as Cloudflare Custom Alerts (beta), each a SQL API query run every minute:8990- **errors**, one per Worker: five or more exceptions or error-level lines in 15 minutes.91- **issue spike**: the stage's Workers report Issues three standard deviations above the two hours before, as after a bad deploy.92- **container failures**: three or more sandbox jobs whose container never answered, in 30 minutes.93- **refusal spike**: refusals, from the stage's metrics dataset in Analytics Engine, three standard deviations above the six hours before.9495No API takes a custom alert's query yet, so a person makes each by hand, once per stage, and again when `infra/alerts.ts` changes:96971. Run `bun run bootstrap -- --stage <stage> --dry-run`. It ends by printing each alert's name, detection and SQL for that stage.982. In the dashboard, under Notifications, create a Custom Alert for each: its name, the printed SQL as custom SQL, the Automatic time range, the detection and windows printed beside it, the default execution and repeat intervals, and the address `ALERT_EMAIL` names (`infra/.env.schema`) as its email destination.99100## The tree101102```103apps/ the platform, sandbox and web Workers, and the CLI
20 unmodified lines