project.ts
This file
Path
packages/project/src/project.ts
5,523 lines · 155.0 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–6why, one step back1import {2 BranchName,3 RefName,4 RepoHost,5 Revision,6} from "@repo/artifacts/repo-host";Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 7–11why, one step back7import type {8 ObjectId,9 RepoNotFound,10 TreeEntry,11} from "@repo/artifacts/repo-host";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 12–43why, one step back12import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";13import { Brand } from "@repo/brand";14import {15 CheckAt,16 CheckLane,17 CheckRunner,18 outputOf,19} from "@repo/checks/check-runner";20import type { CheckRun } from "@repo/checks/check-runner";21import { EvidenceStore, LogRef, logOfRef } from "@repo/checks/evidence-store";22import { findRunBlock } from "@repo/checks/finder";23import { judgeClosure } from "@repo/checks/judge";24import { checkVersion, commandFor } from "@repo/checks/kinds";25import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";26import type { LintToZeroCheck } from "@repo/checks/kinds/lint-to-zero";27import {28 judgeRatchets,29 measure,30 WHOLE_PROJECT,31} from "@repo/checks/kinds/ratchet";32import type { RaiseRatchet, RatchetCount } from "@repo/checks/kinds/ratchet";33import { redFirstOfRuns } from "@repo/checks/red-first";34import { weaknessesOf } from "@repo/checks/weak-shapes";35import {36 escapeDecisions,37 escapeRatchet,38 explainedRaises,39 territoryOf,40} from "@repo/gate/escapes";41import type { Waiver } from "@repo/gate/escapes";42import { PushTarget } from "@repo/gate/facts";43import type { PushFacts } from "@repo/gate/facts";Merge observability into mainoscabrielbefore adoption1985111
lines 44–45why, one step back44import { pushStages, refusingStage, runGate } from "@repo/gate/gate";45import type { StageRefusal } from "@repo/gate/gate";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 46–54why, one step back46import { scan } from "@repo/gate/stages/shape";47import { verdictOf } from "@repo/gate/verdict";48import { patchId } from "@repo/git/patch-id";49import { formatLanding } from "@repo/git/trailers";50import { HarnessAudit } from "@repo/protocol/audit";51import {52 Claim as ClaimContract,53 Credits,54 Decide,Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 55why, one step back55 DraftAsk,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 56–66why, one step back56 EnvSchemaOf,57 EvidenceOf,58 Finish,59 FlagAsk,60 Fork,61 InitProject,62 Land,63 LandingOf,64 LedgerOf,65 ListAsks,66 OpenAsk,Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
line 67why, one step back67 PolicyOf,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 68–71why, one step back68 ProposeAsk,69 Release,70 SetEnv,71 ShowAsk,Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 72why, one step back72 ShowProposal,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 73–87why, one step back73 Status,74 SubmitAnswer,75 TodayOf,76 VerdictOf,77 Vouch,78} from "@repo/protocol/contracts";79import {80 AnswerReceipt,81 HeldBackResult,82 Verdict,83} from "@repo/protocol/domain/answer";84import type { AnswerView, LaneResult } from "@repo/protocol/domain/answer";85import type { Ask, AskListing } from "@repo/protocol/domain/ask";86import { CheckSpec } from "@repo/protocol/domain/check";87import type { ClaimView } from "@repo/protocol/domain/claim";Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 88why, one step back88import { ForkRef } from "@repo/protocol/domain/code";Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 89–91why, one step back89import {90 AtLeastOne,91 ConfigFile,Merge redesign into mainoscabrielbefore adoptioncaedd21
line 92why, one step back92 NoneOrMore,Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 93–95why, one step back93 RefNameText,94} from "@repo/protocol/domain/common";95import type { Evidence } from "@repo/protocol/domain/common";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 96–100why, one step back96import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";97import { DecisionSubject } from "@repo/protocol/domain/decision";98import type { Choice, Decision } from "@repo/protocol/domain/decision";99import { ProjectEvent } from "@repo/protocol/domain/event";100import type { AskKind } from "@repo/protocol/domain/kind";Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 101why, one step back101import { LandingView } from "@repo/protocol/domain/landing";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 102–103why, one step back102import { Outcome } from "@repo/protocol/domain/outcome";103import type { StageName } from "@repo/protocol/domain/outcome";Merge build/imported-from into mainoscabrielbefore adoptionf224a14
line 104why, one step back104import type { ImportSource, PublicPolicy } from "@repo/protocol/domain/policy";Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
line 105why, one step back105import { Policy } from "@repo/protocol/domain/policy";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 106–113why, one step back106import type { Proposal } from "@repo/protocol/domain/proposal";107import {108 AskId,109 CommitSha,110 EnvKey,111 Handle,112 LandedSha,113 LayerName,Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 114why, one step back114 ProposalId,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 115–118why, one step back115 RepoName,116 RepoPath,117 RequestId,118 TreeSha,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 119why, one step back119 addressOfRepo,Merge build/1400-followups into mainoscabrielbefore adoption7a90542
line 120why, one step back120 claimForkName,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 121–123why, one step back121 isSourceNamespace,122 keyOf,123 ownerOf,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 124why, one step back124 sameHandle,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 125why, one step back125 sourceNamespaceOf,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 126why, one step back126} from "@repo/protocol/ids";Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 127why, one step back127import type { DecisionId, LaneName, ProjectName } from "@repo/protocol/ids";Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
line 128why, one step back128import { Posture } from "@repo/protocol/posture";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 129–137why, one step back129import { Person, Principal } from "@repo/protocol/principal";130import {131 AskFull,132 DirectPush,133 ImportFailed,134 IncompleteBrief,135 NotClaimed,136 NotDecider,137 NotRedFirst,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 138why, one step back138 NotYourNamespace,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 139why, one step back139 ProjectExists,Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 140why, one step back140 ProposalClosed,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 141–146why, one step back141 Refusal,142 StaleBase,143 TouchedJudge,144 UnknownAsk,145 UnknownCommit,146 UnknownProject,Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 147why, one step back147 UnknownProposal,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 148–175why, one step back148 VerifierBlocked,149 WeakCheck,150} from "@repo/protocol/refusal";151import type {152 AskBlocked,153 CapReached,154 ClaimLapsed,155 Denounced,156 OutOfScope,157 PrivatePathInPublicTree,158 ReachedInternals,159 RepoBusy,160 Weakened,161 NotVouched,162} from "@repo/protocol/refusal";163import { Finishers } from "@repo/rules/finish";164import { RulesEvaluator, sdkVersion } from "@repo/rules/rules-evaluator";165import {166 Array,167 Cause,168 Context,169 DateTime,170 Effect,171 Layer,172 Match,173 Option,174 Order,175 Record,Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 176why, one step back176 Ref,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 177–196why, one step back177 Result,178 Schema,179 Semaphore,180 Struct,181} from "effect";182import type { Data } from "effect";183import { init } from "isomorphic-git";184185import { Alarms } from "./alarms.ts";186import {187 AnswerReport,188 AnswerRun,189 MeasuredCount,190 ReportedCommand,191 Steps,192} from "./answer-runs.ts";193import type { AnswerQueue, AnswerRuns, RunnableEffect } from "./answer-runs.ts";194import { isStep } from "./answer-runs/steps.ts";195import { openDecision } from "./attention/decisions.ts";196import { recordOf } from "./attention/record.ts";Merge build/standing-caps into mainoscabrielbefore adoption8a78de8
line 197why, one step back197import { capFor, capped, mayClaim, standing } from "./attention/vouch.ts";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 198–206why, one step back198import {199 ClaimCommand,200 ClaimEffect,201 ClaimState,202 toView,203 transition as claimTransition,204} from "./claim.ts";205import type { ClaimStep, Live } from "./claim.ts";206import {Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 207why, one step back207 askIdOf,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 208–214why, one step back208 deciderDeadlines,209 deciders,210 decidersOn,211 decidesOn,212 envSchemaMethod,213 isDecider,214 nextDecisionId,Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 215why, one step back215 pathsOf,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 216–218why, one step back216 strayDecision,217} from "./deciders.ts";218import type { DeciderApi, Opening } from "./deciders.ts";Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 219–226why, one step back219import {220 DraftContextData,221 DraftResult,222 DraftRuns,223 EXCERPT_BYTES,224 Rehearsal,225} from "./draft-runs.ts";226import type { Diagnosis } from "./draft-runs.ts";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 227–253why, one step back227import { ProjectEnv } from "./env-port.ts";228import {229 askClosed,230 askOpened,231 judged,232 listingOf,233 numbered,234 ProjectEventInput,235} from "./events.ts";236import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";237import type { MissingCommit } from "./facts.ts";238import {239 generatedFollowUp,240 generatedRequestId,241 ProjectGenerator,242} from "./generated.ts";243import { Lander, Rebuild } from "./lander.ts";244import type { ComposedFile } from "./lander.ts";245import {246 LandingCommand,247 LandingEffect,248 LandingState,249 outcomeOf,250 transition as landingTransition,251} from "./landing.ts";252import type { LandingQueue, PendingDecision, Request } from "./landing.ts";253import {Merge observability into mainoscabrielbefore adoption1985111
lines 254–260why, one step back254 lanePoints,255 MetricPoint,256 Metrics,257 millisBetween,258 refusedPoints,259} from "./metrics.ts";260import {Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 261–271why, one step back261 callerCountOf,262 callersIn,263 callersRatchet,264 callersSpecs,265 familyClosed,266 remainingBlockers,267 sameCount,268 splitFamily,269} from "./migrate.ts";270import {271 isDue,Merge observability into mainoscabrielbefore adoption1985111
line 272why, one step back272 measuredRow,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 273–321why, one step back273 outboxRow,274 OutboxBody,275 projectedRows,276 runOutbox,277 startRow,278} from "./outbox.ts";279import { ProjectStore } from "./project-store.ts";280import type { ProjectSnapshot, ProjectWrites } from "./project-store.ts";281import type {282 AnswerRow,283 AttemptRow,284 BudgetDayRow,285 ClaimRow,286 EnvValueRow,287 LayerRead,288 LayerRow,289 LedgerRow,290 OutboxRow,291 PinnedSuite,292 ProjectRow,293 PushEventRow,294 RatchetRow,295} from "./project-store/rows.ts";296import { Tables } from "./project-store/tables.ts";297import type { Table } from "./project-store/tables.ts";298import type { Projection } from "./projection.ts";299import { askToLand, holdsSlot, leave, queueOf, storedQueue } from "./queue.ts";300import { afterLanding, decideRaise } from "./ratchets.ts";301import type { RatchetBaseline } from "./ratchets.ts";302import {303 AdmissionPlan,304 AdmissionReport,305 HeldBackJob,306 LayerAccess,307 LayerFacts,308 ProjectVisibility,309} from "./visibility-port.ts";310import type { VisibilityPlan } from "./visibility-port.ts";311312export type ProjectPorts =313 | Alarms314 | AnswerRuns315 | CheckRunner316 | Lander317 | ProjectStore318 | Projection319 | RepoHost320 | RulesEvaluator;321Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 322why, one step back322/** The gateway every repo's git URL starts with; never an Artifacts URL. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 323–326why, one step back323export const GatewayUrl = Context.Reference<string>("project/GatewayUrl", {324 defaultValue: () => `https://${Brand.domain}`,325});326Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 327why, one step back327/** Injected from `@repo/checks` because `rules` may not import `checks`. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 328–334why, one step back328export const FinishersFromChecks: Layer.Layer<Finishers> = Layer.succeed(329 Finishers,330 { findRunBlock, judgeClosure }331);332333export const PushReport = Schema.Struct({334 after: CommitSha,Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 335why, one step back335 /** Self-reported by the credential helper: audit metadata, never who pushed. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 336–350why, one step back336 audit: Schema.optionalKey(HarnessAudit),337 before: Schema.Option(CommitSha),338 eventId: Schema.NonEmptyString,339 pusher: Principal,340 ref: Schema.NonEmptyString,341 repo: RepoName,342});343344export type PushReport = typeof PushReport.Type;345346export interface AskFile {347 readonly content: string;348 readonly path: RepoPath;349}350Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 351–358why, one step back351export const StandingNow = Schema.Struct({352 posture: Posture,353 seen: Schema.Int,354 until: Schema.optionalKey(Schema.DateTimeUtcFromString),355});356357export type StandingNow = typeof StandingNow.Type;358Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 359–389why, one step back359export type SubmitRefusal =360 | NotClaimed361 | ClaimLapsed362 | StaleBase363 | RepoBusy364 | OutOfScope365 | TouchedJudge366 | Weakened367 | ReachedInternals368 | PrivatePathInPublicTree;369370export interface ProjectApi extends AnswerQueue, DeciderApi {371 readonly listAsks: (372 caller: Principal373 ) => Effect.Effect<{ readonly asks: readonly AskListing[] }>;374 readonly showAsk: (375 caller: Principal,376 ask: AskId377 ) => Effect.Effect<{ readonly ask: Ask; readonly brief: string }, UnknownAsk>;378 readonly status: (caller: Person) => Effect.Effect<{379 readonly answers: readonly AnswerView[];380 readonly claims: readonly ClaimView[];381 }>;382 readonly verdict: (383 caller: Principal,384 input: { readonly ask: AskId; readonly head?: CommitSha }385 ) => Effect.Effect<{ readonly verdict?: Verdict }, UnknownAsk>;386 readonly landing: (387 caller: Principal,388 sha: CommitSha389 ) => Effect.Effect<{ readonly landing: LandingView }, UnknownCommit>;Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 390why, one step back390 readonly head: () => Effect.Effect<{ readonly landed?: LandedSha }>;Merge redesign into mainoscabrielbefore adoptioncaedd21
lines 391–392why, one step back391 /** How many landings the platform has made on main, every one it keeps. */392 readonly landingCount: () => Effect.Effect<number>;Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 393why, one step back393 readonly forks: () => Effect.Effect<readonly ForkRef[]>;Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
line 394why, one step back394 readonly standing: () => Effect.Effect<StandingNow>;Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
line 395why, one step back395 readonly policy: () => Effect.Effect<PolicyStatus>;Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 396–407why, one step back396 readonly draftContext: (397 proposal: ProposalId,398 round: number399 ) => Effect.Effect<DraftContextData, UnknownProposal | ProposalClosed>;400 readonly rehearseOpen: (401 files: readonly ConfigFile[]402 ) => Effect.Effect<Rehearsal, VerifierBlocked | StaleBase>;403 readonly draftSettled: (404 proposal: ProposalId,405 round: number,406 result: DraftResult407 ) => Effect.Effect<void>;Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 408–437why, one step back408 readonly evidence: (409 caller: Principal,410 ref: LogRef411 ) => Effect.Effect<412 {413 readonly lane: LaneName;414 readonly text: string;415 readonly truncated: boolean;416 },417 NotDecider | UnknownProject,418 EvidenceStore419 >;420 readonly events: (421 since: number,422 limit: number423 ) => Effect.Effect<424 readonly { readonly event: ProjectEvent; readonly seq: number }[]425 >;426 readonly firstPusher: () => Effect.Effect<Option.Option<Handle>>;427 readonly initProject: (428 caller: Person,429 input: {430 readonly import?: { readonly branch?: string; readonly url: string };431 }432 ) => Effect.Effect<433 {434 readonly landed?: LandedSha;435 readonly project: ProjectName;436 readonly remote: string;437 },Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 438why, one step back438 ProjectExists | NotYourNamespace | ImportFailedMerge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 439–511why, one step back439 >;440 readonly recordFirstPush: (441 caller: Person,442 head: CommitSha443 ) => Effect.Effect<{ readonly landed: LandedSha }, DirectPush>;444 readonly openAsk: (445 caller: Person,446 input: {447 readonly ask: AskId;448 readonly files: Array.NonEmptyReadonlyArray<AskFile>;449 }450 ) => Effect.Effect<451 { readonly ask: Ask; readonly landed: LandedSha },452 | NotDecider453 | NotRedFirst454 | WeakCheck455 | IncompleteBrief456 | TouchedJudge457 | VerifierBlocked458 | StaleBase459 >;460 readonly claim: (461 caller: Person,462 ask: AskId463 ) => Effect.Effect<464 { readonly claim: ClaimView },465 UnknownAsk | AskFull | AskBlocked | CapReached | NotVouched | Denounced466 >;467 readonly release: (468 caller: Person,469 ask: AskId470 ) => Effect.Effect<{ readonly released: boolean }, NotClaimed>;471 readonly recordPush: (input: PushReport) => Effect.Effect<readonly Refusal[]>;472 readonly submitAnswer: (473 caller: Person,474 input: {475 readonly ask: AskId;476 readonly base: CommitSha;477 readonly head: CommitSha;478 readonly requestId: RequestId;479 }480 ) => Effect.Effect<AnswerReceipt, SubmitRefusal>;481 readonly onAlarm: () => Effect.Effect<void>;482 readonly layerAccess: (483 caller: Principal,484 layer: LayerName485 ) => Effect.Effect<Option.Option<LayerAccess>>;486 readonly layerFacts: (caller: Principal) => Effect.Effect<LayerFacts>;487 readonly recordLayerPush: (488 caller: Person,489 input: { readonly head: CommitSha; readonly layer: LayerName }490 ) => Effect.Effect<void>;491 readonly recordLayerRead: (492 caller: Person,493 input: { readonly layer: LayerName; readonly sha?: CommitSha }494 ) => Effect.Effect<void>;495 readonly heldBackJob: (496 requestId: RequestId497 ) => Effect.Effect<Option.Option<HeldBackJob>>;498 readonly recordHeldBack: (499 requestId: RequestId,500 results: readonly HeldBackResult[]501 ) => Effect.Effect<readonly Refusal[]>;502 readonly admissionPlan: (input: {503 readonly head: CommitSha;504 readonly layer: LayerName;505 }) => Effect.Effect<Option.Option<AdmissionPlan>>;506 readonly recordAdmission: (input: AdmissionReport) => Effect.Effect<void>;507 readonly scanForValues: (508 input: { readonly text: string } | { readonly blob: Uint8Array }509 ) => Effect.Effect<Option.Option<EnvKey>>;510}511Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 512–513why, one step back512const MAX_DRAFT_PATHS = 50_000;513Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 514–515why, one step back514export type PolicyStatus = typeof PolicyOf.successSchema.Type;515Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 516–517why, one step back516export const MAX_LANDINGS = 100;517Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 518–559why, one step back518export interface MethodSchema {519 readonly args: readonly Schema.Top[];520 readonly error: Schema.Top;521 readonly success: Schema.Top & { readonly EncodingServices: never };522}523524export const MethodSchemas = {525 [envSchemaMethod]: {526 args: [Principal],527 error: EnvSchemaOf.errorSchema,528 success: EnvSchemaOf.successSchema,529 },530 admissionPlan: {531 args: [Schema.Struct({ head: CommitSha, layer: LayerName })],532 error: Schema.Never,533 success: Schema.Option(AdmissionPlan),534 },535 advanceAnswer: {536 args: [RequestId, ReportedCommand, Schema.UndefinedOr(AnswerReport)],537 error: Schema.Never,538 success: Steps,539 },540 answer: {541 args: [RequestId],542 error: Schema.Never,543 success: Schema.Option(AnswerRun),544 },545 claim: {546 args: [Person, AskId],547 error: ClaimContract.errorSchema,548 success: ClaimContract.successSchema,549 },550 credits: {551 args: [Principal, Handle],552 error: Schema.Never,553 success: Credits.successSchema,554 },555 decide: {556 args: [Person, Decide.payloadSchema.mapFields(Struct.omit(["project"]))],557 error: Decide.errorSchema,558 success: Decide.successSchema,559 },Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 560–564why, one step back560 draftAsk: {561 args: [Person, DraftAsk.payloadSchema.mapFields(Struct.omit(["project"]))],562 error: DraftAsk.errorSchema,563 success: DraftAsk.successSchema,564 },Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 565–574why, one step back565 draftContext: {566 args: [ProposalId, AtLeastOne],567 error: Schema.Union([UnknownProposal, ProposalClosed]),568 success: DraftContextData,569 },570 draftSettled: {571 args: [ProposalId, AtLeastOne, DraftResult],572 error: Schema.Never,573 success: Schema.Void,574 },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 575–606why, one step back575 events: {576 args: [Schema.Int, Schema.Int],577 error: Schema.Never,578 success: Schema.Array(579 Schema.Struct({ event: ProjectEvent, seq: Schema.Int })580 ),581 },582 evidence: {583 args: [Principal, LogRef],584 error: EvidenceOf.errorSchema,585 success: EvidenceOf.successSchema,586 },587 finish: {588 args: [Person, Finish.payloadSchema.mapFields(Struct.omit(["project"]))],589 error: Finish.errorSchema,590 success: Finish.successSchema,591 },592 firstPusher: {593 args: [],594 error: Schema.Never,595 success: Schema.Option(Handle),596 },597 flagAsk: {598 args: [Person, FlagAsk.payloadSchema.mapFields(Struct.omit(["project"]))],599 error: FlagAsk.errorSchema,600 success: FlagAsk.successSchema,601 },602 fork: {603 args: [Person],604 error: Fork.errorSchema,605 success: Fork.successSchema,606 },Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 607–612why, one step back607 forks: { args: [], error: Schema.Never, success: Schema.Array(ForkRef) },608 head: {609 args: [],610 error: Schema.Never,611 success: Schema.Struct({ landed: Schema.optionalKey(LandedSha) }),612 },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 613–635why, one step back613 heldBackJob: {614 args: [RequestId],615 error: Schema.Never,616 success: Schema.Option(HeldBackJob),617 },618 initProject: {619 args: [620 Person,621 Schema.Struct({ import: InitProject.payloadSchema.fields.import }),622 ],623 error: InitProject.errorSchema,624 success: InitProject.successSchema,625 },626 land: {627 args: [Person, Land.payloadSchema.mapFields(Struct.omit(["project"]))],628 error: Land.errorSchema,629 success: Land.successSchema,630 },631 landing: {632 args: [Principal, CommitSha],633 error: LandingOf.errorSchema,634 success: LandingOf.successSchema,635 },Merge redesign into mainoscabrielbefore adoptioncaedd21
line 636why, one step back636 landingCount: { args: [], error: Schema.Never, success: NoneOrMore },Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 637–641why, one step back637 landings: {638 args: [Schema.Array(CommitSha).check(Schema.isMaxLength(MAX_LANDINGS))],639 error: Schema.Never,640 success: Schema.Array(LandingView),641 },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 642–670why, one step back642 layerAccess: {643 args: [Principal, LayerName],644 error: Schema.Never,645 success: Schema.Option(LayerAccess),646 },647 layerFacts: {648 args: [Principal],649 error: Schema.Never,650 success: LayerFacts,651 },652 ledger: {653 args: [Principal],654 error: LedgerOf.errorSchema,655 success: LedgerOf.successSchema,656 },657 listAsks: {658 args: [Principal],659 error: ListAsks.errorSchema,660 success: ListAsks.successSchema,661 },662 onAlarm: { args: [], error: Schema.Never, success: Schema.Void },663 openAsk: {664 args: [665 Person,666 Schema.Struct({ ask: AskId, files: OpenAsk.payloadSchema.fields.files }),667 ],668 error: OpenAsk.errorSchema,669 success: OpenAsk.successSchema,670 },Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 671–673why, one step back671 policy: {672 args: [],673 error: Schema.Never,Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
line 674why, one step back674 success: PolicyOf.successSchema,Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 675why, one step back675 },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 676–678why, one step back676 proposeAsk: {677 args: [678 Person,Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 679–682why, one step back679 // The check reads only `draft`, `files` and `sealed`, which it keeps.680 ProposeAsk.payloadSchema.mapFields(Struct.omit(["project"]), {681 unsafePreserveChecks: true,682 }),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 683–719why, one step back683 ],684 error: ProposeAsk.errorSchema,685 success: ProposeAsk.successSchema,686 },687 recordAdmission: {688 args: [AdmissionReport],689 error: Schema.Never,690 success: Schema.Void,691 },692 recordFirstPush: {693 args: [Person, CommitSha],694 error: DirectPush,695 success: Schema.Struct({ landed: LandedSha }),696 },697 recordHeldBack: {698 args: [RequestId, Schema.Array(HeldBackResult)],699 error: Schema.Never,700 success: Schema.Array(Refusal),701 },702 recordLayerPush: {703 args: [Person, Schema.Struct({ head: CommitSha, layer: LayerName })],704 error: Schema.Never,705 success: Schema.Void,706 },707 recordLayerRead: {708 args: [709 Person,710 Schema.Struct({ layer: LayerName, sha: Schema.optionalKey(CommitSha) }),711 ],712 error: Schema.Never,713 success: Schema.Void,714 },715 recordPush: {716 args: [PushReport],717 error: Schema.Never,718 success: Schema.Array(Refusal),719 },Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 720–724why, one step back720 rehearseOpen: {721 args: [Schema.Array(ConfigFile)],722 error: Schema.Union([VerifierBlocked, StaleBase]),723 success: Rehearsal,724 },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 725–749why, one step back725 release: {726 args: [Person, AskId],727 error: Release.errorSchema,728 success: Release.successSchema,729 },730 scanForValues: {731 args: [732 Schema.Union([733 Schema.Struct({ text: Schema.String }),734 Schema.Struct({ blob: Schema.Uint8Array }),735 ]),736 ],737 error: Schema.Never,738 success: Schema.Option(EnvKey),739 },740 setEnv: {741 args: [Person, SetEnv.payloadSchema.mapFields(Struct.omit(["project"]))],742 error: SetEnv.errorSchema,743 success: SetEnv.successSchema,744 },745 showAsk: {746 args: [Principal, AskId],747 error: ShowAsk.errorSchema,748 success: ShowAsk.successSchema,749 },Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 750–754why, one step back750 showProposal: {751 args: [Principal, ProposalId],752 error: ShowProposal.errorSchema,753 success: ShowProposal.successSchema,754 },Merge build/1213-platform-performance-and-agent-surfacesoscabrielbefore adoption1d75a0d
lines 755–759why, one step back755 standing: {756 args: [],757 error: Schema.Never,758 success: StandingNow,759 },Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 760–818why, one step back760 status: {761 args: [Person],762 error: Status.errorSchema,763 // The contract adds the caller's handle at the platform's edge; a project764 // answers with its own claims and answers only.765 success: Status.successSchema.mapFields(Struct.omit(["handle"])),766 },767 submitAnswer: {768 args: [769 Person,770 Schema.Struct({771 ask: AskId,772 base: CommitSha,773 head: CommitSha,774 requestId: RequestId,775 }),776 ],777 error: SubmitAnswer.errorSchema,778 success: SubmitAnswer.successSchema,779 },780 today: {781 args: [Person],782 error: TodayOf.errorSchema,783 success: TodayOf.successSchema,784 },785 verdict: {786 args: [787 Principal,788 Schema.Struct({ ask: AskId, head: Schema.optionalKey(CommitSha) }),789 ],790 error: VerdictOf.errorSchema,791 success: VerdictOf.successSchema,792 },793 vouch: {794 args: [Person, Vouch.payloadSchema.mapFields(Struct.omit(["project"]))],795 error: Vouch.errorSchema,796 success: Vouch.successSchema,797 },798} as const satisfies { readonly [M in keyof ProjectApi]: MethodSchema };799800export const Measured = Schema.Struct({801 declared: Schema.Array(MeasuredCount),802 escapes: Schema.Array(MeasuredCount),803});804805export type Measured = typeof Measured.Type;806807export const HeldBackJudged = Schema.Struct({808 refusals: Schema.Array(Refusal),809 trailer: Schema.optionalKey(Schema.NonEmptyString),810 tree: TreeSha,811});812813export type HeldBackJudged = typeof HeldBackJudged.Type;814815export const AnswerRecord = Schema.Struct({816 heldBack: Schema.optionalKey(HeldBackJudged),817 landing: LandingState,818 measured: Schema.optionalKey(Measured),Merge observability into mainoscabrielbefore adoption1985111
lines 819–820why, one step back819 /** When the answer was queued: absent from an answer queued before it was kept. */820 queuedAt: Schema.optionalKey(Schema.DateTimeUtcFromString),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 821–864why, one step back821 receipt: AnswerReceipt,822 verdict: Schema.optionalKey(Verdict),823 waived: Schema.optionalKey(Schema.Array(DecisionSubject.cases.Waiver)),824});825826export type AnswerRecord = typeof AnswerRecord.Type;827828const ClaimJson = Schema.toCodecJson(ClaimState);829830const AnswerJson = Schema.toCodecJson(AnswerRecord);831832const PolicyJson = Schema.toCodecJson(Policy);833834const decodeClaim = Schema.decodeUnknownEffect(ClaimJson);835836const encodeClaim = Schema.encodeEffect(ClaimJson);837838const decodeAnswer = Schema.decodeUnknownEffect(AnswerJson);839840const encodeAnswer = Schema.encodeEffect(AnswerJson);841842const decodePolicy = Schema.decodeUnknownEffect(PolicyJson);843844const encodePolicy = Schema.encodeEffect(PolicyJson);845846const checked = <A, E, R>(847 schemas: MethodSchema,848 args: readonly unknown[],849 run: Effect.Effect<A, E, R>850): Effect.Effect<A, E, R> =>851 Effect.forEach(852 schemas.args,853 (schema, index) =>854 Effect.orDie(855 Schema.decodeUnknownEffect(Schema.toType(schema))(args[index])856 ),857 { discard: true }858 ).pipe(859 Effect.andThen(run),860 Effect.tap((value) =>861 Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))862 )863 );864Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 865–886why, one step back865const publicPolicy = (policy: Policy): PublicPolicy =>866 Struct.omit(policy, ["asks", "functions", "visibility"]);867868const listedFork = (claim: Live, state: ClaimView["state"]) =>869 Option.some<ForkRef>({870 ask: claim.ask,871 handle: claim.claimant,872 kind: "claim",873 repo: claim.fork,874 state,875 });876877const forkOf = (state: ClaimState): Option.Option<ForkRef> =>878 ClaimState.match(state, {879 Answered: (claim) => listedFork(claim, "answered"),880 Lapsed: (claim) => listedFork(claim, "lapsed"),881 Live: (claim) => listedFork(claim, "live"),882 Open: () => Option.none(),883 Released: (claim) => listedFork(claim, "released"),884 Warned: (claim) => listedFork(claim, "warned"),885 });886Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 887–890why, one step back887const EVIDENCE_TAIL = 256 * 1024;888889const startsCharacter = (byte: number) => byte < 0x80 || byte >= 0xc0;890Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 891why, one step back891/** The log's tail, where a failure prints, cut between UTF-8 characters. */Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 892why, one step back892const tailOf = (log: string, limit = EVIDENCE_TAIL) => {Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 893–894why, one step back893 const bytes = new TextEncoder().encode(log);894Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 895why, one step back895 if (bytes.length <= limit) {Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 896–898why, one step back896 return { text: log, truncated: false };897 }898Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 899why, one step back899 const tail = bytes.subarray(bytes.length - limit);Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 900–943why, one step back900 const from = tail.findIndex(startsCharacter);901902 return {903 text: from === -1 ? "" : new TextDecoder().decode(tail.subarray(from)),904 truncated: true,905 };906};907908const mainRef = RefName.make("refs/heads/main");909910const HOUR = 3_600_000;911912const defaultClaims: Policy["claims"] = {913 lapseAfterMs: 24 * HOUR,914 warnAfterMs: 2 * HOUR,915};916917interface Claimed {918 readonly row: ClaimRow;919 readonly state: ClaimState;920}921922interface Answered {923 readonly record: AnswerRecord;924 readonly row: AnswerRow;925}926927interface Hydrated {928 readonly answers: readonly Answered[];929 readonly asks: ReadonlyMap<AskId, Ask>;930 readonly budgetDays: readonly BudgetDayRow[];931 readonly claims: readonly Claimed[];932 readonly decisions: readonly Decision[];933 readonly landings: readonly LandingView[];934 readonly lastSeq: number;935 readonly outbox: readonly OutboxRow[];936 readonly policy: Option.Option<Policy>;937 readonly project: Option.Option<ProjectRow>;938 readonly proposals: readonly Proposal[];939 readonly queue: LandingQueue;940 readonly ratchets: readonly RatchetRow[];941 readonly snapshot: ProjectSnapshot;942}943Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 944why, one step back944/** The project row and the queue sit in one-entry maps so the record itself never changes. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 945–1008why, one step back945interface Writes {946 readonly answers: Map<RequestId, AnswerRow>;947 readonly asks: Map<AskId, Ask>;948 readonly attempts: Map<string, AttemptRow>;949 readonly budgetDays: Map<string, BudgetDayRow>;950 readonly claims: Map<string, ClaimRow>;951 readonly decisions: Map<DecisionId, Decision>;952 readonly envValues: Map<EnvKey, EnvValueRow>;953 readonly events: ProjectEventInput[];954 readonly landings: LandingView[];955 readonly layerReads: LayerRead[];956 readonly layers: Map<LayerName, LayerRow>;957 readonly ledger: Map<number, LedgerRow>;958 readonly outbox: OutboxRow[];959 readonly project: Map<"row", ProjectRow>;960 readonly proposals: Map<ProposalId, Proposal>;961 readonly pushEvents: PushEventRow[];962 readonly queue: Map<"queue", LandingQueue>;963 readonly ratchets: Map<string, RatchetRow>;964}965966const writesOf = (): Writes => ({967 answers: new Map(),968 asks: new Map(),969 attempts: new Map(),970 budgetDays: new Map(),971 claims: new Map(),972 decisions: new Map(),973 envValues: new Map(),974 events: [],975 landings: [],976 layerReads: [],977 layers: new Map(),978 ledger: new Map(),979 outbox: [],980 project: new Map(),981 proposals: new Map(),982 pushEvents: [],983 queue: new Map(),984 ratchets: new Map(),985});986987const isEmpty = (writes: Writes) =>988 [989 writes.answers.size,990 writes.asks.size,991 writes.attempts.size,992 writes.budgetDays.size,993 writes.claims.size,994 writes.decisions.size,995 writes.envValues.size,996 writes.events.length,997 writes.landings.length,998 writes.layerReads.length,999 writes.layers.size,1000 writes.ledger.size,1001 writes.outbox.length,1002 writes.project.size,1003 writes.proposals.size,1004 writes.pushEvents.length,1005 writes.queue.size,1006 writes.ratchets.size,1007 ].every((count) => count === 0);1008Merge build/1316-adoption-heard into mainoscabrielbefore adoption2f3d065
lines 1009–1017why, one step back1009const keepLanding = (1010 writes: Writes,1011 landing: LandingView,1012 now: DateTime.Utc1013) => {1014 writes.landings.push(landing);1015 writes.events.push(ProjectEventInput.Landed({ at: now, landing }));1016};1017Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1018–1207why, one step back1018const keyIn = <A>(table: Table<A>, row: A) => {1019 const columns = table.columns(row);10201021 return JSON.stringify(table.key.map((name) => columns[name]));1022};10231024const overlaid = <A>(1025 table: Table<A>,1026 held: readonly A[],1027 written: Iterable<A>1028): readonly A[] => {1029 const fresh = new Map(1030 Array.map([...written], (row) => [keyIn(table, row), row])1031 );10321033 const kept = new Set(held.map((row) => keyIn(table, row)));10341035 return [1036 ...held.map((row) => fresh.get(keyIn(table, row)) ?? row),1037 ...[...fresh.values()].filter((row) => !kept.has(keyIn(table, row))),1038 ];1039};10401041const bySeq = Order.mapInput(Order.Number, (entry: LedgerRow) => entry.seq);10421043const snapshotNow = (h: Hydrated, writes: Writes): ProjectSnapshot => {1044 const held = h.snapshot;10451046 return {1047 ...held,1048 answers: overlaid(Tables.answers, held.answers, writes.answers.values()),1049 asks: overlaid(Tables.asks, held.asks, writes.asks.values()),1050 attempts: overlaid(1051 Tables.attempts,1052 held.attempts,1053 writes.attempts.values()1054 ),1055 budgetDays: overlaid(1056 Tables.budgetDays,1057 held.budgetDays,1058 writes.budgetDays.values()1059 ),1060 claims: overlaid(Tables.claims, held.claims, writes.claims.values()),1061 decisions: overlaid(1062 Tables.decisions,1063 held.decisions,1064 writes.decisions.values()1065 ),1066 envValues: overlaid(1067 Tables.envValues,1068 held.envValues,1069 writes.envValues.values()1070 ),1071 landings: [...writes.landings.toReversed(), ...held.landings],1072 layers: overlaid(Tables.layers, held.layers, writes.layers.values()),1073 ledger: Array.sort(1074 overlaid(Tables.ledger, held.ledger, writes.ledger.values()),1075 bySeq1076 ),1077 outbox: [...held.outbox, ...writes.outbox],1078 project: Option.orElse(1079 Option.fromUndefinedOr(writes.project.get("row")),1080 () => held.project1081 ),1082 proposals: overlaid(1083 Tables.proposals,1084 held.proposals,1085 writes.proposals.values()1086 ),1087 ratchets: overlaid(1088 Tables.ratchets,1089 held.ratchets,1090 writes.ratchets.values()1091 ),1092 };1093};10941095const portTables = new Set<string>([1096 "attempts",1097 "decisions",1098 "envValues",1099 "events",1100 "layerReads",1101 "layers",1102 "ledger",1103 "outbox",1104]);11051106const absorb = (writes: Writes, more: ProjectWrites) => {1107 const foreign = Object.keys(more).filter((table) => !portTables.has(table));11081109 if (Array.isReadonlyArrayNonEmpty(foreign)) {1110 return Effect.die(1111 `a visibility port wrote ${foreign.join(", ")}, which the project service writes itself`1112 );1113 }11141115 for (const row of more.attempts ?? []) {1116 writes.attempts.set(keyIn(Tables.attempts, row), row);1117 }11181119 for (const row of more.decisions ?? []) {1120 writes.decisions.set(row.id, row);1121 }11221123 for (const row of more.envValues ?? []) {1124 writes.envValues.set(row.key, row);1125 }11261127 for (const row of more.layers ?? []) {1128 writes.layers.set(row.name, row);1129 }11301131 for (const row of more.ledger ?? []) {1132 writes.ledger.set(row.seq, row);1133 }11341135 writes.events.push(...(more.events ?? []));1136 writes.layerReads.push(...(more.layerReads ?? []));1137 writes.outbox.push(...(more.outbox ?? []));11381139 return Effect.void;1140};11411142const applyPlan = (writes: Writes, plan: VisibilityPlan, now: DateTime.Utc) =>1143 Effect.gen(function* () {1144 yield* absorb(writes, plan.writes);11451146 yield* Effect.forEach(1147 plan.effects,1148 (effect) =>1149 Effect.map(1150 outboxRow(1151 `visibility:${effect.id}`,1152 OutboxBody.cases.Visibility.make({ effect }),1153 now1154 ),1155 (row) => writes.outbox.push(row)1156 ),1157 { discard: true }1158 );1159 });11601161const claimKey = (ask: AskId, claimant: Handle) =>1162 JSON.stringify([ask, claimant.toLowerCase()]);11631164const claimOf = (state: ClaimState): Option.Option<Live> =>1165 ClaimState.match(state, {1166 Answered: (claim) => Option.some<Live>(claim),1167 Lapsed: (claim) => Option.some<Live>(claim),1168 Live: (claim) => Option.some<Live>(claim),1169 Open: () => Option.none(),1170 Released: (claim) => Option.some<Live>(claim),1171 Warned: (claim) => Option.some<Live>(claim),1172 });11731174const isLive = ClaimState.isAnyOf(["Live", "Warned"]);11751176const deadlineOf = (state: ClaimState): Option.Option<DateTime.Utc> =>1177 ClaimState.match(state, {1178 Answered: () => Option.none(),1179 Lapsed: () => Option.none(),1180 Live: ({ warnsAt }) => Option.some(warnsAt),1181 Open: () => Option.none(),1182 Released: () => Option.none(),1183 Warned: ({ lapsesAt }) => Option.some(lapsesAt),1184 });11851186const isPlainPath = (path: string) =>1187 path1188 .split("/")1189 .every(1190 (segment) =>1191 segment !== "" &&1192 segment !== "." &&1193 segment !== ".." &&1194 segment !== ".git"1195 );11961197const holds = (ask: Ask, wanted: AskKind["requires"][number]) =>1198 Match.value(wanted).pipe(1199 Match.when("want", () => ask.brief.want.length > 0),1200 Match.when("current", () => ask.brief.current !== undefined),1201 Match.when("outOfScope", () => ask.brief.outOfScope !== undefined),1202 Match.when("terms", () => ask.brief.terms !== undefined),1203 Match.when("context", () => ask.brief.context !== undefined),1204 Match.whenOr("check", "territory", () => true),1205 Match.exhaustive1206 );1207Merge build/imported-from into mainoscabrielbefore adoptionf224a14
lines 1208–1210why, one step back1208const sameSource = (a: ImportSource, b: ImportSource) =>1209 a.url === b.url && a.branch === b.branch;1210Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1211–1423why, one step back1211const field = <K extends string, A>(1212 key: K,1213 value: Option.Option<A>1214): Partial<Record<K, A>> =>1215 Option.match(value, {1216 onNone: () => ({}),1217 onSome: (present) => Record.singleton(key, present),1218 });12191220const creditsFor = (ask: Ask, answerer: Handle): readonly Credit[] => [1221 { handle: ask.askedBy, role: "Asked-by" },1222 { handle: answerer, role: "Signed-off-by" },1223 ...Option.toArray(1224 Option.map(Option.fromUndefinedOr(ask.mentor), (handle): Credit => ({1225 handle,1226 role: "Mentored-by",1227 }))1228 ),1229];12301231const askLaneOf = (policy: Policy, ask: Ask) =>1232 commandFor(ask.check, policy.run, policy.ratchets);12331234const isCounted = CheckSpec.isAnyOf(["LintToZero", "Migrate", "SymbolAbsent"]);12351236const countsCallers = CheckSpec.isAnyOf(["Migrate", "SymbolAbsent"]);12371238const askCheckLane = (policy: Policy, ask: Ask) =>1239 Option.map(askLaneOf(policy, ask), ({ command, lane }) =>1240 isCounted(ask.check)1241 ? CheckLane.make({ command, lane, output: "stdout" })1242 : CheckLane.make({ command, lane })1243 );12441245const lanesOf = (1246 policy: Policy,1247 ask: Option.Option<Ask>1248): readonly CheckLane[] => [1249 ...Option.toArray(1250 Option.flatMap(ask, (asked) => askCheckLane(policy, asked))1251 ),1252 ...Record.toEntries(policy.run.checks).map(([lane, command]) =>1253 CheckLane.make({ command, lane })1254 ),1255];12561257const countedBy = (policy: Policy, command: string, stdout: string) =>1258 Effect.map(1259 Effect.forEach(1260 policy.ratchets.filter((spec) => spec.measure.command === command),1261 (spec) =>1262 measure(1263 spec,1264 () => Effect.succeed({ code: 0, stdout }),1265 policy.modules1266 ).pipe(1267 Effect.catchTag("CountUnreadable", (unread) =>1268 Effect.as(1269 Effect.logWarning(1270 `the ratchet ${spec.name} has no count in what its command printed`,1271 unread1272 ),1273 []1274 )1275 )1276 )1277 ),1278 (counts): readonly RatchetCount[] => counts.flat()1279 );12801281const ratchetKey = (row: {1282 readonly ratchet: string;1283 readonly territory: string;1284}) => JSON.stringify([row.ratchet, row.territory]);12851286const baselineOf = (row: RatchetRow): RatchetBaseline => ({1287 count: row.count,1288 ratchet: row.ratchet,1289 setAt: row.at,1290 territory: row.territory,1291});12921293const isEscapeRow = (row: {1294 readonly ratchet: string;1295 readonly territory: string;1296}) => row.ratchet === escapeRatchet(row.territory);12971298const sameEscape = (one: Waiver) => (other: Waiver) =>1299 other.ask === one.ask &&1300 other.marker === one.marker &&1301 other.reason === one.reason &&1302 other.at.path === one.at.path &&1303 other.at.line === one.at.line;13041305interface DecidedOn {1306 readonly choice: Choice;1307 readonly subject: PendingDecision["subject"];1308}13091310const decidedOn = (1311 before: LandingState,1312 command: LandingCommand1313): Option.Option<DecidedOn> =>1314 LandingCommand.$is("Decided")(command) &&1315 LandingState.guards.AwaitingDecision(before)1316 ? Option.map(1317 Option.fromUndefinedOr(1318 before.decisions.find(({ id }) => id === command.decision)1319 ),1320 ({ subject }) => ({ choice: command.choice, subject })1321 )1322 : Option.none();13231324const waivedAfter = (1325 waived: readonly Waiver[],1326 decided: Option.Option<DecidedOn>1327): readonly Waiver[] => [1328 ...waived,1329 ...Option.toArray(1330 Option.flatMap(decided, ({ choice, subject }) =>1331 choice === "accept" && DecisionSubject.guards.Waiver(subject)1332 ? Option.some(subject)1333 : Option.none()1334 )1335 ),1336];13371338const evidenceFor = (1339 request: Request,1340 subject: Waiver | RaiseRatchet1341): readonly Evidence[] => [1342 {1343 label: "answer",1344 value: `${request.answerer} at ${request.head} (${request.requestId})`,1345 },1346 DecisionSubject.guards.Waiver(subject)1347 ? {1348 label: "escape",1349 value: `${subject.at.path}:${subject.at.line}: ${subject.marker} -- ${subject.reason}`,1350 }1351 : {1352 label: "ratchet",1353 value: `${subject.ratchet} in ${subject.territory}: ${subject.before} to ${subject.after}`,1354 },1355];13561357const redByCount = (input: {1358 readonly ask: Ask;1359 readonly check: LintToZeroCheck;1360 readonly lane: LaneName;1361 readonly policy: Policy;1362 readonly runs: readonly [CheckRun, CheckRun];1363}) =>1364 Effect.gen(function* () {1365 const { ask, check, policy } = input;13661367 const read = (run: CheckRun) =>1368 Effect.fromOption(outputOf(run, input.lane)).pipe(1369 Effect.flatMap((stdout) =>1370 Effect.map(1371 lintToZeroCount({1372 asked: ask.territory,1373 check,1374 modules: policy.modules,1375 stdout,1376 }),1377 (count) => ({ count, stdout })1378 )1379 ),1380 Effect.mapError(() => new NotRedFirst({}))1381 );13821383 const [first, second] = input.runs;1384 const once = yield* read(first);1385 const again = yield* read(second);13861387 if (once.count === 0 || once.count !== again.count) {1388 return yield* new NotRedFirst({});1389 }13901391 return yield* countedBy(policy, check.command, once.stdout);1392 });13931394const section = (heading: string, lines: readonly string[] | undefined) =>1395 lines === undefined || lines.length === 01396 ? []1397 : ["", `## ${heading}`, "", ...lines];13981399const listed = (lines: readonly string[] | undefined) =>1400 lines?.map((line) => `- ${line}`);14011402const checkLine = (check: CheckSpec) =>1403 CheckSpec.match(check, {1404 LintToZero: ({ rule }) =>1405 `The lint rule \`${rule}\` reports nothing in the territory.`,1406 Migrate: ({ from, to }) =>1407 to === undefined1408 ? `No caller uses \`${from}\`.`1409 : `No caller uses \`${from}\`; they use \`${to}\`.`,1410 Ratchet: ({ ratchet }) => `The ratchet \`${ratchet}\` goes down.`,1411 RedThenGreen: ({ path }) =>1412 `\`${path}\` fails on main by an assertion; it passes once answered.`,1413 SymbolAbsent: ({ symbol }) => `Nothing uses \`${symbol}\` any more.`,1414 });14151416const briefOf = (ask: Ask): string => {1417 const { brief, territory } = ask;1418 const paths = territory.paths.map((path) => `\`${path}\``).join(", ");14191420 return [1421 `# ${brief.want}`,1422 "",1423 `Ask \`${ask.id}\` in ${ask.project}, a \`${ask.kind}\` ask from ${ask.askedBy}.`,Merge build/1105 into mainoscabrielbefore adoption1fc92ed
lines 1424–1430why, one step back1424 // A paths territory (module `.`) is no module a reader would know: it1425 // reads as its paths alone.1426 ...section("Territory", [1427 territory.module === "."1428 ? `The paths ${paths}.`1429 : `The module \`${territory.module}\`: ${paths}.`,1430 ]),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1431–1590why, one step back1431 ...section(1432 "Current",1433 Option.toArray(Option.fromUndefinedOr(brief.current))1434 ),1435 ...section("Check", [checkLine(ask.check)]),1436 ...section("Out of scope", listed(brief.outOfScope)),1437 ...section("Terms", listed(brief.terms)),1438 ...section("Context", listed(brief.context)),1439 "",1440 ].join("\n");1441};14421443const submitRefusal = (refusal: Refusal, ask: AskId): SubmitRefusal =>1444 Match.value(refusal).pipe(1445 Match.tag(1446 "ClaimLapsed",1447 "NotClaimed",1448 "OutOfScope",1449 "PrivatePathInPublicTree",1450 "ReachedInternals",1451 "RepoBusy",1452 "StaleBase",1453 "TouchedJudge",1454 "Weakened",1455 (kept): SubmitRefusal => kept1456 ),1457 Match.orElse(() => NotClaimed.of(ask))1458 );14591460const withAgent = (1461 agents: readonly AgentTrailer[],1462 audit: HarnessAudit | undefined1463): readonly AgentTrailer[] => {1464 if (audit?.harness === undefined) {1465 return agents;1466 }14671468 const agent: AgentTrailer = {1469 harness: audit.harness,1470 verified: false,1471 ...(audit.model !== undefined && { model: audit.model }),1472 };14731474 return agents.some(1475 ({ harness, model }) => harness === agent.harness && model === agent.model1476 )1477 ? agents1478 : [...agents, agent];1479};14801481const disclosed = (1482 policy: Policy,1483 claim: Option.Option<ClaimRow>1484): readonly AgentTrailer[] =>1485 policy.agents === "none"1486 ? []1487 : Option.match(claim, {1488 onNone: () => [],1489 onSome: ({ assisted }) => assisted ?? [],1490 });14911492const heldBackTrailerOf = (1493 record: { readonly heldBack?: HeldBackJudged },1494 tree: TreeSha1495): Option.Option<string> =>1496 Option.flatMap(1497 Option.filter(1498 Option.fromUndefinedOr(record.heldBack),1499 (held) => held.tree === tree1500 ),1501 ({ trailer }) => Option.fromUndefinedOr(trailer)1502 );15031504const messageOf = (1505 request: Request,1506 ask: Option.Option<Ask>,1507 verdict: Verdict,1508 heldBack: Option.Option<string> = Option.none()1509): string => {1510 const message = {1511 assisted: request.assisted,1512 credits: request.credits,1513 requestId: request.requestId,1514 subject: "Land a change",1515 verdict: { checkVersion: verdict.checkVersion, patchId: verdict.patchId },1516 ...field("heldBack", heldBack),1517 };15181519 return formatLanding(1520 Option.match(ask, {1521 onNone: () => message,1522 onSome: ({ brief, id, project }) => ({1523 ...message,1524 ask: { ask: id, project },1525 body: brief.want,1526 subject: `Answer ${id}`,1527 }),1528 })1529 );1530};15311532const byUpdated = Order.mapInput(1533 DateTime.Order,1534 ({ row }: Answered) => row.updatedAt1535);15361537const landedVerdict = (verdict: Option.Option<Verdict>, sha: LandedSha) =>1538 Option.map(verdict, (made): Verdict => ({1539 ...made,1540 outcome: Outcome.cases.Landed.make({ sha }),1541 }));15421543const withVerdict = (1544 event: ProjectEventInput,1545 verdict: Option.Option<Verdict>1546): ProjectEventInput =>1547 Match.value(event).pipe(1548 Match.tag("Landed", (landed): ProjectEventInput => ({1549 ...landed,1550 landing: {1551 ...landed.landing,1552 ...field("verdict", landedVerdict(verdict, landed.landing.sha)),1553 },1554 })),1555 Match.orElse((other) => other)1556 );15571558const runnable = (effect: LandingEffect): effect is RunnableEffect =>1559 isStep(effect) || LandingEffect.$is("Retry")(effect);15601561const isTouchedJudge = (refusal: Refusal): refusal is TouchedJudge =>1562 Match.value(refusal).pipe(1563 Match.tag("TouchedJudge", () => true),1564 Match.orElse(() => false)1565 );15661567type Checking = Extract<LandingState, { readonly _tag: "Checking" }>;15681569type Landing = Extract<LandingState, { readonly _tag: "Landing" }>;15701571interface Settled {1572 readonly queue: LandingQueue;1573 readonly steps: readonly LandingEffect[];1574}15751576const startOther = (1577 writes: Writes,1578 admitted: Option.Option<RequestId>,1579 advancing: RequestId,1580 now: DateTime.Utc1581) =>1582 Option.match(1583 Option.filter(admitted, (id) => id !== advancing),1584 {1585 onNone: () => Effect.void,1586 onSome: (id) =>1587 Effect.map(startRow(id, now), (row) => writes.outbox.push(row)),1588 }1589 );1590Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
lines 1591–1682why, one step back1591interface Watch {1592 readonly ran: (1593 lane: LaneName,1594 runs: readonly [CheckRun, CheckRun]1595 ) => Effect.Effect<void>;1596 readonly stdout: boolean;1597}15981599const unwatched: Watch = { ran: () => Effect.void, stdout: false };16001601interface Seen {1602 readonly lane: LaneName;1603 readonly runs: readonly [CheckRun, CheckRun];1604}16051606type FinalRefusal =1607 | IncompleteBrief1608 | NotDecider1609 | NotRedFirst1610 | TouchedJudge1611 | WeakCheck;16121613const readingOf = (run: CheckRun, lane: LaneName) => {1614 const result = run.lanes.find((each) => each.lane === lane)?.result;16151616 const signed = run.evidence.some(1617 (each) => each.lane === lane && each.signature !== undefined1618 );16191620 return result === "failed" && !signed ? "loadError" : (result ?? "blocked");1621};16221623const notRedBecause = ({ lane, runs }: Seen): Diagnosis => {1624 const readings = runs.map((run) => readingOf(run, lane));16251626 if (readings.every((reading) => reading === "passed")) {1627 return "Passed";1628 }16291630 if (readings.includes("blocked")) {1631 return "Blocked";1632 }16331634 return readings.includes("loadError") ? "LoadError" : "Flaky";1635};16361637const diagnosisOf = (1638 refusal: FinalRefusal,1639 seen: Option.Option<Seen>1640): Diagnosis =>1641 Match.valueTags(refusal, {1642 IncompleteBrief: (): Diagnosis => "Brief",1643 NotDecider: (): Diagnosis => "Brief",1644 NotRedFirst: () =>1645 Option.match(seen, {1646 onNone: (): Diagnosis => "Brief",1647 onSome: notRedBecause,1648 }),1649 TouchedJudge: (): Diagnosis => "Judge",1650 WeakCheck: ({ weakness }): Diagnosis =>1651 weakness === "no assertion" ? "NoTests" : "Weak",1652 });16531654const excerptOf = (seen: Option.Option<Seen>) =>1655 Option.match(1656 Option.flatMap(seen, ({ lane, runs: [first, second] }) =>1657 Option.orElse(outputOf(second, lane), () => outputOf(first, lane))1658 ),1659 {1660 onNone: () => "",1661 onSome: (printed) => tailOf(printed, EXCERPT_BYTES).text,1662 }1663 );16641665const rehearsalRefused = (1666 refusal: FinalRefusal,1667 seen: Option.Option<Seen>1668): Rehearsal =>1669 Rehearsal.cases.Refused.make({1670 diagnosis: diagnosisOf(refusal, seen),1671 excerpt: excerptOf(seen),1672 refusal,1673 });16741675const redOf = ({ lane, runs }: Seen) => ({1676 lane,1677 signature: Result.match(redFirstOfRuns(runs, lane), {1678 onFailure: () => "red by its count",1679 onSuccess: ({ signature }) => signature,1680 }),1681});1682Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1683–1694why, one step back1683const weakness = (ask: Ask, files: readonly AskFile[]) => {1684 const { check } = ask;16851686 const file = CheckSpec.guards.RedThenGreen(check)1687 ? Option.fromUndefinedOr(files.find(({ path }) => path === check.path))1688 : Option.none<AskFile>();16891690 return Option.flatMap(file, (found) =>1691 Array.head(weaknessesOf(found, ask.territory.paths))1692 );1693};1694Merge observability into mainoscabrielbefore adoption1985111
lines 1695–1705why, one step back1695const refusedAt = (1696 stage: StageName,1697 refusals: readonly Refusal[]1698): Option.Option<StageRefusal> =>1699 Option.map(1700 Option.liftPredicate(refusals, Array.isReadonlyArrayNonEmpty),1701 (all) => ({ refusals: all, stage })1702 );17031704// A fork the host lacks is refused as parse would refuse it; a commit it lacks,1705// as a merge would.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1706–1709why, one step back1706const gateOf = (1707 facts: Effect.Effect<PushFacts, RepoNotFound | MissingCommit>,1708 missing: readonly Refusal[],1709 stale: readonly Refusal[]Merge observability into mainoscabrielbefore adoption1985111
line 1710why, one step back1710): Effect.Effect<Option.Option<StageRefusal>> =>Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 1711why, one step back1711 facts.pipe(Merge observability into mainoscabrielbefore adoption1985111
line 1712why, one step back1712 Effect.flatMap((each) => refusingStage(pushStages, each)),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 1713why, one step back1713 Effect.catchTags({Merge observability into mainoscabrielbefore adoption1985111
lines 1714–1715why, one step back1714 MissingCommit: () => Effect.succeed(refusedAt("merge", stale)),1715 RepoNotFound: () => Effect.succeed(refusedAt("parse", missing)),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1716–1718why, one step back1716 })1717 );1718Merge observability into mainoscabrielbefore adoption1985111
lines 1719–1801why, one step back1719/** The stage whose refusals moved an answer from `before` to `Refused`. */1720const refusingStageOf = (1721 before: LandingState,1722 report: AnswerReport | undefined1723): StageName =>1724 LandingState.matchOrElse<StageName>(1725 before,1726 {1727 AwaitingDecision: () => "human",1728 Checking: () => report?.stage ?? "checks",1729 Landing: () => "merge",1730 Merging: () => "merge",1731 },1732 () => "checks"1733 );17341735const waitedPoints = (input: {1736 readonly before: LandingState;1737 readonly now: DateTime.Utc;1738 readonly project: ProjectName;1739 readonly queuedAt: DateTime.Utc | undefined;1740 readonly state: LandingState;1741}): readonly MetricPoint[] =>1742 LandingState.guards.Merging(input.before) &&1743 LandingState.guards.Checking(input.state) &&1744 input.state.remerges === 0 &&1745 input.queuedAt !== undefined1746 ? [1747 MetricPoint.cases.ChecksWaited.make({1748 project: input.project,1749 waitedMs: millisBetween(input.queuedAt, input.now),1750 }),1751 ]1752 : [];17531754/**1755 * What one step of an answer's landing counts, each under the fact it counts:1756 * its refusal, its checked lanes, and the wait before its first checks. A1757 * report that changes nothing counts nothing, so a replay writes no row.1758 */1759const answerPoints = (input: {1760 readonly before: LandingState;1761 readonly command: LandingCommand;1762 readonly now: DateTime.Utc;1763 readonly project: ProjectName;1764 readonly queuedAt: DateTime.Utc | undefined;1765 readonly report: AnswerReport | undefined;1766 readonly requestId: RequestId;1767 readonly state: LandingState;1768}): Effect.Effect<readonly OutboxRow[]> => {1769 const { before, command, now, project, report, requestId, state } = input;17701771 const refused =1772 LandingState.guards.Refused(state) && !LandingState.guards.Refused(before)1773 ? refusedPoints(project, refusingStageOf(before, report), state.refusals)1774 : [];17751776 const checkedTree =1777 LandingCommand.$is("Checked")(command) &&1778 LandingState.guards.Checking(before) &&1779 before.tree === command.tree &&1780 state !== before1781 ? Option.some(before.tree)1782 : Option.none();17831784 return Effect.map(1785 Effect.all([1786 measuredRow(`waited:${requestId}`, waitedPoints(input), now),1787 Option.match(checkedTree, {1788 onNone: () => Effect.succeed([]),1789 onSome: (tree) =>1790 measuredRow(1791 `lanes:${requestId}:${tree}`,1792 lanePoints(project, report?.lanes ?? []),1793 now1794 ),1795 }),1796 measuredRow(`refused:${requestId}`, refused, now),1797 ]),1798 (rows) => rows.flat()1799 );1800};1801Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1802–1826why, one step back1802const leaveIfDone = (1803 writes: Writes,1804 queue: LandingQueue,1805 input: {1806 readonly now: DateTime.Utc;1807 readonly requestId: RequestId;1808 readonly state: LandingState;1809 }1810) => {1811 const { requestId } = input;18121813 const inLine = holdsSlot(queue, requestId) || queue.order.includes(requestId);18141815 if (LandingState.guards.Landing(input.state) || !inLine) {1816 return Effect.succeed(queue);1817 }18181819 const left = leave(queue, requestId);18201821 return Effect.as(1822 startOther(writes, left.admitted, requestId, input.now),1823 left.queue1824 );1825};1826Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 1827–1829why, one step back1827const namesNoAsk = (landing: LandingView) =>1828 landing.ask === undefined && landing.opened === undefined;1829Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1830–1844why, one step back1830export const projectService = (1831 name: ProjectName1832): Effect.Effect<ProjectApi, never, ProjectPorts> =>1833 Effect.gen(function* () {1834 const ports = yield* Effect.context<ProjectPorts>();1835 const store = Context.get(ports, ProjectStore);1836 const host = Context.get(ports, RepoHost);1837 const lander = Context.get(ports, Lander);1838 const runner = Context.get(ports, CheckRunner);1839 const rules = Context.get(ports, RulesEvaluator);1840 const alarms = Context.get(ports, Alarms);1841 // Read once, as the ports are: a call runs in its caller's context.1842 const generate = yield* ProjectGenerator;1843 const visibility = yield* ProjectVisibility;1844 const envPort = yield* ProjectEnv;Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c
line 1845why, one step back1845 const draftRuns = yield* DraftRuns;Merge observability into mainoscabrielbefore adoption1985111
line 1846why, one step back1846 const metrics = yield* Metrics;Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 1847why, one step back1847 const lock = yield* Semaphore.make(1);Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 1848why, one step back1848 const repo = RepoName.make(keyOf(name));Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1849–2006why, one step back18491850 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>1851 Effect.provideContext(effect, ports);18521853 const hydrate: Effect.Effect<Hydrated> = Effect.gen(function* () {1854 const snapshot = yield* store.load();18551856 const policy = yield* Option.match(1857 Option.flatMap(snapshot.project, (row) =>1858 Option.fromUndefinedOr(row.policy)1859 ),1860 {1861 onNone: () => Effect.succeedNone,1862 onSome: (json) => Effect.asSome(Effect.orDie(decodePolicy(json))),1863 }1864 );18651866 const claims = yield* Effect.forEach(snapshot.claims, (row) =>1867 Effect.map(Effect.orDie(decodeClaim(row.state)), (state) => ({1868 row,1869 state,1870 }))1871 );18721873 const answers = yield* Effect.forEach(snapshot.answers, (row) =>1874 Effect.map(Effect.orDie(decodeAnswer(row.state)), (record) => ({1875 record,1876 row,1877 }))1878 );18791880 return {1881 answers,1882 asks: new Map(snapshot.asks.map((ask) => [ask.id, ask])),1883 budgetDays: snapshot.budgetDays,1884 claims,1885 decisions: snapshot.decisions,1886 landings: snapshot.landings,1887 lastSeq: snapshot.lastSeq,1888 outbox: snapshot.outbox,1889 policy,1890 project: snapshot.project,1891 proposals: snapshot.proposals,1892 queue: yield* queueOf(snapshot.queue),1893 ratchets: snapshot.ratchets,1894 snapshot,1895 };1896 });18971898 const liveRow = (h: Hydrated) =>1899 Option.flatMap(h.project, (row) =>1900 row.state === "live" && row.landed !== undefined1901 ? Option.some({ landed: row.landed, row })1902 : Option.none()1903 );19041905 const askNow = (h: Hydrated, writes: Writes, id: AskId) =>1906 Option.fromUndefinedOr(writes.asks.get(id) ?? h.asks.get(id));19071908 const ratchetsNow = (1909 h: Hydrated,1910 writes: Writes1911 ): readonly RatchetRow[] => [1912 ...h.ratchets.map((row) => writes.ratchets.get(ratchetKey(row)) ?? row),1913 ...[...writes.ratchets.values()].filter(1914 (row) =>1915 !h.ratchets.some((held) => ratchetKey(held) === ratchetKey(row))1916 ),1917 ];19181919 const baselinesNow = (h: Hydrated, writes: Writes) =>1920 ratchetsNow(h, writes)1921 .filter((row) => !isEscapeRow(row))1922 .map(baselineOf);19231924 const putRatchets = (1925 h: Hydrated,1926 writes: Writes,1927 baselines: readonly RatchetBaseline[]1928 ) => {1929 const held = new Map(1930 ratchetsNow(h, writes).map((row) => [ratchetKey(row), row])1931 );19321933 for (const baseline of baselines) {1934 const row: RatchetRow = {1935 at: baseline.setAt,1936 count: baseline.count,1937 ratchet: baseline.ratchet,1938 territory: baseline.territory,1939 };19401941 const before = held.get(ratchetKey(row));19421943 if (before?.count !== row.count || before.at !== row.at) {1944 writes.ratchets.set(ratchetKey(row), row);1945 }1946 }1947 };19481949 const ownClaim = (h: Hydrated, ask: AskId, handle: Handle) =>1950 Option.fromUndefinedOr(1951 h.claims.find(1952 ({ row }) => row.ask === ask && sameHandle(row.claimant, handle)1953 )1954 );19551956 const claimRowNow = (1957 h: Hydrated,1958 writes: Writes,1959 ask: AskId,1960 claimant: Handle1961 ): ClaimRow | undefined =>1962 writes.claims.get(claimKey(ask, claimant)) ??1963 Option.getOrUndefined(ownClaim(h, ask, claimant))?.row;19641965 const heldBy = (h: Hydrated, handle: Handle, except?: AskId) =>1966 h.claims.filter(1967 ({ row, state }) =>1968 isLive(state) &&1969 row.ask !== except &&1970 sameHandle(row.claimant, handle)1971 ).length;19721973 const findAnswer = (h: Hydrated, requestId: RequestId) =>1974 Option.fromUndefinedOr(1975 h.answers.find(({ row }) => row.requestId === requestId)1976 );19771978 const claimsPolicy = (h: Hydrated) =>1979 Option.getOrElse(1980 Option.map(h.policy, ({ claims }) => claims),1981 () => defaultClaims1982 );19831984 const viewOf = (1985 policy: Option.Option<Policy>,1986 ask: Option.Option<Ask>,1987 state: ClaimState,1988 pinned: PinnedSuite | undefined1989 ) =>1990 Effect.gen(function* () {1991 const gateway = yield* GatewayUrl;19921993 const checkCommand = Option.getOrElse(1994 Option.flatMap(1995 Option.all({ ask, policy }),1996 ({ ask: asked, policy: at }) =>1997 Option.map(askLaneOf(at, asked), ({ command }): string => command)1998 ),1999 () => `${Brand.cli} check`2000 );The first 2,000 of 5,523 lines.