Add the claim lifecycle: a claim moves only by a pure transition, and a model test over generated histories holds its invariants
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- packages/project/src/claim.ts: transition(state, command, now, policy.claims) returns Result<{state, effects}, refusal>. It reads no clock and calls no port (ADR 0012, principle 12): deadlines become SetAlarm effects, an alarm comes back as Tick, and MakeFork, RevokeAccess and Emit are data for the project service (214) to settle. forkName gives <project>--<ask>--<handle lowercased>; toView gives the protocol ClaimView for every state but Open. - ClaimState is a Schema.TaggedUnion (Open, Live, Warned, Lapsed, Released, Answered) so the store (210) persists it as encoded JSON; times are DateTimeUtcFromString and lastPushAt is OptionFromOptionalKey (a missing key when there was no push). Matched with ClaimState.match. - Decision: every state carries its ask (Open is {ask}), so NotClaimed, ClaimLapsed and a Tick's Warned/Lapsed events come from the state alone; Claim drops its ask field and toView's context drops ask. Lapsed, Released and Answered keep the whole claim, so toView shows each ClaimView.state. - Decision: Claim carries liveCount and race (the issue allowed it). AskFull when liveCount >= race, when the claim is live for someone else, or when the ask is answered; then AskBlocked, CapReached, Denounced, NotVouched, so a full ask never forks (ADR 0008). - Decision: ClaimCommand is a Schema.TaggedUnion, not Data.TaggedEnum: lint refuses the empty type `Tick: {}`, and a schema can decode a command at a boundary (principle 2). ClaimEffect stays a TaggedEnum. - Decision, where the issue was silent: a Tick past lapsesAt lapses a live claim at once; the warn also sets the lapse alarm; Land revokes a live claim's access (every way a live claim ends does), answers a lapsed one without a second revoke, and leaves Released, Open and Answered alone; a repeated Release, or one on an ended claim, by its claimant converges with no effects. - ProjectEventInput (ProjectEvent without seq) is local and structural, as the issue asked; 210 has its own, and 299 keeps one. - Tests: test/claim.test.ts (32 examples: each refusal and its order, idempotent re-claim, push renews both deadlines, warn at warnsAt, lapse at lapsesAt, release, land, the view, the JSON round trip). test/claim.model.test.ts: it.prop over effect/Arbitrary histories (up to 40 steps of whole hours; claims by 4 people with one refusal each about 40% of the time; pushes, ticks, releases, lands) in four layouts (one shared state, or one state per claimant with race 1, 2 or 3), 1000 runs. After every step: at most race live claimants; MakeFork only into Live from Open/Released/Lapsed, once, named for the claimant; RevokeAccess exactly when a live claim ends; lapsesAt and warnsAt count from the last push or the claim; alarms only for later, events at now; no warn before warnsAt, no lapse before lapsesAt; an alarm leaves no claim past a deadline; Answered never changes, Released only by a fresh claim; a clear claim goes live; AskFull comes first. - Both files failed by assertion against a stub that returned the state unchanged (22 of the 31 examples then written; the model test on "a clear claim goes live"). - Planted bug, caught and removed: a warned claim lapsed at warnsAt instead of lapsesAt. The model test failed with: Property falsified after 204 run(s) and 7 shrink(s) Shrunk input: { "history": [ { "after": 0, "move": { "_tag": "Claim", "standing": "clear", "who": "Bob" } }, { "after": 2, "move": {"_tag":"Tick"} }, { "after": 0, "move": {"_tag":"Tick"} } ], "layout": "race3" } Failure: AssertionError: step 2; lapsed before lapsesAt A second plant (a second claimant on a shared state gets MakeFork) shrank to alice claims, carol claims: "step 1; a full ask takes a claim; a fork made from Live". Off-by-one deadlines, a race of one too many and a push that kept the old lapse time were caught too. - ASSUMPTION: the service passes heldByWho as the person's live claims elsewhere in the project and liveCount as others' live claims on the ask (issue Comments, for 214).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+1448 added−0 removed
- tests:+977 added−0 removed
- other:+471 added−0 removed
Provenance
- Commit
50293df- Tree
2cc0d63- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
3d5870c
3 files changed+1448 added−0 removed
added:packages/project/src/claim.ts+471 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+type Outcome = Result.Result<ClaimStep, ClaimRefusal>;145+146+/** The state as it is, with nothing to settle: how a repeated command converges. */147+const stay = (state: ClaimState): Outcome =>148+ Result.succeed({ effects: [], state });149+150+const move = (state: ClaimState, ...effects: readonly ClaimEffect[]): Outcome =>151+ Result.succeed({ effects, state });152+153+/** A claim's own fields, whatever state holds them. */154+const claimOf = ({155+ ask,156+ base,157+ claimant,158+ fork,159+ lapsesAt,160+ lastPushAt,161+ openedAt,162+ warnsAt,163+}: Live): Live => ({164+ ask,165+ base,166+ claimant,167+ fork,168+ lapsesAt,169+ lastPushAt,170+ openedAt,171+ warnsAt,172+});173+174+/** When a claim quiet since `from` is warned, and when it lapses. */175+const deadlines = (from: DateTime.Utc, policy: Policy["claims"]) => ({176+ lapsesAt: DateTime.add(from, { milliseconds: policy.lapseAfterMs }),177+ warnsAt: DateTime.add(from, { milliseconds: policy.warnAfterMs }),178+});179+180+type Claim = typeof ClaimCommand.cases.Claim.Type;181+182+/**183+ * A new claim on an ask its maker does not hold. `AskFull` comes first, so a184+ * full ask never forks (ADR 0008); then the ask's blockers, the person's cap,185+ * and their standing, a denouncement before a missing vouch.186+ */187+const grant = (188+ ask: AskId,189+ made: Claim,190+ now: DateTime.Utc,191+ policy: Policy["claims"]192+): Outcome => {193+ if (made.liveCount >= made.race) {194+ return Result.fail(new AskFull({ ask }));195+ }196+197+ if (Arr.isReadonlyArrayNonEmpty(made.blockedBy)) {198+ return Result.fail(AskBlocked.of(ask, made.blockedBy));199+ }200+201+ if (made.heldByWho >= made.cap) {202+ return Result.fail(new CapReached({ cap: made.cap }));203+ }204+205+ if (made.denounced) {206+ return Result.fail(new Denounced({}));207+ }208+209+ if (!made.vouched) {210+ return Result.fail(new NotVouched({}));211+ }212+213+ const claimant = made.who.handle;214+215+ const live = ClaimState.cases.Live.make({216+ ask,217+ base: made.base,218+ claimant,219+ fork: forkName(made.project, ask, claimant),220+ lastPushAt: Option.none(),221+ openedAt: now,222+ ...deadlines(now, policy),223+ });224+225+ return move(226+ live,227+ ClaimEffect.MakeFork({228+ from: RepoName.make(made.project),229+ name: live.fork,230+ }),231+ ClaimEffect.SetAlarm({ at: live.warnsAt }),232+ ClaimEffect.Emit({233+ event: ProjectEventInput.Claimed({ ask, at: now, claimant }),234+ })235+ );236+};237+238+const claim = (239+ state: ClaimState,240+ made: Claim,241+ now: DateTime.Utc,242+ policy: Policy["claims"]243+): Outcome => {244+ // A live claim is its holder's to keep, and nobody else's to take.245+ const holder = (live: Live) =>246+ live.claimant === made.who.handle247+ ? stay(state)248+ : Result.fail(new AskFull({ ask: live.ask }));249+250+ return ClaimState.match(state, {251+ Answered: ({ ask }) => Result.fail(new AskFull({ ask })),252+ Lapsed: ({ ask }) => grant(ask, made, now, policy),253+ Live: holder,254+ Open: ({ ask }) => grant(ask, made, now, policy),255+ Released: ({ ask }) => grant(ask, made, now, policy),256+ Warned: holder,257+ });258+};259+260+/** Whoever holds no live claim on the ask. */261+const unclaimed = ({ ask }: { readonly ask: AskId }) =>262+ Result.fail(NotClaimed.of(ask));263+264+const push = (265+ state: ClaimState,266+ { head, who }: typeof ClaimCommand.cases.Push.Type,267+ now: DateTime.Utc,268+ policy: Policy["claims"]269+): Outcome => {270+ // The holder's push starts both deadlines again from now.271+ const kept = (live: Live) => {272+ if (live.claimant !== who) {273+ return Result.fail(NotClaimed.of(live.ask));274+ }275+276+ const pushed = ClaimState.cases.Live.make({277+ ...claimOf(live),278+ lastPushAt: Option.some(now),279+ ...deadlines(now, policy),280+ });281+282+ return move(283+ pushed,284+ ClaimEffect.SetAlarm({ at: pushed.warnsAt }),285+ ClaimEffect.Emit({286+ event: ProjectEventInput.Pushed({ ask: live.ask, at: now, head }),287+ })288+ );289+ };290+291+ return ClaimState.match(state, {292+ Answered: unclaimed,293+ Lapsed: (lapsed) =>294+ lapsed.claimant === who295+ ? Result.fail(ClaimLapsed.of(lapsed.ask))296+ : unclaimed(lapsed),297+ Live: kept,298+ Open: unclaimed,299+ Released: unclaimed,300+ Warned: kept,301+ });302+};303+304+const tick = (state: ClaimState, now: DateTime.Utc): Outcome => {305+ const reached = (deadline: DateTime.Utc) =>306+ DateTime.isGreaterThanOrEqualTo(now, deadline);307+308+ // An alarm that comes late lapses the claim without warning it first.309+ const lapse = (live: Live) =>310+ move(311+ ClaimState.cases.Lapsed.make({ ...claimOf(live), at: now }),312+ ClaimEffect.RevokeAccess({ fork: live.fork }),313+ ClaimEffect.Emit({314+ event: ProjectEventInput.Lapsed({ ask: live.ask, at: now }),315+ })316+ );317+318+ const warn = (live: Live) =>319+ move(320+ ClaimState.cases.Warned.make(claimOf(live)),321+ ClaimEffect.SetAlarm({ at: live.lapsesAt }),322+ ClaimEffect.Emit({323+ event: ProjectEventInput.Warned({ ask: live.ask, at: now }),324+ })325+ );326+327+ return ClaimState.match(state, {328+ Answered: stay,329+ Lapsed: stay,330+ Live: (live) => {331+ if (reached(live.lapsesAt)) {332+ return lapse(live);333+ }334+335+ return reached(live.warnsAt) ? warn(live) : stay(state);336+ },337+ Open: stay,338+ Released: stay,339+ Warned: (warned) =>340+ reached(warned.lapsesAt) ? lapse(warned) : stay(state),341+ });342+};343+344+const release = (345+ state: ClaimState,346+ who: Handle,347+ now: DateTime.Utc348+): Outcome => {349+ const end = (live: Live) =>350+ live.claimant === who351+ ? move(352+ ClaimState.cases.Released.make(claimOf(live)),353+ ClaimEffect.RevokeAccess({ fork: live.fork }),354+ ClaimEffect.Emit({355+ event: ProjectEventInput.Released({ ask: live.ask, at: now }),356+ })357+ )358+ : Result.fail(NotClaimed.of(live.ask));359+360+ // A claim that already ended stays ended: releasing it again converges.361+ const ended = (claimed: Live) =>362+ claimed.claimant === who363+ ? stay(state)364+ : Result.fail(NotClaimed.of(claimed.ask));365+366+ return ClaimState.match(state, {367+ Answered: ended,368+ Lapsed: ended,369+ Live: end,370+ Open: unclaimed,371+ Released: ended,372+ Warned: end,373+ });374+};375+376+/**377+ * The claimant's answer landed. A live claim's access ends with it; a lapsed378+ * claim's already has. A released claim stays released, and an ask that holds379+ * no claim (a decider's own landing) is left as it is.380+ */381+const land = (state: ClaimState, landing: LandedSha): Outcome => {382+ const answer = (live: Live, ...effects: readonly ClaimEffect[]) =>383+ move(384+ ClaimState.cases.Answered.make({ ...claimOf(live), landing }),385+ ...effects386+ );387+388+ const revoked = (live: Live) =>389+ answer(live, ClaimEffect.RevokeAccess({ fork: live.fork }));390+391+ return ClaimState.match(state, {392+ Answered: stay,393+ Lapsed: (lapsed) => answer(lapsed),394+ Live: revoked,395+ Open: stay,396+ Released: stay,397+ Warned: revoked,398+ });399+};400+401+/**402+ * The one way a claim moves: the next state and the effects that settle it,403+ * or a refusal, which changes nothing. Deadlines become `SetAlarm` effects and404+ * an alarm comes back as `Tick`. Pure: the same arguments give the same405+ * result, so a replayed command converges.406+ */407+export const transition = (408+ state: ClaimState,409+ command: ClaimCommand,410+ now: DateTime.Utc,411+ policy: Policy["claims"]412+): Outcome =>413+ ClaimCommand.match(command, {414+ Claim: (made) => claim(state, made, now, policy),415+ Land: ({ landing }) => land(state, landing),416+ Push: (pushed) => push(state, pushed, now, policy),417+ Release: ({ who }) => release(state, who, now),418+ Tick: () => tick(state, now),419+ });420+421+/** Where the claim's fork is served and what to run, for the claim's view. */422+export interface ViewContext {423+ /** What `<cli> check` runs locally for the ask; not empty. */424+ readonly checkCommand: string;425+ readonly project: ProjectName;426+ /** The fork's URL at the gateway; not empty. */427+ readonly remote: string;428+}429+430+/**431+ * The claim as its claimant sees it, in whichever state it is or ended in;432+ * none while the ask holds no claim.433+ */434+export const toView = (435+ state: ClaimState,436+ context: ViewContext437+): Option.Option<ClaimView> => {438+ const view = (claimed: Live, standing: ClaimView["state"]) => {439+ const shown = {440+ ask: claimed.ask,441+ base: claimed.base,442+ checkCommand: context.checkCommand,443+ claimant: claimed.claimant,444+ fork: claimed.fork,445+ lapsesAt: claimed.lapsesAt,446+ openedAt: claimed.openedAt,447+ project: context.project,448+ remote: context.remote,449+ state: standing,450+ warnsAt: claimed.warnsAt,451+ };452+453+ return Option.some(454+ ClaimView.make(455+ Option.match(claimed.lastPushAt, {456+ onNone: () => shown,457+ onSome: (lastPushAt) => ({ ...shown, lastPushAt }),458+ })459+ )460+ );461+ };462+463+ return ClaimState.match(state, {464+ Answered: (answered) => view(answered, "answered"),465+ Lapsed: (lapsed) => view(lapsed, "lapsed"),466+ Live: (live) => view(live, "live"),467+ Open: () => Option.none(),468+ Released: (released) => view(released, "released"),469+ Warned: (warned) => view(warned, "warned"),470+ });471+};added:packages/project/test/claim.model.test.ts+544 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 { AskFull } from "@repo/protocol/refusal";12+import { Arbitrary, DateTime, Option, Result, Schema } from "effect";13+14+import {15+ ClaimCommand,16+ ClaimEffect,17+ ClaimState,18+ forkName,19+ transition,20+} from "../src/claim.ts";21+import type { ClaimRefusal, ClaimStep, Live } from "../src/claim.ts";22+23+// A model test (ADR 0012): generated histories of claims, pushes, alarms,24+// releases and landings run through `transition` the way the project service25+// would, and every step is checked against the claim lifecycle's invariants.26+27+const HOUR = 3_600_000;28+29+/** The defaults: warned after 2 quiet hours, lapsed after 24. */30+const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };31+32+const project = ProjectName.make("datekit");33+34+const canonical = RepoName.make("datekit");35+36+const ask = AskId.make("parse-iso");37+38+const blocker = AskId.make("drop-legacy");39+40+const base = CommitSha.make("1".repeat(40));41+42+const head = CommitSha.make("2".repeat(40));43+44+const landing = LandedSha.make("3".repeat(40));45+46+const cap = 3;47+48+const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");49+50+/** Four people; `Bob` checks that a fork's name lowercases the handle. */51+const People = Schema.Literals(["alice", "Bob", "carol", "dave"]);52+53+/**54+ * How the person making a claim stands: free to claim, or meeting exactly one55+ * refusal (denounced, not vouched, the ask blocked, or at their cap).56+ */57+const Standing = Schema.Literals([58+ "clear",59+ "denounced",60+ "unvouched",61+ "blocked",62+ "atCap",63+]);64+65+type Standing = typeof Standing.Type;66+67+/** One thing that happens to the ask, as a history step names it. */68+const Move = Schema.TaggedUnion({69+ Claim: { standing: Standing, who: People },70+ Land: { who: People },71+ Push: { who: People },72+ Release: { who: People },73+ Tick: {},74+});75+76+type Move = typeof Move.Type;77+78+/**79+ * How the project service keeps the ask's claims: one state for the whole80+ * ask (`shared`, an exclusive kind), or one state per claimant with the81+ * kind's `race` (1 to 3) passed to each claim.82+ */83+const Layout = Schema.Literals(["shared", "race1", "race2", "race3"]);84+85+type Layout = typeof Layout.Type;86+87+/** One step of a history: whole hours waited since the last one, then a move. */88+interface Step {89+ readonly after: number;90+ readonly move: Move;91+}92+93+const roll = (maximum: number) =>94+ Arbitrary.schema(Schema.Int.check(Schema.isBetween({ maximum, minimum: 0 })));95+96+const person = Arbitrary.schema(People);97+98+/** Most claims are clear; a roll below 4 picks one refusal. */99+const troubles = ["denounced", "unvouched", "blocked", "atCap"] as const;100+101+const standing = roll(9).pipe(102+ Arbitrary.map((n): Standing => troubles[n] ?? "clear")103+);104+105+const claims = Arbitrary.all({ standing, who: person }).pipe(106+ Arbitrary.map((made) => Move.cases.Claim.make(made))107+);108+109+const pushes = person.pipe(110+ Arbitrary.map((who) => Move.cases.Push.make({ who }))111+);112+113+const releases = person.pipe(114+ Arbitrary.map((who) => Move.cases.Release.make({ who }))115+);116+117+const lands = person.pipe(118+ Arbitrary.map((who) => Move.cases.Land.make({ who }))119+);120+121+const ticks = Arbitrary.Constant(Move.cases.Tick.make({}));122+123+/** Moves by weight; shrinking a roll towards 0 turns a move into an alarm. */124+const weighted = [125+ ticks,126+ ticks,127+ pushes,128+ pushes,129+ pushes,130+ claims,131+ claims,132+ claims,133+ releases,134+ lands,135+];136+137+const moves = roll(weighted.length - 1).pipe(138+ Arbitrary.flatMap((n): Arbitrary.Arbitrary<Move> => weighted[n] ?? ticks)139+);140+141+/** Whole hours, so steps land exactly on the 2 h and 24 h deadlines often. */142+const histories = Arbitrary.array(143+ Arbitrary.all({ after: roll(26), move: moves }),144+ { maxLength: 40 }145+);146+147+const layouts = Arbitrary.schema(Layout);148+149+const raceOf = (layout: Layout) =>150+ ({ race1: 1, race2: 2, race3: 3, shared: 1 })[layout];151+152+/** A live claim: `Live` or `Warned`. */153+const live = (state: ClaimState): Option.Option<Live> =>154+ ClaimState.match(state, {155+ Answered: () => Option.none(),156+ Lapsed: () => Option.none(),157+ Live: Option.some<Live>,158+ Open: () => Option.none(),159+ Released: () => Option.none(),160+ Warned: Option.some<Live>,161+ });162+163+/** Any state that holds or held a claim. */164+const held = (state: ClaimState): Option.Option<Live> =>165+ ClaimState.match(state, {166+ Answered: Option.some<Live>,167+ Lapsed: Option.some<Live>,168+ Live: Option.some<Live>,169+ Open: () => Option.none(),170+ Released: Option.some<Live>,171+ Warned: Option.some<Live>,172+ });173+174+const isLive = (state: ClaimState) => Option.isSome(live(state));175+176+const tagOf = ClaimState.match({177+ Answered: () => "Answered",178+ Lapsed: () => "Lapsed",179+ Live: () => "Live",180+ Open: () => "Open",181+ Released: () => "Released",182+ Warned: () => "Warned",183+});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+/** Whether a claim command meets none of the refusals it could meet. */204+const clear = ({ before, command }: Call) =>205+ ClaimCommand.guards.Claim(command) &&206+ !isLive(before) &&207+ tagOf(before) !== "Answered" &&208+ command.liveCount < command.race &&209+ command.blockedBy.length === 0 &&210+ command.heldByWho < command.cap &&211+ !command.denounced &&212+ command.vouched;213+214+/** Whether a claim command finds every claim the ask allows taken. */215+const full = ({ before, command }: Call) =>216+ ClaimCommand.guards.Claim(command) &&217+ (tagOf(before) === "Answered" ||218+ command.liveCount >= command.race ||219+ Option.exists(220+ live(before),221+ (holder) => holder.claimant !== command.who.handle222+ ));223+224+/** Whether a push comes from the holder of a live claim. */225+const holderPushes = ({ before, command }: Call) =>226+ ClaimCommand.guards.Push(command) &&227+ Option.exists(live(before), (holder) => holder.claimant === command.who);228+229+/** Whether a claim command goes live, held by the person who made it. */230+const madeLive = ({ command }: Call, state: ClaimState) =>231+ ClaimCommand.guards.Claim(command) &&232+ Option.exists(233+ live(state),234+ (holder) => holder.claimant === command.who.handle235+ );236+237+/** What a refusal keeps: AskFull comes first, and nothing allowed is refused. */238+const brokenByRefusal = (call: Call, refusal: ClaimRefusal) => [239+ ...(full(call) && !Schema.is(AskFull)(refusal)240+ ? [`a full ask is refused with AskFull, not ${refusal._tag}`]241+ : []),242+ ...(clear(call) ? [`a clear claim is refused with ${refusal._tag}`] : []),243+ ...(holderPushes(call) ? ["the holder's push is refused"] : []),244+];245+246+/** An invariant over one successful call, naming what it found broken. */247+type Invariant = (call: Call, done: ClaimStep) => readonly string[];248+249+/** A claim that meets no refusal goes live, held by its maker; a full ask takes none. */250+const progresses: Invariant = (call, { state }) => [251+ ...(clear(call) && !madeLive(call, state) ? ["a clear claim goes live"] : []),252+ ...(full(call) ? ["a full ask takes a claim"] : []),253+];254+255+/** The holder's push keeps the claim live and counts from now. */256+const pushesRenew: Invariant = (call, { state }) =>257+ holderPushes(call) &&258+ !(259+ tagOf(state) === "Live" &&260+ Option.exists(live(state), (holder) =>261+ Option.exists(holder.lastPushAt, (pushed) => ms(pushed) === ms(call.now))262+ )263+ )264+ ? ["the holder's push makes the claim live from now"]265+ : [];266+267+/**268+ * A fork is made only on the way into Live from no claim, a lapsed one or a269+ * released one, and then exactly once, named for the new claimant.270+ */271+const forksOnlyNewClaims: Invariant = ({ before }, { effects, state }) => {272+ const forks = effects.filter(ClaimEffect.$is("MakeFork"));273+274+ const opens =275+ ["Open", "Released", "Lapsed"].includes(tagOf(before)) &&276+ tagOf(state) === "Live";277+278+ if (!opens) {279+ return forks.length > 0 ? [`a fork made from ${tagOf(before)}`] : [];280+ }281+282+ const named = Option.map(live(state), (claim) =>283+ forkName(project, ask, claim.claimant)284+ );285+286+ return forks.length === 1 &&287+ Option.exists(named, (name) => forks[0]?.name === name) &&288+ forks[0]?.from === canonical289+ ? []290+ : ["a new claim makes one fork, named for its claimant"];291+};292+293+/** Access is revoked exactly when a live claim ends. */294+const revokesWhenLiveEnds: Invariant = ({ before }, { effects, state }) => {295+ const revokes = effects.filter(ClaimEffect.$is("RevokeAccess")).length;296+ const ends = isLive(before) && !isLive(state);297+298+ return revokes === (ends ? 1 : 0)299+ ? []300+ : ["access is revoked once when a live claim ends"];301+};302+303+/** Deadlines count from the last push, or from the claim, never from later. */304+const deadlinesCount: Invariant = ({ now }, { state }) =>305+ Option.match(held(state), {306+ onNone: () => [],307+ onSome: (claim) => {308+ const since = ms(quietSince(claim));309+310+ return [311+ ...(ms(claim.lapsesAt) - since === policy.lapseAfterMs312+ ? []313+ : ["lapsesAt is the last push (or the claim) plus lapseAfterMs"]),314+ ...(ms(claim.warnsAt) - since === policy.warnAfterMs315+ ? []316+ : ["warnsAt is the last push (or the claim) plus warnAfterMs"]),317+ ...(since > ms(now) ? ["a claim pushed to or made after now"] : []),318+ ];319+ },320+ });321+322+/** Alarms are set only for later, and events happen now. */323+const noTimeTravel: Invariant = ({ now }, { effects }) => [324+ ...effects325+ .filter(ClaimEffect.$is("SetAlarm"))326+ .flatMap((alarm) =>327+ ms(alarm.at) > ms(now) ? [] : ["an alarm set for now or earlier"]328+ ),329+ ...effects330+ .filter(ClaimEffect.$is("Emit"))331+ .flatMap((emitted) =>332+ ms(emitted.event.at) === ms(now) ? [] : ["an event that is not now"]333+ ),334+];335+336+/** A claim is warned no earlier than warnsAt, and lapses no earlier than lapsesAt. */337+const deadlinesKept: Invariant = ({ before, now }, { state }) => {338+ const entered = tagOf(state) !== tagOf(before);339+340+ return Option.match(held(state), {341+ onNone: () => [],342+ onSome: (claim) => [343+ ...(entered && tagOf(state) === "Warned" && ms(now) < ms(claim.warnsAt)344+ ? ["warned before warnsAt"]345+ : []),346+ ...(entered && tagOf(state) === "Lapsed" && ms(now) < ms(claim.lapsesAt)347+ ? ["lapsed before lapsesAt"]348+ : []),349+ ],350+ });351+};352+353+/** Answered never changes; Released changes only by a fresh claim. */354+const endsAreFinal: Invariant = ({ before, command }, { state }) => [355+ ...(tagOf(before) === "Answered" && !same(before, state)356+ ? ["Answered is terminal"]357+ : []),358+ ...(tagOf(before) === "Released" &&359+ !same(before, state) &&360+ !(ClaimCommand.guards.Claim(command) && tagOf(state) === "Live")361+ ? ["Released changes only by a fresh claim"]362+ : []),363+];364+365+const invariants: readonly Invariant[] = [366+ progresses,367+ pushesRenew,368+ forksOnlyNewClaims,369+ revokesWhenLiveEnds,370+ deadlinesCount,371+ noTimeTravel,372+ deadlinesKept,373+ endsAreFinal,374+];375+376+/** Names every invariant one call broke. */377+const brokenBy = (378+ call: Call,379+ result: Result.Result<ClaimStep, ClaimRefusal>380+): readonly string[] =>381+ Result.match(result, {382+ onFailure: (refusal) => brokenByRefusal(call, refusal),383+ onSuccess: (done) =>384+ invariants.flatMap((invariant) => invariant(call, done)),385+ });386+387+/** The ask's claim states, by slot: the claimant's handle, or `ask` when shared. */388+type Slots = ReadonlyMap<string, ClaimState>;389+390+/** The model project service between two steps. */391+interface World {392+ readonly now: DateTime.Utc;393+ readonly slots: Slots;394+}395+396+const slotOf = (layout: Layout, who: string) =>397+ layout === "shared" ? "ask" : who;398+399+const stateIn = (slots: Slots, slot: string): ClaimState =>400+ slots.get(slot) ?? ClaimState.cases.Open.make({ ask });401+402+const liveOutside = (slots: Slots, slot: string) =>403+ [...slots].filter(([key, state]) => key !== slot && isLive(state)).length;404+405+/** A command for one slot. */406+interface Addressed {407+ readonly command: ClaimCommand;408+ readonly slot: string;409+}410+411+const to = (slot: string, command: ClaimCommand): Addressed => ({412+ command,413+ slot,414+});415+416+/** The commands the project service would send for a move, and where. */417+const commandsFor = (418+ layout: Layout,419+ slots: Slots,420+ move: Move421+): readonly Addressed[] =>422+ Move.match(move, {423+ Claim: ({ standing: made, who }) => [424+ to(425+ slotOf(layout, who),426+ ClaimCommand.cases.Claim.make({427+ base,428+ blockedBy: made === "blocked" ? [blocker] : [],429+ cap,430+ denounced: made === "denounced",431+ heldByWho: made === "atCap" ? cap : 0,432+ liveCount: liveOutside(slots, slotOf(layout, who)),433+ project,434+ race: raceOf(layout),435+ vouched: made !== "unvouched",436+ who: Person.make({ handle: Handle.make(who) }),437+ })438+ ),439+ ],440+ Land: ({ who }) => [441+ to(slotOf(layout, who), ClaimCommand.cases.Land.make({ landing })),442+ ],443+ Push: ({ who }) => [444+ to(445+ slotOf(layout, who),446+ ClaimCommand.cases.Push.make({ head, who: Handle.make(who) })447+ ),448+ ],449+ Release: ({ who }) => [450+ to(451+ slotOf(layout, who),452+ ClaimCommand.cases.Release.make({ who: Handle.make(who) })453+ ),454+ ],455+ // An alarm reaches every claim the ask holds.456+ Tick: () =>457+ [...slots.keys()].map((slot) =>458+ to(slot, ClaimCommand.cases.Tick.make({}))459+ ),460+ });461+462+/** Why an alarm left a claim past a deadline it reached, if it did. */463+const overdue = (now: DateTime.Utc, state: ClaimState) =>464+ Option.flatMap(live(state), (claim) => {465+ if (ms(now) >= ms(claim.lapsesAt)) {466+ return Option.some("an alarm left a claim past lapsesAt");467+ }468+469+ return tagOf(state) === "Live" && ms(now) >= ms(claim.warnsAt)470+ ? Option.some("an alarm left a claim unwarned past warnsAt")471+ : Option.none();472+ });473+474+/** What the whole ask keeps after a step: the race, and alarms that catch up. */475+const brokenAfter = (layout: Layout, world: World, move: Move) => {476+ const states = [...world.slots.values()];477+478+ const holders = new Set(479+ states.flatMap((state) =>480+ Option.toArray(Option.map(live(state), (holder) => holder.claimant))481+ )482+ );483+484+ return [485+ ...(holders.size > raceOf(layout)486+ ? [`${holders.size} live claims on a race of ${raceOf(layout)}`]487+ : []),488+ ...(Move.guards.Tick(move)489+ ? states.flatMap((state) => Option.toArray(overdue(world.now, state)))490+ : []),491+ ];492+};493+494+/** Takes one step: the next world, and what broke on the way. */495+const advance = (layout: Layout, world: World, { after, move }: Step) => {496+ const now = DateTime.add(world.now, { hours: after });497+ const slots = new Map(world.slots);498+ const broken: string[] = [];499+500+ for (const { command, slot } of commandsFor(layout, world.slots, move)) {501+ const call = { before: stateIn(world.slots, slot), command, now };502+ const result = transition(call.before, command, now, policy);503+504+ broken.push(...brokenBy(call, result));505+506+ if (Result.isSuccess(result)) {507+ slots.set(slot, result.success.state);508+ }509+ }510+511+ const next = { now, slots };512+513+ return { broken: [...broken, ...brokenAfter(layout, next, move)], next };514+};515+516+/** Runs a history; returns its first bad step and what that step broke. */517+const firstBreak = (layout: Layout, steps: readonly Step[]) => {518+ let world: World = { now: start, slots: new Map() };519+520+ for (const [index, step] of steps.entries()) {521+ const { broken, next } = advance(layout, world, step);522+523+ if (broken.length > 0) {524+ return [`step ${index}`, ...broken];525+ }526+527+ world = next;528+ }529+530+ return [];531+};532+533+describe("the claim lifecycle, over generated histories", () => {534+ it.prop(535+ "keeps every invariant after every step",536+ { history: histories, layout: layouts },537+ ({ history, layout }) => {538+ const broken = firstBreak(layout, history);539+540+ assert.deepStrictEqual(broken, [], broken.join("; "));541+ },542+ { arbitrary: { runs: 1000, size: 40 } }543+ );544+});added:packages/project/test/claim.test.ts+433 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("says AskFull before anything else, so a full ask never forks", () => {187+ expect(188+ transition(189+ live,190+ claimBy(carol, {191+ blockedBy: [blocker],192+ denounced: true,193+ heldByWho: 3,194+ vouched: false,195+ }),196+ at(1),197+ policy198+ )199+ ).toStrictEqual(Result.fail(new AskFull({ ask })));200+ });201+202+ it("gives a lapsed claim to the next person, with their own fork", () => {203+ const result = transition(lapsed, claimBy(carol), at(25), policy);204+205+ expect(Result.map(result, ({ effects }) => effects[0])).toStrictEqual(206+ Result.succeed(207+ ClaimEffect.MakeFork({208+ from: RepoName.make("datekit"),209+ name: RepoName.make("datekit--parse-iso--carol"),210+ })211+ )212+ );213+ });214+215+ it("refuses any claim on an answered ask with AskFull", () => {216+ const answered = ClaimState.cases.Answered.make({ ...fresh, landing });217+218+ expect(transition(answered, claimBy(bob), at(3), policy)).toStrictEqual(219+ Result.fail(new AskFull({ ask }))220+ );221+ });222+});223+224+describe("pushing keeps a claim alive", () => {225+ it("moves both deadlines on from the push and sets the alarm", () => {226+ expect(227+ transition(live, Push.make({ head, who: bob }), at(1), policy)228+ ).toStrictEqual(229+ step(230+ ClaimState.cases.Live.make({231+ ...fresh,232+ lapsesAt: at(25),233+ lastPushAt: Option.some(at(1)),234+ warnsAt: at(3),235+ }),236+ [237+ ClaimEffect.SetAlarm({ at: at(3) }),238+ ClaimEffect.Emit({239+ event: ProjectEventInput.Pushed({ ask, at: at(1), head }),240+ }),241+ ]242+ )243+ );244+ });245+246+ it("makes a warned claim live again", () => {247+ const result = transition(248+ warned,249+ Push.make({ head, who: bob }),250+ at(5),251+ policy252+ );253+254+ expect(Result.map(result, ({ state }) => state._tag)).toStrictEqual(255+ Result.succeed("Live")256+ );257+ });258+259+ it("refuses a push from someone who holds no claim with NotClaimed", () => {260+ expect(261+ transition(live, Push.make({ head, who: carol }), at(1), policy)262+ ).toStrictEqual(Result.fail(NotClaimed.of(ask)));263+ expect(264+ transition(open, Push.make({ head, who: bob }), at(1), policy)265+ ).toStrictEqual(Result.fail(NotClaimed.of(ask)));266+ });267+268+ it("refuses the lapsed claimant's push with ClaimLapsed", () => {269+ expect(270+ transition(lapsed, Push.make({ head, who: bob }), at(25), policy)271+ ).toStrictEqual(Result.fail(ClaimLapsed.of(ask)));272+ });273+});274+275+describe("an alarm", () => {276+ it("does nothing before the warn deadline", () => {277+ expect(transition(live, Tick.make({}), at(1), policy)).toStrictEqual(278+ step(live)279+ );280+ });281+282+ it("warns a claim at its warn deadline and sets the lapse alarm", () => {283+ expect(transition(live, Tick.make({}), at(2), policy)).toStrictEqual(284+ step(warned, [285+ ClaimEffect.SetAlarm({ at: at(24) }),286+ ClaimEffect.Emit({287+ event: ProjectEventInput.Warned({ ask, at: at(2) }),288+ }),289+ ])290+ );291+ });292+293+ it("lapses a warned claim at its lapse deadline and revokes the fork", () => {294+ expect(transition(warned, Tick.make({}), at(24), policy)).toStrictEqual(295+ step(lapsed, [296+ ClaimEffect.RevokeAccess({ fork }),297+ ClaimEffect.Emit({298+ event: ProjectEventInput.Lapsed({ ask, at: at(24) }),299+ }),300+ ])301+ );302+ });303+304+ it("lapses a live claim straight away when the alarm comes after both deadlines", () => {305+ const result = transition(live, Tick.make({}), at(30), policy);306+307+ expect(Result.map(result, ({ state }) => state._tag)).toStrictEqual(308+ Result.succeed("Lapsed")309+ );310+ });311+312+ it("leaves a warned claim alone before its lapse deadline", () => {313+ expect(transition(warned, Tick.make({}), at(23), policy)).toStrictEqual(314+ step(warned)315+ );316+ });317+});318+319+describe("releasing a claim", () => {320+ it("ends the holder's claim and revokes the fork", () => {321+ expect(322+ transition(live, Release.make({ who: bob }), at(1), policy)323+ ).toStrictEqual(324+ step(ClaimState.cases.Released.make(fresh), [325+ ClaimEffect.RevokeAccess({ fork }),326+ ClaimEffect.Emit({327+ event: ProjectEventInput.Released({ ask, at: at(1) }),328+ }),329+ ])330+ );331+ });332+333+ it("refuses anyone but the holder with NotClaimed", () => {334+ expect(335+ transition(live, Release.make({ who: carol }), at(1), policy)336+ ).toStrictEqual(Result.fail(NotClaimed.of(ask)));337+ });338+339+ it("converges when the holder releases twice", () => {340+ const released = ClaimState.cases.Released.make(fresh);341+342+ expect(343+ transition(released, Release.make({ who: bob }), at(2), policy)344+ ).toStrictEqual(step(released));345+ });346+});347+348+describe("landing the claimant's answer", () => {349+ it("answers the claim and revokes the fork", () => {350+ expect(351+ transition(live, Land.make({ landing }), at(3), policy)352+ ).toStrictEqual(353+ step(ClaimState.cases.Answered.make({ ...fresh, landing }), [354+ ClaimEffect.RevokeAccess({ fork }),355+ ])356+ );357+ });358+359+ it("converges when the landing is told twice", () => {360+ const answered = ClaimState.cases.Answered.make({ ...fresh, landing });361+362+ expect(363+ transition(answered, Land.make({ landing }), at(4), policy)364+ ).toStrictEqual(step(answered));365+ });366+});367+368+describe("the claim's view", () => {369+ const context = {370+ checkCommand: "bun test test/parse-iso.test.ts",371+ project,372+ remote: "https://platform.example/datekit--parse-iso--bob.git",373+ };374+375+ it("shows a live claim with its fork, remote and deadlines", () => {376+ expect(toView(live, context)).toStrictEqual(377+ Option.some(378+ ClaimView.make({379+ ask,380+ base,381+ checkCommand: context.checkCommand,382+ claimant: bob,383+ fork,384+ lapsesAt: at(24),385+ openedAt: start,386+ project,387+ remote: context.remote,388+ state: "live",389+ warnsAt: at(2),390+ })391+ )392+ );393+ });394+395+ it("names the state the claim ended in, and its last push", () => {396+ const pushed = { ...fresh, lastPushAt: Option.some(at(1)) };397+398+ expect(399+ Option.map(400+ toView(401+ ClaimState.cases.Lapsed.make({ ...pushed, at: at(25) }),402+ context403+ ),404+ ({ lastPushAt, state }) => ({ lastPushAt, state })405+ )406+ ).toStrictEqual(Option.some({ lastPushAt: at(1), state: "lapsed" }));407+ });408+409+ it("has no view while the ask holds no claim", () => {410+ expect(toView(open, context)).toStrictEqual(Option.none());411+ });412+});413+414+describe("the persisted state", () => {415+ it("round-trips through JSON text", () => {416+ const pushed = ClaimState.cases.Warned.make({417+ ...fresh,418+ lastPushAt: Option.some(at(1)),419+ });420+421+ const Stored = Schema.fromJsonString(ClaimState);422+ const text = Schema.encodeSync(Stored)(pushed);423+424+ expect(Schema.decodeSync(Stored)(text)).toStrictEqual(pushed);425+ });426+427+ it("is JSON with times as text, and leaves out a push that never came", () => {428+ const stored = Schema.encodeSync(ClaimState)(live);429+430+ expect(stored).toHaveProperty("lapsesAt", "2026-10-08T12:00:00.000Z");431+ expect(stored).not.toHaveProperty("lastPushAt");432+ });433+});