Skip to content
Myr

claim.model.test.ts

This file

Path

packages/project/test/claim.model.test.ts

585 lines · 15.5 KiB · TypeScript

Last changed by

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–3why, one step back
1import { assert, describe, it } from "@effect/vitest";
2import {3 AskId,

Merge build/1400-followups into mainoscabrielbefore adoption7a90542

line 4why, one step back
4 claimForkName,

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 5–33why, one step back
5 CommitSha,
6 Handle,7 LandedSha,8 ProjectName,9 RepoName,10} from "@repo/protocol/ids";11import { Person } from "@repo/protocol/principal";12import {13 Arbitrary,14 Array as Arr,15 DateTime,16 Option,17 Predicate,18 Result,19 Schema,20} from "effect";2122import {23 ClaimCommand,24 ClaimEffect,25 ClaimState,26 transition,27} from "../src/claim.ts";28import type { ClaimResult, ClaimStep, Live } from "../src/claim.ts";2930const HOUR = 3_600_000;3132const policy = { lapseAfterMs: 24 * HOUR, warnAfterMs: 2 * HOUR };33

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 34why, one step back
34const project = ProjectName.make("alice/datekit");

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 35why, one step back
35

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 36why, one step back
36const canonical = RepoName.make("alice__datekit");

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 37–51why, one step back
37
38const ask = AskId.make("parse-iso");3940const blocker = AskId.make("drop-legacy");4142const base = CommitSha.make("1".repeat(40));4344const head = CommitSha.make("2".repeat(40));4546const landing = LandedSha.make("3".repeat(40));4748const cap = 3;4950const start = DateTime.makeUnsafe("2026-10-07T12:00:00Z");51

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

line 52why, one step back
52/** `Bob` checks that a fork's name lowercases the handle. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 53–130why, one step back
53const People = Schema.Literals(["alice", "Bob", "carol", "dave"]);
5455const Standing = Schema.Struct({56 atCap: Schema.Boolean,57 blocked: Schema.Boolean,58 denounced: Schema.Boolean,59 unvouched: Schema.Boolean,60});6162const Move = Schema.TaggedUnion({63 Claim: { standing: Standing, who: People },64 Land: { who: People },65 Push: { who: People },66 Release: { who: People },67 Tick: {},68});6970type Move = typeof Move.Type;7172const Layout = Schema.Literals(["shared", "race1", "race2", "race3"]);7374type Layout = typeof Layout.Type;7576interface Step {77 readonly after: number;78 readonly move: Move;79}8081const roll = (maximum: number) =>82 Arbitrary.schema(Schema.Int.check(Schema.isBetween({ maximum, minimum: 0 })));8384const person = Arbitrary.schema(People);8586/** True one time in six; it shrinks to false, so a shrunk claim meets nothing. */87const rare = roll(5).pipe(Arbitrary.map((n) => n === 5));8889const standing = Arbitrary.all({90 atCap: rare,91 blocked: rare,92 denounced: rare,93 unvouched: rare,94});9596const claims = Arbitrary.all({ standing, who: person }).pipe(97 Arbitrary.map((made) => Move.cases.Claim.make(made))98);99100const pushes = person.pipe(101 Arbitrary.map((who) => Move.cases.Push.make({ who }))102);103104const releases = person.pipe(105 Arbitrary.map((who) => Move.cases.Release.make({ who }))106);107108const lands = person.pipe(109 Arbitrary.map((who) => Move.cases.Land.make({ who }))110);111112const ticks = Arbitrary.Constant(Move.cases.Tick.make({}));113114const weighted = [115 ticks,116 ticks,117 pushes,118 pushes,119 pushes,120 claims,121 claims,122 claims,123 releases,124 lands,125];126127const moves = roll(weighted.length - 1).pipe(128 Arbitrary.flatMap((n): Arbitrary.Arbitrary<Move> => weighted[n] ?? ticks)129);130

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

line 131why, one step back
131/** Whole hours, so steps often land exactly on the 2 h and 24 h deadlines. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 132–315why, one step back
132const histories = Arbitrary.array(
133 Arbitrary.all({ after: roll(26), move: moves }),134 { maxLength: 40 }135);136137const layouts = Arbitrary.schema(Layout);138139const raceOf = (layout: Layout) =>140 ({ race1: 1, race2: 2, race3: 3, shared: 1 })[layout];141142const live = (state: ClaimState): Option.Option<Live> =>143 ClaimState.match(state, {144 Answered: () => Option.none(),145 Lapsed: () => Option.none(),146 Live: Option.some<Live>,147 Open: () => Option.none(),148 Released: () => Option.none(),149 Warned: Option.some<Live>,150 });151152const held = (state: ClaimState): Option.Option<Live> =>153 ClaimState.match(state, {154 Answered: Option.some<Live>,155 Lapsed: Option.some<Live>,156 Live: Option.some<Live>,157 Open: () => Option.none(),158 Released: Option.some<Live>,159 Warned: Option.some<Live>,160 });161162const isLive = (state: ClaimState) => Option.isSome(live(state));163164const ms = (time: DateTime.Utc) => DateTime.toEpochMillis(time);165166const quietSince = (claim: Live) =>167 Option.getOrElse(claim.lastPushAt, () => claim.openedAt);168169const encode = Schema.encodeSync(ClaimState);170171const same = (left: ClaimState, right: ClaimState) =>172 JSON.stringify(encode(left)) === JSON.stringify(encode(right));173174interface Call {175 readonly before: ClaimState;176 readonly command: ClaimCommand;177 readonly now: DateTime.Utc;178}179180type Claim = typeof ClaimCommand.cases.Claim.Type;181182const holds = (before: ClaimState, made: Claim) =>183 Option.exists(live(before), (holder) => holder.claimant === made.who.handle);184185const owed = (before: ClaimState, made: Claim) =>186 Option.map(187 Arr.findFirst(188 [189 [190 "AskFull",191 ClaimState.guards.Answered(before) ||192 isLive(before) ||193 made.liveCount >= made.race,194 ],195 ["AskBlocked", made.blockedBy.length > 0],196 ["CapReached", made.heldByWho >= made.cap],197 ["Denounced", made.denounced],198 ["NotVouched", !made.vouched],199 ] as const,200 ([, meets]) => meets201 ),202 ([refusal]) => refusal203 );204205const claimsAsOwed = (206 { before, command }: Call,207 result: ClaimResult208): readonly string[] => {209 if (!ClaimCommand.guards.Claim(command)) {210 return [];211 }212213 if (holds(before, command)) {214 return Result.match(result, {215 onFailure: (refusal) => [216 `the holder claiming again is refused with ${refusal._tag}`,217 ],218 onSuccess: ({ effects, state }) =>219 effects.length === 0 && same(before, state)220 ? []221 : ["the holder claiming again changes the claim"],222 });223 }224225 const first = owed(before, command);226227 return Result.match(result, {228 onFailure: (refusal) =>229 Option.match(first, {230 onNone: () => [231 `a claim that meets no refusal is refused with ${refusal._tag}`,232 ],233 onSome: (expected) =>234 Predicate.isTagged(refusal, expected)235 ? []236 : [237 `a claim that meets ${expected} first is refused with ${refusal._tag}`,238 ],239 }),240 onSuccess: ({ state }) =>241 Option.match(first, {242 onNone: () =>243 Option.exists(244 live(state),245 (holder) => holder.claimant === command.who.handle246 )247 ? []248 : ["a claim that meets no refusal goes live, held by its maker"],249 onSome: (expected) => [`a claim that meets ${expected} goes through`],250 }),251 });252};253254const pushedOrReleasedBy = ClaimCommand.match({255 Claim: () => Option.none<Handle>(),256 Land: () => Option.none<Handle>(),257 Push: ({ who }) => Option.some(who),258 Release: ({ who }) => Option.some(who),259 Tick: () => Option.none<Handle>(),260});261262const holderOnly = (263 { before, command }: Call,264 result: ClaimResult265): readonly string[] =>266 Option.match(pushedOrReleasedBy(command), {267 onNone: () => [],268 onSome: (who) => {269 const holder = Option.exists(270 live(before),271 (claim) => claim.claimant === who272 );273274 return Result.match(result, {275 onFailure: (refusal) =>276 holder277 ? [`the holder's ${command._tag} is refused with ${refusal._tag}`]278 : [],279 onSuccess: ({ state }) =>280 holder || same(before, state)281 ? []282 : [`a ${command._tag} by someone without the live claim moves it`],283 });284 },285 });286287const holderPushes = ({ before, command }: Call) =>288 ClaimCommand.guards.Push(command) &&289 Option.exists(live(before), (holder) => holder.claimant === command.who);290291type Invariant = (call: Call, done: ClaimStep) => readonly string[];292293const pushesRenew: Invariant = (call, { state }) =>294 holderPushes(call) &&295 !(296 ClaimState.guards.Live(state) &&297 Option.exists(live(state), (holder) =>298 Option.exists(holder.lastPushAt, (pushed) => ms(pushed) === ms(call.now))299 )300 )301 ? ["the holder's push makes the claim live from now"]302 : [];303304const forksOnlyNewClaims: Invariant = ({ before }, { effects, state }) => {305 const forks = effects.filter(ClaimEffect.$is("MakeFork"));306307 const opens =308 ClaimState.isAnyOf(["Open", "Released", "Lapsed"])(before) &&309 ClaimState.guards.Live(state);310311 if (!opens) {312 return forks.length > 0 ? [`a fork made from ${before._tag}`] : [];313 }314315 const named = Option.map(live(state), (claim) =>

Merge build/1400-followups into mainoscabrielbefore adoption7a90542

line 316why, one step back
316 claimForkName(project, ask, claim.claimant)

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 317–570why, one step back
317 );
318319 return forks.length === 1 &&320 Option.exists(named, (name) => forks[0]?.name === name) &&321 forks[0]?.from === canonical322 ? []323 : ["a new claim makes one fork, named for its claimant"];324};325326const revokesWhenLiveEnds: Invariant = ({ before }, { effects, state }) => {327 const revokes = effects.filter(ClaimEffect.$is("RevokeAccess")).length;328 const ends = isLive(before) && !isLive(state);329330 return revokes === (ends ? 1 : 0)331 ? []332 : ["access is revoked once when a live claim ends"];333};334335const deadlinesCount: Invariant = ({ now }, { state }) =>336 Option.match(held(state), {337 onNone: () => [],338 onSome: (claim) => {339 const since = ms(quietSince(claim));340341 return [342 ...(ms(claim.lapsesAt) - since === policy.lapseAfterMs343 ? []344 : ["lapsesAt is the last push (or the claim) plus lapseAfterMs"]),345 ...(ms(claim.warnsAt) - since === policy.warnAfterMs346 ? []347 : ["warnsAt is the last push (or the claim) plus warnAfterMs"]),348 ...(since > ms(now) ? ["a claim pushed to or made after now"] : []),349 ];350 },351 });352353const noTimeTravel: Invariant = ({ now }, { effects }) => [354 ...effects355 .filter(ClaimEffect.$is("SetAlarm"))356 .flatMap((alarm) =>357 ms(alarm.at) > ms(now) ? [] : ["an alarm set for now or earlier"]358 ),359 ...effects360 .filter(ClaimEffect.$is("Emit"))361 .flatMap((emitted) =>362 ms(emitted.event.at) === ms(now) ? [] : ["an event that is not now"]363 ),364];365366const deadlinesKept: Invariant = ({ before, now }, { state }) =>367 Option.match(held(state), {368 onNone: () => [],369 onSome: (claim) => [370 ...(ClaimState.guards.Warned(state) &&371 !ClaimState.guards.Warned(before) &&372 ms(now) < ms(claim.warnsAt)373 ? ["warned before warnsAt"]374 : []),375 ...(ClaimState.guards.Lapsed(state) &&376 !ClaimState.guards.Lapsed(before) &&377 ms(now) < ms(claim.lapsesAt)378 ? ["lapsed before lapsesAt"]379 : []),380 ],381 });382383const alarmsNextDeadline: Invariant = ({ before }, { effects, state }) =>384 Option.match(live(state), {385 onNone: () => [],386 onSome: (claim) => {387 const next = ClaimState.guards.Warned(state)388 ? claim.lapsesAt389 : claim.warnsAt;390391 return same(before, state) ||392 effects393 .filter(ClaimEffect.$is("SetAlarm"))394 .some((alarm) => ms(alarm.at) === ms(next))395 ? []396 : [397 `a claim moved to ${state._tag} sets no alarm for its next deadline`,398 ];399 },400 });401402const endsAreFinal: Invariant = ({ before, command }, { state }) => [403 ...(ClaimState.guards.Answered(before) && !same(before, state)404 ? ["Answered is terminal"]405 : []),406 ...(ClaimState.guards.Released(before) &&407 !same(before, state) &&408 !(ClaimCommand.guards.Claim(command) && ClaimState.guards.Live(state))409 ? ["Released changes only by a fresh claim"]410 : []),411];412413const invariants: readonly Invariant[] = [414 pushesRenew,415 forksOnlyNewClaims,416 revokesWhenLiveEnds,417 deadlinesCount,418 noTimeTravel,419 deadlinesKept,420 alarmsNextDeadline,421 endsAreFinal,422];423424const brokenBy = (call: Call, result: ClaimResult): readonly string[] => [425 ...claimsAsOwed(call, result),426 ...holderOnly(call, result),427 ...Result.match(result, {428 onFailure: () => [],429 onSuccess: (done) =>430 invariants.flatMap((invariant) => invariant(call, done)),431 }),432];433434type Slots = ReadonlyMap<string, ClaimState>;435436interface World {437 readonly now: DateTime.Utc;438 readonly slots: Slots;439}440441const slotOf = (layout: Layout, who: string) =>442 layout === "shared" ? "ask" : who;443444const stateIn = (slots: Slots, slot: string): ClaimState =>445 slots.get(slot) ?? ClaimState.cases.Open.make({ ask });446447const liveOutside = (slots: Slots, slot: string) =>448 [...slots].filter(([key, state]) => key !== slot && isLive(state)).length;449450interface Addressed {451 readonly command: ClaimCommand;452 readonly slot: string;453}454455const to = (slot: string, command: ClaimCommand): Addressed => ({456 command,457 slot,458});459460const commandsFor = (461 layout: Layout,462 slots: Slots,463 move: Move464): readonly Addressed[] =>465 Move.match(move, {466 Claim: ({ standing: made, who }) => [467 to(468 slotOf(layout, who),469 ClaimCommand.cases.Claim.make({470 base,471 blockedBy: made.blocked ? [blocker] : [],472 cap,473 denounced: made.denounced,474 heldByWho: made.atCap ? cap : 0,475 liveCount: liveOutside(slots, slotOf(layout, who)),476 project,477 race: raceOf(layout),478 vouched: !made.unvouched,479 who: Person.make({ handle: Handle.make(who) }),480 })481 ),482 ],483 Land: ({ who }) => [484 to(slotOf(layout, who), ClaimCommand.cases.Land.make({ landing })),485 ],486 Push: ({ who }) => [487 to(488 slotOf(layout, who),489 ClaimCommand.cases.Push.make({ head, who: Handle.make(who) })490 ),491 ],492 Release: ({ who }) => [493 to(494 slotOf(layout, who),495 ClaimCommand.cases.Release.make({ who: Handle.make(who) })496 ),497 ],498 Tick: () =>499 [...slots.keys()].map((slot) =>500 to(slot, ClaimCommand.cases.Tick.make({}))501 ),502 });503504const overdue = (now: DateTime.Utc, state: ClaimState) =>505 Option.flatMap(live(state), (claim) => {506 if (ms(now) >= ms(claim.lapsesAt)) {507 return Option.some("an alarm left a claim past lapsesAt");508 }509510 return ClaimState.guards.Live(state) && ms(now) >= ms(claim.warnsAt)511 ? Option.some("an alarm left a claim unwarned past warnsAt")512 : Option.none();513 });514515const brokenAfter = (layout: Layout, world: World, move: Move) => {516 const states = [...world.slots.values()];517518 const holders = new Set(519 states.flatMap((state) =>520 Option.toArray(Option.map(live(state), (holder) => holder.claimant))521 )522 );523524 return [525 ...(holders.size > raceOf(layout)526 ? [`${holders.size} live claims on a race of ${raceOf(layout)}`]527 : []),528 ...(Move.guards.Tick(move)529 ? states.flatMap((state) => Option.toArray(overdue(world.now, state)))530 : []),531 ];532};533534const advance = (layout: Layout, world: World, { after, move }: Step) => {535 const now = DateTime.add(world.now, { hours: after });536 const slots = new Map(world.slots);537 const broken: string[] = [];538539 for (const { command, slot } of commandsFor(layout, world.slots, move)) {540 const call = { before: stateIn(world.slots, slot), command, now };541 const result = transition(call.before, command, now, policy);542543 broken.push(...brokenBy(call, result));544545 if (Result.isSuccess(result)) {546 slots.set(slot, result.success.state);547 }548 }549550 const next = { now, slots };551552 return { broken: [...broken, ...brokenAfter(layout, next, move)], next };553};554555const firstBreak = (layout: Layout, steps: readonly Step[]) => {556 let world: World = { now: start, slots: new Map() };557558 for (const [index, step] of steps.entries()) {559 const { broken, next } = advance(layout, world, step);560561 if (broken.length > 0) {562 return [`step ${index}`, ...broken];563 }564565 world = next;566 }567568 return [];569};570

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

line 571why, one step back
571/** CPU-bound, but slow while turbo runs every package's tests at once: this catches a hang, not a busy machine. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 572–585why, one step back
572const generated = { timeout: 30_000 };
573574describe("the claim lifecycle, over generated histories", generated, () => {575 it.prop(576 "keeps every invariant after every step",577 { history: histories, layout: layouts },578 ({ history, layout }) => {579 const broken = firstBreak(layout, history);580581 assert.deepStrictEqual(broken, [], broken.join("; "));582 },583 { arbitrary: { runs: 1000, size: 40 } }584 );585});