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.
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
Provenance
- Commit
1e18284- Tree
29fa0d3- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
d048cb9
4 files changed+249 added−76 removed
modified:packages/project/src/facts.ts+13 added-23 removed
334 unmodified lines335 const 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 lines373 export 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+ };386 387+ return Effect.gen(function* () {388 const commit = yield* RepoHost.use((host) => host.readCommit(repo, at));389 390 if (Option.isNone(commit)) {391 return empty;41 unmodified lines433 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 lines124 Steps,125 } from "./answer-runs.ts";126 import type { AnswerQueue, AnswerRuns } from "./answer-runs.ts";127 import { isStep } from "./answer-runs/steps.ts";128+import { decidersFor } from "./attention/decisions.ts";129 import { recordOf, sameHandle } from "./attention/record.ts";130 import { mayClaim, standing } from "./attention/vouch.ts";131 import {132 ClaimCommand,16 unmodified lines149 outcomeOf,150 transition as landingTransition,151 } from "./landing.ts";152 import type { LandingQueue, Request } from "./landing.ts";152-import { isDue, outboxRow, OutboxBody, runOutbox, startRow } from "./outbox.ts";153+import {154+ isDue,155+ outboxRow,156+ OutboxBody,157+ projectedRows,158+ runOutbox,159+ startRow,160+} from "./outbox.ts";161 import { ProjectStore } from "./project-store.ts";162 import type { ProjectWrites } from "./project-store.ts";163 import type {164 AnswerRow,453 unmodified lines618 policy.deciders.some(({ handles }) =>619 handles.some((each) => sameHandle(each, handle))620 );621 622+/**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+ */627+const 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));632+633 /** A path a composed commit can hold: plain folder names and a file name. */634 const isPlainPath = (path: string) =>635 path636 .split("/")403 unmodified lines1040 return [];1041 }1042 1043 const events = yield* numbered(h.lastSeq, writes.events);1044+ const projected = yield* projectedRows(name, events, now);1045 1026- const projected = yield* Effect.forEach(events, (event) =>1027- outboxRow(1028- `projected:${event.seq}`,1029- OutboxBody.cases.Projected.make({ event, project: name }),1030- now1031- )1032- );1033-1046 const outbox = [...writes.outbox, ...projected];1047 1048 const queue = yield* Effect.forEach(writes.queue.values(), (each) =>1049 storedQueue(each)854 unmodified lines1904 1905 return { landed };1906 });1907 1896- /** 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;1922+1923 // 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+ );1930 1931 if (Option.isNone(evaluated)) {1932 return yield* new VerifierBlocked({});1933 }1934 1912- 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);1936 1937 if (stated === undefined) {1938 return yield* new IncompleteBrief({ missing: ["want"] });1939 }8 unmodified lines1948 if (Array.isReadonlyArrayNonEmpty(missing)) {1949 return yield* new IncompleteBrief({ missing });1950 }1951 1930- return { policy, stated };1952+ return stated;1953 });1954 1955 /** The judge an ask's files touch beyond their own (stage 1, as an ask opens). */1956 const touchedJudge = (input: {111 unmodified lines2068 if (Option.isNone(live) || Option.isNone(h.policy)) {2069 return yield* new VerifierBlocked({});2070 }2071 2072+ const policy = h.policy.value;2073+2050- if (!isDecider(h.policy.value, caller.handle)) {2074+ if (!isDecider(policy, caller.handle)) {2075 return yield* new NotDecider({});2076 }2077 2078+ // 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+ );2084+2085+ 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+ }2090+2091 const unplain = input.files.flatMap(({ path }) =>2092 isPlainPath(path) ? [] : [path]2093 );2094 4 unmodified lines2099 const { landed: main, row } = live.value;2100 const { files } = input;2101 const composed = yield* lander.compose({ files, main, repo });2102 2066- 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+ });2110 2111+ if (!decidesOn(policy, stated, caller.handle)) {2112+ return yield* new NotDecider({});2113+ }2114+2115 const ask: Ask = {2116 ...stated,2117 askedBy: caller.handle,2118 openedAt: now,311 unmodified lines2430 2431 return refusals;2432 });2433 2392- /** 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);2451+2452+ if (Option.isSome(same) && !own(same.value.row)) {2453+ return Effect.fail(NotClaimed.of(input.ask));2454+ }2455+2456+ 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 );2467 2468+ return Effect.succeed(Option.map(given, ({ record }) => record.receipt));2469+ };2470+2471 /** 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 line2485 input.now2486 );2487 2488 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 lines2520 }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);2525 2526 if (Option.isSome(given)) {2527 return given.value;2528 }74 unmodified lines2603 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 });2610 2611 /** Every live claim whose deadline passed, moved by `Tick`. */203 unmodified linesmodified:packages/project/test/project.test.ts+128 added-6 removed
4 unmodified lines5 import { Verdict } from "@repo/protocol/domain/answer";6 import type { Ask } from "@repo/protocol/domain/ask";7 import { CheckSpec } from "@repo/protocol/domain/check";8 import { ClaimView } from "@repo/protocol/domain/claim";9+import { Glob } from "@repo/protocol/domain/common";10 import { Outcome } from "@repo/protocol/domain/outcome";11 import {12 AskId,13 LandedSha,7 unmodified lines21 import { Anonymous, Person } from "@repo/protocol/principal";22 import {23 AskFull,24 ClaimLapsed,25+ DirectPush,26 ImportFailed,27+ NotClaimed,28 NotDecider,29 NotRedFirst,30 OutOfScope,31 ProjectExists,3 unmodified lines35 } from "@repo/protocol/refusal";36 import { advanceTo, at as instant } from "@repo/testkit/clock";37 import type { Files } from "@repo/testkit/git-client";38 import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";36-import { Array, DateTime, Effect, Exit, Layer, Option, Schema } from "effect";39+import {40+ Array,41+ DateTime,42+ Effect,43+ Exit,44+ Layer,45+ Option,46+ Result,47+ Schema,48+} from "effect";49 50 import { ScheduledAlarm } from "../src/alarms/memory.ts";51 import { ProjectStore } from "../src/project-store.ts";52 import type { ProjectApi } from "../src/project.ts";9 unmodified lines62 mergedAt,63 Pusher,64 worldOf,65 } from "./world.ts";54-import type { StoreKind } from "./world.ts";66+import type { StoreKind, WorldScenario } from "./world.ts";67 68 const people = ["bob", "carol", "dave", "eve", "frank"];69 70 const scenario = aProject({ people }).pipe(131 unmodified lines202 discard: true,203 })204 );205 194-/** Opens an ask whose check the Checker fails twice the same way on the composed tree. */195-const openRed = (api: ProjectApi, id: string) =>206+/** `decider` opens an ask whose check the Checker fails twice the same way on the composed tree. */207+const 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);211 212 yield* CheckScript.use((checker) =>213 checker.script(composed, redThenGreen, ["failed", "failed"])214 );215 204- return yield* api.openAsk(alice, { ask: AskId.make(id), files });216+ return yield* api.openAsk(decider, { ask: AskId.make(id), files });217 });218 219 /** What each event is, in the order the project numbered them. */220 const eventTags = (api: ProjectApi) =>2 unmodified lines223 );224 225 const scheduled = ScheduledAlarm.use(({ at }) => at);226 227+/** The project's state as its store keeps it, once it is made. */228+const projectState = ProjectStore.use((store) => store.load()).pipe(229+ Effect.map(({ project: row }) => Option.map(row, ({ state }) => state))230+);231+232 const states = (api: ProjectApi, who: Person) =>233 Effect.map(api.status(who), ({ claims }) => claims.map(({ state }) => state));234 235 const outcomes = (api: ProjectApi, who: Person) =>6 unmodified lines242 /** Steps 1 and 2: the project made, and its first ask opened. */243 const opening = (api: ProjectApi) =>244 Effect.gen(function* () {245 const made = yield* Effect.exit(api.initProject(alice, {}));246+ const awaiting = yield* projectState;247 248 const first = yield* Pusher.use((pusher) =>249 pusher.push(repo, Option.none(), start, "Start")250 );251 252+ 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 lines265 const bobRefused = yield* api.openAsk(bob, green).pipe(Effect.flip);266 267 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 lines404 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 lines630 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 lines846 })847 );848 849 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 );860 861 it.effect(183 unmodified lines1045 first: claimed.wideRefusals,1046 };1047 });1048 1049+/** An ask bob claimed, opened again by alice with the same files. */1050+const reopening = Effect.gen(function* () {1051+ yield* advanceTo("2026-10-07T12:00:00Z");1052+1053+ const api = yield* projectService(project);1054+ const { opened } = yield* opening(api);1055+1056+ yield* api.claim(bob, parseIso);1057+1058+ const before = yield* eventTags(api);1059+ const again = yield* openRed(api, "parse-iso");1060+1061+ return {1062+ again,1063+ events: [before, yield* eventTags(api)],1064+ listed: yield* api.listAsks(anyone),1065+ main: yield* mainTip,1066+ opened,1067+ };1068+});1069+1070+/** dave decides for `packages/format/**` only. */1071+const 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+};1083+1084+/** dave opens an ask in the format package, and one in the parser. */1085+const decidingNarrowly = Effect.gen(function* () {1086+ yield* advanceTo("2026-10-07T12:00:00Z");1087+1088+ const api = yield* projectService(project);1089+1090+ yield* api.initProject(alice, {});1091+1092+ const first = yield* Pusher.use((pusher) =>1093+ pusher.push(repo, Option.none(), start, "Start")1094+ );1095+1096+ yield* api.recordFirstPush(alice, first);1097+1098+ const outside = yield* Effect.result(openRed(api, "parse-iso", dave));1099+ const inside = yield* Effect.result(openRed(api, "format-date", dave));1100+1101+ return {1102+ inside: Result.map(inside, ({ ask }) => [ask.id, ask.askedBy]),1103+ outside,1104+ };1105+});1106+1107+describe("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+ );1126+1127+ 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+});1139+1140 describe("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 linesmodified:packages/project/test/world.ts+6 added-3 removed
47 unmodified lines48 49 /** Where the project's store keeps its rows. */50 export type StoreKind = "memory" | "sqlite";51 52+/** What a world reads from a scenario: the policy its rules evaluator returns. */53+export type WorldScenario = Pick<Scenario, "policy">;54+55 /**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 lines104 * 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 */105-const rulesOf = (scenario: Scenario) =>108+const 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 lines255 })256 );257 258 /** Every service the scenario test reads besides the project's ports. */256-const fixtures = (scenario: Scenario) =>259+const fixtures = (scenario: WorldScenario) =>260 Layer.mergeAll(scriptOf, rulesOf(scenario), pusher).pipe(261 Layer.provideMerge(FinishersFromChecks)262 );263 2 unmodified lines266 * test reads back (the store, the alarm, the projection, the repos), built267 * fresh for each test.268 */269 export const worldOf = (267- scenario: Scenario,270+ scenario: WorldScenario,271 store: StoreKind,272 faults: Faults = {}273 ) =>274 Layer.mergeAll(53 unmodified lines