Merge build/comments-project into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
125 files+214 added−4346 removed
- tests:+23 added−544 removed
- other:+191 added−3802 removed
Provenance
- Commit
49efd2a- Tree
5df460c- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
ddf09e8- Parent 2
e78d3c5
125 files changed+214 added−4346 removed
This commit is too large to show whole: its files are listed by path, without their changes.
modified:packages/project/src/alarms/memory.ts-8 removed
1-/**2- * `Alarms` in memory, for tests: like a Durable Object it holds one alarm,3- * the one set last, which the service always computes as its earliest4- * pending deadline. Nothing fires by itself: a test reads `ScheduledAlarm`,5- * moves the TestClock there, and calls the project's `onAlarm`.6- */1 import { Context, Effect, Layer, Option, Ref } from "effect";2 import type { DateTime } from "effect";3 4 import { Alarms } from "../alarms.ts";5 12-/** When the memory alarm is set to go off, if it is set. */6 export class ScheduledAlarm extends Context.Service<7 ScheduledAlarm,8 { readonly at: Effect.Effect<Option.Option<DateTime.Utc>> }9 >()("project/ScheduledAlarm") {}10 18-/** A fresh alarm each time the layer is built, and the reading of it. */11 export const AlarmsMemory: Layer.Layer<Alarms | ScheduledAlarm> =12 Layer.effectContext(13 Effect.gen(function* () {14 const alarm = yield* Ref.make(Option.none<DateTime.Utc>());6 unmodified linesmodified:packages/project/src/answer-runs/inline.ts-7 removed
1-/**2- * `AnswerRuns` in process, for tests: `start` drives the answer's3- * steps (merge, checks, land) through the project's own answer queue until4- * the answer lands, is refused, or waits (on a person, the landing slot, or5- * a retry the project's alarm starts again). A run already under way for the6- * same request is not started twice.7- */1 import type { RepoHost } from "@repo/artifacts/repo-host";2 import type { CheckRunner } from "@repo/checks/check-runner";3 import type { RequestId } from "@repo/protocol/ids";4 import { Effect, Layer, Ref } from "effect";46 unmodified linesmodified:packages/project/src/answer-runs/movers.ts-25 removed
1-/**2- * Who moved the paths a merge conflicts in. A three-way merge conflicts in3- * a path only where main changed it since the answer's base, so for each4- * path the walk finds the newest commit on main's first-parent line since5- * that base that changed it, and names it only when the project's record6- * holds it as a landing (a trailer never reads as one). The walk reads the7- * canonical repo through `RepoHost` (`code/tree.ts`'s lookups, shared as8- * one view), stops at the base or after `MOVER_SCAN` commits, and never9- * fails the merge: what it cannot read, it leaves out.10- */1 import { RepoHost, Revision } from "@repo/artifacts/repo-host";2 import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";3 import type { LandingView } from "@repo/protocol/domain/landing";4 import type {7 unmodified lines12 13 import { asOneView } from "../code/cache.ts";14 import { entryAt, READS_AT_ONCE } from "../code/tree.ts";15 26-/** The most first-parent commits back from main a walk reads. */16 export const MOVER_SCAN = 50;17 29-/** The landings among `shas`, as the project's record holds them. */18 export type LandingsOf = (19 shas: readonly CommitSha[]20 ) => Effect.Effect<readonly LandingView[]>;21 34-/** What a merge conflicted in: the repo, the answer's base, main, and the paths. */22 export interface Conflicted {23 readonly repo: RepoName;24 readonly base: CommitSha;25 readonly main: LandedSha;26 readonly conflicts: readonly RepoPath[];27 }28 42-/** What sits at `path` in `commit`: its mode and id, or nothing. */29 const idAt = (repo: RepoName, commit: Commit | undefined, path: RepoPath) =>30 commit === undefined31 ? Effect.succeedNone32 : Effect.map(33 entryAt(repo, commit.tree, path),34 Option.map(({ mode, sha }) => `${mode} ${sha}`)35 );36 51-/**52- * The newest of the first `since` commits of `scan` that changed `path`53- * from the commit after it, its first parent.54- */37 const moverOf = (38 repo: RepoName,39 scan: readonly Commit[],40 since: number,12 unmodified lines53 : Option.some(commit.sha)54 )55 );56 75-/** Each conflicting path's newest change since the base, where one is found. */57 const moversOf = (input: Conflicted) =>58 asOneView(59 Effect.gen(function* () {60 const scan = yield* RepoHost.use((host) =>19 unmodified lines80 return Array.getSomes(found);81 })82 );83 103-/** A path's mover as the refusal names it, from its landing. */84 const movedByOf = (path: RepoPath, landing: LandingView): MovedBy => {85 const ask = landing.ask ?? landing.opened;86 87 return ask === undefined88 ? { author: landing.author, landing: landing.sha, path }89 : { ask, author: landing.author, landing: landing.sha, path };90 };91 112-/**113- * Who last moved each path `input` conflicts in, by its landing, in the114- * order of `input.conflicts`. None when no conflicting path's change is a115- * landing the record holds, or when the walk could not read the repo.116- */92 export const movedBy = (93 input: Conflicted,94 landings: LandingsOf95 ): Effect.Effect<readonly MovedBy[], never, RepoHost> =>37 unmodified linesmodified:packages/project/src/answer-runs/steps.ts+3 added-51 removed
1-/**2- * An answer run's steps, as Effect programs over the ports. Each port call a3- * `LandingEffect` names becomes the `LandingCommand` that reports it: a4- * merge, the checks on the exact merged tree, or the land on main. A step5- * decides nothing: the landing lifecycle does, in the project's6- * `advanceAnswer`, and the gate classifies a failing lane.7- *8- * The inline adapter drives them in a loop (`drive`); the Answer Workflow9- * runs each as a durable step.10- */1 import type { RepoHost } from "@repo/artifacts/repo-host";2 import { CheckAt, CheckRunner } from "@repo/checks/check-runner";3 import type { CheckLane, CheckRun } from "@repo/checks/check-runner";4 import { classifyFailure } from "@repo/gate/classify";15 unmodified lines20 } from "../landing.ts";21 import { movedBy } from "./movers.ts";22 import type { LandingsOf } from "./movers.ts";23 34-/** A step's result: the command it reports, and what it saw beside it. */24 export interface Reported {25 readonly command: LandingCommand;26 readonly report?: AnswerReport;27 }28 40-/** Whether an effect is a port call a run makes, rather than the project's to settle. */29 export const isStep = (effect: LandingEffect) =>30 LandingEffect.$is("Merge")(effect) ||31 LandingEffect.$is("RunChecks")(effect) ||32 LandingEffect.$is("Land")(effect);33 46-/**47- * The port calls a run makes now: the one its state waits on, except a48- * land, which runs only while the request holds the project's landing slot.49- */34+/** A land runs only while the request holds the project's landing slot. */35 export const nextSteps = (run: AnswerRun): readonly LandingEffect[] =>36 LandingState.guards.Landing(run.state) && !run.admitted37 ? []38 : pendingEffects(run.state);39 55-/** The attempt a port's `Busy` or `Blocked` report is about: the state's own. */40 const attemptOf = (state: LandingState) =>41 LandingState.matchOrElse(42 state,43 {6 unmodified lines50 51 const reported = (command: LandingCommand, report?: AnswerReport): Reported =>52 report === undefined ? { command } : { command, report };53 70-/**71- * The answer's head merged onto `main`: the tree to check, or the paths72- * that conflict, with the landing that last moved each one (`movedBy`).73- */54 const merge = (55 run: AnswerRun,56 step: Extract<LandingEffect, { readonly _tag: "Merge" }>,57 landings: LandingsOf34 unmodified lines92 ),93 })94 );95 116-/** Each lane's result in a run, by lane. */96 const resultsOf = (run: CheckRun): ReadonlyMap<LaneName, LaneResult> =>97 new Map(run.lanes.map((lane) => [lane.lane, lane]));98 99 const isTrouble = (result: LaneOutcome) =>100 result === "flaked" || result === "blocked";101 123-/** Where a lane's log is kept when its run named no place: by request and lane. */102 const logRefOf = (requestId: RequestId, lane: LaneName) =>103 `${requestId}/${lane}`;104 127-/**128- * The checks on the exact merged tree, every lane every time. A lane that129- * did not pass is classified by the gate: a checker that never started gets130- * one fresh run, and a project lane is run on main too, since a lane red on131- * main is the gate's trouble, not the answer's. The ask's own check is red132- * on main by design, so it counts as passing there.133- */105+/** Every lane every time; a failing project lane is run on main too, since red on main is the gate's trouble. The ask's own check is red on main by design, so it passes there. */106 const checks = (107 run: AnswerRun,108 checking: Extract<LandingState, { readonly _tag: "Checking" }>109 ): Effect.Effect<Reported, VerifierBlocked, CheckRunner> =>2 unmodified lines112 const { request } = checking;113 114 const block = yield* runBlockOf(run);115 144- // The merged tree lives in the answer's fork, where the Lander's merge145- // leaves it (its merge ref), and main in the project's own repo: a146- // Checker fetches the repo a job names, so each job names the one that147- // holds its commit, as the `Answer` Workflow's jobs do.116+ // A Checker fetches the repo a job names: the merged tree lives in the answer's fork (the merge ref), main in the project's repo.117 const job = (at: CheckAt, lanes: readonly CheckLane[]) =>118 runner.run({119 ...(run.env ?? noRunEnv),120 at,71 unmodified lines192 { heldBack: merged.heldBack, lanes }193 );194 });195 227-/**228- * The checked tree landed on main as the platform's commit, with the229- * message the project wrote. A moved main sends it back to merge; a busy230- * repo or a blocked Lander waits and tries again.231- */196 const land = (197 run: AnswerRun,198 landing: Extract<LandingState, { readonly _tag: "Landing" }>,199 message: string40 unmodified lines240 ),241 })242 );243 280-/**281- * One step: the port call `effect` names, run for `run`, and the command282- * that reports it. `None` when the run's state no longer waits on that call283- * (a replay after the state moved on). A merge that conflicts asks284- * `landings` who moved each path.285- */244 export const runStep = (245 run: AnswerRun,246 effect: LandingEffect,247 landings: LandingsOf25 unmodified lines273 )274 : Effect.succeedNone,275 });276 319-/**320- * Carries one answer as far as it goes now: runs the step its state waits321- * on, reports it, and goes on with the steps the report returns, until the322- * answer lands, is refused, waits on a person or the queue, or must wait for323- * a retry (the project's alarm starts it again).324- */277 export const drive = (278 queue: AnswerQueue,279 requestId: RequestId280 ): Effect.Effect<void, never, CheckRunner | Lander | RepoHost> => {38 unmodified linesmodified:packages/project/src/attention/budget.ts-16 removed
1-/**2- * The budget: how many decisions a decider takes a day. Each decision they3- * take and each finish they make is spent on the UTC day it happens, in one4- * row per decider and day; a finish costs more than a decision, so it is5- * counted apart, and a project can see where its deciders' time goes.6- */1 import type { Today } from "@repo/protocol/domain/decision";2 import type { Policy } from "@repo/protocol/domain/policy";3 import { sameHandle } from "@repo/protocol/ids";4 import type { Handle } from "@repo/protocol/ids";5 import { DateTime } from "effect";6 7 import type { BudgetDayRow } from "../project-store/rows.ts";8 15-/**16- * One decider's budget for one day, as Today shows it: decisions `used` of17- * the policy's `total` per day, and `finishes`, counted apart.18- */9 export type Budget = Today["budget"];10 21-/** The day a moment falls on, as `BudgetDayRow.day` keys it: `2026-10-07`, in UTC. */11 const dayOf = (now: DateTime.Utc) => DateTime.formatIsoDateUtc(now);12 13 const rowFor = (14 days: readonly BudgetDayRow[],11 unmodified lines26 }27 );28 };29 41-/** What `decider` has spent of today's budget, out of the policy's `decisionsPerDay`. */30 export const budgetFor = (31 policy: Policy,32 decider: Handle,33 days: readonly BudgetDayRow[],3 unmodified lines37 38 return { finishes, total: policy.budget.decisionsPerDay, used };39 };40 53-/**54- * `decider`'s row for the day of `now`, with one more decision or finish55- * spent: the row the service writes back when they decide or finish.56- */41 export const spend = (42 days: readonly BudgetDayRow[],43 input: {44 readonly decider: Handle;10 unmodified linesmodified:packages/project/src/attention/credits.ts+2 added-28 removed
1-/**2- * A person's credits (GLOSSARY "Credit"): how many landings name them in3- * each human role, by project and area, for their credits page. Roles and4- * counts only: no score, no total across roles, no ranking.5- *6- * Credit is read from each landing's `credits` rows, which the platform wrote7- * as the landing's trailers, never from commit messages. `Assisted-by` is a8- * disclosure of the agent a person worked through, kept apart in `assisted`,9- * and never counts.10- */1 import type { Ask } from "@repo/protocol/domain/ask";2 import type { LandingView } from "@repo/protocol/domain/landing";3 import type { CreditSummary } from "@repo/protocol/domain/record";4 import { sameHandle } from "@repo/protocol/ids";1 unmodified line6 import { Array as Arr, Option, Order } from "effect";7 8 import { areaOf } from "./record.ts";9 20-/** What a person's credits are counted from. */10 export interface CreditsInput {22- /**23- * The asks the landings answered, by id, closed ones included, to find24- * each landing's area. Ask ids are unique only within a project, so for a25- * person's credits across projects call once per project and join the26- * rows (they sort by project first): a landing whose id finds another27- * project's ask credits no area.28- */11+ /** Ask ids are unique only within a project: call once per project and join the rows. */12 readonly asks: ReadonlyMap<AskId, Ask>;13 readonly handle: Handle;14 readonly landings: readonly LandingView[];15 }16 17 const byText = (field: (row: CreditSummary) => string) =>18 Order.mapInput(Order.String, field);19 37-/**38- * By project, then area, then role, each as text. Not `Order.Struct`: it39- * compares in key order, and keys are kept sorted.20+// Not `Order.Struct`: it compares in key order, and keys are kept sorted.40- */21 const bySummary = Order.combineAll([22 byText(({ project }) => project),23 byText(({ area }) => area),24 byText(({ role }) => role),25 ]);26 47-/**48- * One row per project, area and role the person holds, counting the landings49- * that credit them so; a role repeated on one landing counts once. A landing50- * with no area (no ask, or one not found) credits no area, so it is not51- * counted, as on the record. Rows are sorted by project, area and role.52- */27 export const creditsByArea = (28 input: CreditsInput29 ): readonly CreditSummary[] => {30 const rows = new Map<string, CreditSummary>();29 unmodified linesmodified:packages/project/src/attention/decisions.ts+2 added-52 removed
1-/**2- * Decisions: everything in a project that needs a person, each with its3- * evidence, its deciders, an expiry and a safe default that is taken when4- * nobody decides in time. Pure, like the lifecycles: each move takes `now`5- * and returns the next state and its effects as data.6- */1 import { matchGlob } from "@repo/gate/glob";2 import type { Evidence } from "@repo/protocol/domain/common";3 import { DecisionSubject } from "@repo/protocol/domain/decision";4 import type { Choice, Decision } from "@repo/protocol/domain/decision";14 unmodified lines19 20 import { ProjectEventInput } from "../events.ts";21 import { AttentionEffect, platformHandle } from "./effects.ts";22 29-/** How a subject's deciders say yes, and no. */23 interface Words {24 readonly no: Choice;25 readonly yes: Choice;26 }27 28 const acceptOrDecline: Words = { no: "decline", yes: "accept" };29 37-/**38- * A stray push is adopted or reverted; everything else is accepted or39- * declined. Every subject is named, so a new one fails to compile until it40- * has its words, and with them its default.41- */30 const wordsFor = DecisionSubject.match({31 Finish: () => acceptOrDecline,32 OpenProposal: () => acceptOrDecline,33 PostureChange: () => acceptOrDecline,4 unmodified lines38 Vouch: () => acceptOrDecline,39 Waiver: () => acceptOrDecline,40 });41 54-/** Whether a choice says yes, in any subject's words. */42 const saysYes = {43 accept: true,44 adopt: true,45 decline: false,46 revert: false,47 } as const satisfies Record<Choice, boolean>;48 62-/**63- * What happens when nobody decides: the subject's no. A proposal is64- * declined, a stray push reverted, a ratchet stays where it is; doing65- * nothing lets nothing in.66- */49 export const defaultChoice = (subject: DecisionSubject): Choice =>50 wordsFor(subject).no;51 70-/** `choice` as `subject`'s deciders say it: `accept` on a stray push adopts it. */52 const inWords = (subject: DecisionSubject, choice: Choice): Choice => {53 const words = wordsFor(subject);54 55 return saysYes[choice] ? words.yes : words.no;56 };57 77-/**78- * What a decided subject asks the service to do: an accepted proposal opens79- * its ask, a reverted stray push is undone, any other yes goes ahead, and any80- * other no leaves things as they are.81- */58 const consequences = (59 subject: DecisionSubject,60 choice: Choice61 ): readonly AttentionEffect[] => {7 unmodified lines69 ? [AttentionEffect.OpenAsk({ proposal: subject.proposal })]70 : [AttentionEffect.Land({ subject })];71 };72 97-/** A decision taken: the decision as it now stands, and what follows from it. */73 export interface Decided {74 readonly decision: Decision;75 readonly effects: readonly AttentionEffect[];76 }77 103-/** Takes `decision` with `choice`, by `by`, at `now`. */78 const take = (79 decision: Decision,80 by: Handle,81 choice: Choice,21 unmodified lines103 ],104 };105 };106 133-/** Whether nobody may decide `decision` any more: it was taken, or it reached its expiry. */107 const isClosed = (decision: Decision, now: DateTime.Utc) =>108 decision.decided !== undefined ||109 DateTime.isGreaterThanOrEqualTo(now, decision.expiresAt);110 138-/**139- * A new decision for `deciders`, with the default its subject gives it,140- * expiring `expireDays` after `now`. The service mints the id and sets the141- * alarm at `expiresAt`.142- */111 export const openDecision = (input: {112 readonly id: DecisionId;113 readonly project: ProjectName;114 readonly subject: DecisionSubject;11 unmodified lines126 project: input.project,127 subject: input.subject,128 });129 162-/**163- * One decider's choice on one open decision, recorded with who chose what164- * and when. `adopt` and `accept` both say yes, `revert` and `decline` both165- * say no, and the decision records the word its subject uses. After an166- * unknown id, a person who does not decide for it is refused before the167- * decision's state is read, so they learn nothing of it; a decision taken,168- * or past its expiry, is closed.169- */130+// A non-decider is refused before the decision's state is read, so they learn131+// nothing of it.132 export const decide = (133 decisions: readonly Decision[],134 input: {135 readonly id: DecisionId;21 unmodified lines157 take(found, input.by, input.choice, input.now, input.note)158 );159 };160 199-/** A project's decisions after an alarm, and what follows from the ones that expired. */161 export interface ExpiredDecisions {162 readonly decisions: readonly Decision[];163 readonly effects: readonly AttentionEffect[];164 }165 205-/**206- * An alarm fired: every open decision past its expiry takes its default,207- * decided by the platform's own handle. The rest stay as they are, in order.208- */166 export const expireDecisions = (167 decisions: readonly Decision[],168 now: DateTime.Utc169 ): ExpiredDecisions => {8 unmodified lines178 effects: steps.flatMap(({ effects }) => effects),179 };180 };181 225-/**226- * Who decides for `paths`: everyone named by a glob in the policy's227- * `deciders` that matches one of them, in the policy's order, each once.228- * `**` matches every path, so whoever holds it decides everything. A229- * decision about no path (a vouch, a posture change) goes to the project's230- * own deciders, those of `**`.231- */182 export const decidersFor = (183 policy: Policy,184 paths: readonly RepoPath[]185 ): readonly Handle[] => {11 unmodified linesmodified:packages/project/src/attention/effects.ts-16 removed
1-/**2- * What attention asks of the project service. Proposals, decisions and Today3- * are pure: each move returns its next state and these effects as data, and4- * the service settles them after it persists the move (ADR 0012), the way it5- * settles a lifecycle's effects.6- */1 import { Brand } from "@repo/brand";2 import type { RefNameText } from "@repo/protocol/domain/common";3 import type { DecisionSubject } from "@repo/protocol/domain/decision";4 import { Handle } from "@repo/protocol/ids";2 unmodified lines7 import type { DateTime } from "effect";8 9 import type { ProjectEventInput } from "../events.ts";10 17-/** What the project service does after a proposal or decision moved, in order. */11 export type AttentionEffect = Data.TaggedEnum<{19- /** Tell the project's watchers. */12 Emit: { readonly event: ProjectEventInput };21- /** Let what a decider said yes to go ahead: a ratchet raised, a waiver, a vouch, a stray push adopted. */13 Land: { readonly subject: DecisionSubject };23- /** Write the accepted proposal's ask file and open it, red first, like any ask. */14 OpenAsk: { readonly proposal: ProposalId };25- /** Land a commit that puts `ref` back to `to`'s tree: a stray push undone, its commits kept in history. */15 Revert: { readonly ref: RefNameText; readonly to: CommitSha };16 SetAlarm: { readonly at: DateTime.Utc };17 }>;18 30-/** Constructors for attention's effects. */19 export const AttentionEffect = Data.taggedEnum<AttentionEffect>();20 33-/**34- * The platform's own handle: who `decided.by` names when nobody decided in35- * time and a decision took its default.36- */21 export const platformHandle: Handle = Handle.make(Brand.slug);modified:packages/project/src/attention/promote.ts+2 added-98 removed
1-/**2- * The Garden's "Promote" beat: when deciders have finished two or3- * more answers in one area for the same reason, the same lint rule, that4- * class of mistake is put to them as one decision. Accepted, its proposal5- * opens a `lintToZero` ask for the rule in that territory, red first like6- * any ask (the run on main at `openAsk` is the proof the rule still finds7- * something; no rule is replayed against old trees). Its default is8- * `decline`, so ignoring it changes nothing, and nothing opens without a9- * person's yes.10- *11- * Pure over records: the service gives the finishes it knows, the project's12- * decisions so far, and ids minted from its sequence; it writes what comes13- * back as it writes a proposal and its decision.14- */1 import { Brand } from "@repo/brand";2 import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";3 import type { Evidence } from "@repo/protocol/domain/common";4 import { DecisionSubject } from "@repo/protocol/domain/decision";12 unmodified lines17 18 import { decidersFor, openDecision } from "./decisions.ts";19 import { platformHandle } from "./effects.ts";20 35-/**36- * One finish: a decider's commits on top of an answer before it landed37- * (`Finished-by`). Its `area` is the module of the ask's territory; `rule`38- * is the lint rule its verdict's lanes name, and `note` what the decider39- * wrote; `paths` are the files the finish changed.40- */21 export interface FinishRecord {42- /** The ask the finished answer answered: a finish's id, one per landing. */22 readonly ask: AskId;23 readonly area: string;24 readonly decider: Handle;25 readonly at: DateTime.Utc;1 unmodified line27 readonly note: Option.Option<string>;28 readonly paths: readonly RepoPath[];29 }30 52-/** A promotion: the proposal for a `lintToZero` ask, and the decision that puts it to its deciders. */31 export interface Promotion {32 readonly decision: Decision;33 readonly proposal: Proposal;34 }35 58-/** What `promotions` reads. */36 export interface PromotionInput {60- /** The project's decisions so far, decided and expired ones included. */37 readonly existing: readonly Decision[];38 readonly finishes: readonly FinishRecord[];63- /** The next ids of the project's sequence (never `crypto.randomUUID`). */39 readonly ids: {40 readonly decision: DecisionId;41 readonly proposal: ProposalId;42 };1 unmodified line44 readonly policy: Policy;45 readonly project: ProjectName;46 }47 73-/** The evidence labels a promotion is found again by. */48 const labels = {49 area: "area",50 finished: "finished",51 promotedFrom: "promoted from",1 unmodified line53 want: "want",54 why: "why",55 } as const;56 83-/**84- * A lint rule as its id is written, in lowercase: `no-date-equality`,85- * `typescript/no-explicit-any`, `@typescript-eslint/no-explicit-any`.86- */57 const ruleId = /^@?[a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)*$/u;58 89-/** Words joined as a rule's id joins them, by a dash or a slash. */59 const joined = /[-/]/u;60 92-/** A backticked span in a note: `` `no-date-equality` ``. */61 const backticked = /`(?<span>[^`]+)`/gu;62 95-/**96- * `text` as the rule a note names. It is taken as written, and it must join97- * two words or more, so a one-word note (`typo`) or a code span98- * (`startOfDay`) names no rule; a one-word rule (`eqeqeq`) comes from the99- * lanes.100- */63 const asRule = (text: string): Option.Option<string> =>64 Option.liftPredicate(65 text.trim(),66 (word) => ruleId.test(word) && joined.test(word)67 );68 107-/**108- * The rule a decider's note names: the note itself when it is one rule id,109- * else its first backticked span that is one. A note in prose alone names110- * no rule, so it promotes nothing: a `lintToZero` ask needs a rule.111- */69 const ruleInNote = (note: string): Option.Option<string> =>70 Option.orElse(asRule(note), () =>71 Arr.findFirst([...note.matchAll(backticked)], ({ groups }) =>72 asRule(groups?.span ?? "")73 )74 );75 119-/** Why a finish was made: the rule its lanes name, else the rule its note names. */76 const reasonOf = (finish: FinishRecord): Option.Option<string> =>77 Option.orElse(78 Option.filter(79 Option.map(finish.rule, (rule) => rule.trim()),1 unmodified line81 ),82 () => Option.flatMap(finish.note, ruleInNote)83 );84 129-/** A finish with the rule it was made for. */85 interface Reasoned {86 readonly finish: FinishRecord;87 readonly rule: string;88 }89 135-/** Finishes in one area for one rule, oldest first. */90 interface Group {91 readonly area: string;92 readonly finishes: Arr.NonEmptyReadonlyArray<FinishRecord>;93 readonly rule: string;8 unmodified lines102 Order.mapInput(Order.String, ({ area }: Group) => area),103 Order.mapInput(Order.String, ({ rule }: Group) => rule)104 );105 152-/** Finishes grouped by (area, rule), each group oldest first, groups by area then rule. */106 const groupsOf = (finishes: readonly Reasoned[]): readonly Group[] =>107 Arr.sort(108 Object.values(109 Arr.groupBy(finishes, ({ finish, rule }) =>14 unmodified lines124 Arr.findFirst(decision.evidence, (each) => each.label === label).pipe(125 Option.map(({ value }) => value)126 );127 175-/** The promotions decided or open for `group`'s area and rule. */128 const promotedFor = (existing: readonly Decision[], group: Group) =>129 existing.filter(130 (decision) =>131 DecisionSubject.guards.OpenProposal(decision.subject) &&1 unmodified line133 Option.contains(valueOf(decision, labels.area), group.area) &&134 Option.contains(valueOf(decision, labels.rule), group.rule)135 );136 185-/** The finishes a promotion was made from: the key its evidence carries. */137 const finishesNamed = (decision: Decision): readonly string[] =>138 Option.match(valueOf(decision, labels.promotedFrom), {139 onNone: () => [],140 onSome: (value) => value.split(" "),2 unmodified lines143 const isOpen = (decision: Decision, now: DateTime.Utc) =>144 decision.decided === undefined &&145 DateTime.isLessThan(now, decision.expiresAt);146 196-/**197- * The finishes of `group` no earlier promotion of the same area and rule198- * was made from, each ask once; none while such a promotion is still open.199- * A promotion declined, or let expire, keeps its finishes: two new ones are200- * needed to ask again.201- */147 const freshOf = (148 existing: readonly Decision[],149 group: Group,150 now: DateTime.Utc11 unmodified lines162 (one, other) => one.ask === other.ask163 );164 };165 221-/** Whether an ask not yet closed already holds `rule` to zero. */166 const alreadyAsked = (policy: Policy, rule: string) =>167 policy.asks.some(168 ({ check, state }) =>169 state !== "closed" &&170 CheckSpec.guards.LintToZero(check) &&171 check.rule === rule172 );173 230-/**231- * The project's own lint command, with JSON output: a counted ratchet's for232- * `rule`, else any counted ratchet's, else a `lintToZero` ask's. A project233- * that has none is not guessed at, and nothing is promoted.234- */174 const lintCommandOf = (policy: Policy, rule: string): Option.Option<string> => {175 const counted = policy.ratchets.flatMap(({ measure }) =>176 RatchetMeasure.guards.Count(measure) ? [measure] : []177 );10 unmodified lines188 )189 );190 };191 253-/** The project's kind for `lintToZero` asks: the first of that check kind it lists. */192 const lintKindOf = (policy: Policy): Option.Option<AskKind> =>193 Arr.findFirst(policy.kinds, ({ checkKind }) => checkKind === "lintToZero");194 257-/** Where the ask may change things: a module by its name, or folders as globs. */195 type Place =196 | { readonly module: string }197 | { readonly globs: Arr.NonEmptyReadonlyArray<string> };198 199 const folderOf = (path: string) => path.split("/").slice(0, -1).join("/");200 264-/** Whether `folder` sits under `other`. */201 const isUnder = (folder: string, other: string) =>202 folder !== other && folder.startsWith(`${other}/`);203 268-/**269- * The folders `paths` sit in, as globs, each under no other: `src/date/**`;270- * `**` when a file sits at the root.271- */204 const foldersOf = (paths: readonly RepoPath[]): readonly string[] => {205 const folders = Arr.dedupe(paths.map(folderOf));206 207 if (folders.includes("")) {7 unmodified lines215 Order.String216 ).map((folder) => `${folder}/**`);217 };218 287-/**288- * The territory the finishes touched: their area when it is one of the289- * project's modules, else the folders of the files they changed.290- */219 const placeOf = (220 policy: Policy,221 area: string,222 finishes: readonly FinishRecord[]11 unmodified lines234 235 const describePlace = (place: Place) =>236 "module" in place ? place.module : place.globs.join(", ");237 310-/** `no-date-equality` in `src/date` → `no-date-equality-in-src-date`. */238 const slug = (text: string) =>239 text240 .toLowerCase()241 .replaceAll(/[^a-z0-9]+/gu, "-")242 .replaceAll(/^-+|-+$/gu, "");243 317-/** The new ask's id: the rule, and the area unless it is the whole repo. */244 const askIdOf = (rule: string, area: string): Option.Option<AskId> =>245 Schema.decodeOption(AskId)(246 area === "." || slug(area) === ""247 ? slug(rule)1 unmodified line249 );250 251 const quoted = (text: string) => JSON.stringify(text);252 327-/** A list of names as a sentence says it: `alice`, `alice and bob`, `alice, bob and carol`. */253 const spoken = (names: Arr.NonEmptyReadonlyArray<string>) => {254 const last = Arr.lastNonEmpty(names);255 const rest = Arr.initNonEmpty(names);256 257 return rest.length === 0 ? last : `${rest.join(", ")} and ${last}`;258 };259 335-/** What the ask file's territory field says. */260 const territoryCall = (place: Place) =>261 "module" in place262 ? `territory.package(${quoted(place.module)})`263 : `territory.paths(${place.globs.map(quoted).join(", ")})`;264 341-/**342- * The ask file, through the sdk's `kinds.lintToZero` when the project's343- * kind is that one, else through a kind of its own name made in the file344- * (as a migrate family's child is written). A `lintToZero` ask's check is345- * built from its args, so the ask file is its only file.346- */265 const askFileOf = (input: {266 readonly command: string;267 readonly from: readonly FinishRecord[];268 readonly kind: AskKind;41 unmodified lines310 "",311 ].join("\n");312 };313 396-/** One finish as its decision shows it: `compare-days by alice on 2026-10-01: <note>`. */314 const finishLine = (finish: FinishRecord) => {315 const line = `${finish.ask} by ${finish.decider} on ${DateTime.formatIsoDateUtc(finish.at)}`;316 317 return Option.match(finish.note, {1 unmodified line319 onSome: (note) => `${line}: ${note.trim()}`,320 });321 };322 406-/** `group`'s promotion, when it is due and the project can hold its ask. */323 const promotionOf = (324 input: PromotionInput,325 group: Group326 ): Option.Option<Promotion> => {17 unmodified lines344 );345 346 const touched = fresh.flatMap(({ paths }) => paths);347 432- // The finishers who still decide for what they touched: the decision is433- // theirs ("you finished 2 answers …"), and accepting needs a decider.348+ // Only finishers who still decide: accepting needs a decider.349 const deciders = decidersFor(policy, touched).filter((decider) =>350 fresh.some((finish) => sameHandle(finish.decider, decider))351 );352 59 unmodified lines412 return { decision, proposal };413 });414 };415 501-/**502- * The promotions due: finishes grouped by (area, rule), counting those503- * within the policy's record window; a group of two or more finishes no504- * earlier promotion of it was made from, with no promotion of it still505- * open, is put to the finishers who still decide for what they touched.506- *507- * At most one per call, since `ids` is one pair from the project's508- * sequence: called as each finish lands, only that finish's group can509- * become due. Groups go by area, then rule; one that cannot be held as an510- * ask (no rule, no `lintToZero` kind, no JSON lint command, an ask for the511- * rule already open, no decider left) is skipped.512- */416+/** At most one per call: `ids` is one pair from the project's sequence. */417 export const promotions = (input: PromotionInput): readonly Promotion[] => {418 const since = DateTime.subtract(input.now, {419 days: input.policy.record.windowDays,420 });15 unmodified linesmodified:packages/project/src/attention/proposals.ts+4 added-96 removed
1-/**2- * Proposals: how a person who is not a decider asks for an ask, or flags one3- * that is wrong. Anyone not denounced may, up to a cap of open proposals per4- * person, and every proposal expires on its own unless a decider accepts it5- * (expiry, not the cap, is what bounds a flood). Pure, like the lifecycles:6- * `now` is an argument, and what follows comes back as effects.7- *8- * A proposal never opens an ask by itself. The service opens an9- * `OpenProposal` decision beside it, and only a decider's `accept` opens the10- * ask (`OpenAsk`), red first like any other.11- */1 import type { Evidence } from "@repo/protocol/domain/common";2 import type { Policy } from "@repo/protocol/domain/policy";3 import { DraftState } from "@repo/protocol/domain/proposal";4 import type { Proposal } from "@repo/protocol/domain/proposal";20 unmodified lines25 import { DRAFT_ROUNDS, DraftResult } from "../draft-runs.ts";26 import { ProjectEventInput } from "../events.ts";27 import { AttentionEffect } from "./effects.ts";28 40-/**41- * What every proposal command carries: the id the service minted, the42- * project, the person proposing, and what the service knows about them that43- * a proposal does not: how many of their proposals are open (`openCount`,44- * against the cap) and whether the vouch file denounces them.45- */29 interface Proposer {30 readonly denounced: boolean;48- /** Minted from the project's sequence. */31 readonly id: ProposalId;32 readonly openCount: number;33 readonly project: ProjectName;34 readonly who: Person;35 }36 55-/** A sealed answer: a commit in the proposer's fork, judged once the ask opens. */37 interface Sealed {38 readonly fork: RepoName;39 readonly head: CommitSha;40 }41 61-/**62- * What a person can put to a project's deciders. `Propose` asks for a new63- * ask; `Flag` says an existing one is wrong (its check, its want, its64- * territory), the legal exit for whoever finds an ask they cannot answer65- * honestly. `vouched` and `recordInArea` (their landings that count in the66- * proposal's area) are the service's to work out.67- */42 export type ProposalCommand = Data.TaggedEnum<{43 Flag: Proposer & { readonly ask: AskId; readonly reason: string };44 Propose: Proposer & {71- /** The proposed ask file and its check, held as rows until accepted. */45 readonly files: readonly RepoPath[];46 readonly recordInArea: number;47 readonly sealed: Option.Option<Sealed>;48 readonly territory: Option.Option<string>;1 unmodified line50 readonly want: string;51 };52 }>;53 81-/** Constructors for proposal commands. */54 export const ProposalCommand = Data.taggedEnum<ProposalCommand>();55 84-/**85- * What moves an open proposal's draft. `DraftStarted`: the platform's86- * agent starts drafting its ask, at `by`'s request, in its first round or87- * one more (at most `DRAFT_ROUNDS`), with the note `by` asked it with, if88- * any. `DraftSettled`: a round ended, as its run reports it.89- */56 export type DraftCommand = Data.TaggedEnum<{57 DraftSettled: { readonly result: DraftResult; readonly round: number };58 DraftStarted: { readonly by: Handle; readonly note?: string };59 }>;60 95-/** Constructors for draft commands. */61 export const DraftCommand = Data.taggedEnum<DraftCommand>();62 63 type Propose = Data.TaggedEnum.Value<ProposalCommand, "Propose">;64 100-/** A proposal opened: the proposal and what the service does next. */65 export interface Proposed {66 readonly effects: readonly AttentionEffect[];67 readonly proposal: Proposal;68 }69 106-/**107- * Whether a new ask's proposer lacks a vouch the project needs: under `all`108- * every proposal needs one; under `forCode` only one that carries a sealed109- * answer (that is code); under `bansOnly` none does. A flag never needs one,110- * since it changes no code.111- */70 const lacksVouch = (policy: Policy, { sealed, vouched }: Propose) => {71 const { mode } = policy.vouch;72 73 return (1 unmodified line75 (mode === "all" || (mode === "forCode" && Option.isSome(sealed)))76 );77 };78 121-/**122- * Whether a person may put a proposal to the deciders. A denouncement bars123- * everyone it names, in every mode; then a missing vouch. The cap comes124- * last: it is the only refusal that waiting can lift.125- */79 const admit = (80 policy: Policy,81 { denounced, openCount }: Proposer,82 unvouched: boolean12 unmodified lines95 ? Result.fail(new CapReached({ cap, limit: "proposals" }))96 : Result.void;97 };98 146-/** The fields every proposal opens with, expiring after the policy's days. */99 const opening = (policy: Policy, proposer: Proposer, now: DateTime.Utc) => ({100 expiresAt: DateTime.add(now, { days: policy.budget.expireDays }),101 id: proposer.id,102 openedAt: now,1 unmodified line104 proposer: proposer.who.handle,105 state: "open" as const,106 });107 156-/**157- * A new ask's proposal. A sealed answer keeps the first-answer slot only158- * when its proposer has a record in the area: then it stays on the159- * proposal and is judged first once the ask opens. Without one it is160- * dropped, so the proposer is credited `Asked-by` only and the ask opens to161- * everyone.162- */108 const proposalFor = (109 policy: Policy,110 command: Propose,111 now: DateTime.Utc19 unmodified lines131 onSome: (sealed) => ({ ...territory, sealed }),132 });133 };134 190-/** The proposal opened, with an alarm at its expiry and an event for watchers. */135 const opened = (proposal: Proposal, now: DateTime.Utc): Proposed => ({136 effects: [137 AttentionEffect.SetAlarm({ at: proposal.expiresAt }),138 AttentionEffect.Emit({5 unmodified lines144 ],145 proposal,146 });147 204-/**205- * Opens a proposal, or refuses it with a refusal that changes nothing. A206- * flag becomes a proposal whose `flags` is the ask and whose want is the207- * reason. Either one expires `budget.expireDays` after `now`.208- */148 export const propose = (149 policy: Policy,150 command: ProposalCommand,151 now: DateTime.Utc16 unmodified lines168 opened(proposalFor(policy, proposing, now), now)169 ),170 });171 233-/** A project's proposals after an alarm, and what follows from the ones that expired. */172 export interface ExpiredProposals {173 readonly effects: readonly AttentionEffect[];174 readonly proposals: readonly Proposal[];175 }176 239-/**240- * An alarm fired: every open proposal at or past its expiry expires. The241- * rest stay as they are, in order.242- *243- * It emits nothing of its own: the proposal's `OpenProposal` decision244- * expires at the same moment, and its `Decided` event (the default,245- * `decline`) is what watchers hear. `ProjectEvent` has no event for a246- * proposal closing.247- */177+// Emits no event: the proposal's `OpenProposal` decision expires at the same178+// moment, and its `Decided` event is what watchers hear.179 export const expire = (180 proposals: readonly Proposal[],181 now: DateTime.Utc182 ): ExpiredProposals => ({5 unmodified lines188 : proposal189 ),190 });191 261-/**262- * A proposal's draft moved: the proposal after it, what the service does263- * next, and, once a round settles, the lines its decision's evidence adds264- * to the want, the territory and the files.265- */192 export interface Drafted {193 readonly effects: readonly AttentionEffect[];194 readonly lines: readonly Evidence[];195 readonly proposal: Proposal;196 }197 272-/** The round a proposal's next draft takes: one after its last, or the first. */198 const nextRound = (proposal: Proposal) =>199 proposal.draft === undefined ? 1 : proposal.draft.round + 1;200 276-/**277- * A round that started drafting and has not settled: the proposal's278- * current one, still open.279- */201 const drafting = (proposal: Proposal, round: number) =>202 proposal.state === "open" &&203 proposal.draft !== undefined &&204 DraftState.guards.Drafting(proposal.draft) &&205 proposal.draft.round === round;206 286-/** The evidence line that says why a proposal's last draft round failed. */207 export const draftFailedLabel = "draft failed";208 289-/** What a settled round's decision says beside the want: red first and who drafted, or why it failed. */209 const settledLines = (result: DraftResult): readonly Evidence[] =>210 DraftResult.match(result, {211 Failed: ({ refusal }): readonly Evidence[] => [212 { label: draftFailedLabel, value: explain([refusal])[0] ?? refusal._tag },7 unmodified lines220 { label: "why this test", value: rationale },221 ],222 });223 305-/**306- * The proposal once a round settled: its files and `Ready`, or `Failed`.307- * A failed first round leaves no files; a later one keeps the files the308- * proposal holds, which are its last ready round's (a failed round before309- * it kept none), so a decider can still accept that draft.310- */224+// A failed round keeps the last ready round's files, so a decider can still225+// accept that draft.226 const settledProposal = (227 proposal: Proposal,228 round: number,229 result: DraftResult20 unmodified lines250 files: files.map(({ path }) => path),251 }),252 });253 339-/**340- * A proposal's draft, moved. `DraftStarted` drafts an open proposal in its341- * next round, refused while a round drafts, once the proposal is closed,342- * and past `DRAFT_ROUNDS`. `DraftSettled` settles the round drafting now343- * and nothing else: a stale round, a settled one, or a closed proposal344- * gives none, so a report that comes twice changes nothing.345- */254 export const draft = (255 proposal: Proposal,256 command: DraftCommand,257 now: DateTime.Utc56 unmodified linesmodified:packages/project/src/attention/record.ts+2 added-45 removed
1-/**2- * A person's record (GLOSSARY "Record"): their landings by area that stayed3- * unreverted long enough to count, inside the window that still counts. It4- * answers trust rules only, yes or no: it is never a score, never a ranking,5- * and never leaves `packages/project`. Nothing here counts6- * against anyone: a check that flaked or a verifier that was blocked never7- * reached a landing, so it is not in the record at all.8- *9- * Pure: `now` and which landings were reverted are arguments. The project10- * service builds `reverted` from revert landings and `StrayPush` decisions11- * decided `revert`, since a landing does not say it was reverted.12- */1 import type { Ask } from "@repo/protocol/domain/ask";2 import type { LandingView } from "@repo/protocol/domain/landing";3 import type { Policy } from "@repo/protocol/domain/policy";4 import type { AskId, Handle, LandedSha, ProjectName } from "@repo/protocol/ids";5 import { Array as Arr, DateTime, Option } from "effect";6 19-/** One landing that counts on its accountable person's record, in its area. */7 export interface RecordEntry {21- /** The module of the territory its ask was in. */8 readonly area: string;23- /** When it landed. */9 readonly at: DateTime.Utc;10 readonly handle: Handle;11 readonly landing: LandedSha;12 readonly project: ProjectName;13 }14 30-/** What a record is built from. */15 export interface RecordInput {32- /**33- * The project's asks by id, closed ones included, to find each landing's34- * area. Ask ids are unique only within a project, so give one project's35- * asks and landings, and build one record per project for several: a36- * landing whose id finds another project's ask counts for no area.37- */16+ /** Ask ids are unique only within a project: give one project's asks and landings. */17 readonly asks: ReadonlyMap<AskId, Ask>;18 readonly landings: readonly LandingView[];19 readonly now: DateTime.Utc;20 readonly policy: Policy["record"];42- /** Landings since reverted; they never count. */21 readonly reverted: ReadonlySet<LandedSha>;22 }23 46-/** A record rule: at least `atLeast` counted landings in `area`. */24 export interface RecordRule {25 readonly area: string;26 readonly atLeast: number;27 }28 52-/** A handle as a map key: the form `sameHandle` (`@repo/protocol/ids`) compares by. */29 const personOf = (handle: Handle) => handle.toLowerCase();30 55-/**56- * A landing's area: the module of the territory its ask was in. A landing57- * that answered no ask (a decider's own, the first adoption), or whose ask58- * is not known in its project, has none.59- */31 export const areaOf = (32 landing: LandingView,33 asks: ReadonlyMap<AskId, Ask>34 ): Option.Option<string> =>2 unmodified lines37 Option.filter((ask) => ask.project === landing.project),38 Option.map((ask) => ask.territory.module)39 );40 70-/**71- * Whether a landing counts at `now`: it has stayed for `countsAfterDays`72- * (from that day on) and is no older than `windowDays` (that day included).73- */41 const counts = (42 landedAt: DateTime.Utc,43 now: DateTime.Utc,44 window: Policy["record"]6 unmodified lines51 now,52 DateTime.add(landedAt, { days: window.windowDays })53 );54 88-/**89- * Everyone's record at `now`, built once; the result looks up one person's.90- * A landing is on the record of its author, the accountable person, and91- * counts after `countsAfterDays` unreverted, for `windowDays`. Entries keep92- * the landings' order.93- */55 export const recordOf = (56 input: RecordInput57 ): ((handle: Handle) => readonly RecordEntry[]) => {58 const entries = Arr.flatMap(input.landings, (landing): RecordEntry[] => {33 unmodified lines92 93 return (handle) => byPerson.get(personOf(handle)) ?? [];94 };95 135-/**136- * Whether a record holds at least `atLeast` counted landings in `area`: yes137- * or no, never how many. It counts every entry it is given, so a caller138- * holding several projects' entries passes one project's (`mayClaim` does).139- */96+/** Counts every entry it is given: pass one project's entries. */97 export const meets = (98 entries: readonly RecordEntry[],99 rule: RecordRule100 ): boolean =>1 unmodified linemodified:packages/project/src/attention/today.ts-26 removed
1-/**2- * Today: a decider's daily page. Their open decisions in order of expiry,3- * held to what is left of the day's budget, with the rest counted as4- * overflow (it waits, and may expire to its safe default); the decisions5- * about to expire; the people to welcome; and a sample of what landed6- * without anyone. A pure function of the project's rows and `now`.7- */1 import type { CreditRole } from "@repo/protocol/domain/credit";2 import type { Decision, Today } from "@repo/protocol/domain/decision";3 import type { LandingView } from "@repo/protocol/domain/landing";4 import { sameHandle } from "@repo/protocol/ids";1 unmodified line6 import { Array as Arr, DateTime, Order } from "effect";7 8 import type { Budget } from "./budget.ts";9 17-/** How near its expiry a decision is called out. */10 const soon = { hours: 24 } as const;11 20-/** How recent a first claim makes a newcomer. */12 const welcome = { days: 7 } as const;13 23-/** How many unattended landings Today samples. */14 const sampled = 5;15 26-/** The credit a decider's attention leaves on a landing. */16 const attended: ReadonlySet<CreditRole> = new Set([17 "Decided-by",18 "Finished-by",19 ]);20 32-/** By expiry, then by opening, then by id: the same order every time. */21 const byExpiry: Order.Order<Decision> = Order.combineAll([22 Order.mapInput(DateTime.Order, ({ expiresAt }: Decision) => expiresAt),23 Order.mapInput(DateTime.Order, ({ openedAt }: Decision) => openedAt),24 Order.mapInput(Order.String, ({ id }: Decision) => id),25 ]);26 39-/** Newest first, then by SHA. */27 const newestFirst: Order.Order<LandingView> = Order.combine(28 Order.flip(29 Order.mapInput(DateTime.Order, ({ landedAt }: LandingView) => landedAt)30 ),31 Order.mapInput(Order.String, ({ sha }: LandingView) => sha)32 );33 47-/**48- * A landing that needed nobody: it answered an ask, and no decider decided49- * on it or finished it. A decider's own landing answers no ask.50- */34 const isUnattended = (landing: LandingView) =>35 landing.ask !== undefined &&36 !landing.credits.some(({ role }) => attended.has(role));37 55-/**56- * `decider`'s Today. Their decisions are the open ones that name them among57- * the deciders (set by `decidersFor` when each opened) and have not reached58- * their expiry. Today shows as many as `budget.total - budget.used` allows,59- * soonest to expire first, and counts the rest as `overflow`.60- * `expiringSoon` names every one of theirs that expires within 24 hours,61- * shown or not. `newcomers` are the people whose first claim was within the62- * last 7 days; `unattended` the newest 5 landings that needed nobody.63- */38 export const today = (input: {39 readonly decider: Handle;40 readonly decisions: readonly Decision[];41 readonly budget: Budget;43 unmodified linesmodified:packages/project/src/attention/vouch.ts+3 added-57 removed
1-/**2- * Vouches and denouncements (GLOSSARY "Vouch", "Denouncement"), and the3- * trust rules they feed: who may claim an ask, and who may propose one.4- * Every answer is yes or no; nothing here ranks or scores anyone.5- *6- * A person's standing comes from the vouch file at the landed SHA (parsed7- * into `Policy.vouches`), plus the vouch decisions decided since, which win8- * because they are newer. The project's deciders are its members, the people9- * who vouch, so they stand vouched without a line of their own: otherwise the10- * person who made a project could not fork it or claim in it.11- *12- * Pure: the project service passes the decisions, the person's record and13- * how many of their landings the project holds.14- */1 import type { Ask } from "@repo/protocol/domain/ask";2 import type { AskKind, ClaimRule } from "@repo/protocol/domain/kind";3 import type { Policy } from "@repo/protocol/domain/policy";4 import { sameHandle } from "@repo/protocol/ids";3 unmodified lines8 9 import { meets } from "./record.ts";10 import type { RecordEntry } from "./record.ts";11 26-/** Where a person stands with a project: vouched for, denounced, or neither. */12 export type Standing = "vouched" | "denounced" | "unknown";13 29-/** A vouch decision decided since the landed SHA, not yet in the vouch file there. */14 export interface DecidedVouch {15 readonly at: DateTime.Utc;16 readonly handle: Handle;17 readonly verdict: "vouch" | "denounce";18 }19 36-/** What `mayClaim` weighs. */20 export interface ClaimQuestion {21 readonly ask: Ask;39- /** The ask's kind, whose `claimers` rule says who may claim it. */22 readonly kind: AskKind;41- /** How many landings the person is accountable for in this project, held or not. */23 readonly landingsInProject: number;24 readonly policy: Policy;44- /** The person's record (`recordOf`), for a kind's record rule; entries in other projects never count. */25 readonly record: readonly RecordEntry[];26 readonly standing: Standing;27 }28 49-/** Why a person may not claim or propose. */29 export type TrustRefusal = Denounced | NotVouched;30 52-/** Yes, or the refusal that says why not. */31 export type TrustAnswer = Result.Result<void, TrustRefusal>;32 33 const allowed: TrustAnswer = Result.void;34 57-/** Oldest first; at one instant, a denouncement after a vouch, so it wins. */35+// Oldest first; at one instant, a denouncement after a vouch, so it wins.36 const byWhen = Order.combine(37 Order.mapInput(DateTime.Order, ({ at }: DecidedVouch) => at),38 Order.mapInput(39 Order.Boolean,40 ({ verdict }: DecidedVouch) => verdict === "denounce"41 )42 );43 66-/** The vouch file's word on a person: a denouncement beats a vouch on another line. */44 const fileSays = (policy: Policy, handle: Handle): Option.Option<Standing> => {45 const lines = policy.vouches.filter((line) =>46 sameHandle(line.handle, handle)47 );6 unmodified lines54 ? Option.some("vouched")55 : Option.none();56 };57 81-/** Whether the person decides for any paths in the project. */58 const isDecider = (policy: Policy, handle: Handle) =>59 policy.deciders.some(({ handles }) =>60 handles.some((each) => sameHandle(each, handle))61 );62 87-/**88- * A person's standing: the latest vouch decision about them, if any;89- * else the vouch file (`-handle` denounces, and wins over a vouch); else90- * `vouched` for a decider; else `unknown`. Handles match without case.91- */63 export const standing = (64 policy: Policy,65 decided: readonly DecidedVouch[],66 handle: Handle18 unmodified lines85 ),86 });87 };88 118-/**119- * Whether a newcomer claims an ask held for newcomers that names their120- * mentor: the mentor stands in for the vouch, as the `newcomer` rule's does.121- */89 const mentored = ({ ask, landingsInProject }: ClaimQuestion) =>90 ask.reserve === "newcomers" &&91 ask.mentor !== undefined &&92 landingsInProject === 0;93 127-/**128- * Whether a kind's `claimers` rule admits the person: `anyone`; `vouched`,129- * which the `bansOnly` mode lifts and a newcomers ask's mentor stands in130- * for; a record of `atLeast` held landings in an area of the ask's project,131- * which no vouch or mentor stands in for; or a newcomer, with no landing in132- * the project, whose mentor the rule names and who needs no vouch for it.133- */94 const admits = (rule: ClaimRule, question: ClaimQuestion): boolean =>95 Match.value(rule).pipe(96 Match.when("anyone", () => true),97 Match.when(17 unmodified lines115 ),116 Match.exhaustive117 );118 159-/**160- * May this person claim this ask? A denounced person never may, in any161- * mode. An ask reserved for `newcomers` takes only people with no landing in162- * the project, and otherwise follows its kind: the reserve narrows who the163- * kind admits, and widens it only by its mentor, who stands in for a vouch164- * (never for a record). An ask reserved for `people` refuses nobody: it165- * tells agents' harnesses to leave it to a person, and the platform can't166- * tell who typed a claim, so it is a hint only. Then the kind's `claimers`167- * rule decides. Every refusal but a denouncement is `NotVouched`: the person168- * is not admitted to this ask.169- */119+// An ask reserved for `people` refuses nobody: the platform can't tell who typed a120+// claim, so the reserve is a hint to agents' harnesses only.121 export const mayClaim = (question: ClaimQuestion): TrustAnswer => {122 if (question.standing === "denounced") {123 return Result.fail(new Denounced({}));124 }6 unmodified lines131 ? allowed132 : Result.fail(new NotVouched({}));133 };134 184-/**185- * May this person propose an ask (or flag one)? A vouch gates code, not186- * voice: anyone not denounced may, except under the `all` mode, where a187- * proposal needs a vouch too.188- */135 export const mayPropose = (policy: Policy, who: Standing): TrustAnswer => {136 if (who === "denounced") {137 return Result.fail(new Denounced({}));138 }5 unmodified linesmodified:packages/project/src/code/cache.ts+2 added-57 removed
1-/**2- * The code reads' cache: what an object id names never changes, so a read3- * keyed by `<repo>:<kind>:<object id>` (a tree, a blob, a commit, a commit's4- * diff, a blame at a commit) is read once. A `Context.Reference` whose5- * default caches nothing, so every host composes before one is given; the6- * platform gives one held in a layer (no module-level state, principle 6),7- * so it lives as long as the isolate. `main` and a tag are never a key:8- * each resolves through the project's record or the repo's tags on every9- * call.10- *11- * Entries come in two weights, each in a cache of its own, so a count of12- * entries bounds the memory they take: trees and commits are light (a few13- * KiB), while a file's text, a commit's path list or changes and a page of14- * the log are heavy (up to hundreds of KiB), and an isolate holds 128 MB.15- *16- * One view's walk (`asOneView`) also shares its light reads among its own17- * fibers while they are under way, and reads its repo through one session:18- * only for the view, never in the isolate's state.19- */1 import { inRepoSession } from "@repo/artifacts/repo-host";2 import { Cache, Context, Deferred, Effect, Exit, Layer, Option } from "effect";3 import type { Cause, Scope } from "effect";4 24-/** How a read's value is kept. */5 export interface Keeping<A> {26- /** Whether the value may weigh up to hundreds of KiB (a text, a list). */6 readonly heavy?: boolean;28- /** Whether this value may be kept at all; a larger one is read again. */7 readonly keep?: (value: A) => boolean;8 }9 32-/** The code reads, each kept by its key once read. */10 export interface CodeReads {34- /**35- * `read`, or what it gave before for `key`. A failure is never kept,36- * and neither is a value `keeping.keep` turns down (a large file's text).37- */11 readonly through: <A, E, R>(12 key: string,13 read: Effect.Effect<A, E, R>,14 keeping?: Keeping<A>5 unmodified lines20 });21 22 const always = () => true;23 51-/**52- * One cache of at most `capacity` values, each kept for good once set. It53- * never runs a lookup: a value enters only through `Cache.set`, once its54- * read has finished, so no entry is ever a read still under way.55- */24 const cacheOf = (capacity: number) =>25 Cache.make<string, unknown>({26 capacity,27 lookup: (key) => Effect.die(`the code cache never looks up ${key}`),28 });29 62-/**63- * `read` through `cache`: what it kept for `key`, else `read` run by this64- * caller, its value kept when `keep` allows. A read under way is never65- * shared: a Worker whose client goes away is cancelled where it stands,66- * with no interruption, so a read another request began may never end, and67- * a caller that joined it would hang with it.68- */30+// A read under way is never shared: a Worker whose client goes away is cancelled31+// without interruption, so a joined read may never end and its joiner would hang.32 const throughCache =33 (cache: Cache.Cache<string, unknown>) =>34 <A, E, R>(35 key: string,18 unmodified lines54 55 return value;56 });57 95-/**96- * At most `capacity` light reads and `heavy` heavy ones, the least97- * recently used of each dropped first. Only a finished read is kept: two98- * calls with one key while neither has finished each read for themselves,99- * and a failure is never kept.100- */58 export const CodeCacheLive = (59 capacity: number,60 heavy = Math.max(1, Math.ceil(capacity / 50))61 ) =>19 unmodified lines81 return reads;82 })83 );84 128-/** What a read under way came to, as the read that joins it: typed as it is. */85 const joined = <B, F>(86 under: Deferred.Deferred<Exit.Exit<unknown, unknown>>87 ): Effect.Effect<B, F> =>88 Effect.flatMap(Deferred.await(under), (exit) => {8 unmodified lines97 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one view shares every kind of read, so its map holds `unknown`; see SAFETY.98 return Effect.failCause(exit.cause as Cause.Cause<F>);99 });100 145-/**146- * `effect` as one view: a light read one of its fibers began (a tree, a147- * commit) is joined by the others rather than read again, its result kept148- * for the rest of the view, and every repo read runs in one `RepoSession`.149- * A walk's lookups run many at once, and two commits whose folders are the150- * same read each folder once. The reads under way live in the view's own151- * scope: a read the view started runs on whichever of its fibers asked for152- * it first gave up, and ends with the view, so nothing outlives the153- * request. Heavy reads, and reads a `keep` may turn down, go154- * straight through.155- */101 export const asOneView = <A, E, R>(102 effect: Effect.Effect<A, E, R>103 ): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>104 inRepoSession(40 unmodified linesmodified:packages/project/src/code/commit.ts+4 added-50 removed
1-/**2- * One commit and what it changed against its first parent (a root commit3- * against the empty tree), through `treeDiff` (`@repo/git/tree-diff`): each4- * file's status, both blob ids, whether it is binary, and its old and new5- * text. At most 300 files and 2 MiB of text in all: past 300 files every6- * file is a path only, and once the text runs past 2 MiB the files after7- * it are; either way the diff says it is `truncated`.8- *9- * Each file's two sides are read `SIDES_AT_ONCE` files at a time, in path10- * order, and the budget is spent in that order, so the diff is the one a11- * read of one file after another gives. A tree entry carries no size, so12- * a side the budget drops cannot be known before it is read: once the13- * budget runs out no further window is read, and at most one window's14- * reads go unused.15- *16- * What a commit changed never changes, so the finished diff is kept in the17- * code store by its repo and id (`commitKey`), without its landing: the18- * landing is asked of the project's record on every call, so a later19- * landing shows at once and the store holds none (principle 7). A kept20- * value that no longer decodes is computed again; the list of changes is21- * also kept in the isolate's cache by the commit's id.22- */1 import { RepoHost } from "@repo/artifacts/repo-host";2 import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";3 import { treeDiff } from "@repo/git/tree-diff";4 import type { Change } from "@repo/git/tree-diff";13 unmodified lines18 import { filesUnder, PATHS_CAP } from "./paths.ts";19 import { commitAt } from "./revision.ts";20 import { entriesOf, entryAt } from "./tree.ts";21 44-/** The most files a commit's diff carries text for. */22 export const DIFF_FILES = 300;23 47-/** The most text a commit's diff carries in all: 2 MiB. */24 export const DIFF_TEXT = 2 * 1024 * 1024;25 50-/** The kept commit's version, in its key: it moves when what is kept changes. */26+/** Bump when what is kept changes. */27 export const COMMIT_VERSION = 1;28 53-/** Where a commit's diff is kept in the code store: by its repo and its id. */29 export const commitKey = (repo: RepoName, sha: CommitSha) =>30 `${repo}/commit/v${COMMIT_VERSION}/${sha}`;31 57-/** How many files' sides are read at once: the fan-out the changes are listed with. */32 const SIDES_AT_ONCE = 8;33 60-/** The longest list of changes the cache keeps. */34 const KEPT_CHANGES = 1000;35 63-/** A change, and whether each side is a submodule (whose id names no blob here). */36+/** Whether each side is a submodule, whose id names no blob here. */37 interface Changed extends Change {38 readonly links: { readonly before: boolean; readonly after: boolean };39 }40 41 const isLink = (entry: Option.Option<TreeEntry>) =>42 Option.exists(entry, ({ type }) => type === "commit");43 71-/** Every file under a root commit's tree, each added. */44 const rootChanges = (repo: RepoName, tree: string) =>45 Effect.map(filesUnder(repo, tree, PATHS_CAP), ({ files }) =>46 files.map(({ entry, path }): Changed => ({47 after: BlobSha.make(entry.sha),2 unmodified lines50 status: "added",51 }))52 );53 82-/**83- * What changed from `base` to `head`, by `treeDiff` over this repo's trees84- * read through the cache (so the side lookups that follow read none again).85- */54 const changesBetween = (repo: RepoName, base: string, head: string) =>55 Effect.gen(function* () {56 const host = yield* RepoHost;57 34 unmodified lines92 });93 94 const byPath = Order.mapInput(Order.String, (change: Changed) => change.path);95 128-/** A side's contents, unless it is a submodule or absent. */96 const sideOf = (97 repo: RepoName,98 blob: BlobSha | undefined,99 link: boolean100 ): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>101 blob === undefined || link ? Effect.succeedNone : contentsOf(repo, blob);102 136-/** A change as a path, its status and its blob ids, with no text. */103 const pathOnly = ({ after, before, path, status }: Changed): ChangedFile => {104 const file = { binary: false, path, status };105 106 if (before !== undefined && after !== undefined) {6 unmodified lines113 114 return after === undefined ? file : { ...file, after };115 };116 151-/** Both sides of `change`: its old contents and its new, where it has them. */117 const sidesOf = (repo: RepoName, change: Changed) =>118 Effect.all([119 sideOf(repo, change.before, change.links.before),120 sideOf(repo, change.after, change.links.after),121 ]);122 158-/** The length of a side's text, or 0 when it has none. */123 const lengthOf = (text: Option.Option<string>) =>124 Option.match(text, { onNone: () => 0, onSome: ({ length }) => length });125 162-/**163- * Each change with its text while the budget lasts, and whether any went164- * without: the sides read a window of `SIDES_AT_ONCE` files at a time, the165- * budget spent in path order, and no window read once it ran out.166- */126+/** The budget is spent in path order, and no window is read once it runs out. */127 const withText = (repo: RepoName, changes: readonly Changed[]) =>128 Effect.gen(function* () {129 if (changes.length > DIFF_FILES) {130 return { files: changes.map(pathOnly), truncated: true };54 unmodified lines185 186 return { files, truncated };187 });188 229-/** A diff as the store keeps it: JSON, by the protocol's own schema. */189 const Kept = Schema.fromJsonString(CommitDiff);190 191 const decodeKept = Schema.decodeUnknownOption(Kept);192 193 const encodeKept = Schema.encodeEffect(Kept);194 236-/** `diff` with its commit's landing, asked of the project's record now. */195 const withLanding = (196 project: CodeProject,197 diff: CommitDiff198 ): Effect.Effect<CommitDiff> =>9 unmodified lines208 }209 )210 );211 254-/** The diff kept for `sha` in the code store, if one is and it still decodes. */212 const keptDiff = (repo: RepoName, sha: CommitSha) =>213 Effect.gen(function* () {214 const store = yield* CodeStore;215 const text = yield* store.get(commitKey(repo, sha));3 unmodified lines219 ({ commit }) => commit.sha === sha220 );221 });222 266-/** `diff`, which carries no landing, kept for `sha`; a store that fails keeps nothing. */223+/** Kept without its landing, which is asked of the record on every call. */224 const keepDiff = (repo: RepoName, sha: CommitSha, diff: CommitDiff) =>225 Effect.gen(function* () {226 const store = yield* CodeStore;227 4 unmodified lines232 )233 );234 });235 279-/** The diff of `sha` against its first parent, computed, with no landing. */236 const computedDiff = (237 repo: RepoName,238 sha: CommitSha239 ): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>24 unmodified lines264 Option.match(parent, {265 onNone: () => rootChanges(repo, commit.tree),266 onSome: ({ tree }) => changesBetween(repo, tree, commit.tree),267 }),312- // A longer list is listed again, over trees the cache keeps.268 { heavy: true, keep: (all) => all.length <= KEPT_CHANGES }269 )270 .pipe(Effect.orDie);271 4 unmodified lines276 277 return { commit: commitView(commit, Option.none()), files, truncated };278 });279 325-/** One commit and the files it changed against its first parent. */280 export const commitDiff = (281 project: CodeProject,282 sha: CommitSha283 ): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>14 unmodified linesmodified:packages/project/src/code/file-walk.ts+1 added-26 removed
1-/**2- * A walk over history that reads the file itself at each commit, one call3- * each, rather than the folders above it. A store answers one view a few4- * dozen calls a second, however many are under way (about 35 on5- * dev-oscabriel, repo reads and code store calls alike), and a path four6- * folders deep took two to three calls a commit by its folders: one root7- * tree each, and the folders above the path wherever they changed. Read8- * whole, the file is one call a commit, its git blob id is the SHA-1 of9- * its bytes, and each version's text is already at hand for the blame.10- *11- * Only a file at most `FILE_WALK_CAP` bytes at the walk's first commit is12- * walked this way, so a walk holds at most `READS_AT_ONCE` such files at13- * once; a larger file, a folder, a submodule or a missing path is looked14- * up by its folders (`tree.ts`). A commit where the path is not a file15- * (missing, or a folder then) reads as none, as a missing file does.16- */1+// A store answers a few dozen calls a second, and walking a path by its folders costs two to three calls a commit; reading a small file whole costs one.2 import { RepoHost, Revision } from "@repo/artifacts/repo-host";3 import type { RepoNotFound } from "@repo/artifacts/repo-host";4 import { BlobSha } from "@repo/protocol/ids";5 import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";6 import { Effect, Option } from "effect";7 23-/** The most a file may weigh at a walk's first commit to be read whole at each commit. */8 export const FILE_WALK_CAP = 256 * 1024;9 10 const encoder = new TextEncoder();11 1 unmodified line13 [...new Uint8Array(digest)]14 .map((byte) => byte.toString(16).padStart(2, "0"))15 .join("");16 33-/** The git blob id of `bytes`: the SHA-1 of `blob <size>\0` and the bytes. */17 export const blobIdOf = (bytes: Uint8Array): Effect.Effect<BlobSha> =>18 Effect.gen(function* () {19 const header = encoder.encode(`blob ${bytes.byteLength}\0`);20 const raw = new Uint8Array(header.byteLength + bytes.byteLength);7 unmodified lines28 29 return BlobSha.make(hex(digest));30 });31 49-/** The file at `path` in `commit`, read whole: none when no file is there. */32 export const fileAt = (33 repo: RepoName,34 commit: CommitSha,35 path: RepoPath1 unmodified line37 RepoHost.use((host) =>38 host.readFile(repo, Revision.Commit({ sha: commit }), path)39 );40 59-/** A file read whole at a commit: its blob id and its bytes. */41 export interface FileVersion {42 readonly blob: BlobSha;43 readonly bytes: Uint8Array;44 }45 65-/** The file's version at `path` in `commit`, read whole; none when no file is there. */46 export const versionAt = (47 repo: RepoName,48 commit: CommitSha,49 path: RepoPath5 unmodified lines55 Effect.map(blobIdOf(bytes), (blob) => Option.some({ blob, bytes })),56 })57 );58 79-/**80- * The file at `path` in `commit` as a version, when a walk may read it81- * whole at each commit: a file of at most `FILE_WALK_CAP` bytes. None82- * means the walk looks the path up by its folders instead.83- */59 export const walkableAt = (60 repo: RepoName,61 commit: CommitSha,62 path: RepoPath5 unmodified linesmodified:packages/project/src/code/file.ts+2 added-35 removed
1-/**2- * One file's contents as a reader sees them: its size, whether it is3- * binary (a NUL in its first 8 KiB, git's own test and `tree-diff.ts`'s),4- * and its text up to 1 MiB; past that, or when Artifacts answers that the5- * blob is too large to hold (`MEMORY_LIMIT`), it is truncated with no text.6- * Kept by the blob's id, unless its text is large.7- */1 import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2 import type { RepoNotFound } from "@repo/artifacts/repo-host";3 import type { FileView, Rev } from "@repo/protocol/domain/code";4 import { BlobSha } from "@repo/protocol/ids";7 unmodified lines12 import { versionAt } from "./file-walk.ts";13 import { commitAt, resolveRev } from "./revision.ts";14 import { entryAt } from "./tree.ts";15 23-/** The most text a file's view carries: 1 MiB. */16 export const TEXT_CAP = 1024 * 1024;17 18 // git's own test: a NUL among the first bytes means the blob is not text.19 const SNIFF = 8192;20 29-/** The largest text a cache entry keeps; a larger one is read again. */21 const KEPT_TEXT = 256 * 1024;22 32-/** Whether `bytes` read as binary: a NUL among the first 8 KiB. */23 export const isBinary = (bytes: Uint8Array) =>24 bytes.subarray(0, SNIFF).includes(0);25 36-/** A file's contents: its text only when it is text and within the cap. */26 export interface Contents {27 readonly size: number;28 readonly binary: boolean;29 readonly truncated: boolean;30 readonly text: Option.Option<string>;31 }32 44-/** What Artifacts throws when a blob is too large for the Worker to hold. */33 const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });34 35 const isMemoryLimit = Schema.is(MemoryLimit);36 49-/**50- * `read`, or `tooLarge` when Artifacts said the blob was too large to hold:51- * its binding throws that as a defect, which here is an answer.52- */37+/** Artifacts' binding throws a too-large blob as a defect, which here is an answer. */38 export const unlessTooLarge = <A, E, R>(39 read: Effect.Effect<A, E, R>,40 tooLarge: () => A41 ): Effect.Effect<A, E, R> =>42 Effect.catchDefect(read, (defect) =>43 isMemoryLimit(defect) ? Effect.succeed(tooLarge()) : Effect.die(defect)44 );45 61-/** `bytes` as a reader sees them. */46 export const contentsOfBytes = (bytes: Uint8Array): Contents => {47 const binary = isBinary(bytes);48 const truncated = !binary && bytes.length > TEXT_CAP;49 7 unmodified lines57 truncated,58 };59 };60 77-/**78- * The blob `blob`'s contents, kept by its id; none when the repo has no79- * blob by it (a submodule's commit).80- */61 export const contentsOf = (62 repo: RepoName,63 blob: BlobSha64 ): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>28 unmodified lines93 }94 );95 });96 117-/** A file's view from its blob id and contents. */97 const viewOf = (98 commit: CommitSha,99 path: RepoPath,100 sha: BlobSha,10 unmodified lines111 onSome: (text) => ({ text }),112 }),113 });114 136-/**137- * The file at `path` in `commit` read whole, one call, kept by the commit138- * and path in the isolate's cache (when within `KEPT_TEXT`); none when no139- * file is there or it is too large to hold, so the view looks it up by its140- * folders. ASSUMPTION: Artifacts' `readFile` gives a symlink's own blob, as141- * the tree does, rather than following it.142- */115+/** ASSUMPTION: Artifacts' `readFile` gives a symlink's own blob, as the tree does, rather than following it. */116 const wholeAt = (repo: RepoName, commit: CommitSha, path: RepoPath) =>117 Effect.gen(function* () {118 const cache = yield* CodeCache;119 10 unmodified lines130 }131 );132 });133 161-/**162- * One file at `at`: its text, or that it is binary or too large. A file163- * is read whole in one call (on a cold isolate its folders took one call164- * each, one after another); a folder, a submodule, a missing path or a165- * file too large to hold is looked up by its folders.166- */134 export const fileView = (135 project: CodeProject,136 at: Option.Option<Rev>,137 path: RepoPath36 unmodified linesmodified:packages/project/src/code/history.ts+7 added-45 removed
1 /**2- * Code history kept by immutable ids: what a why or a3- * path's log computed from a commit, which that commit's content fixes for4- * good, so any isolate reads it back instead of walking history again.5- *6- * Keys: `<repo>/<kind>/v<version>/<commit>/<scan>/<sha256(path)>`, where7- * `kind` is `why` (version `WHY_VERSION`) or `path-log` (version8- * `LOG_VERSION`), `commit` is a commit id (never `main` or a tag's name:9- * those resolve first), `scan` is how many first-parent commits the walk10- * took, and the path is hashed so a key stays under the store's 1,02411- * bytes. Only a project's canonical repo is ever keyed (principle 7). A12- * version moves when its algorithm changes, so an old value is never read13- * as a new one.14- *15- * Values: ids and ranges, encoded with Schema; never a file's text, and16- * never a landing (each view asks the project's record for those, so a17- * later landing shows at once). A value that fails to decode is a miss.18- *19- * Read order: the isolate's `CodeCache` (with the heavy reads: a why's20- * ranges grow with its file), then the `CodeStore`, then the walk; what a21- * walk computed is put in both. A walk may start from what is22- * kept at a first-parent ancestor at most `INCREMENT_REACH` commits back,23- * so a new landing on main costs a handful of reads.2+ * Code history kept by immutable ids. Keys:3+ * `<repo>/<kind>/v<version>/<commit>/<scan>/<sha256(path)>`; `commit` is never4+ * `main` or a tag (those resolve first), the path is hashed to keep a key5+ * under the store's 1,024 bytes, and only a canonical repo is ever keyed.6+ * Values hold ids and ranges, never a file's text or a landing.7 */8 import { WhyRange } from "@repo/protocol/domain/code";9 import { BlobSha, CommitSha } from "@repo/protocol/ids";10 import type { RepoName, RepoPath } from "@repo/protocol/ids";1 unmodified line12 13 import { CodeStore } from "../code-store.ts";14 import { CodeCache } from "./cache.ts";15 33-/** The why walk's algorithm version, in its keys. */16 export const WHY_VERSION = 1;17 36-/** The path log's algorithm version, in its keys. */18 export const LOG_VERSION = 1;19 39-/** How many first-parent commits back a walk looks for a kept result to start from. */20 export const INCREMENT_REACH = 16;21 42-/**43- * Why each line is there at a commit: the path's blob there, the ranges,44- * the commits they name (newest first), and where the walk stopped.45- */22 export const StoredWhy = Schema.Struct({23 blob: BlobSha,24 ranges: Schema.Array(WhyRange),25 shas: Schema.Array(CommitSha),1 unmodified line27 });28 29 export type StoredWhy = typeof StoredWhy.Type;30 55-/**56- * A path's history from a commit: the first-parent commits of the scan57- * that changed it, newest first, and whether the scan reached the root.58- */31 export const StoredPathLog = Schema.Struct({32 reachedRoot: Schema.Boolean,33 shas: Schema.Array(CommitSha),34 });35 36 export type StoredPathLog = typeof StoredPathLog.Type;37 66-/** The lowercase hex SHA-256 of `text`. */38 const sha256 = (text: string) =>39 Effect.map(40 Effect.promise(() =>41 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))3 unmodified lines45 .map((byte) => byte.toString(16).padStart(2, "0"))46 .join("")47 );48 78-/** One kind of kept history: its key's kind and version, and its value. */49 export interface Kept<A> {50 readonly kind: string;51 readonly version: number;52 readonly schema: Schema.Codec<A, unknown>;10 unmodified lines63 schema: StoredPathLog,64 version: LOG_VERSION,65 };66 97-/** Where `kept` is kept for `path` from `commit`, scanning `scan` commits. */67 export const keyOf = <A>(68 kept: Kept<A>,69 at: {70 readonly repo: RepoName;7 unmodified lines78 (hash) =>79 `${at.repo}/${kept.kind}/v${kept.version}/${at.commit}/${at.scan}/${hash}`80 );81 113-/**114- * What is kept under `key`: the isolate's cache first, then the store. A115- * miss is never cached, so a value another isolate keeps later is found.116- */82+/** A miss is never cached, so a value another isolate keeps later is found. */83 export const recall = <A>(84 kept: Kept<A>,85 key: string86 ): Effect.Effect<Option.Option<A>> =>11 unmodified lines98 { heavy: true, keep: Option.isSome }99 );100 });101 136-/** `value` kept under `key`, in the isolate's cache and in the store. */102 export const remember = <A>(103 kept: Kept<A>,104 key: string,105 value: A9 unmodified lines115 yield* store.put(key, encoded);116 yield* cache.through(key, Effect.succeedSome(value), { heavy: true });117 });118 154-/**155- * What is kept under `key`, else `compute` run and its value kept: a156- * failure is never kept.157- */119+/** A failure is never kept. */120 export const throughHistory = <A, E, R>(121 kept: Kept<A>,122 key: string,123 compute: Effect.Effect<A, E, R>7 unmodified linesmodified:packages/project/src/code/log.ts+2 added-49 removed
1-/**2- * The first-parent log from a revision, a page at a time: each commit as a3- * reader sees it (subject, body, trailers, who and when), and `landing`4- * only where the project's record has one, so a trailer in an imported5- * commit never reads as a landing. With a path, only the commits whose6- * first-parent change touched it, scanning at most 200 commits a call;7- * `next` is where the scan stopped, so the next page resumes it.8- *9- * A path's history from the scan's first commit is kept by immutable ids10- * (`history.ts`) under `<repo>/path-log/v<LOG_VERSION>/<commit>/<scan>/11- * <sha256(path)>`: the commits of the scan that changed the path, newest12- * first, and whether the scan reached the root; pages are cut from it.13- * Kept nowhere yet, it is the history kept at the nearest first-parent14- * ancestor within `INCREMENT_REACH` commits plus the commits between that15- * changed the path, cut to the scan; else each commit of the scan has its16- * entry looked up once (`READS_AT_ONCE` under way, in one ordered pass),17- * and neighbours compared.18- */1 import { inRepoSession, Revision, RepoHost } from "@repo/artifacts/repo-host";2 import type {3 Commit,4 RepoNotFound,20 unmodified lines25 import type { StoredPathLog } from "./history.ts";26 import { commitAt, resolveRev } from "./revision.ts";27 import { entryAt, READS_AT_ONCE } from "./tree.ts";28 47-/** The most commits one page holds. */29 export const LOG_LIMIT = 100;30 50-/** The most first-parent commits a path's log scans in one call. */31 export const PATH_SCAN = 200;32 53-/** A commit as a reader sees it, with its landing when it is one. */33 export const commitView = (34 commit: Commit,35 landing: Option.Option<LandingView>36 ): CommitView => {25 unmodified lines62 }),63 };64 };65 87-/** `commits` as a reader sees them, each landing from one batch of the project's record. */66 export const commitViews = (67 project: CodeProject,68 commits: readonly Commit[]69 ): Effect.Effect<readonly CommitView[]> =>11 unmodified lines81 );82 }83 );84 107-/**108- * `count` first-parent commits from `sha`, the first `from` skipped: a109- * commit's history never changes, so the page is kept by its start.110- */85 export const pageOf = (86 repo: RepoName,87 sha: CommitSha,88 from: number,10 unmodified lines99 { heavy: true }100 );101 });102 129-/** What sits at `path` in `tree`: its id and mode, or nothing. */103 const idAt = (repo: RepoName, tree: string, path: RepoPath) =>104 Effect.map(105 entryAt(repo, tree, path),106 Option.map(({ mode, sha }: TreeEntry) => `${mode} ${sha}`)107 );108 136-/** A page of the log, and where the next starts when there is more. */109 export interface LogPage {110 readonly commits: readonly CommitView[];111 readonly next?: number;112 }6 unmodified lines119 onNone: () => ({ commits }),120 onSome: (at) => ({ commits, next: at }),121 });122 151-/** What sits at a path in a commit, as a walk compares it with its parent's. */123 type IdOf = (124 commit: Commit125 ) => Effect.Effect<Option.Option<string>, RepoNotFound, RepoHost>;126 156-/**157- * How a walk from `start` looks `path` up in each commit: a file small158- * enough there is read whole, one call a commit (`file-walk.ts`), and159- * named by its blob id, so a change of its mode alone is not seen; any160- * other path by its folders, named by its mode and id.161- */127+// A small file is named by its blob id, so a change of its mode alone is not seen.128 const idOfFrom = (129 repo: RepoName,130 path: RepoPath,131 start: Commit13 unmodified lines145 ),146 })147 );148 183-/** What sits at the path in each commit of `commits`, in order: one lookup each. */149 const idsOf = (150 idOf: IdOf,151 commits: readonly Commit[]152 ): Effect.Effect<readonly Option.Option<string>[], RepoNotFound, RepoHost> =>153 Effect.forEach(commits, idOf, { concurrency: READS_AT_ONCE });154 190-/**191- * The commits among the first `count` of `scan` that changed `path` from192- * their first parent, newest first. The log is first parents, so each193- * commit's parent is the next in `scan`; only past it (or should the log194- * ever say otherwise) is a parent read on its own.195- */155 const changedIn = (156 repo: RepoName,157 idOf: IdOf,158 scan: readonly Commit[],34 unmodified lines193 194 return Array.getSomes(changed);195 });196 238-/** The path's history from `scan[0]`, kept at the nearest ancestor within reach. */197 const nearestKept = (repo: RepoName, path: RepoPath, scan: readonly Commit[]) =>198 Effect.map(199 Effect.forEach(200 scan.slice(1, INCREMENT_REACH + 1),9 unmodified lines210 Option.map(kept, (value) => ({ back: at + 1, kept: value }))211 )212 );213 256-/** The path's history over `scan` (at most `PATH_SCAN` commits and the parent of its last). */214 const historyOf = (215 repo: RepoName,216 path: RepoPath,217 scan: readonly Commit[]31 unmodified lines249 ],250 };251 });252 296-/** A page of first-parent commits from `at`, each landing with its record. */253 export const logPage = (254 project: CodeProject,255 input: {256 readonly at: Option.Option<Rev>;68 unmodified lines325 return pageWith(326 commits,327 scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()328 );373- }).pipe(374- // The scan and the walk over it: one session, one handle.375- inRepoSession376- );329+ }).pipe(inRepoSession);modified:packages/project/src/code/paths.ts+1 added-19 removed
1-/**2- * Every file of a commit: each blob, symlink and submodule path under its3- * root tree, up to 50,000 (a file tree's sidebar), kept by the root tree's4- * id. The walk reads at most eight trees at once, one depth at a time, and5- * stops descending once the cap is passed.6- */1 import type {2 RepoHost,3 RepoNotFound,4 TreeEntry,9 unmodified lines14 import { CodeCache } from "./cache.ts";15 import { commitAt, resolveRev } from "./revision.ts";16 import { entriesOf } from "./tree.ts";17 24-/** The most paths a commit's list holds. */18 export const PATHS_CAP = 50_000;19 27-/** The longest path list the cache keeps: about 1 MB of paths. */20 const KEPT_PATHS = 10_000;21 30-// Store calls under way at once, however wide or deep the tree.22 const STORE_CALLS = 8;23 33-/** One file under a root tree, with the entry that names it. */24 export interface FileAt {25 readonly path: RepoPath;26 readonly entry: TreeEntry;27 }28 39-/** A folder still to read: its path's prefix and its tree's id. */29 interface Folder {30 readonly prefix: string;31 readonly tree: string;32 }33 45-/**46- * Every file under the tree `root`, in path order; past `cap`, the walk47- * stops and says so. It reads one depth at a time, so which folders it48- * reaches before it stops depends on the tree alone, never on which read49- * came back first: the same tree gives the same list (principle 8).50- */34+/** One depth at a time, so the list past `cap` depends on the tree alone, never on which read came back first. */35 export const filesUnder = (36 repo: RepoName,37 root: string,38 cap: number42 unmodified lines81 truncated: all.length > cap || depth.length > 0,82 };83 });84 101-/** Every file path at `at`, up to the cap. */85 export const pathList = (86 project: CodeProject,87 at: Option.Option<Rev>88 ): Effect.Effect<PathList, UnknownRevision, RepoHost> =>9 unmodified lines98 const { files, truncated } = yield* cache99 .through(100 `${project.repo}:paths:${tree}`,101 filesUnder(project.repo, tree, PATHS_CAP),119- // A longer list is walked again, over trees the cache keeps.102 { heavy: true, keep: (list) => list.files.length <= KEPT_PATHS }103 )104 .pipe(Effect.orDie);105 2 unmodified linesmodified:packages/project/src/code/raw.ts+2 added-43 removed
1-/**2- * A project's raw bytes, `GET /<project>/raw/<rev>/<path…>` (ADR 0019),3- * as one pure response both the platform (`apps/platform/src/raw.ts`) and4- * the web's dev world serve. Both origins hold a session cookie, so no file5- * may run as script there: every answer carries `nosniff` and a sandboxing6- * CSP, images come back as themselves (an SVG too: an `<img>` never runs7- * its script, and opened on its own the sandbox gives it no script and an8- * opaque origin), markup and every other text as plain text, and anything9- * else binary as bytes to save. A file at a commit's id never changes, so10- * it is cached for good; at a name that moves, for a minute. Anything that11- * is not a file at a revision is a 404 that says nothing of the repo.12- */1 import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2 import { Rev } from "@repo/protocol/domain/code";3 import { BlobSha, RepoPath } from "@repo/protocol/ids";4 import type { ProjectName } from "@repo/protocol/ids";5 unmodified lines10 import { isBinary, unlessTooLarge } from "./file.ts";11 import { commitAt, isFullSha, resolveRev } from "./revision.ts";12 import { entryAt, segmentsOf } from "./tree.ts";13 26-/** What a raw answer may load and do: nothing but its own images and inline styles, sandboxed. */14+/** Both origins hold a session cookie, so no raw file may run as script: every answer, a refusal too, carries `nosniff` and this CSP. */15 const SANDBOX =16 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";17 18 const IMAGES = new Map([8 unmodified lines27 ]);28 29 const TEXT = "text/plain; charset=utf-8";30 43-/** What every raw answer carries, a refusal too (ADR 0019). */31 const SAFE = {32 "content-security-policy": SANDBOX,33 "x-content-type-options": "nosniff",34 } as const;35 49-/** `path`'s extension, lowercased; none without one. */36 const extensionOf = (path: string) => {37 const name = path.slice(path.lastIndexOf("/") + 1);38 const dot = name.lastIndexOf(".");39 40 return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();41 };42 57-/**58- * The headers a raw answer for the blob `blob` at `path` carries: its type59- * by extension (an image as itself, anything else as plain text, or as60- * bytes when `binary`), `nosniff` and the sandbox, and a cache for good61- * when `rev` is a commit's id, for a minute when it is a name.62- */43 export const rawHeaders = (44 path: RepoPath,45 rev: "sha" | "ref",46 blob: BlobSha,15 unmodified lines62 63 return headers;64 };65 86-/** A 404 that says nothing of the repo. */66 const notFound = () => new Response(null, { headers: SAFE, status: 404 });67 89-/** A 413: Artifacts said the blob is too large to hold. */68 const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });69 92-/** The file `path` at `rev` of the project's canonical repo, as raw bytes. */70 export const rawOf = (71 project: CodeProject,72 rev: Rev,73 path: RepoPath44 unmodified lines118 const decodePath = Schema.decodeUnknownOption(RepoPath);119 120 const decoded = Option.liftThrowable(decodeURIComponent);121 145-/**146- * A raw request's revision and path from everything after `raw/`, as the147- * URL carries it: the first segment is the revision (a tag's `/` arrives148- * as `%2F`), the rest the file's path, each decoded once. A path with an149- * empty, `.` or `..` segment, before or after decoding, is none.150- */122 export const rawRequestOf = (123 rest: string124 ): Option.Option<{ readonly rev: Rev; readonly path: RepoPath }> => {125 const slash = rest.indexOf("/");10 unmodified lines136 rev: Option.flatMap(decoded(rest.slice(0, slash)), decodeRev),137 });138 };139 169-/**170- * Everything after `/<project>/raw/` in a request's URL (whole, or its path171- * and query), still encoded, where the project's name takes as many172- * segments as it has (`oscabriel/datekit`, `github.com/pallets/click`, or a173- * legacy key's one). Read from the URL itself, not a router's parameter: a174- * router decodes `%2F`, which would cut a tag's name175- * (`%40datekit%2Fcore%402.0.0`) in two.176- */140+/** Read from the URL, not a router's parameter: a router decodes `%2F`, which would cut a tag's name in two. */141 export const rawRestOf = (url: string, project: ProjectName): string => {142 const segments = new URL(url, "http://raw.invalid").pathname.split("/");143 const named = project.split("/").length;144 3 unmodified lines148 149 return segments[2] === "raw" ? segments.slice(3).join("/") : "";150 };151 188-/**189- * The answer to `GET /<project>/raw/<rest>` at `url` (whole, or its path190- * and query): the project found by its name, then its file. A project191- * never made is a 404 too.192- */152 export const rawFor = (153 project: ProjectName,154 url: string155 ): Effect.Effect<Response, never, RepoHost | Projects> =>8 unmodified linesmodified:packages/project/src/code/refs.ts+4 added-25 removed
1-/**2- * A project's refs as readers see them: main's landed commit (the3- * project's record, never a ref), its tags peeled to their commits (the4- * repo's `tags`) in a reader's order (`sortTags`), and its forks. Only5- * `refs/tags/*` is read: nothing of the platform's own (its landed mirror,6- * compose refs, notes) and no branch but main ever shows.7- */1 import { RepoHost } from "@repo/artifacts/repo-host";2 import { packageOf, TagName } from "@repo/protocol/domain/code";3 import type { RefsView, TagRef } from "@repo/protocol/domain/code";4 import { Array, Effect, Option, Schema } from "effect";5 6 import type { CodeProject } from "../code.ts";7 import { tagNameOf } from "./revision.ts";8 16-/** A name cut into runs of digits and runs of anything else. */9 const runsOf = (name: string) => name.match(/\d+|\D+/gu) ?? [];10 11 const isDigits = (run: string) => /^\d/u.test(run);12 21-/** Two strings as written, code point by code point. */13 const compareText = (one: string, other: string) => {14 if (one === other) {15 return 0;16 }17 18 return one < other ? -1 : 1;19 };20 30-/** Two runs of digits by their value, however long. */21 const compareNumbers = (one: string, other: string) => {22 const left = one.replace(/^0+(?=\d)/u, "");23 const right = other.replace(/^0+(?=\d)/u, "");24 3 unmodified lines28 29 return compareText(left, right);30 };31 42-/**43- * Tags newest first, by version: runs of digits compare by value, so44- * `v1.10.0` comes before `v1.9.0`, and a release before its own45- * pre-releases (`v1.10.0` before `v1.10.0-beta.1`). Names are otherwise46- * compared as written, so a scoped package's tags stay together.47- */32+/** Newest first: digit runs compare by value (`v1.10.0` before `v1.9.0`), and a release before its pre-releases. */33 export const compareTags = (one: string, other: string): number => {34 const left = runsOf(one);35 const right = runsOf(other);36 14 unmodified lines51 if (left.length === right.length) {52 return 0;53 }54 70- // One name runs on past the other: a pre-release (`-beta.1`) is older71- // than its release, anything else newer.55+ // A pre-release (`-beta.1`) is older than its release, anything else newer.56 const longer = left.length > right.length ? left : right;57 const rest = longer[Math.min(left.length, right.length)] ?? "";58 const longerIsNewer = !rest.startsWith("-");59 const leftIsLonger = left.length > right.length;60 61 return leftIsLonger === longerIsNewer ? -1 : 1;62 };63 80-/**81- * Tags in the order a reader meets them, from their names alone: the tags82- * that version no package first; then each package's tags as one run, the83- * package with the most tags first (a monorepo's main package), ties by84- * name; newest first within each (`compareTags`).85- */64+/** Unversioned tags first, then each package's tags together, most tags first; newest first within each. */65 export const sortTags = <T extends { readonly name: string }>(66 tags: readonly T[]67 ): readonly T[] => {68 const keyed = tags.map((tag) => ({33 unmodified lines102 };103 104 const decodeTag = Schema.decodeUnknownOption(TagName);105 127-/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */106+/** Only `refs/tags/*` is read: none of the platform's own refs and no branch but main ever shows. */107 export const refsView = (108 project: CodeProject109 ): Effect.Effect<RefsView, never, RepoHost> =>110 Effect.gen(function* () {26 unmodified linesmodified:packages/project/src/code/revision.ts+4 added-15 removed
1 /**2- * A revision as a reader names it, resolved to the commit it means in the3- * project's canonical repo (ADR 0019): absent or `main` is main's landed4- * commit, from the project's record and never from a ref; 40 hex digits are5- * that commit, if the repo holds it; anything else is a tag's exact name,6- * found among the repo's tags and never joined into a ref path, so7- * `../heads/x` or a ref of the platform's own names nothing.2+ * `main` resolves from the project's record, never a ref; a tag name is3+ * matched among the repo's tags, never joined into a ref path, so4+ * `../heads/x` names nothing.5 */6 import { RepoHost } from "@repo/artifacts/repo-host";7 import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";8 import type { Rev } from "@repo/protocol/domain/code";4 unmodified lines13 14 import type { CodeProject } from "../code.ts";15 import { CodeCache } from "./cache.ts";16 20-/** A full commit id: 40 lowercase hex digits. Short ids are not resolved. */17 const FULL_SHA = /^[0-9a-f]{40}$/u;18 23-/** Whether `rev` names a commit by its full id (and so never moves). */19 export const isFullSha = (rev: string) => FULL_SHA.test(rev);20 26-/** Where every tag's name starts. */21 const TAGS = "refs/tags/";22 29-/** A ref name's tag name, when it is a tag's. */23 export const tagNameOf = (ref: string): Option.Option<string> =>24 ref.startsWith(TAGS) ? Option.some(ref.slice(TAGS.length)) : Option.none();25 33-/**34- * The commit `sha` in `repo`, kept once found. A miss is not kept: the35- * commit may yet be pushed.36- */26+/** A miss is not kept: the commit may yet be pushed. */27 export const commitAt = (28 repo: RepoName,29 sha: CommitSha30 ): Effect.Effect<Option.Option<Commit>, RepoNotFound, RepoHost> =>12 unmodified lines43 Effect.catchTag("NoSuchElementError", () => Effect.succeedNone)44 );45 });46 57-/** The commit `at` names in the project's canonical repo. */47 export const resolveRev = (48 project: CodeProject,49 at: Option.Option<Rev>50 ): Effect.Effect<CommitSha, UnknownRevision, RepoHost> => {38 unmodified linesmodified:packages/project/src/code/tree.ts+3 added-42 removed
1-/**2- * Folders of a commit: a tree's entries by its id (kept once read), the3- * entry at a path, walked one segment at a time, and one folder as a4- * reader lists it: folders first, then by name, each entry by its kind,5- * with its README by GitLab's precedence, any case.6- */1 import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2 import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";3 import type { CodeEntry, Rev, TreeListing } from "@repo/protocol/domain/code";4 import { BlobSha, RepoPath } from "@repo/protocol/ids";5 unmodified lines10 import type { CodeProject } from "../code.ts";11 import { CodeCache } from "./cache.ts";12 import { commitAt, resolveRev } from "./revision.ts";13 20-/**21- * How many commits a walk over history (a path's log, why each line is22- * there) has under way at once, in one ordered pass with no batch to wait23- * on. A live store answers each read in tens to hundreds of milliseconds,24- * and a path four folders deep chains five reads per commit, so one at a25- * time a 200-commit walk took a minute on dev-oscabriel and sixteen at26- * once in batches still 14-28 s. Forty-eight at once, at a few27- * hundred milliseconds each, stays under the store's 2,000 requests per28- * 10 s per repo for one viewer.29- */14+/** Live store reads take 0.1-0.5 s and chain per path segment; 48 at once keeps a walk fast and under the store's 2,000 requests per 10 s per repo. */15 export const READS_AT_ONCE = 48;16 32-/** The entries of the tree `id`; a tree a commit or a tree names is always there. */17 export const entriesOf = (18 repo: RepoName,19 id: string20 ): Effect.Effect<readonly TreeEntry[], RepoNotFound, RepoHost> =>12 unmodified lines33 )34 );35 });36 53-/** The segments of `path`; none when one is empty, `.` or `..`. */37 export const segmentsOf = (path: string): Option.Option<readonly string[]> => {38 const segments = path.split("/");39 40 return segments.every(2 unmodified lines43 ? Option.some(segments)44 : Option.none();45 };46 64-/** The entry at `path` under the tree `root`, walked one segment at a time. */47 export const entryAt = (48 repo: RepoName,49 root: string,50 path: string22 unmodified lines73 return found;74 }),75 });76 95-/** What a reader sees an entry as: a gitlink is a submodule, mode 120000 a symlink. */77 export const kindOf = (entry: TreeEntry): CodeEntry["type"] =>78 Match.value(entry).pipe(79 Match.when({ type: "tree" }, () => "tree" as const),80 Match.when({ type: "commit" }, () => "submodule" as const),81 Match.when({ mode: "120000" }, () => "symlink" as const),82 Match.orElse(() => "blob" as const)83 );84 104-/** Folders first, then by name. */85 const byKindThenName = Order.combine(86 Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),87 Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)88 );89 110-/** GitLab's README precedence, lowercased. */90 const README = [91 "readme.md",92 "readme.markdown",93 "readme.mdown",1 unmodified line95 "readme.txt",96 "readme.rst",97 ];98 120-/**121- * Where a symlink in `folder` points, as a path from the repo's root: its122- * target read against the folder, `.` and `..` resolved. None when the123- * target is absolute or climbs out of the repo.124- */99+/** None when the target is absolute or climbs out of the repo. */100 const linkTargetOf = (101 folder: string,102 target: string103 ): Option.Option<string> => {15 unmodified lines119 120 return Option.liftPredicate(resolved.join("/"), (path) => path !== "");121 };122 148-/** The longest path a symlink's target may be: git's own `PATH_MAX`. */123 const LINK_TARGET_MAX = 4096;124 151-/** A symlink's target text, kept by its blob id; none when it is too long to be a path. */125 const linkTextOf = (repo: RepoName, link: string) =>126 Effect.gen(function* () {127 const cache = yield* CodeCache;128 10 unmodified lines139 )140 );141 });142 170-/**171- * The file the symlink blob `link` in `folder` names, if it is a file in172- * the repo: one link followed, never a chain (a link's entry is a blob too,173- * so its kind is asked, not its type).174- */143+/** One link followed, never a chain; a link's entry is a blob too, so its kind is asked, not its type. */144 const linkedFile = (145 repo: RepoName,146 root: Effect.Effect<string, never, RepoHost>,147 folder: string,22 unmodified lines170 : Option.none()171 );172 });173 205-/**206- * The folder's README by GitLab's precedence, any case: a file, or a207- * symlink to a file elsewhere in the repo (axum's root README.md links to208- * its crate's), read where it points, so its relative links resolve there.209- * A link out of the repo, to nothing or to a folder is no README.210- */174 const readmeOf = (175 repo: RepoName,176 root: Effect.Effect<string, never, RepoHost>,177 folder: string,24 unmodified lines202 203 return Option.none();204 });205 243-/** The tree `path` names at `commit`, or `UnknownPath`. */206 export const folderAt = (207 repo: RepoName,208 commit: CommitSha,209 path: Option.Option<RepoPath>20 unmodified lines230 RepoNotFound: Effect.die,231 })232 );233 272-/** One folder at `at`, folders first, with its README. */234 export const listing = (235 project: CodeProject,236 at: Option.Option<Rev>,237 path: Option.Option<RepoPath>49 unmodified linesmodified:packages/project/src/code/why.ts+3 added-92 removed
1-/**2- * Why each line of a file is there (ADR 0019): a first-parent blame from3- * a revision, kept by immutable ids (`history.ts`): the path's blob at the4- * commit, the ranges, the commits they name and where the walk stopped,5- * under `<repo>/why/v<WHY_VERSION>/<commit>/<scan>/<sha256(path)>`. Each6- * view reads the commits it names (kept by id) and asks the project's7- * record for their landings in one batch, so an imported commit never8- * reads as a landing and a later landing shows at once.9- *10- * Kept nowhere yet, the why is computed from the nearest first-parent11- * ancestor within `INCREMENT_REACH` commits that has one: each line is12- * carried forward through the file's versions between them (a line diff13- * per change), and a line a version inserted goes to the commit that made14- * it. Otherwise the walk takes at most `WHY_SCAN` first-parent commits from15- * the log, looks up the path's blob in each (`READS_AT_ONCE` under way, in16- * order, with no batch to wait on, until the file's first commit), then17- * reads the changed versions newest first only until every line has its18- * commit (`@repo/git/blame`). Lines older than the walk reached point at19- * the commit it stopped at, named `stoppedAt`. A binary file, or one past20- * 1 MiB, has no ranges.21- */1 import { inRepoSession, ObjectId, RepoHost } from "@repo/artifacts/repo-host";2 import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";3 import {4 blameFrom,27 unmodified lines32 import { commitViews, pageOf } from "./log.ts";33 import { commitAt, resolveRev } from "./revision.ts";34 import { entryAt, READS_AT_ONCE } from "./tree.ts";35 57-/** The most first-parent commits one view walks. */36 export const WHY_SCAN = 200;37 60-/** A version of the file: its blob, and the oldest commit that holds it. */38 interface Version {39 readonly blob: BlobSha;40 readonly commit: Commit;41 }42 66-/** The file's versions newest first, and whether the walk stopped short of its first commit. */43 interface Versions {44 readonly versions: readonly Version[];45 readonly stopped: boolean;46 }47 72-/** The file's blob at `path` in `commit`, if a file is there. */48 const blobAt = (repo: RepoName, commit: Commit, path: RepoPath) =>49 Effect.map(50 entryAt(repo, commit.tree, path),51 Option.flatMap((entry) =>2 unmodified lines54 : Option.none()55 )56 );57 83-/**84- * The file's blob in each of `commits` (first parents, newest first), by85- * `blobOf`, up to the first commit without the file. One pass with86- * `READS_AT_ONCE` lookups under way and no barrier: a slow lookup holds up87- * only itself, not the ones after it. Once a commit without the file is88- * found, lookups further back are skipped.89- */58 const lookups = <E, R>(59 commits: readonly Commit[],60 blobOf: (commit: Commit) => Effect.Effect<Option.Option<BlobSha>, E, R>61 ) =>62 Effect.gen(function* () {95- // Where the file was found missing: no lookup past it is needed.63 const missingAt = yield* Ref.make(commits.length);64 65 const found = yield* Effect.forEach(66 commits,19 unmodified lines86 87 return missing === -1 ? looked : looked.slice(0, missing + 1);88 });89 123-/**124- * The file's versions newest first, from `newest` and the blobs `found` in125- * the commits before it, and whether the walk stopped short of the file's126- * first commit.127- */90 const versionsOf = (91 newest: Version,92 found: readonly {93 readonly blob: Option.Option<BlobSha>;25 unmodified lines119 versions,120 };121 };122 161-/**162- * An older version's text as the blame reads it, empty for a binary or too163- * large one. Read past the cache: old versions are seldom viewed, and164- * keeping them would push out the reads a reader comes back to.165- */123+// Read past the cache: old versions are seldom viewed, and keeping them would124+// push out the reads a reader comes back to.125 const textOf = (repo: RepoName, blob: BlobSha) =>126 unlessTooLarge(127 RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(128 Effect.map(Option.flatMap((bytes) => contentsOfBytes(bytes).text))129 ),130 Option.none131 ).pipe(Effect.map(Option.getOrElse(() => "")));132 174-/** The landings among `shas`, asked for in batches the record answers. */133 const landingsOf = (project: CodeProject, shas: readonly CommitSha[]) =>134 Effect.map(135 Effect.forEach(Array.chunksOf(shas, MAX_LANDINGS), project.landings),136 Array.flatten137 );138 181-/** Each line's commit, from ranges of consecutive lines numbered from 1. */139 const ownersOf = (ranges: readonly WhyRange[]): readonly CommitSha[] =>140 ranges.flatMap(({ end, sha, start }) =>141 Array.makeBy(end - start + 1, () => sha)142 );143 187-/** Each line's commit as ranges of consecutive lines, numbered from 1. */144 const rangesOf = (owners: readonly CommitSha[]): readonly WhyRange[] => {145 const ranges: WhyRange[] = [];146 147 for (const [index, sha] of owners.entries()) {9 unmodified lines157 158 return ranges;159 };160 205-/**206- * Each line of `after`'s commit, carried forward from `before`'s: a line207- * the diff keeps keeps its commit, and a line `after` inserted goes to208- * `sha`, the commit that made `after`.209- */161 const carried = (162 before: { readonly text: string; readonly owners: readonly CommitSha[] },163 after: string,164 sha: CommitSha11 unmodified lines176 177 return owners;178 };179 229-/** The why kept at `log[at]`'s nearest ancestor within reach, and how far back. */180 const nearestKept = (181 repo: RepoName,182 path: RepoPath,183 log: readonly Commit[],14 unmodified lines198 Option.map(kept, (value) => ({ back: at + 1, kept: value }))199 )200 );201 252-/**253- * The why at `log[0]`, whose blob is `newest`, carried forward from `kept`254- * at `log[back]` through the blobs `between` them; none when the file is255- * missing in a commit between (its history starts again there, so the256- * whole walk answers).257- */202 const forward = (203 repo: RepoName,204 log: readonly Commit[],205 newest: BlobSha,6 unmodified lines212 }213 214 const blobs = [newest, ...between.map(Option.getOrThrow)];215 272- // Each version the commits made, oldest first: where a commit's blob273- // differs from its parent's.216 const changes = blobs217 .flatMap((blob, at) => {218 const parent = blobs[at + 1] ?? from.kept.blob;219 const commit = log[at];57 unmodified lines277 }),278 });279 });280 339-/**340- * The why at `head` from its file's text and the blobs `found` in the341- * commits before it: the newest version is the file as read, and the342- * older ones are read in order by `readText`, `READS_AT_ONCE` under way,343- * only until every line has its commit.344- */281 const blamed = <R>(282 head: Commit,283 newest: BlobSha,284 text: string,42 unmodified lines327 ? { ...none, ranges, shas, stoppedAt: last.commit.sha }328 : { ...none, ranges, shas };329 });330 395-/**396- * The why at `log[0]` by reading the file whole at each commit397- * (`file-walk.ts`): one call a commit, and every version's text kept from398- * those reads, so the blame reads nothing more.399- */331 const walkedByFile = (332 repo: RepoName,333 path: RepoPath,334 log: readonly Commit[],6 unmodified lines341 if (Option.isNone(text)) {342 return { blob: newest.blob, ranges: [], shas: [] };343 }344 414- // Each version's bytes, by its blob id: the commits that share one415- // share its text.345 const texts = new Map<string, Uint8Array>([[newest.blob, newest.bytes]]);346 347 const found = yield* lookups(log.slice(1), (commit) =>348 versionAt(repo, commit.sha, path).pipe(19 unmodified lines368 );369 });370 });371 443-/**444- * The why at `log[0]` by the whole walk: by reading the file whole at each445- * commit when it is small enough at the head, else by its folders. The446- * head's blob and text are read beside the other commits' lookups, so447- * nothing waits on the head's folders before the pass starts.448- */372 const walked = (373 repo: RepoName,374 at: CommitSha,375 path: RepoPath,41 unmodified lines417 (blob) => textOf(repo, blob)418 );419 });420 498-/** The why at `at`, computed: from a kept ancestor's when one is in reach. */421 const computed = (422 repo: RepoName,423 at: CommitSha,424 path: RepoPath,35 unmodified lines460 461 return yield* walked(repo, at, path, log, head);462 });463 542-/**543- * The view of `kept`: each commit it names as a reader sees it, and their544- * landings. The commits come from the walk's page of the log (kept by the545- * isolate once the walk read it, else one read), not one read each: a546- * why names up to dozens of them. One the page lacks is read on its own.547- */464 const viewOf = (465 project: CodeProject,466 at: CommitSha,467 path: RepoPath,45 unmodified lines513 }),514 };515 });516 601-/** Why each line of `path` at `at` is there, walking at most `scan` commits. */517 export const whyView = (518 project: CodeProject,519 at: Option.Option<Rev>,520 path: RepoPath,10 unmodified lines531 asOneView(computed(repo, commit, path, scan))532 );533 534 return yield* viewOf(project, commit, path, kept, scan);620- }).pipe(621- // The walk and the commits it names: one session, one handle.622- inRepoSession,623- Effect.catchTag("RepoNotFound", Effect.die)624- );535+ }).pipe(inRepoSession, Effect.catchTag("RepoNotFound", Effect.die));modified:packages/project/src/code-store/binding.ts+1 added-14 removed
1-/**2- * The code store over an R2 bucket (the platform's `CODE_CACHE`). R2 is3- * strongly consistent, so a value one isolate puts, every other reads next.4- * A get or a put that fails is logged and read as a miss: a store outage5- * slows a read, and never fails it.6- */1 import { Data, Effect, Layer, Option } from "effect";2 3 import { CodeStore, fittingKey } from "../code-store.ts";4 import type { CodeStoreApi } from "../code-store.ts";5 12-/**13- * The slice of `R2Bucket` the store calls. Structural, so the package needs14- * no Workers types; `apps/platform/test/bindings.test.ts` holds the15- * generated `Env["CODE_CACHE"]` to it.16- */6+/** Structural, so the package needs no Workers types. */7 export interface BucketLike {8 readonly get: (9 key: string10 ) => Promise<{ readonly text: () => Promise<string> } | null>;2 unmodified lines13 value: string14 ) => Promise<{ readonly key: string } | null>;15 }16 27-/** R2 refused or never answered one call on one key. */17 class CodeStoreUnreachable extends Data.TaggedError("CodeStoreUnreachable")<{18 readonly cause: unknown;19 }> {}20 32-/** One call on the bucket. */21 const reach = <A>(run: () => Promise<A>) =>22 Effect.tryPromise({23 catch: (cause) => new CodeStoreUnreachable({ cause }),24 try: run,25 });26 39-/** The store over `bucket`. */27 export const CodeStoreR2 = (bucket: BucketLike) => {28 const store: CodeStoreApi = {29 get: (key) =>30 Effect.flatMap(fittingKey(key), (fit) =>27 unmodified linesmodified:packages/project/src/code-store/memory.ts-6 removed
1-/**2- * The code store in memory, for tests: a map per layer, and a count of3- * every get and put, so a test can say a read was served from the store.4- */1 import { Context, Effect, Layer, Option, Ref } from "effect";2 3 import { CodeStore, fittingKey } from "../code-store.ts";4 import type { CodeStoreApi } from "../code-store.ts";5 10-/** How often the memory store was asked, for tests. */6 export class CodeStoreCounts extends Context.Service<7 CodeStoreCounts,8 {9 readonly counts: Effect.Effect<{2 unmodified lines12 }>;13 }14 >()("project/CodeStoreCounts") {}15 21-/** A fresh store in memory, with its counts. */16 export const CodeStoreMemory = Layer.effectContext(17 Effect.gen(function* () {18 const kept = yield* Ref.make<ReadonlyMap<string, string>>(new Map());19 const counts = yield* Ref.make({ gets: 0, puts: 0 });30 unmodified linesmodified:packages/project/src/front-page/memory.ts-7 removed
1-/**2- * `FrontPage` in memory, seeded from data: what tests read the front page,3- * the project list and credits from. It filters as the D14- * adapter does and never changes.5- */1 import type {2 FrontPageEntry,3 ProjectListing,4 } from "@repo/protocol/domain/front-page";4 unmodified lines9 10 import { FrontPage } from "../front-page.ts";11 import type { FrontPageFilter } from "../front-page.ts";12 18-/** What the memory front page reads back. */13 export interface FrontPageSeed {14 readonly projects: readonly ProjectListing[];15 readonly entries: readonly FrontPageEntry[];22- /** Each credit, with the person it credits. */16 readonly credits: readonly {17 readonly handle: Handle;18 readonly credit: CreditSummary;19 }[];25 unmodified linesmodified:packages/project/src/lander/isogit.ts+2 added-86 removed
1-/**2- * The `Lander` over isomorphic-git in a Worker: the production3- * fallback until the container Lander in `apps/sandbox` passes, and the one4- * the core-loop tests run on. It runs no project code and installs nothing.5- *6- * It is stateless. Each call reads the commits, trees and blobs it needs7- * through `RepoHost` (never `fetch`), writes the objects it makes into a8- * scratch git directory in memory, and pushes from there: canonical `main`9- * with a non-force compare-and-swap, then the mirror ref and the verdict10- * note, each in its own push, since Artifacts has no atomic multi-ref push.11- * A scratch directory holds only the objects the repo lacks; the12- * rest are referenced by id.13- *14- * The merge is three-way at the tree level, read through the port: it15- * descends only into folders both sides changed, and a file both sides16- * changed is merged line by line by isomorphic-git's `merge` over a scratch17- * history of that one file.18- *19- * `bundleRules` returns the config folder's sources as committed. This20- * adapter bundles no TypeScript; the container Lander bundles with Bun.21- */1 import {2 BranchName,3 ObjectId,4 RefName,52 unmodified lines57 const SNIFF = 8000;58 59 const blocked = () => new VerifierBlocked({});60 82-/** A store that lost a repo cannot merge or land: `VerifierBlocked`. */61 const unlessLost = <A, R>(62 effect: Effect.Effect<A, RepoNotFound, R>63 ): Effect.Effect<A, VerifierBlocked, R> => Effect.mapError(effect, blocked);64 87-/** An object the store should hold and does not: `VerifierBlocked` too. */65 const found = <A, R>(66 read: Effect.Effect<Option.Option<A>, RepoNotFound, R>67 ): Effect.Effect<A, VerifierBlocked, R> =>68 read.pipe(17 unmodified lines86 87 const refsIn = (repo: RepoName) =>88 RepoHost.use((host) => host.refs(repo)).pipe(unlessLost);89 113-/** One ref's compare-and-swap, alone in its push; what it came to. */90 const pushOne = (repo: RepoName, source: PushSource, update: RefUpdate) =>91 RepoHost.use((host) => host.push(repo, source, [update])).pipe(92 Effect.map((outcomes) => Option.fromNullishOr(outcomes[0]))93 );94 119-/** A push whose ref did not move, for a ref where that is not a refusal. */95 const moves = (outcome: Option.Option<RefOutcome>) =>96 Option.exists(outcome, RefOutcome.$is("Updated"))97 ? Effect.void98 : Effect.fail(blocked());99 125-/** Clock time, in the whole seconds a git signature holds. */100 const seconds = Effect.map(Clock.currentTimeMillis, (millis) =>101 Math.floor(millis / 1000)102 );103 104 const git = <A>(run: () => Promise<A>) =>105 Effect.tryPromise(run).pipe(Effect.orDie);106 133-/** A git signature at `at` seconds past the epoch, in UTC. */107 const signed = (who: GitIdentity, at: number) => ({108 email: who.email,109 name: who.name,110 timestamp: at,3 unmodified lines114 /** A copy of an object must keep its id, or the push would name one it lacks. */115 const kept = (id: ObjectId, made: ObjectId) =>116 made === id ? Effect.void : Effect.die(`copying ${id} produced ${made}`);117 145-/**146- * A bare git directory in memory: what a call writes its new objects into147- * and pushes from. One per call; nothing outlives it.148- */118 const scratch = Effect.gen(function* () {119 const source: PushSource = { fs: memoryFs(), gitdir: "/lander.git" };120 121 yield* git(() => init({ ...source, bare: true, defaultBranch: "main" }));42 unmodified lines164 ),165 (oid) => CommitSha.make(oid)166 );167 199- /** A commit of one file holding `bytes` (or of nothing) on `parents`. */168 const fileCommit = (169 bytes: Option.Option<Uint8Array>,170 parents: readonly CommitSha[]171 ) =>14 unmodified lines186 tree: yield* tree(files),187 });188 });189 222- /**223- * One file's three versions merged line by line, by isomorphic-git's224- * `merge` over a history of that file alone: the merged blob, or `None`225- * when the changes conflict.226- */190 const lines = (191 base: Option.Option<Uint8Array>,192 ours: Uint8Array,193 theirs: Uint8Array58 unmodified lines252 253 const isFile = (entry: TreeEntry | undefined) =>254 entry?.mode === "100644" || entry?.mode === "100755";255 293-/** The folder an entry is, if it is one. */256 const folderOf = (entry: TreeEntry | undefined) =>257 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();258 259 const byName = (entries: readonly TreeEntry[]) =>4 unmodified lines264 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),265 onSome: (id) => treeIn(repo, id),266 });267 306-/** Where an answer's sides are read: main from canonical, base and head from the fork. */268 interface Sides {269 readonly canonical: RepoName;270 readonly fork: RepoName;271 }272 312-/** A merged folder's entries, or the paths under it that conflict. */273 interface MergedTree {274 readonly entries: readonly TreeEntry[];275 readonly conflicts: readonly string[];276 }7 unmodified lines284 conflicts: [path],285 entries: [],286 });287 328-/**329- * Makes `theirs`, an entry the merge takes from the head, pushable: every330- * object under it that differs from the base's entry at its path is copied331- * from the fork into the scratch directory. What equals the base is already332- * in canonical, since the base is a commit on canonical's history.333- */288 const adopt = (289 sides: Sides,290 into: Scratch,291 theirs: TreeEntry,20 unmodified lines312 yield* kept(theirs.sha, yield* into.tree(children));313 });314 };315 362-/** A file's mode once both sides changed it, unless they changed it differently. */316 const mergedMode = (317 base: TreeEntry | undefined,318 ours: TreeEntry,319 theirs: TreeEntry4 unmodified lines324 325 return base?.mode === ours.mode ? Option.some(theirs.mode) : Option.none();326 };327 375-/** A file both sides changed, merged; `None` when the changes conflict. */328 const mergeFile = (329 sides: Sides,330 into: Scratch,331 name: string,48 unmodified lines380 381 return Option.map(yield* into.lines(before, mine, yours), file);382 });383 432-/**433- * Three folders merged by name. An entry only one side changed is taken from434- * that side; a folder both changed is merged inside; a file both changed is435- * merged line by line; anything else both changed conflicts.436- */384 const mergeTrees = (385 sides: Sides,386 into: Scratch,387 prefix: string,36 unmodified lines424 ours: Option.some(o.sha),425 theirs: Option.some(t.sha),426 });427 481- // Both sides emptied it, or something in it conflicts.428 if (inner.conflicts.length > 0 || inner.entries.length === 0) {429 return { conflicts: inner.conflicts, entries: [] };430 }431 27 unmodified lines459 entries: merged.flatMap(({ entries }) => entries),460 };461 });462 517-/**518- * The answer's head merged onto `main`, with the base as the merge base:519- * the merged root (written into `into`) and the base's and head's roots, or520- * `StaleBase` with every path that conflicts.521- */463 const mergeOnto = (into: Scratch, job: MergeJob) =>464 Effect.gen(function* () {465 const [base, ours, theirs] = yield* Effect.all([466 commitIn(job.fork, job.base),30 unmodified lines497 tree: TreeSha.make(yield* into.tree(merged.entries)),498 };499 });500 560-/** A file to place, by the folders and name its path is made of. */501 interface Placed {502 readonly segments: readonly string[];503 readonly content: string;504 }505 566-/** A path's folders and file name; one that cannot name a file is a defect upstream. */506 const placed = ({ content, path }: ComposedFile) => {507 const segments = path.split("/");508 509 return segments.every((segment) => !["", ".", "..", ".git"].includes(segment))510 ? Effect.succeed<Placed>({ content, segments })511 : Effect.die(`${path} cannot name a file in a repo`);512 };513 575-/**576- * `files` written into `repo`'s folder `tree` (or a new folder), folder by577- * folder, keeping every other entry: the new folder's id. A file where a578- * folder stands, or a folder where a file stands, is a defect upstream.579- */514 const placeFiles = (515 repo: RepoName,516 into: Scratch,517 prefix: string,47 unmodified lines565 566 return yield* into.tree([...entries.values()]);567 });568 635-/** `main` with `files` added, written into `into`: the new root. */569 const composeOnto = (570 into: Scratch,571 repo: RepoName,572 main: CommitSha,7 unmodified lines580 yield* placeFiles(repo, into, "", Option.some(commit.tree), paths)581 );582 });583 651-/** The tree a land rebuilds, written into `into` where it is new. */584 const rebuilt = (into: Scratch, job: LandJob) =>585 Rebuild.$match(job.rebuild, {586 Compose: ({ files }) => composeOnto(into, job.repo, job.main, files),587 Existing: ({ commit }) =>13 unmodified lines601 requestIdOf(message) === requestId602 ? Effect.void603 : Effect.die(`a landing's message must carry Request-Id: ${requestId}`);604 673-/**674- * The commit an earlier land of the same request put on `main`: a child of675- * the job's `main` carrying its `Request-Id`, on main's first parents.676- */605 const landedBefore = (job: LandJob) =>606 Effect.gen(function* () {607 const history = yield* RepoHost.use((host) =>608 host.log(job.repo, Revision.Branch({ name: mainBranch }), LOOKBACK)6 unmodified lines615 616 return Option.fromNullishOr(mine?.sha);617 });618 691-/** The mirror ref moved to the landing, while the landing is still main's tip. */619 const mirror = (repo: RepoName, landing: CommitSha) =>620 Effect.gen(function* () {621 const refs = yield* refsIn(repo);622 const current = Option.fromNullishOr(refs.get(landedRef));13 unmodified lines636 })637 );638 });639 713-/** Whether the notes at `tip` already hold a note on `target`. */640 const noted = (641 repo: RepoName,642 tip: Option.Option<CommitSha>,643 target: CommitSha8 unmodified lines652 return entries.some(({ name }) => name === target);653 }),654 });655 730-/** The verdict written as the landing's note, unless it is there already. */656 const note = (repo: RepoName, landing: CommitSha, verdict: Verdict) =>657 Effect.gen(function* () {658 const refs = yield* refsIn(repo);659 const parent = Option.fromNullishOr(refs.get(notesRef));14 unmodified lines674 yield* pushOne(repo, source, { from: parent, ref: notesRef, to: commit })675 );676 });677 753-/** One piece of bookkeeping: `None` once written, its name when it was not. */678 const attempt = <E>(679 item: Bookkeeping,680 write: Effect.Effect<void, E, RepoHost>681 ) =>6 unmodified lines688 )689 )690 );691 768-/**769- * What follows a landing on `main`, in order and each in its own push: the770- * mirror ref, then the verdict note. Neither fails the landing; what was not771- * written comes back pending, and landing the same job again writes it.772- */692+// Mirror ref then verdict note, each in its own push. Neither fails the landing;693+// what was not written comes back pending, and landing the job again writes it.694 const settle = (job: LandJob, landing: CommitSha) =>695 Effect.gen(function* () {696 const mirrored = yield* attempt("mirror", mirror(job.repo, landing));697 7 unmodified lines705 sha: LandedSha.make(landing),706 };707 });708 788-/** The base a stale land names: the answer's own, or the main it was built on. */709 const baseOf = (job: LandJob) =>710 Rebuild.$match(job.rebuild, {711 Compose: () => job.main,712 Existing: () => job.main,713 Merge: ({ base }) => base,714 });715 796-/** A land that found `main` at `tip`: the earlier land of the same request, or stale. */716 const moved = (job: LandJob, tip: Option.Option<CommitSha>) =>717 Effect.gen(function* () {718 const earlier = yield* landedBefore(job);719 96 unmodified lines816 817 return { commit, tree };818 });819 901-/** Every file under the folder `tree`, by repo path, as committed. */820 const filesUnder = (821 repo: RepoName,822 tree: ObjectId,823 prefix: string21 unmodified lines845 846 return nested.flat();847 });848 931-/** The config folder in the root `root`, if the commit has one. */849 const configFolder = (repo: RepoName, root: ObjectId) =>850 Effect.reduce(851 Brand.configDir.split("/"),852 (): Option.Option<ObjectId> => Option.some(root),34 unmodified lines887 888 return { changes, tree };889 });890 974-/** The Lander over isomorphic-git, reading and pushing through `RepoHost`. */891 export const LanderIsogit: Layer.Layer<Lander, never, RepoHost> = Layer.effect(892 Lander,893 Effect.gen(function* () {894 const host = yield* RepoHost;10 unmodified linesmodified:packages/project/src/lander/memory.ts-13 removed
1-/**2- * `Lander` from a script, for tests: each operation returns its scripted3- * results in order, and the last one again once they run out. An operation4- * with no script is `VerifierBlocked`, as a Lander that cannot run is. It5- * records every job it is given, in order, for the test to read back.6- */1 import type { RepoBusy, StaleBase } from "@repo/protocol/refusal";2 import { VerifierBlocked } from "@repo/protocol/refusal";3 import type { ConfigBundle } from "@repo/rules/rules-evaluator";4 import { Array, Data, Effect, Layer } from "effect";9 unmodified lines14 MergeJob,15 Merged,16 } from "../lander.ts";17 24-/** One call the scripted Lander answered, with the job it was given. */18 export type LanderJob = Data.TaggedEnum<{19 Merge: { readonly job: MergeJob };20 Land: { readonly job: LandJob };21 Compose: { readonly job: ComposeJob };1 unmodified line23 }>;24 25 export const LanderJob = Data.taggedEnum<LanderJob>();26 34-/** Each operation's results, in the order its calls get them. */27 export interface LanderScript {28 readonly merge?: readonly Result.Result<29 Merged,30 StaleBase | VerifierBlocked5 unmodified lines36 readonly compose?: readonly Result.Result<Composed, VerifierBlocked>[];37 readonly bundle?: readonly Result.Result<ConfigBundle, VerifierBlocked>[];38 }39 48-/** A scripted Lander, and the jobs it has been given so far. */40 export type ScriptedLander = Layer.Layer<Lander> & {41 readonly jobs: Effect.Effect<readonly LanderJob[]>;42 };43 44 export const LanderMemory = {54- /**55- * One scripted Lander: every build of the layer shares its script's place56- * and its record of jobs, so a test reads `jobs` after providing it.57- */45 layer: (script: LanderScript): ScriptedLander => {46 const jobs: LanderJob[] = [];47 const served = new Map<keyof LanderScript, number>();48 32 unmodified linesmodified:packages/project/src/lander/wire.ts+1 added-27 removed
1-/**2- * What crosses the service binding between the platform and the sandbox3- * Worker for each `Lander` job (`merge`, `land`, `compose`, `bundleRules`):4- * the job as the port takes it, the remotes the platform mints tokens for,5- * and the job's outcome on the way back. Both sides decode with these6- * schemas (principle 2): the platform encodes jobs and decodes outcomes;7- * the sandbox's Lander does the reverse.8- *9- * Each job schema decodes to the port's own argument type (`satisfies`10- * below), so the wire and the port cannot drift apart.11- */1 import { Remote } from "@repo/checks/check-runner/wire";2 import { Verdict } from "@repo/protocol/domain/answer";3 import {4 CommitSha,22 unmodified lines27 export { Remote } from "@repo/checks/check-runner/wire";28 29 export { ConfigBundle } from "@repo/rules/rules-evaluator";30 42-/** One file a decider adds at its path. */31 export const ComposedFile = Schema.Struct({32 content: Schema.String,33 path: RepoPath,34 });10 unmodified lines45 changes: Schema.Array(Change),46 tree: TreeSha,47 }) satisfies Schema.Codec<MergedResult, unknown, unknown, unknown>;48 61-/** How a stateless Lander rebuilds the tree it lands (the port's `Rebuild`). */49 export const Rebuild = Schema.TaggedUnion({50 Compose: { files: Schema.NonEmptyArray(ComposedFile) },51 Existing: { commit: CommitSha },52 Merge: { base: CommitSha, fork: RepoName, head: CommitSha },30 unmodified lines83 at: LandedSha,84 repo: RepoName,85 }) satisfies Schema.Codec<BundleJobArgs, unknown, unknown, unknown>;86 100-/**101- * A merge: a read token on canonical, and a write token on the answer's102- * fork, where the merged commit waits for the Checker.103- */87 export const MergeWire = Schema.Struct({88 fork: Remote,89 job: MergeJob,90 main: Remote,91 });92 110-/**111- * A land: a write token on canonical, which goes only to the trusted Lander,112- * never to a Checker or outside the platform's Workers; a read113- * token on the fork when the rebuild is a merge.114- */93+/** The write token on canonical goes only to the trusted Lander, never to a Checker. */94 export const LandWire = Schema.Struct({95 fork: Schema.optionalKey(Remote),96 job: LandJob,97 main: Remote,1 unmodified line99 100 /** A compose: a write token on canonical, used only for a compose ref, never `main`. */101 export const ComposeWire = Schema.Struct({ job: ComposeJob, main: Remote });102 124-/** A bundle of the config folder: a read token on canonical. */103 export const BundleWire = Schema.Struct({ job: BundleJob, main: Remote });104 127-/** A merge's outcome as it comes back: the merged tree, a refusal, or a defect, as JSON. */105 export const MergeExit = Schema.toCodecJson(106 Schema.Exit(107 Merged,108 Schema.Union([StaleBase, VerifierBlocked]),109 Schema.Defect()110 )111 );112 136-/** A land's outcome as it comes back, as JSON. */113 export const LandExit = Schema.toCodecJson(114 Schema.Exit(115 Landed,116 Schema.Union([StaleBase, RepoBusy, VerifierBlocked]),117 Schema.Defect()118 )119 );120 145-/** A compose's outcome as it comes back, as JSON. */121 export const ComposeExit = Schema.toCodecJson(122 Schema.Exit(Composed, VerifierBlocked, Schema.Defect())123 );124 150-/** A bundle's outcome as it comes back, as JSON. */125 export const BundleExit = Schema.toCodecJson(126 Schema.Exit(ConfigBundle, VerifierBlocked, Schema.Defect())127 );modified:packages/project/src/project-store/memory.ts-18 removed
19 unmodified lines20 writeAll,21 } from "./tables.ts";22 import type { Column, Table, Upsert } from "./tables.ts";23 24-/** A row as a table keeps it: its columns and its encoded body. */24 interface Stored {25 readonly body: string;26 readonly columns: Readonly<Record<string, Column>>;27 }28 30-/** A table's rows by key, in the order each key was first written. */29 type Rows = ReadonlyMap<string, Stored>;30 31 interface State {34- /** The number of the newest layer read, or 0 before the first. */32 readonly lastRead: number;33 readonly lastSeq: number;37- /** Each table's rows by table name; the kept events too, oldest first. */34 readonly tables: ReadonlyMap<string, Rows>;35 }36 37 const keyOf = <A>(table: Table<A>, columns: Stored["columns"]) =>7 unmodified lines45 46 const all = <A>(state: State, table: Table<A>) =>47 decodeAll(table, rowsIn(state, table).values());48 53-/** A landing with the place it was first written in. */49 type Placed = readonly [index: number, row: Stored];50 56-/** Newest first: by landing time, then the later write, as `/sqlite` orders them. */51 const newestFirst = Order.combine(52 Order.mapInput(Order.flip(Order.Number), ([, row]: Placed) =>53 Number(row.columns.landed_at)54 ),55 Order.mapInput(Order.flip(Order.Number), ([index]: Placed) => index)56 );57 64-/** Ledger entries in order, as `/sqlite` reads them. */58 const bySeq = Order.mapInput(Order.Number, (entry: LedgerRow) => entry.seq);59 60 const snapshotOf = (state: State) =>61 Effect.gen(function* () {29 unmodified lines91 ratchets: yield* all(state, Tables.ratchets),92 } satisfies ProjectSnapshot;93 });94 102-/** The push events in `writes` that `state` already holds, each once. */95 const seenIn = (state: State, writes: ProjectWrites) => {96 const seen = rowsIn(state, Tables.pushEvents);97 98 return Array.dedupe(23 unmodified lines122 123 tables.set(table.name, kept);124 });125 134-/**135- * The state after `writes`, built from copies through the write plan both136- * adapters share. A row that won't encode dies before anything is swapped in.137- */126 const written = (state: State, writes: ProjectWrites) =>127 Effect.gen(function* () {128 const tables = new Map(state.tables);129 17 unmodified lines147 148 return [committed, next] as const;149 });150 163-/**164- * A project's store in memory: the same tables, keys and encoded bodies as165- * `/sqlite`, held in one `SynchronizedRef` the layer makes. A commit builds166- * the next state from copies and swaps it in only when every row encoded, so167- * a failed commit leaves the previous state whole.168- */151 export const ProjectStoreMemory = Layer.effect(152 ProjectStore,153 Effect.gen(function* () {154 const ref = yield* SynchronizedRef.make<State>({73 unmodified linesmodified:packages/project/src/project-store/migrations.ts+1 added-14 removed
1 import { Effect } from "effect";2 import * as Migrator from "effect/sql/Migrator";3 import { SqlClient } from "effect/sql/SqlClient";4 5-// A project's tables. Each holds its key columns and `body`, the row's6-// encoded JSON (see `tables.ts`). A migration is never edited once it has7-// run anywhere: a change is a new numbered entry.5+// A migration is never edited once it has run anywhere: a change is a new numbered entry.6 7 const projectState = Effect.gen(function* () {8 const sql = yield* SqlClient;9 46 unmodified lines56 )`;57 yield* sql`CREATE TABLE outbox (id TEXT PRIMARY KEY, body TEXT NOT NULL)`;58 });59 62-// The visibility tables: a project's layers, the attempts on its63-// held-back checks, its public ledger, its write-only values, and the read64-// log of its layer repos. Without the visibility cartridge they stay empty.60 const visibility = Effect.gen(function* () {61 const sql = yield* SqlClient;62 63 yield* sql`CREATE TABLE layers (name TEXT PRIMARY KEY, body TEXT NOT NULL)`;17 unmodified lines81 body TEXT NOT NULL82 )`;83 });84 90-/** Every migration, by `<id>_<name>`, in the order they run. */85 const migrations = {86 "1_project_state": projectState,87 "2_visibility": visibility,88 };89 96-/**97- * Brings a project's database up to date and returns the migrations it ran.98- * It records each one it runs (in `migrations`), so running it again runs99- * nothing. It needs no filesystem, so it runs in a Durable Object. A100- * migration that fails is a defect: the project cannot start without its101- * tables.102- */90 export const migrate: Effect.Effect<91 readonly (readonly [id: number, name: string])[],92 never,93 SqlClient4 unmodified linesmodified:packages/project/src/project-store/rows.ts+8 added-75 removed
20 unmodified lines21 SuiteRoot,22 } from "@repo/protocol/ids";23 import { Schema } from "effect";24 25-// One schema per table. Each row's encoded side is what the store holds as26-// the row's body, so a row reads back exactly as it was written. Lifecycle27-// states travel as encoded JSON: the store never decodes them, the project28-// service does, with the lifecycles' own schemas.25+// Lifecycle states travel as encoded JSON: the store never decodes them.26 30-/**31- * A project: whether it waits for its initializer's first push or is live,32- * the SHA the platform last landed, the policy cached for one landed SHA,33- * and where it was imported from, when it was.34- */27 export const ProjectRow = Schema.Struct({28 createdAt: Schema.DateTimeUtcFromString,37- /** The public repo it was imported from; absent for a project that started empty. */29 importedFrom: Schema.optionalKey(ImportSource),30 initializer: Handle,31 landed: Schema.optionalKey(LandedSha),41- /** The encoded `Policy` evaluated at `policyAt`. */32 policy: Schema.optionalKey(Schema.Json),33 policyAt: Schema.optionalKey(LandedSha),34 project: ProjectName,35 state: Schema.Literals(["awaitingFirstPush", "live"]),36 });37 38 export type ProjectRow = typeof ProjectRow.Type;39 50-/** An ask, as the domain types it. */40 export const AskRow = Ask;41 42 export type AskRow = typeof AskRow.Type;43 55-/**56- * The held-back suite a claim was pinned to when it opened: the root of57- * the sealed suite and the layer commit that holds it. An answer on the58- * claim is judged by this suite, whatever the layer holds later.59- */44+/** An answer on the claim is judged by this suite, whatever the layer holds later. */45 export const PinnedSuite = Schema.Struct({46 at: CommitSha,47 suite: SuiteRoot,48 });49 50 export type PinnedSuite = typeof PinnedSuite.Type;51 67-/**68- * One person's claim on an ask, its lifecycle state encoded, and the agents69- * the claimant's pushes to its fork named (their harnesses, as custody heard70- * them), once each in the order they first pushed: what the answer's landing71- * discloses as `Assisted-by:`. Audit metadata, never credit.72- */52+/** `agents` is audit metadata (`Assisted-by:`), never credit. */53 export const ClaimRow = Schema.Struct({54 ask: AskId,55 assisted: Schema.optionalKey(Schema.Array(AgentTrailer)),56 claimant: Handle,77- /** The held-back suite pinned when the claim opened; absent when none was sealed. */57 pinned: Schema.optionalKey(PinnedSuite),79- /** The encoded claim lifecycle state. */58 state: Schema.Json,59 updatedAt: Schema.DateTimeUtcFromString,60 });61 62 export type ClaimRow = typeof ClaimRow.Type;63 86-/**87- * One answer request, keyed by its `requestId` so a request sent twice is88- * one row; where it stands, encoded.89- */64+/** Keyed by `requestId`, so a request sent twice is one row. */65 export const AnswerRow = Schema.Struct({66 answerer: Handle,67 ask: Schema.optionalKey(AskId),68 head: CommitSha,69 requestId: RequestId,95- /**96- * The service's `AnswerRecord` (`src/project.ts`), encoded: the landing97- * lifecycle's state, the receipt the request was first given, and the98- * verdict on its last checked tree. The store keeps it as one JSON value.99- */70 state: Schema.Json,71 updatedAt: Schema.DateTimeUtcFromString,72 });73 74 export type AnswerRow = typeof AnswerRow.Type;75 106-/** A landing, as the domain types it. */76 export const LandingRow = LandingView;77 78 export type LandingRow = typeof LandingRow.Type;79 111-/** A proposal, as the domain types it. */80 export const ProposalRow = Proposal;81 82 export type ProposalRow = typeof ProposalRow.Type;83 116-/** A decision, as the domain types it. */84 export const DecisionRow = Decision;85 86 export type DecisionRow = typeof DecisionRow.Type;87 121-/** How much of one decider's budget one day used, and how many finishes. */88 export const BudgetDayRow = Schema.Struct({123- /** `YYYY-MM-DD`, in UTC. */89 day: Schema.String,90 decider: Handle,91 finishes: Schema.Int,92 used: Schema.Int,93 });94 95 export type BudgetDayRow = typeof BudgetDayRow.Type;96 132-/** A ratchet's count in one territory, as recorded at a landing. */97 export const RatchetRow = Schema.Struct({98 at: LandedSha,99 count: Schema.Int,100 ratchet: RatchetName,1 unmodified line102 });103 104 export type RatchetRow = typeof RatchetRow.Type;105 142-/**143- * A push the project heard about, kept by its event id so the same event144- * heard twice is acted on once (events arrive per ref, and may repeat).145- */106+/** Keyed by event id: events arrive per ref and may repeat. */107 export const PushEventRow = Schema.Struct({108 after: Schema.optionalKey(CommitSha),109 at: Schema.DateTimeUtcFromString,110 before: Schema.optionalKey(CommitSha),3 unmodified lines114 });115 116 export type PushEventRow = typeof PushEventRow.Type;117 157-/**158- * A side effect still to run after its transition was persisted (a fork, a159- * projection row), kept until it is acknowledged.160- */118 export const OutboxRow = Schema.Struct({119 attempts: Schema.Int,120 body: Schema.Json,121 id: Schema.NonEmptyString,2 unmodified lines124 });125 126 export type OutboxRow = typeof OutboxRow.Type;127 171-// The visibility tables. The store keeps them for the visibility ports172-// (`visibility-port.ts`, `env-port.ts`); the service reads none of them173-// itself, and without the cartridge they stay empty.174-175-/**176- * A layer the project declared: its repo in the private namespace, the177- * layer commit it last admitted with that suite's root and when, a pushed178- * head still waiting on admission, and where the suite's salt is kept. The179- * salt never leaves the project's store: no ledger entry, trailer, note or180- * event carries it.181- */128+/** The salt never leaves the project's store: no ledger entry, trailer, note or event carries it. */129 export const LayerRow = Schema.Struct({130 admittedAt: Schema.optionalKey(Schema.DateTimeUtcFromString),131 landedSha: Schema.optionalKey(CommitSha),132 name: LayerName,186- /** A head pushed to the layer that admission has not let in yet. */133 proposed: Schema.optionalKey(CommitSha),134 repo: RepoName,135 saltRef: Schema.optionalKey(Schema.NonEmptyString),136 suiteRoot: Schema.optionalKey(SuiteRoot),137 });138 139 export type LayerRow = typeof LayerRow.Type;140 195-/**196- * How many held-back runs one claimant's answers to one ask failed in one197- * area in one ISO week (`2026-W41`): the per-claim and the per-person,198- * per-area, per-week caps count these. Never a record of the person.199- */141+/** Never a record of the person. */142 export const AttemptRow = Schema.Struct({143 area: AreaName,144 ask: AskId,145 claimant: Handle,2 unmodified lines148 });149 150 export type AttemptRow = typeof AttemptRow.Type;151 210-/** One entry of the public ledger, numbered by whoever appends it, in order. */152 export const LedgerRow = LedgerEntry;153 154 export type LedgerRow = typeof LedgerRow.Type;155 215-/**216- * A write-only value for one `@sensitive` env item: sealed by the vault217- * (the store never reads into it), and who set it, when. Nothing returns218- * the value.219- */156+/** Sealed by the vault; nothing returns the value. */157 export const EnvValueRow = Schema.Struct({158 key: EnvKey,159 sealed: Schema.Json,160 setAt: Schema.DateTimeUtcFromString,1 unmodified line162 });163 164 export type EnvValueRow = typeof EnvValueRow.Type;165 229-/** A read of a layer repo through the gateway, before the store numbers it. */166 export const LayerRead = Schema.Struct({167 at: Schema.DateTimeUtcFromString,168 handle: Handle,169 layer: LayerName,234- /** The layer commit the read was served at, when the gateway knew it. */170 sha: Schema.optionalKey(CommitSha),171 });172 173 export type LayerRead = typeof LayerRead.Type;174 240-/** A layer read with the number the store gave it: the read log, for the layer's readers. */175 export const LayerReadRow = Schema.Struct({176 ...LayerRead.fields,177 seq: Schema.Int,178 });179 180 export type LayerReadRow = typeof LayerReadRow.Type;181 248-/** An event with the sequence number the store gave it. */182 export const EventRow = Schema.Struct({183 event: ProjectEvent,184 seq: Schema.Int,185 });2 unmodified linesmodified:packages/project/src/project-store/sqlite.ts+4 added-9 removed
17 unmodified lines18 writeAll,19 } from "./tables.ts";20 import type { Table } from "./tables.ts";21 22-// What SQLite hands back is decoded like any other outside input.22 const Bodies = Schema.Array(Schema.Struct({ body: Schema.String }));23 24 const decodeBodies = Schema.decodeUnknownEffect(Bodies);25 4 unmodified lines30 const LastSeq = Schema.Tuple([Schema.Struct({ last: Schema.Int })]);31 32 const decodeLastSeq = Schema.decodeUnknownEffect(LastSeq);33 35-/** The rows a query returns, each decoded from its body. */34 const bodiesOf = <A>(table: Table<A>, statement: Statement<object>) =>35 statement.pipe(36 Effect.flatMap(decodeBodies),37 Effect.flatMap((rows) =>1 unmodified line39 )40 );41 42 /**45- * A project's store on SQLite through `effect/sql`, so the same code runs on46- * a Durable Object's SQLite (`@effect/sql-sqlite-do`, given the storage so47- * transactions work) and on sqlite-node in tests. The layer runs the48- * migrations first. `load` and `commit` each run in one transaction; a49- * `SqlError` is a defect (see `ProjectStore`).43+ * The DO's SQLite needs the storage for transactions. `load` and `commit` each44+ * run in one transaction; a `SqlError` is a defect.45 */46 export const ProjectStoreSqlite = Layer.effect(47 ProjectStore,48 Effect.gen(function* () {14 unmodified lines63 Effect.flatMap(decodeLastSeq),64 Effect.map(([row]) => row.last)65 );66 72- // One statement per row, so a key written twice in one commit replaces73- // its first row in place, as it does in `/memory`.67+ // One statement per row, so a key written twice in one commit replaces its68+ // first row, as in `/memory`.69 const upsert = <A>(table: Table<A>, rows: readonly A[]) =>70 Effect.forEach(71 rows,72 (row) =>121 unmodified linesmodified:packages/project/src/project-store/tables.ts-24 removed
19 unmodified lines20 PushEventRow,21 RatchetRow,22 } from "./rows.ts";23 24-// How each kind of row is kept, shared by every adapter: the table it lives25-// in, the columns a row is found by, its body (the row's encoded JSON), and26-// which tables a commit writes from which `ProjectWrites` field. The SQLite27-// tables themselves are created by `migrations.ts`.28-29-/** A column's value: text, or an integer. */24 export type Column = string | number;25 32-/** One table's rows: how a row becomes its key columns and body, and back. */26 export interface Table<A> {34- /** Every column besides `body`, by name, for one row. */27 readonly columns: (row: A) => Readonly<Record<string, Column>>;28 readonly decode: (body: string) => Effect.Effect<A>;29 readonly encode: (row: A) => Effect.Effect<string>;38- /** The columns that make a row's key: writing a row again under it replaces it. */30 readonly key: readonly string[];31 readonly name: string;32 }33 17 unmodified lines51 name,52 };53 };54 64-/** The tables that hold many rows, by the `ProjectWrites` field that carries them. */55 export const Tables = {56 answers: tableOf("answers", AnswerRow, ["request_id"], (row) => ({57 request_id: row.requestId,58 })),48 unmodified lines107 (row) => ({ ratchet: row.ratchet, territory: row.territory })108 ),109 } as const;110 121-/** A table with one row at most: the project, and the landing queue. */111 const single = { id: 1 } as const;112 124-/** The project's own row. */113 export const ProjectTable = tableOf(114 "project",115 ProjectRow,116 ["id"],117 () => single118 );119 132-/** The encoded landing queue, one row. */120 export const QueueTable = tableOf(121 "landing_queue",122 Schema.Json,123 ["id"],124 () => single125 );126 140-/** The project's events, each body carrying the `seq` it was given. */127 export const EventTable = tableOf("events", ProjectEvent, ["seq"], (event) => ({128 seq: event.seq,129 }));130 145-/** The layer read log, each body carrying the `seq` it was given. */131 export const LayerReadTable = tableOf(132 "layer_reads",133 LayerReadRow,134 ["seq"],135 (read) => ({ at: DateTime.toEpochMillis(read.at), seq: read.seq })136 );137 153-/** How an adapter writes one table's rows, each replacing any row under its key. */138 export type Upsert<E, R> = <A>(139 table: Table<A>,140 rows: readonly A[]141 ) => Effect.Effect<void, E, R>;142 159-/** The newest numbers a store gave: its last event's, and its last layer read's. */143 export interface LastNumbers {144 readonly read: number;145 readonly seq: number;146 }147 165-/**166- * Writes every row in `writes` through an adapter's `upsert`, table by167- * table, with the events numbered on from `last.seq` and the layer reads168- * from `last.read`, and returns the numbers it gave the events. Both169- * adapters commit through it, so a table `ProjectWrites` gains is written by170- * both or by neither.171- */148 export const writeAll = <E, R>(149 writes: ProjectWrites,150 last: LastNumbers,151 upsert: Upsert<E, R>36 unmodified linesmodified:packages/project/src/projection/memory.ts+1 added-9 removed
1-/**2- * `Projection` in memory, for tests and the platform's local composition: it3- * keeps every event it was given once per `(project, event.seq)`, as the port4- * asks, in the order it first took them, and reads them back. Not once per5- * row id: every project's outbox names its rows `projected:<seq>`, so two6- * projects' rows share ids (the dev world once dropped burrow's events that way).7- */1+// Keyed by (project, seq), not row id: every project's outbox names its rows `projected:<seq>`, so ids collide across projects.2 import { Context, Effect, Layer, Ref, Schema } from "effect";3 4 import { Projection, ProjectedEvent } from "../projection.ts";5 6 const decodeProjected = Schema.decodeUnknownEffect(ProjectedEvent);7 14-/** What the memory projection has taken so far. */8 export class ProjectedRows extends Context.Service<9 ProjectedRows,10 { readonly events: Effect.Effect<readonly ProjectedEvent[]> }11 >()("project/ProjectedRows") {}12 20-/** A fresh, empty projection each time the layer is built, and its reading. */13 export const ProjectionMemory: Layer.Layer<Projection | ProjectedRows> =14 Layer.effectContext(15 Effect.gen(function* () {16 const taken = yield* Ref.make<ReadonlyMap<string, ProjectedEvent>>(29 unmodified linesmodified:packages/project/src/projection-d1/front-page.ts+1 added-19 removed
1-/**2- * `FrontPage` over D1: the open asks of every project, the project list and3- * a person's credits, each in one query, read from the rows `ProjectionD1`4- * keeps (`tables.ts`), so no project wakes.5- *6- * An entry is what the anonymous viewer sees: an ask is takeable when no7- * live claim holds it, nothing it waits on is still open, and it is held for8- * nobody. Its `blockedBy` names only the asks it still waits on: one that9- * landed has left the front page. Newest asks come first, each with its10- * project's posture. Projects are listed by name, and a person's credits by11- * project, area and role: counts by role and area, never a score or a total12- * across roles. A failed read is a defect: the port's reads cannot fail.13- */1 import { Reserve } from "@repo/protocol/domain/ask";2 import type {3 FrontPageEntry,4 ProjectListing,10 unmodified lines15 import { handleKey } from "./tables.ts";16 17 const AskIds = Schema.fromJsonString(Schema.Array(AskId));18 32-/** One row of the front page query. */19 const EntryRow = Schema.Struct({20 ask: AskId,21 blocked_by: AskIds,22 claimed: Schema.Int,23 kind: KindName,38- /** The asks it waits on that are still on the front page. */24 open_blockers: AskIds,25 posture: Posture,26 project: ProjectKey,27 reserve: Schema.NullOr(Reserve),4 unmodified lines32 type EntryRow = typeof EntryRow.Type;33 34 const decodeRows = Schema.decodeUnknownEffect(Schema.Array(EntryRow));35 51-/** One row of the projects query. */36 const ProjectRow = Schema.Struct({37 landed_at: Schema.NullOr(Schema.DateTimeUtcFromString),38 open_asks: Schema.Int,39 posture: Posture,3 unmodified lines43 type ProjectRow = typeof ProjectRow.Type;44 45 const decodeProjectRows = Schema.decodeUnknownEffect(Schema.Array(ProjectRow));46 63-// Each row keeps the project's key (ADR 0032); a row whose key no project64-// can have (a throwaway torn down before owners) is left out of every list.47+// A row whose key no project can have is left out of every list.48 const CreditRow = Schema.Struct({49 ...CreditSummary.fields,50 project: ProjectKey,51 });77 unmodified lines129 Effect.map((rows) => Arr.getSomes(rows.map(listingOf))),130 Effect.orDie131 );132 150- // By the key the projection keeps: the handle as `sameHandle` compares it.133 const credits = (handle: Handle) =>134 sql`SELECT project, area, role, count135 FROM credits136 WHERE handle_key = ${handleKey(handle)}9 unmodified linesmodified:packages/project/src/projection-d1/postures.ts+5 added-21 removed
1-/**2- * `StandingPostures` over D1, beside the projection: one row per project in3- * `standing_postures` (`tables.ts`, migration 0005), each the posture a4- * list last read from the project's own record, when it moves by the clock5- * alone, and the project's last event the read saw.6- *7- * The projection deletes a project's row in the same write as an event8- * that can move its posture (`projection.ts`). A read that event came9- * after could still be written once the event is applied, so a row is10- * written only while the project's `cursor` stands at or before the event11- * the read saw, and never over a row from a later read.12- *13- * The lists of projects and of rows each go in as one JSON parameter14- * (`json_each`), so a list of any length is one statement under D1's limit15- * on bound parameters. Every failure, a database the migration has not16- * reached among them, is a miss: logged, and never the list's.17- */1+// The projection deletes a project's row with any event that can move its2+// posture, so a row is written only while the project's `cursor` stands at or3+// before the event the read saw, and never over a row from a later read.4+// Lists go in as one JSON parameter (`json_each`) to stay under D1's limit on5+// bound parameters. Every failure is a miss, never the list's.6 import { keyOf, nameOfKey, ProjectKey } from "@repo/protocol/ids";7 import type { ProjectName } from "@repo/protocol/ids";8 import { Posture } from "@repo/protocol/posture";9 import {13 unmodified lines23 StandingEntry,24 StandingPosturesApi,25 } from "../standing-posture.ts";26 39-/** A row as `standing_postures` holds it. */27 const Row = Schema.Struct({28 moves_at: Schema.NullOr(Schema.DateTimeUtcFromString),29 posture: Posture,30 project: ProjectKey,1 unmodified line32 });33 34 const decodeRow = Schema.decodeUnknownOption(Row);35 49-/** An entry as the row it is written as, one element of the JSON parameter. */36 const rowOf = (project: ProjectName, entry: StandingEntry) => ({37 moves_at: entry.until === undefined ? null : DateTime.formatIso(entry.until),38 posture: entry.posture,39 project: keyOf(project),40 seen: entry.seen,41 });42 57-/** A row read back as an entry; `moves_at` only when it is set. */43 const entryOf = ({44 moves_at: movesAt,45 posture,46 seen,47 }: typeof Row.Type): StandingEntry =>48 movesAt === null ? { posture, seen } : { posture, seen, until: movesAt };49 65-/** `statement`'s rows, or `missed` and a warning when it fails. */50 const orMissed = <A>(51 statement: Effect.Effect<A, SqlError>,52 missed: A,53 warning: string74 unmodified linesmodified:packages/project/src/projection-d1/projection.ts+4 added-80 removed
1-/**2- * `Projection` over D1: each project's outbox rows become the front page's3- * rows, the project list's and every person's credits (`tables.ts`). The4- * Project DO stays the system of record; this is a read model it feeds5- * through its outbox, and nothing else writes it.6- *7- * - A project is listed from its first event on (no event says a project8- * was made), `open` until a `PostureChanged` ledger entry moves it: the9- * fallback for a list, which reads each project's standing posture from10- * its own ledger (`withStandingPosture`), since a first config, a11- * widening and a narrowing taking effect by the clock write no such12- * entry. Its open asks are counted again from the front page whenever an13- * ask opens or closes, and a landing stamps when it last landed.14- * - A landing credits each person it names once per role, in its ask's15- * area: the module of the ask's territory, read from the ask's front16- * page row, which is still there when its `Landed` applies (its17- * `AskClosed` comes after). A landing with no ask, or whose ask the front18- * page never held, credits no area. `Assisted-by` is never credit.19- *20- * Events apply in their project's order, once each. Every statement is21- * guarded by the project's cursor: it runs only if the cursor stands just22- * before its event, and the event's last statement moves the cursor on. So a23- * row seen again, or an older row after a newer one, changes nothing, and24- * two deliveries racing each other apply each event once. A row past a gap25- * (its project's cursor short of the event before it) is not applied, and26- * `apply` fails with `ProjectionFailed` once the rest is in: the outbox keeps27- * those rows and sends them again after the missing one.28- *29- * - A list keeps each project's standing posture beside these tables30- * (`postures.ts`, migration 0005). An event that can move a project's31- * posture deletes its kept row in the same write: a `Landed` (a config32- * lands, a narrowing opens its decision), a `Decided` (an accepted33- * narrowing starts to stand, now or once its notice runs out) and a34- * `LedgerAppended` (a `PostureChanged` row; any other entry too, which35- * costs one read). The table is looked for once per isolate until it is36- * found, so a database the migration has not reached yet projects as37- * before.38- *39- * One call is one atomic write: a D1 batch when the `SqlClient` is D1's40- * (D1 has no interactive transactions), and a transaction anywhere else,41- * such as sqlite-node in tests. The client itself says which it is, so the42- * layer needs nothing but the `SqlClient`. A failed write applies nothing.43- */1 import { TypeId } from "@effect/sql-d1/D1Client";2 import type { D1Client } from "@effect/sql-d1/D1Client";3 import { ProjectEvent } from "@repo/protocol/domain/event";4 import type { LandingView } from "@repo/protocol/domain/landing";27 unmodified lines32 );33 34 const decodeCursors = Schema.decodeUnknownEffect(Cursors);35 79-/**80- * Whether the client is D1's: every client `@effect/sql-d1` makes carries81- * its `TypeId`, and only its `batch` writes several statements atomically82- * there (its `withTransaction` dies).83- */36+// D1 has no interactive transactions (`withTransaction` dies): only its `batch` is atomic.37 const isD1 = (client: SqlClient): client is D1Client => TypeId in client;38 39 const bySeq = Order.mapInput(40 Order.Tuple([Order.String, Order.Number]),41 ({ event, project }: ProjectedEvent) => [project, event.seq] as const42 );43 91-/** Each project, with the last event the rows carry for it. */44 const lastOf = (events: readonly ProjectedEvent[]) =>45 new Map(events.map(({ event, project }) => [project, event.seq]));46 95-/**96- * Each person a landing credits, once per role, by the key `sameHandle`97- * compares handles by (`handleKey`): the rule of98- * `creditsByArea` (`attention/credits.ts`) for one landing, whose99- * area the projection reads from D1. Only `credits` counts: `assisted` (the100- * `Assisted-by` trailers) names agents, never people.101- */47 const creditedOn = (landing: Pick<LandingView, "credits">) =>48 Array.dedupeWith(49 landing.credits.map(({ handle, role }) => ({50 person: handleKey(handle),7 unmodified lines58 Projection,59 Effect.gen(function* () {60 const sql = yield* SqlClient;61 117- /** The statements in order, all or none. */62 const atomically = (63 statements: readonly Statement<object>[]64 ): Effect.Effect<readonly (readonly object[])[], SqlError> =>65 isD1(sql)1 unmodified line67 : sql.withTransaction(Effect.all(statements));68 69 const posturesFound = yield* Ref.make(false);70 127- /**128- * Whether the kept postures' table is there (migration 0005): looked129- * for until it is found, and never again after.130- */71+ // Looked for until found, so a database the migration has not reached projects as before.72 const keepsPostures = Effect.gen(function* () {73 if (yield* Ref.get(posturesFound)) {74 return true;75 }5 unmodified lines81 82 return tables.length > 0;83 });84 144- /** Whether the project's cursor stands just before event `seq`. */85 const isNext = (project: ProjectName, seq: number) =>86 sql`(SELECT COALESCE(MAX(seq), 0) FROM cursor WHERE project = ${keyOf(project)}) = ${seq - 1}`;87 148- /**149- * What one event changes in the read model, if anything: the project's150- * row first, so every event lists its project.151- */88 const writes = (89 { event, project }: ProjectedEvent,90 postures: boolean91 ) => {92 const next = isNext(project, event.seq);93 158- // Every row keeps the project's key, never its name (ADR 0032).94+ // Every row keeps the project's key, never its name.95 const key = keyOf(project);96 161- /** The project's kept posture, cleared: this event may move it. */97 const unkept = postures98 ? [99 sql`DELETE FROM standing_postures100 WHERE project = ${key} AND ${next}`,11 unmodified lines112 const claims = (ask: AskId, change: number) =>113 sql`UPDATE front_page SET claimed = MAX(claimed + ${change}, 0)114 WHERE project = ${key} AND ask = ${ask} AND ${next}`;115 181- /**182- * One more landing for each person `landing` credits, in each role,183- * in its ask's area. A landing that names a project other than the184- * one whose outbox carried it credits nothing: ask ids are unique185- * only within a project (`areaOf` in `attention/record.ts` checks186- * the same).187- */116+ // Ask ids are unique only within a project: a landing naming another project credits nothing.117 const credited = ({ ask, ...landing }: LandingView) =>118 ask === undefined || landing.project !== project119 ? []120 : creditedOn(landing).map(54 unmodified lines175 176 return [listed, ...changes];177 };178 250- /** Moves the project's cursor on to `seq`, if it stands just before it. */179 const advance = (project: ProjectName, seq: number) =>180 sql`INSERT INTO cursor (project, seq)181 SELECT ${keyOf(project)}, ${seq} WHERE ${isNext(project, seq)}182 ON CONFLICT (project) DO UPDATE SET seq = excluded.seq`;183 184 const cursorsOf = (projects: readonly ProjectName[]) =>185 sql`SELECT project, seq FROM cursor WHERE ${sql.in("project", projects.map(keyOf))}`;186 259- /**260- * Applies the events in one write, then reads where each project's261- * cursor stands: short of a project's last event means a gap.262- */187 const deliver = (events: Array.NonEmptyReadonlyArray<ProjectedEvent>) =>188 Effect.gen(function* () {189 const last = lastOf(events);190 65 unmodified linesmodified:packages/project/src/projection-d1/tables.ts+4 added-59 removed
1-/**2- * The front page's tables in D1, as the platform's first D1 migration3- * (`apps/platform/migrations/0001_front_page.sql`) creates them. The file4- * holds exactly this text, and the projection's test applies the file and5- * checks that it does, so the DDL has one source.6- *7- * - `front_page`: one row per open ask of every project. `claimed` counts8- * the live claims on the ask (a race ask may hold several); `blocked_by`9- * is the ask's blockers as a JSON array of ask ids; `opened_at` is when10- * its `AskOpened` happened. A landed ask's row is deleted.11- * - `cursor`: the last event applied per project. Events apply in their12- * project's order, once each, so a replayed or late row changes nothing.13- *14- * A migration is never edited once it has run anywhere: the project list adds15- * its tables in `0004_projects_credits.sql` (`ProjectsCreditsDdl`), and the16- * kept standing postures theirs in `0005_standing_postures.sql`17- * (`StandingPosturesDdl`).18- */1 import type { Handle } from "@repo/protocol/ids";2 21-/**22- * The key `credits.handle_key` holds a person by: the handle lowercased,23- * the rule protocol's `sameHandle` compares by. The projection writes it and24- * the credits query reads by it, so both take it from here.25- */3+/** The projection writes and the credits query reads by this key, as `sameHandle` compares. */4 export const handleKey = (handle: Handle): string => handle.toLowerCase();5 6+/** Must equal `apps/platform/migrations/0001_front_page.sql`; the projection's test checks it. */7 export const FrontPageDdl = `-- The front page: every open ask of every project, projected from each8 -- project's outbox by packages/project/src/projection-d1 (its tables.ts9 -- holds this text). The projection is the only writer.10 18 unmodified lines29 seq INTEGER NOT NULL30 );31 `;32 54-/**55- * The project list's and the credits' tables in D1, as the platform's56- * fourth D1 migration (`apps/platform/migrations/0004_projects_credits.sql`)57- * creates them, beside the front page's. The file holds exactly this text,58- * and the projection's credits test applies the file and checks that it59- * does.60- *61- * - `projects`: one row per project the projection has heard from: its62- * posture (`open` until a `PostureChanged` ledger entry; the fallback a63- * list keeps when it cannot read the project's own ledger, which it reads64- * for the posture standing now: `withStandingPosture`), its open asks65- * (counted from `front_page` whenever an ask opens or closes), and when66- * it last landed (null before its first landing).67- * - `credits`: how many landings credit a person (by `handle_key`, the68- * handle lowercased: `handleKey`) in one role, in one area of one project.69- *70- * Its last statement lists the projects `cursor` already knows of, with71- * their open asks, so a database the front page's migration made keeps its72- * project list (an earlier stopgap read it from `cursor`). Their credits and73- * last landings come back only with a rebuild: clear the four tables and74- * replay each project's events from seq 1.75- */33+/** Must equal `apps/platform/migrations/0004_projects_credits.sql`; the credits test checks it. */34 export const ProjectsCreditsDdl = `-- The project list and every person's credits, projected from each35 -- project's outbox by packages/project/src/projection-d1 beside the front36 -- page (its tables.ts holds this text). The projection is the only writer.37 29 unmodified lines67 NULL68 FROM cursor;69 `;70 113-/**114- * The kept standing postures' table in D1, as the platform's fifth D1115- * migration (`apps/platform/migrations/0005_standing_postures.sql`) creates116- * it. The file holds exactly this text, and the postures' test applies the117- * file and checks that it does.118- *119- * - `standing_postures`: one row per project a list has read the posture120- * of (`withStandingPosture`): the posture, when it moves by the clock121- * alone (`moves_at`, ISO 8601; null when only an event moves it), and122- * the project's last event the read saw (`seen`). The projection deletes123- * a project's row with any event that can move its posture; a list124- * writes one only while `cursor` stands at or before `seen`125- * (`postures.ts`).126- */71+/** Must equal `apps/platform/migrations/0005_standing_postures.sql`; the postures' test checks it. */72 export const StandingPosturesDdl = `-- Each listed project's standing posture, as a list last read it from the73 -- project's own record, kept by packages/project/src/projection-d1 (its74 -- tables.ts holds this text). A cache: a row lost costs one read. The75 -- projection deletes a project's row in the same write as any event that13 unmodified linesmodified:packages/project/src/projects/memory.ts-7 removed
1-/**2- * `Projects` in memory: each project is one service over its own3- * `ProjectStoreMemory`, built when the project is made and kept in a `Ref`4- * the layer makes (never in a module-level variable). Every project shares5- * the other ports the layer is given.6- */1 import type { ProjectName } from "@repo/protocol/ids";2 import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";3 import { Context, Effect, Layer, Option, SynchronizedRef } from "effect";4 16 unmodified lines21 const made = yield* SynchronizedRef.make<22 ReadonlyMap<ProjectName, ProjectApi>23 >(new Map());24 31- /** A new project's service, over a store of its own that lives as long as the layer. */25 const build = (project: ProjectName) =>26 Effect.gen(function* () {27 // Fresh, or the build would reuse a store an enclosing layer made.28 const store = yield* Layer.buildWithScope(28 unmodified linesmodified:packages/project/src/standing-posture/memory.ts-5 removed
1-/**2- * The kept standing postures in memory, for tests: a map per layer, kept3- * whole, with no projection beside it to clear an entry.4- */1 import type { ProjectName } from "@repo/protocol/ids";2 import { Effect, Layer, Ref } from "effect";3 4 import { StandingPostures } from "../standing-posture.ts";1 unmodified line6 StandingEntry,7 StandingPosturesApi,8 } from "../standing-posture.ts";9 14-/** A fresh, empty store each time the layer is built. */10 export const StandingPosturesMemory = Layer.effect(11 StandingPostures,12 Effect.gen(function* () {13 const kept = yield* Ref.make<ReadonlyMap<ProjectName, StandingEntry>>(23 unmodified linesmodified:packages/project/src/visibility/admission.ts-74 removed
1-/**2- * Admission of held-back checks, pure (after3- * poteto's "prove each new check fails on a real past mistake"). A push to4- * the layer that holds a project's held-back checks is a proposal: the5- * suite it would make enters the layer's landed SHA only once each area it6- * changes is admitted.7- *8- * - Every check in the suite cites the clause of an ask or a public doc it9- * enforces; one that cites none is `UnstatedRequirement{area}` (for the10- * deciders only, never the public; the platform logs it until Today can11- * show it), before any run is planned.12- * - Each changed area's checks run on main as many times as the policy13- * asks (3 by default), and must pass every time: one red run refuses the14- * area as flaky or broken.15- * - The checks the push adds or rewrites in the area run again on each16- * known-bad tree the layer's manifest names (main with the known-bad17- * commit's files laid over it), and must fail on at least as many as the18- * policy asks: catching nothing refuses the area. Only those run there,19- * so a new check that catches nothing cannot ride on an older one's20- * catch.21- *22- * An area the push adds or rewrites no check in (its checks unchanged, or23- * only removed) is not run again. The public learns only `Admitted{area,24- * suite, mainRuns, knownBadCaught}`: counts and a root, never a check, a25- * path or a clause.26- */1 import { commandFor } from "@repo/checks/kinds";2 import { CheckSpec } from "@repo/protocol/domain/check";3 import type { RunBlock } from "@repo/protocol/domain/run";4 import {20 unmodified lines25 AdmissionReport,26 HeldBackJob,27 } from "../visibility-port.ts";28 55-/**56- * A held-back check as a pushed manifest lists it: like `SealedCheck`, but57- * its clause may be missing, so admission can refuse it by name to the58- * deciders (`UnstatedRequirement`) rather than read the manifest as none.59- */29 export const PushedCheck = Schema.Struct({30 ...SealedCheck.fields,31 clause: Schema.optionalKey(SealedCheck.fields.clause),32 });33 34 export type PushedCheck = typeof PushedCheck.Type;35 67-/** A layer's manifest as pushed: its checks may leave out their clause. */36 export const PushedManifest = Schema.Struct({37 ...LayerManifest.fields,38 checks: Schema.Array(PushedCheck),39 });40 41 export type PushedManifest = typeof PushedManifest.Type;42 75-/** One file a layer commit holds: its blob id and its bytes. */43 export interface LayerFile {44 readonly blob: BlobSha;45 readonly content: Uint8Array;46 }47 81-/** One file a known-bad commit lays over main for its run. */48 export interface OverlayFile {49 readonly content: Uint8Array;50 readonly path: RepoPath;51 }52 87-/** What a layer push's admission is planned from. */53 export interface AdmissionInput {89- /** The files the pushed head holds, by path (at least its manifest's checks). */54 readonly files: ReadonlyMap<string, LayerFile>;55 readonly head: CommitSha;92- /** Each known-bad commit the layer holds, by id: the files it lays over main. */56 readonly knownBad: ReadonlyMap<string, readonly OverlayFile[]>;94- /** Each file's blob at the layer's landed head, by path; empty before its first landing. */57 readonly landed: ReadonlyMap<string, BlobSha>;96- /** The public main the runs check out. */58 readonly main: LandedSha;98- /** The pushed head's manifest. */59 readonly manifest: PushedManifest;60 readonly policy: SealedChecks;101- /** The landed head's manifest, if the layer landed one. */61 readonly previous: Option.Option<PushedManifest>;103- /** The project's run block: each check runs as its `test`, with `{path}` filled. */62 readonly run: RunBlock;105- /** The root the runs carry (the Checker reports it back). */63 readonly suite: SuiteRoot;64 }65 109-/** An area admission refused, and the run counts the deciders see why by. */66 export interface AdmissionRefused {67 readonly area: AreaName;112- /** How many known-bad trees it ran on, and how many it turned red. */68 readonly knownBad: number;69 readonly knownBadCaught: number;115- /** How many times it ran on main, and how many of those it passed. */70 readonly mainPassed: number;71 readonly mainRuns: number;118- /** Red on main at least once (a flaky or broken check), or red on too few known-bad trees. */72 readonly reason: "flaky" | "catchesNothing";73 }74 122-/** The ledger entry an admitted area earns. */75 export type Admitted = Extract<LedgerEntry, { readonly _tag: "Admitted" }>;76 125-/**126- * What an admission's runs came to: the areas admitted, as ledger entries127- * (numbered from 0: the project numbers them as it appends), and the areas128- * refused, with why. An area with a run still unreported is in neither.129- */77 export interface AdmissionResult {78 readonly admitted: readonly Admitted[];79 readonly refused: readonly AdmissionRefused[];80 }81 135-/** The counts a plan carries when the policy asks for no admission (and no run is planned): the defaults. */82 const osrDefaults = { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 } as const;83 138-/** A suite's checks in order: by area, then path. */84 const byAreaThenPath = Order.combine(85 Order.mapInput(Order.String, (check: PushedCheck) => check.area),86 Order.mapInput(Order.String, (check: PushedCheck) => check.path)87 );88 144-/**145- * The suite a manifest makes at one commit: its checks in an area the146- * policy names, whose files the commit holds, by area, then path.147- */89 const suiteIn = (90 manifest: PushedManifest,91 policy: SealedChecks,92 holds: (path: string) => boolean4 unmodified lines97 ),98 byAreaThenPath99 );100 160-/** One area's checks as (path, blob), to tell which the push added or rewrote. */101 const blobsIn = (102 checks: readonly PushedCheck[],103 area: AreaName,104 blobOf: (path: string) => Option.Option<BlobSha>8 unmodified lines113 })114 )115 );116 177-/** The runs that admit a layer push's checks; `UnstatedRequirement` for a check that cites no clause. */117 export const planAdmission = (118 input: AdmissionInput119 ): Result.Result<AdmissionPlan, UnstatedRequirement> => {120 const fileOf = (path: string) =>14 unmodified lines135 onSome: (previous) =>136 suiteIn(previous, input.policy, (path) => input.landed.has(path)),137 });138 200- /**201- * Each area the push adds or rewrites a check in: all its checks, and202- * the ones whose (path, blob) the landed head does not hold.203- */139 const changed = Arr.sort(140 Object.keys(input.policy.areas).map((area) => AreaName.make(area)),141 Order.String142 ).flatMap((area) => {13 unmodified lines156 const { admit } = input.policy;157 158 const sealedPaths = new Set(suite.map(({ path }) => path));159 225- /** A job of `checks` in `area` (after `overlay`, laid over main first), each run by the run block's `test`. */160 const jobOf = (161 area: AreaName,162 checks: readonly PushedCheck[],163 overlay: readonly OverlayFile[]64 unmodified lines228 runs,229 });230 };231 298-/** A run's identity within its plan: its area, and main's attempt or the known-bad tree. */232 const runKey = (run: AdmissionRun) =>233 AdmissionRun.match(run, {234 OnKnownBad: ({ area, tree }) => `${area}\u0000bad\u0000${tree}`,235 OnMain: ({ area, attempt }) => `${area}\u0000main\u0000${attempt}`,236 });237 305-/**306- * An admission's results, judged against its plan, each reported run307- * matched to a planned one by its area and its attempt or tree. An area308- * passes a run when every check it ran passed, and a known-bad tree309- * catches it when any failed.310- */238 export const judgeAdmission = (239 plan: AdmissionPlan,240 results: AdmissionReport["results"],241 now: DateTime.Utc1 unmodified line243 const reported = new Map(244 results.map(({ areas, run }) => [runKey(run), areas] as const)245 );246 320- /** One area's verdict, once each of its runs is reported. */247 const verdictOf = (248 area: AreaName,249 runs: Arr.NonEmptyReadonlyArray<AdmissionRun>250 ): Option.Option<Result.Result<Admitted, AdmissionRefused>> =>72 unmodified linesmodified:packages/project/src/visibility/claims.ts-37 removed
1-/**2- * Attempts on held-back checks, pure: how many3- * times one claim, and one person in one area, may fail an area's sealed4- * checks in one ISO week before the platform stops judging them.5- *6- * Both caps count failures in the ISO week (UTC) a run is judged in, so7- * both reset when the next week starts: `AttemptsExhausted` is retryable8- * and says when. A failure is a count here and nothing else: it never9- * reaches the answerer's record.10- */1 import type { HeldBackResult } from "@repo/protocol/domain/answer";2 import type { SealedChecks } from "@repo/protocol/domain/visibility";3 import { AreaName, sameHandle } from "@repo/protocol/ids";4 import type { AskId, Handle, SuiteRoot } from "@repo/protocol/ids";4 unmodified lines9 import type { AttemptRow } from "../project-store/rows.ts";10 11 const DAY = 86_400_000;12 23-/** The Monday, 00:00 UTC, that starts the ISO week `at` falls in. */13 const mondayOf = (at: DateTime.Utc) =>14 DateTime.startOf(at, "week", { weekStartsOn: 1 });15 27-/** The ISO week a moment falls in, as attempts are counted by: `2026-W41`, in UTC. */16 export const isoWeek = (at: DateTime.Utc): string => {17 // The week belongs to the year its Thursday falls in.18 const thursday = DateTime.add(mondayOf(at), { days: 3 });19 const year = DateTime.getPartUtc(thursday, "year");7 unmodified lines27 28 return `${year}-W${String(week).padStart(2, "0")}`;29 };30 43-/** When the ISO week `at` falls in ends: the next Monday, 00:00 UTC. */31 export const weekEnds = (at: DateTime.Utc): DateTime.Utc =>32 DateTime.add(mondayOf(at), { days: 7 });33 47-/** Whether one more failure may be judged, and when the counts that stop it reset. */34 export interface AttemptsLeft {35 readonly ok: boolean;36 readonly resetsAt: Option.Option<DateTime.Utc>;37 }38 53-/**54- * Whether one more failure may be judged: the claim's failures in an area55- * this week are under the policy's `perClaim`, and the person's, across56- * all their claims, under `perPersonPerAreaPerWeek`. When either cap is57- * reached, the counts reset as the next ISO week starts.58- */39 export const attemptsLeft = (input: {40 readonly claimCount: number;41 readonly weekCount: number;42 readonly policy: SealedChecks["attempts"];8 unmodified lines51 resetsAt: ok ? Option.none() : Option.some(weekEnds(input.now)),52 };53 };54 75-/** A held-back run, judged: its refusals, the trailer's value when none, and the attempts it counted. */55 export interface AttemptsJudged {56 readonly attempts: readonly AttemptRow[];57 readonly refusals: readonly (AttemptsExhausted | HeldBackFailed)[];58 readonly trailer: Option.Option<string>;59 }60 82-/**83- * One held-back run of a claim's answer, judged against its attempts,84- * in each sealed area that ran in it, sorted by name:85- *86- * - an area whose attempts were already used up this week is87- * `AttemptsExhausted`, whatever the run said, and counts nothing: its88- * bits stay unread until the counts reset;89- * - an area that failed counts one attempt for the claim and for the90- * person this week, and is `HeldBackFailed` under the pinned suite, or91- * `AttemptsExhausted` when that failure used the last attempt;92- * - an area that passed counts nothing.93- *94- * With no refusal, the value of the `Held-back:` trailer (`heldBackValue`'s95- * format, areas with no check in the run as `n/a`). The rows are the attempts96- * the run counted; nothing here reaches the answerer's record.97- */61 export const judgeAttempts = (input: {62 readonly attempts: readonly AttemptRow[];63 readonly ask: AskId;64 readonly checks: SealedChecks;93 unmodified linesmodified:packages/project/src/visibility/env.ts+8 added-88 removed
1-/**2- * The visibility cartridge's env (ADR 0009), as the `ProjectEnv`3- * port:4- *5- * - The env shape: every `.env.schema` at the landed SHA (the repo's root6- * first, then each workspace package's folder), parsed through the7- * parser seam and never resolved, read once per commit, with each8- * sensitive item's who and when from the Project DO's rows. Never a value.9- * - Write-only values: only a person the policy lets set values (the10- * deciders unless `visibility.env.setters` names others) sets one, only11- * for a `@sensitive` item of the shape, sealed by the vault under the12- * platform's master key; the row and a public `ValueSet` ledger entry are13- * the call's writes, and nothing returns the value.14- * - The env a check runs with: a placeholder for every sensitive item and15- * the `@proxy` rules, so unlanded code never sees a value; a run of16- * landed code alone also carries the values, opened for that run.17- * - The scan: the other place a stored value is opened, to find it in a18- * text or a blob, and it answers with the item's key alone.19- * - After a landing: a `ProxyWidened` decision for each item whose value20- * may now reach a host it could not before.21- */1 import { RepoHost, Revision } from "@repo/artifacts/repo-host";2 import type { EnvProxy } from "@repo/checks/check-runner";3 import { Hostname } from "@repo/protocol/domain/common";4 import type { Evidence } from "@repo/protocol/domain/common";43 unmodified lines48 import type { ProjectSnapshot } from "../project-store.ts";49 import type { EnvValueRow } from "../project-store/rows.ts";50 import { noPlan, policyIn } from "../visibility-port.ts";51 73-/** The env schema's name, in the repo's root and in a package's folder. */52 const schemaName = ".env.schema";53 76-/** The root's env schema: where the shape lives when nothing else says. */54 const rootSchema = RepoPath.make(schemaName);55 79-/** A character that makes a path segment a glob. */56 const GLOB = /[*?[{]/u;57 82-/**83- * The folder a territory's glob covers: its fixed head (`packages/week/**`84- * → `packages/week`), or, for a glob naming one file, that file's folder.85- * The root is `""`.86- */58 const folderOf = (glob: string): string => {59 const segments = glob60 .split("/")61 .filter((segment) => segment !== "" && segment !== ".");4 unmodified lines66 "/"67 );68 };69 99-/**100- * Where a project's env schemas live: `.env.schema` in the repo's root,101- * then `<package folder>/.env.schema` for each workspace package the102- * policy's territories name, in order, each once.103- */70 export const schemaFilesAt = (71 modules: readonly Territory[]72 ): readonly RepoPath[] =>73 Array.dedupe([6 unmodified lines80 })81 ),82 ]).map((path) => RepoPath.make(path));83 118-/** Whether `pattern` (a host, or a glob `*.example.com`) covers `host`. */84 const covers = (pattern: string, host: string) =>85 pattern === host ||86 (pattern.startsWith("*.") && host.endsWith(pattern.slice(1)));87 123-/**124- * The hosts an item's value may reach through the platform's proxy: its125- * `@proxy` domains, lower-cased, unless the rule blocks every request. Only126- * a sensitive item holds a value, so any other reaches none.127- */88+/** Only a sensitive item holds a value, so any other reaches no host. */89 const reachOf = (item: EnvItem | undefined): readonly string[] =>90 item?.sensitive === true &&91 item.proxy !== undefined &&92 item.proxy.block !== true93 ? Array.dedupe(item.proxy.domains.map((host) => host.toLowerCase()))94 : [];95 135-/** The hosts `key`'s value may reach in `view`: none when the view has no such item. */96 const reachIn = (view: Pick<EnvSchemaView, "items">, key: EnvKey) =>97 reachOf(view.items.find((item) => item.key === key));98 139-/** A widened `@proxy`: the item, and every host its value may now reach. */99 export interface Widened {100 readonly hosts: readonly Hostname[];101 readonly item: EnvKey;102 }103 145-/**146- * Each item of `after` whose value may reach a host that no host or glob147- * of `before` covered: a new `@proxy` domain, a new proxied item, or a rule148- * that blocked every request and no longer does. A narrowing, an unchanged149- * rule and a newly blocked one widen nothing. The hosts are all the item's150- * hosts after, as hostnames.151- */104 export const widenedProxies = (105 before: Pick<EnvSchemaView, "items">,106 after: Pick<EnvSchemaView, "items">107 ): readonly Widened[] =>5 unmodified lines113 ? [{ hosts: reach.filter(Schema.is(Hostname)), item: item.key }]114 : [];115 });116 165-/** One commit's env schemas, as the cache keeps them. */117 class ReadAt extends Data.Class<{118 readonly at: LandedSha;119 readonly files: readonly RepoPath[];120 readonly project: ProjectName;121 }> {}122 172-/**173- * A commit's env shape, read once: its items without any value's who and174- * when (the DO's rows add those), and the schema that declared each item.175- */123 interface Read {124 readonly declaredIn: ReadonlyMap<EnvKey, RepoPath>;125 readonly schema: EnvSchemaFile;126 }127 181-/** A shape with no schema in it: no items. */128 const unread: Read = {129 declaredIn: new Map(),130 schema: { file: rootSchema, imports: [], items: [] },131 };132 187-/** How many commits' shapes one project keeps read. */133 const readCapacity = 16;134 190-/**191- * Several schemas as one shape: the root's items, then each package's not192- * already declared (the first schema to declare a key holds it); the file193- * is the first schema read, the imports are every schema's, and the194- * current env key is the first one named.195- */135+/** The first schema to declare a key holds it. */136 const merged = (views: readonly EnvSchemaView[]): Read => {137 const [first] = views;138 139 if (first === undefined) {26 unmodified lines166 },167 };168 };169 230-/** The project's landed SHA and its row, once something landed. */170 const landedIn = (snapshot: ProjectSnapshot) =>171 Option.flatMap(snapshot.project, (row) =>172 row.landed === undefined173 ? Option.none()174 : Option.some({ landed: row.landed, row })175 );176 238-/**239- * Whether `handle` may set write-only values: one of the setters the240- * policy's `visibility.env` names, or, when it names the deciders or the241- * project declares no visibility, a decider.242- */177 const maySet = (policy: Policy, handle: Handle) => {178 const setters = policy.visibility?.env.setters ?? "deciders";179 180 return setters === "deciders"181 ? isDecider(policy, handle)182 : setters.some((each) => sameHandle(each, handle));183 };184 251-/** An item with who set its value and when, from its row: only a sensitive item has one. */185 const withValue = (186 item: EnvItem,187 rows: ReadonlyMap<EnvKey, EnvValueRow>188 ): EnvItem => {9 unmodified lines198 const decodeSealed = Schema.decodeUnknownEffect(199 Schema.toCodecJson(SealedValue)200 );201 269-/** `text`, unless it is absent or empty: the check job's wire takes no empty method or path. */202+/** The check job's wire takes no empty method or path. */203 const nonEmpty = (text: Option.Option<string>) =>204 Option.getOrUndefined(Option.filter(text, (each) => each !== ""));205 273-/** A proxy rule as the check job carries it (`EnvProxy`): no key for a method or path the rule leaves open. */206 const onTheWire = (rule: ProxyRule): EnvProxy => {207 const method = nonEmpty(rule.method);208 const path = nonEmpty(rule.path);209 6 unmodified lines216 ...(path !== undefined && { path }),217 };218 };219 288-/** A host list as evidence shows it: `none` before an item had any. */220 const hostsText = (hosts: readonly string[]) =>221 hosts.length === 0 ? "none" : hosts.join(", ");222 292-/**293- * The `ProjectEnv` port over the parser seam, the vault and the project's294- * repos (the public namespace's): the name the port's stub exported, so the295- * cartridge's `index.ts` and the platform compose it unchanged.296- */223 export const ProjectEnvLive: Layer.Layer<224 never,225 never,226 EnvSchemaParser | WriteOnlyValues | RepoHost3 unmodified lines230 const parser = yield* EnvSchemaParser;231 const vault = yield* WriteOnlyValues;232 const host = yield* RepoHost;233 308- /** One schema at a commit, as the public sees it; none where the commit has no such file, or it cannot be read. */234 const viewOf = (key: ReadAt, file: RepoPath) =>235 host236 .readFile(237 RepoName.make(keyOf(key.project)),29 unmodified lines267 })268 )269 );270 346- // Read once per commit: a landed commit's schemas never change. A347- // failed read is not kept, so the next call reads again.271+ // A landed commit's schemas never change; a failed read is not kept.272 const reads = yield* Cache.makeWith(273 (key: ReadAt) =>274 Effect.map(275 Effect.forEach(key.files, (file) => viewOf(key, file)),5 unmodified lines281 Exit.isSuccess(exit) ? Duration.infinity : Duration.zero,282 }283 );284 361- /** The shape at `at`, from the schemas the snapshot's policy places. */285 const readAt = (at: LandedSha, snapshot: ProjectSnapshot) =>286 Option.match(snapshot.project, {287 onNone: () => Effect.succeed(unread),288 onSome: (row) =>11 unmodified lines300 })301 ),302 });303 381- /** The shape at the landed SHA; none before anything landed. */304 const landedRead = (snapshot: ProjectSnapshot) =>305 Option.match(landedIn(snapshot), {306 onNone: () => Effect.succeed(unread),307 onSome: ({ landed }) => readAt(landed, snapshot),308 });309 388- /** Every stored value, opened, to look for; dropped when the scan ends. */310+ /** Opened values to scan for; dropped when the scan ends. */311 const watched = (rows: readonly EnvValueRow[]) =>312 Effect.forEach(rows, (row) =>313 decodeSealed(row.sealed).pipe(314 Effect.orDie,53 unmodified lines368 effects: [],369 writes: { decisions: [...decisions.values()] },370 };371 }),450- // Every run sees placeholders and goes out through the proxy rules; a run451- // of landed code alone also carries the values, opened here for the call452- // that runs it (the sandbox's env gateway swaps them in on the way out).372+ // Only a run of landed code carries the values; the sandbox's env373+ // gateway swaps them in on the way out.374 runEnv: ({ landed }, snapshot) =>375 Effect.gen(function* () {376 const { schema } = yield* landedRead(snapshot);377 const sensitive = schema.items.filter((item) => item.sensitive);52 unmodified lines430 }431 432 const sealed = yield* vault.put({ acknowledgeShort, key, value });433 513- // Who set which item's value, for the platform's own logs, as the514- // public ledger says it: never the value.434+ // Never the value.435 yield* Effect.logInfo("a write-only value was set").pipe(436 Effect.annotateLogs({ by: by.handle, key })437 );438 37 unmodified linesmodified:packages/project/src/visibility/index.ts-13 removed
1-/**2- * The visibility cartridge's side of the project service: the3- * `ProjectVisibility` and `ProjectEnv` ports it provides, merged. The4- * platform plugs it in by one marked line (`apps/platform/src/ports.ts`,5- * through `apps/platform/src/visibility/live.ts`); without it the project6- * service runs on the ports' neutral defaults. Nothing outside the7- * cartridge imports this folder.8- */1 import { Layer } from "effect";2 3 import { ProjectEnvLive } from "./env.ts";4 import { ProjectVisibilityLive } from "./state.ts";12 unmodified lines17 ProjectVisibilityLive,18 SaltSource,19 } from "./state.ts";20 29-/**30- * Both ports, over the private namespace's repos, a salt source and what31- * starts admissions (the platform's `apps/platform/src/visibility/state.ts`32- * gives all three).33- */21 export const ProjectCartridgeLive = Layer.mergeAll(22 ProjectVisibilityLive,23 ProjectEnvLive24 );modified:packages/project/src/visibility/ledger.ts+3 added-57 removed
1-/**2- * The public ledger as the Project DO keeps it:3- * its rows numbered in order, each one also told to watchers and the4- * projection as `LedgerAppended`, and the posture the public is shown.5- *6- * A change to the visibility config that narrows the posture is a7- * `PostureChange` decision (the posture's ratchet): until a decider accepts it8- * and the config's notice period has run since it opened, the posture that9- * stood before stays in effect. Widening needs no decision, and a project's10- * first config stands at once: nothing was public before it existed.11- */1 import { DecisionSubject } from "@repo/protocol/domain/decision";2 import type { Decision } from "@repo/protocol/domain/decision";3 import { LedgerEntry } from "@repo/protocol/domain/visibility";4 import type {10 unmodified lines15 import type { ProjectSnapshot, ProjectWrites } from "../project-store.ts";16 import type { LayerRow, LedgerRow } from "../project-store/rows.ts";17 import { policyIn } from "../visibility-port.ts";18 30-/** Each posture in GLOSSARY.md's words: how a posture still in effect is shown. */19 const WORDS = {20 open: "Open",21 openCore: "Open core",22 openOnSchedule: "Open on schedule",23 openWithSealedEvidence: "Open with sealed evidence",24 sourceAvailable: "Source available",25 } as const satisfies Record<Posture, string>;26 39-/** The number the next ledger row takes: one past the highest kept. */27 export const nextSeq = (rows: readonly LedgerRow[]): number =>28 Math.max(0, ...rows.map(({ seq }) => seq)) + 1;29 43-/** Ledger rows as a plan writes them: the rows, and an event for each. */30 export const appended = (entries: readonly LedgerEntry[]): ProjectWrites =>31 entries.length === 032 ? {}33 : {2 unmodified lines36 ),37 ledger: entries,38 };39 54-/** The visibility config a snapshot's policy holds. */40 export const visibilityIn = (41 snapshot: ProjectSnapshot42 ): Option.Option<VisibilityPolicy> =>43 Option.flatMap(policyIn(snapshot), (policy) =>44 Option.fromUndefinedOr(policy.visibility)45 );46 62-/** The posture a config declares, and its label, read from the config alone. */47 export const declaredBy = (visibility: Option.Option<VisibilityPolicy>) =>48 postureOf({ licence: Option.none(), visibility });49 50 type PostureChange = Extract<51 DecisionSubject,52 { readonly _tag: "PostureChange" }53 >;54 71-/** A decision about a posture change, with its subject typed. */55 interface Asked {56 readonly decision: Decision;57 readonly subject: PostureChange;58 }2 unmodified lines61 DecisionSubject.guards.PostureChange(decision.subject)62 ? Option.some({ decision, subject: decision.subject })63 : Option.none();64 82-/**83- * When an accepted narrowing takes effect: once it was accepted, and its84- * notice period has run since it opened. None while nobody accepted it.85- */65 const takesEffect = (decision: Decision, noticeDays: number) =>66 Option.map(67 Option.filter(68 Option.fromUndefinedOr(decision.decided),2 unmodified lines71 ({ at }) =>72 DateTime.max(at, DateTime.add(decision.openedAt, { days: noticeDays }))73 );74 96-/** The posture in effect, and the decision that put it there or keeps it waiting. */75 export interface Standing {76 readonly label: string;77 readonly posture: Posture;100- /** The posture the config declares, which may still wait on a decision. */78 readonly declared: Posture;102- /** The accepted narrowing that made the declared posture stand, and when it did. */79 readonly changed: Option.Option<{80 readonly at: DateTime.Utc;81 readonly decision: Decision;82 readonly subject: PostureChange;83 }>;84 }85 110-/**111- * The posture in effect at `now` under `visibility`: the declared one,112- * unless the latest posture decision asked about narrowing to it and has113- * not taken effect (open, declined, expired, or accepted with notice still114- * to run); then the posture it would narrow from, in GLOSSARY's words.115- *116- * Only the latest posture decision counts: every landing that narrows what117- * stands opens one, so a config that moved on from the latest one's `to`118- * without a decision widened, and stands, whatever an older decision about119- * the same posture came to.120- */86+/** Only the latest posture decision counts: a config that moved on from its `to` without a decision widened, and stands. */87 export const standing = (input: {88 readonly decisions: readonly Decision[];89 readonly now: DateTime.Utc;90 readonly visibility: Option.Option<VisibilityPolicy>;39 unmodified lines130 }),131 });132 };133 168-/**169- * The next instant the posture in effect moves by the clock alone: an170- * accepted narrowing whose notice still runs at `now`. None when only an171- * event can move it: no narrowing waits, one waits on its decision (a172- * `Decided` event settles it), or one took effect already. A later landing173- * or decision may move it sooner; this is only when time does.174- */134 export const nextMove = (input: {135 readonly decisions: readonly Decision[];136 readonly now: DateTime.Utc;137 readonly visibility: Option.Option<VisibilityPolicy>;13 unmodified lines151 Option.filter((at) => DateTime.isGreaterThan(at, input.now))152 );153 };154 196-/**197- * Whether the config's held-back checks judge answers yet: not while a198- * narrowing from Open waits on its decision (nothing was sealed before).199- */155+/** Not while a narrowing from Open waits on its decision: nothing was sealed before. */156 export const sealedInEffect = (posture: Standing) =>157 posture.posture !== "open" || posture.declared === "open";158 203-/**204- * The `PostureChanged` row an accepted narrowing owes the ledger once it205- * took effect, if no row records it yet. A plan that writes appends it, so206- * the projection and the ledger's entries catch up with the posture shown.207- */159 export const postureCaughtUp = (160 snapshot: ProjectSnapshot,161 posture: Standing,162 seq: number16 unmodified lines179 }),180 ],181 });182 232-/** Each declared layer with the repo the project keeps for it, when it has one. */183 const withRepos = (184 visibility: VisibilityPolicy,185 rows: readonly LayerRow[]186 ): VisibilityPolicy => ({8 unmodified lines195 )196 ),197 });198 249-/**250- * The public ledger: `ledgerOf` over the project's rows and its251- * config (each layer with its repo), shown with the posture in effect at252- * `now`. The layer read log is the layers' readers' own, never in it.253- */199+/** The layer read log is the layers' readers' own, never in the public ledger. */200 export const ledgerFor = (201 project: ProjectName,202 snapshot: ProjectSnapshot,203 now: DateTime.Utc20 unmodified linesmodified:packages/project/src/visibility/state.ts+10 added-142 removed
1-/**2- * The visibility cartridge's project state: the `ProjectVisibility` port, over3- * the private namespace's repos (`LayerRepos`), a source of secret salts, and4- * what starts an admission.5- *6- * - A landing that declares layers provisions each one's repo,7- * `<project>--<layer>` in the private namespace, once (an outbox effect,8- * retried until done; a repo that exists already counts as made), and9- * appends `LayerDeclared`. A change that narrows the posture opens a10- * `PostureChange` decision for a second decider (`./ledger.ts`).11- * - A push to a layer proposes its head. With admission off it lands at12- * once: the layer's sealed checks (its manifest, `<config folder>/13- * layer.json` in the layer repo, filtered to the policy's areas) are14- * committed to under a fresh salt, which the DO's store alone keeps, and15- * each area's root, check count and author count are published16- * (`CommitmentPublished`). With admission on, the head waits for17- * `./admission.ts`'s judgement of its runs (the `Answer` Workflow's18- * admission steps run them), then lands the same way, each admitted19- * area's `Admitted` entry after its commitment; a push that changes no20- * held-back check lands at once.21- * - A claim opened while a sealed suite is in effect is pinned to its root22- * and layer commit; its answers are judged by that suite, read back at23- * that commit, and their failures counted per claim and per person, area24- * and week (`./claims.ts`), never against their record.25- *26- * Nothing it returns for the public names a layer's path, a check, or a27- * salt: roots, counts and area bits only.28- */1 import { ObjectId, Revision } from "@repo/artifacts/repo-host";2 import type { RepoExists } from "@repo/artifacts/repo-host";3 import { Brand } from "@repo/brand";4 import { commandFor } from "@repo/checks/kinds";71 unmodified lines76 standing,77 visibilityIn,78 } from "./ledger.ts";79 108-/** Where a commitment's secret salt comes from: 32 random bytes each time. */80 export class SaltSource extends Context.Service<81 SaltSource,82 { readonly next: Effect.Effect<Uint8Array> }83 >()("project/SaltSource") {}84 114-/**115- * What starts the admission of a layer push's sealed checks: the `Answer`116- * Workflow's admission run. Starting one twice runs it once.117- */85 export class AdmissionStarts extends Context.Service<86 AdmissionStarts,87 {88 readonly start: (input: {3 unmodified lines92 }) => Effect.Effect<void>;93 }94 >()("project/AdmissionStarts") {}95 129-/**130- * Where a layer repo keeps its manifest: the JSON form of `layer.ts`,131- * committed beside it, which the DO reads without evaluating code.132- */96 export const manifestPath = RepoPath.make(`${Brand.configDir}/layer.json`);97 135-/** The effects this port's plans ask for, settled after their commit. */98 const Planned = Schema.Union([99 Schema.TaggedStruct("Provision", { repo: RepoName }),100 Schema.TaggedStruct("Admit", {101 head: CommitSha,9 unmodified lines111 const encodePlanned = Schema.encodeEffect(PlannedJson);112 113 const decodePlanned = Schema.decodeUnknownEffect(PlannedJson);114 153-// A pushed manifest may leave a check's clause out: admission refuses it154-// (`UnstatedRequirement`) rather than read the manifest as none.115+// A manifest may leave a clause out: admission refuses it (`UnstatedRequirement`) rather than read it as none.116 const decodeManifest = Schema.decodeUnknownEffect(117 Schema.fromJsonString(PushedManifest)118 );119 159-/** The repo a declared layer keeps in the private namespace. */120 const repoFor = (project: ProjectName, layer: LayerName) =>121 RepoName.make(`${keyOf(project)}--${layer}`);122 163-/**164- * Whether a layer gets a repo of its own. A personal layer is each165- * person's own, and an embargo is config only: neither166- * has one, so neither is provisioned or reachable.167- */123 const ownsRepo = (layer: LayerDeclaration) =>124 layer.audience !== "personal" && layer.audience !== "security";125 171-/** The people a rule names: the project's deciders, for any path, or those listed. */126 const membersOf = (policy: Policy, members: Members): readonly Handle[] =>127 members === "deciders"128 ? policy.deciders.flatMap(({ handles }) => handles)129 : members;9 unmodified lines139 Order.String,140 (file: { readonly path: RepoPath }) => file.path141 );142 189-/** The areas a suite reports, sorted by name. */143 const areasOf = (checks: SealedChecks) =>144 Arr.sort(Object.keys(checks.areas), Order.String).map((area) =>145 AreaName.make(area)146 );147 195-/** One sealed check as a layer commit holds it: its file, its area, its blob and its author. */148 interface Sealed extends SuiteFile {149 readonly author: Handle;150 }151 200-/** The project's name, from its row. */152 const projectOf = (snapshot: ProjectSnapshot) =>153 Option.map(snapshot.project, ({ project }) => project);154 204-/** A declared layer that keeps a repo, by name. */155 const declaredLayer = (156 visibility: Option.Option<VisibilityPolicy>,157 layer: LayerName158 ) =>159 Option.flatMap(visibility, ({ layers }) =>160 Arr.findFirst(layers, (each) => each.name === layer && ownsRepo(each))161 );162 213-/** The sealed checks a layer holds, when the policy keeps them in it. */163 const checksIn = (164 visibility: Option.Option<VisibilityPolicy>,165 layer: LayerName166 ) =>1 unmodified line168 Option.flatMap(visibility, ({ checks }) => Option.fromUndefinedOr(checks)),169 (checks) => checks.layer === layer170 );171 223-/** The project's row for a layer, or a new one for its repo. */172 const rowFor = (173 snapshot: ProjectSnapshot,174 project: ProjectName,175 layer: LayerName2 unmodified lines178 Arr.findFirst(snapshot.layers, ({ name }) => name === layer),179 () => ({ name: layer, repo: repoFor(project, layer) })180 );181 234-/**235- * The decision a narrowing landing opens: for the project's own236- * deciders but those who landed it, so a second decider countersigns; when237- * nobody else decides for the whole project, its deciders as they are.238- * Its default is decline, and it stays open through the notice period and239- * the policy's usual expiry after it.240- */182+/** Excludes those who landed it, so a second decider countersigns; when nobody else decides, the deciders as they are. */183 const narrowingDecision = (input: {184 readonly after: Policy;185 readonly from: Posture;186 readonly landedBy: readonly Handle[];48 unmodified lines235 }),236 });237 };238 297-/** A plan of rows and the effects to settle after them. */239 const planOf = (240 writes: ProjectWrites,241 effects: readonly VisibilityEffect[] = []242 ): VisibilityPlan => ({ effects, writes });243 303-/** A planned effect, as a plan carries it. */244 const effectOf = (id: string, planned: Planned) =>245 Effect.map(246 Effect.orDie(encodePlanned(planned)),247 (body): VisibilityEffect => ({ body, id })248 );249 310-/** The `PostureChanged` row a narrowing that took effect still owes the ledger, numbered from `seq`. */250 const caughtUp = (251 snapshot: ProjectSnapshot,252 visibility: Option.Option<VisibilityPolicy>,253 now: DateTime.Utc3 unmodified lines257 standing({ decisions: snapshot.decisions, now, visibility }),258 nextSeq(snapshot.ledger)259 );260 322-/** How far `who` reaches into a layer of the project's policy. */261 const reach = (262 policy: Policy,263 layer: LayerDeclaration,264 who: Principal4 unmodified lines269 270 return names(membersOf(policy, layer.readers), who) ? "read" : "none";271 };272 335-/** One held-back run of a claim's answer, judged against its attempts (`./claims.ts`). */273 const judgeHeldBack: VisibilityPort["judgeHeldBack"] = (input, snapshot) => {274 const checks = Option.flatMap(visibilityIn(snapshot), ({ checks: sealed }) =>275 Option.fromUndefinedOr(sealed)276 );18 unmodified lines295 writes: judged.attempts.length === 0 ? {} : { attempts: judged.attempts },296 };297 };298 362-/** A read of a layer through the gateway, for its readers' log. */299 const recordRead: VisibilityPort["recordRead"] = (input) => ({300 layerReads: [301 {302 at: input.at,6 unmodified lines309 },310 ],311 });312 377-/** How far `who` reaches into a declared layer that keeps a repo. */313 const access: VisibilityPort["access"] = (who, layer, snapshot) =>314 Option.flatMap(policyIn(snapshot), (policy) =>315 Option.map(316 declaredLayer(Option.fromUndefinedOr(policy.visibility), layer),317 (declared) => reach(policy, declared, who)318 )319 );320 386-/** The layers `who` reads: the write-down guard runs only for these. */321 const readableLayers: VisibilityPort["readableLayers"] = (who, snapshot) =>322 new Set(323 Option.match(policyIn(snapshot), {324 onNone: () => [],5 unmodified lines330 ),331 })332 );333 400-/**401- * A landing that moved the config: `LayerDeclared` for each layer it adds402- * or changes, a row and a provisioning effect for each layer that has no403- * repo yet, and, for a narrowing, a `PostureChange` decision; first the404- * `PostureChanged` row a narrowing that took effect before still owes.405- */334 const onPolicy: VisibilityPort["onPolicy"] = (input, snapshot) =>335 Effect.gen(function* () {336 const project = projectOf(snapshot);337 const after = Option.fromUndefinedOr(input.after.visibility);8 unmodified lines346 ) {347 return noPlan;348 }349 422- // What stood before this landing, under the config as it was.350 const was = standing({351 decisions: snapshot.decisions,352 now: input.now,353 visibility: before,22 unmodified lines376 const provisions = yield* Effect.forEach(fresh, ({ repo }) =>377 effectOf(`provision:${repo}`, Planned.cases.Provision.make({ repo }))378 );379 453- // A project's first config stands at once, and an unchanged one454- // decides nothing again (a declined narrowing stays declined).380+ // A first config stands at once; an unchanged one decides nothing again (a declined narrowing stays declined).381 const changed = Option.isSome(input.before) && !Equal.equals(before, after);382 383 const to = declaredBy(after);384 25 unmodified lines410 const live = Effect.gen(function* () {411 const repos = yield* LayerRepos;412 const salts = yield* SaltSource;413 const admissions = yield* AdmissionStarts;488- // `pinSuite` and `ledger` are read without a `now`: the posture's notice489- // runs on this clock (the TestClock in tests).414+ // `pinSuite` and `ledger` take no `now`: the posture's notice runs on this clock.415 const clock = yield* Clock.Clock;416 417 const nowOf = () => DateTime.makeUnsafe(clock.currentTimeMillisUnsafe());418 494- // ------------------------------------------------------- layer commits495-496- /** A layer commit, which must exist: a pinned or landed SHA the store recorded. */419 const commitAt = (repo: RepoName, at: CommitSha) =>420 Effect.flatMap(Effect.orDie(repos.readCommit(repo, at)), (found) =>421 Option.match(found, {422 onNone: () => Effect.die(`the layer repo ${repo} has no commit ${at}`),423 onSome: Effect.succeed,424 })425 );426 505- /** Every blob a layer commit's tree holds, by path. */427 const blobsAt = (repo: RepoName, at: CommitSha) =>428 Effect.gen(function* () {429 const commit = yield* commitAt(repo, at);430 const blobs = new Map<string, ObjectId>();23 unmodified lines454 455 return blobs;456 });457 537- /** A layer commit's manifest, when it holds one for this layer that decodes. */458 const manifestAt = (repo: RepoName, layer: LayerName, at: CommitSha) =>459 Effect.gen(function* () {460 const bytes = yield* Effect.orDie(461 repos.readFile(repo, Revision.Commit({ sha: at }), manifestPath)18 unmodified lines480 481 return manifest;482 });483 564- /**565- * The sealed checks a layer commit holds: its manifest's checks in the566- * policy's areas (a check in an area the policy does not name runs567- * nowhere) that cite a clause (one that cites none never judges568- * an answer, admission or not) and whose files the commit has,569- * sorted by path.570- */484 const sealedAt = (485 repo: RepoName,486 layer: LayerName,487 at: CommitSha,42 unmodified lines530 byPath531 );532 });533 621- /**622- * A layer's head, landed: with sealed checks in it, committed to under a623- * fresh salt (kept in the layer's row, nowhere else), and each area's624- * root, check count and author count published.625- */534 const landLayer = (input: {535 readonly checks: Option.Option<SealedChecks>;536 readonly head: CommitSha;537 readonly now: DateTime.Utc;47 unmodified lines585 ],586 } satisfies ProjectWrites;587 });588 681- // ------------------------------------------------------------ the port682-683- /**684- * Every path any layer holds, at its landed head and at a head still685- * proposed: deny by default, so nothing from a layer enters a public686- * tree, admitted yet or not (principle 7).687- */589+ /** Deny by default: heads still proposed count too, so nothing from a layer enters a public tree, admitted or not. */590 const layerPaths: VisibilityPort["layerPaths"] = (snapshot) =>591 Effect.gen(function* () {592 const heads = snapshot.layers.flatMap(({ landedSha, proposed, repo }) =>593 Arr.dedupe(101 unmodified lines695 suite,696 });697 });698 797- /** A blob the layer repo must hold: one its tree named. */699 const contentOf = (repo: RepoName, blob: ObjectId) =>700 Effect.flatMap(Effect.orDie(repos.readBlob(repo, blob)), (content) =>701 Option.match(content, {702 onNone: () =>1 unmodified line704 onSome: Effect.succeed,705 })706 );707 807- /**808- * A known-bad commit the layer repo holds, as the files it lays over809- * main for its run: every file it holds that the pushed head does not810- * (so neither the checks nor the manifest), the public code it breaks at811- * main's paths. None when the repo holds no such commit.812- */708 const overlayAt = (709 repo: RepoName,710 at: CommitSha,711 head: ReadonlyMap<string, ObjectId>22 unmodified lines734 )735 );736 });737 843- /**844- * The runs that would admit `head` to `layer` (`./admission.ts`), against845- * main as it stands: none without a manifest, or for a check that cites no846- * clause. The runs carry the root of the suite they test under a salt847- * drawn for them and kept nowhere: the landing draws its own.848- */738+ /** The runs carry a salt drawn here and kept nowhere: the landing draws its own. */739 const admissionOf = (740 input: { readonly head: CommitSha; readonly layer: LayerName },741 snapshot: ProjectSnapshot742 ) =>33 unmodified lines776 row.landedSha === undefined777 ? Option.none<PushedManifest>()778 : yield* manifestAt(row.repo, row.name, row.landedSha);779 890- // The bytes of each check the manifest lists and the head holds.780 const files = new Map(781 yield* Effect.forEach(782 manifest.value.checks.flatMap(({ path }) =>783 Option.match(Option.fromUndefinedOr(head.get(path)), {63 unmodified lines847 Effect.gen(function* () {848 const project = projectOf(snapshot);849 const visibility = visibilityIn(snapshot);850 962- // The gateway lets only the layer's writers push; a push heard963- // from anyone else, or to a layer the config no longer declares,964- // moves nothing.851+ // Only the layer's writers may push; anyone else, or an undeclared layer, moves nothing.852 if (853 Option.isNone(project) ||854 !Option.contains(855 access(Person.make({ handle: input.pusher }), input.layer, snapshot),8 unmodified lines864 }865 866 const row = rowFor(snapshot, project.value, input.layer);867 981- // The same push heard again changes nothing.868 if (row.landedSha === input.head || row.proposed === input.head) {869 return noPlan;870 }871 872 const owed = caughtUp(snapshot, visibility, input.now);873 const checks = checksIn(visibility, input.layer);874 const admits = Option.exists(checks, ({ admit }) => admit !== undefined);875 990- // Admission decides: the head waits, proposed, for its runs. A991- // push that changes no held-back check has none, and lands at once.876+ // A push that changes no held-back check has no runs, and lands at once.877 const planned = admits878 ? yield* admissionOf({ head: input.head, layer: input.layer }, snapshot)879 : Option.none<AdmissionPlan>();880 30 unmodified lines911 start912 );913 });914 1030- // Only a head still proposed has a plan: the layer repo is not read for1031- // one that landed or was pushed over (every run step asks again).915+ // Only a head still proposed has a plan (every run step asks again).916 const admissionPlan: VisibilityPort["admissionPlan"] = (input, snapshot) =>917 Arr.some(918 snapshot.layers,919 ({ name, proposed }) => name === input.layer && proposed === input.head920 )921 ? admissionOf(input, snapshot)922 : Effect.succeedNone;923 1040- /**1041- * An admission's results, judged by `./admission.ts` against the plan the1042- * project makes again now (a reported run it did not plan counts for1043- * nothing). When every area the push changes is admitted, the head lands1044- * as a push with admission off does, under a fresh salt with each area's1045- * commitment published, then each admitted area's `Admitted` entry,1046- * rooted at its new commitment. Otherwise the landed SHA stays where it1047- * was, and the head stays proposed.1048- */924 const onAdmission: VisibilityPort["onAdmission"] = (input, snapshot) =>925 Effect.gen(function* () {926 const row = Arr.findFirst(927 snapshot.layers,13 unmodified lines941 942 const judged = judgeAdmission(planned.value, input.results, input.now);943 const areas = Arr.dedupe(planned.value.runs.map(({ area }) => area));944 1070- // Every area the push changes admitted, or nothing lands.945 if (judged.admitted.length < areas.length) {946 yield* Effect.logWarning(947 `the push of ${input.head} to ${input.layer} was not admitted`,948 judged.refused23 unmodified lines972 : []973 )974 );975 1102- // Each admitted area cites its new commitment, never the root its1103- // runs carried (that salt was kept nowhere, so nobody could check it).976+ // Each admitted area cites its new commitment, never its runs' root (that salt was kept nowhere).977 const admitted = yield* Effect.forEach(judged.admitted, (entry, index) =>978 Option.match(Option.fromUndefinedOr(roots.get(entry.area)), {979 onNone: () =>980 Effect.die(13 unmodified lines994 ...appended([...owed, ...published, ...admitted]),995 });996 });997 1125- /** One planned effect, run: a repo made (or found made), an admission started. */998 const run = (planned: Planned) =>999 Planned.match(planned, {1000 Admit: ({ head, layer, project }) =>1001 Effect.as(admissions.start({ head, layer, project }), true),51 unmodified lines1053 1054 return port;1055 });1056 1185-/**1186- * The live `ProjectVisibility`, over the private namespace's repos, a salt1187- * source (WebCrypto at the platform's edge) and what starts admissions.1188- */1057 export const ProjectVisibilityLive: Layer.Layer<1058 never,1059 never,1060 AdmissionStarts | LayerRepos | SaltSource1 unmodified linemodified:packages/project/src/alarms.ts-8 removed
1-/**2- * The `Alarms` port: how a project asks to be woken. A Durable Object holds3- * one alarm, so `set` replaces whatever was set before; the project service4- * decides when (the earliest claim deadline, outbox retry or answer retry5- * still pending) and calls `onAlarm` when it fires. Adapters: `/memory`6- * here, the DO's storage alarm in `apps/platform`.7- */1 import { Context } from "effect";2 import type { DateTime, Effect } from "effect";3 4 export class Alarms extends Context.Service<5 Alarms,6 {14- /** Wake the project at `at`, in place of any alarm set before. */7 readonly set: (at: DateTime.Utc) => Effect.Effect<void>;8 }9 >()("project/Alarms") {}modified:packages/project/src/answer-runs.ts+6 added-92 removed
1-/**2- * The `AnswerRuns` port: how the project service starts carrying an admitted3- * answer to its verdict and onto main. The project only records where each4- * answer stands; a run does the slow part (merge, checks, land) through the5- * project's answer queue, step by step, and reports each step back.6- *7- * Adapters: `/inline` here, which runs the steps in process (tests), and8- * the Answer Workflow in `apps/platform`, which runs each step as a9- * durable Workflow step. Both drive the same two methods, `answer` and10- * `advanceAnswer`, with the same steps (`answer-runs/steps.ts`), so they11- * reach the same outcome.12- */1 import { CheckLane } from "@repo/checks/check-runner";2 import {3 HeldBackResult,4 LaneResult,28 unmodified lines33 import type { LandingCommand, LandingEffect } from "./landing.ts";34 35 const Attempt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));36 49-/**50- * A `LandingCommand` as it crosses a boundary: what a step reports back to the51- * project (the platform's Answer Workflow calls `advanceAnswer` over the52- * Project Durable Object's boundary with it).53- */37 export const ReportedCommand = Schema.TaggedUnion({38 Blocked: { attempt: Attempt },39 Busy: { attempt: Attempt },40 Checked: {8 unmodified lines49 MainMoved: { from: LandedSha, main: LandedSha },50 MergeConflict: {51 conflicts: Schema.Array(RepoPath),52 main: LandedSha,70- // Absent from a step recorded before a merge named who moved a path.53+ // Absent from steps recorded before a merge named who moved a path.54 movedBy: Schema.optionalKey(Schema.NonEmptyArray(MovedBy)),55 },56 Merged: { changes: Schema.Array(Change), main: LandedSha, tree: TreeSha },57 Start: { main: LandedSha },58 Wait: { parent: AskId },59 });60 78-/**79- * A port call a run makes next, as `advanceAnswer` returns it: a merge, the80- * checks, a land, or a `Retry` to wait for (the project's alarm starts the81- * run again then). The project settles every other `LandingEffect` itself.82- */61 export const NextStep = Schema.TaggedUnion({62 Land: { main: LandedSha, tree: TreeSha },63 Merge: { base: CommitSha, fork: RepoName, head: CommitSha, main: LandedSha },64 Retry: { at: Schema.DateTimeUtcFromString },65 RunChecks: { tree: TreeSha },66 });67 90-/** What `advanceAnswer` returns, as it crosses a boundary: `Advanced`. */68 export const Steps = Schema.Struct({69 effects: Schema.Array(NextStep),70 outcome: Outcome,71 });72 96-/** A ratchet's count in one territory, as a check of a tree measured it. */73 export const MeasuredCount = Schema.Struct({74 count: Attempt,75 ratchet: RatchetName,76 territory: Schema.NonEmptyString,77 });78 79 export type MeasuredCount = typeof MeasuredCount.Type;80 105-/**106- * One answer request as a run needs it: where it stands, whether it holds107- * the project's one landing slot, and the policy's facts its steps use. It108- * crosses the Project Durable Object's boundary, so it is a schema.109- */81 export const AnswerRun = Schema.Struct({111- /** Whether the request holds the landing slot: a `Landing` lands only then. */82 admitted: Schema.Boolean,113- /** The ask it answers; absent for a decider's own landing. */83 ask: Schema.optionalKey(Ask),115- /** The lane the ask's own check reports as, which is red on main by design. */84+ /** Red on main by design. */85 askLane: Schema.optionalKey(LaneName),117- /**118- * What the cheap stage counts on the merged tree: the policy's ratchets,119- * and the modules a count is split by. Absent without a policy.120- */86 counts: Schema.optionalKey(87 Schema.Struct({88 modules: Schema.Array(Territory),89 ratchets: Schema.Array(RatchetSpec),90 })91 ),127- /**128- * The env every check job of the answer carries (`ProjectEnv.runEnv` for129- * unlanded code): placeholders and proxies, never a value. Absent, none.130- */92+ /** Placeholders and proxies, never a value. */93 env: Schema.optionalKey(UnlandedRunEnv),132- /** Whether a decider must finish it before it lands: the ask kind's `finish`. */94 finish: AskKind.fields.finish,134- /** What the checks run on the merged tree: the ask's check first, then every project lane. */95 lanes: Schema.Array(CheckLane),136- /** The landing commit's whole message, trailers included, once the answer is checked. */96 message: Schema.optionalKey(Schema.String),138- /** The canonical repo the answer lands on. */97 repo: RepoName,140- /**141- * The project's run block, which every check job carries: absent while142- * the project has no policy (the gate is broken, and nothing is checked).143- */98 run: Schema.optionalKey(RunBlock),145- /**146- * Whether a held-back suite judges the answer: its claim was pinned to147- * one. Its checks then end with the held-back run148- * (`ProjectApi.heldBackJob`, `recordHeldBack`). Absent, none does.149- */99 sealed: Schema.optionalKey(Schema.Boolean),100 state: LandingState,152- /** The verdict on the merged tree, once the checks judged it. */101 verdict: Schema.optionalKey(Verdict),102 });103 104 export type AnswerRun = typeof AnswerRun.Type;105 158-/**159- * The run block every check job of an answer's run carries: `VerifierBlocked`160- * while the project has none, since the Checker never guesses a project's161- * setup (live on dev-oscabriel, a job without one was blocked).162- */106+/** `VerifierBlocked` without a run block: the Checker never guesses a project's setup. */107 export const runBlockOf = (from: {108 readonly run?: RunBlock;109 }): Effect.Effect<RunBlock, VerifierBlocked> =>110 Effect.fromOption(Option.fromUndefinedOr(from.run)).pipe(111 Effect.mapError(() => new VerifierBlocked({}))112 );113 170-/**171- * What a step saw beside the command it reports: the lanes and held-back172- * areas a check run judged (the verdict is made from them), the ratchets it173- * counted (the project judges them against its baselines), and the174- * bookkeeping a land left unwritten (the project retries it).175- */114 export const AnswerReport = Schema.Struct({115 heldBack: Schema.optionalKey(Schema.Array(HeldBackResult)),116 lanes: Schema.optionalKey(Schema.Array(LaneResult)),117 pending: Schema.optionalKey(118 Schema.Array(Schema.Literals(["mirror", "notes"]))119 ),182- /** Each ratchet's count on the checked tree, per territory: the project judges them. */120 ratchets: Schema.optionalKey(Schema.Array(MeasuredCount)),121 });122 123 export type AnswerReport = typeof AnswerReport.Type;124 188-/** A landing effect the answer's run carries out: a port call, or a retry to wait for. */125 export type RunnableEffect = Extract<126 LandingEffect,127 { readonly _tag: NextStep["_tag"] }128 >;129 130 type NextStep = typeof NextStep.Type;131 196-/**197- * What one reported step changed: where the answer stands now, and the port198- * calls to run next. Only `NextStep`'s effects, so whatever the service199- * returns here crosses the Project DO's boundary.200- */132 export interface Advanced {133 readonly effects: readonly RunnableEffect[];134 readonly outcome: Outcome;135 }136 206-/**207- * A project's answer queue, as a run sees it: read one answer's run, and208- * report what a step came to. `advanceAnswer` returns only the port calls209- * the run makes next (`Merge`, `RunChecks`, `Land`), and a `Retry` when it210- * should stop and wait for the project's alarm; the project settles211- * everything else itself. A merge that conflicts reads `landings` to name212- * who moved each path.213- */137 export interface AnswerQueue {138 readonly advanceAnswer: (139 requestId: RequestId,140 command: LandingCommand,1 unmodified line142 ) => Effect.Effect<Advanced>;143 readonly answer: (144 requestId: RequestId145 ) => Effect.Effect<Option.Option<AnswerRun>>;223- /**224- * The landings among `shas` (at most `MAX_LANDINGS`), in their order: a225- * commit the platform did not land, imported history among them, has none.226- */146+ /** A commit the platform did not land (imported history) has none. */147 readonly landings: (148 shas: readonly CommitSha[]149 ) => Effect.Effect<readonly LandingView[]>;150 }151 232-/**233- * Starts the run of one answer request. Idempotent by id: starting a run234- * already under way, or already over, changes nothing. `queue` is the235- * project's own answer queue, which an in-process adapter drives directly;236- * the Workflow adapter reaches the same queue through the project's Durable237- * Object and ignores it.238- */152+/** Idempotent by id. The Workflow adapter ignores `queue` and reaches it through the Durable Object. */153 export class AnswerRuns extends Context.Service<154 AnswerRuns,155 {156 readonly start: (5 unmodified linesmodified:packages/project/src/claim.ts+1 added-68 removed
1-/**2- * The claim lifecycle (ADR 0012): one person's exclusive, expiring right to3- * answer an ask, moved only by `transition`. It reads no clock and calls no4- * port: `now` is an argument, and what should happen next comes back as data5- * (`ClaimEffect`) for the project service to settle.6- */1 import { ClaimView } from "@repo/protocol/domain/claim";2 import type { Policy } from "@repo/protocol/domain/policy";3 import {4 AskId,18 unmodified lines23 import { Array as Arr, Data, DateTime, Option, Result, Schema } from "effect";24 25 import { ProjectEventInput } from "./events.ts";26 33-/** What a claim holds while it lasts, and keeps once it ends. */27 const claimFields = {28 ask: AskId,36- /** Main's landed commit when the claim was made. */29 base: CommitSha,30 claimant: Handle,39- /** The claim's fork: `<project>--<ask>--<handle in lowercase>`. */31 fork: RepoName,41- /** The last push (or the claim) plus the policy's `lapseAfterMs`. */32 lapsesAt: Schema.DateTimeUtcFromString,33 lastPushAt: Schema.OptionFromOptionalKey(Schema.DateTimeUtcFromString),34 openedAt: Schema.DateTimeUtcFromString,45- /** The last push (or the claim) plus the policy's `warnAfterMs`. */35 warnsAt: Schema.DateTimeUtcFromString,36 };37 49-/**50- * Where one claim on an ask stands. `Open` holds no claim; `Live` and51- * `Warned` are live; `Lapsed`, `Released` and `Answered` keep the claim they52- * ended. Encoded, it is JSON, so the project store persists it as is.53- */38 export const ClaimState = Schema.TaggedUnion({55- /** The claimant's answer landed. */39 Answered: { ...claimFields, landing: LandedSha },57- /** No push came in time; the claimant may push no more. */40 Lapsed: { ...claimFields, at: Schema.DateTimeUtcFromString },41 Live: claimFields,42 Open: { ask: AskId },61- /** The claimant gave the claim up. */43 Released: claimFields,63- /** Live, but quiet for long enough that the claimant was warned. */44 Warned: claimFields,45 });46 47 export type ClaimState = typeof ClaimState.Type;48 69-/** A claim's fields, which `Live` and `Warned` hold and the ended states keep. */49 export type Live = Omit<typeof ClaimState.cases.Live.Type, "_tag">;50 72-/**73- * What can happen to a claim. `Claim` carries what the project service knows74- * and the lifecycle does not: how many claims the person holds (`heldByWho`)75- * against their `cap`, how many others hold a live claim on the ask76- * (`liveCount`) against the kind's `race`, the person's standing, and the77- * asks this one waits on.78- */51 export const ClaimCommand = Schema.TaggedUnion({52 Claim: {81- /** Main's landed commit now. */53 base: CommitSha,54 blockedBy: Schema.Array(AskId),55 cap: Schema.Int,56 denounced: Schema.Boolean,3 unmodified lines60 race: Schema.Int,61 vouched: Schema.Boolean,62 who: Person,63 },93- /** The claimant's answer landed on main. */64 Land: { landing: LandedSha },95- /** A push reached the claim's fork. */65 Push: { head: CommitSha, who: Handle },66 Release: { who: Handle },98- /** An alarm fired: a deadline may have passed. */67 Tick: {},68 });69 70 export type ClaimCommand = typeof ClaimCommand.Type;71 104-/** What the project service does after a transition, in order. */72 export type ClaimEffect = Data.TaggedEnum<{73 Emit: { readonly event: ProjectEventInput };107- /** Fork the canonical repo; a retried fork converges on the same one. */74 MakeFork: { readonly from: RepoName; readonly name: RepoName };109- /** The claimant may push to the fork no more; the fork stays. */75 RevokeAccess: { readonly fork: RepoName };76 SetAlarm: { readonly at: DateTime.Utc };77 }>;78 79 export const ClaimEffect = Data.taggedEnum<ClaimEffect>();80 116-/** Every way the claim lifecycle says no. */81 export type ClaimRefusal =82 | AskBlocked83 | AskFull84 | CapReached1 unmodified line86 | Denounced87 | NotClaimed88 | NotVouched;89 126-/** A transition's result: the next state and the effects that settle it. */90 export interface ClaimStep {91 readonly effects: readonly ClaimEffect[];92 readonly state: ClaimState;93 }94 132-/** What `transition` returns: a step, or the refusal that changes nothing. */95 export type ClaimResult = Result.Result<ClaimStep, ClaimRefusal>;96 135-/** The state as it is, with nothing to settle: how a repeated command converges. */97 const stay = (state: ClaimState): ClaimResult =>98 Result.succeed({ effects: [], state });99 100 const move = (101 state: ClaimState,102 ...effects: readonly ClaimEffect[]103 ): ClaimResult => Result.succeed({ effects, state });104 144-/** A claim's own fields, whatever state holds them. */105 const claimOf = ({106 ask,107 base,108 claimant,12 unmodified lines121 openedAt,122 warnsAt,123 });124 165-/** When a claim quiet since `from` is warned, and when it lapses. */125 const deadlines = (from: DateTime.Utc, policy: Policy["claims"]) => ({126 lapsesAt: DateTime.add(from, { milliseconds: policy.lapseAfterMs }),127 warnsAt: DateTime.add(from, { milliseconds: policy.warnAfterMs }),128 });129 130 type Claim = typeof ClaimCommand.cases.Claim.Type;131 173-/**174- * A new claim on an ask its maker does not hold. `AskFull` comes first, so a175- * full ask never forks (ADR 0008); then the ask's blockers, the person's cap,176- * and their standing, a denouncement before a missing vouch.177- */132+// `AskFull` comes first, so a full ask never forks.133 const grant = (134 ask: AskId,135 made: Claim,136 now: DateTime.Utc,49 unmodified lines186 made: Claim,187 now: DateTime.Utc,188 policy: Policy["claims"]189 ): ClaimResult => {235- // A live claim is its holder's to keep, and nobody else's to take.190 const holder = (live: Live) =>191 live.claimant === made.who.handle192 ? stay(state)193 : Result.fail(new AskFull({ ask: live.ask }));7 unmodified lines201 Warned: holder,202 });203 };204 251-/** Whoever holds no live claim on the ask. */205 const unclaimed = ({ ask }: { readonly ask: AskId }) =>206 Result.fail(NotClaimed.of(ask));207 208 const push = (1 unmodified line210 { head, who }: typeof ClaimCommand.cases.Push.Type,211 now: DateTime.Utc,212 policy: Policy["claims"]213 ): ClaimResult => {261- // The holder's push starts both deadlines again from now.214 const kept = (live: Live) => {215 if (live.claimant !== who) {216 return Result.fail(NotClaimed.of(live.ask));217 }81 unmodified lines299 })300 )301 : Result.fail(NotClaimed.of(live.ask));302 351- // A claim that already ended stays ended: releasing it again converges.303 const ended = (claimed: Live) =>304 claimed.claimant === who305 ? stay(state)306 : Result.fail(NotClaimed.of(claimed.ask));7 unmodified lines314 Warned: end,315 });316 };317 367-/**368- * The claimant's answer landed. A live claim's access ends with it; a lapsed369- * claim's already has. A released claim stays released, and an ask that holds370- * no claim (a decider's own landing) is left as it is.371- */318 const land = (state: ClaimState, landing: LandedSha): ClaimResult => {319 const answer = (live: Live, ...effects: readonly ClaimEffect[]) =>320 move(321 ClaimState.cases.Answered.make({ ...claimOf(live), landing }),12 unmodified lines334 Warned: revoked,335 });336 };337 392-/**393- * The one way a claim moves: the next state and the effects that settle it,394- * or a refusal, which changes nothing. Deadlines become `SetAlarm` effects and395- * an alarm comes back as `Tick`. Pure: the same arguments give the same396- * result, so a replayed command converges.397- */338 export const transition = (339 state: ClaimState,340 command: ClaimCommand,341 now: DateTime.Utc,6 unmodified lines348 Release: ({ who }) => release(state, who, now),349 Tick: () => tick(state, now),350 });351 412-/** Where the claim's fork is served and what to run, for the claim's view. */352 export interface ViewContext {414- /** What `<cli> check` runs locally for the ask; not empty. */353 readonly checkCommand: string;354 readonly project: ProjectName;417- /** The fork's URL at the gateway; not empty. */355 readonly remote: string;356 }357 421-/**422- * The claim as its claimant sees it, in whichever state it is or ended in;423- * none while the ask holds no claim.424- */358 export const toView = (359 state: ClaimState,360 context: ViewContext361 ): Option.Option<ClaimView> => {34 unmodified linesmodified:packages/project/src/code-store.ts+1 added-19 removed
1-/**2- * The code history's durable store: what a code read computed from immutable3- * ids (a why, a path's history), kept as text across isolates. A4- * `Context.Reference` whose default stores nothing, so every host composes5- * before a store is given, as `CodeCache` does; the platform gives one over6- * its `CODE_CACHE` bucket (`code-store/binding.ts`).7- *8- * Values are text the caller encodes and decodes with Schema: a value that9- * fails to decode is the caller's miss (principle 2). Keys belong to the10- * caller too, and hold at most 1,024 bytes (R2's limit), so a caller hashes11- * a path rather than spelling it.12- */1 import { Context, Effect, Option } from "effect";2 3 /** A store of text by key, whose every failure reads as a miss. */4 export interface CodeStoreApi {17- /** The text kept under `key`; none when nothing is, or the store failed. */5 readonly get: (key: string) => Effect.Effect<Option.Option<string>>;19- /** Keeps `value` under `key`; a store that fails keeps nothing, silently to the caller. */6 readonly put: (key: string, value: string) => Effect.Effect<void>;7 }8 23-/** The longest key a store takes, in UTF-8 bytes: R2's limit. */9 export const MAX_KEY_BYTES = 1024;10 26-/**27- * `key`, once it fits: a longer key is a caller's bug (it should have hashed28- * the path), so it dies rather than reading as a miss.29- */11+/** A key over the limit is a caller's bug (hash the path), so it dies rather than misses. */12 export const fittingKey = (key: string) =>13 new TextEncoder().encode(key).byteLength > MAX_KEY_BYTES14 ? Effect.die(15 `a code store key holds at most ${MAX_KEY_BYTES} bytes; hash its path`9 unmodified linesmodified:packages/project/src/code.ts+1 added-23 removed
1-/**2- * A project's code as its readers browse it, read from its canonical repo3- * only (no payload names a repo, so no fork or layer can be named, principle4- * 7): refs, trees, every path, files, the first-parent log, a commit's diff5- * and why each line is there. Host-free: both the platform's handlers and6- * the web's dev world call these with the `RepoHost` they run on, and7- * consult the project's record only for main's landed commit, its landings8- * and its forks (`CodeProject`). Reads by object id go through `CodeCache`.9- *10- * Each read lives in its own module under `code/`.11- */1 import type { RepoHost } from "@repo/artifacts/repo-host";2 import type {3 CommitDiff,4 CommitView,28 unmodified lines33 import { listing } from "./code/tree.ts";34 import { whyView } from "./code/why.ts";35 import type { ProjectApi } from "./project.ts";36 48-/** What the code reads take from a project's record, beside its canonical repo. */37 export interface CodeProject {50- /** The project, as its refs name it. */38 readonly project: ProjectName;52- /** The project's canonical repo: never a fork's or a layer's. */39+ /** Never a fork's or a layer's. */40 readonly repo: RepoName;54- /** Main's landed commit; none before the first push. */41 readonly head: Effect.Effect<Option.Option<LandedSha>>;42 /** The landings among `shas`, so a forged trailer never reads as one. */43 readonly landings: (44 shas: readonly CommitSha[]45 ) => Effect.Effect<readonly LandingView[]>;46 readonly forks: Effect.Effect<readonly ForkRef[]>;47 }48 63-/** The code reads' view of `project`, through its `ProjectApi`. */49 export const codeProjectOf = (50 api: ProjectApi,51 project: ProjectName52 ): CodeProject => ({3 unmodified lines56 project,57 repo: RepoName.make(keyOf(project)),58 });59 75-/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */60 export const refsOf = (61 project: CodeProject62 ): Effect.Effect<RefsView, never, RepoHost> => refsView(project);63 80-/** One folder at `at` (main when none), folders first, with its README. */64 export const treeOf = (65 project: CodeProject,66 at: Option.Option<Rev>,67 path: Option.Option<RepoPath>68 ): Effect.Effect<TreeListing, UnknownRevision | UnknownPath, RepoHost> =>69 listing(project, at, path);70 88-/** Every file path at `at`, up to the cap. */71 export const pathsOf = (72 project: CodeProject,73 at: Option.Option<Rev>74 ): Effect.Effect<PathList, UnknownRevision, RepoHost> => pathList(project, at);75 94-/** One file at `at`: its text, or that it is binary or too large. */76 export const fileOf = (77 project: CodeProject,78 at: Option.Option<Rev>,79 path: RepoPath80 ): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>81 fileView(project, at, path);82 102-/** A page of first-parent commits from `at`, each landing with its record. */83 export const logOf = (84 project: CodeProject,85 input: {86 readonly at: Option.Option<Rev>;6 unmodified lines93 UnknownRevision,94 RepoHost95 > => logPage(project, input);96 117-/** One commit and the files it changed against its first parent. */97 export const commitOf = (98 project: CodeProject,99 sha: CommitSha100 ): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>101 commitDiff(project, sha);102 124-/** Why each line of a file at `at` is there. */103 export const whyOf = (104 project: CodeProject,105 at: Option.Option<Rev>,106 path: RepoPath2 unmodified linesmodified:packages/project/src/deciders.ts+2 added-266 removed
1-/**2- * The decider-facing half of the project service: a decider's Today,3- * proposals and flags, decisions and the defaults their expiry applies,4- * finishes, a decider's own landing from their working fork, vouches and5- * denouncements, and a person's credits. The ledger, the env shape and6- * write-only values are declared here and answered by the visibility ports7- * (`visibility-port.ts`, `env-port.ts`), in `project.ts`.8- *9- * Every call has the core loop's shape (ADR 0012): the project service10- * lends its hydrate, its one-call `write` (hydrate, transition, persist,11- * settle under the project's lock) and the helpers it already has, as a12- * `DeciderKernel`; the attention rules decide, and this module13- * settles what they return. Nothing here reimplements a rule.14- *15- * Two departures, each said where it happens: a decider's `land` runs its16- * landing's steps within the call, as `openAsk` runs red first, since the17- * answer queue keeps a receipt with an ask; and a proposal's files ride on18- * its decision's evidence, since a proposal row holds their paths only.19- */1 import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";2 import { Brand } from "@repo/brand";3 import { CheckLane } from "@repo/checks/check-runner";4 import type { CheckRunner } from "@repo/checks/check-runner";119 unmodified lines124 OutboxRow,125 ProjectRow,126 } from "./project-store/rows.ts";127 147-/**148- * The env shape method's name, which is its contract's tag. Lint keeps149- * "shape" out of code names, so the name is spelled once, here, and every150- * table that holds the method keys it by this constant.151- */128+/** Lint keeps "shape" out of code names, so the name is spelled once, here. */129 export const envSchemaMethod = "envShape";130 154-/** The decider-facing methods of one project's service. */131 export interface DeciderApi {156- /**157- * The project's env shape at its landed SHA, as `ProjectEnv` reads it158- * (none without the visibility cartridge). A project with nothing landed159- * has none to read: `UnknownProject`.160- */132 readonly [envSchemaMethod]: (133 caller: Principal134 ) => Effect.Effect<EnvSchemaView, UnknownProject>;164- /** A person's credits in this project, by area and role; never a score. */135 readonly credits: (136 caller: Principal,137 handle: Handle138 ) => Effect.Effect<{ readonly credits: readonly CreditSummary[] }>;169- /**170- * One decider's choice on one decision, spent from their budget; what it171- * says yes to goes ahead in the same call (an accepted proposal opens its172- * ask red first), and a declined proposal closes. An accepted proposal173- * whose ask meets a blocked Checker or a moved main fails with that174- * refusal and decides nothing, so it can be decided again.175- */139 readonly decide: (140 caller: Person,141 input: {142 readonly choice: Choice;3 unmodified lines146 ) => Effect.Effect<147 { readonly decision: Decision },148 UnknownDecision | DecisionClosed | NotDecider | WaitRefusal149 >;187- /**188- * A decider finishes an answer that waits on a finish: at the answer's189- * own head it lands as it is; at a head with the decider's commits on190- * top, that head is checked again from the merge. Either way the landing191- * carries `Finished-by`, and the finish is spent from their budget.192- */150 readonly finish: (151 caller: Person,152 input: {153 readonly ask: AskId;4 unmodified lines158 ) => Effect.Effect<159 AnswerReceipt,160 NotDecider | StaleBase | RepoBusy | TouchedJudge161 >;205- /** A flag on an open ask: a proposal that says it is wrong, for its deciders. */162 readonly flagAsk: (163 caller: Person,164 input: { readonly ask: AskId; readonly reason: string }165 ) => Effect.Effect<166 { readonly proposal: Proposal },167 UnknownAsk | Denounced | CapReached168 >;213- /** The caller's working fork, `<project>--me--<handle>`, made once. */169 readonly fork: (170 caller: Person171 ) => Effect.Effect<172 { readonly fork: RepoName; readonly remote: string },173 NotVouched | Denounced174 >;220- /**221- * A decider's own change, from their working fork, through stages 0–1,222- * the merge and the project's checks, landed as a platform commit they223- * author. Refusals from the stages or the checks come back in the224- * receipt's outcome.225- */175 readonly land: (176 caller: Person,177 input: {178 readonly base: CommitSha;1 unmodified line180 readonly message: string;181 readonly requestId: RequestId;182 }183 ) => Effect.Effect<LandReceipt, NotDecider | StaleBase | RepoBusy>;235- /** The project's public ledger, as `ProjectVisibility` keeps it (Open, empty, without the cartridge). */184 readonly ledger: (caller: Principal) => Effect.Effect<Ledger>;237- /** A proposal for a new ask, and the decision that puts it to its deciders. */185 readonly proposeAsk: (186 caller: Person,187 input: {241- /** Have the platform's agent draft the ask's files. */188 readonly draft?: true;189 readonly files?: Array.NonEmptyReadonlyArray<ComposedFile>;190 readonly sealed?: { readonly head: CommitSha };191 readonly territory?: string;2 unmodified lines194 ) => Effect.Effect<195 { readonly proposal: Proposal },196 Denounced | CapReached | NotVouched197 >;252- /**253- * A write-only value for a sensitive item, sealed by `ProjectEnv`;254- * without the visibility cartridge no item takes one (`UnknownEnvItem`255- * for a decider, `NotDecider` for anyone else).256- */198 readonly setEnv: (199 caller: Person,200 input: {201 readonly acknowledgeShort?: boolean;7 unmodified lines209 readonly setBy: Handle;210 },211 NotDecider | UnknownEnvItem | NotSensitive | ValueTooShort212 >;272- /**273- * Has the platform's agent draft an open proposal's ask, or draft it274- * again with a note, for its proposer or a decider of its paths; at most275- * `DRAFT_ROUNDS` rounds. The decision a round settles into goes up then.276- */213 readonly draftAsk: (214 caller: Person,215 input: { readonly note?: string; readonly proposal: ProposalId }216 ) => Effect.Effect<217 { readonly proposal: Proposal },218 UnknownProposal | ProposalClosed | NotDecider | DraftInProgress | CapReached219 >;284- /**285- * The public face of a proposal: its state, its draft's, and the files286- * it holds until a decider accepts it.287- */220 readonly showProposal: (221 caller: Principal,222 proposal: ProposalId223 ) => Effect.Effect<224 { readonly files: readonly ConfigFile[]; readonly proposal: Proposal },225 UnknownProposal226 >;295- /** The caller's Today, held to their budget; a person who decides nothing has none. */227 readonly today: (caller: Person) => Effect.Effect<Today, NotDecider>;297- /** A platform landing of the vouch file with the person vouched for, or denounced. */228 readonly vouch: (229 caller: Person,230 input: {231 readonly handle: Handle;2 unmodified lines234 }235 ) => Effect.Effect<{ readonly landed: LandedSha }, NotDecider | StaleBase>;236 }237 308-/** What a project holds that the decider-facing methods read, at a call's start. */238 export interface DeciderState {239 readonly answers: readonly {240 readonly record: {241 readonly landing: LandingState;13 unmodified lines255 readonly project: Option.Option<ProjectRow>;256 readonly proposals: readonly Proposal[];257 }258 330-/** What a decider-facing call writes, beside what the core loop writes. */259 export interface DeciderWrites {332- /** Keyed by day and decider. */260 readonly budgetDays: Map<string, BudgetDayRow>;261 readonly decisions: Map<DecisionId, Decision>;262 readonly events: ProjectEventInput[];263 readonly landings: LandingView[];1 unmodified line265 readonly project: Map<"row", ProjectRow>;266 readonly proposals: Map<ProposalId, Proposal>;267 }268 342-/** An ask to open from its files, red first, as `openAsk` or an accepted proposal does. */269 export interface Opening {270 readonly ask: AskId;345- /** Who asks it: `askedBy`, and the landing's author. */271 readonly asker: Handle;347- /** The agents the landing discloses (`Assisted-by:`): the platform's drafter, for a drafted ask. */272 readonly assisted: readonly AgentTrailer[];273 readonly credits: readonly Credit[];350- /** Who must decide for its territory. */274 readonly decider: Person;275 readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;276 }277 355-/** The refusals opening an ask can give. */278 export type OpenRefusal =279 | NotDecider280 | NotRedFirst281 | WeakCheck1 unmodified line283 | TouchedJudge284 | VerifierBlocked285 | StaleBase;286 365-/** The refusals waiting lifts: the call that met one fails, and is tried again. */287 export type WaitRefusal = VerifierBlocked | StaleBase;288 368-/** The refusals opening an ask gives that waiting does not lift. */289 type FinalOpenRefusal = Exclude<OpenRefusal, WaitRefusal>;290 371-/** A refusal that declines the proposal whose ask met it. */291 const declines = (refusal: FinalOpenRefusal) => Effect.succeedSome(refusal);292 374-/** The ports the decider-facing methods call, besides the store. */293 export type DeciderPorts = CheckRunner | Lander | RepoHost;294 377-/**378- * What the project service lends the decider-facing methods: its hydrate,379- * its one-call write, and the helpers the core loop already has. `H` and380- * `W` are the service's own state and writes.381- */295 export interface DeciderKernel<296 H extends DeciderState,297 W extends DeciderWrites,298 > {386- /** One reported step of an answer, under the call's lock (`advanceAnswer`'s body). */299 readonly advance: (300 h: H,301 writes: W,302 now: DateTime.Utc,303 requestId: RequestId,304 command: LandingCommand305 ) => Effect.Effect<Advanced>;394- /** A new answer request, queued and started on `main`, with its receipt. */306 readonly enqueue: (307 writes: W,308 request: Request,309 input: {2 unmodified lines312 readonly now: DateTime.Utc;313 }314 ) => Effect.Effect<AnswerReceipt>;315 readonly name: ProjectName;405- /** An ask opened from its files, red first, and landed. */316 readonly open: (317 h: H,318 writes: W,319 now: DateTime.Utc,1 unmodified line321 ) => Effect.Effect<322 { readonly ask: Ask; readonly landed: LandedSha },323 OpenRefusal324 >;415- /** The project row at a new landed SHA, with the policy read there. */325 readonly policyAt: (326 row: ProjectRow,327 at: LandedSha,328 now: DateTime.Utc329 ) => Effect.Effect<ProjectRow>;330 readonly read: Effect.Effect<H>;422- /** The env a check of unlanded code carries (`ProjectEnv.runEnv`). */331 readonly runEnv: Effect.Effect<UnlandedRunEnv>;424- /** A push's stage 0–1 facts with the layer paths and whether the pusher reads a layer (`ProjectVisibility`). */332 readonly withLayers: (facts: PushFacts) => Effect.Effect<PushFacts>;426- /** A repo's URL at the gateway. */333 readonly remote: (fork: RepoName) => Effect.Effect<string>;428- /** The canonical repo. */334 readonly repo: RepoName;335 readonly withPorts: <A, E>(336 effect: Effect.Effect<A, E, DeciderPorts>337 ) => Effect.Effect<A, E>;2 unmodified lines340 body: (h: H, writes: W, now: DateTime.Utc) => Effect.Effect<A, E>341 ) => Effect.Effect<A, E>;342 }343 439-// ------------------------------------------------------------ pure helpers440-344 const mainRef = "refs/heads/main";345 346 const mainRefName = RefName.make(mainRef);347 445-/** The config folder, as a path prefix. */348 const configFolder = `${Brand.configDir}/`;349 448-/** How many steps a decider's land takes at most: merges, checks and lands, with re-merges. */350 const landTurns = 16;351 451-/** Whether `handle` decides for any paths in the project. */352 export const isDecider = (policy: Policy, handle: Handle) =>353 policy.deciders.some(({ handles }) =>354 handles.some((each) => sameHandle(each, handle))355 );356 457-/**458- * Whether `handle` decides for the ask's territory: a deciders entry whose459- * glob holds one of the territory's globs, each read as the path it spells460- * (`packages/**` holds `packages/parser/**`; `**` holds every territory).461- */357 export const decidesOn = (policy: Policy, ask: Ask, handle: Handle) =>358 decidersFor(359 policy,360 ask.territory.paths.map((glob) => RepoPath.make(glob))361 ).some((each) => sameHandle(each, handle));362 468-/** The handle as the policy spells it among its deciders: how decisions name them. */363 const asDecider = (policy: Policy, handle: Handle): Option.Option<Handle> =>364 Array.findFirst(365 policy.deciders.flatMap(({ handles }) => handles),366 (each) => sameHandle(each, handle)367 );368 475-/** A table's rows as this call has them: written ones in place of hydrated ones, new ones after. */369 const overlaid = <K, V extends { readonly id: K }>(370 rows: readonly V[],371 written: ReadonlyMap<K, V>372 ): readonly V[] => [2 unmodified lines375 (row) => !rows.some(({ id }) => id === row.id)376 ),377 ];378 486-/** The next id of a project's sequence: `prop-000001` after none taken. */379 const minted = (prefix: string, taken: number) =>380 `${prefix}-${String(taken + 1).padStart(6, "0")}`;381 490-/** A person's working fork, `<project>--me--<handle in lowercase>`. */382 const workingFork = (project: ProjectName, handle: Handle) =>383 RepoName.make(`${keyOf(project)}--me--${handle.toLowerCase()}`);384 494-/** The module a proposal's territory names: by its name, or by its folder. */385 const moduleOf = (policy: Policy, territory: string) =>386 Array.findFirst(387 policy.modules,388 (module) =>389 module.module === territory ||390 module.paths.some((glob) => glob === `${territory}/**`)391 );392 503-/**504- * The paths whose deciders decide a proposal: its territory's globs read as505- * paths, since opening the ask needs a decider of its territory (`openAsk`'s506- * rule); without a territory, its files outside the config folder, where507- * its check lives. The ask file's own place says nothing of its territory.508- */393 export const pathsOf = (394 policy: Policy,395 files: readonly RepoPath[],396 territory: Option.Option<string>6 unmodified lines403 onSome: ({ paths }) => paths.map((glob) => RepoPath.make(glob)),404 }),405 });406 523-/**524- * Who decides on `paths`: their deciders, else the project's own (`**`),525- * else its initializer. A decision always has someone.526- */407 export const decidersOn = (408 policy: Policy,409 paths: readonly RepoPath[],410 initializer: Handle8 unmodified lines419 };420 421 const proposedLabel = "want";422 543-/** The evidence line that names the model a proposal's files were drafted by. */423 const draftedByLabel = "drafted by";424 546-/** The platform's drafter, as the landing of an ask it drafted discloses it. */425 export const drafterOf = (model: string): AgentTrailer => ({426 harness: `${Brand.cli}-drafter`,427 model,428 verified: true,429 });430 553-/**554- * The agents an accepted proposal's landing discloses: the drafter, when555- * its decision's evidence says the files were drafted (`drafted by:556- * <model>, attempt <n> of 3`), else none.557- */431 const assistedBy = (evidence: readonly Evidence[]): readonly AgentTrailer[] =>432 Option.toArray(433 Option.map(434 Array.findFirst(evidence, ({ label }) => label === draftedByLabel),435 ({ value }) => drafterOf(value.split(", attempt ")[0] ?? value)436 )437 );438 566-/**567- * A proposal's evidence: its want, its territory, and each file it would568- * add, path by content. The decider judges the check as part of the ask, so569- * the files are shown; a sealed answer's diff never is.570- */439 const evidenceOf = (input: {440 readonly files: readonly ComposedFile[];441 readonly sealed: boolean;442 readonly territory: Option.Option<string>;17 unmodified lines460 ]461 : []),462 ];463 596-/** The files a proposal holds, read back from its decision's evidence by path. */464 const filesOf = (465 proposal: Proposal,466 evidence: readonly Evidence[]467 ): readonly ComposedFile[] =>9 unmodified lines477 const askFolder = `${configFolder}asks/`;478 479 const askSuffix = ".ask.ts";480 614-/** The ask a proposal's files open: the one whose ask file they hold. */481 export const askIdOf = (files: readonly ComposedFile[]): Option.Option<AskId> =>482 Array.findFirst(files, ({ path }) =>483 path.startsWith(askFolder) && path.endsWith(askSuffix)484 ? Schema.decodeOption(AskId)(1 unmodified line486 )487 : Option.none()488 );489 624-/** When a person claimed. */490 interface FirstClaim {491 readonly at: DateTime.Utc;492 readonly handle: Handle;493 }494 630-/** Each person's first claim in the project, for Today's newcomers. */495 const firstClaimsOf = (claims: DeciderState["claims"]): readonly FirstClaim[] =>496 Array.dedupeWith(497 Array.sort(498 claims.flatMap(({ row, state }): FirstClaim[] =>17 unmodified lines516 Match.tag("StaleBase", (stale) => Option.some(stale)),517 Match.orElse(() => Option.none())518 );519 656-/** A decision's subject an answer waits on, if it is one. */520 const answerDecisionOf = (subject: DecisionSubject) =>521 Schema.decodeUnknownOption(Schema.toType(AnswerDecision))(subject);522 660-/** A commit message's first line as its subject, the rest as its body. */523 const messageParts = (message: string) => {524 const [subject = "", ...rest] = message.trim().split("\n");525 526 return { body: rest.join("\n").trim(), subject: subject.trim() };527 };528 667-/** `message` with one more trailer in its trailer block, which `formatLanding` always ends with. */529 const withTrailer = (message: string, key: string, value: string) =>530 `${message}${key}: ${value}\n`;531 671-/**672- * The vouch file with `handle`'s lines replaced by one line: `handle`, or673- * `-handle` to denounce, and the note after a space. Every other line674- * stays as it was, comments included.675- */532 const vouchedText = (533 text: string,534 input: {535 readonly handle: Handle;22 unmodified lines558 559 return `${[...lines, `${sign}${input.handle}${note}`].join("\n")}\n`;560 };561 706-/** git's zero id: the `before` of a push that created its ref. */562 const zeroId = CommitSha.make("0".repeat(40));563 709-/**710- * The decision a move of canonical `main` the platform did not make opens:711- * `StrayPush`, whose default is revert, for the project's712- * own deciders (`**`), else its initializer, with `before` as git's zero id713- * when the push created `main`. The service mints the id; a `main` moved to714- * a landing or to the landed SHA is the platform's, and opens none.715- */564 export const strayDecision = (input: {565 readonly after: CommitSha;566 readonly before: Option.Option<CommitSha>;567 readonly id: DecisionId;15 unmodified lines583 ref: RefNameText.make("refs/heads/main"),584 }),585 });586 739-/** The id a project's next decision takes, after the ones `h` and `writes` hold. */587 export const nextDecisionId = (588 decisions: readonly Decision[],589 written: ReadonlyMap<DecisionId, Decision>590 ) => DecisionId.make(minted("dec", overlaid(decisions, written).length));591 745-/** The deadlines a project's proposals and decisions set its alarm to: each open one's expiry. */592 export const deciderDeadlines = (h: DeciderState): readonly DateTime.Utc[] => [593 ...h.proposals.flatMap(({ expiresAt, state }) =>594 state === "open" ? [expiresAt] : []595 ),1 unmodified line597 decided === undefined ? [expiresAt] : []598 ),599 ];600 755-/** A vouch a decision said yes to that did not land: logged, the decision stands. */601 const unlanded = (handle: Handle, refused: NotDecider | StaleBase) =>602 Effect.logWarning(`the vouch for ${handle} did not land`, refused);603 759-/** Who may have a proposal drafted again: its proposer, or a decider of its paths. */604 const mayDraft = (605 policy: Policy,606 row: ProjectRow,607 proposal: Proposal,5 unmodified lines613 pathsOf(policy, proposal.files, Option.fromUndefinedOr(proposal.territory)),614 row.initializer615 ).some((each) => sameHandle(each, handle));616 773-/** The events among `effects`, written; the alarm is set once settled, from every deadline. */617 const emitted = (618 writes: DeciderWrites,619 effects: readonly AttentionEffect[]620 ) => {3 unmodified lines624 }625 }626 };627 785-// ------------------------------------------------------------ the bodies786-787-/**788- * The decider-facing bodies over a project's kernel. Each write takes the789- * project's answer queue, which a finish's or an answer decision's run is790- * settled on; `expire` runs inside the alarm's own write.791- */628 export const deciders = <H extends DeciderState, W extends DeciderWrites>(629 kernel: DeciderKernel<H, W>630 ) => {631 const { name, repo } = kernel;632 797- /** The project once it is live: its landed SHA, its row and its policy. */633 const liveOf = (h: H) =>634 Option.flatMap(635 Option.all({ policy: h.policy, row: h.project }),636 ({ policy, row }) =>1 unmodified line638 ? Option.some({ landed: row.landed, policy, row })639 : Option.none()640 );641 807- /** The project row as this call has it. */642 const rowNow = (h: H, writes: W) =>643 Option.orElse(644 Option.fromUndefinedOr(writes.project.get("row")),645 () => h.project4 unmodified lines650 651 const decisionsNow = (h: H, writes: W) =>652 overlaid(h.decisions, writes.decisions);653 820- /** One more decision or finish spent from `decider`'s budget for the day. */654 const spent = (655 h: H,656 writes: W,657 input: {6 unmodified lines664 665 writes.budgetDays.set(`${row.day}|${row.decider}`, row);666 };667 835- /** A landing the platform made outside the answer queue, recorded: its row, its event, the landed SHA moved. */668 const recordLanding = (669 h: H,670 writes: W,671 landing: LandingView,16 unmodified lines688 );689 }690 });691 860- /** The text of a file at a commit of the canonical repo, or empty. */692 const textAt = (at: CommitSha, path: RepoPath) =>693 kernel694 .withPorts(695 RepoHost.use((host) =>9 unmodified lines705 ),706 Effect.orElseSucceed(() => "")707 );708 878- // ---------------------------------------------------------- proposals879-880- /** A proposal opened, with the decision that puts it to its deciders. */709 const putUp = (710 h: H,711 writes: W,712 input: {25 unmodified lines738 739 return { proposal: proposed.proposal };740 };741 914- /**915- * A proposal's next draft round started: the proposal drafting, the916- * events `effects` emit, and the row that starts its run, with the note917- * for the agent. No decision goes up until the round settles.918- */742 const startDraft = (743 h: H,744 writes: W,745 now: DateTime.Utc,49 unmodified lines795 796 return { proposal };797 });798 976- /** The proposal by `id` as this call has it. */799 const proposalNow = (h: H, writes: W, id: ProposalId) =>800 Array.findFirst(proposalsNow(h, writes), (each) => each.id === id);801 980- /** The decision that puts `proposal` to its deciders, the last one when several did. */802 const decisionOf = (h: H, writes: W, proposal: ProposalId) =>803 Array.findLast(804 decisionsNow(h, writes),805 ({ subject }) =>27 unmodified lines833 proposal,834 });835 });836 1016- /**1017- * A draft's round settled, by the pure rules: the proposal moves, and its1018- * decision goes up with the files (or the want alone) and what the draft1019- * says, or, when one is open already, takes that evidence, and the1020- * deciders of the files it now holds, in its place. A failed round that1021- * kept an earlier ready round's files keeps that decision's evidence1022- * instead, with why this round failed in place of any earlier failure,1023- * so the earlier draft can still be accepted.1024- * A stale round or a closed proposal changes nothing.1025- */837 const settledBody =838 (input: {839 readonly proposal: ProposalId;840 readonly result: DraftResult;95 unmodified lines936 937 writes.decisions.set(decision.id, decision);938 });939 1129- /** A proposal, and the files its decision holds for it (none before one goes up). */940 const proposalOf = (proposal: ProposalId) =>941 Effect.gen(function* () {942 const h = yield* kernel.read;943 18 unmodified lines962 proposal: found.value,963 };964 });965 1156- /** How many of `handle`'s proposals are open. */966 const openCountOf = (h: H, writes: W, handle: Handle) =>967 proposalsNow(h, writes).filter(968 ({ proposer, state }) => state === "open" && sameHandle(proposer, handle)969 ).length;60 unmodified lines1030 now1031 )1032 );1033 1225- // A drafted proposal reaches its deciders once its draft settles.1034 if (input.draft === true) {1035 // A proposal just opened drafts its first round: nothing refuses it.1036 return yield* Effect.orDie(1037 startDraft(h, writes, now, {71 unmodified lines1109 row,1110 });1111 });1112 1305- // ---------------------------------------------------------- landings1306-1307- /**1308- * A platform landing of `files` composed onto main, authored by `author`.1309- * A moved main, a busy repo or a blocked Lander is `StaleBase`: try again.1310- */1113 const landFiles = (1114 h: H,1115 writes: W,1116 input: {63 unmodified lines1180 1181 return landed.sha;1182 });1183 1382- /**1383- * The vouch file landed with `handle` vouched for or denounced, by1384- * `by`. A file that already says so lands nothing: the landed SHA.1385- */1184 const landVouch = (1185 h: H,1186 writes: W,1187 now: DateTime.Utc,40 unmodified lines1228 prefix: "vouch",1229 });1230 });1231 1434- /**1435- * A stray push reverted: a platform landing on top of it whose tree is1436- * `before`'s, so the stray commits stay in history, with a `Reverts:`1437- * trailer. Only `main` lands; any other ref is left for its owner.1438- */1232 const revert = (1233 h: H,1234 writes: W,1235 now: DateTime.Utc,38 unmodified lines1274 : [{ handle: input.by, role: "Decided-by" }];1275 1276 const requestId = RequestId.make(`revert-${after}`);1277 1485- // The stray commit is main's tip, and the revert's parent.1278 const main = LandedSha.make(after);1279 1280 const message = withTrailer(1281 formatLanding({46 unmodified lines1328 now1329 );1330 });1331 1540- /**1541- * A stray push adopted: its commit becomes the landed SHA, read for rules1542- * from now on, decided by `by`.1543- */1332 const adopt = (1333 h: H,1334 writes: W,1335 now: DateTime.Utc,27 unmodified lines1363 )1364 : Effect.void;1365 };1366 1579- // ---------------------------------------------------------- answers1580-1581- /** An answer's step reported, and its run started again to carry what follows. */1367 const advanceAndRun = (1368 h: H,1369 writes: W,1370 now: DateTime.Utc,15 unmodified lines1386 1387 return advanced;1388 });1389 1605- /** The answer to `ask` that waits on a finish, if one does. */1390 const awaitingFinish = (h: H, ask: AskId) =>1391 Array.findFirst(1392 h.answers,1393 ({ record, row }) =>1394 row.ask === ask && LandingState.guards.AwaitingFinish(record.landing)1395 );1396 1613- /** The answers waiting on `decision`, each told what was decided. */1397 const answerWaits = (1398 h: H,1399 writes: W,1400 now: DateTime.Utc,27 unmodified lines1428 ),1429 { discard: true }1430 );1431 1649- /** An accepted `Finish` decision: the answer waiting at its head lands, finished by `by`. */1432 const finishAt = (1433 h: H,1434 writes: W,1435 now: DateTime.Utc,22 unmodified lines1458 ),1459 }1460 );1461 1680- // ---------------------------------------------------------- decisions1681-1682- /**1683- * An accepted proposal: its files open its ask red first, asked by the1684- * proposer and decided by `by`, and the proposal is accepted. A proposal1685- * whose ask cannot open (its check is green on main, its brief lacks a1686- * field) is declined, and why is logged: the decider's choice stands. A1687- * refusal that waiting lifts (a blocked Checker or Lander, a main that1688- * moved) fails the call instead, so nothing is written and the decider1689- * can decide again. A flag, or a proposal with no ask file, is accepted1690- * and opens nothing; a decider writes the change it asks for.1691- */1462 const accept = (1463 h: H,1464 writes: W,1465 now: DateTime.Utc,67 unmodified lines1533 state: Option.isSome(refused) ? "declined" : "accepted",1534 });1535 });1536 1767- /** What a decider said yes to, besides a proposal, going ahead. */1537 const goAhead = (1538 h: H,1539 writes: W,1540 now: DateTime.Utc,26 unmodified lines1567 ),1568 Waiver: () => Effect.void,1569 });1570 1802- /**1803- * A decision taken, by a decider or by its expiry, settled: its effects1804- * (events, an ask opened, a yes gone ahead, a stray push reverted), a1805- * proposal a person declined closed, and the answers waiting on it told.1806- */1571 const settleDecided = (h: H, writes: W, now: DateTime.Utc, taken: Decided) =>1572 Effect.gen(function* () {1573 const { decision } = taken;1574 const { decided } = decision;70 unmodified lines1645 1646 return { decision: taken.decision };1647 });1648 1885- /**1886- * The alarm fired: every open proposal past its expiry expires, then1887- * every open decision past its expiry takes its default, by the1888- * platform's hand, and what follows is settled.1889- */1649 const expire = (h: H, writes: W, now: DateTime.Utc) =>1650 Effect.gen(function* () {1651 const proposals = proposalsNow(h, writes);1652 const expired = expireProposals(proposals, now).proposals;26 unmodified lines1679 { discard: true }1680 );1681 });1682 1924- // ---------------------------------------------------------- finish1925-1683 const finishBody =1684 (caller: Person, input: Parameters<DeciderApi["finish"]>[1]) =>1685 (h: H, writes: W, now: DateTime.Utc) =>1686 Effect.gen(function* () {44 unmodified lines1731 1732 const waiting = awaitingFinish(h, input.ask);1733 1734 if (Option.isNone(waiting)) {1978- // Finished before, at this head: where that answer stands now.1735 const answered = Array.findFirst(1736 h.answers,1737 ({ row }) => row.ask === input.ask && row.head === input.head1738 );24 unmodified lines1763 1764 return receiptOf(advanced.outcome);1765 }1766 2011- // The decider's commits on top: stage 1 over them, then the whole2012- // way again from the merge, already finished.1767 const stale = new StaleBase({ base: input.base, conflicts: [], main });1768 1769 const facts = yield* kernel1770 .withPorts(46 unmodified lines1817 { ask: input.ask, main, now }1818 );1819 });1820 2067- // ---------------------------------------------------------- land2068-2069- /**2070- * A landing request carried as far as it goes within this call: its2071- * landing lifecycle moved by each step's report, as the answer queue's2072- * run would move it, until it lands, is refused, or must wait.2073- */1821 const carry = (1822 input: {2076- /** The env every check job carries: the decider's change is unlanded code. */1823 readonly env: UnlandedRunEnv;1824 readonly lanes: readonly CheckLane[];2079- /** The project's record of landings, for a merge that conflicts. */1825 readonly landings: AnswerQueue["landings"];1826 readonly message: string;1827 readonly now: DateTime.Utc;2083- /** The project's run block, which every check job carries. */1828 readonly run: RunBlock;1829 },1830 step: Step,1831 turns: number95 unmodified lines1927 }),1928 Effect.flatMap(kernel.withLayers)1929 );1930 2187- // A decider lands only in the paths they decide for.1931 if (1932 facts.changes.some(1933 ({ path }) =>1934 !decidersFor(policy, [path]).some((each) =>3 unmodified lines1938 ) {1939 return yield* new NotDecider({});1940 }1941 2199- // Stages 0–1, as for an answer. A decider may change the judge2200- // where they decide: that is how a project changes its process.1942+ // Stages 0–1, minus the touched-judge refusal: a decider may change the judge where they decide.1943 const gate = yield* runGate(pushStages, facts);1944 1945 const refusals = Option.match(gate, {1946 onNone: () => [],75 unmodified lines2022 ? yield* stuck.value2023 : receiptOf(outcomeOf(state));2024 }2025 2284- // A busy repo or a blocked Checker or Lander: try again.2026 return yield* new RepoBusy({});2027 });2028 2288- // ---------------------------------------------------------- fork, vouch2289-2029 const forkBody = (caller: Person) => (h: H, writes: W, now: DateTime.Utc) =>2030 Effect.gen(function* () {2031 const live = liveOf(h);2032 40 unmodified lines2073 (h: H, writes: W, now: DateTime.Utc) =>2074 Effect.gen(function* () {2075 const policy = Option.getOrUndefined(h.policy);2076 2338- // Whoever decides for the vouch file vouches.2077 if (2078 policy === undefined ||2079 !decidersFor(policy, [policy.vouch.file]).some((each) =>2080 sameHandle(each, caller.handle)11 unmodified lines2092 2093 return { landed };2094 });2095 2358- // ---------------------------------------------------------- reads2359-2096 const todayOf = (caller: Person) =>2097 Effect.gen(function* () {2098 const h = yield* kernel.read;2099 const now = yield* DateTime.now;79 unmodified linesmodified:packages/project/src/draft-runs.ts+3 added-47 removed
1-/**2- * The `DraftRuns` port, and what a draft's run carries across the project's3- * boundary. A proposal made with `draft` (or drafted again with `draftAsk`)4- * writes a `StartDraft` outbox row, which starts one run per round through5- * this port; the run asks the project for its context (`draftContext`),6- * rehearses each attempt's files red first without landing them7- * (`rehearseOpen`, a `Rehearsal`), and reports how it ended8- * (`draftSettled`, a `DraftResult`). The run itself lives with the9- * drafter (`@repo/drafting`), which depends on this package, never the10- * reverse.11- *12- * `DraftRuns` is a `Context.Reference` whose default starts nothing, so13- * every host composes before one provides a real one.14- */1 import { AtLeastOne, ConfigFile } from "@repo/protocol/domain/common";2 import { PublicPolicy } from "@repo/protocol/domain/policy";3 import {4 LandedSha,5 unmodified lines10 } from "@repo/protocol/ids";11 import { Refusal } from "@repo/protocol/refusal";12 import { Context, Effect, Schema } from "effect";13 28-/** How many rounds one proposal may be drafted in, and attempts one round makes. */14 export const DRAFT_ROUNDS = 3;15 31-/** The most of a rehearsal's output its `Refused` carries: the tail, where a failure prints. */16 export const EXCERPT_BYTES = 4 * 1024;17 34-/**35- * One draft run: a proposal's round, in its project, with the note its36- * round was asked with. The note travels with the run (the outbox row, then37- * the run's own parameters), since a proposal keeps no note of its own.38- */18+/** The note travels with the run, since a proposal keeps no note of its own. */19 export const DraftParams = Schema.Struct({20 note: Schema.optionalKey(Schema.String),21 project: ProjectName,22 proposal: ProposalId,1 unmodified line24 });25 26 export type DraftParams = typeof DraftParams.Type;27 48-/** What starts a draft's run: the platform's durable run, or nothing by default. */28 export interface DraftStarter {50- /** Starts the run for `params`, or finds it started; safe to call twice. */29+ /** Safe to call twice. */30 readonly start: (params: DraftParams) => Effect.Effect<void>;31 }32 33 export const DraftRuns = Context.Reference<DraftStarter>("project/DraftRuns", {34 defaultValue: () => ({ start: () => Effect.void }),35 });36 58-/**59- * Why a rehearsal was refused, in the words a drafter can mend: the check60- * failed to load, passed, found no tests, failed two ways, could not run;61- * or the brief was weak, incomplete, or touched the judge.62- */37 export const Diagnosis = Schema.Literals([38 "LoadError",39 "Passed",40 "NoTests",5 unmodified lines46 ]);47 48 export type Diagnosis = typeof Diagnosis.Type;49 76-/**77- * A rehearsal of an ask's opening: the gate `accept` runs, without the78- * landing. `Red` says the check failed twice the same way on the composed79- * commit; `Refused` gives the refusal opening would give, why, and the80- * last of the check's output (at most `EXCERPT_BYTES`).81- */50 export const Rehearsal = Schema.TaggedUnion({51 Red: {52 lane: LaneName,53 signature: Schema.NonEmptyString,7 unmodified lines61 });62 63 export type Rehearsal = typeof Rehearsal.Type;64 97-/** A drafted ask's last attempt number, and the model that drafted it. */65 const attempt = {66 attempts: AtLeastOne.check(Schema.isLessThanOrEqualTo(DRAFT_ROUNDS)),67 model: Schema.NonEmptyString,68 };69 103-/**104- * How a draft's round ended: its files rehearsed red first (`Red`, with105- * the drafter's reason for the test), or no attempt did (`Failed`, with106- * the last refusal).107- */70 export const DraftResult = Schema.TaggedUnion({71 Failed: { ...attempt, refusal: Refusal },72 Red: {73 ...attempt,5 unmodified lines79 });80 81 export type DraftResult = typeof DraftResult.Type;82 121-/**122- * What a draft's run reads from the project: the landed commit it drafts123- * against, the want and its territory, the public124- * policy (never `visibility`) for the prompt's digest, and every path of125- * the canonical tree at the landed commit, for picking what the drafter126- * reads.127- */83+/** Carries the public policy only, never `visibility`. */84 export const DraftContextData = Schema.Struct({85 at: LandedSha,86 paths: Schema.Array(RepoPath),87 policy: PublicPolicy,8 unmodified linesmodified:packages/project/src/env-port.ts+2 added-48 removed
1-/**2- * The env shape's neutral port (ADR 0009): a project's public env3- * schema, its write-only values, the env its checks run with, and the scan4- * that finds a stored value where it must not be. The default is a project5- * without the visibility cartridge: no items, no values, nothing to scan6- * for. The cartridge's `ProjectEnv` parses `.env.schema` at the7- * landed SHA and seals values with the platform's master key.8- *9- * As `visibility-port.ts`: each method reads the project as the call has it10- * (`snapshot`) and returns its rows for the service to commit; nothing here11- * returns a value.12- */1 import { CheckJob } from "@repo/checks/check-runner";2 import type { EnvSchemaView } from "@repo/protocol/domain/env";3 import { RepoPath, sameHandle } from "@repo/protocol/ids";4 import type { EnvKey, Handle, LandedSha } from "@repo/protocol/ids";6 unmodified lines11 import type { ProjectSnapshot, ProjectWrites } from "./project-store.ts";12 import { noPlan, policyIn } from "./visibility-port.ts";13 import type { VisibilityPlan } from "./visibility-port.ts";14 27-/**28- * The env a check job of unlanded code carries: what the code sees in place29- * of each write-only value, and the outbound hosts whose requests the30- * platform's env gateway rewrites. Never a value, so it is what an answer's31- * run keeps (`AnswerRun.env`) and what crosses a Workflow step. The32- * `CheckJob`'s own fields, so the job's schema decides their form.33- */15+/** Never holds a value, so it may be stored and cross a Workflow step. */16 export const UnlandedRunEnv = Schema.Struct(17 Struct.pick(CheckJob.fields, ["placeholders", "proxies"])18 );19 20 export type UnlandedRunEnv = typeof UnlandedRunEnv.Type;21 40-/**41- * The env a check job carries: as for unlanded code, and for a job of42- * landed code alone, `landed` and the values opened for it. Built in43- * the call that runs the job and dropped after: never stored, never in a44- * Workflow step's output.45- */22+/** Holds opened values for landed code: never stored, never in a Workflow step's output. */23 export const RunEnv = Schema.Struct(24 Struct.pick(CheckJob.fields, ["landed", "placeholders", "proxies", "values"])25 );26 27 export type RunEnv = typeof RunEnv.Type;28 52-/** The env a job carries when the project has no write-only values: none. */29 export const noRunEnv: UnlandedRunEnv = { placeholders: [], proxies: [] };30 55-/** A project's env schema at one commit, as `envShape` shows it but for where and whose. */31 export type EnvSchemaFile = Omit<EnvSchemaView, "at" | "project">;32 58-/** Where the env schema lives: the repo's root. */33 const envFile = RepoPath.make(".env.schema");34 61-/** A write-only value set: what `setEnv` answers with, and the rows that keep it sealed. */35 export interface ValueSet {36 readonly result: {37 readonly key: EnvKey;38 readonly setAt: DateTime.Utc;1 unmodified line40 };41 readonly writes: ProjectWrites;42 }43 71-/** What `scan` searches: a text that leaves a run, or a blob an answer adds. */44 export type Scanned = { readonly text: string } | { readonly blob: Uint8Array };45 74-/** The project's env, as the project service reaches it. */46 export interface EnvPort {76- /** The env schema at a landed commit: its file, imports and items, each sensitive item with who set its value and when. */47 readonly view: (48 at: LandedSha,49 snapshot: ProjectSnapshot50 ) => Effect.Effect<EnvSchemaFile>;81- /** A write-only value for one sensitive item, sealed; never returned. */51 readonly set: (52 input: {53 readonly acknowledgeShort: boolean;54 readonly by: Person;5 unmodified lines60 ) => Effect.Effect<61 ValueSet,62 NotDecider | UnknownEnvItem | NotSensitive | ValueTooShort63 >;95- /** The env a check runs with: placeholders and proxies for unlanded code, the values only for landed code. */64 readonly runEnv: (65 input: { readonly landed: boolean },66 snapshot: ProjectSnapshot67 ) => Effect.Effect<RunEnv>;100- /** The stored value `scanned` contains, by its item's key; none when it holds none. */68 readonly scan: (69 scanned: Scanned,70 snapshot: ProjectSnapshot71 ) => Effect.Effect<Option.Option<EnvKey>>;105- /** After a landing moved the landed SHA: a `ProxyWidened` decision for each widened `@proxy`. */72 readonly onLanded: (73 input: {74 readonly after: LandedSha;75 readonly before: Option.Option<LandedSha>;2 unmodified lines78 snapshot: ProjectSnapshot79 ) => Effect.Effect<VisibilityPlan>;80 }81 116-/** Whether `handle` decides anything in the project the snapshot holds. */82 const decides = (snapshot: ProjectSnapshot, handle: Handle) =>83 Option.exists(policyIn(snapshot), (policy) =>84 policy.deciders.some(({ handles }) =>85 handles.some((each) => sameHandle(each, handle))86 )87 );88 124-/**125- * A project without the cartridge's env: no items, so no value to set (a126- * decider asking is told the item is unknown; anyone else, that only127- * deciders set values), nothing for a check but its own env, and nothing to128- * scan for.129- */89 export const noEnv: EnvPort = {90 onLanded: () => Effect.succeed(noPlan),91 runEnv: () => Effect.succeed(noRunEnv),92 scan: () => Effect.succeedNone,5 unmodified lines98 ),99 view: () => Effect.succeed({ file: envFile, imports: [], items: [] }),100 };101 143-/**144- * How a host gives the project service its env. The default is `noEnv`,145- * so a host that provides nothing runs the platform without it.146- */102 export const ProjectEnv = Context.Reference<EnvPort>("project/ProjectEnv", {103 defaultValue: () => noEnv,104 });105 151-/** The default, said out loud: a project without the cartridge's env. */106 export const NoEnv: Layer.Layer<never> = Layer.succeed(ProjectEnv, noEnv);modified:packages/project/src/events.ts+2 added-19 removed
1-/**2- * A project's events (`ProjectEvent`): what the service says happened, in3- * the order its store numbers them. Events are written in the same commit as4- * the rows that made them, and each one also goes to the projection through5- * the outbox, so the front page hears every one.6- */1 import type { Ask, AskListing } from "@repo/protocol/domain/ask";2 import type { ProjectEvent as Event } from "@repo/protocol/domain/event";3 import { ProjectEvent } from "@repo/protocol/domain/event";4 import type { Outcome } from "@repo/protocol/domain/outcome";5 unmodified lines10 type OmitEach<Union, Key extends PropertyKey> = Union extends unknown11 ? Omit<Union, Key>12 : never;13 20-/**21- * A project event before the store numbers it: every `ProjectEvent` but its22- * `seq`, which the store assigns at commit. The one type the lifecycles,23- * attention, the service and the store all write events as.24- */14 export type ProjectEventInput = OmitEach<Event, "seq">;15 27-/** Constructors and matchers for project events before the store numbers them. */16 export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();17 30-/** An ask as `listAsks`, the front page and `AskOpened` show it. */18 export const listingOf = (ask: Ask): AskListing => {19 const listing = {20 ask: ask.id,21 blockedBy: ask.blockedBy,7 unmodified lines29 ? listing30 : { ...listing, reserve: ask.reserve };31 };32 46-/** An ask opened. */33 export const askOpened = (ask: Ask, at: DateTime.Utc): ProjectEventInput =>34 ProjectEventInput.AskOpened({ ask: listingOf(ask), at });35 50-/** An answer's landing closed its ask. */36 export const askClosed = (37 ask: AskId,38 landing: LandedSha,39 at: DateTime.Utc40 ): ProjectEventInput => ProjectEventInput.AskClosed({ ask, at, landing });41 57-/** An answer was judged: its checks or its merge decided where it stands. */42 export const judged = (43 ask: AskId,44 head: CommitSha,45 outcome: Outcome,2 unmodified lines48 49 const asEvent = Schema.decodeUnknownEffect(Schema.toType(ProjectEvent));50 51 /**68- * The events as the store will number them when the same commit writes69- * them: on from `lastSeq`, in order. The service commits under the70- * project's lock, so nothing numbers an event in between.52+ * The service commits under the project's lock, so nothing numbers an event in53+ * between.54 */55 export const numbered = (56 lastSeq: number,57 events: readonly ProjectEventInput[]4 unmodified linesmodified:packages/project/src/facts.ts+2 added-46 removed
1-/**2- * The facts the gate and the rules evaluator decide over, gathered from the3- * repos through `RepoHost`: the gate's `PushFacts` for one push (its change4- * list, the lines it added, where it goes), and the rules' `EvaluationFacts`5- * at one commit (the files its finder and judge closure read, its6- * workspaces, its vouch file).7- * Neither the gate nor rule code reads a repo; the project service hands8- * them these.9- */1 import { ObjectId, RepoHost, Revision } from "@repo/artifacts/repo-host";2 import type { RepoNotFound } from "@repo/artifacts/repo-host";3 import { judgeInputs } from "@repo/checks/judge";4 import { workspacesIn } from "@repo/checks/workspaces";17 unmodified lines22 import type { EvaluationFacts } from "@repo/rules/rules-evaluator";23 import { Array, Effect, Option, Schema } from "effect";24 import type { DateTime } from "effect";25 35-/** A commit the push names that the repo does not hold. */26 export class MissingCommit extends Schema.TaggedError<MissingCommit>()(27 "MissingCommit",28 { sha: Schema.String }29 ) {}3 unmodified lines33 const asHandle = Schema.decodeUnknownOption(Handle);34 35 const asLayer = Schema.decodeUnknownOption(LayerName);36 47-/**48- * Where a push goes, read from the repo's name: `<project>`,49- * `<project>--<ask>--<handle>`, `<project>--me--<handle>` or50- * `<project>--<layer>`. Any other name is read as canonical's, which takes51- * no push.52- */37 export const targetOf = (repo: RepoName, project: ProjectName): PushTarget => {38 const [named, second, third, ...rest] = repo.split("--");39 const canonical = PushTarget.Canonical({ project });40 42 unmodified lines83 );84 85 const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);86 103-/** A `package.json` blob's `scripts`, as canonical JSON text; none when it reads as no manifest. */87 const scriptsIn = (repo: RepoName, blob: string | undefined) =>88 blob === undefined89 ? Effect.succeed("")90 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(4 unmodified lines95 )96 )97 );98 116-/** Whether the root manifest's `scripts` differ between the change's two blobs. */99 const scriptsChanged = (repo: RepoName, changes: readonly Change[]) =>100 Option.match(101 Array.findFirst(changes, (change) => change.path === "package.json"),102 {8 unmodified lines111 ),112 }113 );114 133-/** What `pushFacts` is told: the push, and what the project knows about it. */115 export interface PushInput {116 readonly ask: Option.Option<Ask>;117 readonly base: CommitSha;118 readonly claim: Option.Option<ClaimView>;138- /** How many live claims the pusher holds, for `CapReached`. */119 readonly claimsHeld: number;120 readonly head: CommitSha;121 readonly landed: LandedSha;122 readonly policy: Policy;123 readonly project: ProjectName;124 readonly pusher: Principal;125 readonly ref: string;146- /** The repo the push went to, which holds `base` and `head`. */126 readonly repo: RepoName;127 }128 150-/**151- * The gate's facts for one push: its change list from `base` to `head` (by152- * subtree ids, through the port), the lines it added, where it goes, and153- * whether it moved the root manifest's scripts. No layer paths or ratchet154- * counts yet. A commit the repo lacks is `MissingCommit`.155- */129 export const pushFacts = (130 input: PushInput131 ): Effect.Effect<PushFacts, RepoNotFound | MissingCommit, RepoHost> =>132 Effect.gen(function* () {26 unmodified lines159 target: targetOf(input.repo, input.project),160 } satisfies PushFacts;161 });162 190-// ------------------------------------------------------------ rules facts191-192-/** How many of a repo's trees or blobs the facts read at once. */163 const READS_AT_ONCE = 16;164 195-/** A blob or a folder of a commit's tree: its path from the root, and its id. */165 interface Located {166 readonly path: string;167 readonly sha: ObjectId;168 }169 201-/**202- * Every blob under the tree `root`, by its path from the root: each folder203- * read once, a level at a time. A submodule is no file.204- */170 const blobsUnder = (171 repo: RepoName,172 root: ObjectId173 ): Effect.Effect<readonly Located[], RepoNotFound, RepoHost> => {33 unmodified lines207 208 return level([{ path: "", sha: root }], []);209 };210 246-/** What `evaluationFacts` is told besides the commit. */211 export interface FactsInput {212 readonly initializer: Handle;213 readonly now: DateTime.Utc;214 readonly project: ProjectName;251- /** Where the vouch file is, as the policy before this commit says. */215 readonly vouchFile: RepoPath;216 }217 255-/**256- * The rules' facts at one commit of `repo`: every file of its tree, with257- * the text of each one the run-block finder or the judge closure reads258- * (`@repo/checks`' `judgeInputs`, which the CLI's local check and hook259- * gather through too), the workspaces its root manifest declares, and its260- * vouch file. The seed is the commit's own first eight hex digits, so the261- * same commit always sees the same randomness. A commit the repo lacks gives262- * empty facts: the evaluation then decides on its config folder alone.263- */218+// The seed is the commit's first eight hex digits, so the same commit always219+// sees the same randomness.220 export const evaluationFacts = (221 repo: RepoName,222 at: CommitSha,223 input: FactsInput55 unmodified linesmodified:packages/project/src/front-page.ts+1 added-20 removed
1-/**2- * The `FrontPage` port: the read side of the projection every project feeds3- * (the write side is `Projection`, whose rows come from each project's4- * outbox). The front page and a person's credits read from here without5- * waking any project. The project list reads its rows here too, but a listed6- * project's `posture` is the fallback only: a list's callers read each7- * project's posture from its own ledger at list time (`withStandingPosture`),8- * since its standing changes without any event this read model hears, and9- * keep this one for a project whose ledger could not be read.10- *11- * Adapters: `/memory` here, seeded from data, for tests; `projection-d1`12- * over D1 in the Worker.13- */1 import type { Reserve } from "@repo/protocol/domain/ask";2 import type {3 FrontPageEntry,4 ProjectListing,2 unmodified lines7 import type { Handle, KindName } from "@repo/protocol/ids";8 import { Context } from "effect";9 import type { Effect } from "effect";10 24-/** Which open asks to list: one kind, or the ones held for newcomers or for people. */11 export interface FrontPageFilter {12 readonly kind?: KindName;13 readonly reserved?: Reserve;14 }15 16 export class FrontPage extends Context.Service<17 FrontPage,18 {33- /**34- * Every project, with how many asks it has open and the posture last35- * projected (the fallback for its standing posture).36- */19+ /** A listing's `posture` is a fallback only: callers read each project's own ledger (`withStandingPosture`). */20 readonly projects: () => Effect.Effect<readonly ProjectListing[]>;38- /** The open asks across every project, as the anonymous viewer sees them. */21 readonly entries: (22 filter: FrontPageFilter23 ) => Effect.Effect<readonly FrontPageEntry[]>;42- /** A person's credits across every project, by project, area and role. */24 readonly credits: (25 handle: Handle26 ) => Effect.Effect<readonly CreditSummary[]>;27 }1 unmodified linemodified:packages/project/src/generated.ts+7 added-47 removed
1-/**2- * A project's generated files after a landing: the3- * contribute skill and the AGENTS.md block a stranger's agent reads, kept4- * current without anyone writing them. When a landing changes what they say5- * (the run block, the kinds, the judge closure, anything the generator reads6- * from the policy), the platform follows it with a landing of its own that7- * holds only the regenerated files: never folded into the landing that8- * changed the config ("land only the checked tree"), and never made when9- * nothing they say changed.10- *11- * Host-free and generator-free: the generator comes in as a function12- * (`Generate`), since `packages/project` may not import `@repo/agent-kit`.13- * The platform gives the project its generator through14- * `ProjectGenerator`; a project given none generates nothing.15- */1 import { Brand } from "@repo/brand";2 import { formatLanding } from "@repo/git/trailers";3 import type { Credit } from "@repo/protocol/domain/credit";4 import type { LandingView } from "@repo/protocol/domain/landing";4 unmodified lines9 10 import { decidersFor } from "./attention/decisions.ts";11 import { platformHandle } from "./attention/effects.ts";12 28-/** One file a generator makes: where it goes, and every byte of it. */13 export interface GeneratedFile {14 readonly path: string;15 readonly content: string;16 }17 34-/** A file's text in the tree a landing left, if the tree has it. */18 export type ReadAt = (path: string) => Effect.Effect<Option.Option<string>>;19 20 /**38- * Every generated file for one policy at one landing. `read` gives a file's39- * text at that landing, for a file the generator writes into rather than40- * over (AGENTS.md, whose text outside its block is the project's own).21+ * `read` is for files written into rather than over (AGENTS.md: text outside22+ * its block is the project's own).23 */24 export type Generate = (input: {25 readonly project: ProjectName;26 readonly policy: Policy;27 readonly landed: LandedSha;28 readonly read: ReadAt;29 }) => Effect.Effect<readonly GeneratedFile[]>;30 49-/** The platform's landing that follows another with the regenerated files. */31 export interface FollowUp {51- /** The platform: it writes the files, nobody's answer does. */32 readonly author: Handle;53- /** `Decided-by` the decider whose landing changed what the files say. */33 readonly credits: readonly Credit[];55- /** The files whose text the tree does not hold yet, and only those. */34 readonly files: Array.NonEmptyReadonlyArray<GeneratedFile>;57- /** The whole commit message, trailers included. */35 readonly message: string;59- /** `gen-<landed>`: the same follow-up landed again finds the first one. */36+ /** The same follow-up landed again finds the first one. */37 readonly requestId: RequestId;38 }39 40 /**64- * How a host gives a project its generator (`@repo/agent-kit`'s, in the65- * platform). The default makes no files, so a project given none follows66- * no landing with one of its own.41+ * The default makes no files, so a project given none gets no follow-up42+ * landing.43 */44 export const ProjectGenerator = Context.Reference<Generate>(45 "project/ProjectGenerator",46 { defaultValue: () => () => Effect.succeed([]) }47 );48 73-/** The request a follow-up of the landing at `landed` lands as. */49 export const generatedRequestId = (landed: LandedSha) =>50 RequestId.make(`gen-${landed}`);51 77-/** Where the config lives: whoever decides for it decides what the files say. */52 const configPath = RepoPath.make(`${Brand.configDir}/project.ts`);53 80-/**81- * Who the follow-up credits: the landing's `Decided-by`, else its author82- * when they decide for the config, else the person who made the project.83- */54 const deciderOf = (input: {55 readonly after: Policy;56 readonly initializer: Handle;57 readonly landing: LandingView;16 unmodified lines74 () => input.initializer75 );76 };77 108-/** Whether two generations say the same, file for file. */78 const sameFiles = (79 one: readonly GeneratedFile[],80 other: readonly GeneratedFile[]81 ) =>21 unmodified lines103 subject: "Regenerate the contribute skill and the AGENTS.md block",104 });105 106 /**138- * The landing that follows `landing` with the regenerated files, or none.139- * None when the generator makes nothing, when the policy before the landing140- * gave the same files as the policy after it (the landing changed nothing141- * they say), or when the landed tree already holds every file as generated142- * (a replay after the follow-up landed, or a landing that brought them).143- * The first adoption has no policy before it, so it is followed unless its144- * tree holds the files already. The same input always gives the same files.107+ * Never folded into the landing that changed the config: the follow-up holds108+ * only the regenerated files, and is none when nothing they say changed.109 */110 export const generatedFollowUp = (111 input: {112 readonly project: ProjectName;149- /** The person who made the project: credited when no one else decided. */113 readonly initializer: Handle;151- /** The policy before the landing; none for the first adoption. */114 readonly before: Option.Option<Policy>;153- /** The policy read at the landing. */115 readonly after: Policy;116 readonly landing: LandingView;156- /** A file's text at the landed SHA. */117 readonly read: ReadAt;118 },119 generate: Generate120 ): Effect.Effect<Option.Option<FollowUp>> =>36 unmodified linesmodified:packages/project/src/lander.ts+7 added-75 removed
1-/**2- * The `Lander` port: the one way an answer's head is merged onto3- * main, a decider's ask files are composed onto it, a checked tree lands on4- * canonical `main` as a platform commit, and the config folder is read at a5- * landed commit. The Lander is trusted and runs no project code.6- *7- * Three additions to the port as first drawn: `land`'s `rebuild`, since `merge`8- * and `land` run in separate calls (the Answer Workflow's steps), so a9- * stateless adapter rebuilds the tree it lands; `land`'s `verdict`, the note10- * written after main moves; and `compose`, for running an ask's check red11- * first before the ask opens.12- *13- * Adapters: `/memory` (scripted, for tests) and `/isogit` (isomorphic-git over14- * `RepoHost`, the fallback until the container Lander in `apps/sandbox`15- * passes).16- */1 import { RefName } from "@repo/artifacts/repo-host";2 import { Brand } from "@repo/brand";3 import type { Change } from "@repo/git/tree-diff";4 import type { Verdict } from "@repo/protocol/domain/answer";16 unmodified lines21 import type { Array, Effect, Option } from "effect";22 23 export type { Change } from "@repo/git/tree-diff";24 41-/**42- * The mirror of canonical `main` (ADR 0005): it moves only after43- * `main` did, in its own push, and only to the commit `main` points at.44- */25+/** Moves only after `main` did, in its own push, and only to the commit `main` points at. */26 export const landedRef = RefName.make(`${Brand.refsPrefix}landed`);27 47-/**48- * Where a composed commit waits, in the canonical repo, for a Checker to49- * fetch it by id. It is never `main`.50- */28+/** Where a composed commit waits for a Checker to fetch it by id; never `main`. */29 export const composeRef = (tree: TreeSha) =>30 RefName.make(`${Brand.refsPrefix}compose/${tree}`);31 54-/** An answer's head to merge onto canonical `main`. */32 export interface MergeJob {56- /** The canonical repo. */33 readonly repo: RepoName;58- /** Where canonical `main` stood when the merge was asked for. */34 readonly main: LandedSha;60- /** The commit the answer was made on. */35 readonly base: CommitSha;36 readonly head: CommitSha;63- /** The claim's fork, which holds the answer's commits. */37 readonly fork: RepoName;38 }39 67-/** An answer merged onto main: the tree to check, and what the answer changed. */40 export interface Merged {41 readonly tree: TreeSha;70- /** The answer's changes against its base, not main's. */42+ /** Against its base, not main's. */43 readonly changes: readonly Change[];44 }45 74-/** One file a decider adds at its path, such as an ask file or its check. */46 export interface ComposedFile {47 readonly path: RepoPath;48 readonly content: string;49 }50 80-/**81- * How a stateless adapter rebuilds the tree it lands: an answer's merge,82- * a decider's files composed onto main, or an existing commit's tree (a83- * revert). The rebuilt tree must be the job's `tree`.84- */51 export type Rebuild = Data.TaggedEnum<{52 Merge: {53 readonly fork: RepoName;54 readonly base: CommitSha;4 unmodified lines59 }>;60 61 export const Rebuild = Data.taggedEnum<Rebuild>();62 97-/** A checked tree to land on canonical `main` as a platform commit. */63 export interface LandJob {64 readonly repo: RepoName;100- /** The `main` the tree was made and checked on: the push's compare-and-swap. */65+ /** The push's compare-and-swap: a moved `main` makes the land `StaleBase`. */66 readonly main: LandedSha;67 readonly tree: TreeSha;103- /** The accountable person: the commit's author. The platform commits it. */68 readonly author: Handle;105- /**106- * The whole message, trailers included (`formatLanding`), with the107- * `Request-Id` trailer that makes a second land of the same request find108- * the first one's commit.109- */69+ /** Its `Request-Id` trailer lets a second land of the same request find the first one's commit. */70 readonly message: string;71 readonly requestId: RequestId;72 readonly rebuild: Rebuild;113- /** The note written on the new commit once `main` has moved. */73 readonly verdict: Option.Option<Verdict>;74 }75 117-/** Bookkeeping written after `main` moved, each in its own push. */76 export type Bookkeeping = "mirror" | "notes";77 120-/**121- * A landing: the new tip of `main`, and the bookkeeping that did not get122- * written. A pending item never fails the landing; the service queues it in123- * the outbox and lands it again later.124- */78+/** A pending item never fails the landing; the outbox lands it again later. */79 export interface Landed {80 readonly sha: LandedSha;81 readonly pending: readonly Bookkeeping[];82 }83 130-/** A decider's files to compose onto canonical `main`, so an ask's check can run red first. */84 export interface ComposeJob {85 readonly repo: RepoName;86 readonly main: LandedSha;87 readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;88 }89 137-/** Main with the files added: its tree, and the commit a Checker fetches it by. */90 export interface Composed {91 readonly tree: TreeSha;140- /** On `composeRef(tree)` in the canonical repo; its parent is `main`. */92 readonly commit: CommitSha;93 }94 144-/** The config folder to read at one landed commit. */95 export interface BundleJob {96 readonly repo: RepoName;97 readonly at: LandedSha;98 }99 100 export class Lander extends Context.Service<101 Lander,102 {153- /**154- * The answer's head merged three ways onto `main` (its base the merge155- * base), or `StaleBase` with the paths that conflict. An adapter whose156- * Checker fetches the tree keeps it where the Checker reaches: the157- * sandbox Lander pushes a commit of it to the fork's158- * `${Brand.refsPrefix}merge/<tree>`.159- */103 readonly merge: (104 job: MergeJob105 ) => Effect.Effect<Merged, StaleBase | VerifierBlocked>;163- /**164- * One commit on canonical `main` whose parent is `main` and whose tree is165- * `tree`, pushed with a non-force compare-and-swap: if `main` moved, the166- * land is `StaleBase`, never a force push. Then, each in its own push,167- * the mirror ref and the verdict note. A second land of the same request168- * returns the first one's commit.169- */106+ /** A non-force compare-and-swap push; a second land of the same request returns the first one's commit. */107 readonly land: (108 job: LandJob109 ) => Effect.Effect<Landed, StaleBase | RepoBusy | VerifierBlocked>;173- /** `main` with the files added, pushed to `composeRef(tree)`; `main` never moves. */110 readonly compose: (111 job: ComposeJob112 ) => Effect.Effect<Composed, VerifierBlocked>;177- /**178- * Every file under the config folder at `at`, for the rules evaluator.179- * No folder gives no modules: the project runs on the defaults.180- */113 readonly bundleRules: (114 job: BundleJob115 ) => Effect.Effect<ConfigBundle, VerifierBlocked>;116 }1 unmodified linemodified:packages/project/src/landing.ts+3 added-90 removed
1-/**2- * The landing lifecycle: one answer request's way from the queue to main3- * (ADR 0012). A pure `transition(state, command, now)` returns the next state4- * and the effects the project service settles; it reads no clock and calls no5- * port. A command that does not apply to a state changes nothing, so a replay6- * converges (principle 8).7- */1 import { AgentTrailer, Credit } from "@repo/protocol/domain/credit";2 import type { CreditRole } from "@repo/protocol/domain/credit";3 import type { Choice } from "@repo/protocol/domain/decision";4 import { DecisionSubject } from "@repo/protocol/domain/decision";23 unmodified lines28 import { Array, Data, DateTime, Duration, Match, Option, Schema } from "effect";29 30 import { ProjectEventInput } from "./events.ts";31 39-/** How many times a moved main may send an answer back to merge before it is refused as stale. */32 export const maxRemerges = 3;33 42-/**43- * One path an answer's merge changed. Structurally the gate's and git's44- * `Change`, so the service passes one where the other is expected.45- */34+/** Structurally the gate's and git's `Change`, so either passes where the other is expected. */35 export const Change = Schema.Struct({36 after: Schema.optionalKey(BlobSha),37 before: Schema.optionalKey(BlobSha),38 path: RepoPath,1 unmodified line40 });41 42 export type Change = typeof Change.Type;43 55-/**56- * An admitted answer, as the gate let it through: who answers which ask from57- * which fork, and the credit its landing will carry.58- */44 export const Request = Schema.Struct({45 answerer: Handle,46 /** Absent for a decider's own landing. */47 ask: Schema.OptionFromOptionalKey(AskId),48 assisted: Schema.Array(AgentTrailer),49 base: CommitSha,65- /**66- * The credit trailers the landing carries; a finish adds `Finished-by`, and67- * an accepted decision `Decided-by`.68- */50 credits: Schema.Array(Credit),51 fork: RepoName,52 head: CommitSha,53 project: ProjectName,1 unmodified line55 });56 57 export type Request = typeof Request.Type;58 78-/**79- * A decision an answer can wait on. Declining one refuses the answer with the80- * refusal it stands for.81- */59 export const AnswerDecision = Schema.Union([60 DecisionSubject.cases.PostureChange,61 DecisionSubject.cases.RaiseRatchet,62 DecisionSubject.cases.Waiver,63 ]).pipe(Schema.toTaggedUnion("_tag"));64 65 export type AnswerDecision = typeof AnswerDecision.Type;66 90-/** A decision the answer waits on, with the id the service minted for it. */67 export const PendingDecision = Schema.Struct({68 id: DecisionId,69 subject: AnswerDecision,70 });1 unmodified line72 export type PendingDecision = typeof PendingDecision.Type;73 74 const Count = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));75 100-// What every state between the queue and main carries: the main it works101-// against, how often a moved main sent it back, and how often a port retried.76 const underway = {77 attempt: Count,78 main: LandedSha,79 remerges: Count,1 unmodified line81 };82 83 const checkedFields = { ...underway, tree: TreeSha };84 111-/** Where one answer request stands on its way to main. */85 export const LandingState = Schema.TaggedUnion({113- /** Passed its checks, and waits on decisions; a finish may follow. */86 AwaitingDecision: {87 ...checkedFields,88 decisions: Schema.NonEmptyArray(PendingDecision),89 finish: AskKind.fields.finish,90 },119- /** Passed its checks, and waits for a decider's finish. */91 AwaitingFinish: checkedFields,121- /** The merged tree is being checked. */92 Checking: { ...checkedFields, changes: Schema.Array(Change) },93 Landed: { request: Request, sha: LandedSha },124- /** Passed every stage; the platform is landing the tree on main. */94 Landing: checkedFields,126- /** Being merged onto `main`. */95 Merging: underway,96 Queued: { request: Request },97 Refused: { refusals: Schema.NonEmptyArray(Refusal), request: Request },130- /** Passed the gate, and waits for its parent ask to land first. */98 WaitingOnParent: { parent: AskId, request: Request },99 });100 101 export type LandingState = typeof LandingState.Type;102 136-/** What the service tells a landing: a port's answer, a person's decision, or the queue's go. */103 export type LandingCommand = Data.TaggedEnum<{138- /** The queue started the request against the landed main. */104 Start: { readonly main: LandedSha };140- /** The request's ask waits on its parent; `Start` resumes it. */105 Wait: { readonly parent: AskId };142- /** The merge onto `main` came out clean. */106 Merged: {107 readonly changes: readonly Change[];108 readonly main: LandedSha;109 readonly tree: TreeSha;110 };148- /**149- * The merge onto `main` conflicted in these paths; `movedBy` names the150- * landing that last changed each one the step found.151- */111 MergeConflict: {112 readonly conflicts: readonly RepoPath[];113 readonly main: LandedSha;114 readonly movedBy?: Array.NonEmptyReadonlyArray<MovedBy>;115 };157- /** The checks judged `tree`. */116 Checked: {117 readonly decisions: readonly PendingDecision[];118 readonly finish: AskKind["finish"];119 readonly refusals: readonly Refusal[];120 readonly tree: TreeSha;121 };164- /** A decider finished the answer. */122 Finished: { readonly by: Handle };166- /** Decider `by` decided one of the decisions the answer waits on. */123 Decided: {124 readonly by: Handle;125 readonly choice: Choice;126 readonly decision: DecisionId;127 };172- /** Landing found main moved from `from`, the main it landed against, to `main`. */128 MainMoved: { readonly from: LandedSha; readonly main: LandedSha };174- /** The landing is on main at `sha`. */129 LandedOk: { readonly sha: LandedSha };176- /** The repo was busy with another push during landing attempt `attempt`. */130 Busy: { readonly attempt: number };178- /**179- * A port answered `VerifierBlocked` during attempt `attempt`: retried with180- * backoff, never counted against the answerer.181- */131+ /** Retried with backoff, never counted against the answerer. */132 Blocked: { readonly attempt: number };133 }>;134 135 export const LandingCommand = Data.taggedEnum<LandingCommand>();136 187-/** What the service runs for a landing: the transition only describes it. */137 export type LandingEffect = Data.TaggedEnum<{138 Merge: {139 readonly base: CommitSha;140 readonly fork: RepoName;1 unmodified line142 readonly main: LandedSha;143 };144 RunChecks: { readonly tree: TreeSha };145 Land: { readonly main: LandedSha; readonly tree: TreeSha };197- /** Run the state's `pendingEffects` again at `at`. */146 Retry: { readonly at: DateTime.Utc };147 Emit: { readonly event: ProjectEventInput };200- /** Record the landing: close the ask, answer the claim, move the landed SHA. */148 Record: { readonly sha: LandedSha };149 }>;150 151 export const LandingEffect = Data.taggedEnum<LandingEffect>();152 206-/** One step of a landing: the state it reached and the effects to settle. */153 export interface Step {154 readonly effects: readonly LandingEffect[];155 readonly state: LandingState;156 }23 unmodified lines180 request,181 tree,182 });183 238-/** How long a retry waits after attempt `attempt`: a second, doubling, up to five minutes. */184 export const backoff = (attempt: number): Duration.Duration =>185 Duration.millis(Math.min(1000 * 2 ** attempt, 5 * 60 * 1000));186 242-/**243- * The port call a state waits on: the service runs it when the state is244- * entered, and again at a `Retry`.245- */187 export const pendingEffects = (state: LandingState): readonly LandingEffect[] =>188 LandingState.matchOrElse<readonly LandingEffect[]>(189 state,190 {25 unmodified lines216 217 const start = (request: Request, main: LandedSha): Step =>218 enter(Merging.make({ attempt: 0, main, remerges: 0, request }));219 279-// A port answered `Busy` or `VerifierBlocked` for this attempt: the same280-// state waits, then runs its port call again. A report for another attempt281-// is a replay, and changes nothing.220 const retry = (221 state: typeof Checking.Type | typeof Landing.Type | typeof Merging.Type,222 attempt: number,223 now: DateTime.Utc11 unmodified lines235 236 const isFinished = (request: Request) =>237 request.credits.some(({ role }) => role === "Finished-by");238 301-// The landing credits a person once in each role, however often they act in it.239 const credit = (request: Request, role: CreditRole, handle: Handle): Request =>240 request.credits.some(241 (given) => given.role === role && given.handle === handle242 )243 ? request244 : { ...request, credits: [...request.credits, { handle, role }] };245 309-// Every stage passed but the human one: wait on each decision first, then on310-// a finish the kind requires and nobody gave yet, then land.246 const human = (247 passed: Passed,248 decisions: readonly PendingDecision[],249 finish: AskKind["finish"]12 unmodified lines262 })263 ),264 });265 331-/** The refusal a merge that conflicted stands for, naming who moved each path the step found. */266 const staleOn = (267 base: CommitSha,268 {269 conflicts,4 unmodified lines274 movedBy === undefined275 ? new StaleBase({ base, conflicts, main })276 : new StaleBase({ base, conflicts, main, movedBy });277 344-/** The refusal a declined decision stands for. */278 const declined = (subject: AnswerDecision): Refusal =>279 AnswerDecision.match(subject, {280 PostureChange: ({ from, to }) => new PostureChange({ from, to }),281 RaiseRatchet: ({ after, before, ratchet, territory }) =>71 unmodified lines353 state: Landed.make({ request, sha }),354 };355 };356 424-// Main moved under the landing. A report about another main is a replay. A425-// clean re-merge goes back through the checks; past the limit it is stale.357 const moved = (358 state: typeof Landing.Type,359 { from, main }: { readonly from: LandedSha; readonly main: LandedSha }360 ): Step => {14 unmodified lines375 })376 );377 };378 448-/**449- * One step of a landing. A command that does not apply to the state, or450- * reports on another main, tree, attempt or decision than the state is at,451- * returns the state as it was with no effects: replays and late duplicates452- * converge. Landed and Refused never move.453- */379+/** A command that does not apply, or reports on another main, tree, attempt or decision, changes nothing: replays converge. */380 export const transition = (381 state: LandingState,382 command: LandingCommand,383 now: DateTime.Utc71 unmodified lines455 Match.orElse(() => stay(waiting))456 ),457 });458 533-/** Where the answer stands, as `status`, `verdict` and MCP report it. */459 export const outcomeOf = (state: LandingState): Outcome =>460 LandingState.match<Outcome>(state, {461 AwaitingDecision: ({ decisions }) =>462 Outcome.cases.AwaitingDecision.make({ decision: decisions[0].id }),463 AwaitingFinish: () => Outcome.cases.AwaitingFinish.make({}),464 Checking: () => Outcome.cases.Checking.make({ stage: "checks" }),465 Landed: ({ sha }) => Outcome.cases.Landed.make({ sha }),541- // Past every stage: the landing closes the last one.466 Landing: () => Outcome.cases.Checking.make({ stage: "human" }),467 Merging: () => Outcome.cases.Checking.make({ stage: "merge" }),468 Queued: () => Outcome.cases.Checking.make({ stage: "merge" }),469 Refused: ({ refusals }) => Outcome.cases.Refused.make({ refusals }),470 WaitingOnParent: ({ parent }) =>471 Outcome.cases.WaitingOnParent.make({ ask: parent }),472 });473 550-/**551- * The project's landing queue, as a value the store persists: requests land552- * one at a time, in the order their checks passed.553- */474 export const LandingQueue = Schema.Struct({555- /** The request whose landing is underway. */475 active: Schema.OptionFromOptionalKey(RequestId),476 order: Schema.Array(RequestId),477 });478 1 unmodified line480 481 const isActive = (queue: LandingQueue, id: RequestId) =>482 Option.contains(queue.active, id);483 565-/** Adds a request to the back of the queue; a request already in it stays where it is. */484 export const enqueue = (queue: LandingQueue, id: RequestId): LandingQueue =>485 isActive(queue, id) || queue.order.includes(id)486 ? queue487 : { ...queue, order: [...queue.order, id] };488 571-/** Admits the request at the front, unless one is already landing. */489 export const next = (490 queue: LandingQueue491 ): {492 readonly admit: Option.Option<RequestId>;8 unmodified lines501 queue: { active: Option.some(front), order: rest },502 }),503 });504 588-/**589- * Frees the slot once a request's landing is over (landed, refused or sent590- * back to merge), or drops a request that leaves before its turn.591- */505 export const settle = (queue: LandingQueue, id: RequestId): LandingQueue =>506 isActive(queue, id)507 ? { ...queue, active: Option.none() }508 : { ...queue, order: queue.order.filter((waiting) => waiting !== id) };modified:packages/project/src/migrate.ts+4 added-68 removed
1-/**2- * A migrate ask's family: one ask that moves every use of a name3- * to another opens, when its callers sit in two or more of the project's4- * modules, as one child ask per module with callers, each with that module5- * as its territory and "no callers in this module" as its check, and a6- * delete child that waits on every child and checks the name is gone. The7- * children's territories are disjoint, so their claims never overlap and8- * their answers re-merge cleanly through the serial landing queue; the9- * parent closes when its last child lands.10- *11- * Pure: the callers are counted by the project's own command (its stdout is12- * `CallerCount`), never by a scan here, and the service lands the family and13- * moves it after each landing.14- */1 import { Brand } from "@repo/brand";2 import { matchAny } from "@repo/gate/glob";3 import type { Ask } from "@repo/protocol/domain/ask";4 import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";3 unmodified lines8 import type { Territory } from "@repo/protocol/domain/territory";9 import { AskId, RatchetName, RepoPath } from "@repo/protocol/ids";10 import { Array, Option, Schema } from "effect";11 26-/**27- * What a migrate ask's count command prints: every caller of the name, and28- * the callers in each module, by the module's name.29- */12 export const CallerCount = Schema.Struct({13 byModule: Schema.Record(Schema.String, NoneOrMore),14 total: NoneOrMore,15 });16 17 export type CallerCount = typeof CallerCount.Type;18 37-/** A count command's stdout, read as its `CallerCount`. */19 export const callerCountOf = Schema.decodeUnknownOption(20 Schema.fromJsonString(CallerCount)21 );22 42-/** Whether two counts are the same: the same total, and the same callers in every module. */23 export const sameCount = (one: CallerCount, other: CallerCount): boolean =>24 one.total === other.total &&25 Array.dedupe([26 ...Object.keys(one.byModule),1 unmodified line28 ]).every(29 (module) => (one.byModule[module] ?? 0) === (other.byModule[module] ?? 0)30 );31 52-/** A migrate ask's check: the name it moves from, where to, and the command that counts callers. */32 type MigrateCheck = Extract<CheckSpec, { readonly _tag: "Migrate" }>;33 55-/** One file the family adds to the config folder. */34 export interface FamilyFile {35 readonly content: string;36 readonly path: RepoPath;37 }38 61-/** A migrate ask split into its family, and what its opening lands. */39 export interface MigrateFamily {63- /** The migrate ask, blocked by every child and the delete child. */40 readonly parent: Ask;65- /** One child per module with callers, in the policy's module order. */41 readonly children: Array.NonEmptyReadonlyArray<Ask>;67- /** The last child: the name is gone. Blocked by every child until they land. */42 readonly deleteChild: Ask;69- /** The children's and the delete child's ask files, in that order. */43 readonly files: Array.NonEmptyReadonlyArray<FamilyFile>;71- /** The callers ratchet the opening records, at the counted total. */44 readonly ratchet: {45 readonly name: RatchetName;46 readonly baseline: number;47 };48 }49 78-/** `@burrow/http-kit` → `burrow-http-kit`: a name an ask id can carry. */50 const slug = (name: string) =>51 name52 .toLowerCase()53 .replaceAll(/[^a-z0-9]+/gu, "-")54 .replaceAll(/^-+|-+$/gu, "");55 85-/**86- * The id of a family's child in `module`: `drop-legacy-fetch-p1`. It never87- * holds `--`, which repo names keep as their separator.88- */56+/** Never holds `--`, which repo names keep as their separator. */57 export const childId = (parent: AskId, module: string): AskId =>58 AskId.make(`${parent}-${slug(module) || "root"}`);59 92-/** The id of a family's delete child: `drop-legacy-fetch-delete`. */60 export const deleteChildId = (parent: AskId): AskId =>61 AskId.make(`${parent}-delete`);62 96-/** The ratchet on a name's callers: `legacyFetch` → `callers-legacyfetch`. */63 export const callersRatchet = (from: SymbolName): RatchetName =>64 RatchetName.make(`callers-${slug(from) || "name"}`);65 100-/** What an ask still waits on: each ask it is blocked by that has not closed. */66 export const remainingBlockers = (67 ask: Ask,68 asks: ReadonlyMap<AskId, Ask>69 ): readonly AskId[] =>70 ask.blockedBy.filter((blocker) => asks.get(blocker)?.state !== "closed");71 107-/** Whether a family is done: it has children, and every one has closed. */72 export const familyClosed = (73 parent: AskId,74 asks: ReadonlyMap<AskId, Ask>75 ): boolean => {1 unmodified line77 78 return members.length > 0 && members.every(({ state }) => state === "closed");79 };80 117-/**118- * The modules a territory spans: the one it names, or every module whose119- * paths its globs all cover (`packages/**` covers `packages/p1/**`).120- */81 export const modulesWithin = (82 territory: Territory,83 modules: readonly Territory[]84 ): readonly Territory[] => {5 unmodified lines90 paths.every((glob) => matchAny(territory.paths, glob))91 );92 };93 134-/**135- * The callers an ask's own check counts: in its module, when its territory136- * names one; in the modules it spans, when it spans some but not all;137- * everywhere, when it spans them all or none (a repo with no modules).138- */94+/** In its module when the territory names one; in the modules it spans when some but not all; else everywhere. */95 export const callersIn = (96 territory: Territory,97 counts: CallerCount,98 modules: readonly Territory[]7 unmodified lines106 0107 );108 };109 154-/**155- * The ratchet a migrate ask's callers are counted by on every answer while156- * it is open: its count command's `total`, over the whole project.157- */110 export const callersSpec = (check: MigrateCheck): RatchetSpec => ({111 measure: RatchetMeasure.cases.Metric.make({112 command: check.count,113 path: JsonPath.make("$.total"),114 }),115 name: callersRatchet(check.from),116 });117 166-/** The callers ratchets of every migrate ask still open, one per name. */118 export const callersSpecs = (asks: Iterable<Ask>): readonly RatchetSpec[] =>119 Array.dedupeWith(120 [...asks].flatMap(({ check, state }) =>121 CheckSpec.guards.Migrate(check) && state !== "closed"9 unmodified lines131 `// A child of the migrate ask ${parent}, written by ${Brand.name} when it opened.`;132 133 const sdk = quoted(`${Brand.cliPackage}/rules`);134 184-/** An object literal's lines, each `key: value,`, indented by two. */135 const fields = (entries: readonly (readonly [string, string])[]) =>136 entries.map(([key, value]) => ` ${key}: ${value},`);137 188-/**189- * A child's file, through the sdk's `kinds.migrate` when the parent is of190- * that kind, else through a kind of the parent's name made in the file.191- */138 const childFile = (child: Ask, check: MigrateCheck, parent: AskId) => {139 const stated: (readonly [string, string])[] = [140 ["parent", quoted(parent)],141 ["territory", `territory.package(${quoted(child.territory.module)})`],37 unmodified lines179 "",180 ].join("\n");181 };182 237-/**238- * The delete child's file: the sdk has no `symbolAbsent` builder, so the239- * file makes a kind of the parent's name whose check is the name gone.240- */183+/** The sdk has no `symbolAbsent` builder, so the file makes its own kind whose check is the name gone. */184 const deleteFile = (child: Ask, check: MigrateCheck, parent: AskId) =>185 [186 header(parent),187 `import { kind } from ${sdk};`,18 unmodified lines206 207 const callersOf = (count: number) =>208 count === 1 ? "1 caller" : `${count} callers`;209 267-/** A child's want: `p1: 5 callers of legacyFetch → http.get`. */210 const childWant = (module: string, count: number, check: MigrateCheck) =>211 check.to === undefined212 ? `${module}: ${callersOf(count)} of ${check.from} to remove`213 : `${module}: ${callersOf(count)} of ${check.from} → ${check.to}`;214 273-/**274- * Splits a migrate ask into its family: a child for each module of its275- * territory that has callers, in the policy's module order, and a delete276- * child blocked by all of them, each asked by the parent's asker and held277- * as the parent is held. `None` when the ask is no migrate ask, or fewer278- * than two of its modules have callers: a split of one is the ask itself.279- */215+/** `None` for a non-migrate ask, or when fewer than two modules have callers: a split of one is the ask itself. */216 export const splitFamily = (input: {217 readonly parent: Ask;218 readonly counts: CallerCount;219 readonly modules: readonly Territory[];82 unmodified linesmodified:packages/project/src/outbox.ts+3 added-34 removed
1-/**2- * The outbox: side effects a call's commit asked for, kept with the rows3- * that made them until they are done (ADR 0012's settle). A row is written in4- * the same commit as its transition, run right after it, and acknowledged5- * once it succeeded; one that failed stays, with a later `notBefore`, and the6- * next alarm runs it again. Each is safe to run twice.7- *8- * Kinds: a projected event for the read models (`Projected`), a claim's9- * fork (`MakeFork`), the start of an answer run (`StartAnswer`), a10- * landing's unwritten bookkeeping, written by landing the same job again11- * (`Bookkeeping`), an effect a visibility plan asked for, settled by12- * the port that planned it (`Visibility`), and the start of a proposal's13- * draft run, one per round (`StartDraft`).14- */1 import { RefName, RepoHost } from "@repo/artifacts/repo-host";2 import { Verdict } from "@repo/protocol/domain/answer";3 import type { ProjectEvent } from "@repo/protocol/domain/event";4 import {17 unmodified lines22 import { ProjectVisibility, VisibilityEffect } from "./visibility-port.ts";23 24 const mainRef = RefName.make("refs/heads/main");25 40-/** An answer's landing job, as its bookkeeping retry lands it again. */26 export const LandAgain = Schema.Struct({27 author: Handle,28 base: CommitSha,29 fork: RepoName,7 unmodified lines37 });38 39 export type LandAgain = typeof LandAgain.Type;40 56-/** What one outbox row asks for. */41 export const OutboxBody = Schema.Union([42 ProjectedEvent,43 Schema.TaggedStruct("MakeFork", { from: RepoName, name: RepoName }),44 Schema.TaggedStruct("StartAnswer", { requestId: RequestId }),9 unmodified lines54 const encodeBody = Schema.encodeEffect(BodyJson);55 56 const decodeBody = Schema.decodeUnknownEffect(BodyJson);57 74-/** A row asking for `body`, due at `notBefore`; a row with the same id is replaced. */58 export const outboxRow = (59 id: string,60 body: OutboxBody,61 notBefore: DateTime.Utc5 unmodified lines67 kind: body._tag,68 notBefore,69 }));70 88-/** One row per event, for the read models, keyed by the event's number. */71 export const projectedRows = (72 project: ProjectName,73 events: readonly ProjectEvent[],74 now: DateTime.Utc5 unmodified lines80 now81 )82 );83 102-/** The row that starts (or resumes) an answer's run at `at`. */84 export const startRow = (requestId: RequestId, at: DateTime.Utc) =>85 outboxRow(86 `start:${requestId}:${DateTime.toEpochMillis(at)}`,87 OutboxBody.cases.StartAnswer.make({ requestId }),88 at89 );90 110-/** The row that starts a proposal's draft run for one round: one row per round. */91 export const draftRow = (params: DraftParams, at: DateTime.Utc) =>92 outboxRow(93 `draft:${params.proposal}:r${params.round}`,94 OutboxBody.cases.StartDraft.make(params),95 at96 );97 118-/** Whether a row is due at `now`. */98 export const isDue = (row: OutboxRow, now: DateTime.Utc) =>99 DateTime.isLessThanOrEqualTo(row.notBefore, now);100 122-/** What running some rows came to: the ids done, and the rows to run again later. */101 export interface OutboxRun {102 readonly done: readonly string[];103 readonly retry: readonly OutboxRow[];104 }105 128-/** The row again, after `attempts` failures: due after a backoff from `now`. */106 const later = (row: OutboxRow, now: DateTime.Utc): OutboxRow => ({107 ...row,108 attempts: row.attempts + 1,109 notBefore: DateTime.addDuration(now, backoff(row.attempts)),11 unmodified lines121 done: runs.flatMap(({ done }) => done),122 retry: runs.flatMap(({ retry }) => retry),123 });124 148-/**149- * A claim's fork, made or found made. Artifacts may answer a fork that150- * worked with an error: a fork that exists and has `main` is made.151- */125+// Artifacts may answer a fork that worked with an error: a fork that exists126+// and has `main` is made.127 const fork = (from: RepoName, name: RepoName) =>128 RepoHost.use((host) =>129 host.fork(from, name).pipe(130 Effect.as(true),6 unmodified lines137 Effect.orElseSucceed(() => false)138 )139 );140 166-/** The landing job again: its unwritten bookkeeping is written, and nothing else moves. */141 const landAgain = (job: LandAgain) =>142 Lander.use((lander) =>143 lander.land({144 author: job.author,17 unmodified lines162 const bySeq = Order.mapInput(Order.Number, ({ body }: Decoded) =>163 OutboxBody.guards.Projected(body) ? body.event.seq : 0164 );165 192-/**193- * Runs the rows: projected events first, in their order and in one call,194- * then forks, bookkeeping, visibility's effects, the draft runs, and last195- * the answer runs (which may run long, and settle their own rows). Nothing196- * here fails: each row is done, or retried.197- */166+// Answer runs go last: they may run long, and settle their own rows.167 export const runOutbox = (168 rows: readonly OutboxRow[],169 queue: AnswerQueue,170 now: DateTime.Utc74 unmodified linesmodified:packages/project/src/project-store.ts+3 added-44 removed
22 unmodified lines23 PushEventRow,24 RatchetRow,25 } from "./project-store/rows.ts";26 27-/** How many landings a snapshot carries, newest first; `landing` finds older ones. */27 export const snapshotLandings = 50;28 29 /** How many events a project keeps; a watcher resuming from an older one has missed some. */30 export const keptEvents = 500;31 33-/**34- * A project's whole working state, read in one go at the start of a call35- * (hydrate). Rows come back in the order they were first written, except36- * `landings`.37- */32 export interface ProjectSnapshot {33 readonly answers: readonly AnswerRow[];34 readonly asks: readonly AskRow[];41- /** Failed held-back runs per claim, area and week. */35 readonly attempts: readonly AttemptRow[];36 readonly budgetDays: readonly BudgetDayRow[];37 readonly claims: readonly ClaimRow[];38 readonly decisions: readonly DecisionRow[];46- /** Write-only values, sealed, by env key. */39 readonly envValues: readonly EnvValueRow[];48- /** The newest `snapshotLandings` landings, newest first. */40 readonly landings: readonly LandingRow[];50- /** The sequence number of the newest event, or 0 before the first. */41 readonly lastSeq: number;52- /** The layers the project declared. */42 readonly layers: readonly LayerRow[];54- /** The public ledger, every entry. */43 readonly ledger: readonly LedgerRow[];56- /** Side effects not yet acknowledged, in the order they were written. */44 readonly outbox: readonly OutboxRow[];58- /** Absent until the project is initialized. */45 readonly project: Option.Option<ProjectRow>;46 readonly proposals: readonly ProposalRow[];61- /** The encoded landing queue; `null` until a commit writes one. */47 readonly queue: Schema.Json;48 readonly ratchets: readonly RatchetRow[];49 }50 66-/**67- * What one call changed. Every row is an upsert by its table's key (an ask68- * by id, a claim by ask and claimant, an answer by `requestId`, a landing by69- * SHA, an outbox entry by id, a layer by name, an attempt by ask, claimant,70- * area and week, a ledger entry by `seq`, a value by its key); `events` and71- * `layerReads` are appended and numbered.72- */51 export interface ProjectWrites {52 readonly answers?: readonly AnswerRow[];53 readonly asks?: readonly AskRow[];54 readonly attempts?: readonly AttemptRow[];2 unmodified lines57 readonly decisions?: readonly DecisionRow[];58 readonly envValues?: readonly EnvValueRow[];59 readonly events?: readonly ProjectEventInput[];60 readonly landings?: readonly LandingRow[];83- /** Appended to the read log and numbered, as events are. */61 readonly layerReads?: readonly LayerRead[];62 readonly layers?: readonly LayerRow[];86- /** Upserted by `seq`: the ledger's writer numbers its entries. */63 readonly ledger?: readonly LedgerRow[];64 readonly outbox?: readonly OutboxRow[];65 readonly project?: ProjectRow;66 readonly proposals?: readonly ProposalRow[];1 unmodified line68 readonly queue?: Schema.Json;69 readonly ratchets?: readonly RatchetRow[];70 }71 96-/** What a commit did: the numbers it gave its events, and the push events it had already seen. */72 export interface Committed {73 /** Event ids already stored. When there is one, the commit wrote nothing. */74 readonly duplicatePushEvents: readonly string[];100- /** One per event written, in order. */75 readonly seqs: readonly number[];76 }77 78 /**105- * One project's state, hydrated and persisted per call (ADR 0012): `load`106- * reads the whole working state, `commit` writes every row, outbox entry and107- * event a transition produced in one transaction, so a crash between two108- * calls never leaves half a transition.109- *110- * - `commit` is all or nothing. A commit that carries a push event already111- * stored is a replay: it writes nothing, numbers no event, and lists the112- * ids it had seen, so acting on one push event twice is a no-op.113- * - Events are numbered from 1 in commit order; only the newest `keptEvents`114- * are kept, which `eventsSince` reads for a watcher resuming from a number.115- * - `ackOutbox` drops entries the settle step ran; unknown ids are ignored.116- * - `landing` finds a landing by SHA, older than the snapshot's too.117- * - Layer reads are numbered from 1 in commit order and all kept; they are118- * no part of the snapshot, and `layerReadsSince` reads them.119- * - The store reads no clock: every timestamp arrives in a row.120- *121- * Store failures are defects, not errors: a project whose storage fails can122- * do nothing useful, and the platform's error boundary reports it.79+ * `commit` is all or nothing, so a crash between calls never leaves half a80+ * transition. A commit carrying a push event already stored is a replay: it81+ * writes nothing and lists the ids it had seen. Store failures are defects.82 */83 export class ProjectStore extends Context.Service<84 ProjectStore,85 {16 unmodified linesmodified:packages/project/src/project.ts+22 added-635 removed
1-/**2- * The project service: every contract's server logic for one project,3- * host-free, over ports. Each call hydrates the project from4- * its store, moves its lifecycles by pure transitions, persists rows, outbox5- * and events in one commit, then settles the outbox (ADR 0012): forks,6- * projected events, answer runs and unwritten bookkeeping, each retried by7- * the next alarm when it fails. Deadlines (claims warned and lapsed, retries)8- * run on the project's one alarm, set to the earliest pending one.9- *10- * Calls that write run one at a time per project; the slow part of an11- * answer (merge, checks, land) runs outside that lock, in the answer's run,12- * which reports each step back through `advanceAnswer`. Every method checks13- * its arguments and its result against the contract's or the domain's14- * schemas (`MethodSchemas`, principle 2), which the Durable Object boundary15- * reuses.16- */1 import {2 BranchName,3 RefName,4 RepoHost,293 unmodified lines298 ProjectVisibility,299 } from "./visibility-port.ts";300 import type { VisibilityPlan } from "./visibility-port.ts";301 318-/** Every port one project's service runs on. */302 export type ProjectPorts =303 | Alarms304 | AnswerRuns305 | CheckRunner2 unmodified lines308 | Projection309 | RepoHost310 | RulesEvaluator;311 329-/**330- * The platform's gateway, where every repo's git URL starts: what a claim's331- * and a project's `remote` name. Never an Artifacts URL. The platform's332- * Worker sets its own; the default is the product's domain.333- */312+/** The gateway every repo's git URL starts with; never an Artifacts URL. */313 export const GatewayUrl = Context.Reference<string>("project/GatewayUrl", {314 defaultValue: () => `https://${Brand.domain}`,315 });316 338-/**339- * The rules evaluator's finishers from `@repo/checks`: the run-block finder340- * and the judge closure (`rules` may not import `checks`).341- * Every rules evaluator adapter needs it beside the project's ports.342- */317+/** Injected from `@repo/checks` because `rules` may not import `checks`. */318 export const FinishersFromChecks: Layer.Layer<Finishers> = Layer.succeed(319 Finishers,320 { findRunBlock, judgeClosure }321 );322 348-/** A push one repo took, as the gateway's custody reports it. */323 export const PushReport = Schema.Struct({324 after: CommitSha,351- /**352- * The harness the push came through, as its credential helper's username353- * named it (`@repo/protocol/audit`): audit metadata, never who pushed. A354- * claimant's push keeps it on their claim, for the landing's355- * `Assisted-by:`.356- */325+ /** Self-reported by the credential helper: audit metadata, never who pushed. */326 audit: Schema.optionalKey(HarnessAudit),327 before: Schema.Option(CommitSha),359- /** The push event's id; the same event reported twice is acted on once. */328 eventId: Schema.NonEmptyString,329 pusher: Principal,330 ref: Schema.NonEmptyString,331 repo: RepoName,332 });333 334 export type PushReport = typeof PushReport.Type;335 368-/** One file a decider opens an ask with: its ask file, or its check. */336 export interface AskFile {337 readonly content: string;338 readonly path: RepoPath;339 }340 374-/**375- * A project's posture as a list keeps it: the posture its ledger shows376- * now, the next instant it moves by the clock alone, if one is set, and the377- * project's last event the read saw (`ProjectApi.standing`).378- */341 export const StandingNow = Schema.Struct({342 posture: Posture,343 seen: Schema.Int,344 until: Schema.optionalKey(Schema.DateTimeUtcFromString),345 });346 347 export type StandingNow = typeof StandingNow.Type;348 387-/** The refusals `submitAnswer` answers with. */349 export type SubmitRefusal =350 | NotClaimed351 | ClaimLapsed352 | StaleBase3 unmodified lines356 | Weakened357 | ReachedInternals358 | PrivatePathInPublicTree;359 399-/**400- * Every contract's server logic for one project. Each method takes its401- * caller explicitly: one project's service serves many callers. The402- * decider-facing methods (Today, proposals, decisions, finishes, a403- * decider's own landings, vouches, credits, the ledger and the env shape)404- * are `DeciderApi`'s, with their bodies in `deciders.ts`.405- */360 export interface ProjectApi extends AnswerQueue, DeciderApi {407- // reads361 readonly listAsks: (362 caller: Principal363 ) => Effect.Effect<{ readonly asks: readonly AskListing[] }>;364 readonly showAsk: (11 unmodified lines376 readonly landing: (377 caller: Principal,378 sha: CommitSha379 ) => Effect.Effect<{ readonly landing: LandingView }, UnknownCommit>;427- /** Where main has landed: none before the first push. */380 readonly head: () => Effect.Effect<{ readonly landed?: LandedSha }>;429- /** Every claim's fork, with its ask, claimant and the claim's state. */381 readonly forks: () => Effect.Effect<readonly ForkRef[]>;431- /**432- * The posture the ledger shows now, the next instant it moves by the433- * clock alone (none when only an event moves it), and the project's last434- * event this read saw. Platform-only, on no surface: what a list keeps435- * each project's posture by (`standing-posture.ts`).436- */382 readonly standing: () => Effect.Effect<StandingNow>;438- /**439- * The policy at the landed commit as anyone may read it (no layers, no440- * function-valued rules, no asks), once it has evaluated; until then, after441- * the first landing, why it has not (derived at each read, never stored).442- */383 readonly policy: () => Effect.Effect<PolicyStatus>;444- /**445- * What a draft's run reads for one round of an open proposal: the landed446- * commit, the want and territory, the public policy and the canonical447- * tree's paths. Platform-only: no caller.448- */384 readonly draftContext: (385 proposal: ProposalId,386 round: number387 ) => Effect.Effect<DraftContextData, UnknownProposal | ProposalClosed>;453- /**454- * An ask's files rehearsed as `accept` would open them, red first, by the455- * first decider of their paths, and nothing landed or written: `Red`, or456- * the final refusal `Refused` with why and the check's output's tail. A457- * blocked Checker or a moved main stays an error, to try again.458- * Platform-only: no caller.459- */388 readonly rehearseOpen: (389 files: readonly ConfigFile[]390 ) => Effect.Effect<Rehearsal, VerifierBlocked | StaleBase>;463- /**464- * A draft's round ended: a `Red` draft holds its files and goes to the465- * deciders as the proposal's decision; a `Failed` one goes to them with466- * its want alone. A round that is not the proposal's current one, or a467- * proposal no longer open, changes nothing. Platform-only: no caller.468- */391 readonly draftSettled: (392 proposal: ProposalId,393 round: number,394 result: DraftResult395 ) => Effect.Effect<void>;474- /**475- * The log a failing lane left, by the name its verdict gives it476- * (`LaneResult.logRef`), for the project's deciders and the claimant477- * of the answer the name points at. A name `logRefOf` never makes, or one478- * that points at another project, is `UnknownProject` for anyone; past479- * that, anyone else is `NotDecider` whether or not a log is kept under the480- * name, and a reader allowed in finds no log kept as `UnknownProject`481- * too. A log over 256 KiB comes back as its last 256 KiB, where a482- * failure prints. The log is read from the `EvidenceStore` the call runs483- * with (the stage's bucket), outside the project's lock.484- */396 readonly evidence: (397 caller: Principal,398 ref: LogRef399 ) => Effect.Effect<10 unmodified lines410 limit: number411 ) => Effect.Effect<412 readonly { readonly event: ProjectEvent; readonly seq: number }[]413 >;503- /**504- * Who may make the project's first push to its canonical `main`: its505- * initializer, while the project awaits that push; no506- * one once it has a landed SHA. The gateway's custody reads it before a507- * push reaches the canonical repo.508- */414 readonly firstPusher: () => Effect.Effect<Option.Option<Handle>>;510- // writes415 readonly initProject: (416 caller: Person,417 input: {418 readonly import?: { readonly branch?: string; readonly url: string };36 unmodified lines455 readonly release: (456 caller: Person,457 ask: AskId458 ) => Effect.Effect<{ readonly released: boolean }, NotClaimed>;555- /**556- * A push a claim fork took: liveness for its claimant's claim, and stages557- * 0–1 over it. The fork keeps the commit whatever the gate says; the558- * refusals, every one at once, reach the pusher in git's output. The same559- * push event reported again changes nothing.560- */459 readonly recordPush: (input: PushReport) => Effect.Effect<readonly Refusal[]>;562- /**563- * Stages 0–1 over the answer, then its run starts and the receipt says it564- * is being checked. The same `requestId`, or the same head from565- * the same person while its first answer stands, returns the first receipt.566- * Of stage 1's refusals the first comes back; `recordPush` lists them all.567- */460 readonly submitAnswer: (461 caller: Person,462 input: {463 readonly ask: AskId;1 unmodified line465 readonly head: CommitSha;466 readonly requestId: RequestId;467 }468 ) => Effect.Effect<AnswerReceipt, SubmitRefusal>;577- /**578- * The project's alarm fired: deadlines that passed move (claims warned579- * and lapsed, proposals expired, decisions defaulted), and outbox rows580- * due run again.581- */469 readonly onAlarm: () => Effect.Effect<void>;583- // visibility: each delegates to `ProjectVisibility` or584- // `ProjectEnv`, whose defaults are a project without typed visibility.585- /**586- * How far `caller` may reach into `layer`, for the gateway; none when the587- * project declares no such layer, so its repo is an unknown repo.588- */470 readonly layerAccess: (471 caller: Principal,472 layer: LayerName473 ) => Effect.Effect<Option.Option<LayerAccess>>;593- /** What stage 1 takes from visibility for `caller`'s pushes: the layer paths, and whether they read a layer. */474 readonly layerFacts: (caller: Principal) => Effect.Effect<LayerFacts>;595- /** A push a layer's repo took: its head is proposed, and admitted at once or through admission. */475 readonly recordLayerPush: (476 caller: Person,477 input: { readonly head: CommitSha; readonly layer: LayerName }478 ) => Effect.Effect<void>;600- /** A clone or fetch of a layer's repo, for its read log. */479 readonly recordLayerRead: (480 caller: Person,481 input: { readonly layer: LayerName; readonly sha?: CommitSha }482 ) => Effect.Effect<void>;605- /**606- * The held-back run an answer's checks end with: the suite its claim was607- * pinned to, read at the pinned layer commit. None when nothing is sealed608- * for it (the request is unknown, has no claim, or pinned nothing).609- */483 readonly heldBackJob: (484 requestId: RequestId485 ) => Effect.Effect<Option.Option<HeldBackJob>>;613- /**614- * A held-back run's area bits for the tree the answer is being checked615- * on, judged once per tree: the refusals it earns, which the run's checks616- * report with their own. Every area passing keeps the `Held-back:`617- * trailer for the landing. The same tree reported again is judged as618- * before, its attempt counted once.619- */486 readonly recordHeldBack: (487 requestId: RequestId,488 results: readonly HeldBackResult[]489 ) => Effect.Effect<readonly Refusal[]>;624- /** The runs that would admit a layer's pushed head; none when nothing waits on admission. */490 readonly admissionPlan: (input: {491 readonly head: CommitSha;492 readonly layer: LayerName;493 }) => Effect.Effect<Option.Option<AdmissionPlan>>;629- /** What an admission's runs came to: the layer's landed SHA moves, or stays. */494 readonly recordAdmission: (input: AdmissionReport) => Effect.Effect<void>;631- /** The stored write-only value a text or blob contains, by its item; none when it holds none. */495 readonly scanForValues: (496 input: { readonly text: string } | { readonly blob: Uint8Array }497 ) => Effect.Effect<Option.Option<EnvKey>>;498 }499 637-/** The most paths a draft's context lists: as many as the code browser's `listPaths`. */500 const MAX_DRAFT_PATHS = 50_000;501 640-/** What `projectPolicy` answers: the public policy, or why there is none yet. */502 export type PolicyStatus = typeof PolicyOf.successSchema.Type;503 643-/** The most commits one `landings` call looks up: a log page's, or a blame's batch. */504 export const MAX_LANDINGS = 100;505 646-/** The schemas one method's arguments (in order), success and failure cross a boundary with. */506 export interface MethodSchema {507 readonly args: readonly Schema.Top[];508 readonly error: Schema.Top;509 readonly success: Schema.Top & { readonly EncodingServices: never };510 }511 653-/**654- * Every `ProjectApi` method's schemas: contract methods take their success655- * and failure from `Contracts`, the rest from the domain. The service checks656- * each argument and each success against them; the Durable Object boundary657- * encodes and decodes with the same ones.658- */512 export const MethodSchemas = {513 [envSchemaMethod]: {514 args: [Principal],515 error: EnvSchemaOf.errorSchema,267 unmodified lines783 success: Vouch.successSchema,784 },785 } as const satisfies { readonly [M in keyof ProjectApi]: MethodSchema };786 934-/**935- * What the checks of an answer's last checked tree counted: each of the936- * policy's ratchets per territory, and each territory's reasoned escapes937- * once the answer is in (its count on main, and those the answer adds).938- * The answer's landing writes them to the project's `ratchets` rows.939- */787 export const Measured = Schema.Struct({788 declared: Schema.Array(MeasuredCount),789 escapes: Schema.Array(MeasuredCount),790 });791 792 export type Measured = typeof Measured.Type;793 947-/**948- * A held-back run judged for one checked tree: the refusals it earned,949- * and the `Held-back:` trailer's value when every area passed. Judged once950- * per tree, so a run reported again counts no attempt twice.951- */794 export const HeldBackJudged = Schema.Struct({795 refusals: Schema.Array(Refusal),796 trailer: Schema.optionalKey(Schema.NonEmptyString),797 tree: TreeSha,798 });799 800 export type HeldBackJudged = typeof HeldBackJudged.Type;801 960-/**961- * Where one answer stands, as its row keeps it: the landing lifecycle's962- * state, the receipt its request was first given (a replay gets it again),963- * the verdict on its last checked tree, what that tree counted, its last964- * held-back run's judgement, and each `Waiver` a decider accepted for this965- * answer (checked again after main moved, it is not asked again; another966- * answer to the ask is).967- */802 export const AnswerRecord = Schema.Struct({803 heldBack: Schema.optionalKey(HeldBackJudged),804 landing: LandingState,805 measured: Schema.optionalKey(Measured),21 unmodified lines827 const decodePolicy = Schema.decodeUnknownEffect(PolicyJson);828 829 const encodePolicy = Schema.encodeEffect(PolicyJson);830 997-/**998- * A method run between the check of its arguments (each against its999- * schema's type side: a value that is not one is the caller's defect, since1000- * the boundary that decoded it would have refused it) and the check that its1001- * success encodes.1002- */831 const checked = <A, E, R>(832 schemas: MethodSchema,833 args: readonly unknown[],834 run: Effect.Effect<A, E, R>11 unmodified lines846 Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))847 )848 );849 1022-/** A policy as anyone may read it: without its layers, function-valued rules and asks. */850 const publicPolicy = (policy: Policy): PublicPolicy =>851 Struct.omit(policy, ["asks", "functions", "visibility"]);852 1026-/** A claim's fork, as the refs page lists it. */853 const listedFork = (claim: Live, state: ClaimView["state"]) =>854 Option.some<ForkRef>({855 ask: claim.ask,856 handle: claim.claimant,1 unmodified line858 repo: claim.fork,859 state,860 });861 1036-/** Where a claim stands, as its fork's listing says it; an open ask has no fork. */862 const forkOf = (state: ClaimState): Option.Option<ForkRef> =>863 ClaimState.match(state, {864 Answered: (claim) => listedFork(claim, "answered"),865 Lapsed: (claim) => listedFork(claim, "lapsed"),2 unmodified lines868 Released: (claim) => listedFork(claim, "released"),869 Warned: (claim) => listedFork(claim, "warned"),870 });871 1047-/** The most of a lane's log `evidence` gives back: its last 256 KiB. */872 const EVIDENCE_TAIL = 256 * 1024;873 1050-/** Whether a UTF-8 byte starts a character: it is no continuation byte (`10xxxxxx`). */874 const startsCharacter = (byte: number) => byte < 0x80 || byte >= 0xc0;875 1053-/**1054- * A log as `evidence` gives it back: whole up to 256 KiB, else its last1055- * 256 KiB, where a failure prints, cut between characters, never inside one.1056- */876+/** The log's tail, where a failure prints, cut between UTF-8 characters. */877 const tailOf = (log: string, limit = EVIDENCE_TAIL) => {878 const bytes = new TextEncoder().encode(log);879 880 if (bytes.length <= limit) {12 unmodified lines893 const mainRef = RefName.make("refs/heads/main");894 895 const HOUR = 3_600_000;896 1077-/** The claim deadlines before a project has a policy: the defaults. */897 const defaultClaims: Policy["claims"] = {898 lapseAfterMs: 24 * HOUR,899 warnAfterMs: 2 * HOUR,900 };7 unmodified lines908 readonly record: AnswerRecord;909 readonly row: AnswerRow;910 }911 1093-/** A project as one call reads it at its start. */912 interface Hydrated {913 readonly answers: readonly Answered[];914 readonly asks: ReadonlyMap<AskId, Ask>;915 readonly budgetDays: readonly BudgetDayRow[];5 unmodified lines921 readonly policy: Option.Option<Policy>;922 readonly project: Option.Option<ProjectRow>;923 readonly proposals: readonly Proposal[];924 readonly queue: LandingQueue;1107- /** Every ratchet's baseline per territory, the escape ratchets' included. */925 readonly ratchets: readonly RatchetRow[];1109- /** The rows as the store gave them, which the visibility ports read. */926 readonly snapshot: ProjectSnapshot;927 }928 1113-/**1114- * What one call writes, gathered as it goes and committed at its end. The1115- * project row and the queue are kept in one-entry maps, so the record itself1116- * never changes. Budget days are keyed by day and decider.1117- */929+/** The project row and the queue sit in one-entry maps so the record itself never changes. */930 interface Writes {931 readonly answers: Map<RequestId, AnswerRow>;932 readonly asks: Map<AskId, Ask>;1121- /** Keyed by their table's key (`keyIn`); the visibility ports write them. */933 readonly attempts: Map<string, AttemptRow>;934 readonly budgetDays: Map<string, BudgetDayRow>;935 readonly claims: Map<string, ClaimRow>;936 readonly decisions: Map<DecisionId, Decision>;7 unmodified lines944 readonly project: Map<"row", ProjectRow>;945 readonly proposals: Map<ProposalId, Proposal>;946 readonly pushEvents: PushEventRow[];947 readonly queue: Map<"queue", LandingQueue>;1137- /** Keyed by ratchet and territory (`ratchetKey`). */948 readonly ratchets: Map<string, RatchetRow>;949 }950 951 const writesOf = (): Writes => ({38 unmodified lines990 writes.queue.size,991 writes.ratchets.size,992 ].every((count) => count === 0);993 1184-/** A row's key in its table, as the store keys it. */1185-/**1186- * Keeps `landing` and hears it as `Landed`: every landing that moves main1187- * is heard, so a watcher and the front page see it (a project's row is1188- * written on its first event).1189- */994 const keepLanding = (995 writes: Writes,996 landing: LandingView,997 now: DateTime.Utc7 unmodified lines1005 1006 return JSON.stringify(table.key.map((name) => columns[name]));1007 };1008 1205-/** `held` with `written` over it: each written row in its key's place, the new ones after. */1009 const overlaid = <A>(1010 table: Table<A>,1011 held: readonly A[],1012 written: Iterable<A>9 unmodified lines1022 ...[...fresh.values()].filter((row) => !kept.has(keyIn(table, row))),1023 ];1024 };1025 1223-/** Ledger entries in order. */1026 const bySeq = Order.mapInput(Order.Number, (entry: LedgerRow) => entry.seq);1027 1226-/**1227- * The project as one call has it so far: the rows it hydrated with the1228- * rows it wrote on top (a landing it recorded first, as the store orders1229- * them). What the visibility ports read, so a port numbers a ledger entry1230- * or a decision after the ones the call already made.1231- */1028 const snapshotNow = (h: Hydrated, writes: Writes): ProjectSnapshot => {1029 const held = h.snapshot;1030 1031 return {44 unmodified lines1076 ),1077 };1078 };1079 1284-/**1285- * The tables a visibility port may write: its own, and the decisions,1286- * events and outbox rows its plans add. The project service writes every1287- * other one itself.1288- */1080 const portTables = new Set<string>([1081 "attempts",1082 "decisions",1083 "envValues",3 unmodified lines1087 "ledger",1088 "outbox",1089 ]);1090 1300-/** A port's rows added to the call's: each keyed table by its key, the logs appended. */1091 const absorb = (writes: Writes, more: ProjectWrites) => {1092 const foreign = Object.keys(more).filter((table) => !portTables.has(table));1093 1094 if (Array.isReadonlyArrayNonEmpty(foreign)) {28 unmodified lines1123 1124 return Effect.void;1125 };1126 1337-/**1338- * A port's plan taken into the call: its rows with the call's, and each of1339- * its effects as an outbox row, settled after the commit and retried until1340- * done.1341- */1127 const applyPlan = (writes: Writes, plan: VisibilityPlan, now: DateTime.Utc) =>1128 Effect.gen(function* () {1129 yield* absorb(writes, plan.writes);1130 14 unmodified lines1145 1146 const claimKey = (ask: AskId, claimant: Handle) =>1147 JSON.stringify([ask, claimant.toLowerCase()]);1148 1364-/** A claim's own fields, in every state but `Open`. */1149 const claimOf = (state: ClaimState): Option.Option<Live> =>1150 ClaimState.match(state, {1151 Answered: (claim) => Option.some<Live>(claim),1152 Lapsed: (claim) => Option.some<Live>(claim),4 unmodified lines1157 });1158 1159 const isLive = ClaimState.isAnyOf(["Live", "Warned"]);1160 1377-/** When a live claim's next deadline is: its warning, or once warned its lapse. */1161 const deadlineOf = (state: ClaimState): Option.Option<DateTime.Utc> =>1162 ClaimState.match(state, {1163 Answered: () => Option.none(),1164 Lapsed: () => Option.none(),2 unmodified lines1167 Released: () => Option.none(),1168 Warned: ({ lapsesAt }) => Option.some(lapsesAt),1169 });1170 1388-/** A path a composed commit can hold: plain folder names and a file name. */1171 const isPlainPath = (path: string) =>1172 path1173 .split("/")1174 .every(3 unmodified lines1178 segment !== ".." &&1179 segment !== ".git"1180 );1181 1400-/** Whether the brief holds a field its kind requires. */1182 const holds = (ask: Ask, wanted: AskKind["requires"][number]) =>1183 Match.value(wanted).pipe(1184 Match.when("want", () => ask.brief.want.length > 0),1185 Match.when("current", () => ask.brief.current !== undefined),3 unmodified lines1189 Match.whenOr("check", "territory", () => true),1190 Match.exhaustive1191 );1192 1412-/** Whether two import sources name the same repo and branch (ADR 0031). */1193 const sameSource = (a: ImportSource, b: ImportSource) =>1194 a.url === b.url && a.branch === b.branch;1195 1416-/** An optional field as an object to spread: the field when present, nothing when not. */1196 const field = <K extends string, A>(1197 key: K,1198 value: Option.Option<A>1199 ): Partial<Record<K, A>> =>1 unmodified line1201 onNone: () => ({}),1202 onSome: (present) => Record.singleton(key, present),1203 });1204 1426-/** The credit an answer's landing carries: who asked, who answered, who mentored. */1205 const creditsFor = (ask: Ask, answerer: Handle): readonly Credit[] => [1206 { handle: ask.askedBy, role: "Asked-by" },1207 { handle: answerer, role: "Signed-off-by" },1208 ...Option.toArray(3 unmodified lines1212 }))1213 ),1214 ];1215 1438-/** What a check of `ask` runs, and the lane it reports as. */1216 const askLaneOf = (policy: Policy, ask: Ask) =>1217 commandFor(ask.check, policy.run, policy.ratchets);1218 1442-/** A check judged by what its command prints: a lint's count, or a migrate's callers. */1219 const isCounted = CheckSpec.isAnyOf(["LintToZero", "Migrate", "SymbolAbsent"]);1220 1445-/** A check that counts a name's callers: a migrate, or its delete child. */1221 const countsCallers = CheckSpec.isAnyOf(["Migrate", "SymbolAbsent"]);1222 1448-/**1449- * The lane an ask's check runs as: a `lintToZero`, `migrate` or1450- * `symbolAbsent` check is a count, so its lane hands back what its command1451- * printed.1452- */1223 const askCheckLane = (policy: Policy, ask: Ask) =>1224 Option.map(askLaneOf(policy, ask), ({ command, lane }) =>1225 isCounted(ask.check)1226 ? CheckLane.make({ command, lane, output: "stdout" })1227 : CheckLane.make({ command, lane })1228 );1229 1460-/** The lanes an answer's checks run: the ask's own check, then every project lane. */1230 const lanesOf = (1231 policy: Policy,1232 ask: Option.Option<Ask>1233 ): readonly CheckLane[] => [4 unmodified lines1238 CheckLane.make({ command, lane })1239 ),1240 ];1241 1473-/**1474- * The policy's ratchets that `command` counts, read from what it printed:1475- * one count per ratchet and territory. A ratchet whose count can't be read1476- * there is left out, and its first answer's landing sets its baseline.1477- */1242 const countedBy = (policy: Policy, command: string, stdout: string) =>1243 Effect.map(1244 Effect.forEach(1245 policy.ratchets.filter((spec) => spec.measure.command === command),16 unmodified lines1262 ),1263 (counts): readonly RatchetCount[] => counts.flat()1264 );1265 1502-/** A ratchet row's key in a call's writes: its ratchet and territory. */1266 const ratchetKey = (row: {1267 readonly ratchet: string;1268 readonly territory: string;1269 }) => JSON.stringify([row.ratchet, row.territory]);1270 1508-/** A row as `ratchets.ts` reads a baseline. */1271 const baselineOf = (row: RatchetRow): RatchetBaseline => ({1272 count: row.count,1273 ratchet: row.ratchet,1274 setAt: row.at,1275 territory: row.territory,1276 });1277 1516-/**1517- * Whether a row is a territory's escape ratchet's (`escapeRatchet`), which1518- * has no command: its count is the territory's reasoned escapes on main,1519- * moved by those each landing adds.1520- */1278 const isEscapeRow = (row: {1279 readonly ratchet: string;1280 readonly territory: string;1281 }) => row.ratchet === escapeRatchet(row.territory);1282 1526-/** Whether two `Waiver`s are about one escape: one ask, one marker and reason, one line. */1283 const sameEscape = (one: Waiver) => (other: Waiver) =>1284 other.ask === one.ask &&1285 other.marker === one.marker &&1286 other.reason === one.reason &&1287 other.at.path === one.at.path &&1288 other.at.line === one.at.line;1289 1534-/** What a decider just decided for an answer waiting on it: the subject, and the choice in its words. */1290 interface DecidedOn {1291 readonly choice: Choice;1292 readonly subject: PendingDecision["subject"];1293 }1294 1540-/** The decision `command` takes, when it is one the answer waiting in `before` waits on. */1295 const decidedOn = (1296 before: LandingState,1297 command: LandingCommand1298 ): Option.Option<DecidedOn> =>6 unmodified lines1305 ({ subject }) => ({ choice: command.choice, subject })1306 )1307 : Option.none();1308 1555-/** The `Waiver`s a decider accepted for an answer: those it had, and the one just accepted. */1309 const waivedAfter = (1310 waived: readonly Waiver[],1311 decided: Option.Option<DecidedOn>1312 ): readonly Waiver[] => [6 unmodified lines1319 )1320 ),1321 ];1322 1570-/** What a decider weighs for one subject an answer waits on. */1323 const evidenceFor = (1324 request: Request,1325 subject: Waiver | RaiseRatchet1326 ): readonly Evidence[] => [11 unmodified lines1338 value: `${subject.ratchet} in ${subject.territory}: ${subject.before} to ${subject.after}`,1339 },1340 ];1341 1590-/**1591- * A `lintToZero` check is red first by its count: twice on the composed1592- * commit its rule reports something in its territory, the same number1593- * both times. Gives what the policy's ratchets count in the same1594- * lint, for their baselines at the ask's opening.1595- */1342 const redByCount = (input: {1343 readonly ask: Ask;1344 readonly check: LintToZeroCheck;1345 readonly lane: LaneName;29 unmodified lines1375 1376 return yield* countedBy(policy, check.command, once.stdout);1377 });1378 1633-/** A section of a brief, when it has lines. */1379 const section = (heading: string, lines: readonly string[] | undefined) =>1380 lines === undefined || lines.length === 01381 ? []1382 : ["", `## ${heading}`, "", ...lines];1383 1384 const listed = (lines: readonly string[] | undefined) =>1385 lines?.map((line) => `- ${line}`);1386 1642-/** What an ask's check holds it to, in a sentence. */1387 const checkLine = (check: CheckSpec) =>1388 CheckSpec.match(check, {1389 LintToZero: ({ rule }) =>1390 `The lint rule \`${rule}\` reports nothing in the territory.`,6 unmodified lines1397 `\`${path}\` fails on main by an assertion; it passes once answered.`,1398 SymbolAbsent: ({ symbol }) => `Nothing uses \`${symbol}\` any more.`,1399 });1400 1657-/** The ask as an answerer reads it first, in Markdown. */1401 const briefOf = (ask: Ask): string => {1402 const { brief, territory } = ask;1403 const paths = territory.paths.map((path) => `\`${path}\``).join(", ");1404 19 unmodified lines1424 "",1425 ].join("\n");1426 };1427 1685-/** The refusal `submitAnswer` gives for one from the gate: its own, or `NotClaimed`. */1428 const submitRefusal = (refusal: Refusal, ask: AskId): SubmitRefusal =>1429 Match.value(refusal).pipe(1430 Match.tag(1431 "ClaimLapsed",9 unmodified lines1441 ),1442 Match.orElse(() => NotClaimed.of(ask))1443 );1444 1703-/**1704- * The agents a claim's pushes named, with the one `audit` names added: a1705- * harness and its model, once each, in the order they first pushed. The1706- * platform heard the harness from the push's own credential helper and1707- * confirmed nothing, so it is `claimed`. A push no harness named adds none.1708- */1445 const withAgent = (1446 agents: readonly AgentTrailer[],1447 audit: HarnessAudit | undefined1448 ): readonly AgentTrailer[] => {13 unmodified lines1462 ? agents1463 : [...agents, agent];1464 };1465 1730-/**1731- * The agents an answer's landing discloses as `Assisted-by:`:1732- * those its claim's pushes named, unless the project's policy says1733- * `agents: "none"`.1734- */1466 const disclosed = (1467 policy: Policy,1468 claim: Option.Option<ClaimRow>1469 ): readonly AgentTrailer[] =>3 unmodified lines1473 onNone: () => [],1474 onSome: ({ assisted }) => assisted ?? [],1475 });1476 1746-/**1747- * The `Held-back:` trailer's value for the tree a verdict judged: the1748- * answer's last held-back run's, when it ran on that tree and every area1749- * passed.1750- */1477 const heldBackTrailerOf = (1478 record: { readonly heldBack?: HeldBackJudged },1479 tree: TreeSha1480 ): Option.Option<string> =>4 unmodified lines1485 ),1486 ({ trailer }) => Option.fromUndefinedOr(trailer)1487 );1488 1763-/** A landing's commit message, from the platform's own rows. */1489 const messageOf = (1490 request: Request,1491 ask: Option.Option<Ask>,1492 verdict: Verdict,20 unmodified lines1513 })1514 );1515 };1516 1792-/** Answers oldest first, by when their row last moved. */1517 const byUpdated = Order.mapInput(1518 DateTime.Order,1519 ({ row }: Answered) => row.updatedAt1520 );1521 1798-/**1799- * The verdict a landing carries: the one the checks gave, whose outcome1800- * was the answer's when it was judged (a stage still to pass), now `Landed`1801- * at the landing's SHA.1802- */1522 const landedVerdict = (verdict: Option.Option<Verdict>, sha: LandedSha) =>1523 Option.map(verdict, (made): Verdict => ({1524 ...made,1525 outcome: Outcome.cases.Landed.make({ sha }),1526 }));1527 1809-/** A `Landed` event with the verdict the landing carries; any other event as it is. */1528 const withVerdict = (1529 event: ProjectEventInput,1530 verdict: Option.Option<Verdict>1531 ): ProjectEventInput =>7 unmodified lines1539 })),1540 Match.orElse((other) => other)1541 );1542 1825-/** Whether a landing's effect is for the answer's run: a step, or a retry to wait for. */1543 const runnable = (effect: LandingEffect): effect is RunnableEffect =>1544 isStep(effect) || LandingEffect.$is("Retry")(effect);1545 1546 const isTouchedJudge = (refusal: Refusal): refusal is TouchedJudge =>5 unmodified lines1552 type Checking = Extract<LandingState, { readonly _tag: "Checking" }>;1553 1554 type Landing = Extract<LandingState, { readonly _tag: "Landing" }>;1555 1839-/** What a landing's effects leave: the steps to hand to the run, and the queue. */1556 interface Settled {1557 readonly queue: LandingQueue;1558 readonly steps: readonly LandingEffect[];1559 }1560 1845-/** Starts the run of a request the queue just admitted, unless it is the one advancing. */1561 const startOther = (1562 writes: Writes,1563 admitted: Option.Option<RequestId>,1564 advancing: RequestId,7 unmodified lines1572 Effect.map(startRow(id, now), (row) => writes.outbox.push(row)),1573 }1574 );1575 1861-/**1862- * What sees an ask's check run twice as it opens: whether the lane prints1863- * its output back, and both runs. Opening for real sees nothing; a1864- * rehearsal reads why the check was not red, and its output's tail.1865- */1576 interface Watch {1577 readonly ran: (1578 lane: LaneName,1579 runs: readonly [CheckRun, CheckRun]2 unmodified lines1582 }1583 1584 const unwatched: Watch = { ran: () => Effect.void, stdout: false };1585 1876-/** A rehearsal's check, as its watch saw it run twice. */1586 interface Seen {1587 readonly lane: LaneName;1588 readonly runs: readonly [CheckRun, CheckRun];1589 }1590 1882-/** The refusals opening an ask gives that waiting does not lift. */1591 type FinalRefusal =1592 | IncompleteBrief1593 | NotDecider1594 | NotRedFirst1595 | TouchedJudge1596 | WeakCheck;1597 1890-/** How one run of a rehearsed check went, for telling why it was not red. */1598 const readingOf = (run: CheckRun, lane: LaneName) => {1599 const result = run.lanes.find((each) => each.lane === lane)?.result;1600 1601 const signed = run.evidence.some(2 unmodified lines1604 1605 return result === "failed" && !signed ? "loadError" : (result ?? "blocked");1606 };1607 1901-/**1902- * Why a check was not red first, from its two runs: both passed; one could1903- * not run; one never reached an assertion (a load error, or a throw that is1904- * none); else it failed two ways.1905- */1608 const notRedBecause = ({ lane, runs }: Seen): Diagnosis => {1609 const readings = runs.map((run) => readingOf(run, lane));1610 1611 if (readings.every((reading) => reading === "passed")) {6 unmodified lines1618 1619 return readings.includes("loadError") ? "LoadError" : "Flaky";1620 };1621 1920-/** Why opening was refused, in a drafter's words. */1622 const diagnosisOf = (1623 refusal: FinalRefusal,1624 seen: Option.Option<Seen>1625 ): Diagnosis =>1626 Match.valueTags(refusal, {1926- // A territory beyond the decider of the files' paths is the brief's.1627 IncompleteBrief: (): Diagnosis => "Brief",1628 NotDecider: (): Diagnosis => "Brief",1929- // No lane to run is a brief whose check names none.1629 NotRedFirst: () =>1630 Option.match(seen, {1631 onNone: (): Diagnosis => "Brief",1632 onSome: notRedBecause,2 unmodified lines1635 WeakCheck: ({ weakness }): Diagnosis =>1636 weakness === "no assertion" ? "NoTests" : "Weak",1637 });1638 1940-/** The last of what the check printed: its second run's output, else its first's. */1639 const excerptOf = (seen: Option.Option<Seen>) =>1640 Option.match(1641 Option.flatMap(seen, ({ lane, runs: [first, second] }) =>1642 Option.orElse(outputOf(second, lane), () => outputOf(first, lane))3 unmodified lines1646 onSome: (printed) => tailOf(printed, EXCERPT_BYTES).text,1647 }1648 );1649 1952-/** A rehearsal refused: the refusal, why, and the output's tail. */1650 const rehearsalRefused = (1651 refusal: FinalRefusal,1652 seen: Option.Option<Seen>1653 ): Rehearsal =>2 unmodified lines1656 excerpt: excerptOf(seen),1657 refusal,1658 });1659 1963-/**1964- * A red rehearsal's lane and signature: the check's own, or, for a check1965- * red by its count, which has none, that it is.1966- */1660 const redOf = ({ lane, runs }: Seen) => ({1661 lane,1662 signature: Result.match(redFirstOfRuns(runs, lane), {1663 onFailure: () => "red by its count",1664 onSuccess: ({ signature }) => signature,1665 }),1666 });1667 1975-/** Whether an ask's check file has one of the five weak shapes. */1668 const weakness = (ask: Ask, files: readonly AskFile[]) => {1669 const { check } = ask;1670 1671 const file = CheckSpec.guards.RedThenGreen(check)4 unmodified lines1676 Array.head(weaknessesOf(found, ask.territory.paths))1677 );1678 };1679 1988-/** Stage 0–1's refusals for a push, every one; what a missing commit or repo comes to. */1680 const gateOf = (1681 facts: Effect.Effect<PushFacts, RepoNotFound | MissingCommit>,1682 missing: readonly Refusal[],1683 stale: readonly Refusal[]11 unmodified lines1695 RepoNotFound: () => Effect.succeed(missing),1696 })1697 );1698 2008-/** The queue once a request no longer landing has left its place in it. */1699 const leaveIfDone = (1700 writes: Writes,1701 queue: LandingQueue,1702 input: {17 unmodified lines1720 left.queue1721 );1722 };1723 2034-/** A landing that names neither the ask it answers nor one it opened. */1724 const namesNoAsk = (landing: LandingView) =>1725 landing.ask === undefined && landing.opened === undefined;1726 2038-/** One project's service over the ports. */1727 export const projectService = (1728 name: ProjectName1729 ): Effect.Effect<ProjectApi, never, ProjectPorts> =>1730 Effect.gen(function* () {5 unmodified lines1736 const rules = Context.get(ports, RulesEvaluator);1737 const alarms = Context.get(ports, Alarms);1738 // Read once, as the ports are: a call runs in its caller's context.1739 const generate = yield* ProjectGenerator;2052- // Typed visibility and the env: the cartridge's when a host2053- // provides it, a project without them otherwise.1740 const visibility = yield* ProjectVisibility;1741 const envPort = yield* ProjectEnv;1742 const draftRuns = yield* DraftRuns;1743 const lock = yield* Semaphore.make(1);2058- // The repo is the project's key, as every repo of its forks is (ADR 0032).1744 const repo = RepoName.make(keyOf(name));1745 1746 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>1747 Effect.provideContext(effect, ports);1748 2064- // ----------------------------------------------------------- hydrate2065-1749 const hydrate: Effect.Effect<Hydrated> = Effect.gen(function* () {1750 const snapshot = yield* store.load();1751 1752 const policy = yield* Option.match(37 unmodified lines1790 snapshot,1791 };1792 });1793 2111- /** The project row once it is live: it has a landed SHA. */1794 const liveRow = (h: Hydrated) =>1795 Option.flatMap(h.project, (row) =>1796 row.state === "live" && row.landed !== undefined1797 ? Option.some({ landed: row.landed, row })1798 : Option.none()1799 );1800 2119- /** The ask as this call has it: as written so far, or as hydrated. */1801 const askNow = (h: Hydrated, writes: Writes, id: AskId) =>1802 Option.fromUndefinedOr(writes.asks.get(id) ?? h.asks.get(id));1803 2123- /** The `ratchets` rows as this call has them: written so far, over the hydrated ones. */1804 const ratchetsNow = (1805 h: Hydrated,1806 writes: Writes1807 ): readonly RatchetRow[] => [3 unmodified lines1811 !h.ratchets.some((held) => ratchetKey(held) === ratchetKey(row))1812 ),1813 ];1814 2135- /** The baselines of the policy's ratchets, as this call has them; the escape ratchets apart. */1815 const baselinesNow = (h: Hydrated, writes: Writes) =>1816 ratchetsNow(h, writes)1817 .filter((row) => !isEscapeRow(row))1818 .map(baselineOf);1819 2141- /** Writes each baseline that differs from the row this call has for it. */1820 const putRatchets = (1821 h: Hydrated,1822 writes: Writes,1823 baselines: readonly RatchetBaseline[]24 unmodified lines1848 ({ row }) => row.ask === ask && sameHandle(row.claimant, handle)1849 )1850 );1851 2174- /** A claim's row as this call has it: as written so far, over the hydrated one. */1852 const claimRowNow = (1853 h: Hydrated,1854 writes: Writes,1855 ask: AskId,20 unmodified lines1876 Option.map(h.policy, ({ claims }) => claims),1877 () => defaultClaims1878 );1879 2203- /**2204- * A claim as its claimant sees it: with its fork's gateway URL, its2205- * check, and the held-back suite it was pinned to, if any.2206- */1880 const viewOf = (1881 policy: Option.Option<Policy>,1882 ask: Option.Option<Ask>,1883 state: ClaimState,23 unmodified lines1907 )1908 );1909 });1910 2238- /**2239- * Whether `who` reads every layer the project keeps a repo for, so every2240- * layer stage 1's paths come from: only then may a refusal name which2241- * paths collide. Reading one layer never names another's paths.2242- */1911+ /** Only a reader of every layer may hear which layer paths collide. */1912 const readsEveryLayer = (who: Principal, snapshot: ProjectSnapshot) => {1913 const readable = visibility.readableLayers(who, snapshot);1914 1915 return (1 unmodified line1917 snapshot.layers.every((row) => readable.has(row.name))1918 );1919 };1920 2252- /** `facts` with the layer paths, and whether its pusher reads every layer. */1921 const layered = (snapshot: ProjectSnapshot, facts: PushFacts) =>1922 Effect.map(visibility.layerPaths(snapshot), (layerPaths): PushFacts => ({1923 ...facts,1924 canReadLayers: readsEveryLayer(facts.pusher, snapshot),1925 layerPaths,1926 }));1927 2260- /**2261- * A push's stage 0–1 facts with what visibility knows: every2262- * layer path, and whether the pusher reads a layer. A project without2263- * typed visibility has neither.2264- */1928 const withLayerFacts = <E>(1929 h: Hydrated,1930 writes: Writes,1931 facts: Effect.Effect<PushFacts, E, ProjectPorts>1 unmodified line1933 withPorts(facts).pipe(1934 Effect.flatMap((found) => layered(snapshotNow(h, writes), found))1935 );1936 2274- // ------------------------------------------------------------ commit2275-2276- /**2277- * Writes everything the call gathered in one commit, with the events'2278- * projection rows beside them, and returns the outbox rows it wrote. A2279- * commit carrying a push event already stored wrote nothing: none.2280- */1937 const commit = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>1938 Effect.gen(function* () {1939 if (isEmpty(writes)) {1940 return [];51 unmodified lines1992 1993 return outbox;1994 });1995 2340- // ------------------------------------------------------------ settle2341-2342- /** Sets the project's alarm to its earliest pending deadline or retry. */1996 const armAlarm = Effect.gen(function* () {1997 const h = yield* hydrate;1998 1999 const deadlines = [6 unmodified lines2006 yield* alarms.set(Array.min(deadlines, DateTime.Order));2007 }2008 });2009 2357- /**2358- * Runs the outbox rows that are due, acknowledges the ones done, puts2359- * the rest back with a later time, then sets the alarm.2360- */2010 const settle = (queue: AnswerQueue, rows: readonly OutboxRow[]) =>2011 Effect.gen(function* () {2012 const now = yield* DateTime.now;2013 16 unmodified lines2030 2031 yield* armAlarm;2032 });2033 2385- /**2386- * One call that writes: under the project's lock it hydrates, runs2387- * `body` (pure transitions, and the port calls that decide them), and2388- * commits what it gathered; then, outside the lock, settles the outbox2389- * rows it wrote. A body that fails commits nothing. Every method calls2390- * it through `write`, which adds the generated follow-up to the body.2391- */2034 const writeLocked = <A, E>(2035 queue: AnswerQueue,2036 body: (2037 h: Hydrated,17 unmodified lines2055 2056 return answered;2057 });2058 2417- // ------------------------------------------------------------ claims2418-2419- /** The ask's state once a claim on it moved: claimed while a live claim holds it. */2059 const askAfter = (2060 h: Hydrated,2061 writes: Writes,2062 ask: AskId,27 unmodified lines2090 writes.asks.set(ask, { ...open.value, state: next });2091 }2092 };2093 2455- /**2456- * Records a claim's step: its row, its fork, its events and its ask's2457- * state. The row keeps the agents the claim's pushes named: `assisted`2458- * when given (a claim granted anew starts with none), else as it had them.2459- */2094 const applyClaim = (2095 h: Hydrated,2096 writes: Writes,2097 ask: AskId,54 unmodified lines2152 2153 askAfter(h, writes, ask, step);2154 });2155 2522- // ------------------------------------------------------------ policy2523-2524- /** The config folder at a commit, evaluated; none when it can't be. */2156 const evaluateAt = (row: ProjectRow, at: LandedSha, now: DateTime.Utc) =>2157 Effect.gen(function* () {2158 const previous = yield* Option.match(2159 Option.fromUndefinedOr(row.policy),37 unmodified lines2197 )2198 );2199 });2200 2570- /**2571- * The project row with the policy at `at`: the config folder bundled2572- * there and evaluated. A Lander or evaluator that fails keeps the policy2573- * the row held.2574- */2201 const withPolicyAt = (row: ProjectRow, at: LandedSha, now: DateTime.Utc) =>2202 Effect.flatMap(evaluateAt(row, at, now), (policy) =>2203 Option.match(policy, {2204 onNone: () => Effect.succeed(row),5 unmodified lines2210 })),2211 })2212 );2213 2588- /**2589- * Whether the landed tree at `at` has a config folder at its root: one2590- * commit read and one tree read. A commit or tree the repo does not have2591- * has none.2592- */2214 const hasConfigAt = (at: LandedSha) =>2215 Effect.gen(function* () {2216 const landedCommit = yield* host.readCommit(repo, at);2217 10 unmodified lines2228 )2229 );2230 }).pipe(Effect.orDie);2231 2611- /**2612- * The public policy once one has evaluated; before that, after the first2613- * landing, why not: the landed tree has no config folder (the defaults2614- * found no test command), or it has one that did not evaluate. Derived2615- * here, never stored, so a project that never evaluated says why at once.2616- */2232 const policyStatus: Effect.Effect<PolicyStatus> = Effect.gen(function* () {2233 const h = yield* hydrate;2234 2620- // Where the project came from, when it was imported (ADR 0031).2235 const origin = field(2236 "importedFrom",2237 Option.flatMapNullishOr(h.project, (row) => row.importedFrom)2238 );20 unmodified lines2259 },2260 };2261 });2262 2649- /**2650- * Each landing with the ask it opened: a row written before landings2651- * carried `opened` gets it from the asks, the one with no parent whose2652- * `openedIn` is its SHA. Only a landing that names no ask is looked up,2653- * and the asks are read once for the whole batch.2654- */2263+ /** Older landing rows carry no `opened`: it is found from the asks' `openedIn`. */2264 const withOpened = (found: readonly LandingView[]) =>2265 Effect.gen(function* () {2266 if (!found.some(namesNoAsk)) {2267 return found;17 unmodified lines2285 : landing;2286 });2287 });2288 2680- // --------------------------------------------------------- generated2681-2682- /** A file's text at a landed commit of the canonical repo; none where it has no such file. */2289 const textAt = (at: LandedSha) => (path: string) =>2290 host2291 .readFile(repo, Revision.Commit({ sha: at }), RepoPath.make(path))2292 .pipe(2293 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))),2294 Effect.orDie2295 );2296 2691- /**2692- * The platform's own landing of the regenerated files on top of2693- * `landed`, recorded with the landing it follows: the files composed2694- * onto main and landed through the Lander, a compare-and-swap push of2695- * `main` then the mirror, as every platform landing is, with the request2696- * id `gen-<landed>`, so a replay finds its commit.2697- */2297 const landFollowUp = (input: {2298 readonly h: Hydrated;2299 readonly landed: LandedSha;2300 readonly landing: LandingView;2301 readonly now: DateTime.Utc;2703- /** The policy read at `landed`, encoded as the row holds it. */2302 readonly policy: Exclude<ProjectRow["policy"], undefined>;2303 readonly row: ProjectRow;2304 readonly writes: Writes;2305 }) =>53 unmodified lines2359 writes.project.set("row", moved);2360 });2361 2362 /**2765- * A follow-up that did not land. When canonical `main` still stands at2766- * `landed`, nothing of it reached main: the landing it follows stands,2767- * and the failure is logged. When main moved on (the push went through2768- * and the Lander's answer was lost), or where it stands can't be read,2769- * the call fails and commits nothing, so the project's landed SHA never2770- * falls behind main: the same call run again finds both commits by their2771- * request ids.2363+ * When main still stands at `landed`, the failure is only logged. When main2364+ * moved on (the Lander's answer was lost) or can't be read, the call fails,2365+ * so the landed SHA never falls behind main; a rerun finds both commits by2366+ * their request ids.2367 */2368 const unlanded = <E>(landed: LandedSha, cause: Cause.Cause<E>) =>2369 Effect.gen(function* () {2370 const refs = yield* Effect.option(host.refs(repo));13 unmodified lines2384 return yield* Effect.orDie(Effect.failCause(cause));2385 });2386 2387 /**2793- * After a call moved the landed SHA (the first adoption, an answer, a2794- * decider's own landing, an ask opened, a vouch): the platform's own2795- * landing of the regenerated contribute skill and AGENTS.md block on2796- * top, when the policy read at the new landed SHA changes what they say.2797- * It never joins the landing that changed the config2798- * ("land only the checked tree"), and it is recorded in the same commit2799- * as the landing it follows, under the project's lock. It is2800- * bookkeeping: one that cannot land is logged, and the landing it follows2801- * stands; the next landing that changes the config writes the files2802- * again (`unlanded`).2388+ * A separate landing on top, never joined to the one that changed the2389+ * config (land only the checked tree). Bookkeeping: a failure is logged2390+ * and the next config change writes the files again.2391 */2392 const followUp = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2393 Effect.gen(function* () {2394 const row = writes.project.get("row");37 unmodified lines2432 )2433 );2434 });2435 2848- /**2849- * After a call moved the landed SHA: the env port hears the2850- * move (a `ProxyWidened` decision for a widened proxy), and, when the2851- * policy was read at the new SHA, the visibility port hears it (layers2852- * provisioned and declared, a narrowing's `PostureChange`). Their plans2853- * go into the same commit; their effects settle after it. Without the2854- * cartridge both plans are empty.2855- */2436 const visibilityAfter = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2437 Effect.gen(function* () {2438 const row = writes.project.get("row");2439 const landed = row?.landed;34 unmodified lines2474 now2475 );2476 });2477 2898- /** What follows a call that may have landed: the generated files, then visibility. */2478 const afterLandings = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2479 Effect.andThen(followUp(h, writes, now), visibilityAfter(h, writes, now));2480 2902- /**2903- * One call that writes (`writeLocked`), with the generated follow-up of2904- * any landing the body recorded and what visibility makes of it, in the2905- * same commit.2906- */2481 const write = <A, E>(2482 queue: AnswerQueue,2483 body: (2484 h: Hydrated,4 unmodified lines2489 writeLocked(queue, (h, writes, now) =>2490 Effect.tap(body(h, writes, now), () => afterLandings(h, writes, now))2491 );2492 2919- /** A `main` for an imported repo whose branch had another name, at its tip. */2493 const mainAt = (tip: CommitSha) =>2494 Effect.gen(function* () {2495 const empty = { fs: memoryFs(), gitdir: "/adopt.git" };2496 10 unmodified lines2507 );2508 });2509 2510 /**2938- * An imported repo adopted: its tip becomes the first landed SHA, on a2939- * `main` of its own when the imported branch had another name. The tip2940- * is `main`'s, else the named branch's, else the one branch the import2941- * made (the remote's default, `master` or any other).2511+ * The tip is `main`'s, else the named branch's, else the one branch the2512+ * import made.2513 *2943- * `adopt` runs only while the project has no row, so a repo that exists2944- * is this project's earlier import, which died after Artifacts made the2945- * repo (a slow import outlasting the binding's wait): it is waited for2946- * and adopted, as `initBody` keeps an empty repo a failed `create` left.2947- * ASSUMPTION: the retry names the same remote; the repo holds what the2948- * first import copied.2514+ * Runs only while the project has no row, so an existing repo is this2515+ * project's earlier import that died after Artifacts made it; it is waited2516+ * for and adopted. Assumes the retry names the same remote.2517 */2518 const adopt = (from: { readonly branch?: string; readonly url: string }) =>2519 Effect.gen(function* () {2520 const branch = Option.map(51 unmodified lines2572 2573 return LandedSha.make(tip.value);2574 });2575 3008- // ------------------------------------------------------------ answers3009-3010- /** The answer's run, as `answer` and a step see it. */2576 const runOf = (h: Hydrated, found: Answered): AnswerRun => {2577 const { landing, verdict } = found.record;2578 const { request } = landing;2579 58 unmodified lines2638 ...Option.getOrElse(judgedRun, () => ({})),2639 };2640 };2641 3077- /** The verdict on a checked tree: the gate's `verdictOf` over what the checks saw. */2642 const verdictFor = (input: {2643 readonly ask: Ask;2644 readonly checking: Checking;2645 readonly heldBack: readonly HeldBackResult[];52 unmodified lines2698 )2699 );2700 });2701 3138- /** The claim that answered an ask, answered by its landing. */2702 const answerClaim = (2703 h: Hydrated,2704 writes: Writes,2705 ask: AskId,16 unmodified lines2722 }2723 ),2724 });2725 3163- /** Every ask as this call has it: as written so far, over the hydrated ones. */2726 const asksNow = (h: Hydrated, writes: Writes): ReadonlyMap<AskId, Ask> =>2727 new Map([...h.asks, ...writes.asks]);2728 3167- /**3168- * A migrate family once its child `landed` closed: each3169- * child waiting on its siblings opens when the last of them lands, and3170- * the parent closes on the landing that closes its last child.3171- */2729 const familyAfter = (2730 h: Hydrated,2731 writes: Writes,2732 landed: AskId,35 unmodified lines2768 writes.events.push(askClosed(parent.value, at.sha, at.now));2769 }2770 };2771 3215- /**3216- * A landing on main recorded: the landing, its ask closed, the answering3217- * claim answered, its migrate family moved on, the landed SHA moved and3218- * the policy read there.3219- */2772 const recordLanding = (2773 h: Hydrated,2774 writes: Writes,2775 landing: Landing,2776 landed: {3225- /** The `Held-back:` trailer's value the landing carries, if its suite judged it. */2777 readonly heldBack: Option.Option<string>;2778 readonly sha: LandedSha;2779 readonly verdict: Option.Option<Verdict>;2780 },51 unmodified lines2832 );2833 }2834 });2835 3285- /** One of a landing's effects, settled by the project or handed to its run. */2836 const settleEffect = (2837 context: {2838 readonly before: LandingState;2839 readonly h: Hydrated;56 unmodified lines2896 RunChecks: () => Effect.succeed(handed),2897 });2898 };2899 3350- /**3351- * The verdict after a step: a fresh one when the checks just judged the3352- * tree under way, else the one the answer had.3353- */2900 const verdictAfter = (input: {2901 readonly ask: Option.Option<Ask>;2902 readonly before: LandingState;2903 readonly command: LandingCommand;30 unmodified lines2934 (made) => ({ fresh: true, verdict: Option.some(made) })2935 );2936 };2937 3392- /** The row that lands a request's job again, for the bookkeeping it left unwritten. */2938 const bookkeepingRow = (input: {2939 readonly ask: Option.Option<Ask>;2940 readonly heldBack: Option.Option<string>;2941 readonly landing: Landing;26 unmodified lines2968 DateTime.addDuration(input.now, "1 second")2969 );2970 };2971 3427- /** Bookkeeping a land reported unwritten: landed again later, for it alone. */2972 const keepBooks = (input: {2973 readonly ask: Option.Option<Ask>;2974 readonly before: LandingState;2975 readonly command: LandingCommand;26 unmodified lines3002 (row) => input.writes.outbox.push(row)3003 );3004 };3005 3462- /**3463- * The checks' report on the tree under way, judged against the3464- * project's ratchets. Each of the policy's3465- * ratchets the merged tree counts over its baseline is refused3466- * `Weakened{ratchet}`, unless a reasoned escape the answer adds in its3467- * territory asks to raise it (`RaiseRatchet`); each reasoned escape over3468- * its territory's escape baseline waits on a `Waiver`, unless a decider3469- * already accepted it for this answer (`waived`: a re-check after main3470- * moved asks nothing twice). Nothing waits once something refused; the3471- * decisions open with their subject's default, `decline`. The answer's3472- * lines unread are the gate's trouble (`VerifierBlocked`): no escape3473- * lands unweighed. What the tree counted is kept for the answer's3474- * landing.3475- */3006 const ratchetJudged = (input: {3007 readonly checking: Checking;3008 readonly command: Data.TaggedEnum.Value<LandingCommand, "Checked">;3009 readonly h: Hydrated;143 unmodified lines3153 measured: Option.some<Measured>({ declared, escapes }),3154 };3155 });3156 3627- /** An accepted `RaiseRatchet` the answer waits on raises its baseline: the one way a baseline rises. */3157 const raiseOnDecision = (3158 h: Hydrated,3159 writes: Writes,3160 decided: Option.Option<DecidedOn>19 unmodified lines3180 );3181 }3182 };3183 3655- /**3656- * A landing's counts become the baselines: each of the policy's3657- * ratchets lowered where the landed tree counts less (or set, where it3658- * had none), and each territory's escapes as they stand with the3659- * answer's in; the gate let no raise land that a decider did not accept.3660- */3184 const ratchetsAtLanding = (3185 h: Hydrated,3186 writes: Writes,3187 measured: Option.Option<Measured>,15 unmodified lines3203 })),3204 ]);3205 };3206 3684- /** One reported step of an answer, under the lock: its transition and all it settles. */3207 const advanceBody =3208 (requestId: RequestId, reported: LandingCommand, report?: AnswerReport) =>3209 (h: Hydrated, writes: Writes, now: DateTime.Utc) =>3210 Effect.gen(function* () {122 unmodified lines3333 outcome: outcomeOf(state),3334 };3335 });3336 3815- // ------------------------------------------------------------ writes3816-3817- /**3818- * The first adoption as a landing: the initializer's first push, or an3819- * import's tip. It answers no ask, has no parent and credits no one;3820- * its row lets `landing` (and so OnPush) know the commit as the3821- * platform's own, and its event lists the project on the front page3822- * even when no policy evaluates and nothing else happens in it.3823- */3337 const landAdoption = (3338 writes: Writes,3339 author: Handle,3340 sha: LandedSha,12 unmodified lines3353 now3354 );3355 };3356 3844- /**3845- * The project's adoption, the one landing with no parent: in the3846- * snapshot's newest landings, else found by walking back from the last3847- * landed SHA through each landing's parent.3848- */3357 const adoptionOf = (h: Hydrated, row: ProjectRow) =>3358 Effect.gen(function* () {3359 const kept = h.landings.find(({ parent }) => parent === undefined);3360 19 unmodified lines3380 3381 return Option.none<LandingView>();3382 });3383 3876- /**3877- * An import asked again by its initializer converges (ADR 0031): with3878- * the source the row keeps, it answers as the first call did; for a row3879- * that keeps no source yet, the source is written first. Only an3880- * import's row takes one: its adoption landed in the call that made it,3881- * so the adoption's `landedAt` is the row's `createdAt`, where a first3882- * push lands later. Any other repeat is `ProjectExists`, as before.3883- */3384 const keepSource = (3385 caller: Person,3386 from: ImportSource,3387 row: ProjectRow,51 unmodified lines3439 );3440 }3441 3442 // A project is made only in a namespace of one's own: the caller's3943- // handle, or the source namespace the import's URL names (ADR 0032).3443+ // handle, or the source namespace the import's URL names.3444 const owner = ownerOf(name);3445 3446 const mine = isSourceNamespace(owner)3447 ? input.import !== undefined &&76 unmodified lines3524 3525 return { landed };3526 });3527 4028- /**4029- * The ask a decider's files state, read from the config folder at the4030- * commit they compose; its kind, as every rule but the ask itself, is4031- * main's (ADR 0005).4032- */3528 const statedAsk = (input: {3529 readonly composed: CommitSha;3530 readonly id: AskId;3531 readonly now: DateTime.Utc;34 unmodified lines3566 3567 return stated;3568 });3569 4075- /** The judge an ask's files touch beyond their own (stage 1, as an ask opens). */3570 const touchedJudge = (input: {3571 readonly ask: Ask;3572 readonly caller: Person;3573 readonly files: readonly AskFile[];24 unmodified lines3598 }),3599 (refusals) => Array.findFirst(refusals, isTouchedJudge)3600 );3601 4108- /**4109- * An ask's own check run twice on the composed commit, and the lane it4110- * ran as; `watch` sees both runs, and asks for the lane's output.4111- */3602 const runTwice = (3603 policy: Policy,3604 ask: Ask,3605 composed: CommitSha,31 unmodified lines3637 3638 return { lane: lane.value.lane, runs };3639 });3640 4151- /**4152- * Red first: the ask's check fails twice on the composed commit, the4153- * same way (a `lintToZero` check, by its count). Gives the counts of the4154- * policy's ratchets the check's own run read on the way.4155- */3641 const redTwice = (3642 policy: Policy,3643 ask: Ask,3644 composed: CommitSha,16 unmodified lines3661 3662 return [];3663 });3664 4180- /**4181- * Red first for a check that counts callers (`migrate`, `symbolAbsent`):4182- * twice on the composed commit its count command prints the same4183- * callers, and some in the ask's territory. Gives the count.4184- */3665 const callersTwice = (3666 policy: Policy,3667 ask: Ask,3668 composed: CommitSha,20 unmodified lines3689 3690 return once;3691 });3692 4213- /**4214- * The family files of a split that would land on a path already taken:4215- * an ask the project holds, one main's config folder states, one of the4216- * decider's own files, or another file of the family. Overwriting any4217- * would change the judge beyond the ask's own files (`TouchedJudge`).4218- */3693 const takenBy = (3694 h: Hydrated,3695 writes: Writes,3696 input: {17 unmodified lines3714 : []3715 );3716 };3717 4244- /**4245- * What a migrate (or `symbolAbsent`) ask's opening lands: red first by4246- * its callers, then, when its callers sit in two or more of its4247- * modules, its family's files beside the decider's, every4248- * ask of the family, and the callers ratchet at the counted total.4249- */3718 const migrateOpening = (input: {3719 readonly ask: Ask;3720 readonly composed: { readonly commit: CommitSha; readonly tree: TreeSha };3721 readonly files: Array.NonEmptyReadonlyArray<AskFile>;68 unmodified lines3790 tree,3791 };3792 });3793 4326- /**4327- * The landing that opens an ask: its files on main, authored by its4328- * asker. A migrate ask's landing names the children it opened with it.4329- */3794 const landAsk = (input: {3795 readonly ask: Ask;3796 readonly assisted: readonly AgentTrailer[];3797 readonly children: readonly AskId[];39 unmodified lines3837 3838 return Effect.map(landing, ({ sha }) => ({ credits, requestId, sha }));3839 };3840 4377- /**4378- * Everything opening an ask checks, with nothing written and nothing4379- * landed: the files composed onto main, the ask they state evaluated at4380- * the composed commit, the judge they touch, a weak check, and red4381- * first (or a migrate ask's callers and family). Succeeds with what the4382- * landing needs; fails with the ask as it stands when it is open4383- * already, so nothing is to land. `opening.decider` must decide for the4384- * ask's territory. `watch` sees the check's runs.4385- */3841 const prepareOpening = (3842 h: Hydrated,3843 writes: Writes,3844 now: DateTime.Utc,103 unmodified lines3948 3949 return Result.succeed({ ask, main, opens, row });3950 });3951 4497- /**4498- * An ask opened from its files, red first, and landed as a platform4499- * commit: what `openAsk` does for a decider, and what an accepted4500- * proposal does for its proposer. `opening.decider` must decide4501- * for the ask's territory; `opening.asker` asks it and authors the4502- * landing, which carries `opening.credits` and discloses4503- * `opening.assisted`.4504- */3952 const openFrom = (3953 h: Hydrated,3954 writes: Writes,3955 now: DateTime.Utc,42 unmodified lines3998 assisted: opening.assisted,3999 author: opening.asker,4000 credits: landed.credits,4001 landedAt: now,4555- // The ask it opened: a migrate family's parent, never a step.4002 opened: ask.id,4003 parent: main,4004 project: name,4005 requestId: landed.requestId,45 unmodified lines4051 decider: caller,4052 files: input.files,4053 });4054 4609- /**4610- * An ask's files rehearsed: `prepareOpening` by the first decider of4611- * their paths, its lane asked for its output, and nothing landed or4612- * written. A final refusal is `Refused`, with why and the output's tail.4613- */4055 const rehearse = (4056 h: Hydrated,4057 now: DateTime.Utc,4058 files: readonly ConfigFile[]80 unmodified lines4139 })4140 );4141 });4142 4702- /** Every blob's path in the canonical tree at `at`, sorted, at most `MAX_DRAFT_PATHS`. */4143 const pathsAt = (at: LandedSha) => {4144 const walk = (4145 prefix: string,4146 tree: ObjectId25 unmodified lines4172 })4173 );4174 };4175 4736- /**4737- * What a draft's run reads for one round: an open proposal's want and4738- * territory, the landed commit, the public policy there, and every path4739- * of the canonical tree.4740- */4176 const draftContextOf = (proposal: ProposalId, round: number) =>4177 Effect.gen(function* () {4178 const h = yield* hydrate;4179 const found = Array.findFirst(h.proposals, ({ id }) => id === proposal);25 unmodified lines4205 want: wanted.want,4206 };4207 });4208 4774- /** Whether a person may claim an ask, by the trust rules, and the ask's race. */4209 const trustOf = (4210 h: Hydrated,4211 policy: Policy,4212 ask: Ask,154 unmodified lines4367 4368 return { released: step.effects.length > 0 };4369 });4370 4937- /** The claimant's own push keeps their claim alive, whatever the gate says of it. */4371 const keepAlive = (4372 h: Hydrated,4373 writes: Writes,4374 input: {43 unmodified lines4418 ),4419 });4420 };4421 4989- /**4990- * Canonical `main` moved to a commit that is neither the landed SHA nor4991- * a landing, or deleted, opens a `StrayPush` decision, in the same4992- * commit as the push event's row, so an event reported again opens4993- * nothing.4994- */4422 const strayOn = (4423 h: Hydrated,4424 writes: Writes,4425 input: { readonly landed: LandedSha; readonly push: PushReport },111 unmodified lines4537 4538 return refusals;4539 });4540 5114- /**5115- * The receipt of an answer given before: the caller's own request5116- * again, or the same head from them while that answer stands. A5117- * request id another person's answer holds is not the caller's to5118- * replay, nor to take: `NotClaimed`.5119- */4541+ /** A request id another person's answer holds is not the caller's to replay: `NotClaimed`. */4542 const earlier = (4543 h: Hydrated,4544 caller: Person,4545 input: {23 unmodified lines4569 4570 return Effect.succeed(Option.map(given, ({ record }) => record.receipt));4571 };4572 5151- /** A new answer request, queued and started on main as it stands, with its receipt. */4573 const queueAnswer = (4574 writes: Writes,4575 request: Request,4576 input: {137 unmodified lines4714 { ask: input.ask, main: live.value.landed, now }4715 );4716 });4717 5297- /** Every live claim whose deadline passed, moved by `Tick`. */4718 const tickAll = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>4719 Effect.forEach(4720 h.claims.filter(({ state }) => isLive(state)),4721 ({ row, state }) =>14 unmodified lines4736 ),4737 { discard: true }4738 );4739 5320- // ------------------------------------------------------------ reads5321-4740 const statusOf = (caller: Person) =>4741 Effect.gen(function* () {4742 const h = yield* hydrate;4743 55 unmodified lines4799 4800 return Effect.succeed(field("verdict", verdict));4801 });4802 5385- // ---------------------------------------------------------- evidence5386-5387- /**5388- * Who may read the log named `ref`, and then the log: the name must5389- * point at this project (anything else is that project unknown, as a5390- * name nobody made is); then the caller must decide here, or be the5391- * claimant of the answer it points at (`NotDecider` otherwise, whether5392- * or not a log is kept, so the reply tells no one which logs exist);5393- * then the log must be kept.5394- */4803+ /** `NotDecider` comes before the log lookup, so the reply never tells which logs exist. */4804 const evidenceOf = (caller: Principal, ref: LogRef) =>4805 Effect.gen(function* () {4806 const named = logOfRef(ref);4807 30 unmodified lines4838 4839 return { lane, ...tailOf(kept.value) };4840 });4841 5433- // -------------------------------------------------------- visibility5434- //5435- // Each delegates to `ProjectVisibility` or `ProjectEnv`: the5436- // service hydrates, the port decides over the project as the call has5437- // it, and the service commits the port's rows with its own.5438-5439- /** The env a check of unlanded code carries, for the project as it is stored. */4842 const unlandedEnv = Effect.flatMap(hydrate, (h) =>4843 envPort.runEnv({ landed: false }, h.snapshot)4844 );4845 5444- /** The claim an answer is made through, with the suite it was pinned to: none for a decider's own landing, or a claim that pinned none. */4846 const pinnedClaimOf = (h: Hydrated, record: AnswerRecord) => {4847 const { request } = record.landing;4848 4849 return Option.flatMap(request.ask, (ask) =>6 unmodified lines4856 )4857 );4858 };4859 5459- /** An answer's run as `answer` gives it: with the env its checks carry. */4860 const answerOf = (requestId: RequestId) =>4861 Effect.gen(function* () {4862 const h = yield* hydrate;4863 const found = findAnswer(h, requestId);24 unmodified lines4888 ? Option.none<HeldBackJob>()4889 : yield* visibility.heldBackJob(claim.value, h.snapshot);4890 });4891 5492- /**5493- * A held-back run of the tree the answer is being checked on, judged5494- * once: the same tree reported again answers as it did (its attempt5495- * counted once, principle 8), and a run that no longer checks a tree,5496- * or has no pinned suite, earns nothing.5497- */4892 const heldBackBody =4893 (requestId: RequestId, results: readonly HeldBackResult[]) =>4894 (h: Hydrated, writes: Writes, now: DateTime.Utc) =>4895 Effect.gen(function* () {55 unmodified lines4951 layerPaths: [...paths],4952 };4953 });4954 5561- /** The project's env shape at its landed SHA; none to read before anything landed. */4955 const envSchemaOf = Effect.gen(function* () {4956 const h = yield* hydrate;4957 4958 const landed = Option.flatMap(h.project, ({ landed: at }) =>28 unmodified lines4987 4988 return set.result;4989 });4990 5598- /** A plan a port makes of the project as this call has it, taken into the call. */4991 const planned =4992 (4993 plan: (4994 snapshot: ProjectSnapshot,4 unmodified lines4999 Effect.flatMap(plan(snapshotNow(h, writes), now), (made) =>5000 applyPlan(writes, made, now)5001 );5002 5611- // ---------------------------------------------------------- deciders5612-5613- /** The decider-facing methods, over the same hydrate, write and helpers. */5003 const decided = deciders<Hydrated, Writes>({5004 advance: (h, writes, now, requestId, command) =>5005 advanceBody(requestId, command)(h, writes, now),5006 enqueue: queueAnswer,32 unmodified lines5039 5040 yield* settle(queue, rows);5041 });5042 5654- // ------------------------------------------------------------ the api5655-5043 const api: ProjectApi = {5044 [envSchemaMethod]: (caller) =>5045 checked(MethodSchemas[envSchemaMethod], [caller], envSchemaOf),5046 admissionPlan: (input) =>323 unmodified linesmodified:packages/project/src/projection.ts+1 added-9 removed
1-/**2- * The `Projection` port: where the project's events go to feed read models3- * outside its Durable Object, such as the front page's D1 table.4- * The settle step hands it the outbox rows whose body is a `ProjectedEvent`,5- * in the order the events were numbered; it is retried from the outbox on6- * failure, so `apply` must be idempotent by `(project, event.seq)`.7- */1 import { ProjectEvent } from "@repo/protocol/domain/event";2 import { ProjectName } from "@repo/protocol/ids";3 import { Context, Schema } from "effect";4 import type { Effect } from "effect";5 6 import type { OutboxRow } from "./project-store/rows.ts";7 15-/** An outbox row's body for the projection: one numbered event of one project. */8 export const ProjectedEvent = Schema.TaggedStruct("Projected", {9 event: ProjectEvent,10 project: ProjectName,11 });12 13 export type ProjectedEvent = typeof ProjectedEvent.Type;14 23-/** The read model refused or could not take the rows; they stay in the outbox. */15 export class ProjectionFailed extends Schema.TaggedError<ProjectionFailed>()(16 "ProjectionFailed",17 { reason: Schema.String }18 ) {}19 20 export class Projection extends Context.Service<21 Projection,22 {23+ /** Retried on failure: idempotent by `(project, event.seq)`. */24 readonly apply: (25 rows: readonly OutboxRow[]26 ) => Effect.Effect<void, ProjectionFailed>;27 }1 unmodified linemodified:packages/project/src/projects.ts-17 removed
1-/**2- * The `Projects` port: the one way a caller reaches a project by its name.3- * Each project is one service over its own store (one Durable Object on a4- * stage, `DoProjects`); this port finds it, or makes a new one. `creditsFor`5- * folds a person's credits over the projects it is given.6- *7- * Adapters: `/memory` here, which keeps one memory store per project.8- */1 import type { CreditSummary } from "@repo/protocol/domain/record";2 import type { Handle, ProjectName } from "@repo/protocol/ids";3 import { Anonymous } from "@repo/protocol/principal";4 import type { ProjectExists, UnknownProject } from "@repo/protocol/refusal";3 unmodified lines8 9 export class Projects extends Context.Service<10 Projects,11 {20- /** A project made before; one never made is `UnknownProject`. */12 readonly get: (13 project: ProjectName14 ) => Effect.Effect<ProjectApi, UnknownProject>;24- /** A new, empty project, ready for `initProject`; a name taken is `ProjectExists`. */15 readonly create: (16 project: ProjectName17 ) => Effect.Effect<ProjectApi, ProjectExists>;18 }19 >()("project/Projects") {}20 31-/**32- * A person's credits across `projects`, by project, area and role: each33- * project's own count (`credits`), joined in project order, as the public34- * `credits` contract answers them. A project not made is skipped. The port35- * finds projects by name and lists none, so the caller names them: the36- * platform's handler passes the projection's list.37- */21 export const creditsFor = (22 handle: Handle,23 projects: readonly ProjectName[]24 ): Effect.Effect<readonly CreditSummary[], never, Projects> =>15 unmodified linesmodified:packages/project/src/queue.ts+1 added-18 removed
1-/**2- * The project's serial landing queue, over the landing lifecycle's3- * `LandingQueue` value: answers are checked side by side, but land on main4- * one at a time. A request asks for the slot when its lifecycle reaches5- * `Landing`, lands only while it holds it, and leaves when it is no longer6- * landing (landed, refused, or sent back to merge by a moved main); the7- * next in line is admitted then.8- */1 import type { RequestId } from "@repo/protocol/ids";2 import { Effect, Option, Schema } from "effect";3 4 import { enqueue, LandingQueue, next as admitNext, settle } from "./landing.ts";5 14-/** No request waiting, none landing. */6 export const emptyQueue: LandingQueue = { active: Option.none(), order: [] };7 8 const decodeQueue = Schema.decodeUnknownEffect(LandingQueue);9 10 const encodeQueue = Schema.encodeEffect(LandingQueue);11 21-/** The queue as the store held it: `null` until a commit first writes one. */12+/** `null` until a commit first writes one. */13 export const queueOf = (stored: Schema.Json): Effect.Effect<LandingQueue> =>14 stored === null15 ? Effect.succeed(emptyQueue)16 : Effect.orDie(decodeQueue(stored));17 27-/** The queue as the store keeps it. */18 export const storedQueue = (queue: LandingQueue): Effect.Effect<Schema.Json> =>19 Effect.orDie(encodeQueue(queue));20 31-/** Whether `id` holds the landing slot. */21 export const holdsSlot = (queue: LandingQueue, id: RequestId): boolean =>22 Option.contains(queue.active, id);23 35-/** A move of the queue, and the request it admitted to the slot, if any. */24 export interface Moved {25 readonly admitted: Option.Option<RequestId>;26 readonly queue: LandingQueue;27 }28 41-/**42- * `id` asks for the slot: it joins the back of the line (or keeps its43- * place), and the front of the line is admitted if the slot is free.44- */29 export const askToLand = (queue: LandingQueue, id: RequestId): Moved => {30 const { admit, queue: moved } = admitNext(enqueue(queue, id));31 32 return { admitted: admit, queue: moved };33 };34 51-/** `id` leaves the line or the slot, and the next in line is admitted if the slot is free. */35 export const leave = (queue: LandingQueue, id: RequestId): Moved => {36 const { admit, queue: moved } = admitNext(settle(queue, id));37 38 return { admitted: admit, queue: moved };1 unmodified linemodified:packages/project/src/ratchets.ts+2 added-30 removed
1-/**2- * Ratchets' baselines, and the rules that move them (GLOSSARY "Ratchet"):3- * a baseline per (ratchet, territory), recorded at landing and lowered by a4- * landing with no one asking; the only way up is a `RaiseRatchet` decision a5- * decider accepts. Pure: the counts come from `@repo/checks/kinds/ratchet`'s6- * `measure`, an answer's counts are judged against these baselines there7- * (`judgeRatchets`, which `<cli> check` judges with too), and the baselines8- * live in the Project DO's `ratchets` rows (no suppressions file in the9- * tree).10- */1 import { sameRatchet } from "@repo/checks/kinds/ratchet";2 import type {3 RaiseRatchet,4 RatchetCount,2 unmodified lines7 import type { Choice } from "@repo/protocol/domain/decision";8 import type { LandedSha, RatchetName } from "@repo/protocol/ids";9 import { Array, Option } from "effect";10 21-/** A ratchet's baseline in one territory, and the landed SHA that set it. */11 export interface RatchetBaseline {12 readonly ratchet: RatchetName;13 readonly territory: string;14 readonly count: number;15 readonly setAt: LandedSha;16 }17 29-/** A baseline a landing lowered, from what to what. */18 export interface Lowered {19 readonly ratchet: RatchetName;20 readonly territory: string;21 readonly before: number;22 readonly after: number;23 }24 37-/** The baselines after a landing, and the ones it lowered. */25 export interface BaselinesAfterLanding {26 readonly baselines: readonly RatchetBaseline[];27 readonly lowered: readonly Lowered[];28 }29 30 const baselineOf = (baselines: readonly RatchetBaseline[], key: RatchetKey) =>31 Array.findFirst(baselines, sameRatchet(key));32 46-/**47- * The baselines after a landing measured `measured` at `landed`: each count48- * under its baseline lowers it (and is named in `lowered`), a ratchet with no49- * baseline yet takes its count, and nothing else moves. A landing never50- * raises a baseline: an accepted `RaiseRatchet` already set it.51- */33+/** A landing lowers baselines or sets new ones, never raises one: only an accepted `RaiseRatchet` does. */34 export const afterLanding = (35 baselines: readonly RatchetBaseline[],36 measured: readonly RatchetCount[],37 landed: LandedSha38 ): BaselinesAfterLanding => {57- // Each baseline reads the landing's first count for its key, as `first`58- // does for a ratchet with none yet.39 const lowered = baselines.flatMap((held) =>40 Array.findFirst(measured, sameRatchet(held)).pipe(41 Option.filter(({ count }) => count < held.count),42 Option.map(({ count }): Lowered => ({25 unmodified lines68 69 return { baselines: [...kept, ...first], lowered };70 };71 92-/** Whether a choice gives a raise its way: `accept` (or `adopt`) does, `decline` and `revert` don't. */72 const raisesOn = {73 accept: true,74 adopt: true,75 decline: false,76 revert: false,77 } as const satisfies Record<Choice, boolean>;78 100-/**101- * The baselines after a decider answered a `RaiseRatchet`: accepted, the102- * ratchet's baseline in that territory rises to the raised count, set at103- * `landed`; declined, nothing moves. The one way a baseline rises. An104- * accepted raise never lowers one: when another accepted raise already took105- * the baseline past this one's count, main may count that much, and a lower106- * baseline would refuse every later answer for a count it did not raise.107- */79+/** An accepted raise never lowers a baseline another accepted raise already took past it. */80 export const decideRaise = (81 baselines: readonly RatchetBaseline[],82 subject: RaiseRatchet,83 choice: Choice,21 unmodified linesmodified:packages/project/src/repo-names.ts+1 added-17 removed
1-/**2- * What a repo's name says it is: a project's canonical repo3- * `<key>`, a claim's fork `<key>--<ask>--<handle>`, or a person's4- * working fork `<key>--me--<handle>`, each handle in lowercase, where the5- * key is the project's flat key (ADR 0032). `--` occurs in no key or ask6- * name, so a name splits back into its parts.7- * Pure: the platform's gateway, handlers and OnPush read names with it, and8- * a project lists its forks by it.9- */1 import {2 AskId,3 Handle,4 keyOf,3 unmodified lines8 } from "@repo/protocol/ids";9 import type { ProjectName } from "@repo/protocol/ids";10 import { Data, Option, Schema } from "effect";11 21-/** A claim's fork, as `@repo/protocol/ids` spells it. */12 export { claimForkName } from "@repo/protocol/ids";13 24-/** What a repo is, read from its name alone. */14 export type RepoKind =15 | { readonly _tag: "Canonical"; readonly project: ProjectName }16 | {17 readonly _tag: "ClaimFork";18 readonly project: ProjectName;19 readonly ask: AskId;31- /** As the name spells it: in lowercase. */20 readonly handle: Handle;21 }22 | {23 readonly _tag: "WorkingFork";24 readonly project: ProjectName;37- /** As the name spells it: in lowercase. */25 readonly handle: Handle;26 }27 | { readonly _tag: "Unknown" };28 29 export const RepoKind = Data.taggedEnum<RepoKind>();30 31 const asKey = Schema.decodeOption(ProjectKey);32 46-/** The project a repo name's first part names: its key, read back (ADR 0032). */33 const asProject = (first: string) => Option.flatMap(asKey(first), nameOfKey);34 35 const asAsk = Schema.decodeOption(AskId);36 37 const asHandle = Schema.decodeOption(Handle);38 53-/** The word that names a working fork where a claim's fork names its ask. */39 const WORKING = "me";40 56-/** What `name` says it is; `Unknown` for any name the platform never makes. */41 export const repoKind = (name: RepoName): RepoKind => {42+ // `--` occurs in no key or ask name, so a name splits back into its parts.43 const [first = "", second, third, ...rest] = name.split("--");44 45 const kind = Option.flatMap(46 asProject(first),25 unmodified lines72 73 return Option.getOrElse(kind, () => RepoKind.Unknown());74 };75 91-/** A person's working fork: `<key>--me--<handle in lowercase>`. */76 export const workingForkName = (project: ProjectName, handle: Handle) =>77 RepoName.make(`${keyOf(project)}--${WORKING}--${handle.toLowerCase()}`);modified:packages/project/src/standing-posture.ts+6 added-43 removed
1-/**2- * A listed project's posture, as its own record says it now. The3- * projection's `posture` moves only on a `PostureChanged` ledger entry, and4- * a project's standing changes without one: its first config stands at5- * once, a widening needs no decision, and an accepted narrowing takes6- * effect when its notice runs out, by the clock. So a list of projects7- * reads from each one's own record the posture its ledger shows now8- * (`ProjectApi.standing`, the value the ledger's `posture` is), and shows9- * that: the badge and the ledger are one value, read at the source.10- *11- * What was read is kept (`StandingPostures`) with the next instant the12- * posture moves by the clock alone (an accepted narrowing's notice running13- * out) and the project's last event the read saw. A kept posture serves14- * until that instant; an event that can move it sooner (a landing, a15- * decision, a ledger entry) clears it where the projection applies that16- * event (`projection-d1/projection.ts`), and a store that applied a later17- * event than the read saw keeps nothing from it. A store that fails is a18- * miss, never the list's failure.19- *20- * Cost: one read per listed project whose kept posture is missing or ran21- * out, at most 8 at once; none for the rest.22- */1 import type { ProjectListing } from "@repo/protocol/domain/front-page";2 import type { ProjectName } from "@repo/protocol/ids";3 import type { Posture } from "@repo/protocol/posture";4 import { Array as Arr, Cause, Context, DateTime, Effect, Option } from "effect";5 6 import { Projects } from "./projects.ts";7 30-/** A project's standing posture as it is kept between lists. */8 export interface StandingEntry {9 readonly posture: Posture;33- /** The instant it moves by the clock alone; none when only an event moves it. */10 readonly until?: DateTime.Utc;11 /**36- * The project's last event the read saw: a store that has applied a37- * later event of the project keeps nothing from it, since that event may38- * have moved the posture after the read.12+ * A store that applied a later event of the project keeps nothing from this13+ * read.14 */15 readonly seen: number;16 }17 43-/** Where a list keeps each project's standing posture between lists. */18 export interface StandingPosturesApi {45- /** What is kept for each of `projects`; a store that fails keeps nothing. */19 readonly get: (20 projects: readonly ProjectName[]21 ) => Effect.Effect<ReadonlyMap<ProjectName, StandingEntry>>;49- /** Keeps `entries`; a store that fails keeps nothing, silently to the caller. */22 readonly put: (23 entries: ReadonlyMap<ProjectName, StandingEntry>24 ) => Effect.Effect<void>;25 }26 55-/**56- * The kept standing postures: a `Context.Reference` whose default keeps57- * nothing, so every list reads each project, as every host did before one58- * was given; the platform gives one over D1 (`projection-d1/postures.ts`).59- */27+/** The default keeps nothing, so every list reads each project. */28 export const StandingPostures = Context.Reference<StandingPosturesApi>(29 "project/StandingPostures",30 {31 defaultValue: () => ({2 unmodified lines34 }),35 }36 );37 70-/** How many projects a list reads at once (the platform handlers' `FAN_OUT`). */38 const READS_AT_ONCE = 8;39 73-/** `effect`, or `fallback` with a warning if it fails: an interruption stays one. */40 const orWarn = <A, E>(41 effect: Effect.Effect<A, E>,42 fallback: A,43 warning: string4 unmodified lines48 : Effect.as(Effect.logWarning(warning, cause), fallback)49 );50 51 /**86- * `listed` with each project's posture as its own record says it now (the87- * posture its ledger shows): what `StandingPostures` keeps for it while88- * that has not run out, else read from the project, at most 8 at once, and89- * kept with the instant it moves by the clock. A project never made, or90- * one whose read fails, keeps the posture the projection listed and is not91- * kept; a store that fails is a miss.52+ * The projection's posture moves only on a `PostureChanged` entry, but a53+ * standing posture also moves by the clock and without a decision, so a list54+ * reads each project's own record.55 */56 export const withStandingPosture = (57 listed: readonly ProjectListing[]58 ): Effect.Effect<readonly ProjectListing[], never, Projects> =>62 unmodified linesmodified:packages/project/src/visibility-port.ts+4 added-92 removed
1-/**2- * Typed visibility's neutral port: everything the project service3- * asks of layers, held-back checks, admission and the ledger, with a4- * default that is a project without any of it. The visibility cartridge5- * (`./visibility/**`, `@repo/visibility`, and the platform's6- * `apps/platform/src/visibility/**`) plugs in by providing this port, so7- * removing the cartridge is a deletion: the default answers Open, no8- * layers, nothing held back, an empty ledger.9- *10- * The service hydrates, transitions, persists and settles (ADR 0012); the11- * port stays inside that loop. Each method reads the project as one call12- * has it (`snapshot`: its rows with the call's own writes so far on top),13- * and every change comes back as a plan the service commits with its own14- * rows: `writes` in the same commit, `effects` kept in the outbox and15- * settled after it through `settle`, retried by the alarm until done.16- *17- * Nothing here names a layer's paths, a check, or a salt: the port18- * returns roots, area bits and public ledger entries only.19- */1+// Nothing here names a layer's paths, a check, or a salt: the port returns2+// roots, area bits and public ledger entries only.3 import { HeldBackResult } from "@repo/protocol/domain/answer";4 import type { ClaimView } from "@repo/protocol/domain/claim";5 import { AtLeastOne } from "@repo/protocol/domain/common";6 import type { LandingView } from "@repo/protocol/domain/landing";17 unmodified lines24 25 import type { ProjectSnapshot, ProjectWrites } from "./project-store.ts";26 import type { PinnedSuite } from "./project-store/rows.ts";27 45-/**46- * A side effect a plan asks for, opaque to the service: the port that47- * planned it settles it (`settle`), after the commit that recorded it. The48- * id keys its outbox row, so planning it twice runs it once.49- */28+/** The id keys its outbox row, so planning it twice runs it once. */29 export const VisibilityEffect = Schema.Struct({30 body: Schema.Json,31 id: Schema.NonEmptyString,32 });33 34 export type VisibilityEffect = typeof VisibilityEffect.Type;35 57-/** What a port asks the service to write in the call's commit, and to settle after it. */36 export interface VisibilityPlan {37 readonly effects: readonly VisibilityEffect[];38 readonly writes: ProjectWrites;39 }40 63-/** A plan that changes nothing. */41 export const noPlan: VisibilityPlan = { effects: [], writes: {} };42 66-/** How far a person may reach into a layer: clone it, push to it, or neither. */43 export const LayerAccess = Schema.Literals(["none", "read", "write"]);44 45 export type LayerAccess = typeof LayerAccess.Type;46 71-/**72- * A sealed suite's run, as the platform gives it to the Checker: the73- * layer's files under the sealed areas at the pinned commit, read by the74- * platform (no layer token or route ever reaches the sandbox),75- * and one run per sealed check, the run block's `test` with its76- * `{path}` filled. It crosses the Project DO's boundary, so it is a schema.77- */47+/** The layer's files are read by the platform: no layer token or route ever reaches the sandbox. */48 export const HeldBackJob = Schema.Struct({49 areas: Schema.Array(AreaName),80- /** The layer commit the suite was pinned at. */50 at: CommitSha,51 files: Schema.Array(52 Schema.Struct({53 area: AreaName,12 unmodified lines66 });67 68 export type HeldBackJob = typeof HeldBackJob.Type;69 101-/**102- * What one held-back run of an answer came to: the refusals it earns (an103- * area that failed, or an area out of attempts), the `Held-back:` trailer's104- * value when every area passed (without its key, as `formatLanding` takes105- * it), and the rows that count the attempt.106- */70 export interface HeldBackJudgement {71 readonly refusals: readonly (HeldBackFailed | AttemptsExhausted)[];72 readonly trailer: Option.Option<string>;73 readonly writes: ProjectWrites;74 }75 113-/** A judgement that refuses nothing, adds no trailer and counts nothing. */76 const unjudged: HeldBackJudgement = {77 refusals: [],78 trailer: Option.none(),79 writes: {},80 };81 120-/**121- * One admission run of a layer push's sealed checks: an area's122- * checks on main (green every time, `attempt` of the policy's count), or on123- * a known-bad tree (red at least once).124- */82 export const AdmissionRun = Schema.TaggedUnion({83 OnKnownBad: { area: AreaName, job: HeldBackJob, tree: CommitSha },84 OnMain: { area: AreaName, attempt: Schema.Int, job: HeldBackJob },85 });86 87 export type AdmissionRun = typeof AdmissionRun.Type;88 132-/**133- * The runs that admit a layer push, against the main they run on: what134- * admits an area (the policy's counts), and the run block each job runs135- * its checks by.136- */89 export const AdmissionPlan = Schema.Struct({90 admit: Schema.Struct({91 greenOnMainRuns: AtLeastOne,92 redOnKnownBadAtLeast: AtLeastOne,6 unmodified lines99 });100 101 export type AdmissionPlan = typeof AdmissionPlan.Type;102 151-/** What an admission's runs came to, as the `Answer` Workflow reports them: each run with its area bits. */103 export const AdmissionReport = Schema.Struct({104 head: CommitSha,105 layer: LayerName,106 results: Schema.Array(5 unmodified lines112 });113 114 export type AdmissionReport = typeof AdmissionReport.Type;115 165-/** What the gate's stage 1 takes from visibility for one pusher (`ProjectApi.layerFacts`). */116 export const LayerFacts = Schema.Struct({117 /** Whether the pusher reads every layer the paths come from: only then does a refusal name which paths collide. */118 canRead: Schema.Boolean,169- /** Every path in any layer's path set: none enters a public tree. */119 layerPaths: Schema.Array(RepoPath),120 });121 122 export type LayerFacts = typeof LayerFacts.Type;123 175-/** A claim as the port sees it: whose, on which ask, and the suite it was pinned to. */124 export interface PinnedClaim {125 readonly ask: AskId;126 readonly claimant: Handle;127 readonly pinned: PinnedSuite;128 }129 182-/**183- * Typed visibility as the project service reaches it. `snapshot` is always184- * the project as the call has it so far.185- */130 export interface VisibilityPort {187- /**188- * After a call moved the landed SHA with a policy read there: provision189- * each declared layer's repo, append `LayerDeclared`, open a190- * `PostureChange` decision for a narrowing. `landings` are the call's191- * own, oldest first.192- */131 readonly onPolicy: (132 input: {133 readonly after: Policy;134 readonly before: Option.Option<Policy>;1 unmodified line136 readonly now: DateTime.Utc;137 },138 snapshot: ProjectSnapshot139 ) => Effect.Effect<VisibilityPlan>;202- /** The held-back suite a claim opening now is judged by, if one is sealed. */140 readonly pinSuite: (141 claim: { readonly ask: AskId; readonly claimant: Handle },142 snapshot: ProjectSnapshot143 ) => Option.Option<PinnedSuite>;207- /** Every path in any layer's path set, for stage 1's `PrivatePathInPublicTree`. */144 readonly layerPaths: (145 snapshot: ProjectSnapshot146 ) => Effect.Effect<ReadonlySet<RepoPath>>;211- /** The layers `who` may read: the write-down guard runs only for these. */147 readonly readableLayers: (148 who: Principal,149 snapshot: ProjectSnapshot150 ) => ReadonlySet<LayerName>;216- /** How far `who` may reach into `layer` (its readers and writers); none for a layer the project does not declare. */151 readonly access: (152 who: Principal,153 layer: LayerName,154 snapshot: ProjectSnapshot155 ) => Option.Option<LayerAccess>;222- /** The run of the suite a claim was pinned to, for an answer on it; none when nothing is sealed. */156 readonly heldBackJob: (157 claim: PinnedClaim,158 snapshot: ProjectSnapshot159 ) => Effect.Effect<Option.Option<HeldBackJob>>;227- /** One held-back run of an answer, judged: `HeldBackFailed` or `AttemptsExhausted`, or the trailer. */160 readonly judgeHeldBack: (161 input: PinnedClaim & {162 readonly now: DateTime.Utc;163 readonly requestId: RequestId;164 readonly results: readonly HeldBackResult[];165 },166 snapshot: ProjectSnapshot167 ) => HeldBackJudgement;236- /** A push to a layer's repo: its proposed head, admitted at once or through admission. */168 readonly onLayerPush: (169 input: {170 readonly head: CommitSha;171 readonly layer: LayerName;1 unmodified line173 readonly pusher: Handle;174 },175 snapshot: ProjectSnapshot176 ) => Effect.Effect<VisibilityPlan>;246- /** The runs that would admit a layer's pushed head; none when nothing waits on admission. */177 readonly admissionPlan: (178 input: { readonly head: CommitSha; readonly layer: LayerName },179 snapshot: ProjectSnapshot180 ) => Effect.Effect<Option.Option<AdmissionPlan>>;251- /** An admission's results, judged: the layer's landed SHA moves (under a fresh commitment), or stays. */181 readonly onAdmission: (182 input: AdmissionReport & { readonly now: DateTime.Utc },183 snapshot: ProjectSnapshot184 ) => Effect.Effect<VisibilityPlan>;256- /** A read of a layer through the gateway, for the read log. */185 readonly recordRead: (input: {186 readonly at: DateTime.Utc;187 readonly handle: Handle;188 readonly layer: LayerName;189 readonly sha: Option.Option<CommitSha>;190 }) => ProjectWrites;263- /** The public ledger. */191 readonly ledger: (project: ProjectName, snapshot: ProjectSnapshot) => Ledger;265- /**266- * The posture the ledger shows now, and the next instant it moves by the267- * clock alone (an accepted narrowing whose notice still runs), if any:268- * what a list keeps a project's posture by (`standing-posture.ts`).269- */192 readonly standing: (snapshot: ProjectSnapshot) => {193 readonly posture: Posture;194 readonly until: Option.Option<DateTime.Utc>;195 };274- /** Runs one effect a plan asked for: true once it is done, false to try again later. */196 readonly settle: (effect: VisibilityEffect) => Effect.Effect<boolean>;197 }198 278-/** A project without typed visibility: Open, no layers, nothing held back, an empty ledger. */199 export const noVisibility: VisibilityPort = {200 access: () => Option.none(),201 admissionPlan: () => Effect.succeedNone,202 heldBackJob: () => Effect.succeedNone,15 unmodified lines218 settle: () => Effect.succeed(true),219 standing: () => ({ posture: "open", until: Option.none() }),220 };221 302-/**303- * How a host gives the project service typed visibility. The default is304- * `noVisibility`, so a host that provides nothing (the core composition,305- * every test world) runs the platform without it.306- */222 export const ProjectVisibility = Context.Reference<VisibilityPort>(223 "project/ProjectVisibility",224 { defaultValue: () => noVisibility }225 );226 312-/** The default, said out loud: a project without typed visibility. */227 export const NoVisibility: Layer.Layer<never> = Layer.succeed(228 ProjectVisibility,229 noVisibility230 );231 232 const decodePolicy = Schema.decodeUnknownOption(Schema.toCodecJson(Policy));233 320-/** The policy a snapshot's project row holds, decoded: what a port reads its rules from. */234 export const policyIn = (snapshot: ProjectSnapshot): Option.Option<Policy> =>235 Option.flatMap(snapshot.project, (row) =>236 row.policy === undefined ? Option.none() : decodePolicy(row.policy)237 );238 326-/** The suite a claim view shows: its pinned root. */239 export const suiteOf = (240 pinned: Option.Option<PinnedSuite>241 ): Pick<ClaimView, "suite"> =>242 Option.match(pinned, {3 unmodified linesmodified:packages/project/test/attention/credits.test.ts-3 removed
10 unmodified lines11 import { creditsByArea } from "../../src/attention/credits.ts";12 13 const now = at("2026-10-07T12:00:00Z");14 15-/** `datekit`: asks in `packages/parser` and `packages/format`. */15 const datekit = aProject({ now }).pipe(16 withAsk({ id: "parse-iso", territory: "packages/parser" }),17 withAsk({ id: "format-week", territory: "packages/format" })18 );19 21-/** `burrow`: an ask in `packages/p1`. */20 const burrow = aProject({ name: "alice/burrow", now }).pipe(21 withAsk({ id: "drop-legacy-p1", territory: "packages/p1" })22 );23 11 unmodified lines35 handle,36 role,37 });38 41-/** A landing in `scenario` answering `ask` (none: a decider's own landing), with these trailers. */39 const landing = (40 scenario: Scenario,41 seed: string,42 ask: string | undefined,149 unmodified linesmodified:packages/project/test/attention/decisions.test.ts+1 added-4 removed
59 unmodified lines60 const proposal = minted.proposal();61 62 const { OpenProposal, StrayPush } = DecisionSubject.cases;63 64-/** Every subject, with the default it must have: doing nothing lets nothing in. */64+/** Every subject's default: doing nothing lets nothing in. */65 const defaults: readonly (readonly [DecisionSubject, Choice])[] = [66 [OpenProposal.make({ proposal }), "decline"],67 [DecisionSubject.cases.Finish.make({ ask, head: sha("answer") }), "decline"],68 [43 unmodified lines112 const evidence = [113 Evidence.make({ label: "check", value: "packages/parser/test/iso.test.ts" }),114 ];115 116-/** A decision for alice and dana, opened at noon with a 14-day expiry. */116 const open = (subject: DecisionSubject) =>117 openDecision({118 deciders: [alice, dana],119 evidence,9 unmodified lines129 const strayPush = open(StrayPush.make({ after, before, ref: main }));130 131 const later = at("2026-10-08T09:30:00Z");132 134-/** Alice's choice on `decision`, made the next morning. */133 const choose = (decision: Decision, choice: Choice, by = alice) =>134 decide([decision], {135 by,136 choice,1 unmodified line138 note: Option.none(),139 now: later,140 });141 144-/** The word `decision` records when alice chooses `choice`. */142 const words = (decision: Decision, choice: Choice) =>143 Result.map(144 choose(decision, choice),145 ({ decision: { decided } }) => decided?.choice310 unmodified linesmodified:packages/project/test/attention/promote.test.ts-14 removed
31 unmodified lines32 import { promotions } from "../../src/attention/promote.ts";33 import type { FinishRecord, Promotion } from "../../src/attention/promote.ts";34 import { FinishersFromChecks, MethodSchemas } from "../../src/project.ts";35 36-/** The sdk's `lintToZero` kind, as the policy lists it. */36 const lintToZeroKind = {37 checkKind: "lintToZero",38 claimers: "vouched",39 finish: "never",3 unmodified lines43 requires: ["want", "check", "territory"],44 strength: "assertion",45 } as const;46 48-/** The project's own lint, which prints JSON: what its ratchet counts with. */47 const lint = Command.make("bun run lint --format json");48 49 const scenario = aProject({ deciders: ["alice"], people: ["bob"] }).pipe(50 withKind(lintToZeroKind)51 );52 55-/** Datekit with a ratchet counted by its JSON lint, so a lint command is known. */53 const policy: Policy = {54 ...scenario.policy,55 ratchets: [56 {15 unmodified lines72 const askFile = RepoPath.make(73 `${Brand.configDir}/asks/no-date-equality-in-src-date.ask.ts`74 );75 79-/** A finish by alice in `src/date`, with no rule from its lanes and no note unless given. */76 const finish = (77 ask: string,78 day: string,79 more: Partial<FinishRecord> = {}15 unmodified lines95 const diffMonths = finish("diff-months", "2026-10-05", {96 note: Option.some(`Date compared with === again: \`${rule}\``),97 });98 103-/** Two finishes whose notes name `no-date-equality`, one of them in backticks. */99 const pair = [compareDays, diffMonths];100 101 const promote = (102 finishes: readonly FinishRecord[],14 unmodified lines117 project: scenario.project,118 });119 };120 126-/** A decision's evidence without the files its proposal holds. */121 const shown = ({ decision, proposal }: Promotion) =>122 decision.evidence.filter(123 ({ label }) => !proposal.files.some((path) => path === label)124 );125 132-/** The files a proposal holds, read back from its decision's evidence by path, as an accepted proposal's are. */126 const heldFiles = ({ decision, proposal }: Promotion) =>127 proposal.files.flatMap((path) =>128 decision.evidence.flatMap(({ label, value }) =>129 label === path ? [{ content: value, path }] : []58 unmodified lines188 ]);189 });190 });191 199-/** One evidence line of each promotion, by its label. */192 const lineOf = (made: readonly Promotion[], label: string) =>193 made.flatMap(({ decision }) =>194 decision.evidence.flatMap((each) =>195 each.label === label ? [each.value] : []196 )197 );198 207-/** `decision` as a decider left it: declined by alice the day it opened. */199 const declined = (decision: Decision): Decision => ({200 ...decision,201 decided: { at: now, by: alice, choice: "decline" },202 });203 204 const carol = Handle.make("carol");205 215-/** Two finishes in `src/date` whose notes both say `note`. */206 const twice = (note: string) =>207 promote([208 finish("compare-days", "2026-10-01", { note: Option.some(note) }),209 finish("diff-months", "2026-10-05", { note: Option.some(note) }),332 unmodified lines542 );543 });544 });545 556-// ------------------------------------------- the ask file, through the sdk557-558-/** One workspace, `parser`, and alice as the project's initializer. */546 const facts = Schema.decodeSync(EvaluationFacts)({547 ci: [],548 initializer: "alice",549 now: "2026-10-07T12:00:00.000Z",11 unmodified lines561 "});",562 "",563 ].join("\n");564 578-/** What promotions' ask files state, as the rules evaluator reads them back from a config folder. */565 const evaluated = (made: readonly Promotion[]) =>566 Effect.gen(function* () {567 const evaluator = yield* RulesEvaluator;568 91 unmodified linesmodified:packages/project/test/attention/proposals.test.ts-3 removed
36 unmodified lines37 fork: RepoName.make("alice__datekit--me--carol"),38 head: sha("carol's fix for ISO weeks"),39 };40 41-/** Carol, vouched, with no proposal open and no record, proposes a new ask. */41 const byCarol = (42 standing: Partial<Parameters<typeof ProposalCommand.Propose>[0]> = {}43 ) =>44 ProposalCommand.Propose({10 unmodified lines55 who: Person.make({ handle: carol }),56 ...standing,57 });58 60-/** Carol flags the open ask `parse-iso`. */59 const flagBy = (60 standing: Partial<Parameters<typeof ProposalCommand.Flag>[0]> = {}61 ) =>62 ProposalCommand.Flag({173 unmodified lines236 ]);237 });238 });239 242-/** A proposal opened now, and one opened now and accepted since. */240 const proposals = () => {241 const opened = Result.getOrThrow(proposalOf(byCarol()));242 243 const accepted: Proposal = {27 unmodified linesmodified:packages/project/test/attention/record.test.ts-3 removed
8 unmodified lines9 import { meets, recordOf } from "../../src/attention/record.ts";10 11 const now = at("2026-10-07T12:00:00Z");12 13-/** `datekit`, with an ask in `packages/parser` and one in `packages/format`. */13 const scenario = aProject({ now, people: ["bob"] }).pipe(14 withAsk({ id: "parse-iso", territory: "packages/parser" }),15 withAsk({ id: "parse-week", territory: "packages/parser" }),16 withAsk({ id: "format-week", territory: "packages/format" })6 unmodified lines23 const alice = Handle.make("alice");24 25 const bob = Handle.make("bob");26 28-/** A landing `days` before `now`, by `author`, answering `ask` (none: a decider's own landing). */27 const landing = (28 seed: string,29 options: {30 readonly ask?: string;15 unmodified lines46 ? view47 : { ...view, ask: AskId.make(options.ask) };48 };49 52-/** Alice's record as it stands at `now` under the default window (30 days, 365 days). */50 const recordAt = (51 landings: readonly LandingView[],52 reverted: readonly LandingView[] = []53 ) =>125 unmodified linesmodified:packages/project/test/attention/today.test.ts-5 removed
27 unmodified lines28 const alice = handle("alice");29 30 const dana = handle("dana");31 32-/** Thursday noon: alice opens Today. */32 const now = at("2026-10-08T12:00:00Z");33 34 const minted = ids();35 37-/** A decision on a vouch for `name`, for alice and dana, expiring `expiresIn` hours from now. */36 const vouchFor = (name: string, expiresIn: number): Decision =>37 openDecision({38 deciders: [alice, dana],39 evidence: [],20 unmodified lines60 const p7 = vouchFor("p7", 150);61 62 const p8 = vouchFor("p8", 200);63 66-/** The eight, given out of order. */64 const eight = [p5, p1, p8, p3, p2, p7, p4, p6];65 66 const fresh = { finishes: 0, total: 5, used: 0 };67 137 unmodified lines205 expect(page.newcomers).toStrictEqual([handle("carol"), handle("erin")]);206 });207 208 it("samples at most 5 landings that needed nobody, newest first", () => {212- /** A landing `hoursAgo`, with dana in `roles` beside the answerer and the asker. */209 const landing = (210 seed: string,211 hoursAgo: number,212 roles: readonly CreditRole[] = []37 unmodified lines250 );251 });252 });253 258-/** Each spend, in order, kept as the day's one row per decider. */254 const spendAll = (255 spends: readonly {256 readonly decider: Handle;257 readonly on: "decision" | "finish";87 unmodified linesmodified:packages/project/test/attention/vouch.test.ts-13 removed
31 unmodified lines32 requires: ["want", "check", "territory"],33 strength: "assertion",34 };35 36-/**37- * `datekit`: its file vouches for `bob` and `Erin` and denounces `mallory`;38- * kinds `fix` (vouched), `open` (anyone), `parser` (two held landings in39- * `parser`) and `starter` (newcomers, mentored by alice); an ask of each;40- * asks reserved for newcomers of `fix`, `open` and `parser`; and a `fix` ask41- * reserved for people. The deciders are `alice` alone.42- */36 const scenario = aProject({ now }).pipe(37 withVouches(["bob", "Erin"], ["mallory"]),38 withKind({ ...fix, claimers: "anyone", name: "open" }),39 withKind({35 unmodified lines75 );76 77 const { policy } = scenario;78 86-/** The policy with another vouch mode. */79 const inMode = (mode: Policy["vouch"]["mode"]): Policy => ({80 ...policy,81 vouch: { ...policy.vouch, mode },82 });25 unmodified lines108 const carol = Handle.make("carol");109 110 const mallory = Handle.make("mallory");111 120-/** One held landing on carol's record, in `area` of `project` (datekit's by default). */112 const held = (113 area: string,114 seed: string,115 project: ProjectName = scenario.project10 unmodified lines126 const notVouched = Result.fail(new NotVouched({}));127 128 const denounced = Result.fail(new Denounced({}));129 139-/**140- * May a person of this standing, record and landings claim ask `id` under141- * `rules`, with `mentor` named on the ask?142- */130 const claim = (131 id: string,132 who: Standing,133 options: {332 unmodified linesmodified:packages/project/test/visibility/admission.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/visibility/attempts.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/visibility/env.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/visibility/ledger.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/visibility/raw.d.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/visibility/state.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/visibility/world.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/assisted.test.ts-18 removed
1-/**2- * `Assisted-by:` on an answer's landing: every harness that pushed to the3- * claim, as each push's custody named it, once each, in the order they first4- * pushed; none when the project's policy says `agents: "none"`, and none for a5- * push no harness named. The harness is audit metadata: the person who pushed6- * stays the landing's author and only credited name.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost } from "@repo/artifacts/repo-host";3 import { creditsOf } from "@repo/git/trailers";4 import type { HarnessAudit } from "@repo/protocol/audit";50 unmodified lines55 const ask: Ask = Option.getOrThrow(56 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)57 );58 66-/** The ask's own files: its file in the config folder, and its check. */59 const askFiles = Array.make(60 { content: `export default "${parseIso}";\n`, path: ask.file },61 {62 content: [19 unmodified lines82 ["packages/parser/package.json", '{ "name": "parser" }\n'],83 ["packages/parser/src/parse.ts", "export const parse = (s) => 0;\n"],84 ];85 94-/** Main once the ask opened on it, with the parser at `step`. */86 const answerAt = (step: number): Files => [87 ...start.filter(([path]) => path !== "packages/parser/src/parse.ts"),88 ...askFiles.map(({ content, path }) => [path, content] as const),89 [9 unmodified lines99 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))100 );101 });102 112-/** The project made and first pushed by alice, and parse-iso opened red first. */103 const opened = (api: ProjectApi) =>104 Effect.gen(function* () {105 yield* api.initProject(alice, {});106 15 unmodified lines122 return (yield* api.openAsk(alice, { ask: parseIso, files: askFiles }))123 .landed;124 });125 136-/**137- * bob claims parse-iso and pushes once per entry of `pushes`, each push138- * reported by custody with the harness it named (or none); the last head is139- * checked green and submitted. With `claimedAnewAt`, bob releases his claim140- * and claims the ask again before that push. What lands: its trailers and141- * its view.142- */126 const answered = (127 policy: Policy,128 pushes: readonly Option.Option<HarnessAudit>[],129 claimedAnewAt?: number90 unmodified lines220 const claudeCode = Option.some({ harness: "claude-code", model: "haiku" });221 222 const pi = Option.some({ harness: "pi", model: "kimi-k3" });223 241-/** A whole story's limit: real git objects and every gate stage, to catch a hang. */224 const story = { timeout: 30_000 };225 226 describe("Assisted-by on an answer's landing", () => {227 it.effect(85 unmodified linesmodified:packages/project/test/brief.test.ts-7 removed
18 unmodified lines19 import type { ProjectApi } from "../src/project.ts";20 import { projectService } from "../src/project.ts";21 import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";22 23-/**24- * datekit with two asks: `parse-iso` in the module `parser`, and25- * `trim-input` over two paths alone, as `territory.paths(...)` makes it26- * (module `.`).27- */23 const scenario = aProject().pipe(24 withAsk({ id: "parse-iso", territory: "packages/parser" }),25 withAsk({ id: "trim-input", territory: "." })26 );33 unmodified lines60 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],61 ["src/trim.ts", "export const trim = (s) => s;\n"],62 ];63 69-/** alice opens `id`: its file and its check, scripted red twice on main. */64 const openRed = (api: ProjectApi, id: string) =>65 Effect.gen(function* () {66 const { check, file } = askOf(id);67 24 unmodified lines92 93 return yield* api.openAsk(alice, { ask: AskId.make(id), files });94 });95 102-/** The brief's Territory section, its one line. */96 const territoryLine = (brief: string) =>97 brief.split("## Territory\n\n")[1]?.split("\n")[0];98 99 describe("an ask's brief", () => {31 unmodified linesmodified:packages/project/test/claim.model.test.ts+3 added-77 removed
25 unmodified lines26 transition,27 } from "../src/claim.ts";28 import type { ClaimResult, ClaimStep, Live } from "../src/claim.ts";29 30-// A model test (ADR 0012): generated histories of claims, pushes, alarms,31-// releases and landings run through `transition` the way the project service32-// would, and every step is checked against the claim lifecycle's invariants.33-30 const HOUR = 3_600_000;31 36-/** The defaults: warned after 2 quiet hours, lapsed after 24. */32 const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };33 34 const project = ProjectName.make("alice/datekit");35 12 unmodified lines48 const cap = 3;49 50 const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");51 57-/** Four people; `Bob` checks that a fork's name lowercases the handle. */52+/** `Bob` checks that a fork's name lowercases the handle. */53 const People = Schema.Literals(["alice", "Bob", "carol", "dave"]);54 60-/**61- * How the person making a claim stands: each flag is one refusal the claim62- * would meet (the ask blocked, the person at their cap, denounced, or not63- * vouched). A claim may meet several, so their order is checked too.64- */55 const Standing = Schema.Struct({56 atCap: Schema.Boolean,57 blocked: Schema.Boolean,58 denounced: Schema.Boolean,59 unvouched: Schema.Boolean,60 });61 72-/** One thing that happens to the ask, as a history step names it. */62 const Move = Schema.TaggedUnion({63 Claim: { standing: Standing, who: People },64 Land: { who: People },65 Push: { who: People },2 unmodified lines68 });69 70 type Move = typeof Move.Type;71 83-/**84- * How the project service keeps the ask's claims: one state for the whole85- * ask (`shared`, an exclusive kind), or one state per claimant with the86- * kind's `race` (1 to 3) passed to each claim.87- */72 const Layout = Schema.Literals(["shared", "race1", "race2", "race3"]);73 74 type Layout = typeof Layout.Type;75 92-/** One step of a history: whole hours waited since the last one, then a move. */76 interface Step {77 readonly after: number;78 readonly move: Move;79 }5 unmodified lines85 86 /** True one time in six; it shrinks to false, so a shrunk claim meets nothing. */87 const rare = roll(5).pipe(Arbitrary.map((n) => n === 5));88 106-/** About half of all claims meet no refusal. */89 const standing = Arbitrary.all({90 atCap: rare,91 blocked: rare,92 denounced: rare,17 unmodified lines110 );111 112 const ticks = Arbitrary.Constant(Move.cases.Tick.make({}));113 132-/** Moves by weight; shrinking a roll towards 0 turns a move into an alarm. */114 const weighted = [115 ticks,116 ticks,117 pushes,9 unmodified lines127 const moves = roll(weighted.length - 1).pipe(128 Arbitrary.flatMap((n): Arbitrary.Arbitrary<Move> => weighted[n] ?? ticks)129 );130 150-/** Whole hours, so steps land exactly on the 2 h and 24 h deadlines often. */131+/** Whole hours, so steps often land exactly on the 2 h and 24 h deadlines. */132 const histories = Arbitrary.array(133 Arbitrary.all({ after: roll(26), move: moves }),134 { maxLength: 40 }135 );2 unmodified lines138 139 const raceOf = (layout: Layout) =>140 ({ race1: 1, race2: 2, race3: 3, shared: 1 })[layout];141 161-/** A live claim: `Live` or `Warned`. */142 const live = (state: ClaimState): Option.Option<Live> =>143 ClaimState.match(state, {144 Answered: () => Option.none(),145 Lapsed: () => Option.none(),2 unmodified lines148 Released: () => Option.none(),149 Warned: Option.some<Live>,150 });151 172-/** Any state that holds or held a claim. */152 const held = (state: ClaimState): Option.Option<Live> =>153 ClaimState.match(state, {154 Answered: Option.some<Live>,155 Lapsed: Option.some<Live>,6 unmodified lines162 const isLive = (state: ClaimState) => Option.isSome(live(state));163 164 const ms = (time: DateTime.Utc) => DateTime.toEpochMillis(time);165 187-/** The time a claim's deadlines count from: its last push, or its making. */166 const quietSince = (claim: Live) =>167 Option.getOrElse(claim.lastPushAt, () => claim.openedAt);168 169 const encode = Schema.encodeSync(ClaimState);170 171 const same = (left: ClaimState, right: ClaimState) =>172 JSON.stringify(encode(left)) === JSON.stringify(encode(right));173 196-/** One call to `transition`, as the model service made it. */174 interface Call {175 readonly before: ClaimState;176 readonly command: ClaimCommand;177 readonly now: DateTime.Utc;178 }179 180 type Claim = typeof ClaimCommand.cases.Claim.Type;181 205-/** Whether the person making a claim holds the ask's live claim already. */182 const holds = (before: ClaimState, made: Claim) =>183 Option.exists(live(before), (holder) => holder.claimant === made.who.handle);184 209-/**210- * The refusal a claim by someone who does not hold it meets first, in the211- * lifecycle's order: a full ask before anything else (ADR 0008), then the212- * ask's blockers, the person's cap, a denouncement and a missing vouch. None213- * when it should go live.214- */185 const owed = (before: ClaimState, made: Claim) =>186 Option.map(187 Arr.findFirst(188 [12 unmodified lines201 ),202 ([refusal]) => refusal203 );204 235-/**236- * A claim is refused with the first refusal it meets, and goes live, held by237- * its maker, when it meets none; the holder claiming again changes nothing.238- */205 const claimsAsOwed = (206 { before, command }: Call,207 result: ClaimResult208 ): readonly string[] => {41 unmodified lines250 }),251 });252 };253 288-/** Who pushed or released; none for any other command. */254 const pushedOrReleasedBy = ClaimCommand.match({255 Claim: () => Option.none<Handle>(),256 Land: () => Option.none<Handle>(),257 Push: ({ who }) => Option.some(who),258 Release: ({ who }) => Option.some(who),259 Tick: () => Option.none<Handle>(),260 });261 297-/**298- * Only a live claim's holder moves it by a push or a release, and the299- * holder's push or release always goes through.300- */262 const holderOnly = (263 { before, command }: Call,264 result: ClaimResult265 ): readonly string[] =>17 unmodified lines283 });284 },285 });286 326-/** Whether a push comes from the holder of a live claim. */287 const holderPushes = ({ before, command }: Call) =>288 ClaimCommand.guards.Push(command) &&289 Option.exists(live(before), (holder) => holder.claimant === command.who);290 331-/** An invariant over one successful call, naming what it found broken. */291 type Invariant = (call: Call, done: ClaimStep) => readonly string[];292 334-/** The holder's push keeps the claim live and counts from now. */293 const pushesRenew: Invariant = (call, { state }) =>294 holderPushes(call) &&295 !(296 ClaimState.guards.Live(state) &&3 unmodified lines300 )301 ? ["the holder's push makes the claim live from now"]302 : [];303 346-/**347- * A fork is made only on the way into Live from no claim, a lapsed one or a348- * released one, and then exactly once, named for the new claimant.349- */304 const forksOnlyNewClaims: Invariant = ({ before }, { effects, state }) => {305 const forks = effects.filter(ClaimEffect.$is("MakeFork"));306 307 const opens =14 unmodified lines322 ? []323 : ["a new claim makes one fork, named for its claimant"];324 };325 372-/** Access is revoked exactly when a live claim ends. */326 const revokesWhenLiveEnds: Invariant = ({ before }, { effects, state }) => {327 const revokes = effects.filter(ClaimEffect.$is("RevokeAccess")).length;328 const ends = isLive(before) && !isLive(state);329 1 unmodified line331 ? []332 : ["access is revoked once when a live claim ends"];333 };334 382-/** Deadlines count from the last push, or from the claim, never from later. */335 const deadlinesCount: Invariant = ({ now }, { state }) =>336 Option.match(held(state), {337 onNone: () => [],338 onSome: (claim) => {10 unmodified lines349 ];350 },351 });352 401-/** Alarms are set only for later, and events happen now. */353 const noTimeTravel: Invariant = ({ now }, { effects }) => [354 ...effects355 .filter(ClaimEffect.$is("SetAlarm"))356 .flatMap((alarm) =>5 unmodified lines362 ms(emitted.event.at) === ms(now) ? [] : ["an event that is not now"]363 ),364 ];365 415-/** A claim is warned no earlier than warnsAt, and lapses no earlier than lapsesAt. */366 const deadlinesKept: Invariant = ({ before, now }, { state }) =>367 Option.match(held(state), {368 onNone: () => [],369 onSome: (claim) => [9 unmodified lines379 : []),380 ],381 });382 433-/**434- * A claim that moves into or within live sets the alarm for its next435- * deadline (warnsAt while live, lapsesAt once warned): deadlines run on436- * alarms, so a claim with none would never lapse.437- */383 const alarmsNextDeadline: Invariant = ({ before }, { effects, state }) =>384 Option.match(live(state), {385 onNone: () => [],386 onSome: (claim) => {11 unmodified lines398 ];399 },400 });401 457-/** Answered never changes; Released changes only by a fresh claim. */402 const endsAreFinal: Invariant = ({ before, command }, { state }) => [403 ...(ClaimState.guards.Answered(before) && !same(before, state)404 ? ["Answered is terminal"]405 : []),14 unmodified lines420 alarmsNextDeadline,421 endsAreFinal,422 ];423 480-/**481- * Names everything one call broke: who may claim, push and release, then,482- * when it went through, every invariant of the step it took.483- */424 const brokenBy = (call: Call, result: ClaimResult): readonly string[] => [425 ...claimsAsOwed(call, result),426 ...holderOnly(call, result),427 ...Result.match(result, {2 unmodified lines430 invariants.flatMap((invariant) => invariant(call, done)),431 }),432 ];433 494-/** The ask's claim states, by slot: the claimant's handle, or `ask` when shared. */434 type Slots = ReadonlyMap<string, ClaimState>;435 497-/** The model project service between two steps. */436 interface World {437 readonly now: DateTime.Utc;438 readonly slots: Slots;439 }6 unmodified lines446 447 const liveOutside = (slots: Slots, slot: string) =>448 [...slots].filter(([key, state]) => key !== slot && isLive(state)).length;449 512-/** A command for one slot. */450 interface Addressed {451 readonly command: ClaimCommand;452 readonly slot: string;453 }2 unmodified lines456 command,457 slot,458 });459 523-/** The commands the project service would send for a move, and where. */460 const commandsFor = (461 layout: Layout,462 slots: Slots,463 move: Move30 unmodified lines494 slotOf(layout, who),495 ClaimCommand.cases.Release.make({ who: Handle.make(who) })496 ),497 ],562- // An alarm reaches every claim the ask holds.498 Tick: () =>499 [...slots.keys()].map((slot) =>500 to(slot, ClaimCommand.cases.Tick.make({}))501 ),502 });503 569-/** Why an alarm left a claim past a deadline it reached, if it did. */504 const overdue = (now: DateTime.Utc, state: ClaimState) =>505 Option.flatMap(live(state), (claim) => {506 if (ms(now) >= ms(claim.lapsesAt)) {507 return Option.some("an alarm left a claim past lapsesAt");3 unmodified lines511 ? Option.some("an alarm left a claim unwarned past warnsAt")512 : Option.none();513 });514 581-/** What the whole ask keeps after a step: the race, and alarms that catch up. */515 const brokenAfter = (layout: Layout, world: World, move: Move) => {516 const states = [...world.slots.values()];517 518 const holders = new Set(11 unmodified lines530 : []),531 ];532 };533 601-/** Takes one step: the next world, and what broke on the way. */534 const advance = (layout: Layout, world: World, { after, move }: Step) => {535 const now = DateTime.add(world.now, { hours: after });536 const slots = new Map(world.slots);537 const broken: string[] = [];13 unmodified lines551 552 return { broken: [...broken, ...brokenAfter(layout, next, move)], next };553 };554 623-/** Runs a history; returns its first bad step and what that step broke. */555 const firstBreak = (layout: Layout, steps: readonly Step[]) => {556 let world: World = { now: start, slots: new Map() };557 558 for (const [index, step] of steps.entries()) {8 unmodified lines567 568 return [];569 };570 640-/**641- * Generated histories are CPU work alone: under a second on an idle machine,642- * several seconds while turbo runs every package's tests at once (the CLI's643- * build test compiles binaries beside them). This limit is there to catch a644- * hang, not a busy machine.645- */571+/** CPU-bound, but slow while turbo runs every package's tests at once: this catches a hang, not a busy machine. */572 const generated = { timeout: 30_000 };573 574 describe("the claim lifecycle, over generated histories", generated, () => {575 it.prop(10 unmodified linesmodified:packages/project/test/claim.test.ts-5 removed
32 unmodified lines33 const { Claim, Land, Push, Release, Tick } = ClaimCommand.cases;34 35 const HOUR = 3_600_000;36 37-/** The defaults: warned after 2 quiet hours, lapsed after 24. */37 const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };38 39 const project = ProjectName.make("alice/datekit");40 10 unmodified lines51 const bob = Handle.make("Bob");52 53 const carol = Handle.make("carol");54 56-/** Bob's fork: his handle in lowercase. */55 const fork = RepoName.make("alice__datekit--parse-iso--bob");56 57 const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");58 61-/** `hours` after the claim was made. */59 const at = (hours: number) => DateTime.add(start, { hours });60 64-/** A claim by a vouched person under their cap, on an ask nobody holds. */61 const claimBy = (62 handle: Handle,63 standing: Partial<Omit<typeof Claim.Type, "_tag" | "who">> = {}64 ) =>12 unmodified lines77 });78 79 const open = ClaimState.cases.Open.make({ ask });80 85-/** Bob's claim, made at `start`, never pushed to. */81 const fresh = {82 ask,83 base,84 claimant: bob,370 unmodified linesmodified:packages/project/test/code-facade.test.ts-6 removed
1-/**2- * The code façade both handler files call: a project's code read from its3- * canonical repo alone, with main resolved through the project's record.4- * Why each line is there is `code-why.test.ts`'.5- */1 import { describe, expect, it } from "@effect/vitest";2 import type { ProjectApi } from "@repo/project/project";3 import { keyOf, LandedSha, ProjectName } from "@repo/protocol/ids";4 import { untouchable } from "@repo/testkit/untouchable";5 unmodified lines10 const project = ProjectName.make("alice/datekit");11 12 const landed = LandedSha.make("4".repeat(40));13 19-/** A project's record, as the façade reads it: only these three. */14 const api = untouchable<ProjectApi>("ProjectApi", {15 forks: () => Effect.succeed([]),16 head: () => Effect.succeed({ landed }),17 landings: () => Effect.succeed([]),31 unmodified linesmodified:packages/project/test/code-fixtures.ts+3 added-53 removed
1-/**2- * Repos the code reads are tested over, written object by object with3- * isomorphic-git and pushed to the memory repo host: files of every kind4- * (text, binary, too large, a symlink, a submodule), the refs a canonical5- * repo really carries beside main (the landed mirror, a compose ref, the6- * notes, an import's stale `master`), and tags both lightweight and7- * annotated. Each `CodeProject` is fixed: its head, its one landing and its8- * one fork never come from the repo.9- */1 import { RefName, RepoHost } from "@repo/artifacts/repo-host";2 import type { RefUpdate } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";31 unmodified lines36 import type { FsClient, TreeEntry } from "isomorphic-git";37 38 import type { CodeProject } from "../src/code.ts";39 49-/** A file's content: text, bytes, a symlink's target, or a submodule's commit. */40 export type Content = Data.TaggedEnum<{41 Bytes: { readonly bytes: Uint8Array };42 Gitlink: { readonly commit: string };43 Link: { readonly target: string };1 unmodified line45 }>;46 47 export const Content = Data.taggedEnum<Content>();48 59-/** Paths and what each holds. */49 export type Tree = readonly (readonly [path: string, content: Content])[];50 51 interface Source {52 readonly fs: FsClient;53 unmodified lines106 107 return yield* Effect.promise(() => writeTree({ ...source, tree: entries }));108 });109 121-/**122- * A bare repo in memory that commits are written to and pushed from, each123- * commit's time `at` seconds after 2026-10-01.124- */110 export const writer = Effect.gen(function* () {111 const source = { fs: memoryFs(), gitdir: "/source.git" };112 113 yield* Effect.promise(() =>31 unmodified lines145 146 return CommitSha.make(oid);147 });148 164- /** An annotated tag object naming `commit`; its id, as a push sends it. */149 const annotated = (name: string, target: CommitSha) =>150 Effect.map(151 Effect.promise(() =>152 writeTag({15 unmodified lines168 // SAFETY: a tag's id is a 40-hex object id, which a ref update carries as a commit's.169 (oid) => CommitSha.make(oid)170 );171 188- /** `repo` made in the host, holding `refs`, each set to its commit. */172 const push = (173 repo: RepoName,174 refs: readonly (readonly [ref: string, to: CommitSha])[]175 ) =>15 unmodified lines191 192 return { annotated, commit, push };193 });194 212-/** A PNG's signature and the start of its header: a NUL in the first bytes. */195 export const png = Uint8Array.of(196 0x89,197 0x50,198 0x4e,7 unmodified lines206 0,207 0x0d208 );209 228-/** 1.5 MiB of text: past the 1 MiB a file's text may be. */210+/** Past the 1 MiB a file's text may be. */211 export const big = `${"x".repeat(1023)}\n`.repeat(1536);212 213 export const svg =214 '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>\n';37 unmodified lines252 ...without(third, "README.md"),253 ["README.md", text("# datekit, landed\n")],254 ];255 274-/** The claim fork the project's record lists. */256 export const fork: ForkRef = {257 ask: AskId.make("parse-iso"),258 handle: Handle.make("bob"),259 kind: "claim",260 repo: RepoName.make("alice__datekit--parse-iso--bob"),261 };262 282-/** The project's one landing, on `sha`. */263 const landingOf = (sha: CommitSha, parent: CommitSha): LandingView => ({264 ask: AskId.make("parse-iso"),265 assisted: [],266 author: Handle.make("bob"),3 unmodified lines270 project,271 sha: LandedSha.make(sha),272 });273 294-/** A project's record, fixed: main at `head`, `landed` its only landing. */274 const recordOf = (275 name: RepoName,276 head: CommitSha,277 landed: readonly LandingView[]5 unmodified lines283 project: Option.getOrThrow(nameOfKey(ProjectKey.make(name))),284 repo: name,285 });286 308-/**309- * datekit, four commits on main: the root; one that modifies `src/a.ts`,310- * deletes `old.txt` and adds `new.txt`; an imported commit whose trailer311- * forges an ask; and the platform's landing. Beside main: `master` at the312- * root (an import's stale branch), the landed mirror, a compose ref, the313- * notes, and three tags (`v1.9.0` light on the root, `v1.10.0` annotated314- * on the second, `@datekit/core@2.0.0` light on the third).315- */287+/** Main: a root, a change, an imported commit whose trailer forges an ask, and the landing; beside it a stale `master`, the platform's refs, and tags `v1.9.0`, `v1.10.0` (annotated) and `@datekit/core@2.0.0`. */288 export const datekit = Effect.gen(function* () {289 const git = yield* writer;290 const c1 = yield* git.commit("Start", first, [], 1);291 const c2 = yield* git.commit("Rework a", second, [c1], 2);33 unmodified lines325 code: recordOf(repo, c4, [landingOf(c4, c3)]),326 };327 });328 357-/**358- * A history of `count` commits: the first adds `once.txt`, and every one359- * after changes only `count.txt`.360- */329 export const longHistory = (count: number) =>330 Effect.gen(function* () {331 const git = yield* writer;332 const name = RepoName.make("oscabriel__longkit");23 unmodified lines356 357 return { code: recordOf(name, head, []), shas };358 });359 392-/**393- * A history of `count` commits, each appending one line to `grow.txt`, so394- * every line was brought by a commit of its own.395- */360 export const growingHistory = (count: number) =>361 Effect.gen(function* () {362 const git = yield* writer;363 const name = RepoName.make("oscabriel__growkit");22 unmodified lines386 387 return { code: recordOf(name, head, []), shas };388 });389 426-/** One root commit of `count` files. */390 export const wide = (count: number) =>391 Effect.gen(function* () {392 const git = yield* writer;393 const name = RepoName.make("oscabriel__widekit");9 unmodified lines403 404 return { code: recordOf(name, sha, []), sha };405 });406 444-/**445- * A workspace whose root README is a symlink to its crate's, as axum's is,446- * with links elsewhere that a README must not follow: one up out of the447- * repo, one to nothing, one to a folder, one to a link (the root's) and448- * one absolute. `docs` links up one level to the crate's README, and449- * `both` holds a dangling `README.md` link beside a `readme.md` file.450- */407 export const linkedReadmes = Effect.gen(function* () {408 const git = yield* writer;409 const name = RepoName.make("oscabriel__linkkit");410 20 unmodified lines431 432 return { code: recordOf(name, sha, []) };433 });434 479-/**480- * The memory store, each `readTree` (or each `readBlob`, for `"blob"`)481- * taking 10 ms once `reading` is set (a history is written fast, then482- * read), with the most reads ever under way at once kept in `peak`: a live483- * store answers a read in tens of milliseconds, so a walk that reads one484- * object at a time takes all its reads added up.485- */435+/** A live store answers a read in tens of milliseconds, so a walk that reads one object at a time pays for every read; `peak` records the most reads under way at once. */436 export const overlappingTrees = (437 reading: Ref.Ref<boolean>,438 peak: Ref.Ref<number>,439 kind: "blob" | "file" | "tree" = "tree"38 unmodified linesmodified:packages/project/test/code-history.test.ts+6 added-63 removed
1-/**2- * Code history kept by immutable ids, over the memory repo3- * host behind a wrapper that counts the trees and blobs read, the memory4- * code store, and a fresh `CodeCacheLive` for each isolate: a why and a5- * path's log computed on one isolate are read back on another without a6- * walk; one landing past a kept result costs a handful of reads and agrees7- * with the whole walk; landings are always asked fresh; a cold walk keeps8- * many reads under way and looks each commit's entry up once; a value9- * that no longer decodes is computed again and replaced.10- */1 import { describe, expect, it } from "@effect/vitest";2 import { RepoHost, RepoSession, Revision } from "@repo/artifacts/repo-host";3 import type { RepoSessionApi } from "@repo/artifacts/repo-host";4 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";28 unmodified lines33 const format = RepoPath.make("src/format.ts");34 35 const text = (value: string) => Content.Text({ text: value });36 47-/**48- * What the counting host saw: trees and blobs read, the most under way at49- * once, and each read's start (`+<id>`) and end (`-<id>`) in order.50- */37 interface Seen {38 readonly trees: number;39 readonly blobs: number;54- /** Files read whole at a commit (`readFile`). */40 readonly files: number;56- /** Commits read one by one (`readCommit`). */41 readonly commits: number;58- /** Pages of the log read (`log`). */42 readonly logs: number;43 readonly peak: number;44 readonly events: readonly string[];45 }7 unmodified lines53 peak: 0,54 trees: 0,55 };56 74-/** How long a read of the object `id` takes, once a test sets it. */57 type Delay = Option.Option<(id: string) => Duration.Duration>;58 77-/**78- * The memory store, each tree and blob read counted in `seen` and, once79- * `delay` is set, taking as long as it says: a live store answers each80- * read in tens to hundreds of milliseconds.81- */59 const counted = (seen: Ref.Ref<Seen>, delay: Ref.Ref<Delay>) =>60 Layer.effect(61 RepoHost,62 Effect.gen(function* () {40 unmodified lines103 timed("logs", "log", host.log(name, at, limit, offset)),104 readBlob: (name, id) => timed("blobs", id, host.readBlob(name, id)),105 readCommit: (name, sha) =>106 timed("commits", sha, host.readCommit(name, sha)),130- // A file read at a commit is noted by the commit's id.107 readFile: (name, at, path) =>108 timed(109 "files",110 Revision.$match(at, {16 unmodified lines127 project,128 sha: LandedSha.make(sha),129 });130 155-/** A project's record whose landings a test may add to, each batch asked for counted. */131 const recordOf = (head: CommitSha) =>132 Effect.gen(function* () {133 const landed = yield* Ref.make<readonly LandingView[]>([]);134 const asked = yield* Ref.make(0);15 unmodified lines150 151 return { asked, code, landed };152 });153 179-/** histkit's tree: its README and `src/format.ts`. */154 const filesOf = (formatted: string, readme: string): Tree => [155 ["README.md", text(readme)],156 ["src/format.ts", text(formatted)],157 ];158 185-/**186- * histkit: `src/format.ts` grows over four commits (one leaves it alone),187- * then two children of the fourth: `grown` inserts two lines and changes188- * one, `still` changes only the README.189- */159 const history = Effect.gen(function* () {160 const git = yield* writer;161 162 const c1 = yield* git.commit("Adopt", filesOf("a\nb\n", "# one\n"), [], 1);34 unmodified lines197 198 return { c1, c3, c4, grown, still };199 });200 232-/** `effect` on a fresh isolate: a code cache of its own. */201 const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>202 Effect.provide(effect, CodeCacheLive(100));203 236-/** `effect` with a store of its own, empty: the whole walk, from nothing. */204 const fromNothing = <A, E, R>(effect: Effect.Effect<A, E, R>) =>205 onIsolate(Effect.provide(effect, CodeStoreMemory));206 240-/** A view's ranges, the commits it names and where it stopped. */207 const whyOfView = (view: {208 readonly ranges: readonly unknown[];209 readonly commits: readonly { readonly sha: CommitSha }[];210 readonly stoppedAt?: CommitSha;2 unmodified lines213 ranges: view.ranges,214 stoppedAt: view.stoppedAt,215 });216 251-/** A test body over the counting host and one store every isolate shares. */217 const within = <A, E>(218 body: (counts: {219 readonly seen: Ref.Ref<Seen>;220 readonly delay: Ref.Ref<Delay>;26 unmodified lines247 const again = yield* onIsolate(whyOf(code, Option.none(), format));248 const { blobs, commits, files, logs, trees } = yield* Ref.get(seen);249 250 expect(again).toStrictEqual(first);286- // The commits it names come from one page of the log, not one287- // read each.251+ // The commits it names come from one page of the log, not one read each.252 expect({ blobs, commits, files, logs, trees }).toStrictEqual({253 blobs: 0,254 commits: 0,255 files: 0,38 unmodified lines294 )295 );296 });297 334-/** The first page of `src/format.ts`'s log from `from`. */298 const formatLog = (from: CommitSha) => ({299 at: Option.some(from),300 from: 0,301 limit: 30,62 unmodified lines364 const next = yield* onIsolate(logOf(code, formatLog(grown)));365 const counts = yield* Ref.get(seen);366 const whole = yield* fromNothing(logOf(code, formatLog(grown)));367 405- // `src/format.ts` two folders down, in `grown` and in `c4`.368 expect(counts.trees).toBeLessThanOrEqual(4);369 expect(next).toStrictEqual(whole);370 expect(next.commits.map(({ sha }) => sha)[0]).toBe(grown);371 })7 unmodified lines379 Effect.gen(function* () {380 const { c1, grown } = yield* history;381 const { code, landed } = yield* recordOf(grown);382 421- // One isolate, so the second view finds the first's history kept.383 const [before, after] = yield* onIsolate(384 Effect.gen(function* () {385 const first = yield* whyOf(code, Option.none(), format);386 11 unmodified lines398 )399 );400 });401 441-/**442- * `count` commits: each changes `count.txt` at the root and leaves443- * `a/b/c/d/deep.txt` alone, so the commits' root trees all differ and the444- * folders under them never do.445- */402 const deepHistory = (count: number) =>403 Effect.gen(function* () {404 const git = yield* writer;405 const shas: CommitSha[] = [];52 unmodified lines458 ),459 long460 );461 506- // Counted, not timed: a batch of 16 waits for its slowest read, so while507- // one commit's file takes a second, at most its 15 neighbours finish;508- // with no barrier, every other commit does. Wall time under a loaded509- // machine says less than this count (the walk took about a quarter of510- // the batched walk's 1,250 ms when each read took 50 ms).462+ // Counted, not timed: a batch of 16 waits for its slowest read, so while one463+ // commit's file takes a second, at most its 15 neighbours finish; with no464+ // barrier, every other commit does.465 it.live(466 "goes on past a slow read: every other commit's file is read while one takes a second",467 () =>468 within(({ delay, seen }) =>469 Effect.gen(function* () {470 const { head, shas } = yield* deepHistory(64);471 const { code } = yield* recordOf(head);472 519- // The commit after the head: the first the pass looks up. A file520- // read is noted by its commit's id.473 const slow = shas[62] ?? "";474 475 yield* Ref.set(seen, none);476 yield* Ref.set(63 unmodified lines540 path: Option.some(RepoPath.make("a/b")),541 });542 543 expect(commits).toHaveLength(1);592- // Each commit's root tree read once from the store, and `a`, the593- // same tree in every commit, once. The view shares a tree read594- // under way among its fibers, so this count holds the store's595- // reads, not how often the walk asked.544+ // Each commit's root tree once, and `a`, the same tree in every commit,545+ // once: in-flight tree reads are shared among the view's fibers.546 expect((yield* Ref.get(seen)).trees).toBe(201);547 })548 ),549 long108 unmodified lines658 })659 );660 });661 712-/**713- * The memory store, the session each commit, tree, blob and log read ran714- * in noted in `sessions`, in order.715- */662 const sessioned = (663 sessions: Ref.Ref<readonly Option.Option<RepoSessionApi>[]>664 ) => {665 const noted = <A, E>(read: Effect.Effect<A, E>) =>21 unmodified lines687 })688 ).pipe(Layer.provide(RepoHostMemory));689 };690 745-/** How many sessions `sessions` names, and whether a read ran in none. */691 const sessionsIn = (sessions: readonly Option.Option<RepoSessionApi>[]) => ({692 outside: sessions.some(Option.isNone),693 sessions: new Set(sessions.flatMap(Option.toArray)).size,694 });99 unmodified lines794 yield* whyOf(code, Option.none(), RepoPath.make("a/b/c/d/deep.txt"));795 796 const { blobs, files, trees } = yield* Ref.get(seen);797 853- // One read of the file per commit is one call each; the folders854- // above it took five per commit.798 expect({ blobs, files }).toStrictEqual({ blobs: 0, files: 20 });799 expect(trees).toBeLessThanOrEqual(5);800 })801 )113 unmodified linesmodified:packages/project/test/code-raw.test.ts-8 removed
1-/**2- * A project's raw bytes as the platform and the dev world serve them: each3- * file under a sandboxing CSP and `nosniff`, typed by its extension so4- * that only images render as themselves (an SVG under the sandbox), markup5- * comes back as plain text, an immutable cache for a commit's id and a6- * minute for a name that moves, and a 404 with nothing from the repo for7- * anything else.8- */1 import { describe, expect, it } from "@effect/vitest";2 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3 import { ProjectName, RepoPath } from "@repo/protocol/ids";4 import { Effect, Option } from "effect";177 unmodified linesmodified:packages/project/test/code-store.test.ts-9 removed
1-/**2- * The code history's durable store: a `Context.Reference` that stores3- * nothing until a host gives it one, a memory adapter that counts its4- * calls, and the R2 adapter, whose every failure is a miss and never the5- * reader's failure.6- */1 import { describe, expect, it } from "@effect/vitest";2 import { Effect, Exit, Layer, Logger, Option } from "effect";3 4 import { CodeStore } from "../src/code-store.ts";5 unmodified lines10 11 /** A key one byte past R2's limit of 1,024. */12 const tooLong = "k".repeat(1025);13 20-/** A put of `value` under `key`, then a get of it. */14 const putThenGet = Effect.gen(function* () {15 const store = yield* CodeStore;16 17 yield* store.put(key, '{"lines":[]}');18 19 return yield* store.get(key);20 });21 29-/** A bucket over a map, whose `get` or `put` throws when told to. */22 const bucketOf = (fails: {23 readonly get?: boolean;24 readonly put?: boolean;25 }) => {22 unmodified lines48 49 return bucket;50 };51 60-/** Every message logged while `effect` runs, beside its exit. */52 const logged = <A, E>(effect: Effect.Effect<A, E>) =>53 Effect.gen(function* () {54 const messages: unknown[] = [];55 91 unmodified linesmodified:packages/project/test/code-tags.test.ts-9 removed
1-/**2- * A project's tags in the order a reader meets them: tags that version no3- * package first, then each package's tags as one run, the package with the4- * most tags first, newest first within a run. A monorepo's main package5- * (changesets' `@changesets/cli`) then sits on the first page, not several6- * pages in behind every one-tag package.7- */1 import { describe, expect, it } from "@effect/vitest";2 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3 import { packageOf } from "@repo/protocol/domain/code";4 import { ProjectName, RepoName } from "@repo/protocol/ids";3 unmodified lines8 import type { CodeProject } from "../src/code.ts";9 import { sortTags } from "../src/code/refs.ts";10 import { writer } from "./code-fixtures.ts";11 19-/** Changesets' kinds of tag, shuffled: plain, scoped and unscoped. */12 const shuffled = [13 "get-workspaces@1.0.11",14 "@changesets/cli@2.27.1",15 "@changesets/cli@2.3.0",3 unmodified lines19 "v1.10.0-beta.1",20 "v1.10.0",21 ];22 31-/** The order a reader meets them in. */23 const ordered = [24 "v2.0.0",25 "v1.10.0",26 "v1.10.0-beta.1",69 unmodified linesmodified:packages/project/test/code-why.test.ts-17 removed
1-/**2- * Why each line of a file is there, read from the canonical repo over the3- * memory repo host with a fixed project record: an adoption, a commit that4- * leaves the file alone, then two landings that each add a line to5- * `src/format.ts`. Each line points at the commit that brought it, every6- * such commit comes back as a reader sees it, the landings among them come7- * from the record, and the whole view is kept by `(at, path)`.8- */1 import { describe, expect, it } from "@effect/vitest";2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import type { LandingView } from "@repo/protocol/domain/landing";54 unmodified lines59 onSome: (at) => ({ parent: LandedSha.make(at) }),60 }),61 });62 71-/**72- * datekit: the adoption brings `src/format.ts` (two lines) and a binary73- * logo; a commit then changes only the README; `format-iso` inserts a line74- * between the two; `format-week` appends one.75- */63 const history = Effect.gen(function* () {64 const git = yield* writer;65 66 const adopted = yield* git.commit(77 unmodified lines144 145 return { adopted, asked, code, iso, landings, readme, week };146 });147 161-/**162- * The memory store, with each blob `readBlob` is asked for, and each file163- * `readFile` reads whole at a commit, counted in `reads`.164- */148 const countedBy = (reads: Ref.Ref<readonly string[]>) =>149 Layer.effect(150 RepoHost,151 Effect.gen(function* () {196 unmodified linesmodified:packages/project/test/code.test.ts+4 added-26 removed
1-/**2- * A project's code as readers browse it, read from its canonical repo over3- * the memory repo host, with main, the landings and the forks taken from a4- * fixed project record: refs without the platform's internals, folders and5- * their READMEs, revisions that resolve only to main, a commit or a tag,6- * files within their caps, the first-parent log with its landings, a7- * commit's changes, and reads by object id kept once read.8- */1 import { describe, expect, it } from "@effect/vitest";2 import { RepoHost } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import { Brand } from "@repo/brand";51 unmodified lines56 const path = (text: string) => Option.some(RepoPath.make(text));57 58 const page = { at: main, from: 0, limit: 30, path: Option.none() };59 68-/**69- * A history of hundreds of commits, written and pushed in memory: well70- * under a second alone, many times that beside every other package's tests.71- */60+// Hundreds of commits in memory: under a second alone, much longer beside other packages' tests.61 const long = { timeout: 30_000 };62 63 describe("a project's refs", () => {64 it.effect(445 unmodified lines510 511 expect(commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);512 }).pipe(Effect.provide(overlappingTrees(reading, peak, "file")));513 525- // 64 commits, the file read whole in each: one at a time a live526- // store took a minute for 200; `READS_AT_ONCE` commits at once now.514+ // 64 commits, the file read whole in each, `READS_AT_ONCE` at a time.515 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);516 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE);517 }),518 long83 unmodified lines602 603 /** 150 KiB of text: fourteen of them run past a diff's 2 MiB of text. */604 const sizable = (name: string) => `${name.padEnd(1023, "y")}\n`.repeat(150);605 618-/**619- * One commit modifying twenty files, `f00.txt` to `f19.txt`, each from a620- * line to 150 KiB but `f14.txt`, which stays small: thirteen fit the text621- * budget, `f13.txt` runs past it, and every file after it is a path only.622- */606 const twentyFiles = Effect.gen(function* () {607 const git = yield* writer;608 const name = RepoName.make("twentykit");609 87 unmodified lines697 long698 );699 });700 718-/** The memory store, with each blob `readBlob` is asked for counted in `reads`. */701 const blobsCountedBy = (reads: Ref.Ref<number>) =>702 Layer.effect(703 RepoHost,704 Effect.gen(function* () {8 unmodified lines713 });714 })715 ).pipe(Layer.provide(RepoHostMemory));716 735-/** What the store keeps under a key, as a diff, if it holds one that decodes. */717 const keptUnder = (key: string) =>718 Effect.map(719 Effect.flatMap(Effect.service(CodeStore), (store) => store.get(key)),720 Option.flatMap(80 unmodified lines801 })802 );803 });804 824-/** The memory store, with each tree id `readTree` is asked for counted in `reads`. */805 const countedBy = (reads: Ref.Ref<readonly string[]>) =>806 Layer.effect(807 RepoHost,808 Effect.gen(function* () {62 unmodified lines871 it.effect(872 "never make a caller wait on a read another caller left unfinished",873 () =>874 Effect.gen(function* () {895- // A Worker whose client goes away is cancelled where it stands: its896- // fibers are never interrupted, so a read it began never ends. The897- // isolate's next request for that key must read for itself (on898- // dev-oscabriel each such request hung, answering 1101).875+ // A Worker whose client goes away is cancelled without interrupting its876+ // fibers, so a read it began never ends: the next request must read for itself.877 const cache = yield* CodeCache;878 879 yield* Effect.forkDetach(880 cache.through("burrow:text:abandoned", Effect.never)14 unmodified linesmodified:packages/project/test/deciders.test.ts+1 added-59 removed
55 unmodified lines56 import { CheckScript, composedAt, mergedAt, Pusher, worldOf } from "./world.ts";57 58 const people = ["bob", "carol", "dave", "erin", "eve", "frank"];59 60-/**61- * datekit, whose deciders are alice alone (`**`). Everyone but dave is62- * vouched for. `format-date` is a `polish` ask, whose kind needs a finish.63- */60 const scenario = aProject({ people }).pipe(61 withVouches(["bob", "carol", "erin", "eve", "frank"]),62 withKind({63 checkKind: "redThenGreen",21 unmodified lines85 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });86 87 const alice = person("alice");88 93-/** alice, as a sign-in provider that capitalizes handles names her. */89 const aliceSignedIn = Person.make({ handle: Handle.make("Alice") });90 91 const bob = person("bob");92 23 unmodified lines116 117 const daysAfter = (from: DateTime.Utc, count: number) =>118 DateTime.add(from, { days: count });119 125-/** The project as alice first pushes it. */120 const start: Files = [121 [122 "package.json",123 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',6 unmodified lines130 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],131 ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],132 ];133 140-/** An ask's own files: its file in the config folder, and its check. */134 const askFiles = (id: string) => {135 const { check, file, territory } = askOf(id);136 137 const subject = territory.module;16 unmodified lines154 }155 );156 };157 165-/** Where a canonical `main` stands now. */158 const tipOf = (name: RepoName) =>159 Effect.gen(function* () {160 const refs = yield* (yield* RepoHost).refs(name).pipe(Effect.orDie);161 1 unmodified line163 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))164 );165 });166 175-/** Where datekit's `main` stands now. */167 const mainTip = tipOf(repo);168 178-/** A commit's author, committer, parents and trailers. */169 const commitOf = (sha: CommitSha) =>170 Effect.gen(function* () {171 const host = yield* RepoHost;172 const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);3 unmodified lines176 });177 178 const scheduled = ScheduledAlarm.use(({ at }) => at);179 190-/** The project's rows as its store keeps them. */180 const stored = ProjectStore.use((store) => store.load());181 193-/** alice makes a project's first landing: `files`, pushed to its empty repo. */182 const made = (api: ProjectApi, on: RepoName, files: Files = start) =>183 Effect.gen(function* () {184 yield* api.initProject(alice, {});185 5 unmodified lines191 192 return api;193 });194 207-/** alice makes datekit and pushes its first commit. */195 const begun = Effect.gen(function* () {196 yield* advanceTo("2026-10-07T12:00:00Z");197 198 return yield* made(yield* projectService(project), repo);199 });200 214-/** The check of an ask with these files, scripted to fail twice on main as it now stands. */201 const redOnMain = (202 files: Array.NonEmptyReadonlyArray<{203 readonly content: string;204 readonly path: RepoPath;7 unmodified lines212 checker.script(composed, redThenGreen, ["failed", "failed"])213 );214 });215 230-/** alice opens `id`, its check scripted red twice on main. */216 const openRed = (api: ProjectApi, id: string, on: RepoName = repo) =>217 Effect.gen(function* () {218 const files = askFiles(id);219 3 unmodified lines223 });224 225 const lanes = [redThenGreen, LaneName.make("lint"), LaneName.make("types")];226 242-/** `files` with `path` holding `content`, added or replaced. */227 const changed = (files: Files, path: string, content: string): Files => [228 ...files.filter(([each]) => each !== path),229 [path, content],230 ];231 248-/** The files main holds after `ids`' asks opened on it. */232 const withAskFiles = (files: Files, ...ids: readonly string[]): Files => [233 ...files,234 ...ids.flatMap((id) =>235 askFiles(id).map(({ content, path }) => [path, content] as const)236 ),237 ];238 256-/**257- * `who` claims `id` and answers it with `change` on main as it stands, every258- * lane scripted to pass on the merge: what reaches the answer's checks.259- */239 const answered = (240 api: ProjectApi,241 input: {242 readonly change: readonly [path: string, content: string];46 unmodified lines289 });290 291 const firstDecision = DecisionId.make("dec-000001");292 314-/** carol proposes `trim-input` with its files; alice accepts it. */293 const proposing = (api: ProjectApi) =>294 Effect.gen(function* () {295 const files = askFiles("trim-input");296 42 unmodified lines339 third,340 };341 });342 365-/** carol's proposal, left alone for its fourteen days. */343 const expiring = (api: ProjectApi) =>344 Effect.gen(function* () {345 yield* api.proposeAsk(carol, { want: "Trim tabs too" });346 yield* advanceTo("2026-10-21T12:00:00Z");13 unmodified lines360 today: yield* api.today(alice),361 };362 });363 387-/**388- * carol proposes `trim-input`, and alice accepts it while the Checker cannot389- * run its check; then again, once it can.390- */364 const acceptingBlocked = (api: ProjectApi) =>365 Effect.gen(function* () {366 const files = askFiles("trim-input");367 29 unmodified lines397 proposals: between.proposals.map(({ state }) => state),398 };399 });400 428-/** datekit, where alice decides the packages and frank the config folder only. */401 const splitDeciders = {402 policy: {403 ...scenario.policy,404 deciders: [5 unmodified lines410 ],411 },412 };413 442-/** carol proposes `trim-input` in the packages; who is asked to decide it. */414 const askedToDecide = Effect.gen(function* () {415 const api = yield* begun;416 417 const { proposal } = yield* api.proposeAsk(carol, {162 unmodified lines580 )581 );582 });583 613-/** bob's answer to the `polish` ask `format-date`, finished by alice. */584 const finishing = (api: ProjectApi) =>585 Effect.gen(function* () {586 yield* openRed(api, "format-date");587 43 unmodified lines631 waiting,632 };633 });634 665-/**666- * bob's answer to `format-date`, which alice finishes with a commit of her667- * own on top; first with one that touches its check, which she may not.668- */635 const finishingOnTop = (api: ProjectApi) =>636 Effect.gen(function* () {637 yield* openRed(api, "format-date");638 167 unmodified lines806 })807 );808 });809 844-/** alice makes her working fork, and lands a change of her own from it. */810 const landingOwn = (api: ProjectApi) =>811 Effect.gen(function* () {812 const host = yield* RepoHost;813 const forked = yield* api.fork(alice);166 unmodified lines980 })981 );982 });983 1019-/**1020- * The world, with a rules evaluator that also reads the vouch file at the1021- * commit it evaluates, as the real one does (`finishPolicy`): its1022- * lines join the scenario's.1023- */984 const vouchingWorld = Layer.effect(985 RulesEvaluator,986 Effect.gen(function* () {987 const evaluator = yield* RulesEvaluator;13 unmodified lines1001 });1002 })1003 ).pipe(Layer.provideMerge(worldOf(scenario, "memory")));1004 1045-/** The vouch file on main. */1005 const vouchFileNow = Effect.gen(function* () {1006 const host = yield* RepoHost;1007 const at = yield* mainTip;1008 7 unmodified lines1016 1017 return Option.map(bytes, (read) => new TextDecoder().decode(read));1018 });1019 1061-/** alice vouches for dave, who could not claim before, and denounces erin. */1020 const vouching = (api: ProjectApi) =>1021 Effect.gen(function* () {1022 yield* openRed(api, "lex-tokens");1023 yield* openRed(api, "parse-iso");83 unmodified lines1107 })1108 );1109 });1110 1153-/** Six proposals an hour apart, from three people, and alice taking the first. */1111 const filling = (api: ProjectApi) =>1112 Effect.gen(function* () {1113 const proposers = [carol, eve, frank, carol, eve, frank];1114 95 unmodified lines1210 });1211 1212 const burrow = ProjectName.make("alice/burrow");1213 1257-/** One landing's credit in the parser module. */1214 const row = (name: ProjectName, role: "Asked-by" | "Signed-off-by") => ({1215 area: "parser",1216 count: 1,1217 project: name,1218 role,1219 });1220 1265-/** bob answers `parse-iso` in datekit, and carol in burrow, both made through `Projects`. */1221 const crediting = Effect.gen(function* () {1222 yield* advanceTo("2026-10-07T12:00:00Z");1223 1224 const projects = yield* Projects;31 unmodified lines1256 dave: yield* creditsFor(dave.handle, among),1257 };1258 });1259 1305-// Assisted-by never reaches a credit row (the `creditsByArea` test, and1306-// `CreditSummary`'s role type); no answer here carries an agent trailer.1260+// Assisted-by never reaches a credit row; no answer here carries an agent trailer.1261 describe("credits", () => {1262 it.effect("count a person's roles by project and area across projects", () =>1263 Effect.map(1264 crediting.pipe(13 unmodified lines1278 )1279 );1280 });1281 1328-/** A commit pushed straight onto canonical main, past the platform. */1282 const strayOnto = (first: CommitSha) =>1283 Pusher.use((pusher) =>1284 pusher.push(1285 repo,6 unmodified lines1292 "Stray"1293 )1294 );1295 1343-/** canonical main's move as OnPush reports it to the project: from nobody the platform knows. */1296 const reported = (1297 api: ProjectApi,1298 eventId: string,1299 move: { readonly after: CommitSha; readonly before?: CommitSha }6 unmodified lines1306 ref: "refs/heads/main",1307 repo,1308 });1309 1358-/**1359- * Canonical main's moves as OnPush reports them: the initializer's first1360- * push, an ask's landing, then a push the platform did not make, twice1361- * under one event id.1362- */1310 const strayReported = Effect.gen(function* () {1311 const api = yield* begun;1312 const first = yield* mainTip;1313 26 unmodified lines1340 stray,1341 };1342 });1343 1397-/**1398- * A push to canonical main the platform did not make, reported by OnPush,1399- * which opens the decision, then decided by alice.1400- */1344 const strayDecided = (choice: "accept" | "decline") =>1345 Effect.gen(function* () {1346 const api = yield* begun;1347 const host = yield* RepoHost;27 unmodified lines1375 tipTree: yield* treeOf(tip),1376 };1377 });1378 1436-/** canonical main deleted past the platform, as OnPush reports it, then decided by alice. */1379 const deletedDecided = (choice: "accept" | "decline") =>1380 Effect.gen(function* () {1381 const api = yield* begun;1382 const first = yield* mainTip;108 unmodified linesmodified:packages/project/test/do-reads.test.ts+1 added-18 removed
1-/**2- * The four small reads the code browser and the people page take from a3- * project's record: where main has landed, which commits are landings,4- * which forks exist, and the policy as anyone may read it.5- */1 import { describe, expect, it } from "@effect/vitest";2 import { Brand } from "@repo/brand";3 import { CheckSpec } from "@repo/protocol/domain/check";4 import { ProjectEvent } from "@repo/protocol/domain/event";64 unmodified lines69 : RepoPath.make(`${Brand.configDir}/checks/parse-iso.test.ts`),70 }71 );72 78-/** A commit that is no landing: imported history, say. */73 const imported = CommitSha.make("b".repeat(40));74 75 const read = Effect.gen(function* () {76 yield* advanceTo("2026-10-07T12:00:00Z");67 unmodified lines144 it.effect(145 "say where main landed, which commits are landings, the forks and the public policy",146 () =>147 Effect.map(read.pipe(Effect.provide(world)), (got) => {154- // Before the first landing there is no policy, and nothing to say why.148 expect(got.before).toStrictEqual({ forks: [], head: {}, policy: {} });149 expect(got.after.head).toStrictEqual({ landed: got.landed });157- // The ask's opening landed on the adoption; the other commit is none.158- // An opening names the ask it opened, and answers none.150 expect(151 got.after.landings.map(({ ask, opened, parent, sha }) => ({152 ask,153 opened,21 unmodified lines175 const policy = Option.getOrThrow(176 Option.fromUndefinedOr(got.after.policy.policy)177 );178 188- // It evaluated, so there is nothing to say why not.179 expect({180 deciders: policy.deciders,181 hidden: ["asks", "functions", "visibility"].filter(182 (key) => key in policy7 unmodified lines190 })191 );192 });193 204-/** A commit SHA made of one digit, for rows written straight to the store. */194 const shaOf = (digit: string) => LandedSha.make(digit.repeat(40));195 207-/**208- * Rows as an older build wrote them: landings with no `opened`, beside the209- * asks they opened. `p` opens a migrate family (the parent `migrate-p`, its210- * step `migrate-p-1`), `a` lands an answer to `parse-iso`.211- */196+/** Rows as an older build wrote them: landings with no `opened`. */197 const olderRows = Effect.gen(function* () {198 yield* advanceTo("2026-10-07T12:00:00Z");199 200 const api = yield* projectService(project);55 unmodified lines256 })257 );258 });259 275-/** A rules evaluator whose every config folder fails to evaluate. */260 const failingRules = Layer.succeed(261 RulesEvaluator,262 RulesEvaluator.of({263 call: () => Effect.succeed(false),3 unmodified lines267 ),268 })269 );270 287-/** The policy after a first push of `files`, with every evaluation failing. */271 const unevaluatedAfter = (files: Files) =>272 Effect.gen(function* () {273 yield* advanceTo("2026-10-07T12:00:00Z");274 38 unmodified linesmodified:packages/project/test/draft-settle.test.ts-9 removed
37 unmodified lines38 import type { ProjectApi } from "../src/project.ts";39 import { projectService } from "../src/project.ts";40 import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";41 42-/** datekit, decided by alice alone, with one `fix` ask carol may want. */42 const scenario = aProject({ people: ["carol", "dave"] }).pipe(43 withVouches(["carol", "dave"]),44 withAsk({ id: "parse-week", territory: "packages/parser" })45 );42 unmodified lines88 const askSource = `export default "parse-week";\n`;89 90 const testSource = `import { parseWeek } from "../src/parse.ts";\n`;91 93-/** The drafted ask's files: its ask file and its failing test. */92 const files = Array.make(93 { content: askSource, path: ask.file },94 { content: testSource, path: testPath }95 );15 unmodified lines111 });112 113 const mainRef = RefName.make("refs/heads/main");114 117-/** Every draft run the project started, in order. */115 class Started extends Context.Service<116 Started,117 { readonly runs: Effect.Effect<readonly DraftParams[]> }118 >()("test/Started") {}119 123-/** `DraftRuns` that records each run it is asked to start. */120 const recorded = Layer.effectContext(121 Effect.gen(function* () {122 const started = yield* Ref.make<readonly DraftParams[]>([]);123 4 unmodified lines128 );129 130 const world = Layer.mergeAll(worldOf(scenario, "memory"), recorded);131 136-/** alice makes datekit; carol proposes the want with a draft. */132 const proposed = Effect.gen(function* () {133 yield* advanceTo("2026-10-08T12:00:00Z");134 135 const api: ProjectApi = yield* projectService(project);24 unmodified lines160 );161 162 const runs = Started.use(({ runs: all }) => all);163 169-/** The drafted files composed onto main, their check scripted red there. */164 const redOnMain = Effect.gen(function* () {165 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);166 167 const tip = LandedSha.make(8 unmodified lines176 });177 178 const firstDecision = DecisionId.make("dec-000001");179 186-/** datekit as above, with dave deciding the parser beside alice. */180 const parserByDave = {181 policy: {182 ...scenario.policy,183 deciders: [27 unmodified lines211 decisions: yield* openProposalDecisions,212 opened: (yield* api.events(0, 100)).flatMap(({ event }) =>213 ProjectEvent.guards.ProposalOpened(event) ? [event.proposal] : []214 ),222- // The run's row ran, and is gone.215 outbox: (yield* stored).outbox,216 runs: yield* runs,217 today: (yield* api.today(alice)).decisions,218 }).toStrictEqual({327 unmodified lines546 key: "Assisted-by",547 value: `${Brand.cli}-drafter:${model} (verified)`,548 },549 ]);558- // Beside alice's first push, the landing that opened the ask.550 expect(551 landings552 .filter(({ sha }) => sha === tip)553 .map(({ assisted, credits }) => ({ assisted, credits }))141 unmodified linesmodified:packages/project/test/drafting.model.test.ts+3 added-36 removed
26 unmodified lines27 import type { ProjectApi } from "../src/project.ts";28 import { projectService } from "../src/project.ts";29 import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";30 31-// A model test (ADR 0012), as `claim.model.test.ts` is for claims: generated32-// histories of drafted proposals (proposed, settled red or refused, in the33-// current round or a stale one, drafted again, accepted, expired) run34-// through the project service over the memory world, and after every step35-// the stored proposals and decisions are checked against the drafting36-// invariants.37-31 const scenario = aProject({ people: ["carol", "dave"] }).pipe(32 withVouches(["carol", "dave"]),33 withAsk({ id: "parse-week", territory: "packages/parser" })34 );51 unmodified lines86 model,87 refusal: new NotRedFirst({}),88 });89 97-/** Which of the (at most two) proposals a move is about, by the order they were made in. */90 const Which = Schema.Literals([0, 1]);91 100-/** A settle's round: the proposal's current one, or one either side of it. */92 const Round = Schema.Literals(["current", "before", "after"]);93 94 type Round = typeof Round.Type;95 105-/** One thing that happens, as a history step names it. */96 const Move = Schema.TaggedUnion({97 Accept: { which: Which },98 Expire: {},99 Propose: {},5 unmodified lines105 106 const roll = (maximum: number) =>107 Arbitrary.schema(Schema.Int.check(Schema.isBetween({ maximum, minimum: 0 })));108 119-/** Mostly the first proposal, so one proposal lives through many moves. */109 const anyWhich = roll(3).pipe(Arbitrary.map((n) => (n === 3 ? 1 : 0)));110 122-/** Mostly the current round; a stale one now and then. */111 const rounds: readonly Round[] = [112 "current",113 "current",114 "current",5 unmodified lines120 const anyRound = roll(rounds.length - 1).pipe(121 Arbitrary.map((n) => rounds[n] ?? "current")122 );123 136-/** Mostly someone who may draft again; now and then someone who may not. */124 const drafters: readonly People[] = [125 "carol",126 "alice",127 "carol",23 unmodified lines151 152 const expires = Arbitrary.Constant(Move.cases.Expire.make({}));153 154 /**168- * Moves by weight. A roll leans towards 0, and shrinks towards it, so a169- * settle comes first: the move that runs into most of the rules.155+ * A roll leans and shrinks towards 0, so a settle, the move that runs into most156+ * rules, comes first.157 */158 const weighted = [159 settles,160 redrafts,13 unmodified lines174 const histories = Arbitrary.array(moves, { maxLength: 16 });175 176 const offset = (round: Round) => ({ after: 1, before: -1, current: 0 })[round];177 191-/** The labels of a proposal's evidence that are not its files. */178 const notFiles = new Set([179 "want",180 "territory",181 "red first",11 unmodified lines193 );194 195 const roundOf = (proposal: Proposal) => proposal.draft?.round ?? 1;196 211-/** The round a settle names for `proposal`, never below the first. */197 const settledRound = (proposal: Proposal, round: Round) =>198 Math.max(1, roundOf(proposal) + offset(round));199 215-/** Whether a settle of `round` is the proposal's current, unsettled round, while it is open. */200 const isCurrent = (proposal: Proposal, round: number) =>201 proposal.state === "open" &&202 proposal.draft !== undefined &&203 DraftState.guards.Drafting(proposal.draft) &&3 unmodified lines207 decision.evidence.flatMap(({ label }) =>208 notFiles.has(label) ? [] : [label]209 );210 227-/** The files each proposal held when a round of it last settled ready. */211 type ReadyFiles = ReadonlyMap<ProposalId, readonly RepoPath[]>;212 230-/** `ready`, with the files of every proposal that reads `Ready` in `snapshot`. */213 const readyIn = (ready: ReadyFiles, snapshot: ProjectSnapshot): ReadyFiles =>214 new Map([215 ...ready,216 ...snapshot.proposals.flatMap((proposal) =>2 unmodified lines219 : []220 ),221 ]);222 241-/**242- * What a step broke. No decision exists while a proposal drafts its first243- * round; a settle of a stale round, or of a closed proposal, changes244- * nothing; an open `Ready` proposal's files are exactly the files its245- * decision's evidence holds, beside its red first; and a `Failed` one keeps246- * the files of its last ready round (none if it never had one), which its247- * decision holds, with its red first when there are any, and says why.248- */223 const brokenBy = (224 move: Move,225 before: ProjectSnapshot,226 after: ProjectSnapshot,67 unmodified lines294 ];295 296 const stored = ProjectStore.use((store) => store.load());297 324-/** The drafted files composed onto main as it now stands, scripted red there. */298 const redOnMain = Effect.gen(function* () {299 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);300 301 const tip = LandedSha.make(6 unmodified lines308 checker.script(composed, redThenGreen, ["failed", "failed"])309 );310 });311 339-/** One move, as a person or the platform makes it; a refusal is part of the history. */312 const step = (api: ProjectApi, before: ProjectSnapshot, move: Move) => {313 const proposalAt = (which: number) =>314 Option.fromUndefinedOr(before.proposals[which]);315 48 unmodified lines364 }),365 });366 };367 396-/** Runs a history over a fresh project; returns its first bad step and what it broke. */368 const firstBreak = (history: readonly Move[]) =>369 Effect.gen(function* () {370 yield* advanceTo("2026-10-08T12:00:00Z");371 25 unmodified lines397 398 return [];399 }).pipe(Effect.provide(worldOf(scenario, "memory")));400 430-/**431- * Each history runs the project service over the memory world, a project432- * made fresh: a few hundred milliseconds on an idle machine, more while433- * turbo runs every package's tests at once. The limit catches a hang.434- */401+/** Catches a hang, not a busy machine. */402 const generated = { timeout: 120_000 };403 404 describe("drafting, over generated histories", generated, () => {405 it.effect.prop(9 unmodified linesmodified:packages/project/test/evidence.test.ts-17 removed
1-/**2- * Who may read a failing lane's log (`ProjectApi.evidence`): the claimant of3- * the answer the log's name points at, and the project's deciders. Anyone4- * else hears `NotDecider` whatever the name, and a name that points at5- * another project is `UnknownProject`, so no reply tells which logs exist.6- */1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost } from "@repo/artifacts/repo-host";3 import { EvidenceStore, LogRef, logRefOf } from "@repo/checks/evidence-store";4 import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";29 unmodified lines34 35 const person = (name: string) =>36 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });37 44-/** The project's decider. */38 const alice = person("alice");39 47-/** The claimant whose answer failed its `unit` lane. */40 const bob = person("bob");41 50-/** Neither: vouched for, but no claimant of that answer and no decider. */42 const carol = person("carol");43 44 const parseIso = AskId.make("parse-iso");45 10 unmodified lines56 ],57 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],58 ];59 69-/** The ask's own files: its file in the config folder, and its check. */60 const askFiles = () => {61 const ask = Option.getOrThrow(62 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)63 );16 unmodified lines80 }81 );82 };83 94-/** The log bob's `unit` lane left on his answer's first merge. */84 const failing = [85 "FAIL packages/parser/test/parse.test.ts > parses ISO weeks",86 "AssertionError: expected 52 to be 53",87 ].join("\n");88 100-/** The name the log is kept under. */89 const bobsLog = logRefOf({ attempt: 1, lane: unit, project, requestId });90 91 const mainTip = Effect.gen(function* () {92 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);2 unmodified lines95 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))96 );97 });98 111-/**112- * alice makes the project and opens parse-iso; bob claims it and answers113- * under `requestId`; the answer's `unit` lane left `text` under its name.114- */99 const answered = (text: string = failing) =>100 Effect.gen(function* () {101 yield* advanceTo("2026-10-07T12:00:00Z");102 83 unmodified lines186 [187 api.evidence(carol, bobsLog),188 api.evidence(carol, never),189 api.evidence(Anonymous.make({}), bobsLog),206- // bob is the claimant of his own answer only.190 api.evidence(bob, never),191 ],192 Effect.flip193 )119 unmodified linesmodified:packages/project/test/facts.test.ts-27 removed
1-/**2- * The rules' facts at a commit, as the platform reads them through3- * `RepoHost`: the files handed to the judge closure are what `@repo/checks`'4- * `judgeInputs` gathers, the same function the CLI's local check and hook5- * gather through, so the closure the gateway judges a push by is the one6- * every file of the tree gives (one home for the policy facts).7- */1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost } from "@repo/artifacts/repo-host";3 import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";28 unmodified lines33 const project = ProjectName.make("alice/kit");34 35 const repo = RepoName.make(keyOf(project));36 44-/**45- * A tree whose judge reaches past the root and the CI folders: lefthook46- * runs `scripts/pre-commit.sh`, which runs a hook script with a helper;47- * Claude Code's settings run `scripts/hooks/shell-policy.ts`; a package's48- * tsconfig extends the root base and a file of its own; oxlint loads a49- * plugin that imports a helper; a test outside the plugin's folder names50- * it; and product code nothing reaches.51- */37 const tree: Files = [38 ["package.json", JSON.stringify({ name: "kit", workspaces: ["packages/*"] })],39 [40 "lefthook.yml",45 unmodified lines86 ];87 88 const run: RunBlock = { checks: {}, test: Command.make("bun test {path}") };89 105-/** `tree` committed and pushed to the project's repo, as its first commit. */90 const pushed = Effect.gen(function* () {91 const host = yield* RepoHost;92 const client = yield* gitClient(memoryFs());93 75 unmodified lines169 })170 );171 });172 189-// ------------------------------------------------------------ through the gate190-173 const scenario = aProject({ people: ["bob"] }).pipe(174 withVouches(["bob"]),175 withAsk({ id: "parse-iso", territory: "packages/parser" })176 );17 unmodified lines194 const ask = Option.getOrThrow(195 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)196 );197 216-/** The ask's own files: its file in the config folder, and its check. */198 const askFiles = Array.make(199 { content: `export default "${parseIso}";\n`, path: ask.file },200 {201 content: 'import { it } from "vitest";\n\nit("parses a year", () => {});\n',2 unmodified lines204 : RepoPath.make("test/parse-iso.test.ts"),205 }206 );207 227-/**228- * A project whose harness hook config sits in a subfolder, not at the root229- * or in a CI folder, and runs a script outside both.230- */208 const hooked: Files = [209 [210 "package.json",211 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',16 unmodified lines228 ],229 ["scripts/hooks/shell-policy.ts", "export {};\n"],230 ];231 255-/**256- * alice makes the project and opens parse-iso red first; bob claims it and257- * pushes an edit to the script the hook config runs. What the gate says.258- */232 const hookScriptPushed = Effect.gen(function* () {233 yield* advanceTo("2026-10-07T12:00:00Z");234 235 const api = yield* projectService(scenario.project);62 unmodified linesmodified:packages/project/test/generated.test.ts-13 removed
23 unmodified lines24 const parent = LandedSha.make("1".repeat(40));25 26 const landed = LandedSha.make("2".repeat(40));27 28-/** The policy before the landing: lint and types. */28 const before: Policy = { ...scenario.policy, at: parent };29 31-/** The same policy at the landing, read again there: nothing it says changed. */30 const unchanged: Policy = { ...scenario.policy, at: landed };31 34-/** The policy at the landing, with a unit lane added to the run block. */32 const withUnit: Policy = {33 ...unchanged,34 run: Schema.decodeSync(RunBlock)({35 checks: {8 unmodified lines44 const skill = `.agents/skills/${project}-contribute/SKILL.md`;45 46 const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;47 51-/**52- * A generator as `@repo/agent-kit` is one, in miniature: the skill, twice,53- * naming the landing and the run block's lanes, and AGENTS.md with only the54- * text between its markers written over (appended when there are none).55- */48 const generate: Generate = ({ landed: at, policy, read }) =>49 Effect.gen(function* () {50 const lanes = Object.entries(policy.run.checks)51 .map(([lane, command]) => `${lane}: ${command}`)16 unmodified lines68 { content: agents, path: "AGENTS.md" },69 ];70 });71 80-/** The project's own AGENTS.md, with a block the platform wrote before. */72 const ownAgents = [73 "# Datekit",74 "",75 "Our notes.",5 unmodified lines81 "More notes.",82 "",83 ].join("\n");84 94-/** A tree that holds `files` and nothing else. */85 const treeOf =86 (files: Readonly<Record<string, string>>) =>87 (path: string): Effect.Effect<Option.Option<string>> =>88 Effect.succeed(Option.fromUndefinedOr(files[path]));89 90 const at = DateTime.makeUnsafe("2026-10-07T12:00:00Z");91 102-/** alice's own landing from her working fork, which changed the config. */92 const aliceLands: LandingView = {93 assisted: [],94 author: alice,95 credits: [{ handle: alice, role: "Signed-off-by" }],2 unmodified lines98 project,99 sha: landed,100 };101 113-/** The first adoption: the initializer's first push, crediting no one. */102 const firstPush: LandingView = {103 assisted: [],104 author: alice,105 credits: [],21 unmodified lines127 );128 129 const subjectOf = (message: string) => message.split("\n")[0] ?? "";130 143-/** Whom the follow-up of `landing`, after the run block changed, credits. */131 const creditOf = (landing: LandingView) =>132 Effect.map(133 followUp({ after: withUnit, before: Option.some(before), landing }),134 Option.map(({ credits }) => credits)176 unmodified linesmodified:packages/project/test/import.test.ts+1 added-22 removed
1-/**2- * A project adopted from a public repo, whatever its default branch, and3- * adopted again by a retry when the first import died after Artifacts made4- * the repo; and each adoption, an import's or a first push's, heard once5- * as a landing.6- */1 import { describe, expect, it } from "@effect/vitest";2 import { RefName, RepoHost } from "@repo/artifacts/repo-host";3 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4 import { ProjectEvent } from "@repo/protocol/domain/event";20 unmodified lines25 const bob = Person.make({ handle: Handle.make("bob") });26 27 const mainRef = RefName.make("refs/heads/main");28 35-/**36- * The project's row as an import written before sources were kept left it37- * (ADR 0031): the same row without `importedFrom`.38- */29 const forgetSource = ProjectStore.use((store) =>30 Effect.flatMap(store.load(), ({ project: row }) =>31 Option.match(row, {32 onNone: () => Effect.void,4 unmodified lines37 );38 39 const masterRef = RefName.make("refs/heads/master");40 51-/**52- * A public remote `upstream` whose only branch is `master`, as anyhow's53- * and stb's are; the world reads `https://example.com/upstream.git` as it.54- */41 const upstreamOnMaster = Effect.gen(function* () {42 const host = yield* RepoHost;43 const upstream = RepoName.make("upstream");44 const client = yield* gitClient(memoryFs());12 unmodified lines57 58 return { tip, url: "https://example.com/upstream.git" };59 });60 75-/** What the project holds after its imports: its head, its row, and its repo's refs. */61 const settled = Effect.gen(function* () {62 const api = yield* projectService(project);63 const snapshot = yield* ProjectStore.use((store) => store.load());64 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);4 unmodified lines69 state: Option.map(snapshot.project, (row) => row.state),70 };71 });72 88-/**89- * The world's `RepoHost`, standing in for the binding past its wait: until90- * the import is copied, a read of the imported repo dies as the binding's91- * does when Artifacts still answers `IMPORT_IN_PROGRESS` (the binding's92- * own half is `packages/artifacts/test/binding.test.ts`). The first read93- * after an import dies; every later one works.94- */73+/** Reads of the imported repo die once, as the binding does while Artifacts answers `IMPORT_IN_PROGRESS`. */74 const stillCopying = Effect.gen(function* () {75 const host = yield* RepoHost;76 const copying = yield* Ref.make(false);77 242 unmodified linesmodified:packages/project/test/lander-isogit.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/landing.model.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/migrate.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/movers.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/no-visibility.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/project-store-sqlite.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/project-store.contract.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/project.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/projection-d1-credits.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/projection-d1.fixtures.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/projection-d1.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/projection-memory.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/ratchets.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/rehearse.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/standing-posture.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/visibility-ports.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/world.tsnot shown
Its text is not shown, modified.