Skip to content
Myr

Merge build/comments-project into main

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

authored by oscabriel · committed by oscabriel · parents ddf09e8, e78d3c5 · Browse files · 125 files+214 added−4346 removed
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

125 files+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 */1import { Context, Effect, Layer, Option, Ref } from "effect";2import type { DateTime } from "effect";34import { Alarms } from "../alarms.ts";512/** When the memory alarm is set to go off, if it is set. */6export class ScheduledAlarm extends Context.Service<7 ScheduledAlarm,8 { readonly at: Effect.Effect<Option.Option<DateTime.Utc>> }9>()("project/ScheduledAlarm") {}1018/** A fresh alarm each time the layer is built, and the reading of it. */11export 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 lines
modified: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 */1import type { RepoHost } from "@repo/artifacts/repo-host";2import type { CheckRunner } from "@repo/checks/check-runner";3import type { RequestId } from "@repo/protocol/ids";4import { Effect, Layer, Ref } from "effect";
46 unmodified lines
modified: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 */1import { RepoHost, Revision } from "@repo/artifacts/repo-host";2import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";3import type { LandingView } from "@repo/protocol/domain/landing";4import type {
7 unmodified lines
1213import { asOneView } from "../code/cache.ts";14import { entryAt, READS_AT_ONCE } from "../code/tree.ts";1526/** The most first-parent commits back from main a walk reads. */16export const MOVER_SCAN = 50;1729/** The landings among `shas`, as the project's record holds them. */18export type LandingsOf = (19 shas: readonly CommitSha[]20) => Effect.Effect<readonly LandingView[]>;2134/** What a merge conflicted in: the repo, the answer's base, main, and the paths. */22export interface Conflicted {23 readonly repo: RepoName;24 readonly base: CommitSha;25 readonly main: LandedSha;26 readonly conflicts: readonly RepoPath[];27}2842/** What sits at `path` in `commit`: its mode and id, or nothing. */29const 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 );3651/**52 * The newest of the first `since` commits of `scan` that changed `path`53 * from the commit after it, its first parent.54 */37const moverOf = (38 repo: RepoName,39 scan: readonly Commit[],40 since: number,
12 unmodified lines
53 : Option.some(commit.sha)54 )55 );5675/** Each conflicting path's newest change since the base, where one is found. */57const moversOf = (input: Conflicted) =>58 asOneView(59 Effect.gen(function* () {60 const scan = yield* RepoHost.use((host) =>
19 unmodified lines
80 return Array.getSomes(found);81 })82 );83103/** A path's mover as the refusal names it, from its landing. */84const movedByOf = (path: RepoPath, landing: LandingView): MovedBy => {85 const ask = landing.ask ?? landing.opened;8687 return ask === undefined88 ? { author: landing.author, landing: landing.sha, path }89 : { ask, author: landing.author, landing: landing.sha, path };90};91112/**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 */92export const movedBy = (93 input: Conflicted,94 landings: LandingsOf95): Effect.Effect<readonly MovedBy[], never, RepoHost> =>
37 unmodified lines
modified: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 */1import type { RepoHost } from "@repo/artifacts/repo-host";2import { CheckAt, CheckRunner } from "@repo/checks/check-runner";3import type { CheckLane, CheckRun } from "@repo/checks/check-runner";4import { classifyFailure } from "@repo/gate/classify";
15 unmodified lines
20} from "../landing.ts";21import { movedBy } from "./movers.ts";22import type { LandingsOf } from "./movers.ts";2334/** A step's result: the command it reports, and what it saw beside it. */24export interface Reported {25 readonly command: LandingCommand;26 readonly report?: AnswerReport;27}2840/** Whether an effect is a port call a run makes, rather than the project's to settle. */29export const isStep = (effect: LandingEffect) =>30 LandingEffect.$is("Merge")(effect) ||31 LandingEffect.$is("RunChecks")(effect) ||32 LandingEffect.$is("Land")(effect);3346/**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. */35export const nextSteps = (run: AnswerRun): readonly LandingEffect[] =>36 LandingState.guards.Landing(run.state) && !run.admitted37 ? []38 : pendingEffects(run.state);3955/** The attempt a port's `Busy` or `Blocked` report is about: the state's own. */40const attemptOf = (state: LandingState) =>41 LandingState.matchOrElse(42 state,43 {
6 unmodified lines
5051const reported = (command: LandingCommand, report?: AnswerReport): Reported =>52 report === undefined ? { command } : { command, report };5370/**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 */54const merge = (55 run: AnswerRun,56 step: Extract<LandingEffect, { readonly _tag: "Merge" }>,57 landings: LandingsOf
34 unmodified lines
92 ),93 })94 );95116/** Each lane's result in a run, by lane. */96const resultsOf = (run: CheckRun): ReadonlyMap<LaneName, LaneResult> =>97 new Map(run.lanes.map((lane) => [lane.lane, lane]));9899const isTrouble = (result: LaneOutcome) =>100 result === "flaked" || result === "blocked";101123/** Where a lane's log is kept when its run named no place: by request and lane. */102const logRefOf = (requestId: RequestId, lane: LaneName) =>103 `${requestId}/${lane}`;104127/**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. */106const checks = (107 run: AnswerRun,108 checking: Extract<LandingState, { readonly _tag: "Checking" }>109): Effect.Effect<Reported, VerifierBlocked, CheckRunner> =>
2 unmodified lines
112 const { request } = checking;113114 const block = yield* runBlockOf(run);115144 // 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 lines
192 { heldBack: merged.heldBack, lanes }193 );194 });195227/**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 */196const land = (197 run: AnswerRun,198 landing: Extract<LandingState, { readonly _tag: "Landing" }>,199 message: string
40 unmodified lines
240 ),241 })242 );243280/**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 */244export const runStep = (245 run: AnswerRun,246 effect: LandingEffect,247 landings: LandingsOf
25 unmodified lines
273 )274 : Effect.succeedNone,275 });276319/**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 */277export const drive = (278 queue: AnswerQueue,279 requestId: RequestId280): Effect.Effect<void, never, CheckRunner | Lander | RepoHost> => {
38 unmodified lines
modified: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 */1import type { Today } from "@repo/protocol/domain/decision";2import type { Policy } from "@repo/protocol/domain/policy";3import { sameHandle } from "@repo/protocol/ids";4import type { Handle } from "@repo/protocol/ids";5import { DateTime } from "effect";67import type { BudgetDayRow } from "../project-store/rows.ts";815/**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 */9export type Budget = Today["budget"];1021/** The day a moment falls on, as `BudgetDayRow.day` keys it: `2026-10-07`, in UTC. */11const dayOf = (now: DateTime.Utc) => DateTime.formatIsoDateUtc(now);1213const rowFor = (14 days: readonly BudgetDayRow[],
11 unmodified lines
26 }27 );28};2941/** What `decider` has spent of today's budget, out of the policy's `decisionsPerDay`. */30export const budgetFor = (31 policy: Policy,32 decider: Handle,33 days: readonly BudgetDayRow[],
3 unmodified lines
3738 return { finishes, total: policy.budget.decisionsPerDay, used };39};4053/**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 */41export const spend = (42 days: readonly BudgetDayRow[],43 input: {44 readonly decider: Handle;
10 unmodified lines
modified: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 */1import type { Ask } from "@repo/protocol/domain/ask";2import type { LandingView } from "@repo/protocol/domain/landing";3import type { CreditSummary } from "@repo/protocol/domain/record";4import { sameHandle } from "@repo/protocol/ids";
1 unmodified line
6import { Array as Arr, Option, Order } from "effect";78import { areaOf } from "./record.ts";920/** What a person's credits are counted from. */10export 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}1617const byText = (field: (row: CreditSummary) => string) =>18 Order.mapInput(Order.String, field);1937/**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 */21const bySummary = Order.combineAll([22 byText(({ project }) => project),23 byText(({ area }) => area),24 byText(({ role }) => role),25]);2647/**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 */27export const creditsByArea = (28 input: CreditsInput29): readonly CreditSummary[] => {30 const rows = new Map<string, CreditSummary>();
29 unmodified lines
modified: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 */1import { matchGlob } from "@repo/gate/glob";2import type { Evidence } from "@repo/protocol/domain/common";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import type { Choice, Decision } from "@repo/protocol/domain/decision";
14 unmodified lines
1920import { ProjectEventInput } from "../events.ts";21import { AttentionEffect, platformHandle } from "./effects.ts";2229/** How a subject's deciders say yes, and no. */23interface Words {24 readonly no: Choice;25 readonly yes: Choice;26}2728const acceptOrDecline: Words = { no: "decline", yes: "accept" };2937/**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 */30const wordsFor = DecisionSubject.match({31 Finish: () => acceptOrDecline,32 OpenProposal: () => acceptOrDecline,33 PostureChange: () => acceptOrDecline,
4 unmodified lines
38 Vouch: () => acceptOrDecline,39 Waiver: () => acceptOrDecline,40});4154/** Whether a choice says yes, in any subject's words. */42const saysYes = {43 accept: true,44 adopt: true,45 decline: false,46 revert: false,47} as const satisfies Record<Choice, boolean>;4862/**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 */49export const defaultChoice = (subject: DecisionSubject): Choice =>50 wordsFor(subject).no;5170/** `choice` as `subject`'s deciders say it: `accept` on a stray push adopts it. */52const inWords = (subject: DecisionSubject, choice: Choice): Choice => {53 const words = wordsFor(subject);5455 return saysYes[choice] ? words.yes : words.no;56};5777/**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 */58const consequences = (59 subject: DecisionSubject,60 choice: Choice61): readonly AttentionEffect[] => {
7 unmodified lines
69 ? [AttentionEffect.OpenAsk({ proposal: subject.proposal })]70 : [AttentionEffect.Land({ subject })];71};7297/** A decision taken: the decision as it now stands, and what follows from it. */73export interface Decided {74 readonly decision: Decision;75 readonly effects: readonly AttentionEffect[];76}77103/** Takes `decision` with `choice`, by `by`, at `now`. */78const take = (79 decision: Decision,80 by: Handle,81 choice: Choice,
21 unmodified lines
103 ],104 };105};106133/** Whether nobody may decide `decision` any more: it was taken, or it reached its expiry. */107const isClosed = (decision: Decision, now: DateTime.Utc) =>108 decision.decided !== undefined ||109 DateTime.isGreaterThanOrEqualTo(now, decision.expiresAt);110138/**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 */111export const openDecision = (input: {112 readonly id: DecisionId;113 readonly project: ProjectName;114 readonly subject: DecisionSubject;
11 unmodified lines
126 project: input.project,127 subject: input.subject,128});129162/**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.132export const decide = (133 decisions: readonly Decision[],134 input: {135 readonly id: DecisionId;
21 unmodified lines
157 take(found, input.by, input.choice, input.now, input.note)158 );159};160199/** A project's decisions after an alarm, and what follows from the ones that expired. */161export interface ExpiredDecisions {162 readonly decisions: readonly Decision[];163 readonly effects: readonly AttentionEffect[];164}165205/**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 */166export const expireDecisions = (167 decisions: readonly Decision[],168 now: DateTime.Utc169): ExpiredDecisions => {
8 unmodified lines
178 effects: steps.flatMap(({ effects }) => effects),179 };180};181225/**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 */182export const decidersFor = (183 policy: Policy,184 paths: readonly RepoPath[]185): readonly Handle[] => {
11 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import type { RefNameText } from "@repo/protocol/domain/common";3import type { DecisionSubject } from "@repo/protocol/domain/decision";4import { Handle } from "@repo/protocol/ids";
2 unmodified lines
7import type { DateTime } from "effect";89import type { ProjectEventInput } from "../events.ts";1017/** What the project service does after a proposal or decision moved, in order. */11export 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}>;1830/** Constructors for attention's effects. */19export const AttentionEffect = Data.taggedEnum<AttentionEffect>();2033/**34 * The platform's own handle: who `decided.by` names when nobody decided in35 * time and a decision took its default.36 */21export 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 */1import { Brand } from "@repo/brand";2import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";3import type { Evidence } from "@repo/protocol/domain/common";4import { DecisionSubject } from "@repo/protocol/domain/decision";
12 unmodified lines
1718import { decidersFor, openDecision } from "./decisions.ts";19import { platformHandle } from "./effects.ts";2035/**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 */21export 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 line
27 readonly note: Option.Option<string>;28 readonly paths: readonly RepoPath[];29}3052/** A promotion: the proposal for a `lintToZero` ask, and the decision that puts it to its deciders. */31export interface Promotion {32 readonly decision: Decision;33 readonly proposal: Proposal;34}3558/** What `promotions` reads. */36export 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 line
44 readonly policy: Policy;45 readonly project: ProjectName;46}4773/** The evidence labels a promotion is found again by. */48const labels = {49 area: "area",50 finished: "finished",51 promotedFrom: "promoted from",
1 unmodified line
53 want: "want",54 why: "why",55} as const;5683/**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 */57const ruleId = /^@?[a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)*$/u;5889/** Words joined as a rule's id joins them, by a dash or a slash. */59const joined = /[-/]/u;6092/** A backticked span in a note: `` `no-date-equality` ``. */61const backticked = /`(?<span>[^`]+)`/gu;6295/**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 */63const asRule = (text: string): Option.Option<string> =>64 Option.liftPredicate(65 text.trim(),66 (word) => ruleId.test(word) && joined.test(word)67 );68107/**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 */69const ruleInNote = (note: string): Option.Option<string> =>70 Option.orElse(asRule(note), () =>71 Arr.findFirst([...note.matchAll(backticked)], ({ groups }) =>72 asRule(groups?.span ?? "")73 )74 );75119/** Why a finish was made: the rule its lanes name, else the rule its note names. */76const reasonOf = (finish: FinishRecord): Option.Option<string> =>77 Option.orElse(78 Option.filter(79 Option.map(finish.rule, (rule) => rule.trim()),
1 unmodified line
81 ),82 () => Option.flatMap(finish.note, ruleInNote)83 );84129/** A finish with the rule it was made for. */85interface Reasoned {86 readonly finish: FinishRecord;87 readonly rule: string;88}89135/** Finishes in one area for one rule, oldest first. */90interface Group {91 readonly area: string;92 readonly finishes: Arr.NonEmptyReadonlyArray<FinishRecord>;93 readonly rule: string;
8 unmodified lines
102 Order.mapInput(Order.String, ({ area }: Group) => area),103 Order.mapInput(Order.String, ({ rule }: Group) => rule)104);105152/** Finishes grouped by (area, rule), each group oldest first, groups by area then rule. */106const groupsOf = (finishes: readonly Reasoned[]): readonly Group[] =>107 Arr.sort(108 Object.values(109 Arr.groupBy(finishes, ({ finish, rule }) =>
14 unmodified lines
124 Arr.findFirst(decision.evidence, (each) => each.label === label).pipe(125 Option.map(({ value }) => value)126 );127175/** The promotions decided or open for `group`'s area and rule. */128const promotedFor = (existing: readonly Decision[], group: Group) =>129 existing.filter(130 (decision) =>131 DecisionSubject.guards.OpenProposal(decision.subject) &&
1 unmodified line
133 Option.contains(valueOf(decision, labels.area), group.area) &&134 Option.contains(valueOf(decision, labels.rule), group.rule)135 );136185/** The finishes a promotion was made from: the key its evidence carries. */137const finishesNamed = (decision: Decision): readonly string[] =>138 Option.match(valueOf(decision, labels.promotedFrom), {139 onNone: () => [],140 onSome: (value) => value.split(" "),
2 unmodified lines
143const isOpen = (decision: Decision, now: DateTime.Utc) =>144 decision.decided === undefined &&145 DateTime.isLessThan(now, decision.expiresAt);146196/**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 */147const freshOf = (148 existing: readonly Decision[],149 group: Group,150 now: DateTime.Utc
11 unmodified lines
162 (one, other) => one.ask === other.ask163 );164};165221/** Whether an ask not yet closed already holds `rule` to zero. */166const alreadyAsked = (policy: Policy, rule: string) =>167 policy.asks.some(168 ({ check, state }) =>169 state !== "closed" &&170 CheckSpec.guards.LintToZero(check) &&171 check.rule === rule172 );173230/**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 */174const lintCommandOf = (policy: Policy, rule: string): Option.Option<string> => {175 const counted = policy.ratchets.flatMap(({ measure }) =>176 RatchetMeasure.guards.Count(measure) ? [measure] : []177 );
10 unmodified lines
188 )189 );190};191253/** The project's kind for `lintToZero` asks: the first of that check kind it lists. */192const lintKindOf = (policy: Policy): Option.Option<AskKind> =>193 Arr.findFirst(policy.kinds, ({ checkKind }) => checkKind === "lintToZero");194257/** Where the ask may change things: a module by its name, or folders as globs. */195type Place =196 | { readonly module: string }197 | { readonly globs: Arr.NonEmptyReadonlyArray<string> };198199const folderOf = (path: string) => path.split("/").slice(0, -1).join("/");200264/** Whether `folder` sits under `other`. */201const isUnder = (folder: string, other: string) =>202 folder !== other && folder.startsWith(`${other}/`);203268/**269 * The folders `paths` sit in, as globs, each under no other: `src/date/**`;270 * `**` when a file sits at the root.271 */204const foldersOf = (paths: readonly RepoPath[]): readonly string[] => {205 const folders = Arr.dedupe(paths.map(folderOf));206207 if (folders.includes("")) {
7 unmodified lines
215 Order.String216 ).map((folder) => `${folder}/**`);217};218287/**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 */219const placeOf = (220 policy: Policy,221 area: string,222 finishes: readonly FinishRecord[]
11 unmodified lines
234235const describePlace = (place: Place) =>236 "module" in place ? place.module : place.globs.join(", ");237310/** `no-date-equality` in `src/date` → `no-date-equality-in-src-date`. */238const slug = (text: string) =>239 text240 .toLowerCase()241 .replaceAll(/[^a-z0-9]+/gu, "-")242 .replaceAll(/^-+|-+$/gu, "");243317/** The new ask's id: the rule, and the area unless it is the whole repo. */244const askIdOf = (rule: string, area: string): Option.Option<AskId> =>245 Schema.decodeOption(AskId)(246 area === "." || slug(area) === ""247 ? slug(rule)
1 unmodified line
249 );250251const quoted = (text: string) => JSON.stringify(text);252327/** A list of names as a sentence says it: `alice`, `alice and bob`, `alice, bob and carol`. */253const spoken = (names: Arr.NonEmptyReadonlyArray<string>) => {254 const last = Arr.lastNonEmpty(names);255 const rest = Arr.initNonEmpty(names);256257 return rest.length === 0 ? last : `${rest.join(", ")} and ${last}`;258};259335/** What the ask file's territory field says. */260const territoryCall = (place: Place) =>261 "module" in place262 ? `territory.package(${quoted(place.module)})`263 : `territory.paths(${place.globs.map(quoted).join(", ")})`;264341/**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 */265const askFileOf = (input: {266 readonly command: string;267 readonly from: readonly FinishRecord[];268 readonly kind: AskKind;
41 unmodified lines
310 "",311 ].join("\n");312};313396/** One finish as its decision shows it: `compare-days by alice on 2026-10-01: <note>`. */314const finishLine = (finish: FinishRecord) => {315 const line = `${finish.ask} by ${finish.decider} on ${DateTime.formatIsoDateUtc(finish.at)}`;316317 return Option.match(finish.note, {
1 unmodified line
319 onSome: (note) => `${line}: ${note.trim()}`,320 });321};322406/** `group`'s promotion, when it is due and the project can hold its ask. */323const promotionOf = (324 input: PromotionInput,325 group: Group326): Option.Option<Promotion> => {
17 unmodified lines
344 );345346 const touched = fresh.flatMap(({ paths }) => paths);347432 // 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 lines
412 return { decision, proposal };413 });414};415501/**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. */417export const promotions = (input: PromotionInput): readonly Promotion[] => {418 const since = DateTime.subtract(input.now, {419 days: input.policy.record.windowDays,420 });
15 unmodified lines
modified: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 */1import type { Evidence } from "@repo/protocol/domain/common";2import type { Policy } from "@repo/protocol/domain/policy";3import { DraftState } from "@repo/protocol/domain/proposal";4import type { Proposal } from "@repo/protocol/domain/proposal";
20 unmodified lines
25import { DRAFT_ROUNDS, DraftResult } from "../draft-runs.ts";26import { ProjectEventInput } from "../events.ts";27import { AttentionEffect } from "./effects.ts";2840/**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 */29interface 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}3655/** A sealed answer: a commit in the proposer's fork, judged once the ask opens. */37interface Sealed {38 readonly fork: RepoName;39 readonly head: CommitSha;40}4161/**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 */42export 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 line
50 readonly want: string;51 };52}>;5381/** Constructors for proposal commands. */54export const ProposalCommand = Data.taggedEnum<ProposalCommand>();5584/**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 */56export type DraftCommand = Data.TaggedEnum<{57 DraftSettled: { readonly result: DraftResult; readonly round: number };58 DraftStarted: { readonly by: Handle; readonly note?: string };59}>;6095/** Constructors for draft commands. */61export const DraftCommand = Data.taggedEnum<DraftCommand>();6263type Propose = Data.TaggedEnum.Value<ProposalCommand, "Propose">;64100/** A proposal opened: the proposal and what the service does next. */65export interface Proposed {66 readonly effects: readonly AttentionEffect[];67 readonly proposal: Proposal;68}69106/**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 */70const lacksVouch = (policy: Policy, { sealed, vouched }: Propose) => {71 const { mode } = policy.vouch;7273 return (
1 unmodified line
75 (mode === "all" || (mode === "forCode" && Option.isSome(sealed)))76 );77};78121/**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 */79const admit = (80 policy: Policy,81 { denounced, openCount }: Proposer,82 unvouched: boolean
12 unmodified lines
95 ? Result.fail(new CapReached({ cap, limit: "proposals" }))96 : Result.void;97};98146/** The fields every proposal opens with, expiring after the policy's days. */99const 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 line
104 proposer: proposer.who.handle,105 state: "open" as const,106});107156/**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 */108const proposalFor = (109 policy: Policy,110 command: Propose,111 now: DateTime.Utc
19 unmodified lines
131 onSome: (sealed) => ({ ...territory, sealed }),132 });133};134190/** The proposal opened, with an alarm at its expiry and an event for watchers. */135const opened = (proposal: Proposal, now: DateTime.Utc): Proposed => ({136 effects: [137 AttentionEffect.SetAlarm({ at: proposal.expiresAt }),138 AttentionEffect.Emit({
5 unmodified lines
144 ],145 proposal,146});147204/**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 */148export const propose = (149 policy: Policy,150 command: ProposalCommand,151 now: DateTime.Utc
16 unmodified lines
168 opened(proposalFor(policy, proposing, now), now)169 ),170 });171233/** A project's proposals after an alarm, and what follows from the ones that expired. */172export interface ExpiredProposals {173 readonly effects: readonly AttentionEffect[];174 readonly proposals: readonly Proposal[];175}176239/**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.179export const expire = (180 proposals: readonly Proposal[],181 now: DateTime.Utc182): ExpiredProposals => ({
5 unmodified lines
188 : proposal189 ),190});191261/**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 */192export interface Drafted {193 readonly effects: readonly AttentionEffect[];194 readonly lines: readonly Evidence[];195 readonly proposal: Proposal;196}197272/** The round a proposal's next draft takes: one after its last, or the first. */198const nextRound = (proposal: Proposal) =>199 proposal.draft === undefined ? 1 : proposal.draft.round + 1;200276/**277 * A round that started drafting and has not settled: the proposal's278 * current one, still open.279 */201const drafting = (proposal: Proposal, round: number) =>202 proposal.state === "open" &&203 proposal.draft !== undefined &&204 DraftState.guards.Drafting(proposal.draft) &&205 proposal.draft.round === round;206286/** The evidence line that says why a proposal's last draft round failed. */207export const draftFailedLabel = "draft failed";208289/** What a settled round's decision says beside the want: red first and who drafted, or why it failed. */209const 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 lines
220 { label: "why this test", value: rationale },221 ],222 });223305/**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.226const settledProposal = (227 proposal: Proposal,228 round: number,229 result: DraftResult
20 unmodified lines
250 files: files.map(({ path }) => path),251 }),252 });253339/**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 */254export const draft = (255 proposal: Proposal,256 command: DraftCommand,257 now: DateTime.Utc
56 unmodified lines
modified: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 */1import type { Ask } from "@repo/protocol/domain/ask";2import type { LandingView } from "@repo/protocol/domain/landing";3import type { Policy } from "@repo/protocol/domain/policy";4import type { AskId, Handle, LandedSha, ProjectName } from "@repo/protocol/ids";5import { Array as Arr, DateTime, Option } from "effect";619/** One landing that counts on its accountable person's record, in its area. */7export 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}1430/** What a record is built from. */15export 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}2346/** A record rule: at least `atLeast` counted landings in `area`. */24export interface RecordRule {25 readonly area: string;26 readonly atLeast: number;27}2852/** A handle as a map key: the form `sameHandle` (`@repo/protocol/ids`) compares by. */29const personOf = (handle: Handle) => handle.toLowerCase();3055/**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 */31export const areaOf = (32 landing: LandingView,33 asks: ReadonlyMap<AskId, Ask>34): Option.Option<string> =>
2 unmodified lines
37 Option.filter((ask) => ask.project === landing.project),38 Option.map((ask) => ask.territory.module)39 );4070/**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 */41const counts = (42 landedAt: DateTime.Utc,43 now: DateTime.Utc,44 window: Policy["record"]
6 unmodified lines
51 now,52 DateTime.add(landedAt, { days: window.windowDays })53 );5488/**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 */55export const recordOf = (56 input: RecordInput57): ((handle: Handle) => readonly RecordEntry[]) => {58 const entries = Arr.flatMap(input.landings, (landing): RecordEntry[] => {
33 unmodified lines
9293 return (handle) => byPerson.get(personOf(handle)) ?? [];94};95135/**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. */97export const meets = (98 entries: readonly RecordEntry[],99 rule: RecordRule100): boolean =>
1 unmodified line
modified: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 */1import type { CreditRole } from "@repo/protocol/domain/credit";2import type { Decision, Today } from "@repo/protocol/domain/decision";3import type { LandingView } from "@repo/protocol/domain/landing";4import { sameHandle } from "@repo/protocol/ids";
1 unmodified line
6import { Array as Arr, DateTime, Order } from "effect";78import type { Budget } from "./budget.ts";917/** How near its expiry a decision is called out. */10const soon = { hours: 24 } as const;1120/** How recent a first claim makes a newcomer. */12const welcome = { days: 7 } as const;1323/** How many unattended landings Today samples. */14const sampled = 5;1526/** The credit a decider's attention leaves on a landing. */16const attended: ReadonlySet<CreditRole> = new Set([17 "Decided-by",18 "Finished-by",19]);2032/** By expiry, then by opening, then by id: the same order every time. */21const 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]);2639/** Newest first, then by SHA. */27const 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);3347/**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 */34const isUnattended = (landing: LandingView) =>35 landing.ask !== undefined &&36 !landing.credits.some(({ role }) => attended.has(role));3755/**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 */38export const today = (input: {39 readonly decider: Handle;40 readonly decisions: readonly Decision[];41 readonly budget: Budget;
43 unmodified lines
modified: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 */1import type { Ask } from "@repo/protocol/domain/ask";2import type { AskKind, ClaimRule } from "@repo/protocol/domain/kind";3import type { Policy } from "@repo/protocol/domain/policy";4import { sameHandle } from "@repo/protocol/ids";
3 unmodified lines
89import { meets } from "./record.ts";10import type { RecordEntry } from "./record.ts";1126/** Where a person stands with a project: vouched for, denounced, or neither. */12export type Standing = "vouched" | "denounced" | "unknown";1329/** A vouch decision decided since the landed SHA, not yet in the vouch file there. */14export interface DecidedVouch {15 readonly at: DateTime.Utc;16 readonly handle: Handle;17 readonly verdict: "vouch" | "denounce";18}1936/** What `mayClaim` weighs. */20export 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}2849/** Why a person may not claim or propose. */29export type TrustRefusal = Denounced | NotVouched;3052/** Yes, or the refusal that says why not. */31export type TrustAnswer = Result.Result<void, TrustRefusal>;3233const allowed: TrustAnswer = Result.void;3457/** 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.36const byWhen = Order.combine(37 Order.mapInput(DateTime.Order, ({ at }: DecidedVouch) => at),38 Order.mapInput(39 Order.Boolean,40 ({ verdict }: DecidedVouch) => verdict === "denounce"41 )42);4366/** The vouch file's word on a person: a denouncement beats a vouch on another line. */44const fileSays = (policy: Policy, handle: Handle): Option.Option<Standing> => {45 const lines = policy.vouches.filter((line) =>46 sameHandle(line.handle, handle)47 );
6 unmodified lines
54 ? Option.some("vouched")55 : Option.none();56};5781/** Whether the person decides for any paths in the project. */58const isDecider = (policy: Policy, handle: Handle) =>59 policy.deciders.some(({ handles }) =>60 handles.some((each) => sameHandle(each, handle))61 );6287/**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 */63export const standing = (64 policy: Policy,65 decided: readonly DecidedVouch[],66 handle: Handle
18 unmodified lines
85 ),86 });87};88118/**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 */89const mentored = ({ ask, landingsInProject }: ClaimQuestion) =>90 ask.reserve === "newcomers" &&91 ask.mentor !== undefined &&92 landingsInProject === 0;93127/**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 */94const admits = (rule: ClaimRule, question: ClaimQuestion): boolean =>95 Match.value(rule).pipe(96 Match.when("anyone", () => true),97 Match.when(
17 unmodified lines
115 ),116 Match.exhaustive117 );118159/**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.121export const mayClaim = (question: ClaimQuestion): TrustAnswer => {122 if (question.standing === "denounced") {123 return Result.fail(new Denounced({}));124 }
6 unmodified lines
131 ? allowed132 : Result.fail(new NotVouched({}));133};134184/**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 */135export const mayPropose = (policy: Policy, who: Standing): TrustAnswer => {136 if (who === "denounced") {137 return Result.fail(new Denounced({}));138 }
5 unmodified lines
modified: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 */1import { inRepoSession } from "@repo/artifacts/repo-host";2import { Cache, Context, Deferred, Effect, Exit, Layer, Option } from "effect";3import type { Cause, Scope } from "effect";424/** How a read's value is kept. */5export 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}932/** The code reads, each kept by its key once read. */10export 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 lines
20});2122const always = () => true;2351/**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 */24const cacheOf = (capacity: number) =>25 Cache.make<string, unknown>({26 capacity,27 lookup: (key) => Effect.die(`the code cache never looks up ${key}`),28 });2962/**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.32const throughCache =33 (cache: Cache.Cache<string, unknown>) =>34 <A, E, R>(35 key: string,
18 unmodified lines
5455 return value;56 });5795/**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 */58export const CodeCacheLive = (59 capacity: number,60 heavy = Math.max(1, Math.ceil(capacity / 50))61) =>
19 unmodified lines
81 return reads;82 })83 );84128/** What a read under way came to, as the read that joins it: typed as it is. */85const 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 lines
97 // 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 });100145/**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 */101export 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 lines
modified: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 */1import { RepoHost } from "@repo/artifacts/repo-host";2import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";3import { treeDiff } from "@repo/git/tree-diff";4import type { Change } from "@repo/git/tree-diff";
13 unmodified lines
18import { filesUnder, PATHS_CAP } from "./paths.ts";19import { commitAt } from "./revision.ts";20import { entriesOf, entryAt } from "./tree.ts";2144/** The most files a commit's diff carries text for. */22export const DIFF_FILES = 300;2347/** The most text a commit's diff carries in all: 2 MiB. */24export const DIFF_TEXT = 2 * 1024 * 1024;2550/** The kept commit's version, in its key: it moves when what is kept changes. */26/** Bump when what is kept changes. */27export const COMMIT_VERSION = 1;2853/** Where a commit's diff is kept in the code store: by its repo and its id. */29export const commitKey = (repo: RepoName, sha: CommitSha) =>30 `${repo}/commit/v${COMMIT_VERSION}/${sha}`;3157/** How many files' sides are read at once: the fan-out the changes are listed with. */32const SIDES_AT_ONCE = 8;3360/** The longest list of changes the cache keeps. */34const KEPT_CHANGES = 1000;3563/** 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. */37interface Changed extends Change {38 readonly links: { readonly before: boolean; readonly after: boolean };39}4041const isLink = (entry: Option.Option<TreeEntry>) =>42 Option.exists(entry, ({ type }) => type === "commit");4371/** Every file under a root commit's tree, each added. */44const 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 lines
50 status: "added",51 }))52 );5382/**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 */54const changesBetween = (repo: RepoName, base: string, head: string) =>55 Effect.gen(function* () {56 const host = yield* RepoHost;57
34 unmodified lines
92 });9394const byPath = Order.mapInput(Order.String, (change: Changed) => change.path);95128/** A side's contents, unless it is a submodule or absent. */96const 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);102136/** A change as a path, its status and its blob ids, with no text. */103const pathOnly = ({ after, before, path, status }: Changed): ChangedFile => {104 const file = { binary: false, path, status };105106 if (before !== undefined && after !== undefined) {
6 unmodified lines
113114 return after === undefined ? file : { ...file, after };115};116151/** Both sides of `change`: its old contents and its new, where it has them. */117const 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 ]);122158/** The length of a side's text, or 0 when it has none. */123const lengthOf = (text: Option.Option<string>) =>124 Option.match(text, { onNone: () => 0, onSome: ({ length }) => length });125162/**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. */127const 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 lines
185186 return { files, truncated };187 });188229/** A diff as the store keeps it: JSON, by the protocol's own schema. */189const Kept = Schema.fromJsonString(CommitDiff);190191const decodeKept = Schema.decodeUnknownOption(Kept);192193const encodeKept = Schema.encodeEffect(Kept);194236/** `diff` with its commit's landing, asked of the project's record now. */195const withLanding = (196 project: CodeProject,197 diff: CommitDiff198): Effect.Effect<CommitDiff> =>
9 unmodified lines
208 }209 )210 );211254/** The diff kept for `sha` in the code store, if one is and it still decodes. */212const 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 lines
219 ({ commit }) => commit.sha === sha220 );221 });222266/** `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. */224const keepDiff = (repo: RepoName, sha: CommitSha, diff: CommitDiff) =>225 Effect.gen(function* () {226 const store = yield* CodeStore;227
4 unmodified lines
232 )233 );234 });235279/** The diff of `sha` against its first parent, computed, with no landing. */236const computedDiff = (237 repo: RepoName,238 sha: CommitSha239): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>
24 unmodified lines
264 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 lines
276277 return { commit: commitView(commit, Option.none()), files, truncated };278 });279325/** One commit and the files it changed against its first parent. */280export const commitDiff = (281 project: CodeProject,282 sha: CommitSha283): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>
14 unmodified lines
modified: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.2import { RepoHost, Revision } from "@repo/artifacts/repo-host";3import type { RepoNotFound } from "@repo/artifacts/repo-host";4import { BlobSha } from "@repo/protocol/ids";5import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";6import { Effect, Option } from "effect";723/** The most a file may weigh at a walk's first commit to be read whole at each commit. */8export const FILE_WALK_CAP = 256 * 1024;910const encoder = new TextEncoder();11
1 unmodified line
13 [...new Uint8Array(digest)]14 .map((byte) => byte.toString(16).padStart(2, "0"))15 .join("");1633/** The git blob id of `bytes`: the SHA-1 of `blob <size>\0` and the bytes. */17export 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 lines
2829 return BlobSha.make(hex(digest));30 });3149/** The file at `path` in `commit`, read whole: none when no file is there. */32export const fileAt = (33 repo: RepoName,34 commit: CommitSha,35 path: RepoPath
1 unmodified line
37 RepoHost.use((host) =>38 host.readFile(repo, Revision.Commit({ sha: commit }), path)39 );4059/** A file read whole at a commit: its blob id and its bytes. */41export interface FileVersion {42 readonly blob: BlobSha;43 readonly bytes: Uint8Array;44}4565/** The file's version at `path` in `commit`, read whole; none when no file is there. */46export const versionAt = (47 repo: RepoName,48 commit: CommitSha,49 path: RepoPath
5 unmodified lines
55 Effect.map(blobIdOf(bytes), (blob) => Option.some({ blob, bytes })),56 })57 );5879/**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 */59export const walkableAt = (60 repo: RepoName,61 commit: CommitSha,62 path: RepoPath
5 unmodified lines
modified: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 */1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { RepoNotFound } from "@repo/artifacts/repo-host";3import type { FileView, Rev } from "@repo/protocol/domain/code";4import { BlobSha } from "@repo/protocol/ids";
7 unmodified lines
12import { versionAt } from "./file-walk.ts";13import { commitAt, resolveRev } from "./revision.ts";14import { entryAt } from "./tree.ts";1523/** The most text a file's view carries: 1 MiB. */16export const TEXT_CAP = 1024 * 1024;1718// git's own test: a NUL among the first bytes means the blob is not text.19const SNIFF = 8192;2029/** The largest text a cache entry keeps; a larger one is read again. */21const KEPT_TEXT = 256 * 1024;2232/** Whether `bytes` read as binary: a NUL among the first 8 KiB. */23export const isBinary = (bytes: Uint8Array) =>24 bytes.subarray(0, SNIFF).includes(0);2536/** A file's contents: its text only when it is text and within the cap. */26export interface Contents {27 readonly size: number;28 readonly binary: boolean;29 readonly truncated: boolean;30 readonly text: Option.Option<string>;31}3244/** What Artifacts throws when a blob is too large for the Worker to hold. */33const MemoryLimit = Schema.Struct({ code: Schema.Literal("MEMORY_LIMIT") });3435const isMemoryLimit = Schema.is(MemoryLimit);3649/**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. */38export 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 );4561/** `bytes` as a reader sees them. */46export const contentsOfBytes = (bytes: Uint8Array): Contents => {47 const binary = isBinary(bytes);48 const truncated = !binary && bytes.length > TEXT_CAP;49
7 unmodified lines
57 truncated,58 };59};6077/**78 * The blob `blob`'s contents, kept by its id; none when the repo has no79 * blob by it (a submodule's commit).80 */61export const contentsOf = (62 repo: RepoName,63 blob: BlobSha64): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>
28 unmodified lines
93 }94 );95 });96117/** A file's view from its blob id and contents. */97const viewOf = (98 commit: CommitSha,99 path: RepoPath,100 sha: BlobSha,
10 unmodified lines
111 onSome: (text) => ({ text }),112 }),113});114136/**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. */116const wholeAt = (repo: RepoName, commit: CommitSha, path: RepoPath) =>117 Effect.gen(function* () {118 const cache = yield* CodeCache;119
10 unmodified lines
130 }131 );132 });133161/**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 */134export const fileView = (135 project: CodeProject,136 at: Option.Option<Rev>,137 path: RepoPath
36 unmodified lines
modified: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 */8import { WhyRange } from "@repo/protocol/domain/code";9import { BlobSha, CommitSha } from "@repo/protocol/ids";10import type { RepoName, RepoPath } from "@repo/protocol/ids";
1 unmodified line
1213import { CodeStore } from "../code-store.ts";14import { CodeCache } from "./cache.ts";1533/** The why walk's algorithm version, in its keys. */16export const WHY_VERSION = 1;1736/** The path log's algorithm version, in its keys. */18export const LOG_VERSION = 1;1939/** How many first-parent commits back a walk looks for a kept result to start from. */20export const INCREMENT_REACH = 16;2142/**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 */22export const StoredWhy = Schema.Struct({23 blob: BlobSha,24 ranges: Schema.Array(WhyRange),25 shas: Schema.Array(CommitSha),
1 unmodified line
27});2829export type StoredWhy = typeof StoredWhy.Type;3055/**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 */31export const StoredPathLog = Schema.Struct({32 reachedRoot: Schema.Boolean,33 shas: Schema.Array(CommitSha),34});3536export type StoredPathLog = typeof StoredPathLog.Type;3766/** The lowercase hex SHA-256 of `text`. */38const sha256 = (text: string) =>39 Effect.map(40 Effect.promise(() =>41 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))
3 unmodified lines
45 .map((byte) => byte.toString(16).padStart(2, "0"))46 .join("")47 );4878/** One kind of kept history: its key's kind and version, and its value. */49export interface Kept<A> {50 readonly kind: string;51 readonly version: number;52 readonly schema: Schema.Codec<A, unknown>;
10 unmodified lines
63 schema: StoredPathLog,64 version: LOG_VERSION,65};6697/** Where `kept` is kept for `path` from `commit`, scanning `scan` commits. */67export const keyOf = <A>(68 kept: Kept<A>,69 at: {70 readonly repo: RepoName;
7 unmodified lines
78 (hash) =>79 `${at.repo}/${kept.kind}/v${kept.version}/${at.commit}/${at.scan}/${hash}`80 );81113/**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. */83export const recall = <A>(84 kept: Kept<A>,85 key: string86): Effect.Effect<Option.Option<A>> =>
11 unmodified lines
98 { heavy: true, keep: Option.isSome }99 );100 });101136/** `value` kept under `key`, in the isolate's cache and in the store. */102export const remember = <A>(103 kept: Kept<A>,104 key: string,105 value: A
9 unmodified lines
115 yield* store.put(key, encoded);116 yield* cache.through(key, Effect.succeedSome(value), { heavy: true });117 });118154/**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. */120export const throughHistory = <A, E, R>(121 kept: Kept<A>,122 key: string,123 compute: Effect.Effect<A, E, R>
7 unmodified lines
modified: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 */1import { inRepoSession, Revision, RepoHost } from "@repo/artifacts/repo-host";2import type {3 Commit,4 RepoNotFound,
20 unmodified lines
25import type { StoredPathLog } from "./history.ts";26import { commitAt, resolveRev } from "./revision.ts";27import { entryAt, READS_AT_ONCE } from "./tree.ts";2847/** The most commits one page holds. */29export const LOG_LIMIT = 100;3050/** The most first-parent commits a path's log scans in one call. */31export const PATH_SCAN = 200;3253/** A commit as a reader sees it, with its landing when it is one. */33export const commitView = (34 commit: Commit,35 landing: Option.Option<LandingView>36): CommitView => {
25 unmodified lines
62 }),63 };64};6587/** `commits` as a reader sees them, each landing from one batch of the project's record. */66export const commitViews = (67 project: CodeProject,68 commits: readonly Commit[]69): Effect.Effect<readonly CommitView[]> =>
11 unmodified lines
81 );82 }83 );84107/**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 */85export const pageOf = (86 repo: RepoName,87 sha: CommitSha,88 from: number,
10 unmodified lines
99 { heavy: true }100 );101 });102129/** What sits at `path` in `tree`: its id and mode, or nothing. */103const idAt = (repo: RepoName, tree: string, path: RepoPath) =>104 Effect.map(105 entryAt(repo, tree, path),106 Option.map(({ mode, sha }: TreeEntry) => `${mode} ${sha}`)107 );108136/** A page of the log, and where the next starts when there is more. */109export interface LogPage {110 readonly commits: readonly CommitView[];111 readonly next?: number;112}
6 unmodified lines
119 onNone: () => ({ commits }),120 onSome: (at) => ({ commits, next: at }),121 });122151/** What sits at a path in a commit, as a walk compares it with its parent's. */123type IdOf = (124 commit: Commit125) => Effect.Effect<Option.Option<string>, RepoNotFound, RepoHost>;126156/**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.128const idOfFrom = (129 repo: RepoName,130 path: RepoPath,131 start: Commit
13 unmodified lines
145 ),146 })147 );148183/** What sits at the path in each commit of `commits`, in order: one lookup each. */149const 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 });154190/**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 */155const changedIn = (156 repo: RepoName,157 idOf: IdOf,158 scan: readonly Commit[],
34 unmodified lines
193194 return Array.getSomes(changed);195 });196238/** The path's history from `scan[0]`, kept at the nearest ancestor within reach. */197const nearestKept = (repo: RepoName, path: RepoPath, scan: readonly Commit[]) =>198 Effect.map(199 Effect.forEach(200 scan.slice(1, INCREMENT_REACH + 1),
9 unmodified lines
210 Option.map(kept, (value) => ({ back: at + 1, kept: value }))211 )212 );213256/** The path's history over `scan` (at most `PATH_SCAN` commits and the parent of its last). */214const historyOf = (215 repo: RepoName,216 path: RepoPath,217 scan: readonly Commit[]
31 unmodified lines
249 ],250 };251 });252296/** A page of first-parent commits from `at`, each landing with its record. */253export const logPage = (254 project: CodeProject,255 input: {256 readonly at: Option.Option<Rev>;
68 unmodified lines
325 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 */1import type {2 RepoHost,3 RepoNotFound,4 TreeEntry,
9 unmodified lines
14import { CodeCache } from "./cache.ts";15import { commitAt, resolveRev } from "./revision.ts";16import { entriesOf } from "./tree.ts";1724/** The most paths a commit's list holds. */18export const PATHS_CAP = 50_000;1927/** The longest path list the cache keeps: about 1 MB of paths. */20const KEPT_PATHS = 10_000;2130// Store calls under way at once, however wide or deep the tree.22const STORE_CALLS = 8;2333/** One file under a root tree, with the entry that names it. */24export interface FileAt {25 readonly path: RepoPath;26 readonly entry: TreeEntry;27}2839/** A folder still to read: its path's prefix and its tree's id. */29interface Folder {30 readonly prefix: string;31 readonly tree: string;32}3345/**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. */35export const filesUnder = (36 repo: RepoName,37 root: string,38 cap: number
42 unmodified lines
81 truncated: all.length > cap || depth.length > 0,82 };83 });84101/** Every file path at `at`, up to the cap. */85export const pathList = (86 project: CodeProject,87 at: Option.Option<Rev>88): Effect.Effect<PathList, UnknownRevision, RepoHost> =>
9 unmodified lines
98 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 lines
modified: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 */1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import { Rev } from "@repo/protocol/domain/code";3import { BlobSha, RepoPath } from "@repo/protocol/ids";4import type { ProjectName } from "@repo/protocol/ids";
5 unmodified lines
10import { isBinary, unlessTooLarge } from "./file.ts";11import { commitAt, isFullSha, resolveRev } from "./revision.ts";12import { entryAt, segmentsOf } from "./tree.ts";1326/** 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. */15const SANDBOX =16 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";1718const IMAGES = new Map([
8 unmodified lines
27]);2829const TEXT = "text/plain; charset=utf-8";3043/** What every raw answer carries, a refusal too (ADR 0019). */31const SAFE = {32 "content-security-policy": SANDBOX,33 "x-content-type-options": "nosniff",34} as const;3549/** `path`'s extension, lowercased; none without one. */36const extensionOf = (path: string) => {37 const name = path.slice(path.lastIndexOf("/") + 1);38 const dot = name.lastIndexOf(".");3940 return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();41};4257/**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 */43export const rawHeaders = (44 path: RepoPath,45 rev: "sha" | "ref",46 blob: BlobSha,
15 unmodified lines
6263 return headers;64};6586/** A 404 that says nothing of the repo. */66const notFound = () => new Response(null, { headers: SAFE, status: 404 });6789/** A 413: Artifacts said the blob is too large to hold. */68const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });6992/** The file `path` at `rev` of the project's canonical repo, as raw bytes. */70export const rawOf = (71 project: CodeProject,72 rev: Rev,73 path: RepoPath
44 unmodified lines
118const decodePath = Schema.decodeUnknownOption(RepoPath);119120const decoded = Option.liftThrowable(decodeURIComponent);121145/**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 */122export const rawRequestOf = (123 rest: string124): Option.Option<{ readonly rev: Rev; readonly path: RepoPath }> => {125 const slash = rest.indexOf("/");
10 unmodified lines
136 rev: Option.flatMap(decoded(rest.slice(0, slash)), decodeRev),137 });138};139169/**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. */141export 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 lines
148149 return segments[2] === "raw" ? segments.slice(3).join("/") : "";150};151188/**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 */152export const rawFor = (153 project: ProjectName,154 url: string155): Effect.Effect<Response, never, RepoHost | Projects> =>
8 unmodified lines
modified: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 */1import { RepoHost } from "@repo/artifacts/repo-host";2import { packageOf, TagName } from "@repo/protocol/domain/code";3import type { RefsView, TagRef } from "@repo/protocol/domain/code";4import { Array, Effect, Option, Schema } from "effect";56import type { CodeProject } from "../code.ts";7import { tagNameOf } from "./revision.ts";816/** A name cut into runs of digits and runs of anything else. */9const runsOf = (name: string) => name.match(/\d+|\D+/gu) ?? [];1011const isDigits = (run: string) => /^\d/u.test(run);1221/** Two strings as written, code point by code point. */13const compareText = (one: string, other: string) => {14 if (one === other) {15 return 0;16 }1718 return one < other ? -1 : 1;19};2030/** Two runs of digits by their value, however long. */21const compareNumbers = (one: string, other: string) => {22 const left = one.replace(/^0+(?=\d)/u, "");23 const right = other.replace(/^0+(?=\d)/u, "");24
3 unmodified lines
2829 return compareText(left, right);30};3142/**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. */33export const compareTags = (one: string, other: string): number => {34 const left = runsOf(one);35 const right = runsOf(other);36
14 unmodified lines
51 if (left.length === right.length) {52 return 0;53 }5470 // 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;6061 return leftIsLonger === longerIsNewer ? -1 : 1;62};6380/**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. */65export const sortTags = <T extends { readonly name: string }>(66 tags: readonly T[]67): readonly T[] => {68 const keyed = tags.map((tag) => ({
33 unmodified lines
102};103104const decodeTag = Schema.decodeUnknownOption(TagName);105127/** 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. */107export const refsView = (108 project: CodeProject109): Effect.Effect<RefsView, never, RepoHost> =>110 Effect.gen(function* () {
26 unmodified lines
modified: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 */6import { RepoHost } from "@repo/artifacts/repo-host";7import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";8import type { Rev } from "@repo/protocol/domain/code";
4 unmodified lines
1314import type { CodeProject } from "../code.ts";15import { CodeCache } from "./cache.ts";1620/** A full commit id: 40 lowercase hex digits. Short ids are not resolved. */17const FULL_SHA = /^[0-9a-f]{40}$/u;1823/** Whether `rev` names a commit by its full id (and so never moves). */19export const isFullSha = (rev: string) => FULL_SHA.test(rev);2026/** Where every tag's name starts. */21const TAGS = "refs/tags/";2229/** A ref name's tag name, when it is a tag's. */23export const tagNameOf = (ref: string): Option.Option<string> =>24 ref.startsWith(TAGS) ? Option.some(ref.slice(TAGS.length)) : Option.none();2533/**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. */27export const commitAt = (28 repo: RepoName,29 sha: CommitSha30): Effect.Effect<Option.Option<Commit>, RepoNotFound, RepoHost> =>
12 unmodified lines
43 Effect.catchTag("NoSuchElementError", () => Effect.succeedNone)44 );45 });4657/** The commit `at` names in the project's canonical repo. */47export const resolveRev = (48 project: CodeProject,49 at: Option.Option<Rev>50): Effect.Effect<CommitSha, UnknownRevision, RepoHost> => {
38 unmodified lines
modified: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 */1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";3import type { CodeEntry, Rev, TreeListing } from "@repo/protocol/domain/code";4import { BlobSha, RepoPath } from "@repo/protocol/ids";
5 unmodified lines
10import type { CodeProject } from "../code.ts";11import { CodeCache } from "./cache.ts";12import { commitAt, resolveRev } from "./revision.ts";1320/**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. */15export const READS_AT_ONCE = 48;1632/** The entries of the tree `id`; a tree a commit or a tree names is always there. */17export const entriesOf = (18 repo: RepoName,19 id: string20): Effect.Effect<readonly TreeEntry[], RepoNotFound, RepoHost> =>
12 unmodified lines
33 )34 );35 });3653/** The segments of `path`; none when one is empty, `.` or `..`. */37export const segmentsOf = (path: string): Option.Option<readonly string[]> => {38 const segments = path.split("/");3940 return segments.every(
2 unmodified lines
43 ? Option.some(segments)44 : Option.none();45};4664/** The entry at `path` under the tree `root`, walked one segment at a time. */47export const entryAt = (48 repo: RepoName,49 root: string,50 path: string
22 unmodified lines
73 return found;74 }),75 });7695/** What a reader sees an entry as: a gitlink is a submodule, mode 120000 a symlink. */77export 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 );84104/** Folders first, then by name. */85const byKindThenName = Order.combine(86 Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),87 Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)88);89110/** GitLab's README precedence, lowercased. */90const README = [91 "readme.md",92 "readme.markdown",93 "readme.mdown",
1 unmodified line
95 "readme.txt",96 "readme.rst",97];98120/**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. */100const linkTargetOf = (101 folder: string,102 target: string103): Option.Option<string> => {
15 unmodified lines
119120 return Option.liftPredicate(resolved.join("/"), (path) => path !== "");121};122148/** The longest path a symlink's target may be: git's own `PATH_MAX`. */123const LINK_TARGET_MAX = 4096;124151/** A symlink's target text, kept by its blob id; none when it is too long to be a path. */125const linkTextOf = (repo: RepoName, link: string) =>126 Effect.gen(function* () {127 const cache = yield* CodeCache;128
10 unmodified lines
139 )140 );141 });142170/**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. */144const linkedFile = (145 repo: RepoName,146 root: Effect.Effect<string, never, RepoHost>,147 folder: string,
22 unmodified lines
170 : Option.none()171 );172 });173205/**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 */174const readmeOf = (175 repo: RepoName,176 root: Effect.Effect<string, never, RepoHost>,177 folder: string,
24 unmodified lines
202203 return Option.none();204 });205243/** The tree `path` names at `commit`, or `UnknownPath`. */206export const folderAt = (207 repo: RepoName,208 commit: CommitSha,209 path: Option.Option<RepoPath>
20 unmodified lines
230 RepoNotFound: Effect.die,231 })232 );233272/** One folder at `at`, folders first, with its README. */234export const listing = (235 project: CodeProject,236 at: Option.Option<Rev>,237 path: Option.Option<RepoPath>
49 unmodified lines
modified: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 */1import { inRepoSession, ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";3import {4 blameFrom,
27 unmodified lines
32import { commitViews, pageOf } from "./log.ts";33import { commitAt, resolveRev } from "./revision.ts";34import { entryAt, READS_AT_ONCE } from "./tree.ts";3557/** The most first-parent commits one view walks. */36export const WHY_SCAN = 200;3760/** A version of the file: its blob, and the oldest commit that holds it. */38interface Version {39 readonly blob: BlobSha;40 readonly commit: Commit;41}4266/** The file's versions newest first, and whether the walk stopped short of its first commit. */43interface Versions {44 readonly versions: readonly Version[];45 readonly stopped: boolean;46}4772/** The file's blob at `path` in `commit`, if a file is there. */48const blobAt = (repo: RepoName, commit: Commit, path: RepoPath) =>49 Effect.map(50 entryAt(repo, commit.tree, path),51 Option.flatMap((entry) =>
2 unmodified lines
54 : Option.none()55 )56 );5783/**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 */58const 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);6465 const found = yield* Effect.forEach(66 commits,
19 unmodified lines
8687 return missing === -1 ? looked : looked.slice(0, missing + 1);88 });89123/**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 */90const versionsOf = (91 newest: Version,92 found: readonly {93 readonly blob: Option.Option<BlobSha>;
25 unmodified lines
119 versions,120 };121};122161/**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.125const 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(() => "")));132174/** The landings among `shas`, asked for in batches the record answers. */133const landingsOf = (project: CodeProject, shas: readonly CommitSha[]) =>134 Effect.map(135 Effect.forEach(Array.chunksOf(shas, MAX_LANDINGS), project.landings),136 Array.flatten137 );138181/** Each line's commit, from ranges of consecutive lines numbered from 1. */139const ownersOf = (ranges: readonly WhyRange[]): readonly CommitSha[] =>140 ranges.flatMap(({ end, sha, start }) =>141 Array.makeBy(end - start + 1, () => sha)142 );143187/** Each line's commit as ranges of consecutive lines, numbered from 1. */144const rangesOf = (owners: readonly CommitSha[]): readonly WhyRange[] => {145 const ranges: WhyRange[] = [];146147 for (const [index, sha] of owners.entries()) {
9 unmodified lines
157158 return ranges;159};160205/**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 */161const carried = (162 before: { readonly text: string; readonly owners: readonly CommitSha[] },163 after: string,164 sha: CommitSha
11 unmodified lines
176177 return owners;178};179229/** The why kept at `log[at]`'s nearest ancestor within reach, and how far back. */180const nearestKept = (181 repo: RepoName,182 path: RepoPath,183 log: readonly Commit[],
14 unmodified lines
198 Option.map(kept, (value) => ({ back: at + 1, kept: value }))199 )200 );201252/**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 */202const forward = (203 repo: RepoName,204 log: readonly Commit[],205 newest: BlobSha,
6 unmodified lines
212 }213214 const blobs = [newest, ...between.map(Option.getOrThrow)];215272 // 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 lines
277 }),278 });279 });280339/**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 */281const blamed = <R>(282 head: Commit,283 newest: BlobSha,284 text: string,
42 unmodified lines
327 ? { ...none, ranges, shas, stoppedAt: last.commit.sha }328 : { ...none, ranges, shas };329 });330395/**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 */331const walkedByFile = (332 repo: RepoName,333 path: RepoPath,334 log: readonly Commit[],
6 unmodified lines
341 if (Option.isNone(text)) {342 return { blob: newest.blob, ranges: [], shas: [] };343 }344414 // 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]]);346347 const found = yield* lookups(log.slice(1), (commit) =>348 versionAt(repo, commit.sha, path).pipe(
19 unmodified lines
368 );369 });370 });371443/**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 */372const walked = (373 repo: RepoName,374 at: CommitSha,375 path: RepoPath,
41 unmodified lines
417 (blob) => textOf(repo, blob)418 );419 });420498/** The why at `at`, computed: from a kept ancestor's when one is in reach. */421const computed = (422 repo: RepoName,423 at: CommitSha,424 path: RepoPath,
35 unmodified lines
460461 return yield* walked(repo, at, path, log, head);462 });463542/**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 */464const viewOf = (465 project: CodeProject,466 at: CommitSha,467 path: RepoPath,
45 unmodified lines
513 }),514 };515 });516601/** Why each line of `path` at `at` is there, walking at most `scan` commits. */517export const whyView = (518 project: CodeProject,519 at: Option.Option<Rev>,520 path: RepoPath,
10 unmodified lines
531 asOneView(computed(repo, commit, path, scan))532 );533534 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 */1import { Data, Effect, Layer, Option } from "effect";23import { CodeStore, fittingKey } from "../code-store.ts";4import type { CodeStoreApi } from "../code-store.ts";512/**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. */7export interface BucketLike {8 readonly get: (9 key: string10 ) => Promise<{ readonly text: () => Promise<string> } | null>;
2 unmodified lines
13 value: string14 ) => Promise<{ readonly key: string } | null>;15}1627/** R2 refused or never answered one call on one key. */17class CodeStoreUnreachable extends Data.TaggedError("CodeStoreUnreachable")<{18 readonly cause: unknown;19}> {}2032/** One call on the bucket. */21const reach = <A>(run: () => Promise<A>) =>22 Effect.tryPromise({23 catch: (cause) => new CodeStoreUnreachable({ cause }),24 try: run,25 });2639/** The store over `bucket`. */27export const CodeStoreR2 = (bucket: BucketLike) => {28 const store: CodeStoreApi = {29 get: (key) =>30 Effect.flatMap(fittingKey(key), (fit) =>
27 unmodified lines
modified: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 */1import { Context, Effect, Layer, Option, Ref } from "effect";23import { CodeStore, fittingKey } from "../code-store.ts";4import type { CodeStoreApi } from "../code-store.ts";510/** How often the memory store was asked, for tests. */6export class CodeStoreCounts extends Context.Service<7 CodeStoreCounts,8 {9 readonly counts: Effect.Effect<{
2 unmodified lines
12 }>;13 }14>()("project/CodeStoreCounts") {}1521/** A fresh store in memory, with its counts. */16export 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 lines
modified: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 */1import type {2 FrontPageEntry,3 ProjectListing,4} from "@repo/protocol/domain/front-page";
4 unmodified lines
910import { FrontPage } from "../front-page.ts";11import type { FrontPageFilter } from "../front-page.ts";1218/** What the memory front page reads back. */13export 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 lines
modified: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 */1import {2 BranchName,3 ObjectId,4 RefName,
52 unmodified lines
57const SNIFF = 8000;5859const blocked = () => new VerifierBlocked({});6082/** A store that lost a repo cannot merge or land: `VerifierBlocked`. */61const unlessLost = <A, R>(62 effect: Effect.Effect<A, RepoNotFound, R>63): Effect.Effect<A, VerifierBlocked, R> => Effect.mapError(effect, blocked);6487/** An object the store should hold and does not: `VerifierBlocked` too. */65const found = <A, R>(66 read: Effect.Effect<Option.Option<A>, RepoNotFound, R>67): Effect.Effect<A, VerifierBlocked, R> =>68 read.pipe(
17 unmodified lines
8687const refsIn = (repo: RepoName) =>88 RepoHost.use((host) => host.refs(repo)).pipe(unlessLost);89113/** One ref's compare-and-swap, alone in its push; what it came to. */90const 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 );94119/** A push whose ref did not move, for a ref where that is not a refusal. */95const moves = (outcome: Option.Option<RefOutcome>) =>96 Option.exists(outcome, RefOutcome.$is("Updated"))97 ? Effect.void98 : Effect.fail(blocked());99125/** Clock time, in the whole seconds a git signature holds. */100const seconds = Effect.map(Clock.currentTimeMillis, (millis) =>101 Math.floor(millis / 1000)102);103104const git = <A>(run: () => Promise<A>) =>105 Effect.tryPromise(run).pipe(Effect.orDie);106133/** A git signature at `at` seconds past the epoch, in UTC. */107const signed = (who: GitIdentity, at: number) => ({108 email: who.email,109 name: who.name,110 timestamp: at,
3 unmodified lines
114/** A copy of an object must keep its id, or the push would name one it lacks. */115const kept = (id: ObjectId, made: ObjectId) =>116 made === id ? Effect.void : Effect.die(`copying ${id} produced ${made}`);117145/**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 */118const scratch = Effect.gen(function* () {119 const source: PushSource = { fs: memoryFs(), gitdir: "/lander.git" };120121 yield* git(() => init({ ...source, bare: true, defaultBranch: "main" }));
42 unmodified lines
164 ),165 (oid) => CommitSha.make(oid)166 );167199 /** 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 lines
186 tree: yield* tree(files),187 });188 });189222 /**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: Uint8Array
58 unmodified lines
252253const isFile = (entry: TreeEntry | undefined) =>254 entry?.mode === "100644" || entry?.mode === "100755";255293/** The folder an entry is, if it is one. */256const folderOf = (entry: TreeEntry | undefined) =>257 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();258259const byName = (entries: readonly TreeEntry[]) =>
4 unmodified lines
264 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),265 onSome: (id) => treeIn(repo, id),266 });267306/** Where an answer's sides are read: main from canonical, base and head from the fork. */268interface Sides {269 readonly canonical: RepoName;270 readonly fork: RepoName;271}272312/** A merged folder's entries, or the paths under it that conflict. */273interface MergedTree {274 readonly entries: readonly TreeEntry[];275 readonly conflicts: readonly string[];276}
7 unmodified lines
284 conflicts: [path],285 entries: [],286});287328/**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 */288const adopt = (289 sides: Sides,290 into: Scratch,291 theirs: TreeEntry,
20 unmodified lines
312 yield* kept(theirs.sha, yield* into.tree(children));313 });314};315362/** A file's mode once both sides changed it, unless they changed it differently. */316const mergedMode = (317 base: TreeEntry | undefined,318 ours: TreeEntry,319 theirs: TreeEntry
4 unmodified lines
324325 return base?.mode === ours.mode ? Option.some(theirs.mode) : Option.none();326};327375/** A file both sides changed, merged; `None` when the changes conflict. */328const mergeFile = (329 sides: Sides,330 into: Scratch,331 name: string,
48 unmodified lines
380381 return Option.map(yield* into.lines(before, mine, yours), file);382 });383432/**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 */384const mergeTrees = (385 sides: Sides,386 into: Scratch,387 prefix: string,
36 unmodified lines
424 ours: Option.some(o.sha),425 theirs: Option.some(t.sha),426 });427481 // 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 lines
459 entries: merged.flatMap(({ entries }) => entries),460 };461 });462517/**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 */463const 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 lines
497 tree: TreeSha.make(yield* into.tree(merged.entries)),498 };499 });500560/** A file to place, by the folders and name its path is made of. */501interface Placed {502 readonly segments: readonly string[];503 readonly content: string;504}505566/** A path's folders and file name; one that cannot name a file is a defect upstream. */506const placed = ({ content, path }: ComposedFile) => {507 const segments = path.split("/");508509 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};513575/**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 */514const placeFiles = (515 repo: RepoName,516 into: Scratch,517 prefix: string,
47 unmodified lines
565566 return yield* into.tree([...entries.values()]);567 });568635/** `main` with `files` added, written into `into`: the new root. */569const composeOnto = (570 into: Scratch,571 repo: RepoName,572 main: CommitSha,
7 unmodified lines
580 yield* placeFiles(repo, into, "", Option.some(commit.tree), paths)581 );582 });583651/** The tree a land rebuilds, written into `into` where it is new. */584const 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 lines
601 requestIdOf(message) === requestId602 ? Effect.void603 : Effect.die(`a landing's message must carry Request-Id: ${requestId}`);604673/**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 */605const 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 lines
615616 return Option.fromNullishOr(mine?.sha);617 });618691/** The mirror ref moved to the landing, while the landing is still main's tip. */619const 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 lines
636 })637 );638 });639713/** Whether the notes at `tip` already hold a note on `target`. */640const noted = (641 repo: RepoName,642 tip: Option.Option<CommitSha>,643 target: CommitSha
8 unmodified lines
652 return entries.some(({ name }) => name === target);653 }),654 });655730/** The verdict written as the landing's note, unless it is there already. */656const 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 lines
674 yield* pushOne(repo, source, { from: parent, ref: notesRef, to: commit })675 );676 });677753/** One piece of bookkeeping: `None` once written, its name when it was not. */678const attempt = <E>(679 item: Bookkeeping,680 write: Effect.Effect<void, E, RepoHost>681) =>
6 unmodified lines
688 )689 )690 );691768/**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.694const settle = (job: LandJob, landing: CommitSha) =>695 Effect.gen(function* () {696 const mirrored = yield* attempt("mirror", mirror(job.repo, landing));697
7 unmodified lines
705 sha: LandedSha.make(landing),706 };707 });708788/** The base a stale land names: the answer's own, or the main it was built on. */709const baseOf = (job: LandJob) =>710 Rebuild.$match(job.rebuild, {711 Compose: () => job.main,712 Existing: () => job.main,713 Merge: ({ base }) => base,714 });715796/** A land that found `main` at `tip`: the earlier land of the same request, or stale. */716const moved = (job: LandJob, tip: Option.Option<CommitSha>) =>717 Effect.gen(function* () {718 const earlier = yield* landedBefore(job);719
96 unmodified lines
816817 return { commit, tree };818 });819901/** Every file under the folder `tree`, by repo path, as committed. */820const filesUnder = (821 repo: RepoName,822 tree: ObjectId,823 prefix: string
21 unmodified lines
845846 return nested.flat();847 });848931/** The config folder in the root `root`, if the commit has one. */849const configFolder = (repo: RepoName, root: ObjectId) =>850 Effect.reduce(851 Brand.configDir.split("/"),852 (): Option.Option<ObjectId> => Option.some(root),
34 unmodified lines
887888 return { changes, tree };889 });890974/** The Lander over isomorphic-git, reading and pushing through `RepoHost`. */891export const LanderIsogit: Layer.Layer<Lander, never, RepoHost> = Layer.effect(892 Lander,893 Effect.gen(function* () {894 const host = yield* RepoHost;
10 unmodified lines
modified: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 */1import type { RepoBusy, StaleBase } from "@repo/protocol/refusal";2import { VerifierBlocked } from "@repo/protocol/refusal";3import type { ConfigBundle } from "@repo/rules/rules-evaluator";4import { Array, Data, Effect, Layer } from "effect";
9 unmodified lines
14 MergeJob,15 Merged,16} from "../lander.ts";1724/** One call the scripted Lander answered, with the job it was given. */18export type LanderJob = Data.TaggedEnum<{19 Merge: { readonly job: MergeJob };20 Land: { readonly job: LandJob };21 Compose: { readonly job: ComposeJob };
1 unmodified line
23}>;2425export const LanderJob = Data.taggedEnum<LanderJob>();2634/** Each operation's results, in the order its calls get them. */27export interface LanderScript {28 readonly merge?: readonly Result.Result<29 Merged,30 StaleBase | VerifierBlocked
5 unmodified lines
36 readonly compose?: readonly Result.Result<Composed, VerifierBlocked>[];37 readonly bundle?: readonly Result.Result<ConfigBundle, VerifierBlocked>[];38}3948/** A scripted Lander, and the jobs it has been given so far. */40export type ScriptedLander = Layer.Layer<Lander> & {41 readonly jobs: Effect.Effect<readonly LanderJob[]>;42};4344export 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 lines
modified: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 */1import { Remote } from "@repo/checks/check-runner/wire";2import { Verdict } from "@repo/protocol/domain/answer";3import {4 CommitSha,
22 unmodified lines
27export { Remote } from "@repo/checks/check-runner/wire";2829export { ConfigBundle } from "@repo/rules/rules-evaluator";3042/** One file a decider adds at its path. */31export const ComposedFile = Schema.Struct({32 content: Schema.String,33 path: RepoPath,34});
10 unmodified lines
45 changes: Schema.Array(Change),46 tree: TreeSha,47}) satisfies Schema.Codec<MergedResult, unknown, unknown, unknown>;4861/** How a stateless Lander rebuilds the tree it lands (the port's `Rebuild`). */49export const Rebuild = Schema.TaggedUnion({50 Compose: { files: Schema.NonEmptyArray(ComposedFile) },51 Existing: { commit: CommitSha },52 Merge: { base: CommitSha, fork: RepoName, head: CommitSha },
30 unmodified lines
83 at: LandedSha,84 repo: RepoName,85}) satisfies Schema.Codec<BundleJobArgs, unknown, unknown, unknown>;86100/**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 */87export const MergeWire = Schema.Struct({88 fork: Remote,89 job: MergeJob,90 main: Remote,91});92110/**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. */94export const LandWire = Schema.Struct({95 fork: Schema.optionalKey(Remote),96 job: LandJob,97 main: Remote,
1 unmodified line
99100/** A compose: a write token on canonical, used only for a compose ref, never `main`. */101export const ComposeWire = Schema.Struct({ job: ComposeJob, main: Remote });102124/** A bundle of the config folder: a read token on canonical. */103export const BundleWire = Schema.Struct({ job: BundleJob, main: Remote });104127/** A merge's outcome as it comes back: the merged tree, a refusal, or a defect, as JSON. */105export const MergeExit = Schema.toCodecJson(106 Schema.Exit(107 Merged,108 Schema.Union([StaleBase, VerifierBlocked]),109 Schema.Defect()110 )111);112136/** A land's outcome as it comes back, as JSON. */113export const LandExit = Schema.toCodecJson(114 Schema.Exit(115 Landed,116 Schema.Union([StaleBase, RepoBusy, VerifierBlocked]),117 Schema.Defect()118 )119);120145/** A compose's outcome as it comes back, as JSON. */121export const ComposeExit = Schema.toCodecJson(122 Schema.Exit(Composed, VerifierBlocked, Schema.Defect())123);124150/** A bundle's outcome as it comes back, as JSON. */125export const BundleExit = Schema.toCodecJson(126 Schema.Exit(ConfigBundle, VerifierBlocked, Schema.Defect())127);
modified:packages/project/src/project-store/memory.ts-18 removed
19 unmodified lines
20 writeAll,21} from "./tables.ts";22import type { Column, Table, Upsert } from "./tables.ts";2324/** A row as a table keeps it: its columns and its encoded body. */24interface Stored {25 readonly body: string;26 readonly columns: Readonly<Record<string, Column>>;27}2830/** A table's rows by key, in the order each key was first written. */29type Rows = ReadonlyMap<string, Stored>;3031interface 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}3637const keyOf = <A>(table: Table<A>, columns: Stored["columns"]) =>
7 unmodified lines
4546const all = <A>(state: State, table: Table<A>) =>47 decodeAll(table, rowsIn(state, table).values());4853/** A landing with the place it was first written in. */49type Placed = readonly [index: number, row: Stored];5056/** Newest first: by landing time, then the later write, as `/sqlite` orders them. */51const 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);5764/** Ledger entries in order, as `/sqlite` reads them. */58const bySeq = Order.mapInput(Order.Number, (entry: LedgerRow) => entry.seq);5960const snapshotOf = (state: State) =>61 Effect.gen(function* () {
29 unmodified lines
91 ratchets: yield* all(state, Tables.ratchets),92 } satisfies ProjectSnapshot;93 });94102/** The push events in `writes` that `state` already holds, each once. */95const seenIn = (state: State, writes: ProjectWrites) => {96 const seen = rowsIn(state, Tables.pushEvents);9798 return Array.dedupe(
23 unmodified lines
122123 tables.set(table.name, kept);124 });125134/**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 */126const written = (state: State, writes: ProjectWrites) =>127 Effect.gen(function* () {128 const tables = new Map(state.tables);129
17 unmodified lines
147148 return [committed, next] as const;149 });150163/**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 */151export const ProjectStoreMemory = Layer.effect(152 ProjectStore,153 Effect.gen(function* () {154 const ref = yield* SynchronizedRef.make<State>({
73 unmodified lines
modified:packages/project/src/project-store/migrations.ts+1 added-14 removed
1import { Effect } from "effect";2import * as Migrator from "effect/sql/Migrator";3import { SqlClient } from "effect/sql/SqlClient";45// 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.67const projectState = Effect.gen(function* () {8 const sql = yield* SqlClient;9
46 unmodified lines
56 )`;57 yield* sql`CREATE TABLE outbox (id TEXT PRIMARY KEY, body TEXT NOT NULL)`;58});5962// 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.60const visibility = Effect.gen(function* () {61 const sql = yield* SqlClient;6263 yield* sql`CREATE TABLE layers (name TEXT PRIMARY KEY, body TEXT NOT NULL)`;
17 unmodified lines
81 body TEXT NOT NULL82 )`;83});8490/** Every migration, by `<id>_<name>`, in the order they run. */85const migrations = {86 "1_project_state": projectState,87 "2_visibility": visibility,88};8996/**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 */90export const migrate: Effect.Effect<91 readonly (readonly [id: number, name: string])[],92 never,93 SqlClient
4 unmodified lines
modified:packages/project/src/project-store/rows.ts+8 added-75 removed
20 unmodified lines
21 SuiteRoot,22} from "@repo/protocol/ids";23import { Schema } from "effect";2425// 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.2630/**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 */27export 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});3738export type ProjectRow = typeof ProjectRow.Type;3950/** An ask, as the domain types it. */40export const AskRow = Ask;4142export type AskRow = typeof AskRow.Type;4355/**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. */45export const PinnedSuite = Schema.Struct({46 at: CommitSha,47 suite: SuiteRoot,48});4950export type PinnedSuite = typeof PinnedSuite.Type;5167/**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. */53export 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});6162export type ClaimRow = typeof ClaimRow.Type;6386/**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. */65export 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});7374export type AnswerRow = typeof AnswerRow.Type;75106/** A landing, as the domain types it. */76export const LandingRow = LandingView;7778export type LandingRow = typeof LandingRow.Type;79111/** A proposal, as the domain types it. */80export const ProposalRow = Proposal;8182export type ProposalRow = typeof ProposalRow.Type;83116/** A decision, as the domain types it. */84export const DecisionRow = Decision;8586export type DecisionRow = typeof DecisionRow.Type;87121/** How much of one decider's budget one day used, and how many finishes. */88export 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});9495export type BudgetDayRow = typeof BudgetDayRow.Type;96132/** A ratchet's count in one territory, as recorded at a landing. */97export const RatchetRow = Schema.Struct({98 at: LandedSha,99 count: Schema.Int,100 ratchet: RatchetName,
1 unmodified line
102});103104export type RatchetRow = typeof RatchetRow.Type;105142/**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. */107export const PushEventRow = Schema.Struct({108 after: Schema.optionalKey(CommitSha),109 at: Schema.DateTimeUtcFromString,110 before: Schema.optionalKey(CommitSha),
3 unmodified lines
114});115116export type PushEventRow = typeof PushEventRow.Type;117157/**158 * A side effect still to run after its transition was persisted (a fork, a159 * projection row), kept until it is acknowledged.160 */118export const OutboxRow = Schema.Struct({119 attempts: Schema.Int,120 body: Schema.Json,121 id: Schema.NonEmptyString,
2 unmodified lines
124});125126export type OutboxRow = typeof OutboxRow.Type;127171// 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.174175/**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. */129export 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});138139export type LayerRow = typeof LayerRow.Type;140195/**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. */142export const AttemptRow = Schema.Struct({143 area: AreaName,144 ask: AskId,145 claimant: Handle,
2 unmodified lines
148});149150export type AttemptRow = typeof AttemptRow.Type;151210/** One entry of the public ledger, numbered by whoever appends it, in order. */152export const LedgerRow = LedgerEntry;153154export type LedgerRow = typeof LedgerRow.Type;155215/**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. */157export const EnvValueRow = Schema.Struct({158 key: EnvKey,159 sealed: Schema.Json,160 setAt: Schema.DateTimeUtcFromString,
1 unmodified line
162});163164export type EnvValueRow = typeof EnvValueRow.Type;165229/** A read of a layer repo through the gateway, before the store numbers it. */166export 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});172173export type LayerRead = typeof LayerRead.Type;174240/** A layer read with the number the store gave it: the read log, for the layer's readers. */175export const LayerReadRow = Schema.Struct({176 ...LayerRead.fields,177 seq: Schema.Int,178});179180export type LayerReadRow = typeof LayerReadRow.Type;181248/** An event with the sequence number the store gave it. */182export const EventRow = Schema.Struct({183 event: ProjectEvent,184 seq: Schema.Int,185});
2 unmodified lines
modified:packages/project/src/project-store/sqlite.ts+4 added-9 removed
17 unmodified lines
18 writeAll,19} from "./tables.ts";20import type { Table } from "./tables.ts";2122// What SQLite hands back is decoded like any other outside input.22const Bodies = Schema.Array(Schema.Struct({ body: Schema.String }));2324const decodeBodies = Schema.decodeUnknownEffect(Bodies);25
4 unmodified lines
30const LastSeq = Schema.Tuple([Schema.Struct({ last: Schema.Int })]);3132const decodeLastSeq = Schema.decodeUnknownEffect(LastSeq);3335/** The rows a query returns, each decoded from its body. */34const bodiesOf = <A>(table: Table<A>, statement: Statement<object>) =>35 statement.pipe(36 Effect.flatMap(decodeBodies),37 Effect.flatMap((rows) =>
1 unmodified line
39 )40 );4142/**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 */46export const ProjectStoreSqlite = Layer.effect(47 ProjectStore,48 Effect.gen(function* () {
14 unmodified lines
63 Effect.flatMap(decodeLastSeq),64 Effect.map(([row]) => row.last)65 );6672 // 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 lines
modified:packages/project/src/project-store/tables.ts-24 removed
19 unmodified lines
20 PushEventRow,21 RatchetRow,22} from "./rows.ts";2324// 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`.2829/** A column's value: text, or an integer. */24export type Column = string | number;2532/** One table's rows: how a row becomes its key columns and body, and back. */26export 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 lines
51 name,52 };53};5464/** The tables that hold many rows, by the `ProjectWrites` field that carries them. */55export const Tables = {56 answers: tableOf("answers", AnswerRow, ["request_id"], (row) => ({57 request_id: row.requestId,58 })),
48 unmodified lines
107 (row) => ({ ratchet: row.ratchet, territory: row.territory })108 ),109} as const;110121/** A table with one row at most: the project, and the landing queue. */111const single = { id: 1 } as const;112124/** The project's own row. */113export const ProjectTable = tableOf(114 "project",115 ProjectRow,116 ["id"],117 () => single118);119132/** The encoded landing queue, one row. */120export const QueueTable = tableOf(121 "landing_queue",122 Schema.Json,123 ["id"],124 () => single125);126140/** The project's events, each body carrying the `seq` it was given. */127export const EventTable = tableOf("events", ProjectEvent, ["seq"], (event) => ({128 seq: event.seq,129}));130145/** The layer read log, each body carrying the `seq` it was given. */131export const LayerReadTable = tableOf(132 "layer_reads",133 LayerReadRow,134 ["seq"],135 (read) => ({ at: DateTime.toEpochMillis(read.at), seq: read.seq })136);137153/** How an adapter writes one table's rows, each replacing any row under its key. */138export type Upsert<E, R> = <A>(139 table: Table<A>,140 rows: readonly A[]141) => Effect.Effect<void, E, R>;142159/** The newest numbers a store gave: its last event's, and its last layer read's. */143export interface LastNumbers {144 readonly read: number;145 readonly seq: number;146}147165/**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 */148export const writeAll = <E, R>(149 writes: ProjectWrites,150 last: LastNumbers,151 upsert: Upsert<E, R>
36 unmodified lines
modified: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.2import { Context, Effect, Layer, Ref, Schema } from "effect";34import { Projection, ProjectedEvent } from "../projection.ts";56const decodeProjected = Schema.decodeUnknownEffect(ProjectedEvent);714/** What the memory projection has taken so far. */8export class ProjectedRows extends Context.Service<9 ProjectedRows,10 { readonly events: Effect.Effect<readonly ProjectedEvent[]> }11>()("project/ProjectedRows") {}1220/** A fresh, empty projection each time the layer is built, and its reading. */13export const ProjectionMemory: Layer.Layer<Projection | ProjectedRows> =14 Layer.effectContext(15 Effect.gen(function* () {16 const taken = yield* Ref.make<ReadonlyMap<string, ProjectedEvent>>(
29 unmodified lines
modified: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 */1import { Reserve } from "@repo/protocol/domain/ask";2import type {3 FrontPageEntry,4 ProjectListing,
10 unmodified lines
15import { handleKey } from "./tables.ts";1617const AskIds = Schema.fromJsonString(Schema.Array(AskId));1832/** One row of the front page query. */19const 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 lines
32type EntryRow = typeof EntryRow.Type;3334const decodeRows = Schema.decodeUnknownEffect(Schema.Array(EntryRow));3551/** One row of the projects query. */36const ProjectRow = Schema.Struct({37 landed_at: Schema.NullOr(Schema.DateTimeUtcFromString),38 open_asks: Schema.Int,39 posture: Posture,
3 unmodified lines
43type ProjectRow = typeof ProjectRow.Type;4445const decodeProjectRows = Schema.decodeUnknownEffect(Schema.Array(ProjectRow));4663// 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.48const CreditRow = Schema.Struct({49 ...CreditSummary.fields,50 project: ProjectKey,51});
77 unmodified lines
129 Effect.map((rows) => Arr.getSomes(rows.map(listingOf))),130 Effect.orDie131 );132150 // 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 lines
modified: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.6import { keyOf, nameOfKey, ProjectKey } from "@repo/protocol/ids";7import type { ProjectName } from "@repo/protocol/ids";8import { Posture } from "@repo/protocol/posture";9import {
13 unmodified lines
23 StandingEntry,24 StandingPosturesApi,25} from "../standing-posture.ts";2639/** A row as `standing_postures` holds it. */27const Row = Schema.Struct({28 moves_at: Schema.NullOr(Schema.DateTimeUtcFromString),29 posture: Posture,30 project: ProjectKey,
1 unmodified line
32});3334const decodeRow = Schema.decodeUnknownOption(Row);3549/** An entry as the row it is written as, one element of the JSON parameter. */36const 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});4257/** A row read back as an entry; `moves_at` only when it is set. */43const entryOf = ({44 moves_at: movesAt,45 posture,46 seen,47}: typeof Row.Type): StandingEntry =>48 movesAt === null ? { posture, seen } : { posture, seen, until: movesAt };4965/** `statement`'s rows, or `missed` and a warning when it fails. */50const orMissed = <A>(51 statement: Effect.Effect<A, SqlError>,52 missed: A,53 warning: string
74 unmodified lines
modified: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 */1import { TypeId } from "@effect/sql-d1/D1Client";2import type { D1Client } from "@effect/sql-d1/D1Client";3import { ProjectEvent } from "@repo/protocol/domain/event";4import type { LandingView } from "@repo/protocol/domain/landing";
27 unmodified lines
32);3334const decodeCursors = Schema.decodeUnknownEffect(Cursors);3579/**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.37const isD1 = (client: SqlClient): client is D1Client => TypeId in client;3839const bySeq = Order.mapInput(40 Order.Tuple([Order.String, Order.Number]),41 ({ event, project }: ProjectedEvent) => [project, event.seq] as const42);4391/** Each project, with the last event the rows carry for it. */44const lastOf = (events: readonly ProjectedEvent[]) =>45 new Map(events.map(({ event, project }) => [project, event.seq]));4695/**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 */47const creditedOn = (landing: Pick<LandingView, "credits">) =>48 Array.dedupeWith(49 landing.credits.map(({ handle, role }) => ({50 person: handleKey(handle),
7 unmodified lines
58 Projection,59 Effect.gen(function* () {60 const sql = yield* SqlClient;61117 /** 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 line
67 : sql.withTransaction(Effect.all(statements));6869 const posturesFound = yield* Ref.make(false);70127 /**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 lines
8182 return tables.length > 0;83 });84144 /** 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}`;87148 /**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);93158 // 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);96161 /** 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 lines
112 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}`;115181 /**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 lines
175176 return [listed, ...changes];177 };178250 /** 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`;183184 const cursorsOf = (projects: readonly ProjectName[]) =>185 sql`SELECT project, seq FROM cursor WHERE ${sql.in("project", projects.map(keyOf))}`;186259 /**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 lines
modified: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 */1import type { Handle } from "@repo/protocol/ids";221/**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. */4export const handleKey = (handle: Handle): string => handle.toLowerCase();56/** Must equal `apps/platform/migrations/0001_front_page.sql`; the projection's test checks it. */7export 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 lines
29 seq INTEGER NOT NULL30);31`;3254/**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. */34export 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 lines
67 NULL68FROM cursor;69`;70113/**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. */72export 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 that
13 unmodified lines
modified: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 */1import type { ProjectName } from "@repo/protocol/ids";2import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";3import { Context, Effect, Layer, Option, SynchronizedRef } from "effect";4
16 unmodified lines
21 const made = yield* SynchronizedRef.make<22 ReadonlyMap<ProjectName, ProjectApi>23 >(new Map());2431 /** 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 lines
modified: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 */1import type { ProjectName } from "@repo/protocol/ids";2import { Effect, Layer, Ref } from "effect";34import { StandingPostures } from "../standing-posture.ts";
1 unmodified line
6 StandingEntry,7 StandingPosturesApi,8} from "../standing-posture.ts";914/** A fresh, empty store each time the layer is built. */10export const StandingPosturesMemory = Layer.effect(11 StandingPostures,12 Effect.gen(function* () {13 const kept = yield* Ref.make<ReadonlyMap<ProjectName, StandingEntry>>(
23 unmodified lines
modified: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 */1import { commandFor } from "@repo/checks/kinds";2import { CheckSpec } from "@repo/protocol/domain/check";3import type { RunBlock } from "@repo/protocol/domain/run";4import {
20 unmodified lines
25 AdmissionReport,26 HeldBackJob,27} from "../visibility-port.ts";2855/**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 */29export const PushedCheck = Schema.Struct({30 ...SealedCheck.fields,31 clause: Schema.optionalKey(SealedCheck.fields.clause),32});3334export type PushedCheck = typeof PushedCheck.Type;3567/** A layer's manifest as pushed: its checks may leave out their clause. */36export const PushedManifest = Schema.Struct({37 ...LayerManifest.fields,38 checks: Schema.Array(PushedCheck),39});4041export type PushedManifest = typeof PushedManifest.Type;4275/** One file a layer commit holds: its blob id and its bytes. */43export interface LayerFile {44 readonly blob: BlobSha;45 readonly content: Uint8Array;46}4781/** One file a known-bad commit lays over main for its run. */48export interface OverlayFile {49 readonly content: Uint8Array;50 readonly path: RepoPath;51}5287/** What a layer push's admission is planned from. */53export 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}65109/** An area admission refused, and the run counts the deciders see why by. */66export 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}74122/** The ledger entry an admitted area earns. */75export type Admitted = Extract<LedgerEntry, { readonly _tag: "Admitted" }>;76125/**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 */77export interface AdmissionResult {78 readonly admitted: readonly Admitted[];79 readonly refused: readonly AdmissionRefused[];80}81135/** The counts a plan carries when the policy asks for no admission (and no run is planned): the defaults. */82const osrDefaults = { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 } as const;83138/** A suite's checks in order: by area, then path. */84const byAreaThenPath = Order.combine(85 Order.mapInput(Order.String, (check: PushedCheck) => check.area),86 Order.mapInput(Order.String, (check: PushedCheck) => check.path)87);88144/**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 */89const suiteIn = (90 manifest: PushedManifest,91 policy: SealedChecks,92 holds: (path: string) => boolean
4 unmodified lines
97 ),98 byAreaThenPath99 );100160/** One area's checks as (path, blob), to tell which the push added or rewrote. */101const blobsIn = (102 checks: readonly PushedCheck[],103 area: AreaName,104 blobOf: (path: string) => Option.Option<BlobSha>
8 unmodified lines
113 })114 )115 );116177/** The runs that admit a layer push's checks; `UnstatedRequirement` for a check that cites no clause. */117export const planAdmission = (118 input: AdmissionInput119): Result.Result<AdmissionPlan, UnstatedRequirement> => {120 const fileOf = (path: string) =>
14 unmodified lines
135 onSome: (previous) =>136 suiteIn(previous, input.policy, (path) => input.landed.has(path)),137 });138200 /**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 lines
156 const { admit } = input.policy;157158 const sealedPaths = new Set(suite.map(({ path }) => path));159225 /** 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 lines
228 runs,229 });230};231298/** A run's identity within its plan: its area, and main's attempt or the known-bad tree. */232const runKey = (run: AdmissionRun) =>233 AdmissionRun.match(run, {234 OnKnownBad: ({ area, tree }) => `${area}\u0000bad\u0000${tree}`,235 OnMain: ({ area, attempt }) => `${area}\u0000main\u0000${attempt}`,236 });237305/**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 */238export const judgeAdmission = (239 plan: AdmissionPlan,240 results: AdmissionReport["results"],241 now: DateTime.Utc
1 unmodified line
243 const reported = new Map(244 results.map(({ areas, run }) => [runKey(run), areas] as const)245 );246320 /** 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 lines
modified: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 */1import type { HeldBackResult } from "@repo/protocol/domain/answer";2import type { SealedChecks } from "@repo/protocol/domain/visibility";3import { AreaName, sameHandle } from "@repo/protocol/ids";4import type { AskId, Handle, SuiteRoot } from "@repo/protocol/ids";
4 unmodified lines
9import type { AttemptRow } from "../project-store/rows.ts";1011const DAY = 86_400_000;1223/** The Monday, 00:00 UTC, that starts the ISO week `at` falls in. */13const mondayOf = (at: DateTime.Utc) =>14 DateTime.startOf(at, "week", { weekStartsOn: 1 });1527/** The ISO week a moment falls in, as attempts are counted by: `2026-W41`, in UTC. */16export 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 lines
2728 return `${year}-W${String(week).padStart(2, "0")}`;29};3043/** When the ISO week `at` falls in ends: the next Monday, 00:00 UTC. */31export const weekEnds = (at: DateTime.Utc): DateTime.Utc =>32 DateTime.add(mondayOf(at), { days: 7 });3347/** Whether one more failure may be judged, and when the counts that stop it reset. */34export interface AttemptsLeft {35 readonly ok: boolean;36 readonly resetsAt: Option.Option<DateTime.Utc>;37}3853/**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 */39export const attemptsLeft = (input: {40 readonly claimCount: number;41 readonly weekCount: number;42 readonly policy: SealedChecks["attempts"];
8 unmodified lines
51 resetsAt: ok ? Option.none() : Option.some(weekEnds(input.now)),52 };53};5475/** A held-back run, judged: its refusals, the trailer's value when none, and the attempts it counted. */55export interface AttemptsJudged {56 readonly attempts: readonly AttemptRow[];57 readonly refusals: readonly (AttemptsExhausted | HeldBackFailed)[];58 readonly trailer: Option.Option<string>;59}6082/**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 */61export const judgeAttempts = (input: {62 readonly attempts: readonly AttemptRow[];63 readonly ask: AskId;64 readonly checks: SealedChecks;
93 unmodified lines
modified: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 */1import { RepoHost, Revision } from "@repo/artifacts/repo-host";2import type { EnvProxy } from "@repo/checks/check-runner";3import { Hostname } from "@repo/protocol/domain/common";4import type { Evidence } from "@repo/protocol/domain/common";
43 unmodified lines
48import type { ProjectSnapshot } from "../project-store.ts";49import type { EnvValueRow } from "../project-store/rows.ts";50import { noPlan, policyIn } from "../visibility-port.ts";5173/** The env schema's name, in the repo's root and in a package's folder. */52const schemaName = ".env.schema";5376/** The root's env schema: where the shape lives when nothing else says. */54const rootSchema = RepoPath.make(schemaName);5579/** A character that makes a path segment a glob. */56const GLOB = /[*?[{]/u;5782/**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 */58const folderOf = (glob: string): string => {59 const segments = glob60 .split("/")61 .filter((segment) => segment !== "" && segment !== ".");
4 unmodified lines
66 "/"67 );68};6999/**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 */70export const schemaFilesAt = (71 modules: readonly Territory[]72): readonly RepoPath[] =>73 Array.dedupe([
6 unmodified lines
80 })81 ),82 ]).map((path) => RepoPath.make(path));83118/** Whether `pattern` (a host, or a glob `*.example.com`) covers `host`. */84const covers = (pattern: string, host: string) =>85 pattern === host ||86 (pattern.startsWith("*.") && host.endsWith(pattern.slice(1)));87123/**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. */89const 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 : [];95135/** The hosts `key`'s value may reach in `view`: none when the view has no such item. */96const reachIn = (view: Pick<EnvSchemaView, "items">, key: EnvKey) =>97 reachOf(view.items.find((item) => item.key === key));98139/** A widened `@proxy`: the item, and every host its value may now reach. */99export interface Widened {100 readonly hosts: readonly Hostname[];101 readonly item: EnvKey;102}103145/**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 */104export const widenedProxies = (105 before: Pick<EnvSchemaView, "items">,106 after: Pick<EnvSchemaView, "items">107): readonly Widened[] =>
5 unmodified lines
113 ? [{ hosts: reach.filter(Schema.is(Hostname)), item: item.key }]114 : [];115 });116165/** One commit's env schemas, as the cache keeps them. */117class ReadAt extends Data.Class<{118 readonly at: LandedSha;119 readonly files: readonly RepoPath[];120 readonly project: ProjectName;121}> {}122172/**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 */123interface Read {124 readonly declaredIn: ReadonlyMap<EnvKey, RepoPath>;125 readonly schema: EnvSchemaFile;126}127181/** A shape with no schema in it: no items. */128const unread: Read = {129 declaredIn: new Map(),130 schema: { file: rootSchema, imports: [], items: [] },131};132187/** How many commits' shapes one project keeps read. */133const readCapacity = 16;134190/**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. */136const merged = (views: readonly EnvSchemaView[]): Read => {137 const [first] = views;138139 if (first === undefined) {
26 unmodified lines
166 },167 };168};169230/** The project's landed SHA and its row, once something landed. */170const landedIn = (snapshot: ProjectSnapshot) =>171 Option.flatMap(snapshot.project, (row) =>172 row.landed === undefined173 ? Option.none()174 : Option.some({ landed: row.landed, row })175 );176238/**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 */177const maySet = (policy: Policy, handle: Handle) => {178 const setters = policy.visibility?.env.setters ?? "deciders";179180 return setters === "deciders"181 ? isDecider(policy, handle)182 : setters.some((each) => sameHandle(each, handle));183};184251/** An item with who set its value and when, from its row: only a sensitive item has one. */185const withValue = (186 item: EnvItem,187 rows: ReadonlyMap<EnvKey, EnvValueRow>188): EnvItem => {
9 unmodified lines
198const decodeSealed = Schema.decodeUnknownEffect(199 Schema.toCodecJson(SealedValue)200);201269/** `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. */203const nonEmpty = (text: Option.Option<string>) =>204 Option.getOrUndefined(Option.filter(text, (each) => each !== ""));205273/** A proxy rule as the check job carries it (`EnvProxy`): no key for a method or path the rule leaves open. */206const onTheWire = (rule: ProxyRule): EnvProxy => {207 const method = nonEmpty(rule.method);208 const path = nonEmpty(rule.path);209
6 unmodified lines
216 ...(path !== undefined && { path }),217 };218};219288/** A host list as evidence shows it: `none` before an item had any. */220const hostsText = (hosts: readonly string[]) =>221 hosts.length === 0 ? "none" : hosts.join(", ");222292/**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 */223export const ProjectEnvLive: Layer.Layer<224 never,225 never,226 EnvSchemaParser | WriteOnlyValues | RepoHost
3 unmodified lines
230 const parser = yield* EnvSchemaParser;231 const vault = yield* WriteOnlyValues;232 const host = yield* RepoHost;233308 /** 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 lines
267 })268 )269 );270346 // 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 lines
281 Exit.isSuccess(exit) ? Duration.infinity : Duration.zero,282 }283 );284361 /** 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 lines
300 })301 ),302 });303381 /** 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 });309388 /** 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 lines
368 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 lines
430 }431432 const sealed = yield* vault.put({ acknowledgeShort, key, value });433513 // 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 lines
modified: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 */1import { Layer } from "effect";23import { ProjectEnvLive } from "./env.ts";4import { ProjectVisibilityLive } from "./state.ts";
12 unmodified lines
17 ProjectVisibilityLive,18 SaltSource,19} from "./state.ts";2029/**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 */21export 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 */1import { DecisionSubject } from "@repo/protocol/domain/decision";2import type { Decision } from "@repo/protocol/domain/decision";3import { LedgerEntry } from "@repo/protocol/domain/visibility";4import type {
10 unmodified lines
15import type { ProjectSnapshot, ProjectWrites } from "../project-store.ts";16import type { LayerRow, LedgerRow } from "../project-store/rows.ts";17import { policyIn } from "../visibility-port.ts";1830/** Each posture in GLOSSARY.md's words: how a posture still in effect is shown. */19const 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>;2639/** The number the next ledger row takes: one past the highest kept. */27export const nextSeq = (rows: readonly LedgerRow[]): number =>28 Math.max(0, ...rows.map(({ seq }) => seq)) + 1;2943/** Ledger rows as a plan writes them: the rows, and an event for each. */30export const appended = (entries: readonly LedgerEntry[]): ProjectWrites =>31 entries.length === 032 ? {}33 : {
2 unmodified lines
36 ),37 ledger: entries,38 };3954/** The visibility config a snapshot's policy holds. */40export const visibilityIn = (41 snapshot: ProjectSnapshot42): Option.Option<VisibilityPolicy> =>43 Option.flatMap(policyIn(snapshot), (policy) =>44 Option.fromUndefinedOr(policy.visibility)45 );4662/** The posture a config declares, and its label, read from the config alone. */47export const declaredBy = (visibility: Option.Option<VisibilityPolicy>) =>48 postureOf({ licence: Option.none(), visibility });4950type PostureChange = Extract<51 DecisionSubject,52 { readonly _tag: "PostureChange" }53>;5471/** A decision about a posture change, with its subject typed. */55interface Asked {56 readonly decision: Decision;57 readonly subject: PostureChange;58}
2 unmodified lines
61 DecisionSubject.guards.PostureChange(decision.subject)62 ? Option.some({ decision, subject: decision.subject })63 : Option.none();6482/**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 */65const takesEffect = (decision: Decision, noticeDays: number) =>66 Option.map(67 Option.filter(68 Option.fromUndefinedOr(decision.decided),
2 unmodified lines
71 ({ at }) =>72 DateTime.max(at, DateTime.add(decision.openedAt, { days: noticeDays }))73 );7496/** The posture in effect, and the decision that put it there or keeps it waiting. */75export 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}85110/**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. */87export const standing = (input: {88 readonly decisions: readonly Decision[];89 readonly now: DateTime.Utc;90 readonly visibility: Option.Option<VisibilityPolicy>;
39 unmodified lines
130 }),131 });132};133168/**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 */134export const nextMove = (input: {135 readonly decisions: readonly Decision[];136 readonly now: DateTime.Utc;137 readonly visibility: Option.Option<VisibilityPolicy>;
13 unmodified lines
151 Option.filter((at) => DateTime.isGreaterThan(at, input.now))152 );153};154196/**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. */156export const sealedInEffect = (posture: Standing) =>157 posture.posture !== "open" || posture.declared === "open";158203/**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 */159export const postureCaughtUp = (160 snapshot: ProjectSnapshot,161 posture: Standing,162 seq: number
16 unmodified lines
179 }),180 ],181 });182232/** Each declared layer with the repo the project keeps for it, when it has one. */183const withRepos = (184 visibility: VisibilityPolicy,185 rows: readonly LayerRow[]186): VisibilityPolicy => ({
8 unmodified lines
195 )196 ),197});198249/**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. */200export const ledgerFor = (201 project: ProjectName,202 snapshot: ProjectSnapshot,203 now: DateTime.Utc
20 unmodified lines
modified: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 */1import { ObjectId, Revision } from "@repo/artifacts/repo-host";2import type { RepoExists } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { commandFor } from "@repo/checks/kinds";
71 unmodified lines
76 standing,77 visibilityIn,78} from "./ledger.ts";79108/** Where a commitment's secret salt comes from: 32 random bytes each time. */80export class SaltSource extends Context.Service<81 SaltSource,82 { readonly next: Effect.Effect<Uint8Array> }83>()("project/SaltSource") {}84114/**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 */85export class AdmissionStarts extends Context.Service<86 AdmissionStarts,87 {88 readonly start: (input: {
3 unmodified lines
92 }) => Effect.Effect<void>;93 }94>()("project/AdmissionStarts") {}95129/**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 */96export const manifestPath = RepoPath.make(`${Brand.configDir}/layer.json`);97135/** The effects this port's plans ask for, settled after their commit. */98const Planned = Schema.Union([99 Schema.TaggedStruct("Provision", { repo: RepoName }),100 Schema.TaggedStruct("Admit", {101 head: CommitSha,
9 unmodified lines
111const encodePlanned = Schema.encodeEffect(PlannedJson);112113const decodePlanned = Schema.decodeUnknownEffect(PlannedJson);114153// 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.116const decodeManifest = Schema.decodeUnknownEffect(117 Schema.fromJsonString(PushedManifest)118);119159/** The repo a declared layer keeps in the private namespace. */120const repoFor = (project: ProjectName, layer: LayerName) =>121 RepoName.make(`${keyOf(project)}--${layer}`);122163/**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 */123const ownsRepo = (layer: LayerDeclaration) =>124 layer.audience !== "personal" && layer.audience !== "security";125171/** The people a rule names: the project's deciders, for any path, or those listed. */126const membersOf = (policy: Policy, members: Members): readonly Handle[] =>127 members === "deciders"128 ? policy.deciders.flatMap(({ handles }) => handles)129 : members;
9 unmodified lines
139 Order.String,140 (file: { readonly path: RepoPath }) => file.path141);142189/** The areas a suite reports, sorted by name. */143const areasOf = (checks: SealedChecks) =>144 Arr.sort(Object.keys(checks.areas), Order.String).map((area) =>145 AreaName.make(area)146 );147195/** One sealed check as a layer commit holds it: its file, its area, its blob and its author. */148interface Sealed extends SuiteFile {149 readonly author: Handle;150}151200/** The project's name, from its row. */152const projectOf = (snapshot: ProjectSnapshot) =>153 Option.map(snapshot.project, ({ project }) => project);154204/** A declared layer that keeps a repo, by name. */155const 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 );162213/** The sealed checks a layer holds, when the policy keeps them in it. */163const checksIn = (164 visibility: Option.Option<VisibilityPolicy>,165 layer: LayerName166) =>
1 unmodified line
168 Option.flatMap(visibility, ({ checks }) => Option.fromUndefinedOr(checks)),169 (checks) => checks.layer === layer170 );171223/** The project's row for a layer, or a new one for its repo. */172const rowFor = (173 snapshot: ProjectSnapshot,174 project: ProjectName,175 layer: LayerName
2 unmodified lines
178 Arr.findFirst(snapshot.layers, ({ name }) => name === layer),179 () => ({ name: layer, repo: repoFor(project, layer) })180 );181234/**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. */183const narrowingDecision = (input: {184 readonly after: Policy;185 readonly from: Posture;186 readonly landedBy: readonly Handle[];
48 unmodified lines
235 }),236 });237};238297/** A plan of rows and the effects to settle after them. */239const planOf = (240 writes: ProjectWrites,241 effects: readonly VisibilityEffect[] = []242): VisibilityPlan => ({ effects, writes });243303/** A planned effect, as a plan carries it. */244const effectOf = (id: string, planned: Planned) =>245 Effect.map(246 Effect.orDie(encodePlanned(planned)),247 (body): VisibilityEffect => ({ body, id })248 );249310/** The `PostureChanged` row a narrowing that took effect still owes the ledger, numbered from `seq`. */250const caughtUp = (251 snapshot: ProjectSnapshot,252 visibility: Option.Option<VisibilityPolicy>,253 now: DateTime.Utc
3 unmodified lines
257 standing({ decisions: snapshot.decisions, now, visibility }),258 nextSeq(snapshot.ledger)259 );260322/** How far `who` reaches into a layer of the project's policy. */261const reach = (262 policy: Policy,263 layer: LayerDeclaration,264 who: Principal
4 unmodified lines
269270 return names(membersOf(policy, layer.readers), who) ? "read" : "none";271};272335/** One held-back run of a claim's answer, judged against its attempts (`./claims.ts`). */273const judgeHeldBack: VisibilityPort["judgeHeldBack"] = (input, snapshot) => {274 const checks = Option.flatMap(visibilityIn(snapshot), ({ checks: sealed }) =>275 Option.fromUndefinedOr(sealed)276 );
18 unmodified lines
295 writes: judged.attempts.length === 0 ? {} : { attempts: judged.attempts },296 };297};298362/** A read of a layer through the gateway, for its readers' log. */299const recordRead: VisibilityPort["recordRead"] = (input) => ({300 layerReads: [301 {302 at: input.at,
6 unmodified lines
309 },310 ],311});312377/** How far `who` reaches into a declared layer that keeps a repo. */313const 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 );320386/** The layers `who` reads: the write-down guard runs only for these. */321const readableLayers: VisibilityPort["readableLayers"] = (who, snapshot) =>322 new Set(323 Option.match(policyIn(snapshot), {324 onNone: () => [],
5 unmodified lines
330 ),331 })332 );333400/**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 */334const onPolicy: VisibilityPort["onPolicy"] = (input, snapshot) =>335 Effect.gen(function* () {336 const project = projectOf(snapshot);337 const after = Option.fromUndefinedOr(input.after.visibility);
8 unmodified lines
346 ) {347 return noPlan;348 }349422 // 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 lines
376 const provisions = yield* Effect.forEach(fresh, ({ repo }) =>377 effectOf(`provision:${repo}`, Planned.cases.Provision.make({ repo }))378 );379453 // 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);382383 const to = declaredBy(after);384
25 unmodified lines
410const 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;416417 const nowOf = () => DateTime.makeUnsafe(clock.currentTimeMillisUnsafe());418494 // ------------------------------------------------------- layer commits495496 /** 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 );426505 /** 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 lines
454455 return blobs;456 });457537 /** 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 lines
480481 return manifest;482 });483564 /**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 lines
530 byPath531 );532 });533621 /**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 lines
585 ],586 } satisfies ProjectWrites;587 });588681 // ------------------------------------------------------------ the port682683 /**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 lines
695 suite,696 });697 });698797 /** 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 line
704 onSome: Effect.succeed,705 })706 );707807 /**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 lines
734 )735 );736 });737843 /**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 lines
776 row.landedSha === undefined777 ? Option.none<PushedManifest>()778 : yield* manifestAt(row.repo, row.name, row.landedSha);779890 // 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 lines
847 Effect.gen(function* () {848 const project = projectOf(snapshot);849 const visibility = visibilityIn(snapshot);850962 // 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 lines
864 }865866 const row = rowFor(snapshot, project.value, input.layer);867981 // The same push heard again changes nothing.868 if (row.landedSha === input.head || row.proposed === input.head) {869 return noPlan;870 }871872 const owed = caughtUp(snapshot, visibility, input.now);873 const checks = checksIn(visibility, input.layer);874 const admits = Option.exists(checks, ({ admit }) => admit !== undefined);875990 // 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 lines
911 start912 );913 });9141030 // 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;9231040 /**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 lines
941942 const judged = judgeAdmission(planned.value, input.results, input.now);943 const areas = Arr.dedupe(planned.value.runs.map(({ area }) => area));9441070 // 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.refused
23 unmodified lines
972 : []973 )974 );9751102 // 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 lines
994 ...appended([...owed, ...published, ...admitted]),995 });996 });9971125 /** 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 lines
10531054 return port;1055});10561185/**1186 * The live `ProjectVisibility`, over the private namespace's repos, a salt1187 * source (WebCrypto at the platform's edge) and what starts admissions.1188 */1057export const ProjectVisibilityLive: Layer.Layer<1058 never,1059 never,1060 AdmissionStarts | LayerRepos | SaltSource
1 unmodified line
modified: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 */1import { Context } from "effect";2import type { DateTime, Effect } from "effect";34export 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 */1import { CheckLane } from "@repo/checks/check-runner";2import {3 HeldBackResult,4 LaneResult,
28 unmodified lines
33import type { LandingCommand, LandingEffect } from "./landing.ts";3435const Attempt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));3649/**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 */37export const ReportedCommand = Schema.TaggedUnion({38 Blocked: { attempt: Attempt },39 Busy: { attempt: Attempt },40 Checked: {
8 unmodified lines
49 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});6078/**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 */61export 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});6790/** What `advanceAnswer` returns, as it crosses a boundary: `Advanced`. */68export const Steps = Schema.Struct({69 effects: Schema.Array(NextStep),70 outcome: Outcome,71});7296/** A ratchet's count in one territory, as a check of a tree measured it. */73export const MeasuredCount = Schema.Struct({74 count: Attempt,75 ratchet: RatchetName,76 territory: Schema.NonEmptyString,77});7879export type MeasuredCount = typeof MeasuredCount.Type;80105/**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 */81export 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});103104export type AnswerRun = typeof AnswerRun.Type;105158/**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. */107export 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 );113170/**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 */114export 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});122123export type AnswerReport = typeof AnswerReport.Type;124188/** A landing effect the answer's run carries out: a port call, or a retry to wait for. */125export type RunnableEffect = Extract<126 LandingEffect,127 { readonly _tag: NextStep["_tag"] }128>;129130type NextStep = typeof NextStep.Type;131196/**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 */132export interface Advanced {133 readonly effects: readonly RunnableEffect[];134 readonly outcome: Outcome;135}136206/**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 */137export interface AnswerQueue {138 readonly advanceAnswer: (139 requestId: RequestId,140 command: LandingCommand,
1 unmodified line
142 ) => 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}151232/**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. */153export class AnswerRuns extends Context.Service<154 AnswerRuns,155 {156 readonly start: (
5 unmodified lines
modified: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 */1import { ClaimView } from "@repo/protocol/domain/claim";2import type { Policy } from "@repo/protocol/domain/policy";3import {4 AskId,
18 unmodified lines
23import { Array as Arr, Data, DateTime, Option, Result, Schema } from "effect";2425import { ProjectEventInput } from "./events.ts";2633/** What a claim holds while it lasts, and keeps once it ends. */27const 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};3749/**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 */38export 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});4647export type ClaimState = typeof ClaimState.Type;4869/** A claim's fields, which `Live` and `Warned` hold and the ended states keep. */49export type Live = Omit<typeof ClaimState.cases.Live.Type, "_tag">;5072/**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 */51export 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 lines
60 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});6970export type ClaimCommand = typeof ClaimCommand.Type;71104/** What the project service does after a transition, in order. */72export 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}>;7879export const ClaimEffect = Data.taggedEnum<ClaimEffect>();80116/** Every way the claim lifecycle says no. */81export type ClaimRefusal =82 | AskBlocked83 | AskFull84 | CapReached
1 unmodified line
86 | Denounced87 | NotClaimed88 | NotVouched;89126/** A transition's result: the next state and the effects that settle it. */90export interface ClaimStep {91 readonly effects: readonly ClaimEffect[];92 readonly state: ClaimState;93}94132/** What `transition` returns: a step, or the refusal that changes nothing. */95export type ClaimResult = Result.Result<ClaimStep, ClaimRefusal>;96135/** The state as it is, with nothing to settle: how a repeated command converges. */97const stay = (state: ClaimState): ClaimResult =>98 Result.succeed({ effects: [], state });99100const move = (101 state: ClaimState,102 ...effects: readonly ClaimEffect[]103): ClaimResult => Result.succeed({ effects, state });104144/** A claim's own fields, whatever state holds them. */105const claimOf = ({106 ask,107 base,108 claimant,
12 unmodified lines
121 openedAt,122 warnsAt,123});124165/** When a claim quiet since `from` is warned, and when it lapses. */125const deadlines = (from: DateTime.Utc, policy: Policy["claims"]) => ({126 lapsesAt: DateTime.add(from, { milliseconds: policy.lapseAfterMs }),127 warnsAt: DateTime.add(from, { milliseconds: policy.warnAfterMs }),128});129130type Claim = typeof ClaimCommand.cases.Claim.Type;131173/**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.133const grant = (134 ask: AskId,135 made: Claim,136 now: DateTime.Utc,
49 unmodified lines
186 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 lines
201 Warned: holder,202 });203};204251/** Whoever holds no live claim on the ask. */205const unclaimed = ({ ask }: { readonly ask: AskId }) =>206 Result.fail(NotClaimed.of(ask));207208const push = (
1 unmodified line
210 { 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 lines
299 })300 )301 : Result.fail(NotClaimed.of(live.ask));302351 // 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 lines
314 Warned: end,315 });316};317367/**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 */318const 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 lines
334 Warned: revoked,335 });336};337392/**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 */338export const transition = (339 state: ClaimState,340 command: ClaimCommand,341 now: DateTime.Utc,
6 unmodified lines
348 Release: ({ who }) => release(state, who, now),349 Tick: () => tick(state, now),350 });351412/** Where the claim's fork is served and what to run, for the claim's view. */352export 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}357421/**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 */358export const toView = (359 state: ClaimState,360 context: ViewContext361): Option.Option<ClaimView> => {
34 unmodified lines
modified: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 */1import { Context, Effect, Option } from "effect";23/** A store of text by key, whose every failure reads as a miss. */4export 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}823/** The longest key a store takes, in UTF-8 bytes: R2's limit. */9export const MAX_KEY_BYTES = 1024;1026/**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. */12export 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 lines
modified: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 */1import type { RepoHost } from "@repo/artifacts/repo-host";2import type {3 CommitDiff,4 CommitView,
28 unmodified lines
33import { listing } from "./code/tree.ts";34import { whyView } from "./code/why.ts";35import type { ProjectApi } from "./project.ts";3648/** What the code reads take from a project's record, beside its canonical repo. */37export 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}4863/** The code reads' view of `project`, through its `ProjectApi`. */49export const codeProjectOf = (50 api: ProjectApi,51 project: ProjectName52): CodeProject => ({
3 unmodified lines
56 project,57 repo: RepoName.make(keyOf(project)),58});5975/** Main's landed commit, its tags peeled and sorted newest first, and its forks. */60export const refsOf = (61 project: CodeProject62): Effect.Effect<RefsView, never, RepoHost> => refsView(project);6380/** One folder at `at` (main when none), folders first, with its README. */64export 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);7088/** Every file path at `at`, up to the cap. */71export const pathsOf = (72 project: CodeProject,73 at: Option.Option<Rev>74): Effect.Effect<PathList, UnknownRevision, RepoHost> => pathList(project, at);7594/** One file at `at`: its text, or that it is binary or too large. */76export const fileOf = (77 project: CodeProject,78 at: Option.Option<Rev>,79 path: RepoPath80): Effect.Effect<FileView, UnknownRevision | UnknownPath, RepoHost> =>81 fileView(project, at, path);82102/** A page of first-parent commits from `at`, each landing with its record. */83export const logOf = (84 project: CodeProject,85 input: {86 readonly at: Option.Option<Rev>;
6 unmodified lines
93 UnknownRevision,94 RepoHost95> => logPage(project, input);96117/** One commit and the files it changed against its first parent. */97export const commitOf = (98 project: CodeProject,99 sha: CommitSha100): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>101 commitDiff(project, sha);102124/** Why each line of a file at `at` is there. */103export const whyOf = (104 project: CodeProject,105 at: Option.Option<Rev>,106 path: RepoPath
2 unmodified lines
modified: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 */1import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";2import { Brand } from "@repo/brand";3import { CheckLane } from "@repo/checks/check-runner";4import type { CheckRunner } from "@repo/checks/check-runner";
119 unmodified lines
124 OutboxRow,125 ProjectRow,126} from "./project-store/rows.ts";127147/**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. */129export const envSchemaMethod = "envShape";130154/** The decider-facing methods of one project's service. */131export 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 lines
146 ) => 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 lines
158 ) => 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 line
180 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 lines
194 ) => 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 lines
209 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 lines
234 }235 ) => Effect.Effect<{ readonly landed: LandedSha }, NotDecider | StaleBase>;236}237308/** What a project holds that the decider-facing methods read, at a call's start. */238export interface DeciderState {239 readonly answers: readonly {240 readonly record: {241 readonly landing: LandingState;
13 unmodified lines
255 readonly project: Option.Option<ProjectRow>;256 readonly proposals: readonly Proposal[];257}258330/** What a decider-facing call writes, beside what the core loop writes. */259export 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 line
265 readonly project: Map<"row", ProjectRow>;266 readonly proposals: Map<ProposalId, Proposal>;267}268342/** An ask to open from its files, red first, as `openAsk` or an accepted proposal does. */269export 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}277355/** The refusals opening an ask can give. */278export type OpenRefusal =279 | NotDecider280 | NotRedFirst281 | WeakCheck
1 unmodified line
283 | TouchedJudge284 | VerifierBlocked285 | StaleBase;286365/** The refusals waiting lifts: the call that met one fails, and is tried again. */287export type WaitRefusal = VerifierBlocked | StaleBase;288368/** The refusals opening an ask gives that waiting does not lift. */289type FinalOpenRefusal = Exclude<OpenRefusal, WaitRefusal>;290371/** A refusal that declines the proposal whose ask met it. */291const declines = (refusal: FinalOpenRefusal) => Effect.succeedSome(refusal);292374/** The ports the decider-facing methods call, besides the store. */293export type DeciderPorts = CheckRunner | Lander | RepoHost;294377/**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 */295export 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 lines
312 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 line
321 ) => 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 lines
340 body: (h: H, writes: W, now: DateTime.Utc) => Effect.Effect<A, E>341 ) => Effect.Effect<A, E>;342}343439// ------------------------------------------------------------ pure helpers440344const mainRef = "refs/heads/main";345346const mainRefName = RefName.make(mainRef);347445/** The config folder, as a path prefix. */348const configFolder = `${Brand.configDir}/`;349448/** How many steps a decider's land takes at most: merges, checks and lands, with re-merges. */350const landTurns = 16;351451/** Whether `handle` decides for any paths in the project. */352export const isDecider = (policy: Policy, handle: Handle) =>353 policy.deciders.some(({ handles }) =>354 handles.some((each) => sameHandle(each, handle))355 );356457/**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 */357export 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));362468/** The handle as the policy spells it among its deciders: how decisions name them. */363const asDecider = (policy: Policy, handle: Handle): Option.Option<Handle> =>364 Array.findFirst(365 policy.deciders.flatMap(({ handles }) => handles),366 (each) => sameHandle(each, handle)367 );368475/** A table's rows as this call has them: written ones in place of hydrated ones, new ones after. */369const overlaid = <K, V extends { readonly id: K }>(370 rows: readonly V[],371 written: ReadonlyMap<K, V>372): readonly V[] => [
2 unmodified lines
375 (row) => !rows.some(({ id }) => id === row.id)376 ),377];378486/** The next id of a project's sequence: `prop-000001` after none taken. */379const minted = (prefix: string, taken: number) =>380 `${prefix}-${String(taken + 1).padStart(6, "0")}`;381490/** A person's working fork, `<project>--me--<handle in lowercase>`. */382const workingFork = (project: ProjectName, handle: Handle) =>383 RepoName.make(`${keyOf(project)}--me--${handle.toLowerCase()}`);384494/** The module a proposal's territory names: by its name, or by its folder. */385const 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 );392503/**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 */393export const pathsOf = (394 policy: Policy,395 files: readonly RepoPath[],396 territory: Option.Option<string>
6 unmodified lines
403 onSome: ({ paths }) => paths.map((glob) => RepoPath.make(glob)),404 }),405 });406523/**524 * Who decides on `paths`: their deciders, else the project's own (`**`),525 * else its initializer. A decision always has someone.526 */407export const decidersOn = (408 policy: Policy,409 paths: readonly RepoPath[],410 initializer: Handle
8 unmodified lines
419};420421const proposedLabel = "want";422543/** The evidence line that names the model a proposal's files were drafted by. */423const draftedByLabel = "drafted by";424546/** The platform's drafter, as the landing of an ask it drafted discloses it. */425export const drafterOf = (model: string): AgentTrailer => ({426 harness: `${Brand.cli}-drafter`,427 model,428 verified: true,429});430553/**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 */431const 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 );438566/**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 */439const evidenceOf = (input: {440 readonly files: readonly ComposedFile[];441 readonly sealed: boolean;442 readonly territory: Option.Option<string>;
17 unmodified lines
460 ]461 : []),462];463596/** The files a proposal holds, read back from its decision's evidence by path. */464const filesOf = (465 proposal: Proposal,466 evidence: readonly Evidence[]467): readonly ComposedFile[] =>
9 unmodified lines
477const askFolder = `${configFolder}asks/`;478479const askSuffix = ".ask.ts";480614/** The ask a proposal's files open: the one whose ask file they hold. */481export 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 line
486 )487 : Option.none()488 );489624/** When a person claimed. */490interface FirstClaim {491 readonly at: DateTime.Utc;492 readonly handle: Handle;493}494630/** Each person's first claim in the project, for Today's newcomers. */495const firstClaimsOf = (claims: DeciderState["claims"]): readonly FirstClaim[] =>496 Array.dedupeWith(497 Array.sort(498 claims.flatMap(({ row, state }): FirstClaim[] =>
17 unmodified lines
516 Match.tag("StaleBase", (stale) => Option.some(stale)),517 Match.orElse(() => Option.none())518 );519656/** A decision's subject an answer waits on, if it is one. */520const answerDecisionOf = (subject: DecisionSubject) =>521 Schema.decodeUnknownOption(Schema.toType(AnswerDecision))(subject);522660/** A commit message's first line as its subject, the rest as its body. */523const messageParts = (message: string) => {524 const [subject = "", ...rest] = message.trim().split("\n");525526 return { body: rest.join("\n").trim(), subject: subject.trim() };527};528667/** `message` with one more trailer in its trailer block, which `formatLanding` always ends with. */529const withTrailer = (message: string, key: string, value: string) =>530 `${message}${key}: ${value}\n`;531671/**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 */532const vouchedText = (533 text: string,534 input: {535 readonly handle: Handle;
22 unmodified lines
558559 return `${[...lines, `${sign}${input.handle}${note}`].join("\n")}\n`;560};561706/** git's zero id: the `before` of a push that created its ref. */562const zeroId = CommitSha.make("0".repeat(40));563709/**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 */564export const strayDecision = (input: {565 readonly after: CommitSha;566 readonly before: Option.Option<CommitSha>;567 readonly id: DecisionId;
15 unmodified lines
583 ref: RefNameText.make("refs/heads/main"),584 }),585 });586739/** The id a project's next decision takes, after the ones `h` and `writes` hold. */587export const nextDecisionId = (588 decisions: readonly Decision[],589 written: ReadonlyMap<DecisionId, Decision>590) => DecisionId.make(minted("dec", overlaid(decisions, written).length));591745/** The deadlines a project's proposals and decisions set its alarm to: each open one's expiry. */592export const deciderDeadlines = (h: DeciderState): readonly DateTime.Utc[] => [593 ...h.proposals.flatMap(({ expiresAt, state }) =>594 state === "open" ? [expiresAt] : []595 ),
1 unmodified line
597 decided === undefined ? [expiresAt] : []598 ),599];600755/** A vouch a decision said yes to that did not land: logged, the decision stands. */601const unlanded = (handle: Handle, refused: NotDecider | StaleBase) =>602 Effect.logWarning(`the vouch for ${handle} did not land`, refused);603759/** Who may have a proposal drafted again: its proposer, or a decider of its paths. */604const mayDraft = (605 policy: Policy,606 row: ProjectRow,607 proposal: Proposal,
5 unmodified lines
613 pathsOf(policy, proposal.files, Option.fromUndefinedOr(proposal.territory)),614 row.initializer615 ).some((each) => sameHandle(each, handle));616773/** The events among `effects`, written; the alarm is set once settled, from every deadline. */617const emitted = (618 writes: DeciderWrites,619 effects: readonly AttentionEffect[]620) => {
3 unmodified lines
624 }625 }626};627785// ------------------------------------------------------------ the bodies786787/**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 */628export const deciders = <H extends DeciderState, W extends DeciderWrites>(629 kernel: DeciderKernel<H, W>630) => {631 const { name, repo } = kernel;632797 /** 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 line
638 ? Option.some({ landed: row.landed, policy, row })639 : Option.none()640 );641807 /** 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.project
4 unmodified lines
650651 const decisionsNow = (h: H, writes: W) =>652 overlaid(h.decisions, writes.decisions);653820 /** 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 lines
664665 writes.budgetDays.set(`${row.day}|${row.decider}`, row);666 };667835 /** 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 lines
688 );689 }690 });691860 /** 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 lines
705 ),706 Effect.orElseSucceed(() => "")707 );708878 // ---------------------------------------------------------- proposals879880 /** 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 lines
738739 return { proposal: proposed.proposal };740 };741914 /**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 lines
795796 return { proposal };797 });798976 /** 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);801980 /** 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 lines
833 proposal,834 });835 });8361016 /**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 lines
936937 writes.decisions.set(decision.id, decision);938 });9391129 /** 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 lines
962 proposal: found.value,963 };964 });9651156 /** 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 lines
1030 now1031 )1032 );10331225 // 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 lines
1109 row,1110 });1111 });11121305 // ---------------------------------------------------------- landings13061307 /**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 lines
11801181 return landed.sha;1182 });11831382 /**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 lines
1228 prefix: "vouch",1229 });1230 });12311434 /**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 lines
1274 : [{ handle: input.by, role: "Decided-by" }];12751276 const requestId = RequestId.make(`revert-${after}`);12771485 // The stray commit is main's tip, and the revert's parent.1278 const main = LandedSha.make(after);12791280 const message = withTrailer(1281 formatLanding({
46 unmodified lines
1328 now1329 );1330 });13311540 /**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 lines
1363 )1364 : Effect.void;1365 };13661579 // ---------------------------------------------------------- answers15801581 /** 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 lines
13861387 return advanced;1388 });13891605 /** 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 );13961613 /** 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 lines
1428 ),1429 { discard: true }1430 );14311649 /** 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 lines
1458 ),1459 }1460 );14611680 // ---------------------------------------------------------- decisions16811682 /**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 lines
1533 state: Option.isSome(refused) ? "declined" : "accepted",1534 });1535 });15361767 /** 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 lines
1567 ),1568 Waiver: () => Effect.void,1569 });15701802 /**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 lines
16451646 return { decision: taken.decision };1647 });16481885 /**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 lines
1679 { discard: true }1680 );1681 });16821924 // ---------------------------------------------------------- finish19251683 const finishBody =1684 (caller: Person, input: Parameters<DeciderApi["finish"]>[1]) =>1685 (h: H, writes: W, now: DateTime.Utc) =>1686 Effect.gen(function* () {
44 unmodified lines
17311732 const waiting = awaitingFinish(h, input.ask);17331734 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 lines
17631764 return receiptOf(advanced.outcome);1765 }17662011 // 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 });17681769 const facts = yield* kernel1770 .withPorts(
46 unmodified lines
1817 { ask: input.ask, main, now }1818 );1819 });18202067 // ---------------------------------------------------------- land20682069 /**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: number
95 unmodified lines
1927 }),1928 Effect.flatMap(kernel.withLayers)1929 );19302187 // 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 lines
1938 ) {1939 return yield* new NotDecider({});1940 }19412199 // 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);19441945 const refusals = Option.match(gate, {1946 onNone: () => [],
75 unmodified lines
2022 ? yield* stuck.value2023 : receiptOf(outcomeOf(state));2024 }20252284 // A busy repo or a blocked Checker or Lander: try again.2026 return yield* new RepoBusy({});2027 });20282288 // ---------------------------------------------------------- fork, vouch22892029 const forkBody = (caller: Person) => (h: H, writes: W, now: DateTime.Utc) =>2030 Effect.gen(function* () {2031 const live = liveOf(h);2032
40 unmodified lines
2073 (h: H, writes: W, now: DateTime.Utc) =>2074 Effect.gen(function* () {2075 const policy = Option.getOrUndefined(h.policy);20762338 // 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 lines
20922093 return { landed };2094 });20952358 // ---------------------------------------------------------- reads23592096 const todayOf = (caller: Person) =>2097 Effect.gen(function* () {2098 const h = yield* kernel.read;2099 const now = yield* DateTime.now;
79 unmodified lines
modified: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 */1import { AtLeastOne, ConfigFile } from "@repo/protocol/domain/common";2import { PublicPolicy } from "@repo/protocol/domain/policy";3import {4 LandedSha,
5 unmodified lines
10} from "@repo/protocol/ids";11import { Refusal } from "@repo/protocol/refusal";12import { Context, Effect, Schema } from "effect";1328/** How many rounds one proposal may be drafted in, and attempts one round makes. */14export const DRAFT_ROUNDS = 3;1531/** The most of a rehearsal's output its `Refused` carries: the tail, where a failure prints. */16export const EXCERPT_BYTES = 4 * 1024;1734/**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. */19export const DraftParams = Schema.Struct({20 note: Schema.optionalKey(Schema.String),21 project: ProjectName,22 proposal: ProposalId,
1 unmodified line
24});2526export type DraftParams = typeof DraftParams.Type;2748/** What starts a draft's run: the platform's durable run, or nothing by default. */28export 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}3233export const DraftRuns = Context.Reference<DraftStarter>("project/DraftRuns", {34 defaultValue: () => ({ start: () => Effect.void }),35});3658/**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 */37export const Diagnosis = Schema.Literals([38 "LoadError",39 "Passed",40 "NoTests",
5 unmodified lines
46]);4748export type Diagnosis = typeof Diagnosis.Type;4976/**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 */50export const Rehearsal = Schema.TaggedUnion({51 Red: {52 lane: LaneName,53 signature: Schema.NonEmptyString,
7 unmodified lines
61});6263export type Rehearsal = typeof Rehearsal.Type;6497/** A drafted ask's last attempt number, and the model that drafted it. */65const attempt = {66 attempts: AtLeastOne.check(Schema.isLessThanOrEqualTo(DRAFT_ROUNDS)),67 model: Schema.NonEmptyString,68};69103/**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 */70export const DraftResult = Schema.TaggedUnion({71 Failed: { ...attempt, refusal: Refusal },72 Red: {73 ...attempt,
5 unmodified lines
79});8081export type DraftResult = typeof DraftResult.Type;82121/**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`. */84export const DraftContextData = Schema.Struct({85 at: LandedSha,86 paths: Schema.Array(RepoPath),87 policy: PublicPolicy,
8 unmodified lines
modified: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 */1import { CheckJob } from "@repo/checks/check-runner";2import type { EnvSchemaView } from "@repo/protocol/domain/env";3import { RepoPath, sameHandle } from "@repo/protocol/ids";4import type { EnvKey, Handle, LandedSha } from "@repo/protocol/ids";
6 unmodified lines
11import type { ProjectSnapshot, ProjectWrites } from "./project-store.ts";12import { noPlan, policyIn } from "./visibility-port.ts";13import type { VisibilityPlan } from "./visibility-port.ts";1427/**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. */16export const UnlandedRunEnv = Schema.Struct(17 Struct.pick(CheckJob.fields, ["placeholders", "proxies"])18);1920export type UnlandedRunEnv = typeof UnlandedRunEnv.Type;2140/**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. */23export const RunEnv = Schema.Struct(24 Struct.pick(CheckJob.fields, ["landed", "placeholders", "proxies", "values"])25);2627export type RunEnv = typeof RunEnv.Type;2852/** The env a job carries when the project has no write-only values: none. */29export const noRunEnv: UnlandedRunEnv = { placeholders: [], proxies: [] };3055/** A project's env schema at one commit, as `envShape` shows it but for where and whose. */31export type EnvSchemaFile = Omit<EnvSchemaView, "at" | "project">;3258/** Where the env schema lives: the repo's root. */33const envFile = RepoPath.make(".env.schema");3461/** A write-only value set: what `setEnv` answers with, and the rows that keep it sealed. */35export interface ValueSet {36 readonly result: {37 readonly key: EnvKey;38 readonly setAt: DateTime.Utc;
1 unmodified line
40 };41 readonly writes: ProjectWrites;42}4371/** What `scan` searches: a text that leaves a run, or a blob an answer adds. */44export type Scanned = { readonly text: string } | { readonly blob: Uint8Array };4574/** The project's env, as the project service reaches it. */46export 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 lines
60 ) => 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 lines
78 snapshot: ProjectSnapshot79 ) => Effect.Effect<VisibilityPlan>;80}81116/** Whether `handle` decides anything in the project the snapshot holds. */82const 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 );88124/**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 */89export const noEnv: EnvPort = {90 onLanded: () => Effect.succeed(noPlan),91 runEnv: () => Effect.succeed(noRunEnv),92 scan: () => Effect.succeedNone,
5 unmodified lines
98 ),99 view: () => Effect.succeed({ file: envFile, imports: [], items: [] }),100};101143/**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 */102export const ProjectEnv = Context.Reference<EnvPort>("project/ProjectEnv", {103 defaultValue: () => noEnv,104});105151/** The default, said out loud: a project without the cartridge's env. */106export 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 */1import type { Ask, AskListing } from "@repo/protocol/domain/ask";2import type { ProjectEvent as Event } from "@repo/protocol/domain/event";3import { ProjectEvent } from "@repo/protocol/domain/event";4import type { Outcome } from "@repo/protocol/domain/outcome";
5 unmodified lines
10type OmitEach<Union, Key extends PropertyKey> = Union extends unknown11 ? Omit<Union, Key>12 : never;1320/**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 */14export type ProjectEventInput = OmitEach<Event, "seq">;1527/** Constructors and matchers for project events before the store numbers them. */16export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();1730/** An ask as `listAsks`, the front page and `AskOpened` show it. */18export const listingOf = (ask: Ask): AskListing => {19 const listing = {20 ask: ask.id,21 blockedBy: ask.blockedBy,
7 unmodified lines
29 ? listing30 : { ...listing, reserve: ask.reserve };31};3246/** An ask opened. */33export const askOpened = (ask: Ask, at: DateTime.Utc): ProjectEventInput =>34 ProjectEventInput.AskOpened({ ask: listingOf(ask), at });3550/** An answer's landing closed its ask. */36export const askClosed = (37 ask: AskId,38 landing: LandedSha,39 at: DateTime.Utc40): ProjectEventInput => ProjectEventInput.AskClosed({ ask, at, landing });4157/** An answer was judged: its checks or its merge decided where it stands. */42export const judged = (43 ask: AskId,44 head: CommitSha,45 outcome: Outcome,
2 unmodified lines
4849const asEvent = Schema.decodeUnknownEffect(Schema.toType(ProjectEvent));5051/**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 */55export const numbered = (56 lastSeq: number,57 events: readonly ProjectEventInput[]
4 unmodified lines
modified: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 */1import { ObjectId, RepoHost, Revision } from "@repo/artifacts/repo-host";2import type { RepoNotFound } from "@repo/artifacts/repo-host";3import { judgeInputs } from "@repo/checks/judge";4import { workspacesIn } from "@repo/checks/workspaces";
17 unmodified lines
22import type { EvaluationFacts } from "@repo/rules/rules-evaluator";23import { Array, Effect, Option, Schema } from "effect";24import type { DateTime } from "effect";2535/** A commit the push names that the repo does not hold. */26export class MissingCommit extends Schema.TaggedError<MissingCommit>()(27 "MissingCommit",28 { sha: Schema.String }29) {}
3 unmodified lines
33const asHandle = Schema.decodeUnknownOption(Handle);3435const asLayer = Schema.decodeUnknownOption(LayerName);3647/**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 */37export const targetOf = (repo: RepoName, project: ProjectName): PushTarget => {38 const [named, second, third, ...rest] = repo.split("--");39 const canonical = PushTarget.Canonical({ project });40
42 unmodified lines
83);8485const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);86103/** A `package.json` blob's `scripts`, as canonical JSON text; none when it reads as no manifest. */87const scriptsIn = (repo: RepoName, blob: string | undefined) =>88 blob === undefined89 ? Effect.succeed("")90 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(
4 unmodified lines
95 )96 )97 );98116/** Whether the root manifest's `scripts` differ between the change's two blobs. */99const scriptsChanged = (repo: RepoName, changes: readonly Change[]) =>100 Option.match(101 Array.findFirst(changes, (change) => change.path === "package.json"),102 {
8 unmodified lines
111 ),112 }113 );114133/** What `pushFacts` is told: the push, and what the project knows about it. */115export 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}128150/**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 */129export const pushFacts = (130 input: PushInput131): Effect.Effect<PushFacts, RepoNotFound | MissingCommit, RepoHost> =>132 Effect.gen(function* () {
26 unmodified lines
159 target: targetOf(input.repo, input.project),160 } satisfies PushFacts;161 });162190// ------------------------------------------------------------ rules facts191192/** How many of a repo's trees or blobs the facts read at once. */163const READS_AT_ONCE = 16;164195/** A blob or a folder of a commit's tree: its path from the root, and its id. */165interface Located {166 readonly path: string;167 readonly sha: ObjectId;168}169201/**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 */170const blobsUnder = (171 repo: RepoName,172 root: ObjectId173): Effect.Effect<readonly Located[], RepoNotFound, RepoHost> => {
33 unmodified lines
207208 return level([{ path: "", sha: root }], []);209};210246/** What `evaluationFacts` is told besides the commit. */211export 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}217255/**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.220export const evaluationFacts = (221 repo: RepoName,222 at: CommitSha,223 input: FactsInput
55 unmodified lines
modified: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 */1import type { Reserve } from "@repo/protocol/domain/ask";2import type {3 FrontPageEntry,4 ProjectListing,
2 unmodified lines
7import type { Handle, KindName } from "@repo/protocol/ids";8import { Context } from "effect";9import type { Effect } from "effect";1024/** Which open asks to list: one kind, or the ones held for newcomers or for people. */11export interface FrontPageFilter {12 readonly kind?: KindName;13 readonly reserved?: Reserve;14}1516export 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 line
modified: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 */1import { Brand } from "@repo/brand";2import { formatLanding } from "@repo/git/trailers";3import type { Credit } from "@repo/protocol/domain/credit";4import type { LandingView } from "@repo/protocol/domain/landing";
4 unmodified lines
910import { decidersFor } from "./attention/decisions.ts";11import { platformHandle } from "./attention/effects.ts";1228/** One file a generator makes: where it goes, and every byte of it. */13export interface GeneratedFile {14 readonly path: string;15 readonly content: string;16}1734/** A file's text in the tree a landing left, if the tree has it. */18export type ReadAt = (path: string) => Effect.Effect<Option.Option<string>>;1920/**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 */24export type Generate = (input: {25 readonly project: ProjectName;26 readonly policy: Policy;27 readonly landed: LandedSha;28 readonly read: ReadAt;29}) => Effect.Effect<readonly GeneratedFile[]>;3049/** The platform's landing that follows another with the regenerated files. */31export 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}3940/**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 */44export const ProjectGenerator = Context.Reference<Generate>(45 "project/ProjectGenerator",46 { defaultValue: () => () => Effect.succeed([]) }47);4873/** The request a follow-up of the landing at `landed` lands as. */49export const generatedRequestId = (landed: LandedSha) =>50 RequestId.make(`gen-${landed}`);5177/** Where the config lives: whoever decides for it decides what the files say. */52const configPath = RepoPath.make(`${Brand.configDir}/project.ts`);5380/**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 */54const deciderOf = (input: {55 readonly after: Policy;56 readonly initializer: Handle;57 readonly landing: LandingView;
16 unmodified lines
74 () => input.initializer75 );76};77108/** Whether two generations say the same, file for file. */78const sameFiles = (79 one: readonly GeneratedFile[],80 other: readonly GeneratedFile[]81) =>
21 unmodified lines
103 subject: "Regenerate the contribute skill and the AGENTS.md block",104 });105106/**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 */110export 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 lines
modified: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 */1import { RefName } from "@repo/artifacts/repo-host";2import { Brand } from "@repo/brand";3import type { Change } from "@repo/git/tree-diff";4import type { Verdict } from "@repo/protocol/domain/answer";
16 unmodified lines
21import type { Array, Effect, Option } from "effect";2223export type { Change } from "@repo/git/tree-diff";2441/**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. */26export const landedRef = RefName.make(`${Brand.refsPrefix}landed`);2747/**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`. */29export const composeRef = (tree: TreeSha) =>30 RefName.make(`${Brand.refsPrefix}compose/${tree}`);3154/** An answer's head to merge onto canonical `main`. */32export 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}3967/** An answer merged onto main: the tree to check, and what the answer changed. */40export 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}4574/** One file a decider adds at its path, such as an ask file or its check. */46export interface ComposedFile {47 readonly path: RepoPath;48 readonly content: string;49}5080/**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 */51export type Rebuild = Data.TaggedEnum<{52 Merge: {53 readonly fork: RepoName;54 readonly base: CommitSha;
4 unmodified lines
59}>;6061export const Rebuild = Data.taggedEnum<Rebuild>();6297/** A checked tree to land on canonical `main` as a platform commit. */63export 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}75117/** Bookkeeping written after `main` moved, each in its own push. */76export type Bookkeeping = "mirror" | "notes";77120/**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. */79export interface Landed {80 readonly sha: LandedSha;81 readonly pending: readonly Bookkeeping[];82}83130/** A decider's files to compose onto canonical `main`, so an ask's check can run red first. */84export interface ComposeJob {85 readonly repo: RepoName;86 readonly main: LandedSha;87 readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;88}89137/** Main with the files added: its tree, and the commit a Checker fetches it by. */90export interface Composed {91 readonly tree: TreeSha;140 /** On `composeRef(tree)` in the canonical repo; its parent is `main`. */92 readonly commit: CommitSha;93}94144/** The config folder to read at one landed commit. */95export interface BundleJob {96 readonly repo: RepoName;97 readonly at: LandedSha;98}99100export 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 line
modified: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 */1import { AgentTrailer, Credit } from "@repo/protocol/domain/credit";2import type { CreditRole } from "@repo/protocol/domain/credit";3import type { Choice } from "@repo/protocol/domain/decision";4import { DecisionSubject } from "@repo/protocol/domain/decision";
23 unmodified lines
28import { Array, Data, DateTime, Duration, Match, Option, Schema } from "effect";2930import { ProjectEventInput } from "./events.ts";3139/** How many times a moved main may send an answer back to merge before it is refused as stale. */32export const maxRemerges = 3;3342/**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. */35export const Change = Schema.Struct({36 after: Schema.optionalKey(BlobSha),37 before: Schema.optionalKey(BlobSha),38 path: RepoPath,
1 unmodified line
40});4142export type Change = typeof Change.Type;4355/**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 */44export 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 line
55});5657export type Request = typeof Request.Type;5878/**79 * A decision an answer can wait on. Declining one refuses the answer with the80 * refusal it stands for.81 */59export const AnswerDecision = Schema.Union([60 DecisionSubject.cases.PostureChange,61 DecisionSubject.cases.RaiseRatchet,62 DecisionSubject.cases.Waiver,63]).pipe(Schema.toTaggedUnion("_tag"));6465export type AnswerDecision = typeof AnswerDecision.Type;6690/** A decision the answer waits on, with the id the service minted for it. */67export const PendingDecision = Schema.Struct({68 id: DecisionId,69 subject: AnswerDecision,70});
1 unmodified line
72export type PendingDecision = typeof PendingDecision.Type;7374const Count = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));75100// 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.76const underway = {77 attempt: Count,78 main: LandedSha,79 remerges: Count,
1 unmodified line
81};8283const checkedFields = { ...underway, tree: TreeSha };84111/** Where one answer request stands on its way to main. */85export 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});100101export type LandingState = typeof LandingState.Type;102136/** What the service tells a landing: a port's answer, a person's decision, or the queue's go. */103export 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}>;134135export const LandingCommand = Data.taggedEnum<LandingCommand>();136187/** What the service runs for a landing: the transition only describes it. */137export type LandingEffect = Data.TaggedEnum<{138 Merge: {139 readonly base: CommitSha;140 readonly fork: RepoName;
1 unmodified line
142 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}>;150151export const LandingEffect = Data.taggedEnum<LandingEffect>();152206/** One step of a landing: the state it reached and the effects to settle. */153export interface Step {154 readonly effects: readonly LandingEffect[];155 readonly state: LandingState;156}
23 unmodified lines
180 request,181 tree,182});183238/** How long a retry waits after attempt `attempt`: a second, doubling, up to five minutes. */184export const backoff = (attempt: number): Duration.Duration =>185 Duration.millis(Math.min(1000 * 2 ** attempt, 5 * 60 * 1000));186242/**243 * The port call a state waits on: the service runs it when the state is244 * entered, and again at a `Retry`.245 */187export const pendingEffects = (state: LandingState): readonly LandingEffect[] =>188 LandingState.matchOrElse<readonly LandingEffect[]>(189 state,190 {
25 unmodified lines
216217const start = (request: Request, main: LandedSha): Step =>218 enter(Merging.make({ attempt: 0, main, remerges: 0, request }));219279// 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.220const retry = (221 state: typeof Checking.Type | typeof Landing.Type | typeof Merging.Type,222 attempt: number,223 now: DateTime.Utc
11 unmodified lines
235236const isFinished = (request: Request) =>237 request.credits.some(({ role }) => role === "Finished-by");238301// The landing credits a person once in each role, however often they act in it.239const 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 }] };245309// 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.246const human = (247 passed: Passed,248 decisions: readonly PendingDecision[],249 finish: AskKind["finish"]
12 unmodified lines
262 })263 ),264 });265331/** The refusal a merge that conflicted stands for, naming who moved each path the step found. */266const staleOn = (267 base: CommitSha,268 {269 conflicts,
4 unmodified lines
274 movedBy === undefined275 ? new StaleBase({ base, conflicts, main })276 : new StaleBase({ base, conflicts, main, movedBy });277344/** The refusal a declined decision stands for. */278const declined = (subject: AnswerDecision): Refusal =>279 AnswerDecision.match(subject, {280 PostureChange: ({ from, to }) => new PostureChange({ from, to }),281 RaiseRatchet: ({ after, before, ratchet, territory }) =>
71 unmodified lines
353 state: Landed.make({ request, sha }),354 };355};356424// 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.357const moved = (358 state: typeof Landing.Type,359 { from, main }: { readonly from: LandedSha; readonly main: LandedSha }360): Step => {
14 unmodified lines
375 })376 );377};378448/**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. */380export const transition = (381 state: LandingState,382 command: LandingCommand,383 now: DateTime.Utc
71 unmodified lines
455 Match.orElse(() => stay(waiting))456 ),457 });458533/** Where the answer stands, as `status`, `verdict` and MCP report it. */459export 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 });473550/**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 */474export 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 line
480481const isActive = (queue: LandingQueue, id: RequestId) =>482 Option.contains(queue.active, id);483565/** Adds a request to the back of the queue; a request already in it stays where it is. */484export const enqueue = (queue: LandingQueue, id: RequestId): LandingQueue =>485 isActive(queue, id) || queue.order.includes(id)486 ? queue487 : { ...queue, order: [...queue.order, id] };488571/** Admits the request at the front, unless one is already landing. */489export const next = (490 queue: LandingQueue491): {492 readonly admit: Option.Option<RequestId>;
8 unmodified lines
501 queue: { active: Option.some(front), order: rest },502 }),503 });504588/**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 */505export 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 */1import { Brand } from "@repo/brand";2import { matchAny } from "@repo/gate/glob";3import type { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";
3 unmodified lines
8import type { Territory } from "@repo/protocol/domain/territory";9import { AskId, RatchetName, RepoPath } from "@repo/protocol/ids";10import { Array, Option, Schema } from "effect";1126/**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 */12export const CallerCount = Schema.Struct({13 byModule: Schema.Record(Schema.String, NoneOrMore),14 total: NoneOrMore,15});1617export type CallerCount = typeof CallerCount.Type;1837/** A count command's stdout, read as its `CallerCount`. */19export const callerCountOf = Schema.decodeUnknownOption(20 Schema.fromJsonString(CallerCount)21);2242/** Whether two counts are the same: the same total, and the same callers in every module. */23export const sameCount = (one: CallerCount, other: CallerCount): boolean =>24 one.total === other.total &&25 Array.dedupe([26 ...Object.keys(one.byModule),
1 unmodified line
28 ]).every(29 (module) => (one.byModule[module] ?? 0) === (other.byModule[module] ?? 0)30 );3152/** A migrate ask's check: the name it moves from, where to, and the command that counts callers. */32type MigrateCheck = Extract<CheckSpec, { readonly _tag: "Migrate" }>;3355/** One file the family adds to the config folder. */34export interface FamilyFile {35 readonly content: string;36 readonly path: RepoPath;37}3861/** A migrate ask split into its family, and what its opening lands. */39export 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}4978/** `@burrow/http-kit` → `burrow-http-kit`: a name an ask id can carry. */50const slug = (name: string) =>51 name52 .toLowerCase()53 .replaceAll(/[^a-z0-9]+/gu, "-")54 .replaceAll(/^-+|-+$/gu, "");5585/**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. */57export const childId = (parent: AskId, module: string): AskId =>58 AskId.make(`${parent}-${slug(module) || "root"}`);5992/** The id of a family's delete child: `drop-legacy-fetch-delete`. */60export const deleteChildId = (parent: AskId): AskId =>61 AskId.make(`${parent}-delete`);6296/** The ratchet on a name's callers: `legacyFetch` → `callers-legacyfetch`. */63export const callersRatchet = (from: SymbolName): RatchetName =>64 RatchetName.make(`callers-${slug(from) || "name"}`);65100/** What an ask still waits on: each ask it is blocked by that has not closed. */66export const remainingBlockers = (67 ask: Ask,68 asks: ReadonlyMap<AskId, Ask>69): readonly AskId[] =>70 ask.blockedBy.filter((blocker) => asks.get(blocker)?.state !== "closed");71107/** Whether a family is done: it has children, and every one has closed. */72export const familyClosed = (73 parent: AskId,74 asks: ReadonlyMap<AskId, Ask>75): boolean => {
1 unmodified line
7778 return members.length > 0 && members.every(({ state }) => state === "closed");79};80117/**118 * The modules a territory spans: the one it names, or every module whose119 * paths its globs all cover (`packages/**` covers `packages/p1/**`).120 */81export const modulesWithin = (82 territory: Territory,83 modules: readonly Territory[]84): readonly Territory[] => {
5 unmodified lines
90 paths.every((glob) => matchAny(territory.paths, glob))91 );92};93134/**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. */95export const callersIn = (96 territory: Territory,97 counts: CallerCount,98 modules: readonly Territory[]
7 unmodified lines
106 0107 );108};109154/**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 */110export 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});117166/** The callers ratchets of every migrate ask still open, one per name. */118export const callersSpecs = (asks: Iterable<Ask>): readonly RatchetSpec[] =>119 Array.dedupeWith(120 [...asks].flatMap(({ check, state }) =>121 CheckSpec.guards.Migrate(check) && state !== "closed"
9 unmodified lines
131 `// A child of the migrate ask ${parent}, written by ${Brand.name} when it opened.`;132133const sdk = quoted(`${Brand.cliPackage}/rules`);134184/** An object literal's lines, each `key: value,`, indented by two. */135const fields = (entries: readonly (readonly [string, string])[]) =>136 entries.map(([key, value]) => ` ${key}: ${value},`);137188/**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 */138const 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 lines
179 "",180 ].join("\n");181};182237/**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. */184const deleteFile = (child: Ask, check: MigrateCheck, parent: AskId) =>185 [186 header(parent),187 `import { kind } from ${sdk};`,
18 unmodified lines
206207const callersOf = (count: number) =>208 count === 1 ? "1 caller" : `${count} callers`;209267/** A child's want: `p1: 5 callers of legacyFetch → http.get`. */210const 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}`;214273/**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. */216export const splitFamily = (input: {217 readonly parent: Ask;218 readonly counts: CallerCount;219 readonly modules: readonly Territory[];
82 unmodified lines
modified: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 */1import { RefName, RepoHost } from "@repo/artifacts/repo-host";2import { Verdict } from "@repo/protocol/domain/answer";3import type { ProjectEvent } from "@repo/protocol/domain/event";4import {
17 unmodified lines
22import { ProjectVisibility, VisibilityEffect } from "./visibility-port.ts";2324const mainRef = RefName.make("refs/heads/main");2540/** An answer's landing job, as its bookkeeping retry lands it again. */26export const LandAgain = Schema.Struct({27 author: Handle,28 base: CommitSha,29 fork: RepoName,
7 unmodified lines
37});3839export type LandAgain = typeof LandAgain.Type;4056/** What one outbox row asks for. */41export const OutboxBody = Schema.Union([42 ProjectedEvent,43 Schema.TaggedStruct("MakeFork", { from: RepoName, name: RepoName }),44 Schema.TaggedStruct("StartAnswer", { requestId: RequestId }),
9 unmodified lines
54const encodeBody = Schema.encodeEffect(BodyJson);5556const decodeBody = Schema.decodeUnknownEffect(BodyJson);5774/** A row asking for `body`, due at `notBefore`; a row with the same id is replaced. */58export const outboxRow = (59 id: string,60 body: OutboxBody,61 notBefore: DateTime.Utc
5 unmodified lines
67 kind: body._tag,68 notBefore,69 }));7088/** One row per event, for the read models, keyed by the event's number. */71export const projectedRows = (72 project: ProjectName,73 events: readonly ProjectEvent[],74 now: DateTime.Utc
5 unmodified lines
80 now81 )82 );83102/** The row that starts (or resumes) an answer's run at `at`. */84export const startRow = (requestId: RequestId, at: DateTime.Utc) =>85 outboxRow(86 `start:${requestId}:${DateTime.toEpochMillis(at)}`,87 OutboxBody.cases.StartAnswer.make({ requestId }),88 at89 );90110/** The row that starts a proposal's draft run for one round: one row per round. */91export const draftRow = (params: DraftParams, at: DateTime.Utc) =>92 outboxRow(93 `draft:${params.proposal}:r${params.round}`,94 OutboxBody.cases.StartDraft.make(params),95 at96 );97118/** Whether a row is due at `now`. */98export const isDue = (row: OutboxRow, now: DateTime.Utc) =>99 DateTime.isLessThanOrEqualTo(row.notBefore, now);100122/** What running some rows came to: the ids done, and the rows to run again later. */101export interface OutboxRun {102 readonly done: readonly string[];103 readonly retry: readonly OutboxRow[];104}105128/** The row again, after `attempts` failures: due after a backoff from `now`. */106const later = (row: OutboxRow, now: DateTime.Utc): OutboxRow => ({107 ...row,108 attempts: row.attempts + 1,109 notBefore: DateTime.addDuration(now, backoff(row.attempts)),
11 unmodified lines
121 done: runs.flatMap(({ done }) => done),122 retry: runs.flatMap(({ retry }) => retry),123});124148/**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.127const fork = (from: RepoName, name: RepoName) =>128 RepoHost.use((host) =>129 host.fork(from, name).pipe(130 Effect.as(true),
6 unmodified lines
137 Effect.orElseSucceed(() => false)138 )139 );140166/** The landing job again: its unwritten bookkeeping is written, and nothing else moves. */141const landAgain = (job: LandAgain) =>142 Lander.use((lander) =>143 lander.land({144 author: job.author,
17 unmodified lines
162const bySeq = Order.mapInput(Order.Number, ({ body }: Decoded) =>163 OutboxBody.guards.Projected(body) ? body.event.seq : 0164);165192/**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.167export const runOutbox = (168 rows: readonly OutboxRow[],169 queue: AnswerQueue,170 now: DateTime.Utc
74 unmodified lines
modified:packages/project/src/project-store.ts+3 added-44 removed
22 unmodified lines
23 PushEventRow,24 RatchetRow,25} from "./project-store/rows.ts";2627/** How many landings a snapshot carries, newest first; `landing` finds older ones. */27export const snapshotLandings = 50;2829/** How many events a project keeps; a watcher resuming from an older one has missed some. */30export const keptEvents = 500;3133/**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 */32export 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}5066/**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 */51export interface ProjectWrites {52 readonly answers?: readonly AnswerRow[];53 readonly asks?: readonly AskRow[];54 readonly attempts?: readonly AttemptRow[];
2 unmodified lines
57 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 line
68 readonly queue?: Schema.Json;69 readonly ratchets?: readonly RatchetRow[];70}7196/** What a commit did: the numbers it gave its events, and the push events it had already seen. */72export 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}7778/**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 */83export class ProjectStore extends Context.Service<84 ProjectStore,85 {
16 unmodified lines
modified: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 */1import {2 BranchName,3 RefName,4 RepoHost,
293 unmodified lines
298 ProjectVisibility,299} from "./visibility-port.ts";300import type { VisibilityPlan } from "./visibility-port.ts";301318/** Every port one project's service runs on. */302export type ProjectPorts =303 | Alarms304 | AnswerRuns305 | CheckRunner
2 unmodified lines
308 | Projection309 | RepoHost310 | RulesEvaluator;311329/**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. */313export const GatewayUrl = Context.Reference<string>("project/GatewayUrl", {314 defaultValue: () => `https://${Brand.domain}`,315});316338/**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`. */318export const FinishersFromChecks: Layer.Layer<Finishers> = Layer.succeed(319 Finishers,320 { findRunBlock, judgeClosure }321);322348/** A push one repo took, as the gateway's custody reports it. */323export 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});333334export type PushReport = typeof PushReport.Type;335368/** One file a decider opens an ask with: its ask file, or its check. */336export interface AskFile {337 readonly content: string;338 readonly path: RepoPath;339}340374/**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 */341export const StandingNow = Schema.Struct({342 posture: Posture,343 seen: Schema.Int,344 until: Schema.optionalKey(Schema.DateTimeUtcFromString),345});346347export type StandingNow = typeof StandingNow.Type;348387/** The refusals `submitAnswer` answers with. */349export type SubmitRefusal =350 | NotClaimed351 | ClaimLapsed352 | StaleBase
3 unmodified lines
356 | Weakened357 | ReachedInternals358 | PrivatePathInPublicTree;359399/**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 */360export interface ProjectApi extends AnswerQueue, DeciderApi {407 // reads361 readonly listAsks: (362 caller: Principal363 ) => Effect.Effect<{ readonly asks: readonly AskListing[] }>;364 readonly showAsk: (
11 unmodified lines
376 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 lines
410 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 lines
455 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 line
465 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}499637/** The most paths a draft's context lists: as many as the code browser's `listPaths`. */500const MAX_DRAFT_PATHS = 50_000;501640/** What `projectPolicy` answers: the public policy, or why there is none yet. */502export type PolicyStatus = typeof PolicyOf.successSchema.Type;503643/** The most commits one `landings` call looks up: a log page's, or a blame's batch. */504export const MAX_LANDINGS = 100;505646/** The schemas one method's arguments (in order), success and failure cross a boundary with. */506export interface MethodSchema {507 readonly args: readonly Schema.Top[];508 readonly error: Schema.Top;509 readonly success: Schema.Top & { readonly EncodingServices: never };510}511653/**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 */512export const MethodSchemas = {513 [envSchemaMethod]: {514 args: [Principal],515 error: EnvSchemaOf.errorSchema,
267 unmodified lines
783 success: Vouch.successSchema,784 },785} as const satisfies { readonly [M in keyof ProjectApi]: MethodSchema };786934/**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 */787export const Measured = Schema.Struct({788 declared: Schema.Array(MeasuredCount),789 escapes: Schema.Array(MeasuredCount),790});791792export type Measured = typeof Measured.Type;793947/**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 */794export const HeldBackJudged = Schema.Struct({795 refusals: Schema.Array(Refusal),796 trailer: Schema.optionalKey(Schema.NonEmptyString),797 tree: TreeSha,798});799800export type HeldBackJudged = typeof HeldBackJudged.Type;801960/**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 */802export const AnswerRecord = Schema.Struct({803 heldBack: Schema.optionalKey(HeldBackJudged),804 landing: LandingState,805 measured: Schema.optionalKey(Measured),
21 unmodified lines
827const decodePolicy = Schema.decodeUnknownEffect(PolicyJson);828829const encodePolicy = Schema.encodeEffect(PolicyJson);830997/**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 */831const checked = <A, E, R>(832 schemas: MethodSchema,833 args: readonly unknown[],834 run: Effect.Effect<A, E, R>
11 unmodified lines
846 Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))847 )848 );8491022/** A policy as anyone may read it: without its layers, function-valued rules and asks. */850const publicPolicy = (policy: Policy): PublicPolicy =>851 Struct.omit(policy, ["asks", "functions", "visibility"]);8521026/** A claim's fork, as the refs page lists it. */853const listedFork = (claim: Live, state: ClaimView["state"]) =>854 Option.some<ForkRef>({855 ask: claim.ask,856 handle: claim.claimant,
1 unmodified line
858 repo: claim.fork,859 state,860 });8611036/** Where a claim stands, as its fork's listing says it; an open ask has no fork. */862const forkOf = (state: ClaimState): Option.Option<ForkRef> =>863 ClaimState.match(state, {864 Answered: (claim) => listedFork(claim, "answered"),865 Lapsed: (claim) => listedFork(claim, "lapsed"),
2 unmodified lines
868 Released: (claim) => listedFork(claim, "released"),869 Warned: (claim) => listedFork(claim, "warned"),870 });8711047/** The most of a lane's log `evidence` gives back: its last 256 KiB. */872const EVIDENCE_TAIL = 256 * 1024;8731050/** Whether a UTF-8 byte starts a character: it is no continuation byte (`10xxxxxx`). */874const startsCharacter = (byte: number) => byte < 0x80 || byte >= 0xc0;8751053/**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. */877const tailOf = (log: string, limit = EVIDENCE_TAIL) => {878 const bytes = new TextEncoder().encode(log);879880 if (bytes.length <= limit) {
12 unmodified lines
893const mainRef = RefName.make("refs/heads/main");894895const HOUR = 3_600_000;8961077/** The claim deadlines before a project has a policy: the defaults. */897const defaultClaims: Policy["claims"] = {898 lapseAfterMs: 24 * HOUR,899 warnAfterMs: 2 * HOUR,900};
7 unmodified lines
908 readonly record: AnswerRecord;909 readonly row: AnswerRow;910}9111093/** A project as one call reads it at its start. */912interface Hydrated {913 readonly answers: readonly Answered[];914 readonly asks: ReadonlyMap<AskId, Ask>;915 readonly budgetDays: readonly BudgetDayRow[];
5 unmodified lines
921 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}9281113/**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. */930interface 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 lines
944 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}950951const writesOf = (): Writes => ({
38 unmodified lines
990 writes.queue.size,991 writes.ratchets.size,992 ].every((count) => count === 0);9931184/** 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 */994const keepLanding = (995 writes: Writes,996 landing: LandingView,997 now: DateTime.Utc
7 unmodified lines
10051006 return JSON.stringify(table.key.map((name) => columns[name]));1007};10081205/** `held` with `written` over it: each written row in its key's place, the new ones after. */1009const overlaid = <A>(1010 table: Table<A>,1011 held: readonly A[],1012 written: Iterable<A>
9 unmodified lines
1022 ...[...fresh.values()].filter((row) => !kept.has(keyIn(table, row))),1023 ];1024};10251223/** Ledger entries in order. */1026const bySeq = Order.mapInput(Order.Number, (entry: LedgerRow) => entry.seq);10271226/**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 */1028const snapshotNow = (h: Hydrated, writes: Writes): ProjectSnapshot => {1029 const held = h.snapshot;10301031 return {
44 unmodified lines
1076 ),1077 };1078};10791284/**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 */1080const portTables = new Set<string>([1081 "attempts",1082 "decisions",1083 "envValues",
3 unmodified lines
1087 "ledger",1088 "outbox",1089]);10901300/** A port's rows added to the call's: each keyed table by its key, the logs appended. */1091const absorb = (writes: Writes, more: ProjectWrites) => {1092 const foreign = Object.keys(more).filter((table) => !portTables.has(table));10931094 if (Array.isReadonlyArrayNonEmpty(foreign)) {
28 unmodified lines
11231124 return Effect.void;1125};11261337/**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 */1127const applyPlan = (writes: Writes, plan: VisibilityPlan, now: DateTime.Utc) =>1128 Effect.gen(function* () {1129 yield* absorb(writes, plan.writes);1130
14 unmodified lines
11451146const claimKey = (ask: AskId, claimant: Handle) =>1147 JSON.stringify([ask, claimant.toLowerCase()]);11481364/** A claim's own fields, in every state but `Open`. */1149const 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 lines
1157 });11581159const isLive = ClaimState.isAnyOf(["Live", "Warned"]);11601377/** When a live claim's next deadline is: its warning, or once warned its lapse. */1161const deadlineOf = (state: ClaimState): Option.Option<DateTime.Utc> =>1162 ClaimState.match(state, {1163 Answered: () => Option.none(),1164 Lapsed: () => Option.none(),
2 unmodified lines
1167 Released: () => Option.none(),1168 Warned: ({ lapsesAt }) => Option.some(lapsesAt),1169 });11701388/** A path a composed commit can hold: plain folder names and a file name. */1171const isPlainPath = (path: string) =>1172 path1173 .split("/")1174 .every(
3 unmodified lines
1178 segment !== ".." &&1179 segment !== ".git"1180 );11811400/** Whether the brief holds a field its kind requires. */1182const 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 lines
1189 Match.whenOr("check", "territory", () => true),1190 Match.exhaustive1191 );11921412/** Whether two import sources name the same repo and branch (ADR 0031). */1193const sameSource = (a: ImportSource, b: ImportSource) =>1194 a.url === b.url && a.branch === b.branch;11951416/** An optional field as an object to spread: the field when present, nothing when not. */1196const field = <K extends string, A>(1197 key: K,1198 value: Option.Option<A>1199): Partial<Record<K, A>> =>
1 unmodified line
1201 onNone: () => ({}),1202 onSome: (present) => Record.singleton(key, present),1203 });12041426/** The credit an answer's landing carries: who asked, who answered, who mentored. */1205const 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 lines
1212 }))1213 ),1214];12151438/** What a check of `ask` runs, and the lane it reports as. */1216const askLaneOf = (policy: Policy, ask: Ask) =>1217 commandFor(ask.check, policy.run, policy.ratchets);12181442/** A check judged by what its command prints: a lint's count, or a migrate's callers. */1219const isCounted = CheckSpec.isAnyOf(["LintToZero", "Migrate", "SymbolAbsent"]);12201445/** A check that counts a name's callers: a migrate, or its delete child. */1221const countsCallers = CheckSpec.isAnyOf(["Migrate", "SymbolAbsent"]);12221448/**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 */1223const 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 );12291460/** The lanes an answer's checks run: the ask's own check, then every project lane. */1230const lanesOf = (1231 policy: Policy,1232 ask: Option.Option<Ask>1233): readonly CheckLane[] => [
4 unmodified lines
1238 CheckLane.make({ command, lane })1239 ),1240];12411473/**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 */1242const countedBy = (policy: Policy, command: string, stdout: string) =>1243 Effect.map(1244 Effect.forEach(1245 policy.ratchets.filter((spec) => spec.measure.command === command),
16 unmodified lines
1262 ),1263 (counts): readonly RatchetCount[] => counts.flat()1264 );12651502/** A ratchet row's key in a call's writes: its ratchet and territory. */1266const ratchetKey = (row: {1267 readonly ratchet: string;1268 readonly territory: string;1269}) => JSON.stringify([row.ratchet, row.territory]);12701508/** A row as `ratchets.ts` reads a baseline. */1271const baselineOf = (row: RatchetRow): RatchetBaseline => ({1272 count: row.count,1273 ratchet: row.ratchet,1274 setAt: row.at,1275 territory: row.territory,1276});12771516/**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 */1278const isEscapeRow = (row: {1279 readonly ratchet: string;1280 readonly territory: string;1281}) => row.ratchet === escapeRatchet(row.territory);12821526/** Whether two `Waiver`s are about one escape: one ask, one marker and reason, one line. */1283const 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;12891534/** What a decider just decided for an answer waiting on it: the subject, and the choice in its words. */1290interface DecidedOn {1291 readonly choice: Choice;1292 readonly subject: PendingDecision["subject"];1293}12941540/** The decision `command` takes, when it is one the answer waiting in `before` waits on. */1295const decidedOn = (1296 before: LandingState,1297 command: LandingCommand1298): Option.Option<DecidedOn> =>
6 unmodified lines
1305 ({ subject }) => ({ choice: command.choice, subject })1306 )1307 : Option.none();13081555/** The `Waiver`s a decider accepted for an answer: those it had, and the one just accepted. */1309const waivedAfter = (1310 waived: readonly Waiver[],1311 decided: Option.Option<DecidedOn>1312): readonly Waiver[] => [
6 unmodified lines
1319 )1320 ),1321];13221570/** What a decider weighs for one subject an answer waits on. */1323const evidenceFor = (1324 request: Request,1325 subject: Waiver | RaiseRatchet1326): readonly Evidence[] => [
11 unmodified lines
1338 value: `${subject.ratchet} in ${subject.territory}: ${subject.before} to ${subject.after}`,1339 },1340];13411590/**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 */1342const redByCount = (input: {1343 readonly ask: Ask;1344 readonly check: LintToZeroCheck;1345 readonly lane: LaneName;
29 unmodified lines
13751376 return yield* countedBy(policy, check.command, once.stdout);1377 });13781633/** A section of a brief, when it has lines. */1379const section = (heading: string, lines: readonly string[] | undefined) =>1380 lines === undefined || lines.length === 01381 ? []1382 : ["", `## ${heading}`, "", ...lines];13831384const listed = (lines: readonly string[] | undefined) =>1385 lines?.map((line) => `- ${line}`);13861642/** What an ask's check holds it to, in a sentence. */1387const checkLine = (check: CheckSpec) =>1388 CheckSpec.match(check, {1389 LintToZero: ({ rule }) =>1390 `The lint rule \`${rule}\` reports nothing in the territory.`,
6 unmodified lines
1397 `\`${path}\` fails on main by an assertion; it passes once answered.`,1398 SymbolAbsent: ({ symbol }) => `Nothing uses \`${symbol}\` any more.`,1399 });14001657/** The ask as an answerer reads it first, in Markdown. */1401const briefOf = (ask: Ask): string => {1402 const { brief, territory } = ask;1403 const paths = territory.paths.map((path) => `\`${path}\``).join(", ");1404
19 unmodified lines
1424 "",1425 ].join("\n");1426};14271685/** The refusal `submitAnswer` gives for one from the gate: its own, or `NotClaimed`. */1428const submitRefusal = (refusal: Refusal, ask: AskId): SubmitRefusal =>1429 Match.value(refusal).pipe(1430 Match.tag(1431 "ClaimLapsed",
9 unmodified lines
1441 ),1442 Match.orElse(() => NotClaimed.of(ask))1443 );14441703/**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 */1445const withAgent = (1446 agents: readonly AgentTrailer[],1447 audit: HarnessAudit | undefined1448): readonly AgentTrailer[] => {
13 unmodified lines
1462 ? agents1463 : [...agents, agent];1464};14651730/**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 */1466const disclosed = (1467 policy: Policy,1468 claim: Option.Option<ClaimRow>1469): readonly AgentTrailer[] =>
3 unmodified lines
1473 onNone: () => [],1474 onSome: ({ assisted }) => assisted ?? [],1475 });14761746/**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 */1477const heldBackTrailerOf = (1478 record: { readonly heldBack?: HeldBackJudged },1479 tree: TreeSha1480): Option.Option<string> =>
4 unmodified lines
1485 ),1486 ({ trailer }) => Option.fromUndefinedOr(trailer)1487 );14881763/** A landing's commit message, from the platform's own rows. */1489const messageOf = (1490 request: Request,1491 ask: Option.Option<Ask>,1492 verdict: Verdict,
20 unmodified lines
1513 })1514 );1515};15161792/** Answers oldest first, by when their row last moved. */1517const byUpdated = Order.mapInput(1518 DateTime.Order,1519 ({ row }: Answered) => row.updatedAt1520);15211798/**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 */1522const landedVerdict = (verdict: Option.Option<Verdict>, sha: LandedSha) =>1523 Option.map(verdict, (made): Verdict => ({1524 ...made,1525 outcome: Outcome.cases.Landed.make({ sha }),1526 }));15271809/** A `Landed` event with the verdict the landing carries; any other event as it is. */1528const withVerdict = (1529 event: ProjectEventInput,1530 verdict: Option.Option<Verdict>1531): ProjectEventInput =>
7 unmodified lines
1539 })),1540 Match.orElse((other) => other)1541 );15421825/** Whether a landing's effect is for the answer's run: a step, or a retry to wait for. */1543const runnable = (effect: LandingEffect): effect is RunnableEffect =>1544 isStep(effect) || LandingEffect.$is("Retry")(effect);15451546const isTouchedJudge = (refusal: Refusal): refusal is TouchedJudge =>
5 unmodified lines
1552type Checking = Extract<LandingState, { readonly _tag: "Checking" }>;15531554type Landing = Extract<LandingState, { readonly _tag: "Landing" }>;15551839/** What a landing's effects leave: the steps to hand to the run, and the queue. */1556interface Settled {1557 readonly queue: LandingQueue;1558 readonly steps: readonly LandingEffect[];1559}15601845/** Starts the run of a request the queue just admitted, unless it is the one advancing. */1561const startOther = (1562 writes: Writes,1563 admitted: Option.Option<RequestId>,1564 advancing: RequestId,
7 unmodified lines
1572 Effect.map(startRow(id, now), (row) => writes.outbox.push(row)),1573 }1574 );15751861/**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 */1576interface Watch {1577 readonly ran: (1578 lane: LaneName,1579 runs: readonly [CheckRun, CheckRun]
2 unmodified lines
1582}15831584const unwatched: Watch = { ran: () => Effect.void, stdout: false };15851876/** A rehearsal's check, as its watch saw it run twice. */1586interface Seen {1587 readonly lane: LaneName;1588 readonly runs: readonly [CheckRun, CheckRun];1589}15901882/** The refusals opening an ask gives that waiting does not lift. */1591type FinalRefusal =1592 | IncompleteBrief1593 | NotDecider1594 | NotRedFirst1595 | TouchedJudge1596 | WeakCheck;15971890/** How one run of a rehearsed check went, for telling why it was not red. */1598const readingOf = (run: CheckRun, lane: LaneName) => {1599 const result = run.lanes.find((each) => each.lane === lane)?.result;16001601 const signed = run.evidence.some(
2 unmodified lines
16041605 return result === "failed" && !signed ? "loadError" : (result ?? "blocked");1606};16071901/**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 */1608const notRedBecause = ({ lane, runs }: Seen): Diagnosis => {1609 const readings = runs.map((run) => readingOf(run, lane));16101611 if (readings.every((reading) => reading === "passed")) {
6 unmodified lines
16181619 return readings.includes("loadError") ? "LoadError" : "Flaky";1620};16211920/** Why opening was refused, in a drafter's words. */1622const 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 lines
1635 WeakCheck: ({ weakness }): Diagnosis =>1636 weakness === "no assertion" ? "NoTests" : "Weak",1637 });16381940/** The last of what the check printed: its second run's output, else its first's. */1639const 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 lines
1646 onSome: (printed) => tailOf(printed, EXCERPT_BYTES).text,1647 }1648 );16491952/** A rehearsal refused: the refusal, why, and the output's tail. */1650const rehearsalRefused = (1651 refusal: FinalRefusal,1652 seen: Option.Option<Seen>1653): Rehearsal =>
2 unmodified lines
1656 excerpt: excerptOf(seen),1657 refusal,1658 });16591963/**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 */1660const 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});16671975/** Whether an ask's check file has one of the five weak shapes. */1668const weakness = (ask: Ask, files: readonly AskFile[]) => {1669 const { check } = ask;16701671 const file = CheckSpec.guards.RedThenGreen(check)
4 unmodified lines
1676 Array.head(weaknessesOf(found, ask.territory.paths))1677 );1678};16791988/** Stage 0–1's refusals for a push, every one; what a missing commit or repo comes to. */1680const gateOf = (1681 facts: Effect.Effect<PushFacts, RepoNotFound | MissingCommit>,1682 missing: readonly Refusal[],1683 stale: readonly Refusal[]
11 unmodified lines
1695 RepoNotFound: () => Effect.succeed(missing),1696 })1697 );16982008/** The queue once a request no longer landing has left its place in it. */1699const leaveIfDone = (1700 writes: Writes,1701 queue: LandingQueue,1702 input: {
17 unmodified lines
1720 left.queue1721 );1722};17232034/** A landing that names neither the ask it answers nor one it opened. */1724const namesNoAsk = (landing: LandingView) =>1725 landing.ask === undefined && landing.opened === undefined;17262038/** One project's service over the ports. */1727export const projectService = (1728 name: ProjectName1729): Effect.Effect<ProjectApi, never, ProjectPorts> =>1730 Effect.gen(function* () {
5 unmodified lines
1736 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));17451746 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>1747 Effect.provideContext(effect, ports);17482064 // ----------------------------------------------------------- hydrate20651749 const hydrate: Effect.Effect<Hydrated> = Effect.gen(function* () {1750 const snapshot = yield* store.load();17511752 const policy = yield* Option.match(
37 unmodified lines
1790 snapshot,1791 };1792 });17932111 /** 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 );18002119 /** 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));18032123 /** 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 lines
1811 !h.ratchets.some((held) => ratchetKey(held) === ratchetKey(row))1812 ),1813 ];18142135 /** 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);18192141 /** 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 lines
1848 ({ row }) => row.ask === ask && sameHandle(row.claimant, handle)1849 )1850 );18512174 /** 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 lines
1876 Option.map(h.policy, ({ claims }) => claims),1877 () => defaultClaims1878 );18792203 /**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 lines
1907 )1908 );1909 });19102238 /**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);19141915 return (
1 unmodified line
1917 snapshot.layers.every((row) => readable.has(row.name))1918 );1919 };19202252 /** `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 }));19272260 /**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 line
1933 withPorts(facts).pipe(1934 Effect.flatMap((found) => layered(snapshotNow(h, writes), found))1935 );19362274 // ------------------------------------------------------------ commit22752276 /**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 lines
19921993 return outbox;1994 });19952340 // ------------------------------------------------------------ settle23412342 /** Sets the project's alarm to its earliest pending deadline or retry. */1996 const armAlarm = Effect.gen(function* () {1997 const h = yield* hydrate;19981999 const deadlines = [
6 unmodified lines
2006 yield* alarms.set(Array.min(deadlines, DateTime.Order));2007 }2008 });20092357 /**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 lines
20302031 yield* armAlarm;2032 });20332385 /**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 lines
20552056 return answered;2057 });20582417 // ------------------------------------------------------------ claims24182419 /** 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 lines
2090 writes.asks.set(ask, { ...open.value, state: next });2091 }2092 };20932455 /**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 lines
21522153 askAfter(h, writes, ask, step);2154 });21552522 // ------------------------------------------------------------ policy25232524 /** 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 lines
2197 )2198 );2199 });22002570 /**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 lines
2210 })),2211 })2212 );22132588 /**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 lines
2228 )2229 );2230 }).pipe(Effect.orDie);22312611 /**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;22342620 // 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 lines
2259 },2260 };2261 });22622649 /**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 lines
2285 : landing;2286 });2287 });22882680 // --------------------------------------------------------- generated26812682 /** 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 );22962691 /**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 lines
2359 writes.project.set("row", moved);2360 });23612362 /**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 lines
2384 return yield* Effect.orDie(Effect.failCause(cause));2385 });23862387 /**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 lines
2432 )2433 );2434 });24352848 /**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 lines
2474 now2475 );2476 });24772898 /** 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));24802902 /**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 lines
2489 writeLocked(queue, (h, writes, now) =>2490 Effect.tap(body(h, writes, now), () => afterLandings(h, writes, now))2491 );24922919 /** 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 lines
2507 );2508 });25092510 /**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 lines
25722573 return LandedSha.make(tip.value);2574 });25753008 // ------------------------------------------------------------ answers30093010 /** 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 lines
2638 ...Option.getOrElse(judgedRun, () => ({})),2639 };2640 };26413077 /** 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 lines
2698 )2699 );2700 });27013138 /** The claim that answered an ask, answered by its landing. */2702 const answerClaim = (2703 h: Hydrated,2704 writes: Writes,2705 ask: AskId,
16 unmodified lines
2722 }2723 ),2724 });27253163 /** 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]);27283167 /**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 lines
2768 writes.events.push(askClosed(parent.value, at.sha, at.now));2769 }2770 };27713215 /**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 lines
2832 );2833 }2834 });28353285 /** 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 lines
2896 RunChecks: () => Effect.succeed(handed),2897 });2898 };28993350 /**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 lines
2934 (made) => ({ fresh: true, verdict: Option.some(made) })2935 );2936 };29373392 /** 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 lines
2968 DateTime.addDuration(input.now, "1 second")2969 );2970 };29713427 /** 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 lines
3002 (row) => input.writes.outbox.push(row)3003 );3004 };30053462 /**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 lines
3153 measured: Option.some<Measured>({ declared, escapes }),3154 };3155 });31563627 /** 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 lines
3180 );3181 }3182 };31833655 /**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 lines
3203 })),3204 ]);3205 };32063684 /** 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 lines
3333 outcome: outcomeOf(state),3334 };3335 });33363815 // ------------------------------------------------------------ writes38163817 /**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 lines
3353 now3354 );3355 };33563844 /**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 lines
33803381 return Option.none<LandingView>();3382 });33833876 /**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 lines
3439 );3440 }34413442 // 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);34453446 const mine = isSourceNamespace(owner)3447 ? input.import !== undefined &&
76 unmodified lines
35243525 return { landed };3526 });35274028 /**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 lines
35663567 return stated;3568 });35694075 /** 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 lines
3598 }),3599 (refusals) => Array.findFirst(refusals, isTouchedJudge)3600 );36014108 /**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 lines
36373638 return { lane: lane.value.lane, runs };3639 });36404151 /**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 lines
36613662 return [];3663 });36644180 /**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 lines
36893690 return once;3691 });36924213 /**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 lines
3714 : []3715 );3716 };37174244 /**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 lines
3790 tree,3791 };3792 });37934326 /**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 lines
38373838 return Effect.map(landing, ({ sha }) => ({ credits, requestId, sha }));3839 };38404377 /**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 lines
39483949 return Result.succeed({ ask, main, opens, row });3950 });39514497 /**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 lines
3998 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 lines
4051 decider: caller,4052 files: input.files,4053 });40544609 /**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 lines
4139 })4140 );4141 });41424702 /** 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: ObjectId
25 unmodified lines
4172 })4173 );4174 };41754736 /**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 lines
4205 want: wanted.want,4206 };4207 });42084774 /** 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 lines
43674368 return { released: step.effects.length > 0 };4369 });43704937 /** 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 lines
4418 ),4419 });4420 };44214989 /**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 lines
45374538 return refusals;4539 });45405114 /**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 lines
45694570 return Effect.succeed(Option.map(given, ({ record }) => record.receipt));4571 };45725151 /** 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 lines
4714 { ask: input.ask, main: live.value.landed, now }4715 );4716 });47175297 /** 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 lines
4736 ),4737 { discard: true }4738 );47395320 // ------------------------------------------------------------ reads53214740 const statusOf = (caller: Person) =>4741 Effect.gen(function* () {4742 const h = yield* hydrate;4743
55 unmodified lines
47994800 return Effect.succeed(field("verdict", verdict));4801 });48025385 // ---------------------------------------------------------- evidence53865387 /**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 lines
48384839 return { lane, ...tailOf(kept.value) };4840 });48415433 // -------------------------------------------------------- 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.54385439 /** 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 );48455444 /** 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;48484849 return Option.flatMap(request.ask, (ask) =>
6 unmodified lines
4856 )4857 );4858 };48595459 /** 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 lines
4888 ? Option.none<HeldBackJob>()4889 : yield* visibility.heldBackJob(claim.value, h.snapshot);4890 });48915492 /**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 lines
4951 layerPaths: [...paths],4952 };4953 });49545561 /** 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;49574958 const landed = Option.flatMap(h.project, ({ landed: at }) =>
28 unmodified lines
49874988 return set.result;4989 });49905598 /** 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 lines
4999 Effect.flatMap(plan(snapshotNow(h, writes), now), (made) =>5000 applyPlan(writes, made, now)5001 );50025611 // ---------------------------------------------------------- deciders56125613 /** 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 lines
50395040 yield* settle(queue, rows);5041 });50425654 // ------------------------------------------------------------ the api56555043 const api: ProjectApi = {5044 [envSchemaMethod]: (caller) =>5045 checked(MethodSchemas[envSchemaMethod], [caller], envSchemaOf),5046 admissionPlan: (input) =>
323 unmodified lines
modified: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 */1import { ProjectEvent } from "@repo/protocol/domain/event";2import { ProjectName } from "@repo/protocol/ids";3import { Context, Schema } from "effect";4import type { Effect } from "effect";56import type { OutboxRow } from "./project-store/rows.ts";715/** An outbox row's body for the projection: one numbered event of one project. */8export const ProjectedEvent = Schema.TaggedStruct("Projected", {9 event: ProjectEvent,10 project: ProjectName,11});1213export type ProjectedEvent = typeof ProjectedEvent.Type;1423/** The read model refused or could not take the rows; they stay in the outbox. */15export class ProjectionFailed extends Schema.TaggedError<ProjectionFailed>()(16 "ProjectionFailed",17 { reason: Schema.String }18) {}1920export 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 line
modified: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 */1import type { CreditSummary } from "@repo/protocol/domain/record";2import type { Handle, ProjectName } from "@repo/protocol/ids";3import { Anonymous } from "@repo/protocol/principal";4import type { ProjectExists, UnknownProject } from "@repo/protocol/refusal";
3 unmodified lines
89export 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") {}2031/**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 */21export const creditsFor = (22 handle: Handle,23 projects: readonly ProjectName[]24): Effect.Effect<readonly CreditSummary[], never, Projects> =>
15 unmodified lines
modified: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 */1import type { RequestId } from "@repo/protocol/ids";2import { Effect, Option, Schema } from "effect";34import { enqueue, LandingQueue, next as admitNext, settle } from "./landing.ts";514/** No request waiting, none landing. */6export const emptyQueue: LandingQueue = { active: Option.none(), order: [] };78const decodeQueue = Schema.decodeUnknownEffect(LandingQueue);910const encodeQueue = Schema.encodeEffect(LandingQueue);1121/** The queue as the store held it: `null` until a commit first writes one. */12/** `null` until a commit first writes one. */13export const queueOf = (stored: Schema.Json): Effect.Effect<LandingQueue> =>14 stored === null15 ? Effect.succeed(emptyQueue)16 : Effect.orDie(decodeQueue(stored));1727/** The queue as the store keeps it. */18export const storedQueue = (queue: LandingQueue): Effect.Effect<Schema.Json> =>19 Effect.orDie(encodeQueue(queue));2031/** Whether `id` holds the landing slot. */21export const holdsSlot = (queue: LandingQueue, id: RequestId): boolean =>22 Option.contains(queue.active, id);2335/** A move of the queue, and the request it admitted to the slot, if any. */24export interface Moved {25 readonly admitted: Option.Option<RequestId>;26 readonly queue: LandingQueue;27}2841/**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 */29export const askToLand = (queue: LandingQueue, id: RequestId): Moved => {30 const { admit, queue: moved } = admitNext(enqueue(queue, id));3132 return { admitted: admit, queue: moved };33};3451/** `id` leaves the line or the slot, and the next in line is admitted if the slot is free. */35export const leave = (queue: LandingQueue, id: RequestId): Moved => {36 const { admit, queue: moved } = admitNext(settle(queue, id));3738 return { admitted: admit, queue: moved };
1 unmodified line
modified: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 */1import { sameRatchet } from "@repo/checks/kinds/ratchet";2import type {3 RaiseRatchet,4 RatchetCount,
2 unmodified lines
7import type { Choice } from "@repo/protocol/domain/decision";8import type { LandedSha, RatchetName } from "@repo/protocol/ids";9import { Array, Option } from "effect";1021/** A ratchet's baseline in one territory, and the landed SHA that set it. */11export interface RatchetBaseline {12 readonly ratchet: RatchetName;13 readonly territory: string;14 readonly count: number;15 readonly setAt: LandedSha;16}1729/** A baseline a landing lowered, from what to what. */18export interface Lowered {19 readonly ratchet: RatchetName;20 readonly territory: string;21 readonly before: number;22 readonly after: number;23}2437/** The baselines after a landing, and the ones it lowered. */25export interface BaselinesAfterLanding {26 readonly baselines: readonly RatchetBaseline[];27 readonly lowered: readonly Lowered[];28}2930const baselineOf = (baselines: readonly RatchetBaseline[], key: RatchetKey) =>31 Array.findFirst(baselines, sameRatchet(key));3246/**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. */34export 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 lines
6869 return { baselines: [...kept, ...first], lowered };70};7192/** Whether a choice gives a raise its way: `accept` (or `adopt`) does, `decline` and `revert` don't. */72const raisesOn = {73 accept: true,74 adopt: true,75 decline: false,76 revert: false,77} as const satisfies Record<Choice, boolean>;78100/**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. */80export const decideRaise = (81 baselines: readonly RatchetBaseline[],82 subject: RaiseRatchet,83 choice: Choice,
21 unmodified lines
modified: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 */1import {2 AskId,3 Handle,4 keyOf,
3 unmodified lines
8} from "@repo/protocol/ids";9import type { ProjectName } from "@repo/protocol/ids";10import { Data, Option, Schema } from "effect";1121/** A claim's fork, as `@repo/protocol/ids` spells it. */12export { claimForkName } from "@repo/protocol/ids";1324/** What a repo is, read from its name alone. */14export 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" };2829export const RepoKind = Data.taggedEnum<RepoKind>();3031const asKey = Schema.decodeOption(ProjectKey);3246/** The project a repo name's first part names: its key, read back (ADR 0032). */33const asProject = (first: string) => Option.flatMap(asKey(first), nameOfKey);3435const asAsk = Schema.decodeOption(AskId);3637const asHandle = Schema.decodeOption(Handle);3853/** The word that names a working fork where a claim's fork names its ask. */39const WORKING = "me";4056/** What `name` says it is; `Unknown` for any name the platform never makes. */41export 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("--");4445 const kind = Option.flatMap(46 asProject(first),
25 unmodified lines
7273 return Option.getOrElse(kind, () => RepoKind.Unknown());74};7591/** A person's working fork: `<key>--me--<handle in lowercase>`. */76export 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 */1import type { ProjectListing } from "@repo/protocol/domain/front-page";2import type { ProjectName } from "@repo/protocol/ids";3import type { Posture } from "@repo/protocol/posture";4import { Array as Arr, Cause, Context, DateTime, Effect, Option } from "effect";56import { Projects } from "./projects.ts";730/** A project's standing posture as it is kept between lists. */8export 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}1743/** Where a list keeps each project's standing posture between lists. */18export 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}2655/**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. */28export const StandingPostures = Context.Reference<StandingPosturesApi>(29 "project/StandingPostures",30 {31 defaultValue: () => ({
2 unmodified lines
34 }),35 }36);3770/** How many projects a list reads at once (the platform handlers' `FAN_OUT`). */38const READS_AT_ONCE = 8;3973/** `effect`, or `fallback` with a warning if it fails: an interruption stays one. */40const orWarn = <A, E>(41 effect: Effect.Effect<A, E>,42 fallback: A,43 warning: string
4 unmodified lines
48 : Effect.as(Effect.logWarning(warning, cause), fallback)49 );5051/**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 */56export const withStandingPosture = (57 listed: readonly ProjectListing[]58): Effect.Effect<readonly ProjectListing[], never, Projects> =>
62 unmodified lines
modified: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.3import { HeldBackResult } from "@repo/protocol/domain/answer";4import type { ClaimView } from "@repo/protocol/domain/claim";5import { AtLeastOne } from "@repo/protocol/domain/common";6import type { LandingView } from "@repo/protocol/domain/landing";
17 unmodified lines
2425import type { ProjectSnapshot, ProjectWrites } from "./project-store.ts";26import type { PinnedSuite } from "./project-store/rows.ts";2745/**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. */29export const VisibilityEffect = Schema.Struct({30 body: Schema.Json,31 id: Schema.NonEmptyString,32});3334export type VisibilityEffect = typeof VisibilityEffect.Type;3557/** What a port asks the service to write in the call's commit, and to settle after it. */36export interface VisibilityPlan {37 readonly effects: readonly VisibilityEffect[];38 readonly writes: ProjectWrites;39}4063/** A plan that changes nothing. */41export const noPlan: VisibilityPlan = { effects: [], writes: {} };4266/** How far a person may reach into a layer: clone it, push to it, or neither. */43export const LayerAccess = Schema.Literals(["none", "read", "write"]);4445export type LayerAccess = typeof LayerAccess.Type;4671/**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. */48export 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 lines
66});6768export type HeldBackJob = typeof HeldBackJob.Type;69101/**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 */70export interface HeldBackJudgement {71 readonly refusals: readonly (HeldBackFailed | AttemptsExhausted)[];72 readonly trailer: Option.Option<string>;73 readonly writes: ProjectWrites;74}75113/** A judgement that refuses nothing, adds no trailer and counts nothing. */76const unjudged: HeldBackJudgement = {77 refusals: [],78 trailer: Option.none(),79 writes: {},80};81120/**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 */82export const AdmissionRun = Schema.TaggedUnion({83 OnKnownBad: { area: AreaName, job: HeldBackJob, tree: CommitSha },84 OnMain: { area: AreaName, attempt: Schema.Int, job: HeldBackJob },85});8687export type AdmissionRun = typeof AdmissionRun.Type;88132/**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 */89export const AdmissionPlan = Schema.Struct({90 admit: Schema.Struct({91 greenOnMainRuns: AtLeastOne,92 redOnKnownBadAtLeast: AtLeastOne,
6 unmodified lines
99});100101export type AdmissionPlan = typeof AdmissionPlan.Type;102151/** What an admission's runs came to, as the `Answer` Workflow reports them: each run with its area bits. */103export const AdmissionReport = Schema.Struct({104 head: CommitSha,105 layer: LayerName,106 results: Schema.Array(
5 unmodified lines
112});113114export type AdmissionReport = typeof AdmissionReport.Type;115165/** What the gate's stage 1 takes from visibility for one pusher (`ProjectApi.layerFacts`). */116export 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});121122export type LayerFacts = typeof LayerFacts.Type;123175/** A claim as the port sees it: whose, on which ask, and the suite it was pinned to. */124export interface PinnedClaim {125 readonly ask: AskId;126 readonly claimant: Handle;127 readonly pinned: PinnedSuite;128}129182/**183 * Typed visibility as the project service reaches it. `snapshot` is always184 * the project as the call has it so far.185 */130export 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 line
136 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 line
173 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}198278/** A project without typed visibility: Open, no layers, nothing held back, an empty ledger. */199export const noVisibility: VisibilityPort = {200 access: () => Option.none(),201 admissionPlan: () => Effect.succeedNone,202 heldBackJob: () => Effect.succeedNone,
15 unmodified lines
218 settle: () => Effect.succeed(true),219 standing: () => ({ posture: "open", until: Option.none() }),220};221302/**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 */222export const ProjectVisibility = Context.Reference<VisibilityPort>(223 "project/ProjectVisibility",224 { defaultValue: () => noVisibility }225);226312/** The default, said out loud: a project without typed visibility. */227export const NoVisibility: Layer.Layer<never> = Layer.succeed(228 ProjectVisibility,229 noVisibility230);231232const decodePolicy = Schema.decodeUnknownOption(Schema.toCodecJson(Policy));233320/** The policy a snapshot's project row holds, decoded: what a port reads its rules from. */234export const policyIn = (snapshot: ProjectSnapshot): Option.Option<Policy> =>235 Option.flatMap(snapshot.project, (row) =>236 row.policy === undefined ? Option.none() : decodePolicy(row.policy)237 );238326/** The suite a claim view shows: its pinned root. */239export const suiteOf = (240 pinned: Option.Option<PinnedSuite>241): Pick<ClaimView, "suite"> =>242 Option.match(pinned, {
3 unmodified lines
modified:packages/project/test/attention/credits.test.ts-3 removed
10 unmodified lines
11import { creditsByArea } from "../../src/attention/credits.ts";1213const now = at("2026-10-07T12:00:00Z");1415/** `datekit`: asks in `packages/parser` and `packages/format`. */15const datekit = aProject({ now }).pipe(16 withAsk({ id: "parse-iso", territory: "packages/parser" }),17 withAsk({ id: "format-week", territory: "packages/format" })18);1921/** `burrow`: an ask in `packages/p1`. */20const burrow = aProject({ name: "alice/burrow", now }).pipe(21 withAsk({ id: "drop-legacy-p1", territory: "packages/p1" })22);23
11 unmodified lines
35 handle,36 role,37});3841/** A landing in `scenario` answering `ask` (none: a decider's own landing), with these trailers. */39const landing = (40 scenario: Scenario,41 seed: string,42 ask: string | undefined,
149 unmodified lines
modified:packages/project/test/attention/decisions.test.ts+1 added-4 removed
59 unmodified lines
60const proposal = minted.proposal();6162const { OpenProposal, StrayPush } = DecisionSubject.cases;6364/** Every subject, with the default it must have: doing nothing lets nothing in. */64/** Every subject's default: doing nothing lets nothing in. */65const defaults: readonly (readonly [DecisionSubject, Choice])[] = [66 [OpenProposal.make({ proposal }), "decline"],67 [DecisionSubject.cases.Finish.make({ ask, head: sha("answer") }), "decline"],68 [
43 unmodified lines
112const evidence = [113 Evidence.make({ label: "check", value: "packages/parser/test/iso.test.ts" }),114];115116/** A decision for alice and dana, opened at noon with a 14-day expiry. */116const open = (subject: DecisionSubject) =>117 openDecision({118 deciders: [alice, dana],119 evidence,
9 unmodified lines
129const strayPush = open(StrayPush.make({ after, before, ref: main }));130131const later = at("2026-10-08T09:30:00Z");132134/** Alice's choice on `decision`, made the next morning. */133const choose = (decision: Decision, choice: Choice, by = alice) =>134 decide([decision], {135 by,136 choice,
1 unmodified line
138 note: Option.none(),139 now: later,140 });141144/** The word `decision` records when alice chooses `choice`. */142const words = (decision: Decision, choice: Choice) =>143 Result.map(144 choose(decision, choice),145 ({ decision: { decided } }) => decided?.choice
310 unmodified lines
modified:packages/project/test/attention/promote.test.ts-14 removed
31 unmodified lines
32import { promotions } from "../../src/attention/promote.ts";33import type { FinishRecord, Promotion } from "../../src/attention/promote.ts";34import { FinishersFromChecks, MethodSchemas } from "../../src/project.ts";3536/** The sdk's `lintToZero` kind, as the policy lists it. */36const lintToZeroKind = {37 checkKind: "lintToZero",38 claimers: "vouched",39 finish: "never",
3 unmodified lines
43 requires: ["want", "check", "territory"],44 strength: "assertion",45} as const;4648/** The project's own lint, which prints JSON: what its ratchet counts with. */47const lint = Command.make("bun run lint --format json");4849const scenario = aProject({ deciders: ["alice"], people: ["bob"] }).pipe(50 withKind(lintToZeroKind)51);5255/** Datekit with a ratchet counted by its JSON lint, so a lint command is known. */53const policy: Policy = {54 ...scenario.policy,55 ratchets: [56 {
15 unmodified lines
72const askFile = RepoPath.make(73 `${Brand.configDir}/asks/no-date-equality-in-src-date.ask.ts`74);7579/** A finish by alice in `src/date`, with no rule from its lanes and no note unless given. */76const finish = (77 ask: string,78 day: string,79 more: Partial<FinishRecord> = {}
15 unmodified lines
95const diffMonths = finish("diff-months", "2026-10-05", {96 note: Option.some(`Date compared with === again: \`${rule}\``),97});98103/** Two finishes whose notes name `no-date-equality`, one of them in backticks. */99const pair = [compareDays, diffMonths];100101const promote = (102 finishes: readonly FinishRecord[],
14 unmodified lines
117 project: scenario.project,118 });119};120126/** A decision's evidence without the files its proposal holds. */121const shown = ({ decision, proposal }: Promotion) =>122 decision.evidence.filter(123 ({ label }) => !proposal.files.some((path) => path === label)124 );125132/** The files a proposal holds, read back from its decision's evidence by path, as an accepted proposal's are. */126const heldFiles = ({ decision, proposal }: Promotion) =>127 proposal.files.flatMap((path) =>128 decision.evidence.flatMap(({ label, value }) =>129 label === path ? [{ content: value, path }] : []
58 unmodified lines
188 ]);189 });190});191199/** One evidence line of each promotion, by its label. */192const lineOf = (made: readonly Promotion[], label: string) =>193 made.flatMap(({ decision }) =>194 decision.evidence.flatMap((each) =>195 each.label === label ? [each.value] : []196 )197 );198207/** `decision` as a decider left it: declined by alice the day it opened. */199const declined = (decision: Decision): Decision => ({200 ...decision,201 decided: { at: now, by: alice, choice: "decline" },202});203204const carol = Handle.make("carol");205215/** Two finishes in `src/date` whose notes both say `note`. */206const 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 lines
542 );543 });544});545556// ------------------------------------------- the ask file, through the sdk557558/** One workspace, `parser`, and alice as the project's initializer. */546const facts = Schema.decodeSync(EvaluationFacts)({547 ci: [],548 initializer: "alice",549 now: "2026-10-07T12:00:00.000Z",
11 unmodified lines
561 "});",562 "",563].join("\n");564578/** What promotions' ask files state, as the rules evaluator reads them back from a config folder. */565const evaluated = (made: readonly Promotion[]) =>566 Effect.gen(function* () {567 const evaluator = yield* RulesEvaluator;568
91 unmodified lines
modified:packages/project/test/attention/proposals.test.ts-3 removed
36 unmodified lines
37 fork: RepoName.make("alice__datekit--me--carol"),38 head: sha("carol's fix for ISO weeks"),39};4041/** Carol, vouched, with no proposal open and no record, proposes a new ask. */41const byCarol = (42 standing: Partial<Parameters<typeof ProposalCommand.Propose>[0]> = {}43) =>44 ProposalCommand.Propose({
10 unmodified lines
55 who: Person.make({ handle: carol }),56 ...standing,57 });5860/** Carol flags the open ask `parse-iso`. */59const flagBy = (60 standing: Partial<Parameters<typeof ProposalCommand.Flag>[0]> = {}61) =>62 ProposalCommand.Flag({
173 unmodified lines
236 ]);237 });238});239242/** A proposal opened now, and one opened now and accepted since. */240const proposals = () => {241 const opened = Result.getOrThrow(proposalOf(byCarol()));242243 const accepted: Proposal = {
27 unmodified lines
modified:packages/project/test/attention/record.test.ts-3 removed
8 unmodified lines
9import { meets, recordOf } from "../../src/attention/record.ts";1011const now = at("2026-10-07T12:00:00Z");1213/** `datekit`, with an ask in `packages/parser` and one in `packages/format`. */13const 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 lines
23const alice = Handle.make("alice");2425const bob = Handle.make("bob");2628/** A landing `days` before `now`, by `author`, answering `ask` (none: a decider's own landing). */27const landing = (28 seed: string,29 options: {30 readonly ask?: string;
15 unmodified lines
46 ? view47 : { ...view, ask: AskId.make(options.ask) };48};4952/** Alice's record as it stands at `now` under the default window (30 days, 365 days). */50const recordAt = (51 landings: readonly LandingView[],52 reverted: readonly LandingView[] = []53) =>
125 unmodified lines
modified:packages/project/test/attention/today.test.ts-5 removed
27 unmodified lines
28const alice = handle("alice");2930const dana = handle("dana");3132/** Thursday noon: alice opens Today. */32const now = at("2026-10-08T12:00:00Z");3334const minted = ids();3537/** A decision on a vouch for `name`, for alice and dana, expiring `expiresIn` hours from now. */36const vouchFor = (name: string, expiresIn: number): Decision =>37 openDecision({38 deciders: [alice, dana],39 evidence: [],
20 unmodified lines
60const p7 = vouchFor("p7", 150);6162const p8 = vouchFor("p8", 200);6366/** The eight, given out of order. */64const eight = [p5, p1, p8, p3, p2, p7, p4, p6];6566const fresh = { finishes: 0, total: 5, used: 0 };67
137 unmodified lines
205 expect(page.newcomers).toStrictEqual([handle("carol"), handle("erin")]);206 });207208 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 lines
250 );251 });252});253258/** Each spend, in order, kept as the day's one row per decider. */254const spendAll = (255 spends: readonly {256 readonly decider: Handle;257 readonly on: "decision" | "finish";
87 unmodified lines
modified:packages/project/test/attention/vouch.test.ts-13 removed
31 unmodified lines
32 requires: ["want", "check", "territory"],33 strength: "assertion",34};3536/**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 */36const scenario = aProject({ now }).pipe(37 withVouches(["bob", "Erin"], ["mallory"]),38 withKind({ ...fix, claimers: "anyone", name: "open" }),39 withKind({
35 unmodified lines
75);7677const { policy } = scenario;7886/** The policy with another vouch mode. */79const inMode = (mode: Policy["vouch"]["mode"]): Policy => ({80 ...policy,81 vouch: { ...policy.vouch, mode },82});
25 unmodified lines
108const carol = Handle.make("carol");109110const mallory = Handle.make("mallory");111120/** One held landing on carol's record, in `area` of `project` (datekit's by default). */112const held = (113 area: string,114 seed: string,115 project: ProjectName = scenario.project
10 unmodified lines
126const notVouched = Result.fail(new NotVouched({}));127128const denounced = Result.fail(new Denounced({}));129139/**140 * May a person of this standing, record and landings claim ask `id` under141 * `rules`, with `mentor` named on the ask?142 */130const claim = (131 id: string,132 who: Standing,133 options: {
332 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { creditsOf } from "@repo/git/trailers";4import type { HarnessAudit } from "@repo/protocol/audit";
50 unmodified lines
55const ask: Ask = Option.getOrThrow(56 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)57);5866/** The ask's own files: its file in the config folder, and its check. */59const askFiles = Array.make(60 { content: `export default "${parseIso}";\n`, path: ask.file },61 {62 content: [
19 unmodified lines
82 ["packages/parser/package.json", '{ "name": "parser" }\n'],83 ["packages/parser/src/parse.ts", "export const parse = (s) => 0;\n"],84];8594/** Main once the ask opened on it, with the parser at `step`. */86const 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 lines
99 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))100 );101});102112/** The project made and first pushed by alice, and parse-iso opened red first. */103const opened = (api: ProjectApi) =>104 Effect.gen(function* () {105 yield* api.initProject(alice, {});106
15 unmodified lines
122 return (yield* api.openAsk(alice, { ask: parseIso, files: askFiles }))123 .landed;124 });125136/**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 */126const answered = (127 policy: Policy,128 pushes: readonly Option.Option<HarnessAudit>[],129 claimedAnewAt?: number
90 unmodified lines
220const claudeCode = Option.some({ harness: "claude-code", model: "haiku" });221222const pi = Option.some({ harness: "pi", model: "kimi-k3" });223241/** A whole story's limit: real git objects and every gate stage, to catch a hang. */224const story = { timeout: 30_000 };225226describe("Assisted-by on an answer's landing", () => {227 it.effect(
85 unmodified lines
modified:packages/project/test/brief.test.ts-7 removed
18 unmodified lines
19import type { ProjectApi } from "../src/project.ts";20import { projectService } from "../src/project.ts";21import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";2223/**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 */23const scenario = aProject().pipe(24 withAsk({ id: "parse-iso", territory: "packages/parser" }),25 withAsk({ id: "trim-input", territory: "." })26);
33 unmodified lines
60 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],61 ["src/trim.ts", "export const trim = (s) => s;\n"],62];6369/** alice opens `id`: its file and its check, scripted red twice on main. */64const openRed = (api: ProjectApi, id: string) =>65 Effect.gen(function* () {66 const { check, file } = askOf(id);67
24 unmodified lines
9293 return yield* api.openAsk(alice, { ask: AskId.make(id), files });94 });95102/** The brief's Territory section, its one line. */96const territoryLine = (brief: string) =>97 brief.split("## Territory\n\n")[1]?.split("\n")[0];9899describe("an ask's brief", () => {
31 unmodified lines
modified:packages/project/test/claim.model.test.ts+3 added-77 removed
25 unmodified lines
26 transition,27} from "../src/claim.ts";28import type { ClaimResult, ClaimStep, Live } from "../src/claim.ts";2930// 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.3330const HOUR = 3_600_000;3136/** The defaults: warned after 2 quiet hours, lapsed after 24. */32const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };3334const project = ProjectName.make("alice/datekit");35
12 unmodified lines
48const cap = 3;4950const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");5157/** Four people; `Bob` checks that a fork's name lowercases the handle. */52/** `Bob` checks that a fork's name lowercases the handle. */53const People = Schema.Literals(["alice", "Bob", "carol", "dave"]);5460/**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 */55const Standing = Schema.Struct({56 atCap: Schema.Boolean,57 blocked: Schema.Boolean,58 denounced: Schema.Boolean,59 unvouched: Schema.Boolean,60});6172/** One thing that happens to the ask, as a history step names it. */62const Move = Schema.TaggedUnion({63 Claim: { standing: Standing, who: People },64 Land: { who: People },65 Push: { who: People },
2 unmodified lines
68});6970type Move = typeof Move.Type;7183/**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 */72const Layout = Schema.Literals(["shared", "race1", "race2", "race3"]);7374type Layout = typeof Layout.Type;7592/** One step of a history: whole hours waited since the last one, then a move. */76interface Step {77 readonly after: number;78 readonly move: Move;79}
5 unmodified lines
8586/** True one time in six; it shrinks to false, so a shrunk claim meets nothing. */87const rare = roll(5).pipe(Arbitrary.map((n) => n === 5));88106/** About half of all claims meet no refusal. */89const standing = Arbitrary.all({90 atCap: rare,91 blocked: rare,92 denounced: rare,
17 unmodified lines
110);111112const ticks = Arbitrary.Constant(Move.cases.Tick.make({}));113132/** Moves by weight; shrinking a roll towards 0 turns a move into an alarm. */114const weighted = [115 ticks,116 ticks,117 pushes,
9 unmodified lines
127const moves = roll(weighted.length - 1).pipe(128 Arbitrary.flatMap((n): Arbitrary.Arbitrary<Move> => weighted[n] ?? ticks)129);130150/** 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. */132const histories = Arbitrary.array(133 Arbitrary.all({ after: roll(26), move: moves }),134 { maxLength: 40 }135);
2 unmodified lines
138139const raceOf = (layout: Layout) =>140 ({ race1: 1, race2: 2, race3: 3, shared: 1 })[layout];141161/** A live claim: `Live` or `Warned`. */142const live = (state: ClaimState): Option.Option<Live> =>143 ClaimState.match(state, {144 Answered: () => Option.none(),145 Lapsed: () => Option.none(),
2 unmodified lines
148 Released: () => Option.none(),149 Warned: Option.some<Live>,150 });151172/** Any state that holds or held a claim. */152const held = (state: ClaimState): Option.Option<Live> =>153 ClaimState.match(state, {154 Answered: Option.some<Live>,155 Lapsed: Option.some<Live>,
6 unmodified lines
162const isLive = (state: ClaimState) => Option.isSome(live(state));163164const ms = (time: DateTime.Utc) => DateTime.toEpochMillis(time);165187/** The time a claim's deadlines count from: its last push, or its making. */166const quietSince = (claim: Live) =>167 Option.getOrElse(claim.lastPushAt, () => claim.openedAt);168169const encode = Schema.encodeSync(ClaimState);170171const same = (left: ClaimState, right: ClaimState) =>172 JSON.stringify(encode(left)) === JSON.stringify(encode(right));173196/** One call to `transition`, as the model service made it. */174interface Call {175 readonly before: ClaimState;176 readonly command: ClaimCommand;177 readonly now: DateTime.Utc;178}179180type Claim = typeof ClaimCommand.cases.Claim.Type;181205/** Whether the person making a claim holds the ask's live claim already. */182const holds = (before: ClaimState, made: Claim) =>183 Option.exists(live(before), (holder) => holder.claimant === made.who.handle);184209/**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 */185const owed = (before: ClaimState, made: Claim) =>186 Option.map(187 Arr.findFirst(188 [
12 unmodified lines
201 ),202 ([refusal]) => refusal203 );204235/**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 */205const claimsAsOwed = (206 { before, command }: Call,207 result: ClaimResult208): readonly string[] => {
41 unmodified lines
250 }),251 });252};253288/** Who pushed or released; none for any other command. */254const 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});261297/**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 */262const holderOnly = (263 { before, command }: Call,264 result: ClaimResult265): readonly string[] =>
17 unmodified lines
283 });284 },285 });286326/** Whether a push comes from the holder of a live claim. */287const holderPushes = ({ before, command }: Call) =>288 ClaimCommand.guards.Push(command) &&289 Option.exists(live(before), (holder) => holder.claimant === command.who);290331/** An invariant over one successful call, naming what it found broken. */291type Invariant = (call: Call, done: ClaimStep) => readonly string[];292334/** The holder's push keeps the claim live and counts from now. */293const pushesRenew: Invariant = (call, { state }) =>294 holderPushes(call) &&295 !(296 ClaimState.guards.Live(state) &&
3 unmodified lines
300 )301 ? ["the holder's push makes the claim live from now"]302 : [];303346/**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 */304const forksOnlyNewClaims: Invariant = ({ before }, { effects, state }) => {305 const forks = effects.filter(ClaimEffect.$is("MakeFork"));306307 const opens =
14 unmodified lines
322 ? []323 : ["a new claim makes one fork, named for its claimant"];324};325372/** Access is revoked exactly when a live claim ends. */326const revokesWhenLiveEnds: Invariant = ({ before }, { effects, state }) => {327 const revokes = effects.filter(ClaimEffect.$is("RevokeAccess")).length;328 const ends = isLive(before) && !isLive(state);329
1 unmodified line
331 ? []332 : ["access is revoked once when a live claim ends"];333};334382/** Deadlines count from the last push, or from the claim, never from later. */335const deadlinesCount: Invariant = ({ now }, { state }) =>336 Option.match(held(state), {337 onNone: () => [],338 onSome: (claim) => {
10 unmodified lines
349 ];350 },351 });352401/** Alarms are set only for later, and events happen now. */353const noTimeTravel: Invariant = ({ now }, { effects }) => [354 ...effects355 .filter(ClaimEffect.$is("SetAlarm"))356 .flatMap((alarm) =>
5 unmodified lines
362 ms(emitted.event.at) === ms(now) ? [] : ["an event that is not now"]363 ),364];365415/** A claim is warned no earlier than warnsAt, and lapses no earlier than lapsesAt. */366const deadlinesKept: Invariant = ({ before, now }, { state }) =>367 Option.match(held(state), {368 onNone: () => [],369 onSome: (claim) => [
9 unmodified lines
379 : []),380 ],381 });382433/**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 */383const alarmsNextDeadline: Invariant = ({ before }, { effects, state }) =>384 Option.match(live(state), {385 onNone: () => [],386 onSome: (claim) => {
11 unmodified lines
398 ];399 },400 });401457/** Answered never changes; Released changes only by a fresh claim. */402const endsAreFinal: Invariant = ({ before, command }, { state }) => [403 ...(ClaimState.guards.Answered(before) && !same(before, state)404 ? ["Answered is terminal"]405 : []),
14 unmodified lines
420 alarmsNextDeadline,421 endsAreFinal,422];423480/**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 */424const brokenBy = (call: Call, result: ClaimResult): readonly string[] => [425 ...claimsAsOwed(call, result),426 ...holderOnly(call, result),427 ...Result.match(result, {
2 unmodified lines
430 invariants.flatMap((invariant) => invariant(call, done)),431 }),432];433494/** The ask's claim states, by slot: the claimant's handle, or `ask` when shared. */434type Slots = ReadonlyMap<string, ClaimState>;435497/** The model project service between two steps. */436interface World {437 readonly now: DateTime.Utc;438 readonly slots: Slots;439}
6 unmodified lines
446447const liveOutside = (slots: Slots, slot: string) =>448 [...slots].filter(([key, state]) => key !== slot && isLive(state)).length;449512/** A command for one slot. */450interface Addressed {451 readonly command: ClaimCommand;452 readonly slot: string;453}
2 unmodified lines
456 command,457 slot,458});459523/** The commands the project service would send for a move, and where. */460const commandsFor = (461 layout: Layout,462 slots: Slots,463 move: Move
30 unmodified lines
494 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 });503569/** Why an alarm left a claim past a deadline it reached, if it did. */504const 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 lines
511 ? Option.some("an alarm left a claim unwarned past warnsAt")512 : Option.none();513 });514581/** What the whole ask keeps after a step: the race, and alarms that catch up. */515const brokenAfter = (layout: Layout, world: World, move: Move) => {516 const states = [...world.slots.values()];517518 const holders = new Set(
11 unmodified lines
530 : []),531 ];532};533601/** Takes one step: the next world, and what broke on the way. */534const 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 lines
551552 return { broken: [...broken, ...brokenAfter(layout, next, move)], next };553};554623/** Runs a history; returns its first bad step and what that step broke. */555const firstBreak = (layout: Layout, steps: readonly Step[]) => {556 let world: World = { now: start, slots: new Map() };557558 for (const [index, step] of steps.entries()) {
8 unmodified lines
567568 return [];569};570640/**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. */572const generated = { timeout: 30_000 };573574describe("the claim lifecycle, over generated histories", generated, () => {575 it.prop(
10 unmodified lines
modified:packages/project/test/claim.test.ts-5 removed
32 unmodified lines
33const { Claim, Land, Push, Release, Tick } = ClaimCommand.cases;3435const HOUR = 3_600_000;3637/** The defaults: warned after 2 quiet hours, lapsed after 24. */37const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };3839const project = ProjectName.make("alice/datekit");40
10 unmodified lines
51const bob = Handle.make("Bob");5253const carol = Handle.make("carol");5456/** Bob's fork: his handle in lowercase. */55const fork = RepoName.make("alice__datekit--parse-iso--bob");5657const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");5861/** `hours` after the claim was made. */59const at = (hours: number) => DateTime.add(start, { hours });6064/** A claim by a vouched person under their cap, on an ask nobody holds. */61const claimBy = (62 handle: Handle,63 standing: Partial<Omit<typeof Claim.Type, "_tag" | "who">> = {}64) =>
12 unmodified lines
77 });7879const open = ClaimState.cases.Open.make({ ask });8085/** Bob's claim, made at `start`, never pushed to. */81const fresh = {82 ask,83 base,84 claimant: bob,
370 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import type { ProjectApi } from "@repo/project/project";3import { keyOf, LandedSha, ProjectName } from "@repo/protocol/ids";4import { untouchable } from "@repo/testkit/untouchable";
5 unmodified lines
10const project = ProjectName.make("alice/datekit");1112const landed = LandedSha.make("4".repeat(40));1319/** A project's record, as the façade reads it: only these three. */14const api = untouchable<ProjectApi>("ProjectApi", {15 forks: () => Effect.succeed([]),16 head: () => Effect.succeed({ landed }),17 landings: () => Effect.succeed([]),
31 unmodified lines
modified: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 */1import { RefName, RepoHost } from "@repo/artifacts/repo-host";2import type { RefUpdate } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";
31 unmodified lines
36import type { FsClient, TreeEntry } from "isomorphic-git";3738import type { CodeProject } from "../src/code.ts";3949/** A file's content: text, bytes, a symlink's target, or a submodule's commit. */40export type Content = Data.TaggedEnum<{41 Bytes: { readonly bytes: Uint8Array };42 Gitlink: { readonly commit: string };43 Link: { readonly target: string };
1 unmodified line
45}>;4647export const Content = Data.taggedEnum<Content>();4859/** Paths and what each holds. */49export type Tree = readonly (readonly [path: string, content: Content])[];5051interface Source {52 readonly fs: FsClient;
53 unmodified lines
106107 return yield* Effect.promise(() => writeTree({ ...source, tree: entries }));108 });109121/**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 */110export const writer = Effect.gen(function* () {111 const source = { fs: memoryFs(), gitdir: "/source.git" };112113 yield* Effect.promise(() =>
31 unmodified lines
145146 return CommitSha.make(oid);147 });148164 /** 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 lines
168 // 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 );171188 /** `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 lines
191192 return { annotated, commit, push };193});194212/** A PNG's signature and the start of its header: a NUL in the first bytes. */195export const png = Uint8Array.of(196 0x89,197 0x50,198 0x4e,
7 unmodified lines
206 0,207 0x0d208);209228/** 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. */211export const big = `${"x".repeat(1023)}\n`.repeat(1536);212213export const svg =214 '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>\n';
37 unmodified lines
252 ...without(third, "README.md"),253 ["README.md", text("# datekit, landed\n")],254];255274/** The claim fork the project's record lists. */256export 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};262282/** The project's one landing, on `sha`. */263const landingOf = (sha: CommitSha, parent: CommitSha): LandingView => ({264 ask: AskId.make("parse-iso"),265 assisted: [],266 author: Handle.make("bob"),
3 unmodified lines
270 project,271 sha: LandedSha.make(sha),272});273294/** A project's record, fixed: main at `head`, `landed` its only landing. */274const recordOf = (275 name: RepoName,276 head: CommitSha,277 landed: readonly LandingView[]
5 unmodified lines
283 project: Option.getOrThrow(nameOfKey(ProjectKey.make(name))),284 repo: name,285});286308/**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`. */288export 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 lines
325 code: recordOf(repo, c4, [landingOf(c4, c3)]),326 };327});328357/**358 * A history of `count` commits: the first adds `once.txt`, and every one359 * after changes only `count.txt`.360 */329export const longHistory = (count: number) =>330 Effect.gen(function* () {331 const git = yield* writer;332 const name = RepoName.make("oscabriel__longkit");
23 unmodified lines
356357 return { code: recordOf(name, head, []), shas };358 });359392/**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 */360export const growingHistory = (count: number) =>361 Effect.gen(function* () {362 const git = yield* writer;363 const name = RepoName.make("oscabriel__growkit");
22 unmodified lines
386387 return { code: recordOf(name, head, []), shas };388 });389426/** One root commit of `count` files. */390export const wide = (count: number) =>391 Effect.gen(function* () {392 const git = yield* writer;393 const name = RepoName.make("oscabriel__widekit");
9 unmodified lines
403404 return { code: recordOf(name, sha, []), sha };405 });406444/**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 */407export const linkedReadmes = Effect.gen(function* () {408 const git = yield* writer;409 const name = RepoName.make("oscabriel__linkkit");410
20 unmodified lines
431432 return { code: recordOf(name, sha, []) };433});434479/**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. */436export const overlappingTrees = (437 reading: Ref.Ref<boolean>,438 peak: Ref.Ref<number>,439 kind: "blob" | "file" | "tree" = "tree"
38 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RepoHost, RepoSession, Revision } from "@repo/artifacts/repo-host";3import type { RepoSessionApi } from "@repo/artifacts/repo-host";4import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";
28 unmodified lines
33const format = RepoPath.make("src/format.ts");3435const text = (value: string) => Content.Text({ text: value });3647/**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 */37interface 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 lines
53 peak: 0,54 trees: 0,55};5674/** How long a read of the object `id` takes, once a test sets it. */57type Delay = Option.Option<(id: string) => Duration.Duration>;5877/**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 */59const counted = (seen: Ref.Ref<Seen>, delay: Ref.Ref<Delay>) =>60 Layer.effect(61 RepoHost,62 Effect.gen(function* () {
40 unmodified lines
103 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 lines
127 project,128 sha: LandedSha.make(sha),129});130155/** A project's record whose landings a test may add to, each batch asked for counted. */131const recordOf = (head: CommitSha) =>132 Effect.gen(function* () {133 const landed = yield* Ref.make<readonly LandingView[]>([]);134 const asked = yield* Ref.make(0);
15 unmodified lines
150151 return { asked, code, landed };152 });153179/** histkit's tree: its README and `src/format.ts`. */154const filesOf = (formatted: string, readme: string): Tree => [155 ["README.md", text(readme)],156 ["src/format.ts", text(formatted)],157];158185/**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 */159const history = Effect.gen(function* () {160 const git = yield* writer;161162 const c1 = yield* git.commit("Adopt", filesOf("a\nb\n", "# one\n"), [], 1);
34 unmodified lines
197198 return { c1, c3, c4, grown, still };199});200232/** `effect` on a fresh isolate: a code cache of its own. */201const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>202 Effect.provide(effect, CodeCacheLive(100));203236/** `effect` with a store of its own, empty: the whole walk, from nothing. */204const fromNothing = <A, E, R>(effect: Effect.Effect<A, E, R>) =>205 onIsolate(Effect.provide(effect, CodeStoreMemory));206240/** A view's ranges, the commits it names and where it stopped. */207const whyOfView = (view: {208 readonly ranges: readonly unknown[];209 readonly commits: readonly { readonly sha: CommitSha }[];210 readonly stoppedAt?: CommitSha;
2 unmodified lines
213 ranges: view.ranges,214 stoppedAt: view.stoppedAt,215});216251/** A test body over the counting host and one store every isolate shares. */217const within = <A, E>(218 body: (counts: {219 readonly seen: Ref.Ref<Seen>;220 readonly delay: Ref.Ref<Delay>;
26 unmodified lines
247 const again = yield* onIsolate(whyOf(code, Option.none(), format));248 const { blobs, commits, files, logs, trees } = yield* Ref.get(seen);249250 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 lines
294 )295 );296});297334/** The first page of `src/format.ts`'s log from `from`. */298const formatLog = (from: CommitSha) => ({299 at: Option.some(from),300 from: 0,301 limit: 30,
62 unmodified lines
364 const next = yield* onIsolate(logOf(code, formatLog(grown)));365 const counts = yield* Ref.get(seen);366 const whole = yield* fromNothing(logOf(code, formatLog(grown)));367405 // `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 lines
379 Effect.gen(function* () {380 const { c1, grown } = yield* history;381 const { code, landed } = yield* recordOf(grown);382421 // 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 lines
398 )399 );400});401441/**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 */402const deepHistory = (count: number) =>403 Effect.gen(function* () {404 const git = yield* writer;405 const shas: CommitSha[] = [];
52 unmodified lines
458 ),459 long460 );461506 // 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);472519 // 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] ?? "";474475 yield* Ref.set(seen, none);476 yield* Ref.set(
63 unmodified lines
540 path: Option.some(RepoPath.make("a/b")),541 });542543 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 long
108 unmodified lines
658 })659 );660});661712/**713 * The memory store, the session each commit, tree, blob and log read ran714 * in noted in `sessions`, in order.715 */662const sessioned = (663 sessions: Ref.Ref<readonly Option.Option<RepoSessionApi>[]>664) => {665 const noted = <A, E>(read: Effect.Effect<A, E>) =>
21 unmodified lines
687 })688 ).pipe(Layer.provide(RepoHostMemory));689};690745/** How many sessions `sessions` names, and whether a read ran in none. */691const sessionsIn = (sessions: readonly Option.Option<RepoSessionApi>[]) => ({692 outside: sessions.some(Option.isNone),693 sessions: new Set(sessions.flatMap(Option.toArray)).size,694});
99 unmodified lines
794 yield* whyOf(code, Option.none(), RepoPath.make("a/b/c/d/deep.txt"));795796 const { blobs, files, trees } = yield* Ref.get(seen);797853 // 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 lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3import { ProjectName, RepoPath } from "@repo/protocol/ids";4import { Effect, Option } from "effect";
177 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { Effect, Exit, Layer, Logger, Option } from "effect";34import { CodeStore } from "../src/code-store.ts";
5 unmodified lines
1011/** A key one byte past R2's limit of 1,024. */12const tooLong = "k".repeat(1025);1320/** A put of `value` under `key`, then a get of it. */14const putThenGet = Effect.gen(function* () {15 const store = yield* CodeStore;1617 yield* store.put(key, '{"lines":[]}');1819 return yield* store.get(key);20});2129/** A bucket over a map, whose `get` or `put` throws when told to. */22const bucketOf = (fails: {23 readonly get?: boolean;24 readonly put?: boolean;25}) => {
22 unmodified lines
4849 return bucket;50};5160/** Every message logged while `effect` runs, beside its exit. */52const logged = <A, E>(effect: Effect.Effect<A, E>) =>53 Effect.gen(function* () {54 const messages: unknown[] = [];55
91 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3import { packageOf } from "@repo/protocol/domain/code";4import { ProjectName, RepoName } from "@repo/protocol/ids";
3 unmodified lines
8import type { CodeProject } from "../src/code.ts";9import { sortTags } from "../src/code/refs.ts";10import { writer } from "./code-fixtures.ts";1119/** Changesets' kinds of tag, shuffled: plain, scoped and unscoped. */12const shuffled = [13 "get-workspaces@1.0.11",14 "@changesets/cli@2.27.1",15 "@changesets/cli@2.3.0",
3 unmodified lines
19 "v1.10.0-beta.1",20 "v1.10.0",21];2231/** The order a reader meets them in. */23const ordered = [24 "v2.0.0",25 "v1.10.0",26 "v1.10.0-beta.1",
69 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import type { LandingView } from "@repo/protocol/domain/landing";
54 unmodified lines
59 onSome: (at) => ({ parent: LandedSha.make(at) }),60 }),61});6271/**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 */63const history = Effect.gen(function* () {64 const git = yield* writer;6566 const adopted = yield* git.commit(
77 unmodified lines
144145 return { adopted, asked, code, iso, landings, readme, week };146});147161/**162 * The memory store, with each blob `readBlob` is asked for, and each file163 * `readFile` reads whole at a commit, counted in `reads`.164 */148const countedBy = (reads: Ref.Ref<readonly string[]>) =>149 Layer.effect(150 RepoHost,151 Effect.gen(function* () {
196 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import { Brand } from "@repo/brand";
51 unmodified lines
56const path = (text: string) => Option.some(RepoPath.make(text));5758const page = { at: main, from: 0, limit: 30, path: Option.none() };5968/**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.61const long = { timeout: 30_000 };6263describe("a project's refs", () => {64 it.effect(
445 unmodified lines
510511 expect(commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);512 }).pipe(Effect.provide(overlappingTrees(reading, peak, "file")));513525 // 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 long
83 unmodified lines
602603/** 150 KiB of text: fourteen of them run past a diff's 2 MiB of text. */604const sizable = (name: string) => `${name.padEnd(1023, "y")}\n`.repeat(150);605618/**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 */606const twentyFiles = Effect.gen(function* () {607 const git = yield* writer;608 const name = RepoName.make("twentykit");609
87 unmodified lines
697 long698 );699});700718/** The memory store, with each blob `readBlob` is asked for counted in `reads`. */701const blobsCountedBy = (reads: Ref.Ref<number>) =>702 Layer.effect(703 RepoHost,704 Effect.gen(function* () {
8 unmodified lines
713 });714 })715 ).pipe(Layer.provide(RepoHostMemory));716735/** What the store keeps under a key, as a diff, if it holds one that decodes. */717const keptUnder = (key: string) =>718 Effect.map(719 Effect.flatMap(Effect.service(CodeStore), (store) => store.get(key)),720 Option.flatMap(
80 unmodified lines
801 })802 );803});804824/** The memory store, with each tree id `readTree` is asked for counted in `reads`. */805const countedBy = (reads: Ref.Ref<readonly string[]>) =>806 Layer.effect(807 RepoHost,808 Effect.gen(function* () {
62 unmodified lines
871 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;878879 yield* Effect.forkDetach(880 cache.through("burrow:text:abandoned", Effect.never)
14 unmodified lines
modified:packages/project/test/deciders.test.ts+1 added-59 removed
55 unmodified lines
56import { CheckScript, composedAt, mergedAt, Pusher, worldOf } from "./world.ts";5758const people = ["bob", "carol", "dave", "erin", "eve", "frank"];5960/**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 */60const scenario = aProject({ people }).pipe(61 withVouches(["bob", "carol", "erin", "eve", "frank"]),62 withKind({63 checkKind: "redThenGreen",
21 unmodified lines
85 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });8687const alice = person("alice");8893/** alice, as a sign-in provider that capitalizes handles names her. */89const aliceSignedIn = Person.make({ handle: Handle.make("Alice") });9091const bob = person("bob");92
23 unmodified lines
116117const daysAfter = (from: DateTime.Utc, count: number) =>118 DateTime.add(from, { days: count });119125/** The project as alice first pushes it. */120const start: Files = [121 [122 "package.json",123 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',
6 unmodified lines
130 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],131 ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],132];133140/** An ask's own files: its file in the config folder, and its check. */134const askFiles = (id: string) => {135 const { check, file, territory } = askOf(id);136137 const subject = territory.module;
16 unmodified lines
154 }155 );156};157165/** Where a canonical `main` stands now. */158const tipOf = (name: RepoName) =>159 Effect.gen(function* () {160 const refs = yield* (yield* RepoHost).refs(name).pipe(Effect.orDie);161
1 unmodified line
163 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))164 );165 });166175/** Where datekit's `main` stands now. */167const mainTip = tipOf(repo);168178/** A commit's author, committer, parents and trailers. */169const 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 lines
176 });177178const scheduled = ScheduledAlarm.use(({ at }) => at);179190/** The project's rows as its store keeps them. */180const stored = ProjectStore.use((store) => store.load());181193/** alice makes a project's first landing: `files`, pushed to its empty repo. */182const made = (api: ProjectApi, on: RepoName, files: Files = start) =>183 Effect.gen(function* () {184 yield* api.initProject(alice, {});185
5 unmodified lines
191192 return api;193 });194207/** alice makes datekit and pushes its first commit. */195const begun = Effect.gen(function* () {196 yield* advanceTo("2026-10-07T12:00:00Z");197198 return yield* made(yield* projectService(project), repo);199});200214/** The check of an ask with these files, scripted to fail twice on main as it now stands. */201const redOnMain = (202 files: Array.NonEmptyReadonlyArray<{203 readonly content: string;204 readonly path: RepoPath;
7 unmodified lines
212 checker.script(composed, redThenGreen, ["failed", "failed"])213 );214 });215230/** alice opens `id`, its check scripted red twice on main. */216const openRed = (api: ProjectApi, id: string, on: RepoName = repo) =>217 Effect.gen(function* () {218 const files = askFiles(id);219
3 unmodified lines
223 });224225const lanes = [redThenGreen, LaneName.make("lint"), LaneName.make("types")];226242/** `files` with `path` holding `content`, added or replaced. */227const changed = (files: Files, path: string, content: string): Files => [228 ...files.filter(([each]) => each !== path),229 [path, content],230];231248/** The files main holds after `ids`' asks opened on it. */232const 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];238256/**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 */239const answered = (240 api: ProjectApi,241 input: {242 readonly change: readonly [path: string, content: string];
46 unmodified lines
289 });290291const firstDecision = DecisionId.make("dec-000001");292314/** carol proposes `trim-input` with its files; alice accepts it. */293const proposing = (api: ProjectApi) =>294 Effect.gen(function* () {295 const files = askFiles("trim-input");296
42 unmodified lines
339 third,340 };341 });342365/** carol's proposal, left alone for its fourteen days. */343const 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 lines
360 today: yield* api.today(alice),361 };362 });363387/**388 * carol proposes `trim-input`, and alice accepts it while the Checker cannot389 * run its check; then again, once it can.390 */364const acceptingBlocked = (api: ProjectApi) =>365 Effect.gen(function* () {366 const files = askFiles("trim-input");367
29 unmodified lines
397 proposals: between.proposals.map(({ state }) => state),398 };399 });400428/** datekit, where alice decides the packages and frank the config folder only. */401const splitDeciders = {402 policy: {403 ...scenario.policy,404 deciders: [
5 unmodified lines
410 ],411 },412};413442/** carol proposes `trim-input` in the packages; who is asked to decide it. */414const askedToDecide = Effect.gen(function* () {415 const api = yield* begun;416417 const { proposal } = yield* api.proposeAsk(carol, {
162 unmodified lines
580 )581 );582});583613/** bob's answer to the `polish` ask `format-date`, finished by alice. */584const finishing = (api: ProjectApi) =>585 Effect.gen(function* () {586 yield* openRed(api, "format-date");587
43 unmodified lines
631 waiting,632 };633 });634665/**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 */635const finishingOnTop = (api: ProjectApi) =>636 Effect.gen(function* () {637 yield* openRed(api, "format-date");638
167 unmodified lines
806 })807 );808});809844/** alice makes her working fork, and lands a change of her own from it. */810const landingOwn = (api: ProjectApi) =>811 Effect.gen(function* () {812 const host = yield* RepoHost;813 const forked = yield* api.fork(alice);
166 unmodified lines
980 })981 );982});9831019/**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 */984const vouchingWorld = Layer.effect(985 RulesEvaluator,986 Effect.gen(function* () {987 const evaluator = yield* RulesEvaluator;
13 unmodified lines
1001 });1002 })1003).pipe(Layer.provideMerge(worldOf(scenario, "memory")));10041045/** The vouch file on main. */1005const vouchFileNow = Effect.gen(function* () {1006 const host = yield* RepoHost;1007 const at = yield* mainTip;1008
7 unmodified lines
10161017 return Option.map(bytes, (read) => new TextDecoder().decode(read));1018});10191061/** alice vouches for dave, who could not claim before, and denounces erin. */1020const vouching = (api: ProjectApi) =>1021 Effect.gen(function* () {1022 yield* openRed(api, "lex-tokens");1023 yield* openRed(api, "parse-iso");
83 unmodified lines
1107 })1108 );1109});11101153/** Six proposals an hour apart, from three people, and alice taking the first. */1111const filling = (api: ProjectApi) =>1112 Effect.gen(function* () {1113 const proposers = [carol, eve, frank, carol, eve, frank];1114
95 unmodified lines
1210});12111212const burrow = ProjectName.make("alice/burrow");12131257/** One landing's credit in the parser module. */1214const row = (name: ProjectName, role: "Asked-by" | "Signed-off-by") => ({1215 area: "parser",1216 count: 1,1217 project: name,1218 role,1219});12201265/** bob answers `parse-iso` in datekit, and carol in burrow, both made through `Projects`. */1221const crediting = Effect.gen(function* () {1222 yield* advanceTo("2026-10-07T12:00:00Z");12231224 const projects = yield* Projects;
31 unmodified lines
1256 dave: yield* creditsFor(dave.handle, among),1257 };1258});12591305// 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.1261describe("credits", () => {1262 it.effect("count a person's roles by project and area across projects", () =>1263 Effect.map(1264 crediting.pipe(
13 unmodified lines
1278 )1279 );1280});12811328/** A commit pushed straight onto canonical main, past the platform. */1282const strayOnto = (first: CommitSha) =>1283 Pusher.use((pusher) =>1284 pusher.push(1285 repo,
6 unmodified lines
1292 "Stray"1293 )1294 );12951343/** canonical main's move as OnPush reports it to the project: from nobody the platform knows. */1296const reported = (1297 api: ProjectApi,1298 eventId: string,1299 move: { readonly after: CommitSha; readonly before?: CommitSha }
6 unmodified lines
1306 ref: "refs/heads/main",1307 repo,1308 });13091358/**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 */1310const strayReported = Effect.gen(function* () {1311 const api = yield* begun;1312 const first = yield* mainTip;1313
26 unmodified lines
1340 stray,1341 };1342});13431397/**1398 * A push to canonical main the platform did not make, reported by OnPush,1399 * which opens the decision, then decided by alice.1400 */1344const strayDecided = (choice: "accept" | "decline") =>1345 Effect.gen(function* () {1346 const api = yield* begun;1347 const host = yield* RepoHost;
27 unmodified lines
1375 tipTree: yield* treeOf(tip),1376 };1377 });13781436/** canonical main deleted past the platform, as OnPush reports it, then decided by alice. */1379const deletedDecided = (choice: "accept" | "decline") =>1380 Effect.gen(function* () {1381 const api = yield* begun;1382 const first = yield* mainTip;
108 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { CheckSpec } from "@repo/protocol/domain/check";4import { ProjectEvent } from "@repo/protocol/domain/event";
64 unmodified lines
69 : RepoPath.make(`${Brand.configDir}/checks/parse-iso.test.ts`),70 }71);7278/** A commit that is no landing: imported history, say. */73const imported = CommitSha.make("b".repeat(40));7475const read = Effect.gen(function* () {76 yield* advanceTo("2026-10-07T12:00:00Z");
67 unmodified lines
144 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 lines
175 const policy = Option.getOrThrow(176 Option.fromUndefinedOr(got.after.policy.policy)177 );178188 // 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 policy
7 unmodified lines
190 })191 );192});193204/** A commit SHA made of one digit, for rows written straight to the store. */194const shaOf = (digit: string) => LandedSha.make(digit.repeat(40));195207/**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`. */197const olderRows = Effect.gen(function* () {198 yield* advanceTo("2026-10-07T12:00:00Z");199200 const api = yield* projectService(project);
55 unmodified lines
256 })257 );258});259275/** A rules evaluator whose every config folder fails to evaluate. */260const failingRules = Layer.succeed(261 RulesEvaluator,262 RulesEvaluator.of({263 call: () => Effect.succeed(false),
3 unmodified lines
267 ),268 })269);270287/** The policy after a first push of `files`, with every evaluation failing. */271const unevaluatedAfter = (files: Files) =>272 Effect.gen(function* () {273 yield* advanceTo("2026-10-07T12:00:00Z");274
38 unmodified lines
modified:packages/project/test/draft-settle.test.ts-9 removed
37 unmodified lines
38import type { ProjectApi } from "../src/project.ts";39import { projectService } from "../src/project.ts";40import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";4142/** datekit, decided by alice alone, with one `fix` ask carol may want. */42const scenario = aProject({ people: ["carol", "dave"] }).pipe(43 withVouches(["carol", "dave"]),44 withAsk({ id: "parse-week", territory: "packages/parser" })45);
42 unmodified lines
88const askSource = `export default "parse-week";\n`;8990const testSource = `import { parseWeek } from "../src/parse.ts";\n`;9193/** The drafted ask's files: its ask file and its failing test. */92const files = Array.make(93 { content: askSource, path: ask.file },94 { content: testSource, path: testPath }95);
15 unmodified lines
111});112113const mainRef = RefName.make("refs/heads/main");114117/** Every draft run the project started, in order. */115class Started extends Context.Service<116 Started,117 { readonly runs: Effect.Effect<readonly DraftParams[]> }118>()("test/Started") {}119123/** `DraftRuns` that records each run it is asked to start. */120const recorded = Layer.effectContext(121 Effect.gen(function* () {122 const started = yield* Ref.make<readonly DraftParams[]>([]);123
4 unmodified lines
128);129130const world = Layer.mergeAll(worldOf(scenario, "memory"), recorded);131136/** alice makes datekit; carol proposes the want with a draft. */132const proposed = Effect.gen(function* () {133 yield* advanceTo("2026-10-08T12:00:00Z");134135 const api: ProjectApi = yield* projectService(project);
24 unmodified lines
160);161162const runs = Started.use(({ runs: all }) => all);163169/** The drafted files composed onto main, their check scripted red there. */164const redOnMain = Effect.gen(function* () {165 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);166167 const tip = LandedSha.make(
8 unmodified lines
176});177178const firstDecision = DecisionId.make("dec-000001");179186/** datekit as above, with dave deciding the parser beside alice. */180const parserByDave = {181 policy: {182 ...scenario.policy,183 deciders: [
27 unmodified lines
211 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 lines
546 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 lines
modified:packages/project/test/drafting.model.test.ts+3 added-36 removed
26 unmodified lines
27import type { ProjectApi } from "../src/project.ts";28import { projectService } from "../src/project.ts";29import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";3031// 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.3731const scenario = aProject({ people: ["carol", "dave"] }).pipe(32 withVouches(["carol", "dave"]),33 withAsk({ id: "parse-week", territory: "packages/parser" })34);
51 unmodified lines
86 model,87 refusal: new NotRedFirst({}),88});8997/** Which of the (at most two) proposals a move is about, by the order they were made in. */90const Which = Schema.Literals([0, 1]);91100/** A settle's round: the proposal's current one, or one either side of it. */92const Round = Schema.Literals(["current", "before", "after"]);9394type Round = typeof Round.Type;95105/** One thing that happens, as a history step names it. */96const Move = Schema.TaggedUnion({97 Accept: { which: Which },98 Expire: {},99 Propose: {},
5 unmodified lines
105106const roll = (maximum: number) =>107 Arbitrary.schema(Schema.Int.check(Schema.isBetween({ maximum, minimum: 0 })));108119/** Mostly the first proposal, so one proposal lives through many moves. */109const anyWhich = roll(3).pipe(Arbitrary.map((n) => (n === 3 ? 1 : 0)));110122/** Mostly the current round; a stale one now and then. */111const rounds: readonly Round[] = [112 "current",113 "current",114 "current",
5 unmodified lines
120const anyRound = roll(rounds.length - 1).pipe(121 Arbitrary.map((n) => rounds[n] ?? "current")122);123136/** Mostly someone who may draft again; now and then someone who may not. */124const drafters: readonly People[] = [125 "carol",126 "alice",127 "carol",
23 unmodified lines
151152const expires = Arbitrary.Constant(Move.cases.Expire.make({}));153154/**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 */158const weighted = [159 settles,160 redrafts,
13 unmodified lines
174const histories = Arbitrary.array(moves, { maxLength: 16 });175176const offset = (round: Round) => ({ after: 1, before: -1, current: 0 })[round];177191/** The labels of a proposal's evidence that are not its files. */178const notFiles = new Set([179 "want",180 "territory",181 "red first",
11 unmodified lines
193 );194195const roundOf = (proposal: Proposal) => proposal.draft?.round ?? 1;196211/** The round a settle names for `proposal`, never below the first. */197const settledRound = (proposal: Proposal, round: Round) =>198 Math.max(1, roundOf(proposal) + offset(round));199215/** Whether a settle of `round` is the proposal's current, unsettled round, while it is open. */200const isCurrent = (proposal: Proposal, round: number) =>201 proposal.state === "open" &&202 proposal.draft !== undefined &&203 DraftState.guards.Drafting(proposal.draft) &&
3 unmodified lines
207 decision.evidence.flatMap(({ label }) =>208 notFiles.has(label) ? [] : [label]209 );210227/** The files each proposal held when a round of it last settled ready. */211type ReadyFiles = ReadonlyMap<ProposalId, readonly RepoPath[]>;212230/** `ready`, with the files of every proposal that reads `Ready` in `snapshot`. */213const readyIn = (ready: ReadyFiles, snapshot: ProjectSnapshot): ReadyFiles =>214 new Map([215 ...ready,216 ...snapshot.proposals.flatMap((proposal) =>
2 unmodified lines
219 : []220 ),221 ]);222241/**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 */223const brokenBy = (224 move: Move,225 before: ProjectSnapshot,226 after: ProjectSnapshot,
67 unmodified lines
294];295296const stored = ProjectStore.use((store) => store.load());297324/** The drafted files composed onto main as it now stands, scripted red there. */298const redOnMain = Effect.gen(function* () {299 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);300301 const tip = LandedSha.make(
6 unmodified lines
308 checker.script(composed, redThenGreen, ["failed", "failed"])309 );310});311339/** One move, as a person or the platform makes it; a refusal is part of the history. */312const step = (api: ProjectApi, before: ProjectSnapshot, move: Move) => {313 const proposalAt = (which: number) =>314 Option.fromUndefinedOr(before.proposals[which]);315
48 unmodified lines
364 }),365 });366};367396/** Runs a history over a fresh project; returns its first bad step and what it broke. */368const firstBreak = (history: readonly Move[]) =>369 Effect.gen(function* () {370 yield* advanceTo("2026-10-08T12:00:00Z");371
25 unmodified lines
397398 return [];399 }).pipe(Effect.provide(worldOf(scenario, "memory")));400430/**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. */402const generated = { timeout: 120_000 };403404describe("drafting, over generated histories", generated, () => {405 it.effect.prop(
9 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { EvidenceStore, LogRef, logRefOf } from "@repo/checks/evidence-store";4import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";
29 unmodified lines
3435const person = (name: string) =>36 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });3744/** The project's decider. */38const alice = person("alice");3947/** The claimant whose answer failed its `unit` lane. */40const bob = person("bob");4150/** Neither: vouched for, but no claimant of that answer and no decider. */42const carol = person("carol");4344const parseIso = AskId.make("parse-iso");45
10 unmodified lines
56 ],57 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],58];5969/** The ask's own files: its file in the config folder, and its check. */60const askFiles = () => {61 const ask = Option.getOrThrow(62 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)63 );
16 unmodified lines
80 }81 );82};8394/** The log bob's `unit` lane left on his answer's first merge. */84const failing = [85 "FAIL packages/parser/test/parse.test.ts > parses ISO weeks",86 "AssertionError: expected 52 to be 53",87].join("\n");88100/** The name the log is kept under. */89const bobsLog = logRefOf({ attempt: 1, lane: unit, project, requestId });9091const mainTip = Effect.gen(function* () {92 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);
2 unmodified lines
95 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))96 );97});98111/**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 */99const answered = (text: string = failing) =>100 Effect.gen(function* () {101 yield* advanceTo("2026-10-07T12:00:00Z");102
83 unmodified lines
186 [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 lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";4import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";
28 unmodified lines
33const project = ProjectName.make("alice/kit");3435const repo = RepoName.make(keyOf(project));3644/**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 */37const tree: Files = [38 ["package.json", JSON.stringify({ name: "kit", workspaces: ["packages/*"] })],39 [40 "lefthook.yml",
45 unmodified lines
86];8788const run: RunBlock = { checks: {}, test: Command.make("bun test {path}") };89105/** `tree` committed and pushed to the project's repo, as its first commit. */90const pushed = Effect.gen(function* () {91 const host = yield* RepoHost;92 const client = yield* gitClient(memoryFs());93
75 unmodified lines
169 })170 );171});172189// ------------------------------------------------------------ through the gate190173const scenario = aProject({ people: ["bob"] }).pipe(174 withVouches(["bob"]),175 withAsk({ id: "parse-iso", territory: "packages/parser" })176);
17 unmodified lines
194const ask = Option.getOrThrow(195 Array.findFirst(scenario.policy.asks, ({ id }) => id === parseIso)196);197216/** The ask's own files: its file in the config folder, and its check. */198const 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 lines
204 : RepoPath.make("test/parse-iso.test.ts"),205 }206);207227/**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 */208const hooked: Files = [209 [210 "package.json",211 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',
16 unmodified lines
228 ],229 ["scripts/hooks/shell-policy.ts", "export {};\n"],230];231255/**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 */232const hookScriptPushed = Effect.gen(function* () {233 yield* advanceTo("2026-10-07T12:00:00Z");234235 const api = yield* projectService(scenario.project);
62 unmodified lines
modified:packages/project/test/generated.test.ts-13 removed
23 unmodified lines
24const parent = LandedSha.make("1".repeat(40));2526const landed = LandedSha.make("2".repeat(40));2728/** The policy before the landing: lint and types. */28const before: Policy = { ...scenario.policy, at: parent };2931/** The same policy at the landing, read again there: nothing it says changed. */30const unchanged: Policy = { ...scenario.policy, at: landed };3134/** The policy at the landing, with a unit lane added to the run block. */32const withUnit: Policy = {33 ...unchanged,34 run: Schema.decodeSync(RunBlock)({35 checks: {
8 unmodified lines
44const skill = `.agents/skills/${project}-contribute/SKILL.md`;4546const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;4751/**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 */48const 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 lines
68 { content: agents, path: "AGENTS.md" },69 ];70 });7180/** The project's own AGENTS.md, with a block the platform wrote before. */72const ownAgents = [73 "# Datekit",74 "",75 "Our notes.",
5 unmodified lines
81 "More notes.",82 "",83].join("\n");8494/** A tree that holds `files` and nothing else. */85const treeOf =86 (files: Readonly<Record<string, string>>) =>87 (path: string): Effect.Effect<Option.Option<string>> =>88 Effect.succeed(Option.fromUndefinedOr(files[path]));8990const at = DateTime.makeUnsafe("2026-10-07T12:00:00Z");91102/** alice's own landing from her working fork, which changed the config. */92const aliceLands: LandingView = {93 assisted: [],94 author: alice,95 credits: [{ handle: alice, role: "Signed-off-by" }],
2 unmodified lines
98 project,99 sha: landed,100};101113/** The first adoption: the initializer's first push, crediting no one. */102const firstPush: LandingView = {103 assisted: [],104 author: alice,105 credits: [],
21 unmodified lines
127 );128129const subjectOf = (message: string) => message.split("\n")[0] ?? "";130143/** Whom the follow-up of `landing`, after the run block changed, credits. */131const creditOf = (landing: LandingView) =>132 Effect.map(133 followUp({ after: withUnit, before: Option.some(before), landing }),134 Option.map(({ credits }) => credits)
176 unmodified lines
modified: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 */1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4import { ProjectEvent } from "@repo/protocol/domain/event";
20 unmodified lines
25const bob = Person.make({ handle: Handle.make("bob") });2627const mainRef = RefName.make("refs/heads/main");2835/**36 * The project's row as an import written before sources were kept left it37 * (ADR 0031): the same row without `importedFrom`.38 */29const forgetSource = ProjectStore.use((store) =>30 Effect.flatMap(store.load(), ({ project: row }) =>31 Option.match(row, {32 onNone: () => Effect.void,
4 unmodified lines
37);3839const masterRef = RefName.make("refs/heads/master");4051/**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 */41const upstreamOnMaster = Effect.gen(function* () {42 const host = yield* RepoHost;43 const upstream = RepoName.make("upstream");44 const client = yield* gitClient(memoryFs());
12 unmodified lines
5758 return { tip, url: "https://example.com/upstream.git" };59});6075/** What the project holds after its imports: its head, its row, and its repo's refs. */61const 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 lines
69 state: Option.map(snapshot.project, (row) => row.state),70 };71});7288/**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`. */74const stillCopying = Effect.gen(function* () {75 const host = yield* RepoHost;76 const copying = yield* Ref.make(false);77
242 unmodified lines
modified: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.