Merge build/209-claim-lifecycle: a claim moves only by a pure transition, and a model test proves it
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 766f380, b938092 · Browse files · 3 files·+1579 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+1579 added−0 removed
- tests:+1105 added−0 removed
- other:+474 added−0 removed
Provenance
- Commit
7723381- Tree
5edbfda- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
766f380- Parent 2
b938092
3 files changed+1579 added−0 removed
added:packages/project/src/claim.ts+474 added
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+ */7+import { ClaimView } from "@repo/protocol/domain/claim";8+import type { ProjectEvent } from "@repo/protocol/domain/event";9+import type { Policy } from "@repo/protocol/domain/policy";10+import {11+ AskId,12+ CommitSha,13+ Handle,14+ LandedSha,15+ ProjectName,16+ RepoName,17+} from "@repo/protocol/ids";18+import { Person } from "@repo/protocol/principal";19+import {20+ AskBlocked,21+ AskFull,22+ CapReached,23+ ClaimLapsed,24+ Denounced,25+ NotClaimed,26+ NotVouched,27+} from "@repo/protocol/refusal";28+import { Array as Arr, Data, DateTime, Option, Result, Schema } from "effect";29+30+/** What a claim holds while it lasts, and keeps once it ends. */31+const claimFields = {32+ ask: AskId,33+ /** Main's landed commit when the claim was made. */34+ base: CommitSha,35+ claimant: Handle,36+ /** The claim's fork: `<project>--<ask>--<handle in lowercase>`. */37+ fork: RepoName,38+ /** The last push (or the claim) plus the policy's `lapseAfterMs`. */39+ lapsesAt: Schema.DateTimeUtcFromString,40+ lastPushAt: Schema.OptionFromOptionalKey(Schema.DateTimeUtcFromString),41+ openedAt: Schema.DateTimeUtcFromString,42+ /** The last push (or the claim) plus the policy's `warnAfterMs`. */43+ warnsAt: Schema.DateTimeUtcFromString,44+};45+46+/**47+ * Where one claim on an ask stands. `Open` holds no claim; `Live` and48+ * `Warned` are live; `Lapsed`, `Released` and `Answered` keep the claim they49+ * ended. Encoded, it is JSON, so the project store persists it as is.50+ */51+export const ClaimState = Schema.TaggedUnion({52+ /** The claimant's answer landed. */53+ Answered: { ...claimFields, landing: LandedSha },54+ /** No push came in time; the claimant may push no more. */55+ Lapsed: { ...claimFields, at: Schema.DateTimeUtcFromString },56+ Live: claimFields,57+ Open: { ask: AskId },58+ /** The claimant gave the claim up. */59+ Released: claimFields,60+ /** Live, but quiet for long enough that the claimant was warned. */61+ Warned: claimFields,62+});63+64+export type ClaimState = typeof ClaimState.Type;65+66+/** A claim's fields, which `Live` and `Warned` hold and the ended states keep. */67+export type Live = Omit<typeof ClaimState.cases.Live.Type, "_tag">;68+69+/** A project event before the store gives it its place in the sequence. */70+type Unsequenced<Event> = Event extends ProjectEvent71+ ? Omit<Event, "seq">72+ : never;73+74+/** A project event without its `seq`, which the store assigns at commit. */75+export type ProjectEventInput = Unsequenced<ProjectEvent>;76+77+/** Constructors for project events without their `seq`. */78+export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();79+80+/**81+ * What can happen to a claim. `Claim` carries what the project service knows82+ * and the lifecycle does not: how many claims the person holds (`heldByWho`)83+ * against their `cap`, how many others hold a live claim on the ask84+ * (`liveCount`) against the kind's `race`, the person's standing, and the85+ * asks this one waits on.86+ */87+export const ClaimCommand = Schema.TaggedUnion({88+ Claim: {89+ /** Main's landed commit now. */90+ base: CommitSha,91+ blockedBy: Schema.Array(AskId),92+ cap: Schema.Int,93+ denounced: Schema.Boolean,94+ heldByWho: Schema.Int,95+ liveCount: Schema.Int,96+ project: ProjectName,97+ race: Schema.Int,98+ vouched: Schema.Boolean,99+ who: Person,100+ },101+ /** The claimant's answer landed on main. */102+ Land: { landing: LandedSha },103+ /** A push reached the claim's fork. */104+ Push: { head: CommitSha, who: Handle },105+ Release: { who: Handle },106+ /** An alarm fired: a deadline may have passed. */107+ Tick: {},108+});109+110+export type ClaimCommand = typeof ClaimCommand.Type;111+112+/** What the project service does after a transition, in order. */113+export type ClaimEffect = Data.TaggedEnum<{114+ Emit: { readonly event: ProjectEventInput };115+ /** Fork the canonical repo; a retried fork converges on the same one. */116+ MakeFork: { readonly from: RepoName; readonly name: RepoName };117+ /** The claimant may push to the fork no more; the fork stays. */118+ RevokeAccess: { readonly fork: RepoName };119+ SetAlarm: { readonly at: DateTime.Utc };120+}>;121+122+export const ClaimEffect = Data.taggedEnum<ClaimEffect>();123+124+/** Every way the claim lifecycle says no. */125+export type ClaimRefusal =126+ | AskBlocked127+ | AskFull128+ | CapReached129+ | ClaimLapsed130+ | Denounced131+ | NotClaimed132+ | NotVouched;133+134+/** A transition's result: the next state and the effects that settle it. */135+export interface ClaimStep {136+ readonly effects: readonly ClaimEffect[];137+ readonly state: ClaimState;138+}139+140+/** A claim's fork: `<project>--<ask>--<handle in lowercase>` (spec §4.5). */141+export const forkName = (project: ProjectName, ask: AskId, handle: Handle) =>142+ RepoName.make(`${project}--${ask}--${handle.toLowerCase()}`);143+144+/** What `transition` returns: a step, or the refusal that changes nothing. */145+export type ClaimResult = Result.Result<ClaimStep, ClaimRefusal>;146+147+/** The state as it is, with nothing to settle: how a repeated command converges. */148+const stay = (state: ClaimState): ClaimResult =>149+ Result.succeed({ effects: [], state });150+151+const move = (152+ state: ClaimState,153+ ...effects: readonly ClaimEffect[]154+): ClaimResult => Result.succeed({ effects, state });155+156+/** A claim's own fields, whatever state holds them. */157+const claimOf = ({158+ ask,159+ base,160+ claimant,161+ fork,162+ lapsesAt,163+ lastPushAt,164+ openedAt,165+ warnsAt,166+}: Live): Live => ({167+ ask,168+ base,169+ claimant,170+ fork,171+ lapsesAt,172+ lastPushAt,173+ openedAt,174+ warnsAt,175+});176+177+/** When a claim quiet since `from` is warned, and when it lapses. */178+const deadlines = (from: DateTime.Utc, policy: Policy["claims"]) => ({179+ lapsesAt: DateTime.add(from, { milliseconds: policy.lapseAfterMs }),180+ warnsAt: DateTime.add(from, { milliseconds: policy.warnAfterMs }),181+});182+183+type Claim = typeof ClaimCommand.cases.Claim.Type;184+185+/**186+ * A new claim on an ask its maker does not hold. `AskFull` comes first, so a187+ * full ask never forks (ADR 0008); then the ask's blockers, the person's cap,188+ * and their standing, a denouncement before a missing vouch.189+ */190+const grant = (191+ ask: AskId,192+ made: Claim,193+ now: DateTime.Utc,194+ policy: Policy["claims"]195+): ClaimResult => {196+ if (made.liveCount >= made.race) {197+ return Result.fail(new AskFull({ ask }));198+ }199+200+ if (Arr.isReadonlyArrayNonEmpty(made.blockedBy)) {201+ return Result.fail(AskBlocked.of(ask, made.blockedBy));202+ }203+204+ if (made.heldByWho >= made.cap) {205+ return Result.fail(new CapReached({ cap: made.cap }));206+ }207+208+ if (made.denounced) {209+ return Result.fail(new Denounced({}));210+ }211+212+ if (!made.vouched) {213+ return Result.fail(new NotVouched({}));214+ }215+216+ const claimant = made.who.handle;217+218+ const live = ClaimState.cases.Live.make({219+ ask,220+ base: made.base,221+ claimant,222+ fork: forkName(made.project, ask, claimant),223+ lastPushAt: Option.none(),224+ openedAt: now,225+ ...deadlines(now, policy),226+ });227+228+ return move(229+ live,230+ ClaimEffect.MakeFork({231+ from: RepoName.make(made.project),232+ name: live.fork,233+ }),234+ ClaimEffect.SetAlarm({ at: live.warnsAt }),235+ ClaimEffect.Emit({236+ event: ProjectEventInput.Claimed({ ask, at: now, claimant }),237+ })238+ );239+};240+241+const claim = (242+ state: ClaimState,243+ made: Claim,244+ now: DateTime.Utc,245+ policy: Policy["claims"]246+): ClaimResult => {247+ // A live claim is its holder's to keep, and nobody else's to take.248+ const holder = (live: Live) =>249+ live.claimant === made.who.handle250+ ? stay(state)251+ : Result.fail(new AskFull({ ask: live.ask }));252+253+ return ClaimState.match(state, {254+ Answered: ({ ask }) => Result.fail(new AskFull({ ask })),255+ Lapsed: ({ ask }) => grant(ask, made, now, policy),256+ Live: holder,257+ Open: ({ ask }) => grant(ask, made, now, policy),258+ Released: ({ ask }) => grant(ask, made, now, policy),259+ Warned: holder,260+ });261+};262+263+/** Whoever holds no live claim on the ask. */264+const unclaimed = ({ ask }: { readonly ask: AskId }) =>265+ Result.fail(NotClaimed.of(ask));266+267+const push = (268+ state: ClaimState,269+ { head, who }: typeof ClaimCommand.cases.Push.Type,270+ now: DateTime.Utc,271+ policy: Policy["claims"]272+): ClaimResult => {273+ // The holder's push starts both deadlines again from now.274+ const kept = (live: Live) => {275+ if (live.claimant !== who) {276+ return Result.fail(NotClaimed.of(live.ask));277+ }278+279+ const pushed = ClaimState.cases.Live.make({280+ ...claimOf(live),281+ lastPushAt: Option.some(now),282+ ...deadlines(now, policy),283+ });284+285+ return move(286+ pushed,287+ ClaimEffect.SetAlarm({ at: pushed.warnsAt }),288+ ClaimEffect.Emit({289+ event: ProjectEventInput.Pushed({ ask: live.ask, at: now, head }),290+ })291+ );292+ };293+294+ return ClaimState.match(state, {295+ Answered: unclaimed,296+ Lapsed: (lapsed) =>297+ lapsed.claimant === who298+ ? Result.fail(ClaimLapsed.of(lapsed.ask))299+ : unclaimed(lapsed),300+ Live: kept,301+ Open: unclaimed,302+ Released: unclaimed,303+ Warned: kept,304+ });305+};306+307+const tick = (state: ClaimState, now: DateTime.Utc): ClaimResult => {308+ const reached = (deadline: DateTime.Utc) =>309+ DateTime.isGreaterThanOrEqualTo(now, deadline);310+311+ // An alarm that comes late lapses the claim without warning it first.312+ const lapse = (live: Live) =>313+ move(314+ ClaimState.cases.Lapsed.make({ ...claimOf(live), at: now }),315+ ClaimEffect.RevokeAccess({ fork: live.fork }),316+ ClaimEffect.Emit({317+ event: ProjectEventInput.Lapsed({ ask: live.ask, at: now }),318+ })319+ );320+321+ const warn = (live: Live) =>322+ move(323+ ClaimState.cases.Warned.make(claimOf(live)),324+ ClaimEffect.SetAlarm({ at: live.lapsesAt }),325+ ClaimEffect.Emit({326+ event: ProjectEventInput.Warned({ ask: live.ask, at: now }),327+ })328+ );329+330+ return ClaimState.match(state, {331+ Answered: stay,332+ Lapsed: stay,333+ Live: (live) => {334+ if (reached(live.lapsesAt)) {335+ return lapse(live);336+ }337+338+ return reached(live.warnsAt) ? warn(live) : stay(state);339+ },340+ Open: stay,341+ Released: stay,342+ Warned: (warned) =>343+ reached(warned.lapsesAt) ? lapse(warned) : stay(state),344+ });345+};346+347+const release = (348+ state: ClaimState,349+ who: Handle,350+ now: DateTime.Utc351+): ClaimResult => {352+ const end = (live: Live) =>353+ live.claimant === who354+ ? move(355+ ClaimState.cases.Released.make(claimOf(live)),356+ ClaimEffect.RevokeAccess({ fork: live.fork }),357+ ClaimEffect.Emit({358+ event: ProjectEventInput.Released({ ask: live.ask, at: now }),359+ })360+ )361+ : Result.fail(NotClaimed.of(live.ask));362+363+ // A claim that already ended stays ended: releasing it again converges.364+ const ended = (claimed: Live) =>365+ claimed.claimant === who366+ ? stay(state)367+ : Result.fail(NotClaimed.of(claimed.ask));368+369+ return ClaimState.match(state, {370+ Answered: ended,371+ Lapsed: ended,372+ Live: end,373+ Open: unclaimed,374+ Released: ended,375+ Warned: end,376+ });377+};378+379+/**380+ * The claimant's answer landed. A live claim's access ends with it; a lapsed381+ * claim's already has. A released claim stays released, and an ask that holds382+ * no claim (a decider's own landing) is left as it is.383+ */384+const land = (state: ClaimState, landing: LandedSha): ClaimResult => {385+ const answer = (live: Live, ...effects: readonly ClaimEffect[]) =>386+ move(387+ ClaimState.cases.Answered.make({ ...claimOf(live), landing }),388+ ...effects389+ );390+391+ const revoked = (live: Live) =>392+ answer(live, ClaimEffect.RevokeAccess({ fork: live.fork }));393+394+ return ClaimState.match(state, {395+ Answered: stay,396+ Lapsed: (lapsed) => answer(lapsed),397+ Live: revoked,398+ Open: stay,399+ Released: stay,400+ Warned: revoked,401+ });402+};403+404+/**405+ * The one way a claim moves: the next state and the effects that settle it,406+ * or a refusal, which changes nothing. Deadlines become `SetAlarm` effects and407+ * an alarm comes back as `Tick`. Pure: the same arguments give the same408+ * result, so a replayed command converges.409+ */410+export const transition = (411+ state: ClaimState,412+ command: ClaimCommand,413+ now: DateTime.Utc,414+ policy: Policy["claims"]415+): ClaimResult =>416+ ClaimCommand.match(command, {417+ Claim: (made) => claim(state, made, now, policy),418+ Land: ({ landing }) => land(state, landing),419+ Push: (pushed) => push(state, pushed, now, policy),420+ Release: ({ who }) => release(state, who, now),421+ Tick: () => tick(state, now),422+ });423+424+/** Where the claim's fork is served and what to run, for the claim's view. */425+export interface ViewContext {426+ /** What `<cli> check` runs locally for the ask; not empty. */427+ readonly checkCommand: string;428+ readonly project: ProjectName;429+ /** The fork's URL at the gateway; not empty. */430+ readonly remote: string;431+}432+433+/**434+ * The claim as its claimant sees it, in whichever state it is or ended in;435+ * none while the ask holds no claim.436+ */437+export const toView = (438+ state: ClaimState,439+ context: ViewContext440+): Option.Option<ClaimView> => {441+ const view = (claimed: Live, standing: ClaimView["state"]) => {442+ const shown = {443+ ask: claimed.ask,444+ base: claimed.base,445+ checkCommand: context.checkCommand,446+ claimant: claimed.claimant,447+ fork: claimed.fork,448+ lapsesAt: claimed.lapsesAt,449+ openedAt: claimed.openedAt,450+ project: context.project,451+ remote: context.remote,452+ state: standing,453+ warnsAt: claimed.warnsAt,454+ };455+456+ return Option.some(457+ ClaimView.make(458+ Option.match(claimed.lastPushAt, {459+ onNone: () => shown,460+ onSome: (lastPushAt) => ({ ...shown, lastPushAt }),461+ })462+ )463+ );464+ };465+466+ return ClaimState.match(state, {467+ Answered: (answered) => view(answered, "answered"),468+ Lapsed: (lapsed) => view(lapsed, "lapsed"),469+ Live: (live) => view(live, "live"),470+ Open: () => Option.none(),471+ Released: (released) => view(released, "released"),472+ Warned: (warned) => view(warned, "warned"),473+ });474+};added:packages/project/test/claim.model.test.ts+651 added
1+import { assert, describe, it } from "@effect/vitest";2+import {3+ AskId,4+ CommitSha,5+ Handle,6+ LandedSha,7+ ProjectName,8+ RepoName,9+} from "@repo/protocol/ids";10+import { Person } from "@repo/protocol/principal";11+import {12+ Arbitrary,13+ Array as Arr,14+ DateTime,15+ Option,16+ Predicate,17+ Result,18+ Schema,19+} from "effect";20+21+import {22+ ClaimCommand,23+ ClaimEffect,24+ ClaimState,25+ forkName,26+ transition,27+} from "../src/claim.ts";28+import type { ClaimResult, ClaimStep, Live } from "../src/claim.ts";29+30+// A model test (ADR 0012): generated histories of claims, pushes, alarms,31+// releases and landings run through `transition` the way the project service32+// would, and every step is checked against the claim lifecycle's invariants.33+34+const HOUR = 3_600_000;35+36+/** The defaults: warned after 2 quiet hours, lapsed after 24. */37+const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };38+39+const project = ProjectName.make("datekit");40+41+const canonical = RepoName.make("datekit");42+43+const ask = AskId.make("parse-iso");44+45+const blocker = AskId.make("drop-legacy");46+47+const base = CommitSha.make("1".repeat(40));48+49+const head = CommitSha.make("2".repeat(40));50+51+const landing = LandedSha.make("3".repeat(40));52+53+const cap = 3;54+55+const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");56+57+/** Four people; `Bob` checks that a fork's name lowercases the handle. */58+const People = Schema.Literals(["alice", "Bob", "carol", "dave"]);59+60+/**61+ * How the person making a claim stands: each flag is one refusal the claim62+ * would meet (the ask blocked, the person at their cap, denounced, or not63+ * vouched). A claim may meet several, so their order is checked too.64+ */65+const Standing = Schema.Struct({66+ atCap: Schema.Boolean,67+ blocked: Schema.Boolean,68+ denounced: Schema.Boolean,69+ unvouched: Schema.Boolean,70+});71+72+/** One thing that happens to the ask, as a history step names it. */73+const Move = Schema.TaggedUnion({74+ Claim: { standing: Standing, who: People },75+ Land: { who: People },76+ Push: { who: People },77+ Release: { who: People },78+ Tick: {},79+});80+81+type Move = typeof Move.Type;82+83+/**84+ * How the project service keeps the ask's claims: one state for the whole85+ * ask (`shared`, an exclusive kind), or one state per claimant with the86+ * kind's `race` (1 to 3) passed to each claim.87+ */88+const Layout = Schema.Literals(["shared", "race1", "race2", "race3"]);89+90+type Layout = typeof Layout.Type;91+92+/** One step of a history: whole hours waited since the last one, then a move. */93+interface Step {94+ readonly after: number;95+ readonly move: Move;96+}97+98+const roll = (maximum: number) =>99+ Arbitrary.schema(Schema.Int.check(Schema.isBetween({ maximum, minimum: 0 })));100+101+const person = Arbitrary.schema(People);102+103+/** True one time in six; it shrinks to false, so a shrunk claim meets nothing. */104+const rare = roll(5).pipe(Arbitrary.map((n) => n === 5));105+106+/** About half of all claims meet no refusal. */107+const standing = Arbitrary.all({108+ atCap: rare,109+ blocked: rare,110+ denounced: rare,111+ unvouched: rare,112+});113+114+const claims = Arbitrary.all({ standing, who: person }).pipe(115+ Arbitrary.map((made) => Move.cases.Claim.make(made))116+);117+118+const pushes = person.pipe(119+ Arbitrary.map((who) => Move.cases.Push.make({ who }))120+);121+122+const releases = person.pipe(123+ Arbitrary.map((who) => Move.cases.Release.make({ who }))124+);125+126+const lands = person.pipe(127+ Arbitrary.map((who) => Move.cases.Land.make({ who }))128+);129+130+const ticks = Arbitrary.Constant(Move.cases.Tick.make({}));131+132+/** Moves by weight; shrinking a roll towards 0 turns a move into an alarm. */133+const weighted = [134+ ticks,135+ ticks,136+ pushes,137+ pushes,138+ pushes,139+ claims,140+ claims,141+ claims,142+ releases,143+ lands,144+];145+146+const moves = roll(weighted.length - 1).pipe(147+ Arbitrary.flatMap((n): Arbitrary.Arbitrary<Move> => weighted[n] ?? ticks)148+);149+150+/** Whole hours, so steps land exactly on the 2 h and 24 h deadlines often. */151+const histories = Arbitrary.array(152+ Arbitrary.all({ after: roll(26), move: moves }),153+ { maxLength: 40 }154+);155+156+const layouts = Arbitrary.schema(Layout);157+158+const raceOf = (layout: Layout) =>159+ ({ race1: 1, race2: 2, race3: 3, shared: 1 })[layout];160+161+/** A live claim: `Live` or `Warned`. */162+const live = (state: ClaimState): Option.Option<Live> =>163+ ClaimState.match(state, {164+ Answered: () => Option.none(),165+ Lapsed: () => Option.none(),166+ Live: Option.some<Live>,167+ Open: () => Option.none(),168+ Released: () => Option.none(),169+ Warned: Option.some<Live>,170+ });171+172+/** Any state that holds or held a claim. */173+const held = (state: ClaimState): Option.Option<Live> =>174+ ClaimState.match(state, {175+ Answered: Option.some<Live>,176+ Lapsed: Option.some<Live>,177+ Live: Option.some<Live>,178+ Open: () => Option.none(),179+ Released: Option.some<Live>,180+ Warned: Option.some<Live>,181+ });182+183+const isLive = (state: ClaimState) => Option.isSome(live(state));184+185+const ms = (time: DateTime.Utc) => DateTime.toEpochMillis(time);186+187+/** The time a claim's deadlines count from: its last push, or its making. */188+const quietSince = (claim: Live) =>189+ Option.getOrElse(claim.lastPushAt, () => claim.openedAt);190+191+const encode = Schema.encodeSync(ClaimState);192+193+const same = (left: ClaimState, right: ClaimState) =>194+ JSON.stringify(encode(left)) === JSON.stringify(encode(right));195+196+/** One call to `transition`, as the model service made it. */197+interface Call {198+ readonly before: ClaimState;199+ readonly command: ClaimCommand;200+ readonly now: DateTime.Utc;201+}202+203+type Claim = typeof ClaimCommand.cases.Claim.Type;204+205+/** Whether the person making a claim holds the ask's live claim already. */206+const holds = (before: ClaimState, made: Claim) =>207+ Option.exists(live(before), (holder) => holder.claimant === made.who.handle);208+209+/**210+ * The refusal a claim by someone who does not hold it meets first, in the211+ * lifecycle's order: a full ask before anything else (ADR 0008), then the212+ * ask's blockers, the person's cap, a denouncement and a missing vouch. None213+ * when it should go live.214+ */215+const owed = (before: ClaimState, made: Claim) =>216+ Option.map(217+ Arr.findFirst(218+ [219+ [220+ "AskFull",221+ ClaimState.guards.Answered(before) ||222+ isLive(before) ||223+ made.liveCount >= made.race,224+ ],225+ ["AskBlocked", made.blockedBy.length > 0],226+ ["CapReached", made.heldByWho >= made.cap],227+ ["Denounced", made.denounced],228+ ["NotVouched", !made.vouched],229+ ] as const,230+ ([, meets]) => meets231+ ),232+ ([refusal]) => refusal233+ );234+235+/**236+ * A claim is refused with the first refusal it meets, and goes live, held by237+ * its maker, when it meets none; the holder claiming again changes nothing.238+ */239+const claimsAsOwed = (240+ { before, command }: Call,241+ result: ClaimResult242+): readonly string[] => {243+ if (!ClaimCommand.guards.Claim(command)) {244+ return [];245+ }246+247+ if (holds(before, command)) {248+ return Result.match(result, {249+ onFailure: (refusal) => [250+ `the holder claiming again is refused with ${refusal._tag}`,251+ ],252+ onSuccess: ({ effects, state }) =>253+ effects.length === 0 && same(before, state)254+ ? []255+ : ["the holder claiming again changes the claim"],256+ });257+ }258+259+ const first = owed(before, command);260+261+ return Result.match(result, {262+ onFailure: (refusal) =>263+ Option.match(first, {264+ onNone: () => [265+ `a claim that meets no refusal is refused with ${refusal._tag}`,266+ ],267+ onSome: (expected) =>268+ Predicate.isTagged(refusal, expected)269+ ? []270+ : [271+ `a claim that meets ${expected} first is refused with ${refusal._tag}`,272+ ],273+ }),274+ onSuccess: ({ state }) =>275+ Option.match(first, {276+ onNone: () =>277+ Option.exists(278+ live(state),279+ (holder) => holder.claimant === command.who.handle280+ )281+ ? []282+ : ["a claim that meets no refusal goes live, held by its maker"],283+ onSome: (expected) => [`a claim that meets ${expected} goes through`],284+ }),285+ });286+};287+288+/** Who pushed or released; none for any other command. */289+const pushedOrReleasedBy = ClaimCommand.match({290+ Claim: () => Option.none<Handle>(),291+ Land: () => Option.none<Handle>(),292+ Push: ({ who }) => Option.some(who),293+ Release: ({ who }) => Option.some(who),294+ Tick: () => Option.none<Handle>(),295+});296+297+/**298+ * Only a live claim's holder moves it by a push or a release, and the299+ * holder's push or release always goes through.300+ */301+const holderOnly = (302+ { before, command }: Call,303+ result: ClaimResult304+): readonly string[] =>305+ Option.match(pushedOrReleasedBy(command), {306+ onNone: () => [],307+ onSome: (who) => {308+ const holder = Option.exists(309+ live(before),310+ (claim) => claim.claimant === who311+ );312+313+ return Result.match(result, {314+ onFailure: (refusal) =>315+ holder316+ ? [`the holder's ${command._tag} is refused with ${refusal._tag}`]317+ : [],318+ onSuccess: ({ state }) =>319+ holder || same(before, state)320+ ? []321+ : [`a ${command._tag} by someone without the live claim moves it`],322+ });323+ },324+ });325+326+/** Whether a push comes from the holder of a live claim. */327+const holderPushes = ({ before, command }: Call) =>328+ ClaimCommand.guards.Push(command) &&329+ Option.exists(live(before), (holder) => holder.claimant === command.who);330+331+/** An invariant over one successful call, naming what it found broken. */332+type Invariant = (call: Call, done: ClaimStep) => readonly string[];333+334+/** The holder's push keeps the claim live and counts from now. */335+const pushesRenew: Invariant = (call, { state }) =>336+ holderPushes(call) &&337+ !(338+ ClaimState.guards.Live(state) &&339+ Option.exists(live(state), (holder) =>340+ Option.exists(holder.lastPushAt, (pushed) => ms(pushed) === ms(call.now))341+ )342+ )343+ ? ["the holder's push makes the claim live from now"]344+ : [];345+346+/**347+ * A fork is made only on the way into Live from no claim, a lapsed one or a348+ * released one, and then exactly once, named for the new claimant.349+ */350+const forksOnlyNewClaims: Invariant = ({ before }, { effects, state }) => {351+ const forks = effects.filter(ClaimEffect.$is("MakeFork"));352+353+ const opens =354+ ClaimState.isAnyOf(["Open", "Released", "Lapsed"])(before) &&355+ ClaimState.guards.Live(state);356+357+ if (!opens) {358+ return forks.length > 0 ? [`a fork made from ${before._tag}`] : [];359+ }360+361+ const named = Option.map(live(state), (claim) =>362+ forkName(project, ask, claim.claimant)363+ );364+365+ return forks.length === 1 &&366+ Option.exists(named, (name) => forks[0]?.name === name) &&367+ forks[0]?.from === canonical368+ ? []369+ : ["a new claim makes one fork, named for its claimant"];370+};371+372+/** Access is revoked exactly when a live claim ends. */373+const revokesWhenLiveEnds: Invariant = ({ before }, { effects, state }) => {374+ const revokes = effects.filter(ClaimEffect.$is("RevokeAccess")).length;375+ const ends = isLive(before) && !isLive(state);376+377+ return revokes === (ends ? 1 : 0)378+ ? []379+ : ["access is revoked once when a live claim ends"];380+};381+382+/** Deadlines count from the last push, or from the claim, never from later. */383+const deadlinesCount: Invariant = ({ now }, { state }) =>384+ Option.match(held(state), {385+ onNone: () => [],386+ onSome: (claim) => {387+ const since = ms(quietSince(claim));388+389+ return [390+ ...(ms(claim.lapsesAt) - since === policy.lapseAfterMs391+ ? []392+ : ["lapsesAt is the last push (or the claim) plus lapseAfterMs"]),393+ ...(ms(claim.warnsAt) - since === policy.warnAfterMs394+ ? []395+ : ["warnsAt is the last push (or the claim) plus warnAfterMs"]),396+ ...(since > ms(now) ? ["a claim pushed to or made after now"] : []),397+ ];398+ },399+ });400+401+/** Alarms are set only for later, and events happen now. */402+const noTimeTravel: Invariant = ({ now }, { effects }) => [403+ ...effects404+ .filter(ClaimEffect.$is("SetAlarm"))405+ .flatMap((alarm) =>406+ ms(alarm.at) > ms(now) ? [] : ["an alarm set for now or earlier"]407+ ),408+ ...effects409+ .filter(ClaimEffect.$is("Emit"))410+ .flatMap((emitted) =>411+ ms(emitted.event.at) === ms(now) ? [] : ["an event that is not now"]412+ ),413+];414+415+/** A claim is warned no earlier than warnsAt, and lapses no earlier than lapsesAt. */416+const deadlinesKept: Invariant = ({ before, now }, { state }) =>417+ Option.match(held(state), {418+ onNone: () => [],419+ onSome: (claim) => [420+ ...(ClaimState.guards.Warned(state) &&421+ !ClaimState.guards.Warned(before) &&422+ ms(now) < ms(claim.warnsAt)423+ ? ["warned before warnsAt"]424+ : []),425+ ...(ClaimState.guards.Lapsed(state) &&426+ !ClaimState.guards.Lapsed(before) &&427+ ms(now) < ms(claim.lapsesAt)428+ ? ["lapsed before lapsesAt"]429+ : []),430+ ],431+ });432+433+/**434+ * A claim that moves into or within live sets the alarm for its next435+ * deadline (warnsAt while live, lapsesAt once warned): deadlines run on436+ * alarms, so a claim with none would never lapse.437+ */438+const alarmsNextDeadline: Invariant = ({ before }, { effects, state }) =>439+ Option.match(live(state), {440+ onNone: () => [],441+ onSome: (claim) => {442+ const next = ClaimState.guards.Warned(state)443+ ? claim.lapsesAt444+ : claim.warnsAt;445+446+ return same(before, state) ||447+ effects448+ .filter(ClaimEffect.$is("SetAlarm"))449+ .some((alarm) => ms(alarm.at) === ms(next))450+ ? []451+ : [452+ `a claim moved to ${state._tag} sets no alarm for its next deadline`,453+ ];454+ },455+ });456+457+/** Answered never changes; Released changes only by a fresh claim. */458+const endsAreFinal: Invariant = ({ before, command }, { state }) => [459+ ...(ClaimState.guards.Answered(before) && !same(before, state)460+ ? ["Answered is terminal"]461+ : []),462+ ...(ClaimState.guards.Released(before) &&463+ !same(before, state) &&464+ !(ClaimCommand.guards.Claim(command) && ClaimState.guards.Live(state))465+ ? ["Released changes only by a fresh claim"]466+ : []),467+];468+469+const invariants: readonly Invariant[] = [470+ pushesRenew,471+ forksOnlyNewClaims,472+ revokesWhenLiveEnds,473+ deadlinesCount,474+ noTimeTravel,475+ deadlinesKept,476+ alarmsNextDeadline,477+ endsAreFinal,478+];479+480+/**481+ * Names everything one call broke: who may claim, push and release, then,482+ * when it went through, every invariant of the step it took.483+ */484+const brokenBy = (call: Call, result: ClaimResult): readonly string[] => [485+ ...claimsAsOwed(call, result),486+ ...holderOnly(call, result),487+ ...Result.match(result, {488+ onFailure: () => [],489+ onSuccess: (done) =>490+ invariants.flatMap((invariant) => invariant(call, done)),491+ }),492+];493+494+/** The ask's claim states, by slot: the claimant's handle, or `ask` when shared. */495+type Slots = ReadonlyMap<string, ClaimState>;496+497+/** The model project service between two steps. */498+interface World {499+ readonly now: DateTime.Utc;500+ readonly slots: Slots;501+}502+503+const slotOf = (layout: Layout, who: string) =>504+ layout === "shared" ? "ask" : who;505+506+const stateIn = (slots: Slots, slot: string): ClaimState =>507+ slots.get(slot) ?? ClaimState.cases.Open.make({ ask });508+509+const liveOutside = (slots: Slots, slot: string) =>510+ [...slots].filter(([key, state]) => key !== slot && isLive(state)).length;511+512+/** A command for one slot. */513+interface Addressed {514+ readonly command: ClaimCommand;515+ readonly slot: string;516+}517+518+const to = (slot: string, command: ClaimCommand): Addressed => ({519+ command,520+ slot,521+});522+523+/** The commands the project service would send for a move, and where. */524+const commandsFor = (525+ layout: Layout,526+ slots: Slots,527+ move: Move528+): readonly Addressed[] =>529+ Move.match(move, {530+ Claim: ({ standing: made, who }) => [531+ to(532+ slotOf(layout, who),533+ ClaimCommand.cases.Claim.make({534+ base,535+ blockedBy: made.blocked ? [blocker] : [],536+ cap,537+ denounced: made.denounced,538+ heldByWho: made.atCap ? cap : 0,539+ liveCount: liveOutside(slots, slotOf(layout, who)),540+ project,541+ race: raceOf(layout),542+ vouched: !made.unvouched,543+ who: Person.make({ handle: Handle.make(who) }),544+ })545+ ),546+ ],547+ Land: ({ who }) => [548+ to(slotOf(layout, who), ClaimCommand.cases.Land.make({ landing })),549+ ],550+ Push: ({ who }) => [551+ to(552+ slotOf(layout, who),553+ ClaimCommand.cases.Push.make({ head, who: Handle.make(who) })554+ ),555+ ],556+ Release: ({ who }) => [557+ to(558+ slotOf(layout, who),559+ ClaimCommand.cases.Release.make({ who: Handle.make(who) })560+ ),561+ ],562+ // An alarm reaches every claim the ask holds.563+ Tick: () =>564+ [...slots.keys()].map((slot) =>565+ to(slot, ClaimCommand.cases.Tick.make({}))566+ ),567+ });568+569+/** Why an alarm left a claim past a deadline it reached, if it did. */570+const overdue = (now: DateTime.Utc, state: ClaimState) =>571+ Option.flatMap(live(state), (claim) => {572+ if (ms(now) >= ms(claim.lapsesAt)) {573+ return Option.some("an alarm left a claim past lapsesAt");574+ }575+576+ return ClaimState.guards.Live(state) && ms(now) >= ms(claim.warnsAt)577+ ? Option.some("an alarm left a claim unwarned past warnsAt")578+ : Option.none();579+ });580+581+/** What the whole ask keeps after a step: the race, and alarms that catch up. */582+const brokenAfter = (layout: Layout, world: World, move: Move) => {583+ const states = [...world.slots.values()];584+585+ const holders = new Set(586+ states.flatMap((state) =>587+ Option.toArray(Option.map(live(state), (holder) => holder.claimant))588+ )589+ );590+591+ return [592+ ...(holders.size > raceOf(layout)593+ ? [`${holders.size} live claims on a race of ${raceOf(layout)}`]594+ : []),595+ ...(Move.guards.Tick(move)596+ ? states.flatMap((state) => Option.toArray(overdue(world.now, state)))597+ : []),598+ ];599+};600+601+/** Takes one step: the next world, and what broke on the way. */602+const advance = (layout: Layout, world: World, { after, move }: Step) => {603+ const now = DateTime.add(world.now, { hours: after });604+ const slots = new Map(world.slots);605+ const broken: string[] = [];606+607+ for (const { command, slot } of commandsFor(layout, world.slots, move)) {608+ const call = { before: stateIn(world.slots, slot), command, now };609+ const result = transition(call.before, command, now, policy);610+611+ broken.push(...brokenBy(call, result));612+613+ if (Result.isSuccess(result)) {614+ slots.set(slot, result.success.state);615+ }616+ }617+618+ const next = { now, slots };619+620+ return { broken: [...broken, ...brokenAfter(layout, next, move)], next };621+};622+623+/** Runs a history; returns its first bad step and what that step broke. */624+const firstBreak = (layout: Layout, steps: readonly Step[]) => {625+ let world: World = { now: start, slots: new Map() };626+627+ for (const [index, step] of steps.entries()) {628+ const { broken, next } = advance(layout, world, step);629+630+ if (broken.length > 0) {631+ return [`step ${index}`, ...broken];632+ }633+634+ world = next;635+ }636+637+ return [];638+};639+640+describe("the claim lifecycle, over generated histories", () => {641+ it.prop(642+ "keeps every invariant after every step",643+ { history: histories, layout: layouts },644+ ({ history, layout }) => {645+ const broken = firstBreak(layout, history);646+647+ assert.deepStrictEqual(broken, [], broken.join("; "));648+ },649+ { arbitrary: { runs: 1000, size: 40 } }650+ );651+});added:packages/project/test/claim.test.ts+454 added
1+import { describe, expect, it } from "@effect/vitest";2+import { ClaimView } from "@repo/protocol/domain/claim";3+import {4+ AskId,5+ CommitSha,6+ Handle,7+ LandedSha,8+ ProjectName,9+ RepoName,10+} from "@repo/protocol/ids";11+import { Person } from "@repo/protocol/principal";12+import {13+ AskBlocked,14+ AskFull,15+ CapReached,16+ ClaimLapsed,17+ Denounced,18+ NotClaimed,19+ NotVouched,20+} from "@repo/protocol/refusal";21+import { DateTime, Option, Result, Schema } from "effect";22+23+import {24+ ClaimCommand,25+ ClaimEffect,26+ ClaimState,27+ forkName,28+ ProjectEventInput,29+ toView,30+ transition,31+} from "../src/claim.ts";32+33+const { Claim, Land, Push, Release, Tick } = ClaimCommand.cases;34+35+const HOUR = 3_600_000;36+37+/** The defaults: warned after 2 quiet hours, lapsed after 24. */38+const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };39+40+const project = ProjectName.make("datekit");41+42+const ask = AskId.make("parse-iso");43+44+const blocker = AskId.make("drop-legacy");45+46+const base = CommitSha.make("1".repeat(40));47+48+const head = CommitSha.make("2".repeat(40));49+50+const landing = LandedSha.make("3".repeat(40));51+52+const bob = Handle.make("Bob");53+54+const carol = Handle.make("carol");55+56+/** Bob's fork: his handle in lowercase. */57+const fork = RepoName.make("datekit--parse-iso--bob");58+59+const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");60+61+/** `hours` after the claim was made. */62+const at = (hours: number) => DateTime.add(start, { hours });63+64+/** A claim by a vouched person under their cap, on an ask nobody holds. */65+const claimBy = (66+ handle: Handle,67+ standing: Partial<Omit<typeof Claim.Type, "_tag" | "who">> = {}68+) =>69+ Claim.make({70+ base,71+ blockedBy: [],72+ cap: 3,73+ denounced: false,74+ heldByWho: 0,75+ liveCount: 0,76+ project,77+ race: 1,78+ vouched: true,79+ who: Person.make({ handle }),80+ ...standing,81+ });82+83+const open = ClaimState.cases.Open.make({ ask });84+85+/** Bob's claim, made at `start`, never pushed to. */86+const fresh = {87+ ask,88+ base,89+ claimant: bob,90+ fork,91+ lapsesAt: at(24),92+ lastPushAt: Option.none(),93+ openedAt: start,94+ warnsAt: at(2),95+};96+97+const live = ClaimState.cases.Live.make(fresh);98+99+const warned = ClaimState.cases.Warned.make(fresh);100+101+const lapsed = ClaimState.cases.Lapsed.make({ ...fresh, at: at(24) });102+103+const step = (state: ClaimState, effects: readonly ClaimEffect[] = []) =>104+ Result.succeed({ effects, state });105+106+describe("claiming an ask", () => {107+ it("gives a vouched person under their cap a live claim, a fork and a warn alarm", () => {108+ expect(transition(open, claimBy(bob), start, policy)).toStrictEqual(109+ step(live, [110+ ClaimEffect.MakeFork({ from: RepoName.make("datekit"), name: fork }),111+ ClaimEffect.SetAlarm({ at: at(2) }),112+ ClaimEffect.Emit({113+ event: ProjectEventInput.Claimed({ ask, at: start, claimant: bob }),114+ }),115+ ])116+ );117+ });118+119+ it("names the fork after the project, the ask and the handle in lowercase", () => {120+ expect(forkName(project, ask, bob)).toBe("datekit--parse-iso--bob");121+ });122+123+ it("refuses a second person with AskFull, and forks nothing", () => {124+ expect(transition(live, claimBy(carol), at(1), policy)).toStrictEqual(125+ Result.fail(new AskFull({ ask }))126+ );127+ });128+129+ it("refuses with AskFull when others hold every claim the kind allows", () => {130+ expect(131+ transition(open, claimBy(carol, { liveCount: 2, race: 2 }), at(1), policy)132+ ).toStrictEqual(Result.fail(new AskFull({ ask })));133+ });134+135+ it("lets a racing kind take another claim while it has room", () => {136+ const result = transition(137+ open,138+ claimBy(carol, { liveCount: 1, race: 2 }),139+ at(1),140+ policy141+ );142+143+ expect(Result.map(result, ({ state }) => state._tag)).toStrictEqual(144+ Result.succeed("Live")145+ );146+ });147+148+ it("leaves the holder's own claim as it is when they claim again", () => {149+ expect(transition(live, claimBy(bob), at(1), policy)).toStrictEqual(150+ step(live)151+ );152+ expect(transition(warned, claimBy(bob), at(3), policy)).toStrictEqual(153+ step(warned)154+ );155+ });156+157+ it("refuses an ask that waits on others with AskBlocked", () => {158+ expect(159+ transition(open, claimBy(bob, { blockedBy: [blocker] }), start, policy)160+ ).toStrictEqual(Result.fail(AskBlocked.of(ask, [blocker])));161+ });162+163+ it("refuses a person at their cap with CapReached", () => {164+ expect(165+ transition(open, claimBy(bob, { heldByWho: 3 }), start, policy)166+ ).toStrictEqual(Result.fail(new CapReached({ cap: 3 })));167+ });168+169+ it("refuses an unvouched person with NotVouched", () => {170+ expect(171+ transition(open, claimBy(bob, { vouched: false }), start, policy)172+ ).toStrictEqual(Result.fail(new NotVouched({})));173+ });174+175+ it("refuses a denounced person with Denounced, before NotVouched", () => {176+ expect(177+ transition(178+ open,179+ claimBy(bob, { denounced: true, vouched: false }),180+ start,181+ policy182+ )183+ ).toStrictEqual(Result.fail(new Denounced({})));184+ });185+186+ it("names only the first refusal a claim meets: blockers, then the cap, then standing", () => {187+ const troubled = {188+ blockedBy: [blocker],189+ denounced: true,190+ heldByWho: 3,191+ vouched: false,192+ };193+194+ expect(195+ transition(open, claimBy(bob, troubled), start, policy)196+ ).toStrictEqual(Result.fail(AskBlocked.of(ask, [blocker])));197+ expect(198+ transition(199+ open,200+ claimBy(bob, { ...troubled, blockedBy: [] }),201+ start,202+ policy203+ )204+ ).toStrictEqual(Result.fail(new CapReached({ cap: 3 })));205+ });206+207+ it("says AskFull before anything else, so a full ask never forks", () => {208+ expect(209+ transition(210+ live,211+ claimBy(carol, {212+ blockedBy: [blocker],213+ denounced: true,214+ heldByWho: 3,215+ vouched: false,216+ }),217+ at(1),218+ policy219+ )220+ ).toStrictEqual(Result.fail(new AskFull({ ask })));221+ });222+223+ it("gives a lapsed claim to the next person, with their own fork", () => {224+ const result = transition(lapsed, claimBy(carol), at(25), policy);225+226+ expect(Result.map(result, ({ effects }) => effects[0])).toStrictEqual(227+ Result.succeed(228+ ClaimEffect.MakeFork({229+ from: RepoName.make("datekit"),230+ name: RepoName.make("datekit--parse-iso--carol"),231+ })232+ )233+ );234+ });235+236+ it("refuses any claim on an answered ask with AskFull", () => {237+ const answered = ClaimState.cases.Answered.make({ ...fresh, landing });238+239+ expect(transition(answered, claimBy(bob), at(3), policy)).toStrictEqual(240+ Result.fail(new AskFull({ ask }))241+ );242+ });243+});244+245+describe("pushing keeps a claim alive", () => {246+ it("moves both deadlines on from the push and sets the alarm", () => {247+ expect(248+ transition(live, Push.make({ head, who: bob }), at(1), policy)249+ ).toStrictEqual(250+ step(251+ ClaimState.cases.Live.make({252+ ...fresh,253+ lapsesAt: at(25),254+ lastPushAt: Option.some(at(1)),255+ warnsAt: at(3),256+ }),257+ [258+ ClaimEffect.SetAlarm({ at: at(3) }),259+ ClaimEffect.Emit({260+ event: ProjectEventInput.Pushed({ ask, at: at(1), head }),261+ }),262+ ]263+ )264+ );265+ });266+267+ it("makes a warned claim live again", () => {268+ const result = transition(269+ warned,270+ Push.make({ head, who: bob }),271+ at(5),272+ policy273+ );274+275+ expect(Result.map(result, ({ state }) => state._tag)).toStrictEqual(276+ Result.succeed("Live")277+ );278+ });279+280+ it("refuses a push from someone who holds no claim with NotClaimed", () => {281+ expect(282+ transition(live, Push.make({ head, who: carol }), at(1), policy)283+ ).toStrictEqual(Result.fail(NotClaimed.of(ask)));284+ expect(285+ transition(open, Push.make({ head, who: bob }), at(1), policy)286+ ).toStrictEqual(Result.fail(NotClaimed.of(ask)));287+ });288+289+ it("refuses the lapsed claimant's push with ClaimLapsed", () => {290+ expect(291+ transition(lapsed, Push.make({ head, who: bob }), at(25), policy)292+ ).toStrictEqual(Result.fail(ClaimLapsed.of(ask)));293+ });294+});295+296+describe("an alarm", () => {297+ it("does nothing before the warn deadline", () => {298+ expect(transition(live, Tick.make({}), at(1), policy)).toStrictEqual(299+ step(live)300+ );301+ });302+303+ it("warns a claim at its warn deadline and sets the lapse alarm", () => {304+ expect(transition(live, Tick.make({}), at(2), policy)).toStrictEqual(305+ step(warned, [306+ ClaimEffect.SetAlarm({ at: at(24) }),307+ ClaimEffect.Emit({308+ event: ProjectEventInput.Warned({ ask, at: at(2) }),309+ }),310+ ])311+ );312+ });313+314+ it("lapses a warned claim at its lapse deadline and revokes the fork", () => {315+ expect(transition(warned, Tick.make({}), at(24), policy)).toStrictEqual(316+ step(lapsed, [317+ ClaimEffect.RevokeAccess({ fork }),318+ ClaimEffect.Emit({319+ event: ProjectEventInput.Lapsed({ ask, at: at(24) }),320+ }),321+ ])322+ );323+ });324+325+ it("lapses a live claim straight away when the alarm comes after both deadlines", () => {326+ const result = transition(live, Tick.make({}), at(30), policy);327+328+ expect(Result.map(result, ({ state }) => state._tag)).toStrictEqual(329+ Result.succeed("Lapsed")330+ );331+ });332+333+ it("leaves a warned claim alone before its lapse deadline", () => {334+ expect(transition(warned, Tick.make({}), at(23), policy)).toStrictEqual(335+ step(warned)336+ );337+ });338+});339+340+describe("releasing a claim", () => {341+ it("ends the holder's claim and revokes the fork", () => {342+ expect(343+ transition(live, Release.make({ who: bob }), at(1), policy)344+ ).toStrictEqual(345+ step(ClaimState.cases.Released.make(fresh), [346+ ClaimEffect.RevokeAccess({ fork }),347+ ClaimEffect.Emit({348+ event: ProjectEventInput.Released({ ask, at: at(1) }),349+ }),350+ ])351+ );352+ });353+354+ it("refuses anyone but the holder with NotClaimed", () => {355+ expect(356+ transition(live, Release.make({ who: carol }), at(1), policy)357+ ).toStrictEqual(Result.fail(NotClaimed.of(ask)));358+ });359+360+ it("converges when the holder releases twice", () => {361+ const released = ClaimState.cases.Released.make(fresh);362+363+ expect(364+ transition(released, Release.make({ who: bob }), at(2), policy)365+ ).toStrictEqual(step(released));366+ });367+});368+369+describe("landing the claimant's answer", () => {370+ it("answers the claim and revokes the fork", () => {371+ expect(372+ transition(live, Land.make({ landing }), at(3), policy)373+ ).toStrictEqual(374+ step(ClaimState.cases.Answered.make({ ...fresh, landing }), [375+ ClaimEffect.RevokeAccess({ fork }),376+ ])377+ );378+ });379+380+ it("converges when the landing is told twice", () => {381+ const answered = ClaimState.cases.Answered.make({ ...fresh, landing });382+383+ expect(384+ transition(answered, Land.make({ landing }), at(4), policy)385+ ).toStrictEqual(step(answered));386+ });387+});388+389+describe("the claim's view", () => {390+ const context = {391+ checkCommand: "bun test test/parse-iso.test.ts",392+ project,393+ remote: "https://platform.example/datekit--parse-iso--bob.git",394+ };395+396+ it("shows a live claim with its fork, remote and deadlines", () => {397+ expect(toView(live, context)).toStrictEqual(398+ Option.some(399+ ClaimView.make({400+ ask,401+ base,402+ checkCommand: context.checkCommand,403+ claimant: bob,404+ fork,405+ lapsesAt: at(24),406+ openedAt: start,407+ project,408+ remote: context.remote,409+ state: "live",410+ warnsAt: at(2),411+ })412+ )413+ );414+ });415+416+ it("names the state the claim ended in, and its last push", () => {417+ const pushed = { ...fresh, lastPushAt: Option.some(at(1)) };418+419+ expect(420+ Option.map(421+ toView(422+ ClaimState.cases.Lapsed.make({ ...pushed, at: at(25) }),423+ context424+ ),425+ ({ lastPushAt, state }) => ({ lastPushAt, state })426+ )427+ ).toStrictEqual(Option.some({ lastPushAt: at(1), state: "lapsed" }));428+ });429+430+ it("has no view while the ask holds no claim", () => {431+ expect(toView(open, context)).toStrictEqual(Option.none());432+ });433+});434+435+describe("the persisted state", () => {436+ it("round-trips through JSON text", () => {437+ const pushed = ClaimState.cases.Warned.make({438+ ...fresh,439+ lastPushAt: Option.some(at(1)),440+ });441+442+ const Stored = Schema.fromJsonString(ClaimState);443+ const text = Schema.encodeSync(Stored)(pushed);444+445+ expect(Schema.decodeSync(Stored)(text)).toStrictEqual(pushed);446+ });447+448+ it("is JSON with times as text, and leaves out a push that never came", () => {449+ const stored = Schema.encodeSync(ClaimState)(live);450+451+ expect(stored).toHaveProperty("lapsesAt", "2026-10-08T12:00:00.000Z");452+ expect(stored).not.toHaveProperty("lastPushAt");453+ });454+});