Skip to content
Myr

Hold the claim model test to who may claim, push and release, and to the alarm each live claim needs

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

- Review finding: the model test generated standings (denounced, unvouched, blocked, at cap) but never checked that a claim meeting one was refused. Each of these bugs, planted in transition, passed it: a denounced person, an off-by-one cap or an ignored blockedBy getting a claim; someone else releasing the holder's claim; a push or a warn that set no alarm. Only the examples caught them. - The model now owes every claim its first refusal, in the lifecycle's order (AskFull, AskBlocked, CapReached, Denounced, NotVouched), and a claim that owes none goes live, held by its maker. The holder claiming again changes nothing. Standings are four independent flags, each true one time in six, so claims meet several at once (the order is checked) and a shrunk one meets none. A planted skip of the denouncement shrinks to: Shrunk input: { "history": [{ "after": 0, "move": { "_tag": "Claim", "standing": { "atCap": false, "blocked": false, "denounced": true, "unvouched": false }, ... } }], "layout": "race3" } Failure: AssertionError: step 0; a claim that meets Denounced goes through Swapping CapReached ahead of AskBlocked shrinks to one claim with both flags set. - New invariants: only a live claim's holder moves it by a push or a release, and theirs always goes through; a move into or within live sets the alarm for its next deadline (warnsAt while live, lapsesAt once warned), since a claim with no alarm would never lapse. All 15 plants tried in review now fail the model test, then were removed. - Standards: the model compared tag strings from a tagOf helper (tagOf(x) === "Answered"), which gets around no-manual-tag-comparison. It now uses ClaimState.guards and isAnyOf, and Predicate.isTagged for the expected refusal. - claim.ts: the transition's result type was a local alias named Outcome, which is also the protocol's name for an answer's outcome. It is now the exported ClaimResult, and the model test uses it. - claim.test.ts: one example pins the rest of the order. A claim that meets every refusal but AskFull gets AskBlocked; without the blocker, it gets CapReached. - For 214 (issue Comments): Land carries no answerer, so keep one state per (ask, claimant) and send Land only to the answerer's own row.

authored by oscabriel · committed by oscabriel · parent 50293df · Browse files · 3 files+240 added−109 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+240 added−109 removed

  • tests:+226 added−98 removed
  • other:+14 added−11 removed

3 files+240 added−109 removed

modified:packages/project/src/claim.ts+14 added-11 removed
139 unmodified lines
140/** A claim's fork: `<project>--<ask>--<handle in lowercase>` (spec §4.5). */141export const forkName = (project: ProjectName, ask: AskId, handle: Handle) =>142 RepoName.make(`${project}--${ask}--${handle.toLowerCase()}`);143144/** What `transition` returns: a step, or the refusal that changes nothing. */144type Outcome = Result.Result<ClaimStep, ClaimRefusal>;145export type ClaimResult = Result.Result<ClaimStep, ClaimRefusal>;146147/** The state as it is, with nothing to settle: how a repeated command converges. */147const stay = (state: ClaimState): Outcome =>148const stay = (state: ClaimState): ClaimResult =>149 Result.succeed({ effects: [], state });150150const move = (state: ClaimState, ...effects: readonly ClaimEffect[]): Outcome =>151 Result.succeed({ effects, state });151const move = (152 state: ClaimState,153 ...effects: readonly ClaimEffect[]154): ClaimResult => Result.succeed({ effects, state });155156/** A claim's own fields, whatever state holds them. */157const claimOf = ({158 ask,
32 unmodified lines
191 ask: AskId,192 made: Claim,193 now: DateTime.Utc,194 policy: Policy["claims"]192): Outcome => {195): ClaimResult => {196 if (made.liveCount >= made.race) {197 return Result.fail(new AskFull({ ask }));198 }199
42 unmodified lines
242 state: ClaimState,243 made: Claim,244 now: DateTime.Utc,245 policy: Policy["claims"]243): Outcome => {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)
17 unmodified lines
268 state: ClaimState,269 { head, who }: typeof ClaimCommand.cases.Push.Type,270 now: DateTime.Utc,271 policy: Policy["claims"]269): Outcome => {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));
26 unmodified lines
303 Warned: kept,304 });305};306304const tick = (state: ClaimState, now: DateTime.Utc): Outcome => {307const tick = (state: ClaimState, now: DateTime.Utc): ClaimResult => {308 const reached = (deadline: DateTime.Utc) =>309 DateTime.isGreaterThanOrEqualTo(now, deadline);310311 // An alarm that comes late lapses the claim without warning it first.
35 unmodified lines
347const release = (348 state: ClaimState,349 who: Handle,350 now: DateTime.Utc348): Outcome => {351): ClaimResult => {352 const end = (live: Live) =>353 live.claimant === who354 ? move(355 ClaimState.cases.Released.make(claimOf(live)),
24 unmodified lines
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 */381const land = (state: ClaimState, landing: LandedSha): Outcome => {384const 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 ...effects
22 unmodified lines
411 state: ClaimState,412 command: ClaimCommand,413 now: DateTime.Utc,414 policy: Policy["claims"]412): Outcome =>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),
55 unmodified lines
modified:packages/project/test/claim.model.test.ts+205 added-98 removed
6 unmodified lines
7 ProjectName,8 RepoName,9} from "@repo/protocol/ids";10import { Person } from "@repo/protocol/principal";11import { AskFull } from "@repo/protocol/refusal";12import { Arbitrary, DateTime, Option, Result, Schema } from "effect";11import {12 Arbitrary,13 Array as Arr,14 DateTime,15 Option,16 Predicate,17 Result,18 Schema,19} from "effect";2021import {22 ClaimCommand,23 ClaimEffect,24 ClaimState,25 forkName,26 transition,27} from "../src/claim.ts";21import type { ClaimRefusal, ClaimStep, Live } from "../src/claim.ts";28import type { ClaimResult, ClaimStep, Live } from "../src/claim.ts";2930// A model test (ADR 0012): generated histories of claims, pushes, alarms,31// releases and landings run through `transition` the way the project service32// would, and every step is checked against the claim lifecycle's invariants.
24 unmodified lines
57/** Four people; `Bob` checks that a fork's name lowercases the handle. */58const People = Schema.Literals(["alice", "Bob", "carol", "dave"]);5960/**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).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 */57const Standing = Schema.Literals([58 "clear",59 "denounced",60 "unvouched",61 "blocked",62 "atCap",63]);65const Standing = Schema.Struct({66 atCap: Schema.Boolean,67 blocked: Schema.Boolean,68 denounced: Schema.Boolean,69 unvouched: Schema.Boolean,70});7165type Standing = typeof Standing.Type;6672/** One thing that happens to the ask, as a history step names it. */73const Move = Schema.TaggedUnion({74 Claim: { standing: Standing, who: People },75 Land: { who: People },
23 unmodified lines
99 Arbitrary.schema(Schema.Int.check(Schema.isBetween({ maximum, minimum: 0 })));100101const person = Arbitrary.schema(People);10298/** Most claims are clear; a roll below 4 picks one refusal. */99const troubles = ["denounced", "unvouched", "blocked", "atCap"] as const;103/** True one time in six; it shrinks to false, so a shrunk claim meets nothing. */104const rare = roll(5).pipe(Arbitrary.map((n) => n === 5));105101const standing = roll(9).pipe(102 Arbitrary.map((n): Standing => troubles[n] ?? "clear")103);106/** About half of all claims meet no refusal. */107const standing = Arbitrary.all({108 atCap: rare,109 blocked: rare,110 denounced: rare,111 unvouched: rare,112});113114const claims = Arbitrary.all({ standing, who: person }).pipe(115 Arbitrary.map((made) => Move.cases.Claim.make(made))116);
64 unmodified lines
181 });182183const isLive = (state: ClaimState) => Option.isSome(live(state));184176const tagOf = ClaimState.match({177 Answered: () => "Answered",178 Lapsed: () => "Lapsed",179 Live: () => "Live",180 Open: () => "Open",181 Released: () => "Released",182 Warned: () => "Warned",183});184185const ms = (time: DateTime.Utc) => DateTime.toEpochMillis(time);186187/** The time a claim's deadlines count from: its last push, or its making. */188const quietSince = (claim: Live) =>
10 unmodified lines
199 readonly command: ClaimCommand;200 readonly now: DateTime.Utc;201}202203/** Whether a claim command meets none of the refusals it could meet. */204const 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;203type Claim = typeof ClaimCommand.cases.Claim.Type;204214/** Whether a claim command finds every claim the ask allows taken. */215const 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 ));205/** Whether the person making a claim holds the ask's live claim already. */206const holds = (before: ClaimState, made: Claim) =>207 Option.exists(live(before), (holder) => holder.claimant === made.who.handle);208209/**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 */215const 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 );234235/**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 */239const claimsAsOwed = (240 { before, command }: Call,241 result: ClaimResult242): readonly string[] => {243 if (!ClaimCommand.guards.Claim(command)) {244 return [];245 }246247 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 }258259 const first = owed(before, command);260261 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};287288/** Who pushed or released; none for any other command. */289const 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});296297/**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 */301const 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 );312313 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 });325326/** Whether a push comes from the holder of a live claim. */327const holderPushes = ({ before, command }: Call) =>328 ClaimCommand.guards.Push(command) &&329 Option.exists(live(before), (holder) => holder.claimant === command.who);330229/** Whether a claim command goes live, held by the person who made it. */230const madeLive = ({ command }: Call, state: ClaimState) =>231 ClaimCommand.guards.Claim(command) &&232 Option.exists(233 live(state),234 (holder) => holder.claimant === command.who.handle235 );236237/** What a refusal keeps: AskFull comes first, and nothing allowed is refused. */238const 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];245331/** An invariant over one successful call, naming what it found broken. */332type Invariant = (call: Call, done: ClaimStep) => readonly string[];333249/** A claim that meets no refusal goes live, held by its maker; a full ask takes none. */250const 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];254334/** The holder's push keeps the claim live and counts from now. */335const pushesRenew: Invariant = (call, { state }) =>336 holderPushes(call) &&337 !(259 tagOf(state) === "Live" &&338 ClaimState.guards.Live(state) &&339 Option.exists(live(state), (holder) =>340 Option.exists(holder.lastPushAt, (pushed) => ms(pushed) === ms(call.now))341 )342 )
7 unmodified lines
350const forksOnlyNewClaims: Invariant = ({ before }, { effects, state }) => {351 const forks = effects.filter(ClaimEffect.$is("MakeFork"));352353 const opens =275 ["Open", "Released", "Lapsed"].includes(tagOf(before)) &&276 tagOf(state) === "Live";354 ClaimState.isAnyOf(["Open", "Released", "Lapsed"])(before) &&355 ClaimState.guards.Live(state);356357 if (!opens) {279 return forks.length > 0 ? [`a fork made from ${tagOf(before)}`] : [];358 return forks.length > 0 ? [`a fork made from ${before._tag}`] : [];359 }360361 const named = Option.map(live(state), (claim) =>362 forkName(project, ask, claim.claimant)
49 unmodified lines
412 ),413];414415/** A claim is warned no earlier than warnsAt, and lapses no earlier than lapsesAt. */337const deadlinesKept: Invariant = ({ before, now }, { state }) => {338 const entered = tagOf(state) !== tagOf(before);339340 return Option.match(held(state), {416const deadlinesKept: Invariant = ({ before, now }, { state }) =>417 Option.match(held(state), {418 onNone: () => [],419 onSome: (claim) => [343 ...(entered && tagOf(state) === "Warned" && ms(now) < ms(claim.warnsAt)420 ...(ClaimState.guards.Warned(state) &&421 !ClaimState.guards.Warned(before) &&422 ms(now) < ms(claim.warnsAt)423 ? ["warned before warnsAt"]424 : []),346 ...(entered && tagOf(state) === "Lapsed" && ms(now) < ms(claim.lapsesAt)425 ...(ClaimState.guards.Lapsed(state) &&426 !ClaimState.guards.Lapsed(before) &&427 ms(now) < ms(claim.lapsesAt)428 ? ["lapsed before lapsesAt"]429 : []),430 ],431 });351};432433/**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 */438const 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;445446 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 });456457/** Answered never changes; Released changes only by a fresh claim. */458const endsAreFinal: Invariant = ({ before, command }, { state }) => [355 ...(tagOf(before) === "Answered" && !same(before, state)459 ...(ClaimState.guards.Answered(before) && !same(before, state)460 ? ["Answered is terminal"]461 : []),358 ...(tagOf(before) === "Released" &&462 ...(ClaimState.guards.Released(before) &&463 !same(before, state) &&360 !(ClaimCommand.guards.Claim(command) && tagOf(state) === "Live")464 !(ClaimCommand.guards.Claim(command) && ClaimState.guards.Live(state))465 ? ["Released changes only by a fresh claim"]466 : []),467];468469const invariants: readonly Invariant[] = [366 progresses,470 pushesRenew,471 forksOnlyNewClaims,472 revokesWhenLiveEnds,473 deadlinesCount,474 noTimeTravel,475 deadlinesKept,476 alarmsNextDeadline,477 endsAreFinal,478];479376/** Names every invariant one call broke. */377const brokenBy = (378 call: Call,379 result: Result.Result<ClaimStep, ClaimRefusal>380): readonly string[] =>381 Result.match(result, {382 onFailure: (refusal) => brokenByRefusal(call, refusal),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 */484const 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)),385 });491 }),492];493494/** The ask's claim states, by slot: the claimant's handle, or `ask` when shared. */495type Slots = ReadonlyMap<string, ClaimState>;496
34 unmodified lines
531 to(532 slotOf(layout, who),533 ClaimCommand.cases.Claim.make({534 base,428 blockedBy: made === "blocked" ? [blocker] : [],535 blockedBy: made.blocked ? [blocker] : [],536 cap,430 denounced: made === "denounced",431 heldByWho: made === "atCap" ? cap : 0,537 denounced: made.denounced,538 heldByWho: made.atCap ? cap : 0,539 liveCount: liveOutside(slots, slotOf(layout, who)),540 project,541 race: raceOf(layout),435 vouched: made !== "unvouched",542 vouched: !made.unvouched,543 who: Person.make({ handle: Handle.make(who) }),544 })545 ),546 ],
25 unmodified lines
572 if (ms(now) >= ms(claim.lapsesAt)) {573 return Option.some("an alarm left a claim past lapsesAt");574 }575469 return tagOf(state) === "Live" && ms(now) >= ms(claim.warnsAt)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
71 unmodified lines
modified:packages/project/test/claim.test.ts+21 added
181 unmodified lines
182 )183 ).toStrictEqual(Result.fail(new Denounced({})));184 });185186 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 };193194 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 });206207 it("says AskFull before anything else, so a full ask never forks", () => {208 expect(209 transition(210 live,
244 unmodified lines