Skip to content
Myr

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).

authored by oscabriel · committed by oscabriel · parent 08d244c · Browse files · 55 files+829 added−434 removed
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

55 files+829 added−434 removed

modified:docs/reference/protocol.schema.json+9 added
2547 unmodified lines
2548 "$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 lines
6263 "$ref": "#/$defs/DenouncedEncoded"6264 },6265 {6266 "$ref": "#/$defs/CapReachedEncoded"6267 },6268 {6269 "$ref": "#/$defs/NotVouchedEncoded"6270 }6271 ]6272 },6273 "proposeAsk.payload": {
5390 unmodified lines
added: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 */8import { Duration, Schema } from "effect";910import { Revision } from "../repo-host.ts";1112/** Artifacts' names for its errors: `ArtifactsError.code` on the binding. */13export 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]);2829export type Code = typeof Code.Type;3031export const isCode = Schema.is(Code);3233/**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 */38export 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]);5253/**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 */57export 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[];6566/** Artifacts' name for a revision: a short branch name or a commit id, never `refs/…` (S1 #20). */67export const refOf = (at: Revision) =>68 Revision.$match(at, {69 Branch: ({ name }) => name,70 Commit: ({ sha }) => sha,71 });7273// Artifacts takes a token's ttl in whole seconds, from a minute to a year.74const MIN_TTL_SECONDS = 60;7576const MAX_TTL_SECONDS = 31_536_000;7778/** A token's ttl as Artifacts takes it: whole seconds, clamped to a minute and a year. */79export const secondsOf = (ttl: Duration.Duration) =>80 Math.min(81 Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),82 MAX_TTL_SECONDS83 );8485/** `log` reads at most this many commits per call. */86export const LOG_PAGE = 1000;
modified:packages/artifacts/src/repo-host/binding.ts+16 added-52 removed
35 unmodified lines
36 RefName,37 RepoExists,38 RepoHost,39 RepoNotFound,40 Revision,40 TreeEntry,41} from "../repo-host.ts";43import type { RepoName, RepoToken, TokenScope } from "../repo-host.ts";42import type {43 RepoName,44 RepoToken,45 TokenScope,46 Revision,47} from "../repo-host.ts";48import {49 isCode,50 LOG_PAGE,51 NO_SOURCE,52 refOf,53 secondsOf,54} from "./artifacts-api.ts";55import type { Code } from "./artifacts-api.ts";56import { listRefs, pushRefs } from "./smart-http.ts";5746const 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]);6162type Code = typeof Code.Type;6364const isCode = Schema.is(Code);6558/**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 lines
145146/** How long a token minted for one call lives; it is revoked after the call. */147const CALL_TOKEN_TTL = Duration.minutes(5);148157// Artifacts takes a token's ttl in whole seconds, from a minute to a year.158const MIN_TTL_SECONDS = 60;149/** The codes `import` refuses a source with. */150const IMPORT_REFUSALS: ReadonlySet<Code> = new Set(NO_SOURCE);151160const MAX_TTL_SECONDS = 31_536_000;161162const secondsOf = (ttl: Duration.Duration) =>163 Math.min(164 Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),165 MAX_TTL_SECONDS166 );167168/** `log` reads at most this many commits per call. */169const LOG_PAGE = 1000;170171/** The codes `import` refuses a source with: not git, not public, not reachable, too big. */172const 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]);180181/** The binding's name for a revision: never `refs/…` (S1 #20). */182const refOf = (at: Revision) =>183 Revision.$match(at, {184 Branch: ({ name }) => name,185 Commit: ({ sha }) => sha,186 });187152const bytesOf = (blob: Blob) =>153 attempt(() => blob.arrayBuffer()).pipe(154 Effect.map((buffer) => new Uint8Array(buffer)),155 Effect.catchTag("Thrown", asDefect)
364 unmodified lines
modified:packages/artifacts/src/repo-host/local.ts+1 added-14 removed
1import * as fs from "node:fs";2import { tmpdir } from "node:os";2import { fileURLToPath } from "node:url";34import type { CommitSha } from "@repo/protocol/ids";5import {
7 unmodified lines
13 Schema,14 Semaphore,15 Stream,16} from "effect";18import type { Context, Scope } from "effect";17import type { Context } from "effect";18import {19 Errors,20 addRemote,21 currentBranch,
513 unmodified lines
535 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 lines
87 RefName,88 RepoExists,89 RepoHost,90 RepoNotFound,91 Revision,91 TreeEntry,92} from "../repo-host.ts";94import type { Commit, RepoName, RepoToken, TokenScope } from "../repo-host.ts";93import type {94 Commit,95 RepoName,96 RepoToken,97 TokenScope,98 Revision,99} from "../repo-host.ts";100import {101 LOG_PAGE,102 NO_SOURCE,103 NUMBERED,104 refOf,105 secondsOf,106} from "./artifacts-api.ts";107import type { Code } from "./artifacts-api.ts";108import { listRefs, pushRefs } from "./smart-http.ts";10997/** The binding's names for Artifacts' errors (`ArtifactsError.code`). */98type 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";112113/**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 */117const 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]);131110/** A refusal that names no code at all, such as a proxy's, read by status. */111const byStatus = (status: number): Option.Option<Code> =>112 Match.value(status).pipe(113 Match.when(404, () => Option.some<Code>("NOT_FOUND")),
128 unmodified lines
242 };243 })244 ).pipe(Effect.orDie);245268/** The API's name for a revision: a short branch name or a commit id (S1 #20). */269const refOf = (at: Revision) =>270 Revision.$match(at, {271 Branch: ({ name }) => name,272 Commit: ({ sha }) => sha,273 });274246const repoPath = (name: RepoName) => `/repos/${encodeURIComponent(name)}`;247248const textOf = (response: Response) => Effect.promise(() => response.text());249
25 unmodified lines
275 response.ok ? Effect.void : refusal(response);276277const main = RefName.make("refs/heads/main");278308/** `log` asks for at most this many commits per request, as the binding does. */309const LOG_PAGE = 1000;310311// Artifacts takes a token's ttl in whole seconds, from a minute to a year.312const MIN_TTL_SECONDS = 60;313314const MAX_TTL_SECONDS = 31_536_000;315316const secondsOf = (ttl: Duration.Duration) =>317 Math.min(318 Math.max(Math.ceil(Duration.toSeconds(ttl)), MIN_TTL_SECONDS),319 MAX_TTL_SECONDS320 );321279/** How long a token for git calls lives, and how near its expiry it is replaced. */280const CALL_TOKEN_TTL = Duration.minutes(30);281282const CALL_TOKEN_MARGIN = Duration.minutes(5);
22 unmodified lines
305 keep: (value: V, key: K) => boolean306): ReadonlyMap<K, V> =>307 new Map([...map].filter(([key, value]) => keep(value, key)));308352/** The import refusals that say the source is no repo to take (the binding's). */353const 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[];361309/** A repo that exists but is still being made answers its info and mints 409. */310const BEING_MADE = [311 "CREATE_IN_PROGRESS",312 "FORK_IN_PROGRESS",
523 unmodified lines
modified:packages/artifacts/test/binding.test.ts+2 added-1 removed
39 unmodified lines
40import { RepoHostLocal } from "../src/repo-host/local.ts";41import { memoryFs } from "../src/repo-host/memory-fs.ts";42import { fetchInto, listRefs, pushRefs } from "../src/repo-host/smart-http.ts";43import { describeRepoHost } from "./repo-host-contract.ts";44import { temporaryRoot } from "./temporary-root.ts";4546const main = RefName.make("refs/heads/main");4748const landed = RefName.make("refs/asked/landed");
34 unmodified lines
83const 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;8889 const spawner =90 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();91
661 unmodified lines
modified:packages/artifacts/test/local.test.ts+79 added-6 removed
1import { NodeHttpServer, NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { gitOk } from "@repo/testkit/git";4import { gitClient } from "@repo/testkit/git-client";3import { Duration, Effect, Layer, Option } from "effect";5import { httpBackend } from "@repo/testkit/http-backend";6import { Context, Duration, Effect, FileSystem, Layer, Option } from "effect";7import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";8import type { ChildProcessSpawner } from "effect/process";910import { Fetch, FetchFailed } from "../src/fetch.ts";11import {12 BranchName,
4 unmodified lines
17} from "../src/repo-host.ts";18import { RepoHostLocal } from "../src/repo-host/local.ts";19import { memoryFs } from "../src/repo-host/memory-fs.ts";20import { describeRepoHost } from "./repo-host-contract.ts";21import { temporaryRoot } from "./temporary-root.ts";2223const main = RefName.make("refs/heads/main");2425/** No network: every request fails as an unreachable host's would. */
11 unmodified lines
37 Layer.provide(offline)38 );3940/** A store in a new temporary directory, removed when the test ends. */35const freshStore = Layer.unwrap(36 Effect.map(RepoHostLocal.temporaryRoot, storeAt)37);41const freshStore = Layer.unwrap(Effect.map(temporaryRoot, storeAt));4243/** Real `git http-backend` over `root` on a local port: its base URL. */44const served = (root: string) =>45 Effect.gen(function* () {46 const spawner =47 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();4849 const backend = httpBackend(root);5051 const app = Effect.gen(function* () {52 const request = yield* HttpServerRequest.toWeb(53 yield* HttpServerRequest.HttpServerRequest54 );5556 return HttpServerResponse.fromWeb(57 yield* Effect.scoped(backend(request)).pipe(Effect.provide(spawner))58 );59 }).pipe(Effect.orDie);6061 const server = yield* Layer.build(62 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))63 ).pipe(Effect.orDie);6465 const { address } = Context.get(server, HttpServer.HttpServer);6667 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 });7172// Its test-only meaning of a public remote: another bare repo on disk, named73// by its `file://` URL.74describeRepoHost("local", freshStore, {75 importUrl: (name) =>76 RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),77});7879describe("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");9293 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 ]);99100 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 );110111 yield* gitOk(work, "clone", "--quiet", remote, "clone");112113 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 );119120 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");124125 const remote = yield* RepoHost.use((repos) =>126 Effect.andThen(repos.create(name), repos.remote(name))
13 unmodified lines
140 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 lines
modified:packages/artifacts/test/repo-host-contract.ts+4 added-2 removed
40 unmodified lines
41 ) => Effect.Effect<string, never, RepoHost>;42}4344/**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 */50export const describeRepoHost = (51 adapter: string,52 host: Layer.Layer<RepoHost>,
443 unmodified lines
modified:packages/artifacts/test/rest.test.ts+2 added-1 removed
36 unmodified lines
37import { RepoHostRest } from "../src/repo-host/rest.ts";38import { fakeRest } from "./fake-rest.ts";39import type { FakeRestOptions } from "./fake-rest.ts";40import { describeRepoHost } from "./repo-host-contract.ts";41import { temporaryRoot } from "./temporary-root.ts";4243const main = RefName.make("refs/heads/main");4445const accountId = "0123456789abcdef0123456789abcdef";
42 unmodified lines
88const world = (89 options: Omit<FakeRestOptions, "accountId" | "namespace" | "token"> = {}90) =>91 Effect.gen(function* () {91 const root = yield* RepoHostLocal.temporaryRoot;92 const root = yield* temporaryRoot;9394 const spawner =95 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();96
602 unmodified lines
added:packages/artifacts/test/temporary-root.ts+12 added
1import { NodeServices } from "@effect/platform-node";2import { Effect, FileSystem } from "effect";34/**5 * A new temporary directory for a store's root, removed with its contents6 * when the test's scope closes.7 */8export 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 lines
3 * pusher, the policy and the claim, so it is free; the first rule a push4 * breaks is its one refusal.5 */6import type { Policy } from "@repo/protocol/domain/policy";7import { sameHandle } from "@repo/protocol/ids";8import type { Handle } from "@repo/protocol/ids";9import { Principal } from "@repo/protocol/principal";10import {11 CapReached,
13 unmodified lines
25import type { Stage } from "../stage.ts";2627type Rule = (facts: PushFacts) => Option.Option<Refusal>;2828/** Handles name one person however their sign-in provider cases them. */29const sameHandle = (one: Handle, other: Handle) =>30 one.toLowerCase() === other.toLowerCase();3129const handleOf = (pusher: Principal): Option.Option<Handle> =>30 Principal.guards.Person(pusher) ? Option.some(pusher.handle) : Option.none();3132const isPusher = (facts: PushFacts, handle: Handle) =>33 Option.exists(handleOf(facts.pusher), (pusher) => sameHandle(pusher, handle));3435/**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 */41const 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 );4545 if (line !== undefined) {46 return line.denounced ? "denounced" : "vouched";46 if (lines.some(({ denounced }) => denounced)) {47 return "denounced";48 }4950 if (lines.length > 0) {51 return "vouched";52 }5354 const decides = policy.deciders.some((decider) =>55 decider.handles.some((each) => sameHandle(each, handle))56 );57
15 unmodified lines
73 ? Option.none()74 : Option.some(new DirectPush({ ref: facts.ref })),75 });7672/** 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 */84const trust: Rule = (facts) =>85 Option.flatMap(handleOf(facts.pusher), (handle) => {86 const standing = standingOf(facts.policy, handle);8788 if (standing === "denounced") {89 return Option.some<Refusal>(new Denounced({}));90 }9181 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 lines
modified:packages/gate/test/parse.test.ts+34 added-5 removed
41 unmodified lines
42 project: ask.project,43 }),44 });4546/** Dana's push to her own working fork (`<project>--me--dana`). */47const 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 });5556const main = RefNameText.make("refs/heads/main");5758// Each row is one push; parse answers with at most one refusal, the first59// rule the push breaks.
48 unmodified lines
108 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 lines
modified:packages/project/src/attention/budget.ts+2 added-1 removed
4 unmodified lines
5 * counted apart, and a project can see where its deciders' time goes.6 */7import type { Today } from "@repo/protocol/domain/decision";8import type { Policy } from "@repo/protocol/domain/policy";9import { sameHandle } from "@repo/protocol/ids";10import type { Handle } from "@repo/protocol/ids";11import { DateTime } from "effect";1213import type { BudgetDayRow } from "../project-store/rows.ts";
14 unmodified lines
28) => {29 const day = dayOf(now);3031 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 lines
modified:packages/project/src/attention/credits.ts+2 added-1 removed
9 unmodified lines
10 */11import type { Ask } from "@repo/protocol/domain/ask";12import type { LandingView } from "@repo/protocol/domain/landing";13import type { CreditSummary } from "@repo/protocol/domain/record";14import { sameHandle } from "@repo/protocol/ids";15import type { AskId, Handle } from "@repo/protocol/ids";16import { Array as Arr, Option, Order } from "effect";1717import { areaOf, sameHandle } from "./record.ts";18import { areaOf } from "./record.ts";1920/** What a person's credits are counted from. */21export interface CreditsInput {22 /**
63 unmodified lines
modified:packages/project/src/attention/decisions.ts+5 added-3 removed
7 unmodified lines
8import type { Evidence } from "@repo/protocol/domain/common";9import { DecisionSubject } from "@repo/protocol/domain/decision";10import type { Choice, Decision } from "@repo/protocol/domain/decision";11import type { Policy } from "@repo/protocol/domain/policy";12import { sameHandle } from "@repo/protocol/ids";13import type {14 DecisionId,15 Handle,16 ProjectName,
5 unmodified lines
22 UnknownDecision,23} from "@repo/protocol/refusal";24import { Array as Arr, DateTime, Option, Result } from "effect";2526import { ProjectEventInput } from "../events.ts";25import { AttentionEffect, AttentionEvent, platformHandle } from "./effects.ts";27import { AttentionEffect, platformHandle } from "./effects.ts";2829/** How a subject's deciders say yes, and no. */30interface Words {31 readonly no: Choice;
87 unmodified lines
119 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 lines
182 if (found === undefined) {183 return Result.fail(new UnknownDecision({ decision: input.id }));184 }185184 if (!found.deciders.includes(input.by)) {186 if (!found.deciders.some((each) => sameHandle(each, input.by))) {187 return Result.fail(new NotDecider({}));188 }189190 if (isClosed(found, input.now)) {
56 unmodified lines
modified:packages/project/src/attention/effects.ts+1 added-4 removed
10 unmodified lines
11import type { CommitSha, ProposalId } from "@repo/protocol/ids";12import { Data } from "effect";13import type { DateTime } from "effect";1415import type { ProjectEventInput } from "../project-store/rows.ts";15import type { ProjectEventInput } from "../events.ts";1617/** What the project service does after a proposal or decision moved, in order. */18export type AttentionEffect = Data.TaggedEnum<{19 /** Tell the project's watchers. */
9 unmodified lines
2930/** Constructors for attention's effects. */31export const AttentionEffect = Data.taggedEnum<AttentionEffect>();3233/** Constructors for the project events attention emits, before the store numbers them. */34export const AttentionEvent = Data.taggedEnum<ProjectEventInput>();3533/**34 * The platform's own handle: who `decided.by` names when nobody decided in35 * time and a decision took its default.36 */
1 unmodified line
modified:packages/project/src/attention/proposals.ts+6 added-2 removed
21 unmodified lines
22import type { Person } from "@repo/protocol/principal";23import { CapReached, Denounced, NotVouched } from "@repo/protocol/refusal";24import { Data, DateTime, Option, Result } from "effect";2526import { AttentionEffect, AttentionEvent } from "./effects.ts";26import { ProjectEventInput } from "../events.ts";27import { AttentionEffect } from "./effects.ts";2829/**30 * What every proposal command carries: the id the service minted, the31 * project, the person proposing, and what the service knows about them that
132 unmodified lines
164const 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 lines
modified:packages/project/src/attention/record.ts+1 added-8 removed
47 unmodified lines
48 readonly area: string;49 readonly atLeast: number;50}5152/**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. */53const personOf = (handle: Handle) => handle.toLowerCase();5458/** Whether two handles name one person: a vouch file's `Alice` is `alice`. */59export const sameHandle = (one: Handle, other: Handle): boolean =>60 personOf(one) === personOf(other);6155/**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 lines
modified:packages/project/src/attention/today.ts+2 added-1 removed
6 unmodified lines
7 */8import type { CreditRole } from "@repo/protocol/domain/credit";9import type { Decision, Today } from "@repo/protocol/domain/decision";10import type { LandingView } from "@repo/protocol/domain/landing";11import { sameHandle } from "@repo/protocol/ids";12import type { Handle } from "@repo/protocol/ids";13import { Array as Arr, DateTime, Order } from "effect";1415import type { Budget } from "./budget.ts";
61 unmodified lines
77 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 lines
modified:packages/project/src/attention/vouch.ts+2 added-1 removed
13 unmodified lines
14 */15import type { Ask } from "@repo/protocol/domain/ask";16import type { AskKind, ClaimRule } from "@repo/protocol/domain/kind";17import type { Policy } from "@repo/protocol/domain/policy";18import { sameHandle } from "@repo/protocol/ids";19import type { Handle } from "@repo/protocol/ids";20import { Denounced, NotVouched } from "@repo/protocol/refusal";21import { Array as Arr, DateTime, Match, Option, Order, Result } from "effect";2222import { meets, sameHandle } from "./record.ts";23import { meets } from "./record.ts";24import type { RecordEntry } from "./record.ts";2526/** Where a person stands with a project: vouched for, denounced, or neither. */27export type Standing = "vouched" | "denounced" | "unknown";
170 unmodified lines
modified:packages/project/src/lander/isogit.ts+1 added-7 removed
42 unmodified lines
43import type { Verdict } from "@repo/protocol/domain/answer";44import { CommitSha, LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";45import type { RepoName, RequestId } from "@repo/protocol/ids";46import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";47import { sdkVersion } from "@repo/rules/rules-evaluator";48import type { ConfigBundle } from "@repo/rules/rules-evaluator";49import { Array, Clock, DateTime, Effect, Layer, Option, Order } from "effect";50import {51 Errors,
19 unmodified lines
71const mainRef = RefName.make("refs/heads/main");7273const mainBranch = BranchName.make("main");7474/**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 */79const sdkVersion = "0.0.0";8075// How far back from main's tip a second land looks for the first one's commit.76const LOOKBACK = 16;7778// git's test for a binary file: a NUL among its first bytes.
911 unmodified lines
modified:packages/project/src/project-store/rows.ts+6 added-10 removed
53 unmodified lines
54export type ClaimRow = typeof ClaimRow.Type;5556/**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 */60export 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 lines
144 seq: Schema.Int,145});146147export type EventRow = typeof EventRow.Type;144145/** Drops a key from each member of a union, not from the union as a whole. */146type OmitEach<Union, Key extends PropertyKey> = Union extends unknown147 ? Omit<Union, Key>148 : never;149150/** An event before the store numbers it: every `ProjectEvent` but its `seq`. */151export type ProjectEventInput = OmitEach<ProjectEvent, "seq">;
modified:packages/project/src/claim.ts+2 added-12 removed
3 unmodified lines
4 * port: `now` is an argument, and what should happen next comes back as data5 * (`ClaimEffect`) for the project service to settle.6 */7import { ClaimView } from "@repo/protocol/domain/claim";8import type { ProjectEvent } from "@repo/protocol/domain/event";8import type { Policy } from "@repo/protocol/domain/policy";9import {10 AskId,11 CommitSha,
13 unmodified lines
25 NotVouched,26} from "@repo/protocol/refusal";27import { Array as Arr, Data, DateTime, Option, Result, Schema } from "effect";2829import { ProjectEventInput } from "./events.ts";3031/** What a claim holds while it lasts, and keeps once it ends. */32const claimFields = {33 ask: AskId,34 /** Main's landed commit when the claim was made. */
31 unmodified lines
6667/** A claim's fields, which `Live` and `Warned` hold and the ended states keep. */68export type Live = Omit<typeof ClaimState.cases.Live.Type, "_tag">;6969/** A project event before the store gives it its place in the sequence. */70type Unsequenced<Event> = Event extends ProjectEvent71 ? Omit<Event, "seq">72 : never;7374/** A project event without its `seq`, which the store assigns at commit. */75export type ProjectEventInput = Unsequenced<ProjectEvent>;7677/** Constructors for project events without their `seq`. */78export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();7970/**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 ask
391 unmodified lines
modified:packages/project/src/deciders.ts+6 added-12 removed
22 unmodified lines
23import type { CheckRunner } from "@repo/checks/check-runner";24import { pushStages, runGate } from "@repo/gate/gate";25import { scan } from "@repo/gate/stages/shape";26import { formatLanding } from "@repo/git/trailers";27import type { AnswerReceipt } from "@repo/protocol/domain/answer";27import type { AnswerReceipt, LandReceipt } from "@repo/protocol/domain/answer";28import type { Ask } from "@repo/protocol/domain/ask";29import type { Evidence } from "@repo/protocol/domain/common";30import type { Credit } from "@repo/protocol/domain/credit";31import { DecisionSubject } from "@repo/protocol/domain/decision";
14 unmodified lines
46 RepoName,47 RepoPath,48 RequestId,49 TreeSha,50 sameHandle,51} from "@repo/protocol/ids";52import type { CommitSha, ProjectName, Handle } from "@repo/protocol/ids";53import { Person } from "@repo/protocol/principal";54import type { Principal } from "@repo/protocol/principal";
43 unmodified lines
98 expireDecisions,99 openDecision,100} from "./attention/decisions.ts";101import type { Decided } from "./attention/decisions.ts";102import { AttentionEffect, platformHandle } from "./attention/effects.ts";103import {102 AttentionEffect,103 AttentionEvent,104 platformHandle,105} from "./attention/effects.ts";106import {104 expire as expireProposals,105 propose,106 ProposalCommand,107} from "./attention/proposals.ts";108import type { Proposed } from "./attention/proposals.ts";112import { recordOf, sameHandle } from "./attention/record.ts";109import { recordOf } from "./attention/record.ts";110import { today } from "./attention/today.ts";111import { standing } from "./attention/vouch.ts";112import { ClaimState } from "./claim.ts";113import { ProjectEventInput } from "./events.ts";114import { pushFacts } from "./facts.ts";115import { Lander, Rebuild } from "./lander.ts";116import type { ComposedFile } from "./lander.ts";117import {
9 unmodified lines
127 AnswerRow,128 BudgetDayRow,129 ClaimRow,130 OutboxRow,133 ProjectEventInput,131 ProjectRow,132} from "./project-store/rows.ts";133134/**
2 unmodified lines
137 * table that holds the method keys it by this constant.138 */139export const envSchemaMethod = "envShape";140144/** What a decider's land returns: an answer's receipt, without an ask. */145export type LandReceipt = Omit<AnswerReceipt, "ask">;146141/** The decider-facing methods of one project's service (spec §3.2's decider rows). */142export interface DeciderApi {143 /**144 * The project's env shape: the items its landed `.env.schema` declares,
646 unmodified lines
791 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 }));796797 const row = rowNow(h, writes);798799 if (Option.isSome(row)) {
1339 unmodified lines
modified:packages/project/src/events.ts+19 added-6 removed
3 unmodified lines
4 * the rows that made them, and each one also goes to the projection through5 * the outbox, so the front page hears every one.6 */7import type { Ask, AskListing } from "@repo/protocol/domain/ask";8import type { ProjectEvent as Event } from "@repo/protocol/domain/event";9import { ProjectEvent } from "@repo/protocol/domain/event";10import type { Outcome } from "@repo/protocol/domain/outcome";11import type { AskId, CommitSha, LandedSha } from "@repo/protocol/ids";11import { Effect, Schema } from "effect";12import { Data, Effect, Schema } from "effect";13import type { DateTime } from "effect";1414import { ProjectEventInput as EventInput } from "./claim.ts";15import type { ProjectEventInput } from "./project-store/rows.ts";15/** Drops a key from each member of a union, not from the union as a whole. */16type OmitEach<Union, Key extends PropertyKey> = Union extends unknown17 ? Omit<Union, Key>18 : never;1920/**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 */25export type ProjectEventInput = OmitEach<Event, "seq">;2627/** Constructors and matchers for project events before the store numbers them. */28export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();2930/** An ask as `listAsks`, the front page and `AskOpened` show it. */31export const listingOf = (ask: Ask): AskListing => {32 const listing = {33 ask: ask.id,
10 unmodified lines
44};4546/** An ask opened. */47export const askOpened = (ask: Ask, at: DateTime.Utc): ProjectEventInput =>35 EventInput.AskOpened({ ask: listingOf(ask), at });48 ProjectEventInput.AskOpened({ ask: listingOf(ask), at });4950/** An answer's landing closed its ask. */51export 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 });5657/** An answer was judged: its checks or its merge decided where it stands. */58export 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 });6465const asEvent = Schema.decodeUnknownEffect(Schema.toType(ProjectEvent));6667/**
11 unmodified lines
modified:packages/project/src/landing.ts+2 added-8 removed
7 unmodified lines
8import { AgentTrailer, Credit } from "@repo/protocol/domain/credit";9import type { CreditRole } from "@repo/protocol/domain/credit";10import type { Choice } from "@repo/protocol/domain/decision";11import { DecisionSubject } from "@repo/protocol/domain/decision";12import type { ProjectEvent } from "@repo/protocol/domain/event";12import { AskKind } from "@repo/protocol/domain/kind";13import { LandingView } from "@repo/protocol/domain/landing";14import { Outcome } from "@repo/protocol/domain/outcome";15import {
16 unmodified lines
32 Weakened,33} from "@repo/protocol/refusal";34import { Array, Data, DateTime, Duration, Match, Option, Schema } from "effect";3536import { ProjectEventInput } from "./events.ts";3738/** How many times a moved main may send an answer back to merge before it is refused as stale. */39export const maxRemerges = 3;4041/**
136 unmodified lines
178}>;179180export const LandingCommand = Data.taggedEnum<LandingCommand>();181181type WithoutSeq<E> = E extends ProjectEvent ? Omit<E, "seq"> : never;182183/** A project event before the store gives it its place in the sequence. */184export type ProjectEventInput = WithoutSeq<ProjectEvent>;185186export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();187182/** What the service runs for a landing: the transition only describes it. */183export type LandingEffect = Data.TaggedEnum<{184 Merge: {185 readonly base: CommitSha;
394 unmodified lines
modified:packages/project/src/project-store.ts+1 added-1 removed
1import type { CommitSha } from "@repo/protocol/ids";2import { Context } from "effect";3import type { Effect, Option, Schema } from "effect";45import type { ProjectEventInput } from "./events.ts";6import type {7 AnswerRow,8 AskRow,9 BudgetDayRow,
1 unmodified line
11 DecisionRow,12 EventRow,13 LandingRow,14 OutboxRow,14 ProjectEventInput,15 ProjectRow,16 ProposalRow,17 PushEventRow,18 RatchetRow,
95 unmodified lines
modified:packages/project/src/project.ts+7 added-19 removed
79 unmodified lines
80 LandedSha,81 RepoName,82 RepoPath,83 RequestId,84 sameHandle,85} from "@repo/protocol/ids";86import type {87 DecisionId,88 LaneName,
8 unmodified lines
97 IncompleteBrief,98 NotClaimed,99 NotDecider,100 NotRedFirst,100 NotVouched,101 ProjectExists,102 Refusal,103 StaleBase,104 TouchedJudge,
11 unmodified lines
116 PrivatePathInPublicTree,117 ReachedInternals,118 RepoBusy,119 Weakened,120 NotVouched,121} from "@repo/protocol/refusal";122import { Finishers } from "@repo/rules/finish";122import { RulesEvaluator } from "@repo/rules/rules-evaluator";123import { RulesEvaluator, sdkVersion } from "@repo/rules/rules-evaluator";124import {125 Array,126 Context,127 DateTime,
18 unmodified lines
146 Steps,147} from "./answer-runs.ts";148import type { AnswerQueue, AnswerRuns } from "./answer-runs.ts";149import { isStep } from "./answer-runs/steps.ts";149import { recordOf, sameHandle } from "./attention/record.ts";150import { recordOf } from "./attention/record.ts";151import { mayClaim, standing } from "./attention/vouch.ts";152import {153 ClaimCommand,154 ClaimEffect,
11 unmodified lines
166 isDecider,167} from "./deciders.ts";168import type { DeciderApi, Opening } from "./deciders.ts";169import { askClosed, askOpened, judged, listingOf, numbered } from "./events.ts";170import type { ProjectEventInput } from "./events.ts";171import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";172import type { MissingCommit } from "./facts.ts";173import { Lander, Rebuild } from "./lander.ts";174import type { ComposedFile } from "./lander.ts";
19 unmodified lines
194 AnswerRow,195 BudgetDayRow,196 ClaimRow,197 OutboxRow,196 ProjectEventInput,198 ProjectRow,199 PushEventRow,200} from "./project-store/rows.ts";201import type { Projection } from "./projection.ts";
19 unmodified lines
221 defaultValue: () => `https://${Brand.domain}`,222});223224/**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 */228const sdkVersion = "0.0.0";229230/**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 lines
409 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 lines
473 ],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 lines
modified:packages/project/test/attention/decisions.test.ts+16 added-8 removed
31 unmodified lines
32 openDecision,33} from "../../src/attention/decisions.ts";34import {35 AttentionEffect,36 AttentionEvent,36 platformHandle,37} from "../../src/attention/effects.ts";38import { ProjectEventInput } from "../../src/events.ts";3940const scenario = aProject({ deciders: ["alice", "dana"], people: ["bob"] });4142const alice = Handle.make("alice");
153 unmodified lines
196 },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 lines
213 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 lines
230 ).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 lines
247 ).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 lines
271 Result.succeed("decline"),272 ]);273 });274275 // 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 });282283 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 lines
370 ]);371372 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 lines
406 ],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 lines
modified:packages/project/test/attention/proposals.test.ts+3 added-5 removed
6 unmodified lines
7import { at } from "@repo/testkit/clock";8import { aProject, ids, sha, withAsk } from "@repo/testkit/scenarios";9import { DateTime, Option, Result } from "effect";1011import { AttentionEffect } from "../../src/attention/effects.ts";12import {12 AttentionEffect,13 AttentionEvent,14} from "../../src/attention/effects.ts";15import {13 expire,14 ProposalCommand,15 propose,16} from "../../src/attention/proposals.ts";17import { ProjectEventInput } from "../../src/events.ts";1819const scenario = aProject({ people: ["carol"] }).pipe(20 withAsk({ id: "parse-iso", territory: "packages/parser" })21);
62 unmodified lines
84 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 lines
modified:packages/project/test/attention/today.test.ts+14 added
90 unmodified lines
91 expect(page.budget).toStrictEqual(fresh);92 expect(page.decider).toBe(alice);93 });9495 it("shows a decider their decisions however sign-in cases the handle", () => {96 const page = todayFor({ decider: handle("ALICE"), decisions: eight });9798 expect(page.decisions).toStrictEqual([p1, p2, p3, p4, p5]);99 });100101 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 lines
301 used: 2,302 });303 });304305 it("counts what a decider spent under any casing of their handle", () => {306 const days = spendAll([{ decider: alice, now: thursday, on: "decision" }]);307308 expect(309 budgetFor(scenario.policy, handle("Alice"), days, thursday).used310 ).toBe(1);311 });312313 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 lines
modified:packages/project/test/claim.test.ts+1 added-1 removed
23 unmodified lines
24 ClaimCommand,25 ClaimEffect,26 ClaimState,27 forkName,28 ProjectEventInput,28 toView,29 transition,30} from "../src/claim.ts";31import { ProjectEventInput } from "../src/events.ts";3233const { Claim, Land, Push, Release, Tick } = ClaimCommand.cases;3435const HOUR = 3_600_000;
419 unmodified lines
modified:packages/project/test/landing.model.test.ts+1 added-1 removed
26 unmodified lines
27 Result,28 Schema,29} from "effect";3031import { ProjectEventInput } from "../src/events.ts";32import {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 lines
modified:packages/project/test/landing.test.ts+1 added-1 removed
21 unmodified lines
22 Weakened,23} from "@repo/protocol/refusal";24import { DateTime, Duration, Option, Schema } from "effect";2526import { ProjectEventInput } from "../src/events.ts";27import {28 backoff,29 enqueue,30 LandingCommand,
3 unmodified lines
34 maxRemerges,35 next as admitNext,36 outcomeOf,37 pendingEffects,37 ProjectEventInput,38 Request,39 settle,40 transition,41} from "../src/landing.ts";
722 unmodified lines
modified:packages/project/test/project-store.contract.ts+1 added-1 removed
10 unmodified lines
11} from "@repo/protocol/ids";12import { DateTime, Effect, Exit, Option, Schema, Struct } from "effect";13import type { Layer } from "effect";1415import type { ProjectEventInput } from "../src/events.ts";16import { ProjectStore } from "../src/project-store.ts";17import type { ProjectWrites } from "../src/project-store.ts";18import {19 AnswerRow,
7 unmodified lines
27 ProposalRow,28 PushEventRow,29 RatchetRow,30} from "../src/project-store/rows.ts";30import type { ProjectEventInput } from "../src/project-store/rows.ts";3132// 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 lines
modified:packages/protocol/src/domain/answer.ts+9 added-1 removed
1import { Schema } from "effect";1import { Schema, Struct } from "effect";23import {4 AreaName,5 AskId,
83 unmodified lines
89});9091export type AnswerReceipt = typeof AnswerReceipt.Type;9293/**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 */97export const LandReceipt = AnswerReceipt.mapFields(Struct.omit(["ask"]));9899export type LandReceipt = typeof LandReceipt.Type;100101/** One of a person's answers, as their status shows it. */102export const AnswerView = Schema.Struct({103 ask: AskId,104 at: Schema.DateTimeUtcFromString,
6 unmodified lines
modified:packages/protocol/src/domain/common.ts+18 added-1 removed
67 unmodified lines
68});6970export type Evidence = typeof Evidence.Type;7172/**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 */76export const ConfigFile = Schema.Struct({77 content: Schema.String,78 path: RepoPath,79});8081export type ConfigFile = typeof ConfigFile.Type;8283/** A count or span that must hold at least one: a cap, a budget, a race, a window. */84export const AtLeastOne = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));8586/** A count or span that may be zero but never less: a record's count, a delay. */87export const NoneOrMore = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));8889/** Where in the tree something points, when it points at one line. */90export const At = Schema.Struct({74 line: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),91 line: AtLeastOne,92 path: RepoPath,93});9495export type At = typeof At.Type;
modified:packages/protocol/src/domain/kind.ts+3 added-2 removed
1import { Schema } from "effect";23import { Handle, KindName } from "../ids.ts";4import { Strength } from "./check.ts";5import { AtLeastOne, NoneOrMore } from "./common.ts";67/** A field of an ask's brief that its kind can require. */8export const BriefField = Schema.Literals([9 "want",
24 unmodified lines
34 */35export 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 lines
55 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 lines
modified:packages/protocol/src/domain/policy.ts+11 added-9 removed
2 unmodified lines
34import { Handle, LandedSha, RepoPath } from "../ids.ts";5import { Ask } from "./ask.ts";6import { RatchetSpec } from "./check.ts";7import { Glob } from "./common.ts";7import { AtLeastOne, Glob, NoneOrMore } from "./common.ts";8import { AskKind } from "./kind.ts";9import { RunBlock } from "./run.ts";10import { Territory } from "./territory.ts";11
1 unmodified line
13const Source = Schema.Literals(["config", "defaults"]);1415/** How many decisions a decider takes a day, and how long one waits before its default. */16const Budget = Schema.Struct({17 decisionsPerDay: Schema.Int,18 expireDays: Schema.Int,17 decisionsPerDay: AtLeastOne,18 expireDays: AtLeastOne,19});2021/** How many proposals and claims one person may hold open at once. */22const Caps = Schema.Struct({23 claimsPerPerson: Schema.Int,24 proposalsPerPerson: Schema.Int,23 claimsPerPerson: AtLeastOne,24 /** `0` turns proposals off. */25 proposalsPerPerson: NoneOrMore,26});2728/** How long a claim may go without a push before it is warned, and before it lapses. */29const Claims = Schema.Struct({29 lapseAfterMs: Schema.Int,30 warnAfterMs: Schema.Int,30 lapseAfterMs: AtLeastOne,31 warnAfterMs: AtLeastOne,32});3334/** When a landing starts to count on a person's record, and how long it counts. */35const 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});4041/**42 * What a vouch gates: claims and sealed answers (`forCode`), everything
139 unmodified lines
modified:packages/protocol/src/contracts.ts+16 added-16 removed
1import { Context, Schema, Struct } from "effect";1import { Context, Schema } from "effect";2import { Rpc, RpcGroup, RpcSchema } from "effect/rpc";3import type { RpcClient, RpcClientError } from "effect/rpc";45import {
7 unmodified lines
13 SurfaceName,14 Surfaces,15 Visibility,16} from "./annotations.ts";17import { AnswerReceipt, AnswerView, Verdict } from "./domain/answer.ts";17import {18 AnswerReceipt,19 AnswerView,20 LandReceipt,21 Verdict,22} from "./domain/answer.ts";23import { Ask, AskListing, Reserve } from "./domain/ask.ts";24import { ClaimView } from "./domain/claim.ts";25import { ConfigFile } from "./domain/common.ts";26import { Choice, Decision, Today } from "./domain/decision.ts";27import { EnvSchemaView } from "./domain/env.ts";28import { ProjectEvent } from "./domain/event.ts";29import { FrontPageEntry, ProjectListing } from "./domain/front-page.ts";
10 unmodified lines
40 KindName,41 LandedSha,42 ProjectName,43 RepoName,38 RepoPath,44 RequestId,45} from "./ids.ts";46import { Authenticated } from "./principal.ts";47import {
89 unmodified lines
137 * input needs; this is the form `Tool.EmptyParams` takes.138 */139const NoPayload = Schema.Record(Schema.String, Schema.Never);140136/**137 * One file an ask or a proposal adds to the config folder: its path and its138 * text.139 */140const ConfigFile = Schema.Struct({ content: Schema.String, path: RepoPath });141142/**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 */146const LandReceipt = AnswerReceipt.mapFields(Struct.omit(["ask"]));147141// --- Reads ------------------------------------------------------------------142143export class ListProjects extends Rpc.make("listProjects", {144 payload: NoPayload,
293 unmodified lines
438 .annotate(Cli, { name: "ask open" })439 .annotate(Surfaces, servedOn.openAsk) {}440441export 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 lines
492 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 lines
modified:packages/protocol/src/ids.ts+9 added
237 unmodified lines
238 Schema.brand("Handle")239);240241export type Handle = typeof Handle.Type;242243/**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 */249export 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 lines
158 },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 lines
179 "UnknownProject",180 "UnknownDecision",181 "DecisionClosed",182 "NotDecider",183 "VerifierBlocked",184 "StaleBase",185 ],186 flags: "A",187 on: "RMCW",188 tag: "decide",
323 unmodified lines
modified:packages/protocol/test/domain.test.ts+44 added
41 unmodified lines
42 RepoName,43 RequestId,44 SuiteRoot,45 TreeSha,46 sameHandle,47} from "../src/ids.ts";48import { Anonymous, Person, Principal } from "../src/principal.ts";49import wire from "./fixtures/domain.json" with { type: "json" };50
123 unmodified lines
174 record: { countsAfterDays: 30, windowDays: 365 },175 vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },176 });177 });178179 // 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;182183 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 });204205 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});215216describe("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 });223224 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 lines
modified:packages/rules/src/rules-evaluator/bun.ts+13 added-9 removed
19 unmodified lines
20 statedWithoutCode,21} from "../config-folder.ts";22import { defaultPolicyInput } from "../defaults.ts";23import { Finishers, finishPolicy } from "../finish.ts";24import { RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";24import { factsOf, RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";25import type { ConfigBundle } from "../rules-evaluator.ts";26import { bunMain } from "./bun-main.ts";27import { bunPrelude, clockVariable } from "./bun-prelude.ts";28
271 unmodified lines
300 })301 );302303 return RulesEvaluator.of({304 call: ({ facts, modules, rule }) => {304 call: (input) => {305 const { modules, rule } = input;306 const project = projectModule(modules);307308 if (project === undefined) {309 return Effect.succeed(false);310 }311312 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 lines
modified:packages/rules/src/defaults.ts+14 added-56 removed
1import { FromCI, PolicyInput } from "@repo/protocol/domain/policy";1import { PolicyInput } from "@repo/protocol/domain/policy";2import { defaults, toPolicyInput } from "@repo/sdk";3import { Schema } from "effect";44// The Effect language service reads its directive's name anywhere in a5// source, string literals included, so the marker is joined at run time.6const effectDirective = ["@effect", "diagnostics"].join("-");75/**9 * The markers that disable a check when an answer adds them (spec §4.210 * `packages/gate`); a project may add its own.11 */12const 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];3031/**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 */41export 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});17export const defaultPolicyInput: PolicyInput = Schema.decodeSync(PolicyInput)(18 toPolicyInput(defaults)19);
modified:packages/rules/src/entry.ts+18 added-12 removed
1 unmodified line
2 * 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 */10import { Functions } from "@repo/sdk/functions";11import { Predicate } from "effect";12import type { Schema } from "effect";1314/**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 */21export type Definition = Schema.Json;2223/** A function-valued rule: called with the facts its caller passes. */
34 unmodified lines
58};5960const isRule = (value: unknown): value is Rule => Predicate.isFunction(value);6160/** 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 */66export 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 }7369 const found: unknown = Object.getOwnPropertyDescriptor(70 definition,71 rule72 )?.value;74 const carried = definition[Functions];7576 const found = Predicate.hasProperty(carried, rule)77 ? carried[rule]78 : undefined;7980 return isRule(found) ? found : undefined;81};
modified:packages/rules/src/finish.ts+42 added-3 removed
1 unmodified line
2import { FromCI, Policy } from "@repo/protocol/domain/policy";3import type { PolicyInput } from "@repo/protocol/domain/policy";4import { RunBlock } from "@repo/protocol/domain/run";5import type { LandedSha, RepoPath } from "@repo/protocol/ids";6import { packageDir } from "@repo/sdk";6import { Context, DateTime, Effect, Schema } from "effect";7import { Array as Arr, Context, DateTime, Effect, Schema } from "effect";89import { failedAt } from "./config-folder.ts";10import { RulesFailed } from "./rules-evaluator.ts";11import type { EvaluationFacts } from "./rules-evaluator.ts";
117 unmodified lines
129 ? { module: name, paths }130 : { module: name, paths, publicFiles: exports };131 });132133/** A glob with the package's folder written over the sdk's `{dir}`. */134const placed = (glob: string, folder: string) => {135 const written = glob.replaceAll(packageDir, folder).replace(/^\/+/u, "");136137 return written === "" ? "**" : written;138};139140/**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 */149const placedIn = (150 workspaces: EvaluationFacts["workspaces"],151 territory: PolicyInput["asks"][number]["territory"]152) => {153 const workspace = workspaces.find(({ name }) => name === territory.module);154155 if (156 workspace === undefined ||157 !territory.paths.some((glob) => glob.includes(packageDir))158 ) {159 return territory;160 }161162 const folder = folderOf(workspace.dir);163 const paths = Arr.map(territory.paths, (glob) => placed(glob, folder));164165 return territory.publicFiles !== undefined || workspace.exports.length === 0166 ? { ...territory, paths }167 : { ...territory, paths, publicFiles: workspace.exports };168};169170/** Fails when two asks share an id: an id names one ask, and one fork per claim. */171const distinctAsks = (asks: PolicyInput["asks"]) => {172 const seen = new Map<string, string>();173
17 unmodified lines
191192/**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 lines
221 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 lines
modified:packages/rules/src/rules-evaluator.ts+36 added-8 removed
1import type { Policy } from "@repo/protocol/domain/policy";2import type { LandedSha } from "@repo/protocol/ids";3import { Handle, ProjectName, RepoPath } from "@repo/protocol/ids";4import { Context, Schema } from "effect";5import type { Effect } from "effect";4import { ClaimantFacts, ProposalFacts } from "@repo/sdk/functions";5import { Context, Effect, Schema } from "effect";67/**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 lines
23});2425export type ConfigBundle = typeof ConfigBundle.Type;2627/**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 */32export { sdkVersion } from "@repo/sdk";3334/** One workspace package, as the repo's manifests declare it. */35const Workspace = Schema.Struct({36 /** Its folder, from the repo's root: `packages/parse`. */37 dir: Schema.String,
47 unmodified lines
8586export type RuleName = typeof RuleName.Type;8788/**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 */94export type RuleCall =95 | { readonly rule: "opensAlone"; readonly facts: ProposalFacts }96 | { readonly rule: "admit"; readonly facts: ClaimantFacts };9798/** A call's facts as JSON carries them into the sandbox. */99export 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);104105 // The facts were typed by the same schemas, so encoding them can't fail.106 return Effect.orDie(encoded);107};108109/**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 */115export 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 lines
modified:packages/rules/test/fixtures/cm/project.ts+10 added-4 removed
1import { Functions } from "@repo/sdk";23import data from "./project.json" with { type: "json" };45/**6 * The convex-merged design's example project (its §3), as the data the sdk's
2 unmodified lines
9 * 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 */14const project = Object.defineProperty({ ...data }, "opensAlone", {17const 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});2425export default project;
modified:packages/rules/test/evaluate.test.ts+125 added-30 removed
1 unmodified line
2import { assert, describe, expect, it } from "@effect/vitest";3import { CheckSpec } from "@repo/protocol/domain/check";4import { Policy } from "@repo/protocol/domain/policy";5import { RepoPath } from "@repo/protocol/ids";6import { ClaimantFacts, ProposalFacts } from "@repo/sdk";7import { Duration, Effect, Layer, Result, Schema } from "effect";89import { Finishers } from "../src/finish.ts";10import { RulesEvaluator } from "../src/rules-evaluator.ts";
11 unmodified lines
22 folder,23 now,24} from "./world.ts";2526const decodeProposal = Schema.decodeUnknownSync(ProposalFacts);2728const decodeClaimant = Schema.decodeUnknownSync(ClaimantFacts);2930/** A proposal for an ask of the example's `fixBug` kind, but its record. */31const fixBugProposal = {32 kind: "fixBug",33 proposer: "carol",34 territory: "@datekit/parse",35};3637/** A red-then-green check on one file, as `CheckSpec` encodes it. */38const redThenGreen = (path: string) =>39 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });40
140 unmodified lines
181 weakening: { markers: [".skip("] },182};183184/**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 */188const defaultsEncoded = {189 ...fromFacts,190 agents: "trailer",
11 unmodified lines
202 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};218219/** Evaluates a bundle at `at` with the shared facts, and encodes the policy. */220const evaluated = (modules: ConfigBundle) =>
205 unmodified lines
426 expect(failure.detail).toMatch(/x+the end$/u);427 }).pipe(Effect.provide(bunEvaluator()))428 );429430 // 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 });450451 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;455456 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 });468469 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 });482483 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 );493494 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 );507508 expect(stated).toStrictEqual({ ...defaultsEncoded, source: "config" });509 }).pipe(Effect.provide(bunEvaluator()))510 );511512 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");516442 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 });524445 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 });537538 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 lines
594 const evaluator = yield* RulesEvaluator;595596 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 lines
modified:packages/rules/test/finish.test.ts+59 added-3 removed
6 unmodified lines
7import { defaultPolicyInput } from "../src/defaults.ts";8import { finishPolicy } from "../src/finish.ts";9import { at, facts, finishers } from "./world.ts";1011/** An ask with the given id, declared in `file`. */12const askIn = (id: string, file: string) =>11/** The whole repo, as one module. */12const wholeRepo: (typeof AskInput.Encoded)["territory"] = {13 module: ".",14 paths: ["**"],15};1617/** An ask with the given id, declared in `file`, in `territory`. */18const 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 lines
29 }),30 file,31 id,32 kind: "fix",23 territory: { module: ".", paths: ["**"] },33 territory,34 });3536describe(finishPolicy, () => {37 it.effect("refuses a vouch file line that names no handle, by its line", () =>
32 unmodified lines
70 expect(failure.reason).toBe("decode");71 expect(failure.detail).toContain("a/dates.ask.ts");72 })73 );7475 // 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 });103104 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# Myr23Myr 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.45**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.67The 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:89- the concept: §3;
11 unmodified lines
21| # | 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) |3536## Fence3738`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 lines
modified:PROVENANCE.md+1 added
12 unmodified lines
13| `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`. |1920## Ideas, no code21
7 unmodified lines
modified:tsconfig.base.json+6 added-1 removed
157 unmodified lines
158 }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 line
167 "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 lines
modified:turbo.json+1 added
8 unmodified lines
9 "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