Close W2: one handle rule, typed rule facts from the sdk, claim-fork pushes judged by the claim, and the open points the groups left folded in
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- protocol: Policy and PolicyInput counts are bounded (AtLeastOne, NoneOrMore in domain/common.ts; AskKind.race too), so a config's "-1 days" or a cap of 0 fails as RulesFailed{decode} (203 #22). sameHandle lives once in ids.ts: handles compare without case, as GitHub logins and claim forks do (213 #11, 220 #8). proposeAsk can refuse NotVouched; decide can refuse VerifierBlocked and StaleBase (213 #3, 221 #5), so the project's MethodSchemas stopgaps are gone. ConfigFile and LandReceipt moved into domain/ (215 #3). bun run gen rewrote protocol.schema.json. - rules: entry.ts reads function rules under the sdk's Functions symbol; RulesEvaluator.call takes RuleCall (opensAlone with ProposalFacts, admit with ClaimantFacts) and encodes the facts before the sandbox; finishPolicy writes the workspace's folder over the sdk's {dir} and its exports as public files (a module no workspace names keeps the placeholder and fails closed); defaultPolicyInput is the sdk's defaults, decoded, so the default numbers have one home; sdkVersion is re-exported for @repo/project (203 #5/#7/#8/#19, 204 #6, 212 #5). Behaviour change: the defaults' fix kind now requires a territory and adds no markers (the gate keeps its default list). - gate: parse no longer refuses NotVouched on a push to a claim's fork, because the claim already passed the kind's claimers rule (an anyone kind, a record, a mentor); a working fork still needs a vouch unless bansOnly. A denouncement on any vouch-file line wins, as the service reads it (220 #8, 206's open point). - project: decide, Today and the budget compare handles by sameHandle; ProjectEventInput has one home in src/events.ts (209 #3, 210 #3, 213 #10, 219 #6; AttentionEvent is gone); AnswerRow.state's doc names AnswerRecord (214 #3); the Lander and checkVersion read sdkVersion from @repo/rules/rules-evaluator. - artifacts: codes, numbers, import refusals, refOf, secondsOf and LOG_PAGE live once in src/repo-host/artifacts-api.ts for /binding and /rest (218 #4). The tests got an override with effect/http and the it.live case 208's Check asked for: a pushed file comes back from a real git clone through git http-backend. RepoHostLocal.temporaryRoot is gone for FileSystem.makeTempDirectoryScoped (208 #1, #2). - Root: tsconfig.base.json gives packages/artifacts/test its own override (effect/http, effect/process; a widening for tests only, pre-approved); turbo.json's test task lists UPDATE_GOLDEN under env, so it reaches vitest and a cached run can't stand in for a rewrite (211). - PROVENANCE.md: 204's mulberry32 row (public domain). AGENTS.md: the W2 fences now hold principles 3, 6, 7, 8 and 12 (the gate's shape test, the RepoHost contract suite, the rules replay test, the store contract, the two lifecycle model tests). - Tests added, each red by assertion first: PolicyInput bounds (10 rows) and the zero cases it keeps; sameHandle; decide, Today and the budget under another casing; three gate parse rows; a project written with the real sdk answering both rules through /bun; project({}) evaluating as no folder; finishPolicy filling {dir}; the contracts table's new errors. - Spot checks, each planted and removed: a module-level let in packages/project/src fails check (fence/no-module-level-mutable-state); node:fs in packages/gate/src fails typecheck (nodeBuiltinImport); Date.now() in packages/rules/src fails typecheck (globalDate); effect/Arbitrary in packages/gate/src fails typecheck (unstableApiUsage); @repo/testkit from packages/project/src fails imports:check (test-only). turbo run typecheck --dry=json: 13 packages, no cycle; testkit's only @repo deps are brand, protocol and the dev config. - No smoke tests remain. verify green: config 693, protocol 316, project 282, checks 166, artifacts 105 (+12 live, skipped), gate 105, testkit 48, rules 31, git 31, sdk 15, platform 12, brand 9, cli 4; debt 4/4; platform entry 770 KB of 900 KB. - Left for W3 and later, forwarded into each owning issue's Comments: the isogit Lander over /binding or /rest (isomorphic-git's push walks unchanged trees; 306, 311, 317), merge pushing nothing (304, 306, 314), Bearer vs Basic auth (311), an ask lane named like a project lane (417), one glob matcher (402), tools/list size (408).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
55 files+829 added−434 removed
- tests:+411 added−70 removed
- other:+418 added−364 removed
Provenance
- Commit
ec1d6f9- Tree
888d485- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
08d244c
55 files changed+829 added−434 removed
modified:docs/reference/protocol.schema.json+9 added
2547 unmodified lines2548 "$ref": "#/$defs/DecisionClosedEncoded"2549 },2550 {2551 "$ref": "#/$defs/NotDeciderEncoded"2552+ },2553+ {2554+ "$ref": "#/$defs/VerifierBlockedEncoded"2555+ },2556+ {2557+ "$ref": "#/$defs/StaleBaseEncoded"2558 }2559 ]2560 },2561 "decide.payload": {3701 unmodified lines6263 "$ref": "#/$defs/DenouncedEncoded"6264 },6265 {6266 "$ref": "#/$defs/CapReachedEncoded"6267+ },6268+ {6269+ "$ref": "#/$defs/NotVouchedEncoded"6270 }6271 ]6272 },6273 "proposeAsk.payload": {5390 unmodified linesadded:packages/artifacts/src/repo-host/artifacts-api.ts+86 added
1+/**2+ * What the two adapters over Artifacts share, the Workers binding's3+ * (`binding.ts`) and the REST API's (`rest.ts`): Artifacts' error codes and4+ * their numbers, the codes an import refuses a source with, how a revision5+ * is named, and the limits on a token's ttl and a log page. One table each,6+ * so the two adapters can't drift apart.7+ */8+import { Duration, Schema } from "effect";9+10+import { Revision } from "../repo-host.ts";11+12+/** Artifacts' names for its errors: `ArtifactsError.code` on the binding. */13+export const Code = Schema.Literals([14+ "ALREADY_EXISTS",15+ "NOT_FOUND",16+ "CREATE_IN_PROGRESS",17+ "IMPORT_IN_PROGRESS",18+ "FORK_IN_PROGRESS",19+ "INVALID_INPUT",20+ "INVALID_REPO_NAME",21+ "INVALID_TTL",22+ "INVALID_URL",23+ "REMOTE_AUTH_REQUIRED",24+ "UPSTREAM_UNAVAILABLE",25+ "MEMORY_LIMIT",26+ "INTERNAL_ERROR",27+]);28+29+export type Code = typeof Code.Type;30+31+export const isCode = Schema.is(Code);32+33+/**34+ * Each code by its number, from Artifacts' errors page: the REST API's35+ * `errors[].code`, and the binding's `numericCode`. The page gives36+ * `CREATE_IN_PROGRESS` no number.37+ */38+export const NUMBERED: ReadonlyMap<number, Code> = new Map<number, Code>([39+ [10_100, "INVALID_INPUT"],40+ [10_101, "INVALID_REPO_NAME"],41+ [10_103, "INVALID_TTL"],42+ [10_104, "INVALID_URL"],43+ [10_106, "REMOTE_AUTH_REQUIRED"],44+ [10_200, "NOT_FOUND"],45+ [10_201, "ALREADY_EXISTS"],46+ [10_302, "IMPORT_IN_PROGRESS"],47+ [10_303, "FORK_IN_PROGRESS"],48+ [10_400, "INTERNAL_ERROR"],49+ [10_401, "UPSTREAM_UNAVAILABLE"],50+ [10_402, "MEMORY_LIMIT"],51+]);52+53+/**54+ * The codes an import refuses its source with, as no repo to take: not git,55+ * not public, not reachable, or too big.56+ */57+export const NO_SOURCE = [58+ "INVALID_INPUT",59+ "INVALID_URL",60+ "MEMORY_LIMIT",61+ "NOT_FOUND",62+ "REMOTE_AUTH_REQUIRED",63+ "UPSTREAM_UNAVAILABLE",64+] as const satisfies readonly Code[];65+66+/** Artifacts' name for a revision: a short branch name or a commit id, never `refs/…` (S1 #20). */67+export const refOf = (at: Revision) =>68+ Revision.$match(at, {69+ Branch: ({ name }) => name,70+ Commit: ({ sha }) => sha,71+ });72+73+// Artifacts takes a token's ttl in whole seconds, from a minute to a year.74+const MIN_TTL_SECONDS = 60;75+76+const MAX_TTL_SECONDS = 31_536_000;77+78+/** A token's ttl as Artifacts takes it: whole seconds, clamped to a minute and a year. */79+export const secondsOf = (ttl: Duration.Duration) =>80+ Math.min(81+ Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),82+ MAX_TTL_SECONDS83+ );84+85+/** `log` reads at most this many commits per call. */86+export const LOG_PAGE = 1000;modified:packages/artifacts/src/repo-host/binding.ts+16 added-52 removed
35 unmodified lines36 RefName,37 RepoExists,38 RepoHost,39 RepoNotFound,40- Revision,40 TreeEntry,41 } from "../repo-host.ts";43-import type { RepoName, RepoToken, TokenScope } from "../repo-host.ts";42+import type {43+ RepoName,44+ RepoToken,45+ TokenScope,46+ Revision,47+} from "../repo-host.ts";48+import {49+ isCode,50+ LOG_PAGE,51+ NO_SOURCE,52+ refOf,53+ secondsOf,54+} from "./artifacts-api.ts";55+import type { Code } from "./artifacts-api.ts";56 import { listRefs, pushRefs } from "./smart-http.ts";57 46-const Code = Schema.Literals([47- "ALREADY_EXISTS",48- "NOT_FOUND",49- "CREATE_IN_PROGRESS",50- "IMPORT_IN_PROGRESS",51- "FORK_IN_PROGRESS",52- "INVALID_INPUT",53- "INVALID_REPO_NAME",54- "INVALID_TTL",55- "INVALID_URL",56- "REMOTE_AUTH_REQUIRED",57- "UPSTREAM_UNAVAILABLE",58- "MEMORY_LIMIT",59- "INTERNAL_ERROR",60-]);61-62-type Code = typeof Code.Type;63-64-const isCode = Schema.is(Code);65-58 /**59 * The codes a message names when the error carries none (S1 #22): Artifacts'60 * words, the fake's, and the code itself.61 */83 unmodified lines145 146 /** How long a token minted for one call lives; it is revoked after the call. */147 const CALL_TOKEN_TTL = Duration.minutes(5);148 157-// Artifacts takes a token's ttl in whole seconds, from a minute to a year.158-const MIN_TTL_SECONDS = 60;149+/** The codes `import` refuses a source with. */150+const IMPORT_REFUSALS: ReadonlySet<Code> = new Set(NO_SOURCE);151 160-const MAX_TTL_SECONDS = 31_536_000;161-162-const secondsOf = (ttl: Duration.Duration) =>163- Math.min(164- Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),165- MAX_TTL_SECONDS166- );167-168-/** `log` reads at most this many commits per call. */169-const LOG_PAGE = 1000;170-171-/** The codes `import` refuses a source with: not git, not public, not reachable, too big. */172-const IMPORT_REFUSALS: ReadonlySet<Code> = new Set([173- "INVALID_INPUT",174- "INVALID_URL",175- "MEMORY_LIMIT",176- "NOT_FOUND",177- "REMOTE_AUTH_REQUIRED",178- "UPSTREAM_UNAVAILABLE",179-]);180-181-/** The binding's name for a revision: never `refs/…` (S1 #20). */182-const refOf = (at: Revision) =>183- Revision.$match(at, {184- Branch: ({ name }) => name,185- Commit: ({ sha }) => sha,186- });187-152 const bytesOf = (blob: Blob) =>153 attempt(() => blob.arrayBuffer()).pipe(154 Effect.map((buffer) => new Uint8Array(buffer)),155 Effect.catchTag("Thrown", asDefect)364 unmodified linesmodified:packages/artifacts/src/repo-host/local.ts+1 added-14 removed
1 import * as fs from "node:fs";2-import { tmpdir } from "node:os";2 import { fileURLToPath } from "node:url";3 4 import type { CommitSha } from "@repo/protocol/ids";5 import {7 unmodified lines13 Schema,14 Semaphore,15 Stream,16 } from "effect";18-import type { Context, Scope } from "effect";17+import type { Context } from "effect";18 import {19 Errors,20 addRemote,21 currentBranch,513 unmodified lines535 readonly root: string;536 readonly remoteBase: string;537 }): Layer.Layer<RepoHost, never, Fetch> =>538 Layer.effect(RepoHost, make(options)),540- /**541- * A new, empty directory for a store, deleted with everything in it when542- * the scope closes: a root for callers with no file system of their own,543- * such as this package's tests.544- */545- temporaryRoot: Effect.acquireRelease(546- io(() => fs.promises.mkdtemp(`${tmpdir()}/repo-host-`)).pipe(Effect.orDie),547- (root) =>548- io(() => fs.promises.rm(root, { force: true, recursive: true })).pipe(549- Effect.orDie550- )551- ) satisfies Effect.Effect<string, never, Scope.Scope>,539 };modified:packages/artifacts/src/repo-host/rest.ts+15 added-68 removed
86 unmodified lines87 RefName,88 RepoExists,89 RepoHost,90 RepoNotFound,91- Revision,91 TreeEntry,92 } from "../repo-host.ts";94-import type { Commit, RepoName, RepoToken, TokenScope } from "../repo-host.ts";93+import type {94+ Commit,95+ RepoName,96+ RepoToken,97+ TokenScope,98+ Revision,99+} from "../repo-host.ts";100+import {101+ LOG_PAGE,102+ NO_SOURCE,103+ NUMBERED,104+ refOf,105+ secondsOf,106+} from "./artifacts-api.ts";107+import type { Code } from "./artifacts-api.ts";108 import { listRefs, pushRefs } from "./smart-http.ts";109 97-/** The binding's names for Artifacts' errors (`ArtifactsError.code`). */98-type Code =99- | "ALREADY_EXISTS"100- | "NOT_FOUND"101- | "CREATE_IN_PROGRESS"102- | "IMPORT_IN_PROGRESS"103- | "FORK_IN_PROGRESS"104- | "INVALID_INPUT"105- | "INVALID_REPO_NAME"106- | "INVALID_TTL"107- | "INVALID_URL"108- | "REMOTE_AUTH_REQUIRED"109- | "UPSTREAM_UNAVAILABLE"110- | "MEMORY_LIMIT"111- | "INTERNAL_ERROR";112-113-/**114- * Each REST `errors[].code` by the binding's name for it, from Artifacts'115- * errors page. The page gives `CREATE_IN_PROGRESS` no number.116- */117-const NUMBERED: ReadonlyMap<number, Code> = new Map<number, Code>([118- [10_100, "INVALID_INPUT"],119- [10_101, "INVALID_REPO_NAME"],120- [10_103, "INVALID_TTL"],121- [10_104, "INVALID_URL"],122- [10_106, "REMOTE_AUTH_REQUIRED"],123- [10_200, "NOT_FOUND"],124- [10_201, "ALREADY_EXISTS"],125- [10_302, "IMPORT_IN_PROGRESS"],126- [10_303, "FORK_IN_PROGRESS"],127- [10_400, "INTERNAL_ERROR"],128- [10_401, "UPSTREAM_UNAVAILABLE"],129- [10_402, "MEMORY_LIMIT"],130-]);131-110 /** A refusal that names no code at all, such as a proxy's, read by status. */111 const byStatus = (status: number): Option.Option<Code> =>112 Match.value(status).pipe(113 Match.when(404, () => Option.some<Code>("NOT_FOUND")),128 unmodified lines242 };243 })244 ).pipe(Effect.orDie);245 268-/** The API's name for a revision: a short branch name or a commit id (S1 #20). */269-const refOf = (at: Revision) =>270- Revision.$match(at, {271- Branch: ({ name }) => name,272- Commit: ({ sha }) => sha,273- });274-246 const repoPath = (name: RepoName) => `/repos/${encodeURIComponent(name)}`;247 248 const textOf = (response: Response) => Effect.promise(() => response.text());249 25 unmodified lines275 response.ok ? Effect.void : refusal(response);276 277 const main = RefName.make("refs/heads/main");278 308-/** `log` asks for at most this many commits per request, as the binding does. */309-const LOG_PAGE = 1000;310-311-// Artifacts takes a token's ttl in whole seconds, from a minute to a year.312-const MIN_TTL_SECONDS = 60;313-314-const MAX_TTL_SECONDS = 31_536_000;315-316-const secondsOf = (ttl: Duration.Duration) =>317- Math.min(318- Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),319- MAX_TTL_SECONDS320- );321-279 /** How long a token for git calls lives, and how near its expiry it is replaced. */280 const CALL_TOKEN_TTL = Duration.minutes(30);281 282 const CALL_TOKEN_MARGIN = Duration.minutes(5);22 unmodified lines305 keep: (value: V, key: K) => boolean306 ): ReadonlyMap<K, V> =>307 new Map([...map].filter(([key, value]) => keep(value, key)));308 352-/** The import refusals that say the source is no repo to take (the binding's). */353-const NO_SOURCE = [354- "INVALID_INPUT",355- "INVALID_URL",356- "MEMORY_LIMIT",357- "NOT_FOUND",358- "REMOTE_AUTH_REQUIRED",359- "UPSTREAM_UNAVAILABLE",360-] as const satisfies readonly Code[];361-309 /** A repo that exists but is still being made answers its info and mints 409. */310 const BEING_MADE = [311 "CREATE_IN_PROGRESS",312 "FORK_IN_PROGRESS",523 unmodified linesmodified:packages/artifacts/test/binding.test.ts+2 added-1 removed
39 unmodified lines40 import { RepoHostLocal } from "../src/repo-host/local.ts";41 import { memoryFs } from "../src/repo-host/memory-fs.ts";42 import { fetchInto, listRefs, pushRefs } from "../src/repo-host/smart-http.ts";43 import { describeRepoHost } from "./repo-host-contract.ts";44+import { temporaryRoot } from "./temporary-root.ts";45 46 const main = RefName.make("refs/heads/main");47 48 const landed = RefName.make("refs/asked/landed");34 unmodified lines83 const world = (84 options: FakeOptions & { readonly wrap?: (host: HostLike) => HostLike } = {}85 ) =>86 Effect.gen(function* () {86- const root = yield* RepoHostLocal.temporaryRoot;87+ const root = yield* temporaryRoot;88 89 const spawner =90 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();91 661 unmodified linesmodified:packages/artifacts/test/local.test.ts+79 added-6 removed
1+import { NodeHttpServer, NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3+import { gitOk } from "@repo/testkit/git";4 import { gitClient } from "@repo/testkit/git-client";3-import { Duration, Effect, Layer, Option } from "effect";5+import { httpBackend } from "@repo/testkit/http-backend";6+import { Context, Duration, Effect, FileSystem, Layer, Option } from "effect";7+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";8+import type { ChildProcessSpawner } from "effect/process";9 10 import { Fetch, FetchFailed } from "../src/fetch.ts";11 import {12 BranchName,4 unmodified lines17 } from "../src/repo-host.ts";18 import { RepoHostLocal } from "../src/repo-host/local.ts";19 import { memoryFs } from "../src/repo-host/memory-fs.ts";20 import { describeRepoHost } from "./repo-host-contract.ts";21+import { temporaryRoot } from "./temporary-root.ts";22 23 const main = RefName.make("refs/heads/main");24 25 /** No network: every request fails as an unreachable host's would. */11 unmodified lines37 Layer.provide(offline)38 );39 40 /** A store in a new temporary directory, removed when the test ends. */35-const freshStore = Layer.unwrap(36- Effect.map(RepoHostLocal.temporaryRoot, storeAt)37-);41+const freshStore = Layer.unwrap(Effect.map(temporaryRoot, storeAt));42 43+/** Real `git http-backend` over `root` on a local port: its base URL. */44+const served = (root: string) =>45+ Effect.gen(function* () {46+ const spawner =47+ yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();48+49+ const backend = httpBackend(root);50+51+ const app = Effect.gen(function* () {52+ const request = yield* HttpServerRequest.toWeb(53+ yield* HttpServerRequest.HttpServerRequest54+ );55+56+ return HttpServerResponse.fromWeb(57+ yield* Effect.scoped(backend(request)).pipe(Effect.provide(spawner))58+ );59+ }).pipe(Effect.orDie);60+61+ const server = yield* Layer.build(62+ HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))63+ ).pipe(Effect.orDie);64+65+ const { address } = Context.get(server, HttpServer.HttpServer);66+67+ return "port" in address68+ ? `http://127.0.0.1:${address.port}`69+ : yield* Effect.die("the test server listens on a socket, not a port");70+ });71+72 // Its test-only meaning of a public remote: another bare repo on disk, named73 // by its `file://` URL.74 describeRepoHost("local", freshStore, {75 importUrl: (name) =>76 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),77 });78 79 describe("bare repos on local disk", () => {80+ // The issue's Check: what the adapter stores is a repo real git can clone81+ // over smart HTTP, served by `git http-backend` from the same root.82+ it.live(83+ "serves a pushed file to a real git clone of its remote",84+ () =>85+ Effect.gen(function* () {86+ const fs = yield* FileSystem.FileSystem;87+ const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);88+ const work = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);89+ const client = yield* gitClient(memoryFs());90+ const first = yield* client.commit("first", [["src/a.ts", "v1\n"]]);91+ const name = RepoName.make("demo");92+93+ const remote = yield* RepoHost.use((repos) =>94+ Effect.gen(function* () {95+ yield* repos.create(name);96+ yield* repos.push(name, client.source, [97+ { from: Option.none(), ref: main, to: first },98+ ]);99+100+ return yield* repos.remote(name);101+ })102+ ).pipe(103+ Effect.provide(104+ RepoHostLocal.layer({105+ remoteBase: yield* served(root),106+ root,107+ }).pipe(Layer.provide(offline))108+ )109+ );110+111+ yield* gitOk(work, "clone", "--quiet", remote, "clone");112+113+ expect(114+ yield* fs.readFileString(`${work}/clone/src/a.ts`).pipe(Effect.orDie)115+ ).toBe("v1\n");116+ }).pipe(Effect.provide(NodeServices.layer)),117+ 30_000118+ );119+120 it.effect("names each repo's remote under the base it was given", () =>121 Effect.gen(function* () {49- const root = yield* RepoHostLocal.temporaryRoot;122+ const root = yield* temporaryRoot;123 const name = RepoName.make("demo");124 125 const remote = yield* RepoHost.use((repos) =>126 Effect.andThen(repos.create(name), repos.remote(name))13 unmodified lines140 it.effect(141 "keeps repos, refs and tokens for the next layer over the same root",142 () =>143 Effect.gen(function* () {71- const root = yield* RepoHostLocal.temporaryRoot;144+ const root = yield* temporaryRoot;145 const client = yield* gitClient(memoryFs());146 const first = yield* client.commit("first", [["a", "1"]]);147 const name = RepoName.make("kept");148 143 unmodified linesmodified:packages/artifacts/test/repo-host-contract.ts+4 added-2 removed
40 unmodified lines41 ) => Effect.Effect<string, never, RepoHost>;42 }43 44 /**45- * What every RepoHost adapter must do, written against the port. `/memory`46- * runs it on every `verify`; `/binding` runs it against live Artifacts.45+ * What every RepoHost adapter must do, written against the port. `/memory`,46+ * `/local`, `/binding` (over testkit's fake Artifacts on `/local`) and47+ * `/rest` (over a fake REST API on `/local`) run it on every `verify`;48+ * `binding-live.test.ts` runs it against live Artifacts when asked.49 */50 export const describeRepoHost = (51 adapter: string,52 host: Layer.Layer<RepoHost>,443 unmodified linesmodified:packages/artifacts/test/rest.test.ts+2 added-1 removed
36 unmodified lines37 import { RepoHostRest } from "../src/repo-host/rest.ts";38 import { fakeRest } from "./fake-rest.ts";39 import type { FakeRestOptions } from "./fake-rest.ts";40 import { describeRepoHost } from "./repo-host-contract.ts";41+import { temporaryRoot } from "./temporary-root.ts";42 43 const main = RefName.make("refs/heads/main");44 45 const accountId = "0123456789abcdef0123456789abcdef";42 unmodified lines88 const world = (89 options: Omit<FakeRestOptions, "accountId" | "namespace" | "token"> = {}90 ) =>91 Effect.gen(function* () {91- const root = yield* RepoHostLocal.temporaryRoot;92+ const root = yield* temporaryRoot;93 94 const spawner =95 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();96 602 unmodified linesadded:packages/artifacts/test/temporary-root.ts+12 added
1+import { NodeServices } from "@effect/platform-node";2+import { Effect, FileSystem } from "effect";3+4+/**5+ * A new temporary directory for a store's root, removed with its contents6+ * when the test's scope closes.7+ */8+export const temporaryRoot = FileSystem.FileSystem.pipe(9+ Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "repo-host-" })),10+ Effect.orDie,11+ Effect.provide(NodeServices.layer)12+);modified:packages/gate/src/stages/parse.ts+23 added-10 removed
2 unmodified lines3 * pusher, the policy and the claim, so it is free; the first rule a push4 * breaks is its one refusal.5 */6 import type { Policy } from "@repo/protocol/domain/policy";7+import { sameHandle } from "@repo/protocol/ids";8 import type { Handle } from "@repo/protocol/ids";9 import { Principal } from "@repo/protocol/principal";10 import {11 CapReached,13 unmodified lines25 import type { Stage } from "../stage.ts";26 27 type Rule = (facts: PushFacts) => Option.Option<Refusal>;28 28-/** Handles name one person however their sign-in provider cases them. */29-const sameHandle = (one: Handle, other: Handle) =>30- one.toLowerCase() === other.toLowerCase();31-29 const handleOf = (pusher: Principal): Option.Option<Handle> =>30 Principal.guards.Person(pusher) ? Option.some(pusher.handle) : Option.none();31 32 const isPusher = (facts: PushFacts, handle: Handle) =>33 Option.exists(handleOf(facts.pusher), (pusher) => sameHandle(pusher, handle));34 35 /**36 * Where a person stands by the vouch file: a line names them vouched or40- * denounced. Deciders vouch for others, so a decider with no line is vouched.37+ * denounced, and a denouncement on any line wins, as the project service38+ * reads the file (`attention/vouch.ts`). Deciders vouch for others, so a39+ * decider with no line is vouched.40 */41 const standingOf = (policy: Policy, handle: Handle) => {43- const line = policy.vouches.find((vouch) => sameHandle(vouch.handle, handle));42+ const lines = policy.vouches.filter((vouch) =>43+ sameHandle(vouch.handle, handle)44+ );45 45- if (line !== undefined) {46- return line.denounced ? "denounced" : "vouched";46+ if (lines.some(({ denounced }) => denounced)) {47+ return "denounced";48 }49 50+ if (lines.length > 0) {51+ return "vouched";52+ }53+54 const decides = policy.deciders.some((decider) =>55 decider.handles.some((each) => sameHandle(each, handle))56 );57 15 unmodified lines73 ? Option.none()74 : Option.some(new DirectPush({ ref: facts.ref })),75 });76 72-/** A denounced person pushes nothing; an unvouched one only when the mode says so. */77+/**78+ * A denounced person pushes nothing. An unvouched one pushes to a working79+ * fork (a sealed answer, a decider's own change) only when the mode says so.80+ * A push to a claim's fork is not judged on the vouch again: the claim81+ * already passed the kind's `claimers` rule, which may admit a person no one82+ * vouched for (an `anyone` kind, a record, a newcomer's mentor).83+ */84 const trust: Rule = (facts) =>85 Option.flatMap(handleOf(facts.pusher), (handle) => {86 const standing = standingOf(facts.policy, handle);87 88 if (standing === "denounced") {89 return Option.some<Refusal>(new Denounced({}));90 }91 81- return standing === "unknown" && facts.policy.vouch.mode !== "bansOnly"92+ return standing === "unknown" &&93+ facts.policy.vouch.mode !== "bansOnly" &&94+ !PushTarget.$is("ClaimFork")(facts.target)95 ? Option.some(new NotVouched({}))96 : Option.none();97 });98 60 unmodified linesmodified:packages/gate/test/parse.test.ts+34 added-5 removed
41 unmodified lines42 project: ask.project,43 }),44 });45 46+/** Dana's push to her own working fork (`<project>--me--dana`). */47+const danasWorkingForkPush = (mode: PushFacts["policy"]["vouch"]["mode"]) =>48+ testFacts({49+ ask: Option.none(),50+ claim: Option.none(),51+ policy: { ...policy, vouch: { ...policy.vouch, mode } },52+ pusher: Person.make({ handle: dana }),53+ target: PushTarget.WorkingFork({ owner: dana, project: ask.project }),54+ });55+56 const main = RefNameText.make("refs/heads/main");57 58 // Each row is one push; parse answers with at most one refusal, the first59 // rule the push breaks.48 unmodified lines108 facts: testFacts({ pusher: Person.make({ handle: mallory }) }),109 name: "a push by a denounced person",110 refusals: [new Denounced({})],111 },112+ // The claim already passed the kind's `claimers` rule (`mayClaim`), which113+ // may admit an unvouched person (an `anyone` kind, a record, a mentor), so114+ // a push to the claim's own fork does not judge the vouch again.115 {116 facts: danasPush("forCode"),104- name: "a push by an unvouched person when code needs a vouch",105- refusals: [new NotVouched({})],117+ name: "an unvouched claimant's push to their claim's fork when code needs a vouch",118+ refusals: [],119 },120 {121 facts: danasPush("all"),109- name: "a push by an unvouched person when everything needs a vouch",122+ name: "an unvouched claimant's push to their claim's fork when everything needs a vouch",123+ refusals: [],124+ },125+ {126+ facts: danasWorkingForkPush("forCode"),127+ name: "an unvouched person's push to their working fork when code needs a vouch",128 refusals: [new NotVouched({})],129 },130 {113- facts: danasPush("bansOnly"),114- name: "a push by an unvouched person when only denouncements count",131+ facts: danasWorkingForkPush("bansOnly"),132+ name: "an unvouched person's push to their working fork when only denouncements count",133 refusals: [],134 },135 {136 facts: testFacts({137+ policy: {138+ ...policy,139+ vouches: [{ denounced: false, handle: mallory }, ...policy.vouches],140+ },141 pusher: Person.make({ handle: mallory }),142+ }),143+ name: "a push by a person the vouch file both vouches for and denounces",144+ refusals: [new Denounced({})],145+ },146+ {147+ facts: testFacts({148+ pusher: Person.make({ handle: mallory }),149 target: PushTarget.Canonical({ project: ask.project }),150 }),151 name: "a push to canonical main, even by a denounced person",152 refusals: [new DirectPush({ ref: main })],84 unmodified linesmodified:packages/project/src/attention/budget.ts+2 added-1 removed
4 unmodified lines5 * counted apart, and a project can see where its deciders' time goes.6 */7 import type { Today } from "@repo/protocol/domain/decision";8 import type { Policy } from "@repo/protocol/domain/policy";9+import { sameHandle } from "@repo/protocol/ids";10 import type { Handle } from "@repo/protocol/ids";11 import { DateTime } from "effect";12 13 import type { BudgetDayRow } from "../project-store/rows.ts";14 unmodified lines28 ) => {29 const day = dayOf(now);30 31 return (31- days.find((row) => row.day === day && row.decider === decider) ?? {32+ days.find((row) => row.day === day && sameHandle(row.decider, decider)) ?? {33 day,34 decider,35 finishes: 0,36 used: 0,34 unmodified linesmodified:packages/project/src/attention/credits.ts+2 added-1 removed
9 unmodified lines10 */11 import type { Ask } from "@repo/protocol/domain/ask";12 import type { LandingView } from "@repo/protocol/domain/landing";13 import type { CreditSummary } from "@repo/protocol/domain/record";14+import { sameHandle } from "@repo/protocol/ids";15 import type { AskId, Handle } from "@repo/protocol/ids";16 import { Array as Arr, Option, Order } from "effect";17 17-import { areaOf, sameHandle } from "./record.ts";18+import { areaOf } from "./record.ts";19 20 /** What a person's credits are counted from. */21 export interface CreditsInput {22 /**63 unmodified linesmodified:packages/project/src/attention/decisions.ts+5 added-3 removed
7 unmodified lines8 import type { Evidence } from "@repo/protocol/domain/common";9 import { DecisionSubject } from "@repo/protocol/domain/decision";10 import type { Choice, Decision } from "@repo/protocol/domain/decision";11 import type { Policy } from "@repo/protocol/domain/policy";12+import { sameHandle } from "@repo/protocol/ids";13 import type {14 DecisionId,15 Handle,16 ProjectName,5 unmodified lines22 UnknownDecision,23 } from "@repo/protocol/refusal";24 import { Array as Arr, DateTime, Option, Result } from "effect";25 26+import { ProjectEventInput } from "../events.ts";25-import { AttentionEffect, AttentionEvent, platformHandle } from "./effects.ts";27+import { AttentionEffect, platformHandle } from "./effects.ts";28 29 /** How a subject's deciders say yes, and no. */30 interface Words {31 readonly no: Choice;87 unmodified lines119 decision: { ...decision, decided },120 effects: [121 ...consequences(decision.subject, worded),122 AttentionEffect.Emit({121- event: AttentionEvent.Decided({123+ event: ProjectEventInput.Decided({124 at: now,125 choice: worded,126 decision: decision.id,127 }),54 unmodified lines182 if (found === undefined) {183 return Result.fail(new UnknownDecision({ decision: input.id }));184 }185 184- if (!found.deciders.includes(input.by)) {186+ if (!found.deciders.some((each) => sameHandle(each, input.by))) {187 return Result.fail(new NotDecider({}));188 }189 190 if (isClosed(found, input.now)) {56 unmodified linesmodified:packages/project/src/attention/effects.ts+1 added-4 removed
10 unmodified lines11 import type { CommitSha, ProposalId } from "@repo/protocol/ids";12 import { Data } from "effect";13 import type { DateTime } from "effect";14 15-import type { ProjectEventInput } from "../project-store/rows.ts";15+import type { ProjectEventInput } from "../events.ts";16 17 /** What the project service does after a proposal or decision moved, in order. */18 export type AttentionEffect = Data.TaggedEnum<{19 /** Tell the project's watchers. */9 unmodified lines29 30 /** Constructors for attention's effects. */31 export const AttentionEffect = Data.taggedEnum<AttentionEffect>();32 33-/** Constructors for the project events attention emits, before the store numbers them. */34-export const AttentionEvent = Data.taggedEnum<ProjectEventInput>();35-33 /**34 * The platform's own handle: who `decided.by` names when nobody decided in35 * time and a decision took its default.36 */1 unmodified linemodified:packages/project/src/attention/proposals.ts+6 added-2 removed
21 unmodified lines22 import type { Person } from "@repo/protocol/principal";23 import { CapReached, Denounced, NotVouched } from "@repo/protocol/refusal";24 import { Data, DateTime, Option, Result } from "effect";25 26-import { AttentionEffect, AttentionEvent } from "./effects.ts";26+import { ProjectEventInput } from "../events.ts";27+import { AttentionEffect } from "./effects.ts";28 29 /**30 * What every proposal command carries: the id the service minted, the31 * project, the person proposing, and what the service knows about them that132 unmodified lines164 const opened = (proposal: Proposal, now: DateTime.Utc): Proposed => ({165 effects: [166 AttentionEffect.SetAlarm({ at: proposal.expiresAt }),167 AttentionEffect.Emit({167- event: AttentionEvent.ProposalOpened({ at: now, proposal: proposal.id }),168+ event: ProjectEventInput.ProposalOpened({169+ at: now,170+ proposal: proposal.id,171+ }),172 }),173 ],174 proposal,175 });57 unmodified linesmodified:packages/project/src/attention/record.ts+1 added-8 removed
47 unmodified lines48 readonly area: string;49 readonly atLeast: number;50 }51 52-/**53- * A handle as people are told apart: without case, as the sign-in provider54- * (GitHub) tells them apart, and as claim forks already name them.55- */52+/** A handle as a map key: the form `sameHandle` (`@repo/protocol/ids`) compares by. */53 const personOf = (handle: Handle) => handle.toLowerCase();54 58-/** Whether two handles name one person: a vouch file's `Alice` is `alice`. */59-export const sameHandle = (one: Handle, other: Handle): boolean =>60- personOf(one) === personOf(other);61-55 /**56 * A landing's area: the module of the territory its ask was in. A landing57 * that answered no ask (a decider's own, the first adoption), or whose ask58 * is not known in its project, has none.86 unmodified linesmodified:packages/project/src/attention/today.ts+2 added-1 removed
6 unmodified lines7 */8 import type { CreditRole } from "@repo/protocol/domain/credit";9 import type { Decision, Today } from "@repo/protocol/domain/decision";10 import type { LandingView } from "@repo/protocol/domain/landing";11+import { sameHandle } from "@repo/protocol/ids";12 import type { Handle } from "@repo/protocol/ids";13 import { Array as Arr, DateTime, Order } from "effect";14 15 import type { Budget } from "./budget.ts";61 unmodified lines77 const theirs = Arr.sort(78 input.decisions.filter(79 (decision) =>80 decision.decided === undefined &&80- decision.deciders.includes(decider) &&81+ decision.deciders.some((each) => sameHandle(each, decider)) &&82 DateTime.isLessThan(now, decision.expiresAt)83 ),84 byExpiry85 );25 unmodified linesmodified:packages/project/src/attention/vouch.ts+2 added-1 removed
13 unmodified lines14 */15 import type { Ask } from "@repo/protocol/domain/ask";16 import type { AskKind, ClaimRule } from "@repo/protocol/domain/kind";17 import type { Policy } from "@repo/protocol/domain/policy";18+import { sameHandle } from "@repo/protocol/ids";19 import type { Handle } from "@repo/protocol/ids";20 import { Denounced, NotVouched } from "@repo/protocol/refusal";21 import { Array as Arr, DateTime, Match, Option, Order, Result } from "effect";22 22-import { meets, sameHandle } from "./record.ts";23+import { meets } from "./record.ts";24 import type { RecordEntry } from "./record.ts";25 26 /** Where a person stands with a project: vouched for, denounced, or neither. */27 export type Standing = "vouched" | "denounced" | "unknown";170 unmodified linesmodified:packages/project/src/lander/isogit.ts+1 added-7 removed
42 unmodified lines43 import type { Verdict } from "@repo/protocol/domain/answer";44 import { CommitSha, LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";45 import type { RepoName, RequestId } from "@repo/protocol/ids";46 import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";47+import { sdkVersion } from "@repo/rules/rules-evaluator";48 import type { ConfigBundle } from "@repo/rules/rules-evaluator";49 import { Array, Clock, DateTime, Effect, Layer, Option, Order } from "effect";50 import {51 Errors,19 unmodified lines71 const mainRef = RefName.make("refs/heads/main");72 73 const mainBranch = BranchName.make("main");74 74-/**75- * The SDK version a bundle reports. ASSUMPTION: the platform's own, `0.0.0`76- * until release. `@repo/project` may not import `@repo/sdk`, which states it,77- * so 299 decides where this comes from (212's Comments).78- */79-const sdkVersion = "0.0.0";80-75 // How far back from main's tip a second land looks for the first one's commit.76 const LOOKBACK = 16;77 78 // git's test for a binary file: a NUL among its first bytes.911 unmodified linesmodified:packages/project/src/project-store/rows.ts+6 added-10 removed
53 unmodified lines54 export type ClaimRow = typeof ClaimRow.Type;55 56 /**57 * One answer request, keyed by its `requestId` so a request sent twice is58- * one row; its landing lifecycle state encoded.58+ * one row; where it stands, encoded.59 */60 export const AnswerRow = Schema.Struct({61 answerer: Handle,62 ask: Schema.optionalKey(AskId),63 head: CommitSha,64 requestId: RequestId,65- /** The encoded landing lifecycle state. */65+ /**66+ * The service's `AnswerRecord` (`src/project.ts`), encoded: the landing67+ * lifecycle's state, the receipt the request was first given, and the68+ * verdict on its last checked tree. The store keeps it as one JSON value.69+ */70 state: Schema.Json,71 updatedAt: Schema.DateTimeUtcFromString,72 });73 70 unmodified lines144 seq: Schema.Int,145 });146 147 export type EventRow = typeof EventRow.Type;144-145-/** Drops a key from each member of a union, not from the union as a whole. */146-type OmitEach<Union, Key extends PropertyKey> = Union extends unknown147- ? Omit<Union, Key>148- : never;149-150-/** An event before the store numbers it: every `ProjectEvent` but its `seq`. */151-export type ProjectEventInput = OmitEach<ProjectEvent, "seq">;modified:packages/project/src/claim.ts+2 added-12 removed
3 unmodified lines4 * 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";8 import type { Policy } from "@repo/protocol/domain/policy";9 import {10 AskId,11 CommitSha,13 unmodified lines25 NotVouched,26 } from "@repo/protocol/refusal";27 import { Array as Arr, Data, DateTime, Option, Result, Schema } from "effect";28 29+import { ProjectEventInput } from "./events.ts";30+31 /** What a claim holds while it lasts, and keeps once it ends. */32 const claimFields = {33 ask: AskId,34 /** Main's landed commit when the claim was made. */31 unmodified lines66 67 /** A claim's fields, which `Live` and `Warned` hold and the ended states keep. */68 export type Live = Omit<typeof ClaimState.cases.Live.Type, "_tag">;69 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-70 /**71 * What can happen to a claim. `Claim` carries what the project service knows72 * and the lifecycle does not: how many claims the person holds (`heldByWho`)73 * against their `cap`, how many others hold a live claim on the ask391 unmodified linesmodified:packages/project/src/deciders.ts+6 added-12 removed
22 unmodified lines23 import type { CheckRunner } from "@repo/checks/check-runner";24 import { pushStages, runGate } from "@repo/gate/gate";25 import { scan } from "@repo/gate/stages/shape";26 import { formatLanding } from "@repo/git/trailers";27-import type { AnswerReceipt } from "@repo/protocol/domain/answer";27+import type { AnswerReceipt, LandReceipt } from "@repo/protocol/domain/answer";28 import type { Ask } from "@repo/protocol/domain/ask";29 import type { Evidence } from "@repo/protocol/domain/common";30 import type { Credit } from "@repo/protocol/domain/credit";31 import { DecisionSubject } from "@repo/protocol/domain/decision";14 unmodified lines46 RepoName,47 RepoPath,48 RequestId,49 TreeSha,50+ sameHandle,51 } from "@repo/protocol/ids";52 import type { CommitSha, ProjectName, Handle } from "@repo/protocol/ids";53 import { Person } from "@repo/protocol/principal";54 import type { Principal } from "@repo/protocol/principal";43 unmodified lines98 expireDecisions,99 openDecision,100 } from "./attention/decisions.ts";101 import type { Decided } from "./attention/decisions.ts";102+import { AttentionEffect, platformHandle } from "./attention/effects.ts";103 import {102- AttentionEffect,103- AttentionEvent,104- platformHandle,105-} from "./attention/effects.ts";106-import {104 expire as expireProposals,105 propose,106 ProposalCommand,107 } from "./attention/proposals.ts";108 import type { Proposed } from "./attention/proposals.ts";112-import { recordOf, sameHandle } from "./attention/record.ts";109+import { recordOf } from "./attention/record.ts";110 import { today } from "./attention/today.ts";111 import { standing } from "./attention/vouch.ts";112 import { ClaimState } from "./claim.ts";113+import { ProjectEventInput } from "./events.ts";114 import { pushFacts } from "./facts.ts";115 import { Lander, Rebuild } from "./lander.ts";116 import type { ComposedFile } from "./lander.ts";117 import {9 unmodified lines127 AnswerRow,128 BudgetDayRow,129 ClaimRow,130 OutboxRow,133- ProjectEventInput,131 ProjectRow,132 } from "./project-store/rows.ts";133 134 /**2 unmodified lines137 * table that holds the method keys it by this constant.138 */139 export const envSchemaMethod = "envShape";140 144-/** What a decider's land returns: an answer's receipt, without an ask. */145-export type LandReceipt = Omit<AnswerReceipt, "ask">;146-141 /** The decider-facing methods of one project's service (spec §3.2's decider rows). */142 export interface DeciderApi {143 /**144 * The project's env shape: the items its landed `.env.schema` declares,646 unmodified lines791 now: DateTime.Utc792 ) =>793 Effect.gen(function* () {794 writes.landings.push(landing);801- writes.events.push(AttentionEvent.Landed({ at: now, landing }));795+ writes.events.push(ProjectEventInput.Landed({ at: now, landing }));796 797 const row = rowNow(h, writes);798 799 if (Option.isSome(row)) {1339 unmodified linesmodified:packages/project/src/events.ts+19 added-6 removed
3 unmodified lines4 * the rows that made them, and each one also goes to the projection through5 * the outbox, so the front page hears every one.6 */7 import type { Ask, AskListing } from "@repo/protocol/domain/ask";8+import type { ProjectEvent as Event } from "@repo/protocol/domain/event";9 import { ProjectEvent } from "@repo/protocol/domain/event";10 import type { Outcome } from "@repo/protocol/domain/outcome";11 import type { AskId, CommitSha, LandedSha } from "@repo/protocol/ids";11-import { Effect, Schema } from "effect";12+import { Data, Effect, Schema } from "effect";13 import type { DateTime } from "effect";14 14-import { ProjectEventInput as EventInput } from "./claim.ts";15-import type { ProjectEventInput } from "./project-store/rows.ts";15+/** Drops a key from each member of a union, not from the union as a whole. */16+type OmitEach<Union, Key extends PropertyKey> = Union extends unknown17+ ? Omit<Union, Key>18+ : never;19 20+/**21+ * A project event before the store numbers it: every `ProjectEvent` but its22+ * `seq`, which the store assigns at commit. The one type the lifecycles,23+ * attention, the service and the store all write events as.24+ */25+export type ProjectEventInput = OmitEach<Event, "seq">;26+27+/** Constructors and matchers for project events before the store numbers them. */28+export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();29+30 /** An ask as `listAsks`, the front page and `AskOpened` show it. */31 export const listingOf = (ask: Ask): AskListing => {32 const listing = {33 ask: ask.id,10 unmodified lines44 };45 46 /** An ask opened. */47 export const askOpened = (ask: Ask, at: DateTime.Utc): ProjectEventInput =>35- EventInput.AskOpened({ ask: listingOf(ask), at });48+ ProjectEventInput.AskOpened({ ask: listingOf(ask), at });49 50 /** An answer's landing closed its ask. */51 export const askClosed = (52 ask: AskId,53 landing: LandedSha,54 at: DateTime.Utc42-): ProjectEventInput => EventInput.AskClosed({ ask, at, landing });55+): ProjectEventInput => ProjectEventInput.AskClosed({ ask, at, landing });56 57 /** An answer was judged: its checks or its merge decided where it stands. */58 export const judged = (59 ask: AskId,60 head: CommitSha,61 outcome: Outcome,62 at: DateTime.Utc50-): ProjectEventInput => EventInput.Judged({ ask, at, head, outcome });63+): ProjectEventInput => ProjectEventInput.Judged({ ask, at, head, outcome });64 65 const asEvent = Schema.decodeUnknownEffect(Schema.toType(ProjectEvent));66 67 /**11 unmodified linesmodified:packages/project/src/landing.ts+2 added-8 removed
7 unmodified lines8 import { AgentTrailer, Credit } from "@repo/protocol/domain/credit";9 import type { CreditRole } from "@repo/protocol/domain/credit";10 import type { Choice } from "@repo/protocol/domain/decision";11 import { DecisionSubject } from "@repo/protocol/domain/decision";12-import type { ProjectEvent } from "@repo/protocol/domain/event";12 import { AskKind } from "@repo/protocol/domain/kind";13 import { LandingView } from "@repo/protocol/domain/landing";14 import { Outcome } from "@repo/protocol/domain/outcome";15 import {16 unmodified lines32 Weakened,33 } from "@repo/protocol/refusal";34 import { Array, Data, DateTime, Duration, Match, Option, Schema } from "effect";35 36+import { ProjectEventInput } from "./events.ts";37+38 /** How many times a moved main may send an answer back to merge before it is refused as stale. */39 export const maxRemerges = 3;40 41 /**136 unmodified lines178 }>;179 180 export const LandingCommand = Data.taggedEnum<LandingCommand>();181 181-type WithoutSeq<E> = E extends ProjectEvent ? Omit<E, "seq"> : never;182-183-/** A project event before the store gives it its place in the sequence. */184-export type ProjectEventInput = WithoutSeq<ProjectEvent>;185-186-export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();187-182 /** What the service runs for a landing: the transition only describes it. */183 export type LandingEffect = Data.TaggedEnum<{184 Merge: {185 readonly base: CommitSha;394 unmodified linesmodified:packages/project/src/project-store.ts+1 added-1 removed
1 import type { CommitSha } from "@repo/protocol/ids";2 import { Context } from "effect";3 import type { Effect, Option, Schema } from "effect";4 5+import type { ProjectEventInput } from "./events.ts";6 import type {7 AnswerRow,8 AskRow,9 BudgetDayRow,1 unmodified line11 DecisionRow,12 EventRow,13 LandingRow,14 OutboxRow,14- ProjectEventInput,15 ProjectRow,16 ProposalRow,17 PushEventRow,18 RatchetRow,95 unmodified linesmodified:packages/project/src/project.ts+7 added-19 removed
79 unmodified lines80 LandedSha,81 RepoName,82 RepoPath,83 RequestId,84+ sameHandle,85 } from "@repo/protocol/ids";86 import type {87 DecisionId,88 LaneName,8 unmodified lines97 IncompleteBrief,98 NotClaimed,99 NotDecider,100 NotRedFirst,100- NotVouched,101 ProjectExists,102 Refusal,103 StaleBase,104 TouchedJudge,11 unmodified lines116 PrivatePathInPublicTree,117 ReachedInternals,118 RepoBusy,119 Weakened,120+ NotVouched,121 } from "@repo/protocol/refusal";122 import { Finishers } from "@repo/rules/finish";122-import { RulesEvaluator } from "@repo/rules/rules-evaluator";123+import { RulesEvaluator, sdkVersion } from "@repo/rules/rules-evaluator";124 import {125 Array,126 Context,127 DateTime,18 unmodified lines146 Steps,147 } from "./answer-runs.ts";148 import type { AnswerQueue, AnswerRuns } from "./answer-runs.ts";149 import { isStep } from "./answer-runs/steps.ts";149-import { recordOf, sameHandle } from "./attention/record.ts";150+import { recordOf } from "./attention/record.ts";151 import { mayClaim, standing } from "./attention/vouch.ts";152 import {153 ClaimCommand,154 ClaimEffect,11 unmodified lines166 isDecider,167 } from "./deciders.ts";168 import type { DeciderApi, Opening } from "./deciders.ts";169 import { askClosed, askOpened, judged, listingOf, numbered } from "./events.ts";170+import type { ProjectEventInput } from "./events.ts";171 import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";172 import type { MissingCommit } from "./facts.ts";173 import { Lander, Rebuild } from "./lander.ts";174 import type { ComposedFile } from "./lander.ts";19 unmodified lines194 AnswerRow,195 BudgetDayRow,196 ClaimRow,197 OutboxRow,196- ProjectEventInput,198 ProjectRow,199 PushEventRow,200 } from "./project-store/rows.ts";201 import type { Projection } from "./projection.ts";19 unmodified lines221 defaultValue: () => `https://${Brand.domain}`,222 });223 224 /**224- * The SDK version a check's version is keyed by. ASSUMPTION: the platform's225- * own, `0.0.0` until release, as the isogit Lander reports it (212's226- * Comments); 299 decides where both come from.227- */228-const sdkVersion = "0.0.0";229-230-/**225 * The rules evaluator's finishers from `@repo/checks`: the run-block finder226 * and the judge closure (spec §4.2 `rules`, which may not import `checks`).227 * Every rules evaluator adapter needs it beside the project's ports.228 */180 unmodified lines409 args: [Principal, Handle],410 error: Schema.Never,411 success: Credits.successSchema,412 },419- // The contract leaves out what waiting lifts: an accepted proposal whose420- // ask meets a blocked Checker or a moved main decides nothing and fails421- // with it, so the decider can decide again. 221's Comments ask 299 to add422- // both.413 decide: {414 args: [Person, Decide.payloadSchema.mapFields(Struct.omit(["project"]))],425- error: Schema.Union([Decide.errorSchema, VerifierBlocked, StaleBase]),415+ error: Decide.errorSchema,416 success: Decide.successSchema,417 },418 events: {419 args: [Schema.Int, Schema.Int],53 unmodified lines473 ],474 error: OpenAsk.errorSchema,475 success: OpenAsk.successSchema,476 },487- // The contract leaves `NotVouched` out; a project whose vouch mode is488- // `all` gives it (213's `propose`). 221's Comments ask 299 to add it.477 proposeAsk: {478 args: [479 Person,480 ProposeAsk.payloadSchema.mapFields(Struct.omit(["project"])),481 ],494- error: Schema.Union([ProposeAsk.errorSchema, NotVouched]),482+ error: ProposeAsk.errorSchema,483 success: ProposeAsk.successSchema,484 },485 recordFirstPush: {486 args: [Person, CommitSha],2520 unmodified linesmodified:packages/project/test/attention/decisions.test.ts+16 added-8 removed
31 unmodified lines32 openDecision,33 } from "../../src/attention/decisions.ts";34 import {35 AttentionEffect,36- AttentionEvent,36 platformHandle,37 } from "../../src/attention/effects.ts";38+import { ProjectEventInput } from "../../src/events.ts";39 40 const scenario = aProject({ deciders: ["alice", "dana"], people: ["bob"] });41 42 const alice = Handle.make("alice");153 unmodified lines196 },197 effects: [198 AttentionEffect.OpenAsk({ proposal }),199 AttentionEffect.Emit({200- event: AttentionEvent.Decided({200+ event: ProjectEventInput.Decided({201 at: later,202 choice: "accept",203 decision: proposalDecision.id,204 }),8 unmodified lines213 Result.map(choose(proposalDecision, "decline"), ({ effects }) => effects)214 ).toStrictEqual(215 Result.succeed([216 AttentionEffect.Emit({217- event: AttentionEvent.Decided({217+ event: ProjectEventInput.Decided({218 at: later,219 choice: "decline",220 decision: proposalDecision.id,221 }),8 unmodified lines230 ).toStrictEqual(231 Result.succeed([232 AttentionEffect.Revert({ ref: main, to: before }),233 AttentionEffect.Emit({234- event: AttentionEvent.Decided({234+ event: ProjectEventInput.Decided({235 at: later,236 choice: "revert",237 decision: strayPush.id,238 }),8 unmodified lines247 ).toStrictEqual(248 Result.succeed([249 AttentionEffect.Land({ subject: strayPush.subject }),250 AttentionEffect.Emit({251- event: AttentionEvent.Decided({251+ event: ProjectEventInput.Decided({252 at: later,253 choice: "adopt",254 decision: strayPush.id,255 }),15 unmodified lines271 Result.succeed("decline"),272 ]);273 });274 275+ // One rule for handles everywhere (`sameHandle`): the policy's `alice` is276+ // the person GitHub signs in as `Alice`.277+ it("takes a decision from its decider however sign-in cases the handle", () => {278+ expect(279+ Result.isSuccess(choose(proposalDecision, "accept", Handle.make("Alice")))280+ ).toBeTruthy();281+ });282+283 it("refuses a person who does not decide for it", () => {284 expect(choose(proposalDecision, "accept", bob)).toStrictEqual(285 Result.fail(new NotDecider({}))286 );83 unmodified lines370 ]);371 372 expect(effects).toStrictEqual([373 AttentionEffect.Emit({366- event: AttentionEvent.Decided({374+ event: ProjectEventInput.Decided({375 at: due,376 choice: "decline",377 decision: proposalDecision.id,378 }),379 }),380 AttentionEffect.Revert({ ref: main, to: before }),381 AttentionEffect.Emit({374- event: AttentionEvent.Decided({382+ event: ProjectEventInput.Decided({383 at: due,384 choice: "revert",385 decision: strayPush.id,386 }),19 unmodified lines406 ],407 effects: [408 AttentionEffect.Revert({ ref: main, to: before }),409 AttentionEffect.Emit({402- event: AttentionEvent.Decided({410+ event: ProjectEventInput.Decided({411 at: due,412 choice: "revert",413 decision: strayPush.id,414 }),44 unmodified linesmodified:packages/project/test/attention/proposals.test.ts+3 added-5 removed
6 unmodified lines7 import { at } from "@repo/testkit/clock";8 import { aProject, ids, sha, withAsk } from "@repo/testkit/scenarios";9 import { DateTime, Option, Result } from "effect";10 11+import { AttentionEffect } from "../../src/attention/effects.ts";12 import {12- AttentionEffect,13- AttentionEvent,14-} from "../../src/attention/effects.ts";15-import {13 expire,14 ProposalCommand,15 propose,16 } from "../../src/attention/proposals.ts";17+import { ProjectEventInput } from "../../src/events.ts";18 19 const scenario = aProject({ people: ["carol"] }).pipe(20 withAsk({ id: "parse-iso", territory: "packages/parser" })21 );62 unmodified lines84 Result.succeed({85 effects: [86 AttentionEffect.SetAlarm({ at: at("2026-10-21T12:00:00Z") }),87 AttentionEffect.Emit({90- event: AttentionEvent.ProposalOpened({88+ event: ProjectEventInput.ProposalOpened({89 at: now,90 proposal: command.id,91 }),92 }),181 unmodified linesmodified:packages/project/test/attention/today.test.ts+14 added
90 unmodified lines91 expect(page.budget).toStrictEqual(fresh);92 expect(page.decider).toBe(alice);93 });94 95+ it("shows a decider their decisions however sign-in cases the handle", () => {96+ const page = todayFor({ decider: handle("ALICE"), decisions: eight });97+98+ expect(page.decisions).toStrictEqual([p1, p2, p3, p4, p5]);99+ });100+101 it("shows only what is left of the budget once some of it is used", () => {102 const page = todayFor({103 budget: { finishes: 0, total: 5, used: 2 },104 decisions: eight,196 unmodified lines301 used: 2,302 });303 });304 305+ it("counts what a decider spent under any casing of their handle", () => {306+ const days = spendAll([{ decider: alice, now: thursday, on: "decision" }]);307+308+ expect(309+ budgetFor(scenario.policy, handle("Alice"), days, thursday).used310+ ).toBe(1);311+ });312+313 it("counts a finish apart from the decisions", () => {314 const days = spendAll([315 { decider: alice, now: thursday, on: "finish" },316 { decider: alice, now: thursday, on: "decision" },33 unmodified linesmodified:packages/project/test/claim.test.ts+1 added-1 removed
23 unmodified lines24 ClaimCommand,25 ClaimEffect,26 ClaimState,27 forkName,28- ProjectEventInput,28 toView,29 transition,30 } from "../src/claim.ts";31+import { ProjectEventInput } from "../src/events.ts";32 33 const { Claim, Land, Push, Release, Tick } = ClaimCommand.cases;34 35 const HOUR = 3_600_000;419 unmodified linesmodified:packages/project/test/landing.model.test.ts+1 added-1 removed
26 unmodified lines27 Result,28 Schema,29 } from "effect";30 31+import { ProjectEventInput } from "../src/events.ts";32 import {33 enqueue,34 LandingCommand,35 LandingEffect,36 LandingQueue,37 LandingState,38 maxRemerges,39 next as admitNext,39- ProjectEventInput,40 Request,41 settle,42 transition,43 } from "../src/landing.ts";765 unmodified linesmodified:packages/project/test/landing.test.ts+1 added-1 removed
21 unmodified lines22 Weakened,23 } from "@repo/protocol/refusal";24 import { DateTime, Duration, Option, Schema } from "effect";25 26+import { ProjectEventInput } from "../src/events.ts";27 import {28 backoff,29 enqueue,30 LandingCommand,3 unmodified lines34 maxRemerges,35 next as admitNext,36 outcomeOf,37 pendingEffects,37- ProjectEventInput,38 Request,39 settle,40 transition,41 } from "../src/landing.ts";722 unmodified linesmodified:packages/project/test/project-store.contract.ts+1 added-1 removed
10 unmodified lines11 } from "@repo/protocol/ids";12 import { DateTime, Effect, Exit, Option, Schema, Struct } from "effect";13 import type { Layer } from "effect";14 15+import type { ProjectEventInput } from "../src/events.ts";16 import { ProjectStore } from "../src/project-store.ts";17 import type { ProjectWrites } from "../src/project-store.ts";18 import {19 AnswerRow,7 unmodified lines27 ProposalRow,28 PushEventRow,29 RatchetRow,30 } from "../src/project-store/rows.ts";30-import type { ProjectEventInput } from "../src/project-store/rows.ts";31 32 // Rows are written here encoded, as the store keeps them, and decoded once;33 // a snapshot is compared encoded, so every field reads back as written.34 539 unmodified linesmodified:packages/protocol/src/domain/answer.ts+9 added-1 removed
1-import { Schema } from "effect";1+import { Schema, Struct } from "effect";2 3 import {4 AreaName,5 AskId,83 unmodified lines89 });90 91 export type AnswerReceipt = typeof AnswerReceipt.Type;92 93+/**94+ * What a decider gets back on landing their own change from their working95+ * fork: an answer's receipt without an ask, since such a landing answers none.96+ */97+export const LandReceipt = AnswerReceipt.mapFields(Struct.omit(["ask"]));98+99+export type LandReceipt = typeof LandReceipt.Type;100+101 /** One of a person's answers, as their status shows it. */102 export const AnswerView = Schema.Struct({103 ask: AskId,104 at: Schema.DateTimeUtcFromString,6 unmodified linesmodified:packages/protocol/src/domain/common.ts+18 added-1 removed
67 unmodified lines68 });69 70 export type Evidence = typeof Evidence.Type;71 72+/**73+ * One file an ask or a proposal adds to the config folder: its path and its74+ * text, as `openAsk` and `proposeAsk` carry them.75+ */76+export const ConfigFile = Schema.Struct({77+ content: Schema.String,78+ path: RepoPath,79+});80+81+export type ConfigFile = typeof ConfigFile.Type;82+83+/** A count or span that must hold at least one: a cap, a budget, a race, a window. */84+export const AtLeastOne = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));85+86+/** A count or span that may be zero but never less: a record's count, a delay. */87+export const NoneOrMore = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));88+89 /** Where in the tree something points, when it points at one line. */90 export const At = Schema.Struct({74- line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),91+ line: AtLeastOne,92 path: RepoPath,93 });94 95 export type At = typeof At.Type;modified:packages/protocol/src/domain/kind.ts+3 added-2 removed
1 import { Schema } from "effect";2 3 import { Handle, KindName } from "../ids.ts";4 import { Strength } from "./check.ts";5+import { AtLeastOne, NoneOrMore } from "./common.ts";6 7 /** A field of an ask's brief that its kind can require. */8 export const BriefField = Schema.Literals([9 "want",24 unmodified lines34 */35 export const ClaimRule = Schema.Union([36 Schema.Literals(["vouched", "anyone"]),37 Schema.Struct({37- record: Schema.Struct({ area: Schema.NonEmptyString, atLeast: Schema.Int }),38+ record: Schema.Struct({ area: Schema.NonEmptyString, atLeast: NoneOrMore }),39 }),40 Schema.Struct({ newcomer: Schema.Struct({ mentor: Handle }) }),41 ]);42 12 unmodified lines55 name: KindName,56 /** Answers can't be undone by a later answer: judge changes and dependency changes. */57 oneWay: Schema.Boolean,58 /** How many claims an ask takes at once; 1 is exclusive (ADR 0008). */58- race: Schema.Int,59+ race: AtLeastOne,60 /** The brief's fields an ask of this kind must have. */61 requires: Schema.Array(BriefField),62 strength: Strength,63 });2 unmodified linesmodified:packages/protocol/src/domain/policy.ts+11 added-9 removed
2 unmodified lines3 4 import { Handle, LandedSha, RepoPath } from "../ids.ts";5 import { Ask } from "./ask.ts";6 import { RatchetSpec } from "./check.ts";7-import { Glob } from "./common.ts";7+import { AtLeastOne, Glob, NoneOrMore } from "./common.ts";8 import { AskKind } from "./kind.ts";9 import { RunBlock } from "./run.ts";10 import { Territory } from "./territory.ts";11 1 unmodified line13 const Source = Schema.Literals(["config", "defaults"]);14 15 /** How many decisions a decider takes a day, and how long one waits before its default. */16 const Budget = Schema.Struct({17- decisionsPerDay: Schema.Int,18- expireDays: Schema.Int,17+ decisionsPerDay: AtLeastOne,18+ expireDays: AtLeastOne,19 });20 21 /** How many proposals and claims one person may hold open at once. */22 const Caps = Schema.Struct({23- claimsPerPerson: Schema.Int,24- proposalsPerPerson: Schema.Int,23+ claimsPerPerson: AtLeastOne,24+ /** `0` turns proposals off. */25+ proposalsPerPerson: NoneOrMore,26 });27 28 /** How long a claim may go without a push before it is warned, and before it lapses. */29 const Claims = Schema.Struct({29- lapseAfterMs: Schema.Int,30- warnAfterMs: Schema.Int,30+ lapseAfterMs: AtLeastOne,31+ warnAfterMs: AtLeastOne,32 });33 34 /** When a landing starts to count on a person's record, and how long it counts. */35 const RecordWindow = Schema.Struct({36+ /** `0` counts a landing from the day it lands. */35- countsAfterDays: Schema.Int,36- windowDays: Schema.Int,37+ countsAfterDays: NoneOrMore,38+ windowDays: AtLeastOne,39 });40 41 /**42 * What a vouch gates: claims and sealed answers (`forCode`), everything139 unmodified linesmodified:packages/protocol/src/contracts.ts+16 added-16 removed
1-import { Context, Schema, Struct } from "effect";1+import { Context, Schema } from "effect";2 import { Rpc, RpcGroup, RpcSchema } from "effect/rpc";3 import type { RpcClient, RpcClientError } from "effect/rpc";4 5 import {7 unmodified lines13 SurfaceName,14 Surfaces,15 Visibility,16 } from "./annotations.ts";17-import { AnswerReceipt, AnswerView, Verdict } from "./domain/answer.ts";17+import {18+ AnswerReceipt,19+ AnswerView,20+ LandReceipt,21+ Verdict,22+} from "./domain/answer.ts";23 import { Ask, AskListing, Reserve } from "./domain/ask.ts";24 import { ClaimView } from "./domain/claim.ts";25+import { ConfigFile } from "./domain/common.ts";26 import { Choice, Decision, Today } from "./domain/decision.ts";27 import { EnvSchemaView } from "./domain/env.ts";28 import { ProjectEvent } from "./domain/event.ts";29 import { FrontPageEntry, ProjectListing } from "./domain/front-page.ts";10 unmodified lines40 KindName,41 LandedSha,42 ProjectName,43 RepoName,38- RepoPath,44 RequestId,45 } from "./ids.ts";46 import { Authenticated } from "./principal.ts";47 import {89 unmodified lines137 * input needs; this is the form `Tool.EmptyParams` takes.138 */139 const NoPayload = Schema.Record(Schema.String, Schema.Never);140 136-/**137- * One file an ask or a proposal adds to the config folder: its path and its138- * text.139- */140-const ConfigFile = Schema.Struct({ content: Schema.String, path: RepoPath });141-142-/**143- * What a decider gets back on landing their own change: the request, and144- * where it stands. An answer's receipt, without an ask.145- */146-const LandReceipt = AnswerReceipt.mapFields(Struct.omit(["ask"]));147-141 // --- Reads ------------------------------------------------------------------142 143 export class ListProjects extends Rpc.make("listProjects", {144 payload: NoPayload,293 unmodified lines438 .annotate(Cli, { name: "ask open" })439 .annotate(Surfaces, servedOn.openAsk) {}440 441 export class ProposeAsk extends Rpc.make("proposeAsk", {442+ // `NotVouched` under the `all` mode, or for a sealed answer from someone443+ // unvouched under `forCode` (a vouch admits sealed answers).449- error: Schema.Union([UnknownProject, Denounced, CapReached]),444+ error: Schema.Union([UnknownProject, Denounced, CapReached, NotVouched]),445 payload: {446 files: Schema.optionalKey(Schema.NonEmptyArray(ConfigFile)),447 project: ProjectName,448 /** A sealed answer: the commit in the caller's working fork that answers it. */43 unmodified lines492 UnknownProject,493 UnknownDecision,494 DecisionClosed,495 NotDecider,496+ // Accepting a proposal opens its ask, red first on main: a blocked497+ // Checker or a main that moved fails the call, and the decider can498+ // accept again.499+ VerifierBlocked,500+ StaleBase,501 ]),502 payload: {503 choice: Choice,504 decision: DecisionId,325 unmodified linesmodified:packages/protocol/src/ids.ts+9 added
237 unmodified lines238 Schema.brand("Handle")239 );240 241 export type Handle = typeof Handle.Type;242+243+/**244+ * Whether two handles name one person: without case, as the sign-in provider245+ * (GitHub) tells logins apart and as claim forks name them, so a vouch246+ * file's or a policy's `Alice` is the person signed in as `alice`. The one247+ * rule every package compares handles by.248+ */249+export const sameHandle = (one: Handle, other: Handle): boolean =>250+ one.toLowerCase() === other.toLowerCase();modified:packages/protocol/test/contracts.test.ts+3 added-1 removed
157 unmodified lines158 },159 {160 audience: "signedIn",161 cli: "propose",162- errors: ["UnknownProject", "Denounced", "CapReached"],162+ errors: ["UnknownProject", "Denounced", "CapReached", "NotVouched"],163 flags: "",164 on: "RMCW",165 tag: "proposeAsk",166 },12 unmodified lines179 "UnknownProject",180 "UnknownDecision",181 "DecisionClosed",182 "NotDecider",183+ "VerifierBlocked",184+ "StaleBase",185 ],186 flags: "A",187 on: "RMCW",188 tag: "decide",323 unmodified linesmodified:packages/protocol/test/domain.test.ts+44 added
41 unmodified lines42 RepoName,43 RequestId,44 SuiteRoot,45 TreeSha,46+ sameHandle,47 } from "../src/ids.ts";48 import { Anonymous, Person, Principal } from "../src/principal.ts";49 import wire from "./fixtures/domain.json" with { type: "json" };50 123 unmodified lines174 record: { countsAfterDays: 30, windowDays: 365 },175 vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },176 });177 });178+179+ // A span the config folder writes as `"-1 days"` is a valid string to the180+ // sdk; the policy is where a count or a span that can't hold is refused.181+ const [kind] = wire.withoutDefaults.kinds;182+183+ it.each([184+ ["budget", { budget: { decisionsPerDay: 0, expireDays: 14 } }],185+ ["budget", { budget: { decisionsPerDay: 5, expireDays: -1 } }],186+ ["caps", { caps: { claimsPerPerson: 0, proposalsPerPerson: 2 } }],187+ ["caps", { caps: { claimsPerPerson: 3, proposalsPerPerson: -1 } }],188+ ["claims", { claims: { lapseAfterMs: 0, warnAfterMs: 7_200_000 } }],189+ ["claims", { claims: { lapseAfterMs: 86_400_000, warnAfterMs: -1 } }],190+ ["record", { record: { countsAfterDays: -1, windowDays: 365 } }],191+ ["record", { record: { countsAfterDays: 30, windowDays: 0 } }],192+ ["a kind's race", { kinds: [{ ...kind, race: 0 }] }],193+ [194+ "a kind's record rule",195+ {196+ kinds: [{ ...kind, claimers: { record: { area: "x", atLeast: -1 } } }],197+ },198+ ],199+ ] as const)("refuse %s below what can hold", (_name, change) => {200+ expect(201+ refuses(PolicyInput, { ...wire.withoutDefaults, ...change })202+ ).toBeTruthy();203+ });204+205+ it("let a project turn proposals off and count a landing at once", () => {206+ expect(207+ refuses(PolicyInput, {208+ ...wire.withoutDefaults,209+ caps: { claimsPerPerson: 1, proposalsPerPerson: 0 },210+ record: { countsAfterDays: 0, windowDays: 1 },211+ })212+ ).toBeFalsy();213+ });214 });215 216 describe("names and ids", () => {217+ // GitHub tells logins apart without case, and claim forks lowercase them,218+ // so a vouch file's or a policy's `Alice` is the person signed in as `alice`.219+ it("tell two handles apart without case, as sign-in does", () => {220+ expect(sameHandle(Handle.make("Alice"), Handle.make("alice"))).toBeTruthy();221+ expect(sameHandle(Handle.make("alice"), Handle.make("alicia"))).toBeFalsy();222+ });223+224 it.each(["a--b", "-a", "a-", "A", "a_b", ""])(225 "a project or an ask may not be named %j",226 (name) => {227 expect(refuses(ProjectName, name)).toBeTruthy();61 unmodified linesmodified:packages/rules/src/rules-evaluator/bun.ts+13 added-9 removed
19 unmodified lines20 statedWithoutCode,21 } from "../config-folder.ts";22 import { defaultPolicyInput } from "../defaults.ts";23 import { Finishers, finishPolicy } from "../finish.ts";24-import { RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";24+import { factsOf, RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";25 import type { ConfigBundle } from "../rules-evaluator.ts";26 import { bunMain } from "./bun-main.ts";27 import { bunPrelude, clockVariable } from "./bun-prelude.ts";28 271 unmodified lines300 })301 );302 303 return RulesEvaluator.of({304- call: ({ facts, modules, rule }) => {304+ call: (input) => {305+ const { modules, rule } = input;306 const project = projectModule(modules);307 308 if (project === undefined) {309 return Effect.succeed(false);310 }311 312+ return factsOf(input).pipe(313+ Effect.flatMap((facts) =>311- return limited(312- run(modules, epoch, (written) => ({313- ...modulesOf(written, project, []),314- facts,315- rule,316- }))317- ).pipe(314+ limited(315+ run(modules, epoch, (written) => ({316+ ...modulesOf(written, project, []),317+ facts,318+ rule,319+ }))320+ )321+ ),322 Effect.flatMap(323 Output.match({324 Called: ({ result }) =>325 Schema.decodeUnknownEffect(Schema.Boolean)(result).pipe(62 unmodified linesmodified:packages/rules/src/defaults.ts+14 added-56 removed
1-import { FromCI, PolicyInput } from "@repo/protocol/domain/policy";1+import { PolicyInput } from "@repo/protocol/domain/policy";2+import { defaults, toPolicyInput } from "@repo/sdk";3 import { Schema } from "effect";4 4-// The Effect language service reads its directive's name anywhere in a5-// source, string literals included, so the marker is joined at run time.6-const effectDirective = ["@effect", "diagnostics"].join("-");7-5 /**9- * The markers that disable a check when an answer adds them (spec §4.210- * `packages/gate`); a project may add its own.11- */12-const weakeningMarkers = [13- ".skip(",14- ".only(",15- ".todo(",16- "eslint-disable",17- "oxlint-disable",18- "biome-ignore",19- "@ts-ignore",20- "@ts-expect-error",21- "@ts-nocheck",22- effectDirective,23- "# noqa",24- "# type: ignore",25- "#[allow(",26- "//nolint",27- "istanbul ignore",28- "c8 ignore",29-];30-31-/**6 * The policy a project with no config folder runs on (convex-merged design33- * §3, "no folder means defaults"): one `fix` kind whose asks a vouched person34- * claims, the run block found in the project's CI, the initializer deciding35- * everything (spec D20), and the default weakening markers. The rest is36- * `PolicyInput`'s own defaults: five decisions a day that wait 14 days, two37- * proposals and three claims per person, a claim warned after 2 hours and38- * lapsed after 24, a vouch for code in the config folder's `vouched.td`,39- * `Assisted-by` trailers, and a record that counts after 30 days for a year.7+ * §3, "no folder means defaults"): the sdk's own `defaults`, decoded, so the8+ * default kinds and numbers have one home each. One `fix` kind whose asks a9+ * vouched person claims, the run block found in the project's CI, and the10+ * initializer deciding everything (spec D20); the rest is `PolicyInput`'s11+ * own defaults: five decisions a day that wait 14 days, two proposals and12+ * three claims per person, a claim warned after 2 hours and lapsed after 24,13+ * a vouch for code in the config folder's `vouched.td`, `Assisted-by`14+ * trailers, and a record that counts after 30 days for a year. It adds no15+ * weakening markers: the gate scans its own defaults plus a project's.16 */41-export const defaultPolicyInput: PolicyInput = Schema.decodeSync(PolicyInput)({42- asks: [],43- deciders: [{ handles: "owners", paths: "**" }],44- functions: { admit: false, opensAlone: false },45- kinds: [46- {47- checkKind: "redThenGreen",48- claimers: "vouched",49- finish: "optional",50- name: "fix",51- oneWay: false,52- race: 1,53- requires: ["want", "check"],54- strength: "assertion",55- },56- ],57- ratchets: [],58- run: FromCI.make({}),59- source: "defaults",60- weakening: { markers: weakeningMarkers },61-});17+export const defaultPolicyInput: PolicyInput = Schema.decodeSync(PolicyInput)(18+ toPolicyInput(defaults)19+);modified:packages/rules/src/entry.ts+18 added-12 removed
1 unmodified line2 * The evaluator's side inside the sandbox (a `bun` subprocess here, a Dynamic3 * Worker in W3): it hands what the config folder's modules exported back as4 * data, which the sandbox's main sends as JSON, so functions and5 * non-enumerable properties drop out and the host decodes the rest; and it6- * finds a function-valued rule to call. It imports only `effect`, which the7- * sdk brings anyway, so a bundler can inline it beside the sdk.6+ * finds a function-valued rule to call. It imports only `effect` and the7+ * sdk's `Functions` key, which config code brings anyway, so a bundler can8+ * inline it beside the sdk.9 */10+import { Functions } from "@repo/sdk/functions";11 import { Predicate } from "effect";12 import type { Schema } from "effect";13 14 /**15 * What a config module's default export is: the sdk's definition, plain14- * data shaped as `PolicyInput` or `AskInput` once encoded. A function-valued15- * rule rides on the project's definition as an own property named after the16- * rule (`opensAlone`, `admit`) that JSON leaves out: the sdk makes it17- * non-enumerable, and `functions` in the data says it exists.16+ * data shaped as `PolicyInput` or `AskInput` once encoded. Its17+ * function-valued rules (`opensAlone`, `admit`) ride under the sdk's18+ * `Functions` symbol, which JSON never meets, and `functions` in the data19+ * says which exist.20 */21 export type Definition = Schema.Json;22 23 /** A function-valued rule: called with the facts its caller passes. */34 unmodified lines58 };59 60 const isRule = (value: unknown): value is Rule => Predicate.isFunction(value);61 60-/** The project definition's function-valued rule, when it has one. */62+/**63+ * The project definition's function-valued rule, when it has one: read64+ * where the sdk keeps it (`functionsOf`), under its `Functions` symbol.65+ */66 export const ruleOf = (67 definition: Definition | undefined,68 rule: string69 ): Rule | undefined => {65- if (definition === undefined || definition === null) {70+ if (!Predicate.hasProperty(definition, Functions)) {71 return undefined;72 }73 69- const found: unknown = Object.getOwnPropertyDescriptor(70- definition,71- rule72- )?.value;74+ const carried = definition[Functions];75 76+ const found = Predicate.hasProperty(carried, rule)77+ ? carried[rule]78+ : undefined;79+80 return isRule(found) ? found : undefined;81 };modified:packages/rules/src/finish.ts+42 added-3 removed
1 unmodified line2 import { FromCI, Policy } from "@repo/protocol/domain/policy";3 import type { PolicyInput } from "@repo/protocol/domain/policy";4 import { RunBlock } from "@repo/protocol/domain/run";5 import type { LandedSha, RepoPath } from "@repo/protocol/ids";6+import { packageDir } from "@repo/sdk";6-import { Context, DateTime, Effect, Schema } from "effect";7+import { Array as Arr, Context, DateTime, Effect, Schema } from "effect";8 9 import { failedAt } from "./config-folder.ts";10 import { RulesFailed } from "./rules-evaluator.ts";11 import type { EvaluationFacts } from "./rules-evaluator.ts";117 unmodified lines129 ? { module: name, paths }130 : { module: name, paths, publicFiles: exports };131 });132 133+/** A glob with the package's folder written over the sdk's `{dir}`. */134+const placed = (glob: string, folder: string) => {135+ const written = glob.replaceAll(packageDir, folder).replace(/^\/+/u, "");136+137+ return written === "" ? "**" : written;138+};139+140+/**141+ * An ask's territory with its package's folder written in. The sdk's142+ * `territory.package(name)` can't know where the package lives, so it names143+ * the workspace by `module` and writes `{dir}` in its paths; here the144+ * workspace's folder replaces it, and its `exports` become the public files145+ * unless the ask states its own. A module no workspace names keeps the146+ * placeholder, which matches no real path, so the gate refuses every change147+ * (it fails closed).148+ */149+const placedIn = (150+ workspaces: EvaluationFacts["workspaces"],151+ territory: PolicyInput["asks"][number]["territory"]152+) => {153+ const workspace = workspaces.find(({ name }) => name === territory.module);154+155+ if (156+ workspace === undefined ||157+ !territory.paths.some((glob) => glob.includes(packageDir))158+ ) {159+ return territory;160+ }161+162+ const folder = folderOf(workspace.dir);163+ const paths = Arr.map(territory.paths, (glob) => placed(glob, folder));164+165+ return territory.publicFiles !== undefined || workspace.exports.length === 0166+ ? { ...territory, paths }167+ : { ...territory, paths, publicFiles: workspace.exports };168+};169+170 /** Fails when two asks share an id: an id names one ask, and one fork per claim. */171 const distinctAsks = (asks: PolicyInput["asks"]) => {172 const seen = new Map<string, string>();173 17 unmodified lines191 192 /**193 * Turns what the config folder evaluated to into the project's `Policy` at194 * `at`, filling in what the platform knows from the facts: the run block157- * (`fromCI` resolved by the finder), the modules from the workspaces, the158- * judge closure, `owners` as the initializer (spec D20), and the vouch195+ * (`fromCI` resolved by the finder), the modules from the workspaces, each196+ * package territory's folder (the sdk's `{dir}`), the judge closure, `owners` as the initializer (spec D20), and the vouch197 * file's lines. Each ask counts as open, opened at `facts.now` in `at`: the198 * Project DO overwrites `openedAt`, `openedIn` and `state` from its own rows.199 * The whole is decoded with `Policy`, so a value the finishers or facts got200 * wrong fails here as `RulesFailed`, not later.20 unmodified lines221 openedAt,222 openedIn: at,223 project: facts.project,224 state: "open" as const,225+ territory: placedIn(facts.workspaces, ask.territory),226 })),227 at,228 budget: policy.budget,229 caps: policy.caps,22 unmodified linesmodified:packages/rules/src/rules-evaluator.ts+36 added-8 removed
1 import type { Policy } from "@repo/protocol/domain/policy";2 import type { LandedSha } from "@repo/protocol/ids";3 import { Handle, ProjectName, RepoPath } from "@repo/protocol/ids";4-import { Context, Schema } from "effect";5-import type { Effect } from "effect";4+import { ClaimantFacts, ProposalFacts } from "@repo/sdk/functions";5+import { Context, Effect, Schema } from "effect";6 7 /**8 * The config folder as it stood at one landed commit, ready to evaluate.9 * `modules` maps each file's repo path (`<folder>/project.ts`,13 unmodified lines23 });24 25 export type ConfigBundle = typeof ConfigBundle.Type;26 27+/**28+ * The version of the rules the platform runs, the sdk's own: what a bundle29+ * the platform makes reports, and part of every check version. Callers that30+ * may not import the sdk (`@repo/project`) read it here.31+ */32+export { sdkVersion } from "@repo/sdk";33+34 /** One workspace package, as the repo's manifests declare it. */35 const Workspace = Schema.Struct({36 /** Its folder, from the repo's root: `packages/parse`. */37 dir: Schema.String,47 unmodified lines85 86 export type RuleName = typeof RuleName.Type;87 88 /**89+ * One function-valued rule and the facts it is told, typed by the sdk's own90+ * fact schemas (principle 2): `opensAlone` hears about a proposal, `admit`91+ * about a person who wants to claim. The facts are encoded as JSON before92+ * they cross into the sandbox.93+ */94+export type RuleCall =95+ | { readonly rule: "opensAlone"; readonly facts: ProposalFacts }96+ | { readonly rule: "admit"; readonly facts: ClaimantFacts };97+98+/** A call's facts as JSON carries them into the sandbox. */99+export const factsOf = (call: RuleCall): Effect.Effect<Schema.Json> => {100+ const encoded: Effect.Effect<Schema.Json, Schema.SchemaError> =101+ call.rule === "opensAlone"102+ ? Schema.encodeEffect(ProposalFacts)(call.facts)103+ : Schema.encodeEffect(ClaimantFacts)(call.facts);104+105+ // The facts were typed by the same schemas, so encoding them can't fail.106+ return Effect.orDie(encoded);107+};108+109+/**110 * Turns the config folder at a landed commit into its `Policy`, the same111 * one every time for the same facts, and calls its function-valued rules on112 * demand. Adapters: `/bun` (a subprocess with frozen time), `/json` (a113 * committed `policy.json`, or the defaults) and, in W3, `/worker`.114 */115 export class RulesEvaluator extends Context.Service<116 RulesEvaluator,117 {90- readonly call: (input: {91- readonly at: LandedSha;92- readonly facts: Schema.Json;93- readonly modules: ConfigBundle;94- readonly rule: RuleName;95- }) => Effect.Effect<boolean, RulesFailed>;118+ readonly call: (119+ input: RuleCall & {120+ readonly at: LandedSha;121+ readonly modules: ConfigBundle;122+ }123+ ) => Effect.Effect<boolean, RulesFailed>;124 readonly evaluate: (input: {125 readonly at: LandedSha;126 readonly facts: EvaluationFacts;127 readonly modules: ConfigBundle;3 unmodified linesmodified:packages/rules/test/fixtures/cm/project.ts+10 added-4 removed
1+import { Functions } from "@repo/sdk";2+3 import data from "./project.json" with { type: "json" };4 5 /**6 * The convex-merged design's example project (its §3), as the data the sdk's2 unmodified lines9 * budget and caps, `Assisted-by` trailers, and the record window. The run10 * block is the one found in CI; claims and the vouch file keep their11 * defaults.12 *11- * The example's one function-valued rule rides beside the data, where JSON12- * leaves it out: a proposal opens alone for someone who has held three asks.13+ * The example's one function-valued rule rides where the sdk keeps it,14+ * under its `Functions` symbol, which JSON never meets: a proposal opens15+ * alone for someone with three unreverted landings in the territory.16 */14-const project = Object.defineProperty({ ...data }, "opensAlone", {17+const project = Object.defineProperty({ ...data }, Functions, {18 enumerable: false,16- value: (facts: { readonly held: number }) => facts.held >= 3,19+ value: {20+ admit: undefined,21+ opensAlone: (proposal: { readonly record: number }) => proposal.record >= 3,22+ },23 });24 25 export default project;modified:packages/rules/test/evaluate.test.ts+125 added-30 removed
1 unmodified line2 import { assert, describe, expect, it } from "@effect/vitest";3 import { CheckSpec } from "@repo/protocol/domain/check";4 import { Policy } from "@repo/protocol/domain/policy";5 import { RepoPath } from "@repo/protocol/ids";6+import { ClaimantFacts, ProposalFacts } from "@repo/sdk";7 import { Duration, Effect, Layer, Result, Schema } from "effect";8 9 import { Finishers } from "../src/finish.ts";10 import { RulesEvaluator } from "../src/rules-evaluator.ts";11 unmodified lines22 folder,23 now,24 } from "./world.ts";25 26+const decodeProposal = Schema.decodeUnknownSync(ProposalFacts);27+28+const decodeClaimant = Schema.decodeUnknownSync(ClaimantFacts);29+30+/** A proposal for an ask of the example's `fixBug` kind, but its record. */31+const fixBugProposal = {32+ kind: "fixBug",33+ proposer: "carol",34+ territory: "@datekit/parse",35+};36+37 /** A red-then-green check on one file, as `CheckSpec` encodes it. */38 const redThenGreen = (path: string) =>39 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });40 140 unmodified lines181 weakening: { markers: [".skip("] },182 };183 184 /**173- * The defaults (convex-merged design §3, "no folder means defaults"; the174- * weakening markers from spec §4.2), as `Policy` encodes them.185+ * The defaults (convex-merged design §3, "no folder means defaults"), as186+ * `Policy` encodes them: the sdk's `defaults`, finished with the facts.187 */188 const defaultsEncoded = {189 ...fromFacts,190 agents: "trailer",11 unmodified lines202 finish: "optional",203 name: "fix",204 oneWay: false,205 race: 1,194- requires: ["want", "check"],206+ requires: ["want", "check", "territory"],207 strength: "assertion",208 },209 ],210 ratchets: [],211 record: { countsAfterDays: 30, windowDays: 365 },212 run: foundRun,213 source: "defaults",214 vouch: { file: defaultVouchFile, mode: "forCode" },203- weakening: {204- markers: [205- ".skip(",206- ".only(",207- ".todo(",208- "eslint-disable",209- "oxlint-disable",210- "biome-ignore",211- "@ts-ignore",212- "@ts-expect-error",213- "@ts-nocheck",214- // The Effect language service would read the whole word as a directive.215- ["@effect", "diagnostics"].join("-"),216- "# noqa",217- "# type: ignore",218- "#[allow(",219- "//nolint",220- "istanbul ignore",221- "c8 ignore",222- ],223- },215+ // The gate scans its own default markers plus these, a project's own.216+ weakening: { markers: [] },217 };218 219 /** Evaluates a bundle at `at` with the shared facts, and encodes the policy. */220 const evaluated = (modules: ConfigBundle) =>205 unmodified lines426 expect(failure.detail).toMatch(/x+the end$/u);427 }).pipe(Effect.provide(bunEvaluator()))428 );429 430+ // A project written with the real sdk: the rules ride under its symbol,431+ // and the facts are the sdk's own fact schemas.432+ const sdkProject = bundleOf({433+ "project.ts": [434+ 'import { check, kind, kinds, project } from "@repo/sdk";',435+ "",436+ "const trusted = kind({",437+ " args: {},",438+ ' check: () => check.redThenGreen("test/trusted.test.ts"),',439+ ' checkKind: "redThenGreen",',440+ ' name: "trusted",',441+ " opensAlone: (proposal) => proposal.record >= 3,",442+ "});",443+ "",444+ "export default project({",445+ " admit: (claimant) => claimant.vouched || claimant.record > 0,",446+ " kinds: [kinds.fix, trusted],",447+ "});",448+ ].join("\n"),449+ });450+451+ it.live("calls the rules a project written with the sdk carries", () =>452+ Effect.gen(function* () {453+ const evaluator = yield* RulesEvaluator;454+ const modules = sdkProject;455+456+ const proposal = (kind: string, record: number) =>457+ evaluator.call({458+ at,459+ facts: decodeProposal({460+ kind,461+ proposer: "carol",462+ record,463+ territory: ".",464+ }),465+ modules,466+ rule: "opensAlone",467+ });468+469+ const claimant = (vouched: boolean, record: number) =>470+ evaluator.call({471+ at,472+ facts: decodeClaimant({473+ handle: "bram",474+ kind: "fix",475+ record,476+ territory: ".",477+ vouched,478+ }),479+ modules,480+ rule: "admit",481+ });482+483+ expect([484+ yield* proposal("trusted", 3),485+ yield* proposal("trusted", 2),486+ yield* proposal("fix", 9),487+ yield* claimant(true, 0),488+ yield* claimant(false, 1),489+ yield* claimant(false, 0),490+ ]).toStrictEqual([true, false, false, true, true, false]);491+ }).pipe(Effect.provide(bunEvaluator()))492+ );493+494+ it.live(495+ "evaluates a project file that states nothing as no folder at all",496+ () =>497+ Effect.gen(function* () {498+ const stated = yield* evaluated(499+ bundleOf({500+ "project.ts": [501+ 'import { project } from "@repo/sdk";',502+ "",503+ "export default project({});",504+ ].join("\n"),505+ })506+ );507+508+ expect(stated).toStrictEqual({ ...defaultsEncoded, source: "config" });509+ }).pipe(Effect.provide(bunEvaluator()))510+ );511+512 it.live("calls a function-valued rule with the facts it is given", () =>513 Effect.gen(function* () {514 const evaluator = yield* RulesEvaluator;515 const modules = yield* folder("cm");516 442- const call = (rule: "admit" | "opensAlone", held: number) =>443- evaluator.call({ at, facts: { held }, modules, rule });517+ const opensAlone = (record: number) =>518+ evaluator.call({519+ at,520+ facts: decodeProposal({ ...fixBugProposal, record }),521+ modules,522+ rule: "opensAlone",523+ });524 445- expect(yield* call("opensAlone", 3)).toBeTruthy();446- expect(yield* call("opensAlone", 1)).toBeFalsy();447- expect(yield* call("admit", 3)).toBeFalsy();525+ const admit = evaluator.call({526+ at,527+ facts: decodeClaimant({528+ handle: "bram",529+ kind: "fixBug",530+ record: 3,531+ territory: "@datekit/parse",532+ vouched: true,533+ }),534+ modules,535+ rule: "admit",536+ });537+538+ expect([539+ yield* opensAlone(3),540+ yield* opensAlone(1),541+ yield* admit,542+ ]).toStrictEqual([true, false, false]);543 }).pipe(Effect.provide(bunEvaluator()))544 );545 });546 47 unmodified lines594 const evaluator = yield* RulesEvaluator;595 596 const called = yield* evaluator.call({597 at,503- facts: { held: 3 },598+ facts: decodeProposal({ ...fixBugProposal, record: 3 }),599 modules: yield* folder("cm"),600 rule: "opensAlone",601 });602 4 unmodified linesmodified:packages/rules/test/finish.test.ts+59 added-3 removed
6 unmodified lines7 import { defaultPolicyInput } from "../src/defaults.ts";8 import { finishPolicy } from "../src/finish.ts";9 import { at, facts, finishers } from "./world.ts";10 11-/** An ask with the given id, declared in `file`. */12-const askIn = (id: string, file: string) =>11+/** The whole repo, as one module. */12+const wholeRepo: (typeof AskInput.Encoded)["territory"] = {13+ module: ".",14+ paths: ["**"],15+};16+17+/** An ask with the given id, declared in `file`, in `territory`. */18+const askIn = (19+ id: string,20+ file: string,21+ territory: (typeof AskInput.Encoded)["territory"] = wholeRepo22+) =>23 Schema.decodeSync(AskInput)({24 askedBy: "olivia",25 blockedBy: [],26 brief: { want: "Parse dates" },2 unmodified lines29 }),30 file,31 id,32 kind: "fix",23- territory: { module: ".", paths: ["**"] },33+ territory,34 });35 36 describe(finishPolicy, () => {37 it.effect("refuses a vouch file line that names no handle, by its line", () =>32 unmodified lines70 expect(failure.reason).toBe("decode");71 expect(failure.detail).toContain("a/dates.ask.ts");72 })73 );74+75+ // The sdk's `territory.package(name)` can't know the package's folder, so76+ // it writes `{dir}`; the evaluator knows the workspaces.77+ it.effect(78+ "writes a package territory's folder and public files in from the workspaces",79+ () =>80+ Effect.gen(function* () {81+ const policy = yield* finishPolicy({82+ at,83+ facts,84+ finishers,85+ policy: {86+ ...defaultPolicyInput,87+ asks: [88+ askIn("parse", "a/parse.ask.ts", {89+ module: "@datekit/parse",90+ paths: ["{dir}/**"],91+ }),92+ askIn("format", "a/format.ask.ts", {93+ module: "@datekit/format",94+ paths: ["{dir}/src/**", "{dir}/test/**"],95+ }),96+ askIn("gone", "a/gone.ask.ts", {97+ module: "@datekit/gone",98+ paths: ["{dir}/**"],99+ }),100+ ],101+ },102+ });103+104+ expect(policy.asks.map(({ territory }) => territory)).toStrictEqual([105+ {106+ module: "@datekit/parse",107+ paths: ["packages/parse/**"],108+ publicFiles: ["packages/parse/src/index.ts"],109+ },110+ {111+ module: "@datekit/format",112+ paths: ["packages/format/src/**", "packages/format/test/**"],113+ },114+ // A package no workspace names keeps the placeholder, which matches115+ // no real path, so the gate refuses every change (fails closed).116+ { module: "@datekit/gone", paths: ["{dir}/**"] },117+ ]);118+ })119+ );120 });modified:AGENTS.md+6 added-6 removed
1 # Myr2 3 Myr is a whole Git platform on Cloudflare. Everything a project ships is public, the contribution process is typed code, and a push lands only by passing a typed gate. It is our entry to Cloudflare's "Build the next GitHub" competition, which closes Wed Oct 14, 11:59 PM PDT.4 5-**W1's fences exist, and `bun run verify` runs them.** The principles table says which rules still wait for theirs; until a rule's fence lands, review holds it.5+**The W1 and W2 fences exist, and `bun run verify` runs them.** The principles table says which rules still wait for theirs; until a rule's fence lands, review holds it.6 7 The plan is the synthesis: `~/Developer/projects/wanted-explainer/notes/git-platform-research/zoom-out/synthesis.md`, published at https://plans.gneiss.run/wanted-explainer/zoom-out/synthesis.html. Read the section your task touches:8 9 - the concept: §3;11 unmodified lines21 | # | Principle | Held by |22 | --- | --- | --- |23 | 1 | **Encode lessons in structure; prose is the last rung.** When a mistake repeats, make it unrepresentable, then a lint or test, then a skill. | `packages/config/test/agents-table.test.ts`: every enforcer this column names exists and is on |24 | 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | The Effect diagnostics at error in `tsconfig.base.json`; `anti-slop/no-unknown-parameters`, `anti-slop/no-widen-then-assert` and `anti-slop/require-safety-comment-for-type-assertion`; the generated `apps/platform/worker-configuration.d.ts` types the env, and `apps/platform/test/platform.test.ts` proves a bad env fails at start. No fence yet: the decoded bindings equal `wrangler.jsonc`'s, with no `as` on `env` (`apps/platform/test/bindings.test.ts`, W3 317) |25-| 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` (the tag list is closed; each refusal reaches MCP as JSON with retryable and next); `packages/protocol/test/render.test.ts`; `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `gen:check` on `docs/reference/refusals.md`; `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`. No fence yet: the gate's stage-1 test that every refusal accumulates (W2 206); a `tools/call` test per refusing contract (W4 408) |25+| 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` (the tag list is closed; each refusal reaches MCP as JSON with retryable and next); `packages/protocol/test/render.test.ts`; `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `gen:check` on `docs/reference/refusals.md`; `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`; `packages/gate/test/shape.test.ts` (one push hears every stage-1 refusal at once, in the union's order). No fence yet: a `tools/call` test per refusing contract (W4 408) |26 | 4 | **One schema, many surfaces.** Change `packages/protocol`, then run `bun run gen`. `skills/`, `plugins/` and `docs/reference/` are generated. Projections live only in `apps/*/src/surfaces.ts`. | `gen:check` (`scripts/gen.ts`, tested by `packages/config/test/gen.test.ts`) fails on a stale, missing or hand-written generated file; per-package `allowedUnstableApis` with `unstableApiUsage` at error keep Rpc and Tool construction in protocol and the apps |27 | 5 | **The name lives only in `packages/brand`.** Internal packages use `@repo/*`. DO classes, Workflows, queues and databases carry job names. | `brand:check` (`scripts/brand.ts`, tested by `packages/brand/test/leaks.test.ts`) in `verify`. No fence yet: `scripts/acceptance.ts` renames the brand at random on a cold clone and runs `verify` (W7 714) |28-| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. | `imports:check` (`scripts/imports.ts`, tested by `packages/config/test/imports.test.ts`): the package matrix, apps never importing apps, host-free Worker code, adapters only through their subpaths, alchemy only in infra; scoped `allowedUnstableApis`; `fence/no-module-level-mutable-state`. No fence yet: Artifacts and each other beta dependency behind one port with a `/memory` adapter, composed from the decoded env (W2 202; W3 317 `apps/platform/src/ports.ts`) |29-| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree` in the closed refusal union. No fence yet: the stage-1 path checks that raise it (W2 206 gate, W6 606 gateway); the web `Env` type test, no `ARTIFACTS_PRIVATE` (W5 501 `apps/web/test/env.test-d.ts`); the snapshot-order test (W3 315, W6 605) |30-| 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins. No fence yet: the rules replay-twice test (W2 204); dedupe by `requestId` and event id (W2 210, W3 313); the Answer Workflow's replay test (W3 304); lifecycle model tests (W2 209, 219) |28+| 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. | `imports:check` (`scripts/imports.ts`, tested by `packages/config/test/imports.test.ts`): the package matrix, apps never importing apps, host-free Worker code, adapters only through their subpaths, alchemy only in infra; scoped `allowedUnstableApis`; `fence/no-module-level-mutable-state`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract that the memory, local, binding and REST adapters each pass). No fence yet: every beta dependency's port composed from the decoded env, and losing a binding failing the build (W3 317 `apps/platform/src/ports.ts`) |29+| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree` in the closed refusal union, raised by the gate's stage 1 for a layer's path in an answer (`packages/gate/test/shape.test.ts`). No fence yet: the gateway's layer guard (W6 606); the web `Env` type test, no `ARTIFACTS_PRIVATE` (W5 501 `apps/web/test/env.test-d.ts`); the snapshot-order test (W3 315, W6 605) |30+| 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts` (equal facts give equal policies, with the clock and randomness frozen); `packages/project/test/project-store.contract.ts` (a replayed push event or request writes nothing twice); `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts` (any command delivered twice converges). No fence yet: push events deduped by (repo, sha) at the gateway (W3 313); the Answer Workflow's replay test (W3 304) |31 | 9 | **Effect v4 only.** Read `node_modules/effect/src`, or `.agent_sources/effect` (see Commands), as API truth. Off limits: `effect/unstable/*`, v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `no-restricted-imports`; `fence/no-manual-effect-runtime-in-tests` |32 | 10 | **Escapes need a reason and only shrink.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries a reason after `--` and is counted. The count rises only with sign-off. | `debt` (`scripts/debt.ts` over `oxlint.debt.config.ts`, tested by `packages/config/test/debt.test.ts`) against `debt.baseline.json` in `verify`; `check` fails on an unused directive |33 | 11 | **Hooks are early feedback; `bun run verify` and CI are the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `scripts/hooks/vcs-policy.ts`, wired into Claude Code (`.claude/settings.json`), Cursor (`.cursor/hooks.json`) and pi (`.pi/extensions/vcs-policy/`), refusing every bypass variant in `packages/config/test/vcs-policy.test.ts`; `verify`. No fence yet: `infra/deploy.ts` refuses without a stage and runs `scripts/smoke.ts` (W3 308); `scripts/acceptance.ts` runs `verify` on a cold install in place of CI (W7 714) |34-| 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | `globalTimers` and `globalTimersInEffect` refuse JavaScript timers outside and inside Effect; `fence/no-effect-sleep-in-project` refuses Effect.sleep and Effect.delay in the project package's source. No fence yet: lifecycle model tests over `effect/Arbitrary` histories with one planted bug (W2 209, 219) |34+| 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | `globalTimers` and `globalTimersInEffect` refuse JavaScript timers outside and inside Effect; `fence/no-effect-sleep-in-project` refuses Effect.sleep and Effect.delay in the project package's source; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`, model tests over effect/Arbitrary histories, each seen catching its planted bug. No fence yet: the Project Durable Object's hydrate, transition, persist and settle per call, with deadlines on its alarm (W3 302) |35 36 ## Fence37 38 `bun run verify` is the gate (see Commands). Run it before you stop. When a hook or check fails, fix the cause. Loosening, skipping or disabling a check needs the user's sign-off.115 unmodified linesmodified:PROVENANCE.md+1 added
12 unmodified lines13 | `tools/oxlint/fence/rules/no-module-level-mutable-state.ts` | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `scripts/oxlint-plugin-patterns.ts` l.28–43 and l.621–677 at `fba26d8` | MIT, `LICENSES/rat-stack.MIT.txt` | Only this rule is ported from that file. A named export in the `fence` plugin. `workspacePath` reads the path string alone: it strips oxlint's `cwd`, then finds the whole `(apps\|packages)/<name>/src/` shape anywhere, so a fixture tree counts and folders above the checkout don't; no `node:path` import and no `nodeBuiltinImport` escape. `workspacePath` is exported, for `no-effect-sleep-in-project`. The `.svelte` exclusion is dropped, and `declare let`/`declare var` is skipped. The scope check, `isModuleScopedVar`, the `moduleState` message and the description are upstream's. See `tools/oxlint/fence/UPSTREAM.md`. |14 | `tools/oxlint/fence/rules/no-manual-effect-runtime-in-tests.ts` | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `scripts/oxlint-plugin-effect-tests.ts` at `fba26d8`, adapted there from [pingdotgg/t3code](https://github.com/pingdotgg/t3code) `oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.ts` (Rat Stack names no commit; licence copied at `05d4042`) | MIT, `LICENSES/rat-stack.MIT.txt` and `LICENSES/t3code.MIT.txt` | A named export in the `fence` plugin. `manualRunnerName` (a string nobody read) became the boolean `isManualRunner`. The test-file pattern, the twelve `Effect.run*` methods plus `ManagedRuntime.make`, the `manualRunner` message and the description are Rat Stack's. t3code's later `maxOccurrences` ceiling and `Option` unwrapping are not ported. See `tools/oxlint/fence/UPSTREAM.md`. |15 | `scripts/hooks/lib/policy.ts`, `scripts/hooks/vcs-policy.ts`, `.claude/settings.json`, `.cursor/hooks.json`, `.pi/extensions/vcs-policy/index.ts` | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `scripts/vcs-command-policy.js`, `scripts/hooks/block-git-no-verify.mjs`, `.claude/settings.json`, `.cursor/hooks.json` and `.pi/extensions/git-interceptor/index.ts` at `fba26d8` | MIT, `LICENSES/rat-stack.MIT.txt` | The regex became argv parsing: a shell reader (`scripts/hooks/lib/shell.ts`: simple commands, quotes, `$'…'`, substitutions, heredocs, redirects) and an option parser (`scripts/hooks/lib/argv.ts`), both new, so flag text inside a quoted `-m` is a message. Five rules instead of one: hook bypasses (`--no-verify` and its prefixes, `commit -n` and bundles, `-c core.hooksPath`, `--config-env`, aliases, `git config core.hooksPath`, `LEFTHOOK=0`, `HUSKY=0`, `lefthook uninstall`), `git push`, deletes (wrangler; cf without `--dry-run`, read the way yargs reads it), cf's project commands (also through cf's second bin name, `cloudflare`), and reads of the closed env files (a recursive `grep` or `rg -uu` included). Each refusal carries its rule and a reason sentence. Deny-only: the `GIT_EDITOR=:` rewrite is dropped. The adapter decodes its input with Effect Schema, runs under `BunRuntime.runMain`, writes through `Stdio`, denies Claude Code by exit 2 and fails closed on input it cannot read (upstream exits 0). The Cursor hook has no `matcher`, so every shell command is judged; the pi extension blocks through a local structural type instead of importing pi. Beyond the shell: `.claude/settings.json` denies Claude Code's Read tool the closed env files, and the pi extension blocks pi's `read`, `edit` and `grep` of them (`isClosedEnvPath`). |16 | `scripts/vendor-agent-sources.sh` | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `scripts/vendor-agent-sources.sh` at `fba26d8` | MIT, `LICENSES/rat-stack.MIT.txt` | Two sources (Effect, workers-sdk) in place of six, in a flat `.agent_sources/<repo>` layout in place of `github.com/<owner>/<repo>`. The pins come from the root catalog's `effect` and `apps/platform`'s `wrangler`, refused unless each is one exact version. Every tag is checked with `git ls-remote --exit-code` before its clone, with no fallback. The clone's own package version must equal the pin. The metadata is written last and marks a finished clone; a pin that moved re-clones without `--refresh`. |17+| `packages/rules/src/rules-evaluator/bun-prelude.ts` (the `next` generator, about 8 lines) | mulberry32, Tommy Ettinger's 32-bit seeded generator, written from the published algorithm | Public domain; no licence text to keep | Seeded from the evaluation's `seed` fact (or 0 for a rule call), and installed as `Math.random`, `crypto.getRandomValues` and `crypto.randomUUID` inside the config sandbox, so rule code sees the same numbers for the same facts (principle 8). |18 | `tsconfig.base.json` (compiler options and the Effect diagnostics map) | [joelhooks/rat-stack](https://github.com/joelhooks/rat-stack) `tsconfig.base.json` at `fba26d8` | MIT, `LICENSES/rat-stack.MIT.txt` | `importFromBarrel` dropped (unknown to `@effect/tsgo` 0.48.1); `types` emptied, so each package opts into its host's types; `@effect/platform-bun` added to `namespaceImportPackages`; `outdatedApi`, `unstableApiUsage` and `experimentalApiUsage` raised to `error`; `allowedUnstableApis` emptied and granted per path through `overrides`. |19 20 ## Ideas, no code21 7 unmodified linesmodified:tsconfig.base.json+6 added-1 removed
157 unmodified lines158 }159 },160 {161 "include": [162- "packages/artifacts/test/**/*.ts",162 "packages/checks/test/**/*.ts",163 "packages/rules/test/**/*.ts",164 "packages/testkit/test/**/*.ts"165 ],1 unmodified line167 "allowedUnstableApis": ["effect/process"]168 }169 },170 {171+ "include": ["packages/artifacts/test/**/*.ts"],172+ "options": {173+ "allowedUnstableApis": ["effect/http", "effect/process"]174+ }175+ },176+ {177 "include": ["packages/artifacts/src/repo-host/local.ts"],178 "options": {179 "diagnosticSeverity": { "nodeBuiltinImport": "off" }180 }6 unmodified linesmodified:turbo.json+1 added
8 unmodified lines9 "outputs": []10 },11 "test": {12 "dependsOn": ["types", "^types"],13+ "env": ["UPDATE_GOLDEN"],14 "outputs": []15 },16 "@repo/config#test": {17 "cache": false,5 unmodified lines