Skip to content
Myr

Hold openAsk to deciders of the ask's territory, and keep an open ask and another person's request id from being taken over

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

- openAsk refuses NotDecider unless a deciders entry's glob holds the ask's territory (attention/decisions.decidersFor, each territory glob read as the path it spells). It used to admit anyone named in any entry, whatever its glob. - openAsk on an ask still open or claimed returns the ask as it stands and the commit that opened it. It used to land a second commit, emit AskOpened again and reset a claimed ask to open. ASSUMPTION: changing an open ask is a decision (221), not a second openAsk. - openAsk reads only the stated ask from the composed commit. Its kind, the judge closure for TouchedJudge and the check's lane come from main's policy (ADR 0005), so an ask's own files cannot change the rules it is judged by. - submitAnswer with a requestId another person's answer already holds is NotClaimed. It used to return that person's receipt, and with a claim of its own it could have overwritten their answer row. - Smaller fixes: commit reuses outbox.projectedRows (it was dead and duplicated inline); a workspace's manifest is <dir>/package.json exactly, not any name ending in package.json; evaluationFacts builds its empty facts once; queueAnswer takes the ask id instead of calling Option.getOrThrow. - test/world.ts: worldOf takes only what it reads, a scenario's policy (WorldScenario), so a test can vary the deciders. - Tests added (project.test.ts, 30 now). Each new assertion failed against the old code: step 1 checks awaitingFirstPush and DirectPush for a first push that isn't the initializer's; step 6 checks that carol's replay of bob's request is NotClaimed; "opening an ask" checks a second open of a claimed ask, and a decider for packages/format/** only, who opens a format ask but is NotDecider for a parser ask.

authored by oscabriel · committed by oscabriel · parent d048cb9 · Browse files · 4 files+249 added−76 removed
This commit

State

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

Diff stats

4 files+249 added−76 removed

  • tests:+134 added−9 removed
  • other:+115 added−67 removed

4 files+249 added−76 removed

modified:packages/project/src/facts.ts+13 added-23 removed
334 unmodified lines
335const workspaceAt = (repo: RepoName, root: ObjectId, dir: string) =>336 Effect.map(filesIn(repo, root, dir), (files) =>337 Option.flatMap(338 Option.fromNullishOr(339 files.find(({ path }) => path.endsWith("package.json"))339 files.find(({ path }) => path === `${dir}/package.json`)340 ),341 ({ content }) => decodeManifest(content)342 ).pipe(343 Option.flatMap((manifest) =>
29 unmodified lines
373export const evaluationFacts = (374 repo: RepoName,375 at: CommitSha,376 input: FactsInput377): Effect.Effect<EvaluationFacts, never, RepoHost> =>378 Effect.gen(function* () {379 const empty: EvaluationFacts = {380 ci: [],381 initializer: input.initializer,382 now: input.now,383 project: input.project,384 seed: Number.parseInt(at.slice(0, 8), 16),385 workspaces: [],386 };377): Effect.Effect<EvaluationFacts, never, RepoHost> => {378 const empty: EvaluationFacts = {379 ci: [],380 initializer: input.initializer,381 now: input.now,382 project: input.project,383 seed: Number.parseInt(at.slice(0, 8), 16),384 workspaces: [],385 };386387 return Effect.gen(function* () {388 const commit = yield* RepoHost.use((host) => host.readCommit(repo, at));389390 if (Option.isNone(commit)) {391 return empty;
41 unmodified lines
433 return Option.match(vouch, {434 onNone: () => facts,435 onSome: (bytes) => ({ ...facts, vouchFile: textOf(bytes) }),436 });437 }).pipe(438 Effect.catchTag("RepoNotFound", () =>439 Effect.succeed({440 ci: [],441 initializer: input.initializer,442 now: input.now,443 project: input.project,444 seed: Number.parseInt(at.slice(0, 8), 16),445 workspaces: [],446 })447 )448 );437 }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeed(empty)));438};
modified:packages/project/src/project.ts+102 added-44 removed
123 unmodified lines
124 Steps,125} from "./answer-runs.ts";126import type { AnswerQueue, AnswerRuns } from "./answer-runs.ts";127import { isStep } from "./answer-runs/steps.ts";128import { decidersFor } from "./attention/decisions.ts";129import { recordOf, sameHandle } from "./attention/record.ts";130import { mayClaim, standing } from "./attention/vouch.ts";131import {132 ClaimCommand,
16 unmodified lines
149 outcomeOf,150 transition as landingTransition,151} from "./landing.ts";152import type { LandingQueue, Request } from "./landing.ts";152import { isDue, outboxRow, OutboxBody, runOutbox, startRow } from "./outbox.ts";153import {154 isDue,155 outboxRow,156 OutboxBody,157 projectedRows,158 runOutbox,159 startRow,160} from "./outbox.ts";161import { ProjectStore } from "./project-store.ts";162import type { ProjectWrites } from "./project-store.ts";163import type {164 AnswerRow,
453 unmodified lines
618 policy.deciders.some(({ handles }) =>619 handles.some((each) => sameHandle(each, handle))620 );621622/**623 * Whether `handle` decides for the ask's territory: a deciders entry whose624 * glob holds one of the territory's globs, each read as the path it spells625 * (`packages/**` holds `packages/parser/**`; `**` holds every territory).626 */627const decidesOn = (policy: Policy, ask: Ask, handle: Handle) =>628 decidersFor(629 policy,630 ask.territory.paths.map((glob) => RepoPath.make(glob))631 ).some((each) => sameHandle(each, handle));632633/** A path a composed commit can hold: plain folder names and a file name. */634const isPlainPath = (path: string) =>635 path636 .split("/")
403 unmodified lines
1040 return [];1041 }10421043 const events = yield* numbered(h.lastSeq, writes.events);1044 const projected = yield* projectedRows(name, events, now);10451026 const projected = yield* Effect.forEach(events, (event) =>1027 outboxRow(1028 `projected:${event.seq}`,1029 OutboxBody.cases.Projected.make({ event, project: name }),1030 now1031 )1032 );10331046 const outbox = [...writes.outbox, ...projected];10471048 const queue = yield* Effect.forEach(writes.queue.values(), (each) =>1049 storedQueue(each)
854 unmodified lines
19041905 return { landed };1906 });19071896 /** The ask a decider's files state, read from the config folder at the commit they compose. */1897 const statedAsk = (1898 row: ProjectRow,1899 composed: CommitSha,1900 id: AskId,1901 now: DateTime.Utc1902 ) =>1908 /**1909 * The ask a decider's files state, read from the config folder at the1910 * commit they compose; its kind, as every rule but the ask itself, is1911 * main's (ADR 0005).1912 */1913 const statedAsk = (input: {1914 readonly composed: CommitSha;1915 readonly id: AskId;1916 readonly now: DateTime.Utc;1917 readonly policy: Policy;1918 readonly row: ProjectRow;1919 }) =>1920 Effect.gen(function* () {1921 const { id, policy } = input;19221923 // The composed commit is never main; the evaluator reads it as it1924 // would a landing, which is all the port knows how to name.1906 const evaluated = yield* evaluateAt(row, LandedSha.make(composed), now);1925 const evaluated = yield* evaluateAt(1926 input.row,1927 LandedSha.make(input.composed),1928 input.now1929 );19301931 if (Option.isNone(evaluated)) {1932 return yield* new VerifierBlocked({});1933 }19341912 const policy = evaluated.value;1913 const stated = policy.asks.find((ask) => ask.id === id);1935 const stated = evaluated.value.asks.find((ask) => ask.id === id);19361937 if (stated === undefined) {1938 return yield* new IncompleteBrief({ missing: ["want"] });1939 }
8 unmodified lines
1948 if (Array.isReadonlyArrayNonEmpty(missing)) {1949 return yield* new IncompleteBrief({ missing });1950 }19511930 return { policy, stated };1952 return stated;1953 });19541955 /** The judge an ask's files touch beyond their own (stage 1, as an ask opens). */1956 const touchedJudge = (input: {
111 unmodified lines
2068 if (Option.isNone(live) || Option.isNone(h.policy)) {2069 return yield* new VerifierBlocked({});2070 }20712072 const policy = h.policy.value;20732050 if (!isDecider(h.policy.value, caller.handle)) {2074 if (!isDecider(policy, caller.handle)) {2075 return yield* new NotDecider({});2076 }20772078 // An ask still open (or claimed) is not opened twice: the same2079 // call again finds it as it stands, and nothing lands.2080 const stillOpen = Option.filter(2081 askNow(h, writes, input.ask),2082 ({ state }) => state !== "closed"2083 );20842085 if (Option.isSome(stillOpen)) {2086 return decidesOn(policy, stillOpen.value, caller.handle)2087 ? { ask: stillOpen.value, landed: stillOpen.value.openedIn }2088 : yield* new NotDecider({});2089 }20902091 const unplain = input.files.flatMap(({ path }) =>2092 isPlainPath(path) ? [] : [path]2093 );2094
4 unmodified lines
2099 const { landed: main, row } = live.value;2100 const { files } = input;2101 const composed = yield* lander.compose({ files, main, repo });21022066 const { policy, stated } = yield* statedAsk(2103 const stated = yield* statedAsk({2104 composed: composed.commit,2105 id: input.ask,2106 now,2107 policy,2108 row,2068 composed.commit,2069 input.ask,2070 now2071 );2109 });21102111 if (!decidesOn(policy, stated, caller.handle)) {2112 return yield* new NotDecider({});2113 }21142115 const ask: Ask = {2116 ...stated,2117 askedBy: caller.handle,2118 openedAt: now,
311 unmodified lines
24302431 return refusals;2432 });24332392 /** An answer given before for the same request, or for the same head while it stands. */2434 /**2435 * The receipt of an answer given before: the caller's own request2436 * again, or the same head from them while that answer stands. A2437 * request id another person's answer holds is not the caller's to2438 * replay, nor to take: `NotClaimed`.2439 */2440 const earlier = (2441 h: Hydrated,2442 caller: Person,2443 input: {2444 readonly ask: AskId;2445 readonly head: CommitSha;2446 readonly requestId: RequestId;2447 }2401 ) =>2402 Option.map(2403 Option.orElse(findAnswer(h, input.requestId), () =>2404 Option.fromUndefinedOr(2405 h.answers.find(2406 ({ record, row }) =>2407 row.ask === input.ask &&2408 row.head === input.head &&2409 sameHandle(row.answerer, caller.handle) &&2410 !LandingState.guards.Refused(record.landing)2411 )2448 ): Effect.Effect<Option.Option<AnswerReceipt>, NotClaimed> => {2449 const own = (row: AnswerRow) => sameHandle(row.answerer, caller.handle);2450 const same = findAnswer(h, input.requestId);24512452 if (Option.isSome(same) && !own(same.value.row)) {2453 return Effect.fail(NotClaimed.of(input.ask));2454 }24552456 const given = Option.orElse(same, () =>2457 Option.fromUndefinedOr(2458 h.answers.find(2459 ({ record, row }) =>2460 row.ask === input.ask &&2461 row.head === input.head &&2462 own(row) &&2463 !LandingState.guards.Refused(record.landing)2464 )2413 ),2414 ({ record }) => record.receipt2465 )2466 );24672468 return Effect.succeed(Option.map(given, ({ record }) => record.receipt));2469 };24702471 /** A new answer request, queued and started on main as it stands, with its receipt. */2472 const queueAnswer = (2473 writes: Writes,2474 request: Request,2421 input: { readonly main: LandedSha; readonly now: DateTime.Utc }2475 input: {2476 readonly ask: AskId;2477 readonly main: LandedSha;2478 readonly now: DateTime.Utc;2479 }2480 ) =>2481 Effect.gen(function* () {2482 const started = landingTransition(2483 LandingState.cases.Queued.make({ request }),
1 unmodified line
2485 input.now2486 );24872488 const receipt: AnswerReceipt = {2431 ask: Option.getOrThrow(request.ask),2489 ask: input.ask,2490 base: request.base,2491 head: request.head,2492 outcome: outcomeOf(started.state),2493 project: name,
26 unmodified lines
2520 }2521 ) =>2522 (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2523 Effect.gen(function* () {2466 const given = earlier(h, caller, input);2524 const given = yield* earlier(h, caller, input);25252526 if (Option.isSome(given)) {2527 return given.value;2528 }
74 unmodified lines
2603 head: input.head,2604 project: name,2605 requestId: input.requestId,2606 },2549 { main: live.value.landed, now }2607 { ask: input.ask, main: live.value.landed, now }2608 );2609 });26102611 /** Every live claim whose deadline passed, moved by `Tick`. */
203 unmodified lines
modified:packages/project/test/project.test.ts+128 added-6 removed
4 unmodified lines
5import { Verdict } from "@repo/protocol/domain/answer";6import type { Ask } from "@repo/protocol/domain/ask";7import { CheckSpec } from "@repo/protocol/domain/check";8import { ClaimView } from "@repo/protocol/domain/claim";9import { Glob } from "@repo/protocol/domain/common";10import { Outcome } from "@repo/protocol/domain/outcome";11import {12 AskId,13 LandedSha,
7 unmodified lines
21import { Anonymous, Person } from "@repo/protocol/principal";22import {23 AskFull,24 ClaimLapsed,25 DirectPush,26 ImportFailed,27 NotClaimed,28 NotDecider,29 NotRedFirst,30 OutOfScope,31 ProjectExists,
3 unmodified lines
35} from "@repo/protocol/refusal";36import { advanceTo, at as instant } from "@repo/testkit/clock";37import type { Files } from "@repo/testkit/git-client";38import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";36import { Array, DateTime, Effect, Exit, Layer, Option, Schema } from "effect";39import {40 Array,41 DateTime,42 Effect,43 Exit,44 Layer,45 Option,46 Result,47 Schema,48} from "effect";4950import { ScheduledAlarm } from "../src/alarms/memory.ts";51import { ProjectStore } from "../src/project-store.ts";52import type { ProjectApi } from "../src/project.ts";
9 unmodified lines
62 mergedAt,63 Pusher,64 worldOf,65} from "./world.ts";54import type { StoreKind } from "./world.ts";66import type { StoreKind, WorldScenario } from "./world.ts";6768const people = ["bob", "carol", "dave", "eve", "frank"];6970const scenario = aProject({ people }).pipe(
131 unmodified lines
202 discard: true,203 })204 );205194/** Opens an ask whose check the Checker fails twice the same way on the composed tree. */195const openRed = (api: ProjectApi, id: string) =>206/** `decider` opens an ask whose check the Checker fails twice the same way on the composed tree. */207const openRed = (api: ProjectApi, id: string, decider: Person = alice) =>208 Effect.gen(function* () {209 const files = askFiles(id);210 const composed = yield* composedAt(repo, yield* mainTip, files);211212 yield* CheckScript.use((checker) =>213 checker.script(composed, redThenGreen, ["failed", "failed"])214 );215204 return yield* api.openAsk(alice, { ask: AskId.make(id), files });216 return yield* api.openAsk(decider, { ask: AskId.make(id), files });217 });218219/** What each event is, in the order the project numbered them. */220const eventTags = (api: ProjectApi) =>
2 unmodified lines
223 );224225const scheduled = ScheduledAlarm.use(({ at }) => at);226227/** The project's state as its store keeps it, once it is made. */228const projectState = ProjectStore.use((store) => store.load()).pipe(229 Effect.map(({ project: row }) => Option.map(row, ({ state }) => state))230);231232const states = (api: ProjectApi, who: Person) =>233 Effect.map(api.status(who), ({ claims }) => claims.map(({ state }) => state));234235const outcomes = (api: ProjectApi, who: Person) =>
6 unmodified lines
242/** Steps 1 and 2: the project made, and its first ask opened. */243const opening = (api: ProjectApi) =>244 Effect.gen(function* () {245 const made = yield* Effect.exit(api.initProject(alice, {}));246 const awaiting = yield* projectState;247248 const first = yield* Pusher.use((pusher) =>249 pusher.push(repo, Option.none(), start, "Start")250 );251252 const notHers = yield* api.recordFirstPush(bob, first).pipe(Effect.flip);253 const recorded = yield* api.recordFirstPush(alice, first);254 const evaluated = yield* Evaluated.use(({ shas }) => shas);255 const opened = yield* openRed(api, "parse-iso");256 const greenFiles = askFiles("parse-green");
8 unmodified lines
265 const bobRefused = yield* api.openAsk(bob, green).pipe(Effect.flip);266267 return {268 asked: yield* commitOf(opened.landed),269 awaiting,270 bobRefused,271 evaluated,272 first,273 greenRefused,274 listed: yield* api.listAsks(anyone),275 made,276 mainAfterRefusals: yield* mainTip,277 notHers,278 opened,279 recorded,280 shown: yield* api.showAsk(anyone, parseIso),281 };
122 unmodified lines
404 Effect.map(events, (rows) => rows.map(({ event }) => event._tag))405 ),406 receipt,407 replay: yield* api.submitAnswer(bob, submission),408 replayByCarol: yield* Effect.result(api.submitAnswer(carol, submission)),409 requestId,410 roundTrip,411 status: yield* api.status(bob),412 tipAfterReplay: yield* mainTip,
217 unmodified lines
630 Effect.map(seen, ({ opened }) => {631 expect(opened.made).toStrictEqual(632 Exit.succeed({ project, remote: remoteOf(project) })633 );634 expect(opened.awaiting).toStrictEqual(635 Option.some("awaitingFirstPush")636 );637 expect(opened.notHers).toStrictEqual(638 new DirectPush({ ref: mainRef })639 );640 expect(opened.recorded).toStrictEqual({ landed: opened.first });641 expect(opened.evaluated).toStrictEqual([opened.first]);642 })643 );
202 unmodified lines
846 })847 );848849 it.effect(822 "6. the same request again gets the same receipt, and nothing lands twice",850 "6. the same request again gets the same receipt, and nothing lands twice; nobody else's request is theirs",851 () =>852 Effect.map(seen, ({ answered }) => {853 expect(answered.replay).toStrictEqual(answered.receipt);854 expect(answered.tipAfterReplay).toBe(answered.landed);855 expect(answered.replayByCarol).toStrictEqual(856 Result.fail(NotClaimed.of(parseIso))857 );858 })859 );860861 it.effect(
183 unmodified lines
1045 first: claimed.wideRefusals,1046 };1047});10481049/** An ask bob claimed, opened again by alice with the same files. */1050const reopening = Effect.gen(function* () {1051 yield* advanceTo("2026-10-07T12:00:00Z");10521053 const api = yield* projectService(project);1054 const { opened } = yield* opening(api);10551056 yield* api.claim(bob, parseIso);10571058 const before = yield* eventTags(api);1059 const again = yield* openRed(api, "parse-iso");10601061 return {1062 again,1063 events: [before, yield* eventTags(api)],1064 listed: yield* api.listAsks(anyone),1065 main: yield* mainTip,1066 opened,1067 };1068});10691070/** dave decides for `packages/format/**` only. */1071const narrowDecider: WorldScenario = {1072 policy: {1073 ...scenario.policy,1074 deciders: [1075 ...scenario.policy.deciders,1076 {1077 handles: Array.make(dave.handle),1078 paths: Glob.make("packages/format/**"),1079 },1080 ],1081 },1082};10831084/** dave opens an ask in the format package, and one in the parser. */1085const decidingNarrowly = Effect.gen(function* () {1086 yield* advanceTo("2026-10-07T12:00:00Z");10871088 const api = yield* projectService(project);10891090 yield* api.initProject(alice, {});10911092 const first = yield* Pusher.use((pusher) =>1093 pusher.push(repo, Option.none(), start, "Start")1094 );10951096 yield* api.recordFirstPush(alice, first);10971098 const outside = yield* Effect.result(openRed(api, "parse-iso", dave));1099 const inside = yield* Effect.result(openRed(api, "format-date", dave));11001101 return {1102 inside: Result.map(inside, ({ ask }) => [ask.id, ask.askedBy]),1103 outside,1104 };1105});11061107describe("opening an ask", () => {1108 it.effect(1109 "again, once it is claimed, answers with the ask as it stands and lands nothing",1110 () =>1111 Effect.map(1112 reopening.pipe(Effect.provide(worldOf(scenario, "memory"))),1113 ({ again, events, listed, main, opened }) => {1114 expect(again).toStrictEqual({1115 ask: { ...opened.ask, state: "claimed" },1116 landed: opened.landed,1117 });1118 expect(main).toBe(opened.landed);1119 expect(events[1]).toStrictEqual(events[0]);1120 expect(listed.asks.map(({ claimed }) => claimed)).toStrictEqual([1121 true,1122 ]);1123 }1124 )1125 );11261127 it.effect("is for a decider whose paths hold the ask's territory", () =>1128 Effect.map(1129 decidingNarrowly.pipe(Effect.provide(worldOf(narrowDecider, "memory"))),1130 ({ inside, outside }) => {1131 expect(outside).toStrictEqual(Result.fail(new NotDecider({})));1132 expect(inside).toStrictEqual(1133 Result.succeed([AskId.make("format-date"), dave.handle])1134 );1135 }1136 )1137 );1138});11391140describe("the project's outbox", () => {1141 it.effect(1142 "keeps a fork and a projection that failed, and the next alarm runs them again",1143 () =>
78 unmodified lines
modified:packages/project/test/world.ts+6 added-3 removed
47 unmodified lines
4849/** Where the project's store keeps its rows. */50export type StoreKind = "memory" | "sqlite";5152/** What a world reads from a scenario: the policy its rules evaluator returns. */53export type WorldScenario = Pick<Scenario, "policy">;5455/**56 * What the Checker answers, by `(tree or commit, lane)`: the test adds to57 * it as it learns the trees an answer will be checked on.58 */
45 unmodified lines
104 * A `RulesEvaluator` that evaluates nothing: at any commit it returns the105 * scenario's policy at that commit, holding the scenario's asks whose files106 * the commit's config folder has, and the judge closure `checks` derives.107 */105const rulesOf = (scenario: Scenario) =>108const rulesOf = (scenario: WorldScenario) =>109 Layer.effectContext(110 Effect.gen(function* () {111 const finishers = yield* Finishers;112 const seen = yield* Ref.make<readonly LandedSha[]>([]);
142 unmodified lines
255 })256);257258/** Every service the scenario test reads besides the project's ports. */256const fixtures = (scenario: Scenario) =>259const fixtures = (scenario: WorldScenario) =>260 Layer.mergeAll(scriptOf, rulesOf(scenario), pusher).pipe(261 Layer.provideMerge(FinishersFromChecks)262 );263
2 unmodified lines
266 * test reads back (the store, the alarm, the projection, the repos), built267 * fresh for each test.268 */269export const worldOf = (267 scenario: Scenario,270 scenario: WorldScenario,271 store: StoreKind,272 faults: Faults = {}273) =>274 Layer.mergeAll(
53 unmodified lines