Close W3: an answer runs again after a wait, a stray main opens its own decision, merged trees reach the Checker, and AGENTS.md names the fences W3 built
Before adoption: this commit came in with the history the project adopted, so no landing records it.
W3 integration (399). Merged on main before this commit, in the index's order: group A (302, 303, 304, 305, 306, 307, 308, 309, 312, 313, 314, 315, 316) at fc79b02, 317 at 70930e7, 310 at 0d3d308, and 311 live at c430a13. This commit folds every issue's open Comments item, applied here test-first at the owning issue's seam or answered in its issue file and spec §8.4. - AnswerRunsWorkflow restarts an instance whose run ended (complete, errored, terminated) and leaves a running one alone (304 #2, 317 #8, 310 #8). A run ends whenever the answer waits, and the project starts the same request again; before, that start found the old instance and did nothing, so the answer hung. Test: project-do.test.ts (red by assertion: no restarts). - memoSteps replays as the Workflow engine does: a step whose retries are spent keeps its failure, and a replay dies without running it (313 #8). Test: step.test.ts (red: the body ran again). No program test relied on the old behaviour. - recordPush opens the StrayPush decision itself, in the same commit as the push event's row, for canonical main moved to anything but the landed SHA or a landing, a deleted main included (313 #1); OnPush's test double that stood in for it is gone, and its tests run on the real service. The initializer's first push and an import's adoption now write a landing row, so `landing(sha)` and OnPush know them as the platform's (313 #3); LandingView.parent is optional ("absent for the first adoption"; docs/reference regenerated). Adopting or reverting a deleted main changes nothing and logs an error (part of 313 #4). Tests: deciders.test.ts (one decision for an event reported twice, none for the first push or a landing; a deleted main decided either way moves nothing), red by assertion. - The sandbox Lander's merge pushes a commit of the merged tree (parents main and the head, dated at the epoch so a re-merge makes the same commit) to the fork's `<refs prefix>merge/<tree>`, and the platform mints a write token on the fork for it, never on canonical (212 #7, 304 #1, 306 #8, 314 #5, 315 #6). Before, an answer whose base was behind main had a merged tree no ref held, so its checks were VerifierBlocked. Tests: lander.test.ts (canonical untouched, the fork's merge ref holds the merged tree on main and the head) and sandbox-adapters.test.ts (read on canonical, write on the fork), each red first. - A landing's stored verdict says Landed at its SHA, not the stage it was judged at (311 #9). Test: project.test.ts step 5 (red: Checking). - Advanced.effects is RunnableEffect[], the NextStep subset that crosses the Project DO's boundary (302 #3); typecheck holds it. - RepoHostBinding revokes the day-long write token create, fork and importFrom hand back (any write token can force-push main, S1 #4), logging a revoke that fails without failing the call, and waits out CREATE_IN_PROGRESS and IMPORT_IN_PROGRESS (from 250 ms, eight tries) (302 #4). Tests: binding.test.ts (no live token left; a repo still being made is read), red first. - SdkBox kills a process whose lane ran past its limit: Effect aborts exec's signal only while exec is pending, so a timed-out lane kept running beside the next ones (315 #11). Test: box-sdk.test.ts (red: no kill). - protocol/render gains receiptLine, the push receipt's `remote:` line, moved from custody (303 #12, principle 3's one renderer); @repo/git/gateway exports gitRoute and plain, and the platform's git route uses them instead of a copy (303 #13); bearerToken reads the scheme in any case (RFC 7235, 305 #12); sameHandle's comment names the platform's accounts (316). Tests: render.test.ts, gateway.test.ts, authenticate.test.ts, each red by assertion first. - surfaces.ts no longer serves 305's placeholder authorization-server document: 316's provider answers that path before the surfaces in the deployed Worker, and oauth.test.ts tests the real document; the auth.test.ts case that pinned the placeholder went with it. - bytes:check's entry limit drops from 1,700,000 to 1,665,000, about 10% over the platform entry (1,513,262 bytes; sandbox 474,690). The planned trim did not happen, for a measured reason: Wrangler's esbuild build has no code splitting, so a dynamic import() is inlined into the entry (a probe Worker whose only code is `await import("yaml")` builds to one 259,900-byte file); isomorphic-git and pako serve the binding's smart-HTTP pushes on the request path, and yaml the run-block finder at each policy refresh. Spec §8.3 O3 records it. - AGENTS.md "Held by": principle 2 (env decoded once in platform.ts; bindings.test.ts), 6 (the composition in ports.ts; bindings and worker-init tests), 7 (no private namespace in the platform's Env; the Checker's no-snapshot-after-held-back test), 8 (the Answer replay, OnPush dedupe and request-id convergence tests; one push deduped across gateway and OnPush stays "No fence yet"), 11 (infra/deploy.ts with deploy and smoke tests), 12 (project-do.test.ts). The agents-table test passes. - PROVENANCE.md: 307's mulberry32 row for packages/rules/src/prelude.ts; ideas from Rat Stack for the rate-limit service (312) and the Loader binding's shape (307). No new licence. - debt.baseline.json unchanged (oxlint-disable 6, @effect-diagnostics 2, the sum of the group's named escapes). - Answered, not applied, each with its reason in spec §8.4: a replay of a spent land step dies (narrow; record Busy as a value, as OnPush's settle does); one push deduped by (repo, sha) across gateway and OnPush (313 #2); putting a deleted main back (313 #4); the gateway locks the body before admit (303 #1, works as is); rules' /worker repeating /bun (307 #4); the evaluation clock (307 #5: RepoHost commits carry no time); the mirror without a lease (306 #12); the isogit fallback is not live-ready. Forwarded to W4 404, 407, 417, 418, 419, W5 501, 503, 504, 510, 513, 514, W6 605, 611, 612 and W8 808; W4 407, 417 and 418's territories now name answer/program.ts and answer/lanes.ts, where 304 put the slots. - Human steps still open: 311's test resources on Cloudflare need the user's OK to delete (seven w3live-* projects and their forks, scratch-onpush-muykseuk, the S8B_PROBE secret on platform-dev-oscabriel, the test account w3tester-muyk9zdx). The optional Google sign-in (H4, W4 419) needs a client whose redirect URI is the dev stage's /oauth/google/callback. - bun run fix && bun run verify green: config 743 tests, protocol 319, project 302, platform 245, checks 169, artifacts 108 (+12 live skipped), gate 105, rules 54, testkit 51, sandbox 45, git 32; gen:check, imports:check, debt and brand:check pass.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
39 files+387 added−271 removed
- tests:+153 added−116 removed
- other:+234 added−155 removed
Provenance
- Commit
cb9b01d- Tree
313f8e4- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
c430a13
39 files changed+387 added−271 removed
This commit is too large to show whole: its files are listed by path, without their changes.
modified:apps/platform/src/adapters/answer-runs-workflow.ts+35 added-4 removed
5 unmodified lines6 * in-process `queue` is not used here.7 *8 * Starting twice is starting once (principle 8): an instance with the id9 * already exists, so `create` refuses, and the adapter takes the instance it10- * finds instead. Any other failure is a defect: the outbox row that asked11- * for the start stays, and the project's next alarm runs it again.10+ * finds instead. A run ends whenever the answer waits (the landing slot, a11+ * finish, a decision, a retry), and the project starts the same request12+ * again once it can go on (W3 304 #2), so an instance whose run has ended13+ * (complete, errored or terminated) is restarted from its first step; each14+ * step re-reads the run from the DO, so a fresh run picks up where the15+ * answer stands. An instance still running is left alone. Any other failure16+ * is a defect: the outbox row that asked for the start stays, and the17+ * project's next alarm runs it again.18 */19 import { AnswerRuns } from "@repo/project/answer-runs";20 import type { ProjectName } from "@repo/protocol/ids";21 import { Effect, Layer, Schema } from "effect";22 23 import { AnswerParams } from "../answer-runs.ts";24 25+/** The part of a Workflow instance the adapter uses. */26+export interface AnswerInstance {27+ readonly id: string;28+ readonly restart: () => Promise<void>;29+ readonly status: () => Promise<{ readonly status: InstanceStatus["status"] }>;30+}31+32 /** The part of the `Answer` Workflow binding the adapter uses. */33 export interface AnswerWorkflow {34 readonly create: (options: {35 readonly id: string;36 readonly params: typeof AnswerParams.Encoded;37 }) => Promise<{ readonly id: string }>;25- readonly get: (id: string) => Promise<{ readonly id: string }>;38+ readonly get: (id: string) => Promise<AnswerInstance>;39 }40 41 const encodeParams = Schema.encodeEffect(AnswerParams);42 43+/** The states an instance's run has ended in, so a start must run it again. */44+const ended: ReadonlySet<InstanceStatus["status"]> = new Set([45+ "complete",46+ "errored",47+ "terminated",48+]);49+50+/** Restarts the instance when its run has ended; a running one is left alone. */51+const runAgain = (instance: AnswerInstance) =>52+ Effect.gen(function* () {53+ const { status } = yield* Effect.tryPromise(() => instance.status());54+55+ if (ended.has(status)) {56+ yield* Effect.tryPromise(() => instance.restart());57+ }58+ });59+60 export const AnswerRunsWorkflow = (61 workflow: AnswerWorkflow,62 project: ProjectName63 ): Layer.Layer<AnswerRuns> =>9 unmodified lines73 ).pipe(74 // The id is taken: the run was started before.75 Effect.catch((error) =>76 Effect.tryPromise(() => workflow.get(requestId)).pipe(47- Effect.mapError(() => error)77+ Effect.mapError(() => error),78+ Effect.flatMap(runAgain)79 )80 )81 );82 }).pipe(Effect.orDie),2 unmodified linesmodified:apps/platform/src/adapters/custody.ts+2 added-31 removed
26 unmodified lines27 * as `<cli> submit`) and the pusher reads that it is being checked. The28 * gate's later stages never run inside the push (spec D5).29 */30 import type { RepoName } from "@repo/artifacts/repo-host";31-import { Brand } from "@repo/brand";31 import { Custody } from "@repo/git/custody";32 import type { Command } from "@repo/git/custody";33 import type { ProjectApi } from "@repo/project/project";34 import { Projects } from "@repo/project/projects";36-import type { AnswerReceipt } from "@repo/protocol/domain/answer";37-import { Outcome } from "@repo/protocol/domain/outcome";35 import { RequestId, sameHandle } from "@repo/protocol/ids";36 import type { AskId, CommitSha, Handle, ProjectName } from "@repo/protocol/ids";37 import { Principal } from "@repo/protocol/principal";38 import type { Person } from "@repo/protocol/principal";39 import { ClaimLapsed, DirectPush, NotClaimed } from "@repo/protocol/refusal";40 import type { Refusal } from "@repo/protocol/refusal";41+import { receiptLine } from "@repo/protocol/render";42 import { Array, Effect, Option, Result } from "effect";43 44 import { RepoKind } from "../repo-names.ts";45 2 unmodified lines48 49 /** Says a line to the pusher, as a `remote:` line of git's output. */50 export type Notice = (line: string) => Effect.Effect<void>;51 54-const short = (sha: string) => sha.slice(0, 7);55-52 /**53 * The request a push to a claim's fork answers with: it names the head and54 * the pusher, so two people pushing one commit make two requests. A request55 * id holds 64 characters, so the head comes first and is never cut: a long16 unmodified lines72 (command) =>73 Option.map(command.to, (head) => ({ from: command.from, head }))74 );75 80-/** What the pusher reads of the answer the push offered, or the refusals it came to. */81-const receiptSays = (82- receipt: AnswerReceipt83-): Result.Result<string, readonly Refusal[]> => {84- const at = `${receipt.ask} at ${short(receipt.head)}`;85- const follow = `follow with ${Brand.cli} status`;86-87- return Outcome.match<Result.Result<string, readonly Refusal[]>>(88- receipt.outcome,89- {90- AwaitingDecision: ({ decision }) =>91- Result.succeed(`${at} waits on decision ${decision}; ${follow}`),92- AwaitingFinish: () =>93- Result.succeed(94- `${at} passed and waits for a decider's finish; ${follow}`95- ),96- Checking: () => Result.succeed(`checking ${at}; ${follow}`),97- Landed: ({ sha }) => Result.succeed(`${at} landed as ${short(sha)}`),98- Refused: ({ refusals }) => Result.fail(refusals),99- WaitingOnParent: ({ ask }) =>100- Result.succeed(`${at} passed and waits for ${ask} to land; ${follow}`),101- }102- );103-};104-76 /** Runs `judge` against the project; a project never made refuses the push. */77 const against = (78 projects: Projects["Service"],79 project: ProjectName,132 unmodified lines212 if (Result.isFailure(submitted)) {213 return [submitted.failure];214 }215 245- return yield* Result.match(receiptSays(submitted.success), {216+ return yield* Result.match(receiptLine(submitted.success), {217 onFailure: Effect.succeed,218 onSuccess: (line) => Effect.as(input.notice(line), []),219 });220 });83 unmodified linesmodified:apps/platform/src/adapters/lander-sandbox.ts+6 added-3 removed
1 /**2 * `Lander` over the sandbox Worker (spec §4.3, D6): each job goes to the3 * trusted Lander container through the `SANDBOX` service binding, with the4- * fewest tokens it needs. Reads take read tokens: a merge on canonical and5- * the fork, a bundle on canonical. A write token on canonical goes only to4+ * fewest tokens it needs. Reads take read tokens: a merge on canonical, a5+ * bundle on canonical. A merge's write token is on the answer's fork alone,6+ * for the merged commit the Checker fetches. A write token on canonical goes only to7 * `land`, which moves `main` with a non-force compare-and-swap, and to8 * `compose`, which pushes its compose ref alone; never to a Checker, never9 * outside the platform's Workers (S1 change 2). The outcome comes back as10 * the port's own types or its refusals: `StaleBase`, `RepoBusy`,75 unmodified lines86 landing(sandbox, { fork: forkRemote, job, main })87 ),88 })89 ).pipe(Effect.provideService(RepoHost, host)),90+ // The merged commit goes to the fork, for the Checker: a write token91+ // there, never on canonical (W3 304 #1).92 merge: (job) =>93 withRemote("merge", read(job.repo), (main) =>91- withRemote("merge", read(job.fork), (fork) =>94+ withRemote("merge", write(job.fork), (fork) =>95 sandboxJob({96 exit: MergeExit,97 job: { fork, job, main },98 method: "merge",9 unmodified linesmodified:apps/platform/src/workflows/step.ts+44 added-12 removed
37 unmodified lines38 {39 /**40 * Runs `effect` once per (instance, name); a replay returns the recorded41 * value, decoded with `schema`. A failure is retried per `retry` (the42- * engine's default without one), records nothing, and, once the retries43- * are spent, fails the step with the last failure.42+ * engine's default without one), records no value, and, once the43+ * retries are spent, fails the step with the last failure. A replay of44+ * a spent step dies: the engine keeps only an error, not the typed45+ * failure, so a program that must survive one records its outcome as a46+ * value in a step of its own (OnPush's `settle`).47 */48 readonly step: <A, I, E, R>(49 name: string,50 schema: Schema.Codec<A, I>,61 unmodified lines112 */113 export const workflowSteps = (steps: WorkflowSteps): Layer.Layer<StepRunner> =>114 Layer.succeed(StepRunner, StepRunner.of({ step: durableStep(steps) }));115 116+/** What the in-memory steps keep per name: a step's value, or its last failure. */117+interface MemoRecords {118+ readonly values: Ref.Ref<ReadonlyMap<string, Schema.Json>>;119+ readonly failures: Ref.Ref<ReadonlyMap<string, unknown>>;120+}121+122 /** One step over an in-memory record of steps, keyed by name. */123 const memoStep =115- (records: Ref.Ref<ReadonlyMap<string, Schema.Json>>) =>124+ ({ failures, values }: MemoRecords) =>125 <A, I, E, R>(126 name: string,127 schema: Schema.Codec<A, I>,128 effect: Effect.Effect<A, E, R>,129 retry?: StepRetry130 ): Effect.Effect<A, E, R> =>131 Effect.gen(function* () {132 const json = Schema.toCodecJson(schema);124- const kept = (yield* Ref.get(records)).get(name);133+ const kept = (yield* Ref.get(values)).get(name);134 135 if (kept !== undefined) {136 return yield* Effect.orDie(Schema.decodeEffect(json)(kept));137 }138 139+ // The engine throws a spent step's kept failure again without running140+ // it, and no process in a replay saw the typed failure (W3 313 #8).141+ const spent = (yield* Ref.get(failures)).get(name);142+143+ if (spent !== undefined) {144+ return yield* Effect.die(spent);145+ }146+130- const value = yield* Effect.retry(effect, { times: retry?.limit ?? 0 });147+ const value = yield* Effect.retry(effect, {148+ times: retry?.limit ?? 0,149+ }).pipe(150+ Effect.tapError((failure) =>151+ Ref.update(failures, (all) => new Map(all).set(name, failure))152+ )153+ );154+155 const encoded = yield* Effect.orDie(Schema.encodeEffect(json)(value));156 133- yield* Ref.update(records, (all) => new Map(all).set(name, encoded));157+ yield* Ref.update(values, (all) => new Map(all).set(name, encoded));158 159 return yield* Effect.orDie(Schema.decodeEffect(json)(encoded));160 });161 162 /**139- * Steps in memory, for tests: the layer keeps one record per step name for140- * as long as the returned layer lives, so running a program twice over it141- * replays the second time. A failed step records nothing and is retried up142- * to its limit, without waiting.163+ * Steps in memory, for tests, replaying as the engine does: the layer keeps164+ * one record per step name for as long as the returned layer lives, so165+ * running a program twice over it replays the second time. A failed step is166+ * retried up to its limit, without waiting; once its retries are spent it167+ * fails with its last failure, and a replay dies without running it, as a168+ * replay over `workflowSteps` does when the engine throws the failure it169+ * kept.170 */171 export const memoSteps = (): Effect.Effect<Layer.Layer<StepRunner>> =>145- Effect.map(Ref.make<ReadonlyMap<string, Schema.Json>>(new Map()), (records) =>146- Layer.succeed(StepRunner, StepRunner.of({ step: memoStep(records) }))172+ Effect.map(173+ Effect.all({174+ failures: Ref.make<ReadonlyMap<string, unknown>>(new Map()),175+ values: Ref.make<ReadonlyMap<string, Schema.Json>>(new Map()),176+ }),177+ (records) =>178+ Layer.succeed(StepRunner, StepRunner.of({ step: memoStep(records) }))179 );modified:apps/platform/src/git.ts+8 added-23 removed
12 unmodified lines13 * the upstream adds the platform's own.14 */15 import { Brand } from "@repo/brand";16 import { Custody } from "@repo/git/custody";17-import { gateway } from "@repo/git/gateway";17+import { gateway, gitRoute, plain } from "@repo/git/gateway";18 import { concat, packetAt, pkt, utf8 } from "@repo/git/pkt-line";19 import type { Upstream } from "@repo/git/upstream";20 import type { Projects } from "@repo/project/projects";21 import { RepoName } from "@repo/protocol/ids";7 unmodified lines29 30 /** What serving git needs: who is calling, their projects, and the git server behind. */31 export type GitServices = Sessions | Projects | Upstream;32 33-const ROUTE =34- /^\/(?<name>[A-Za-z0-9._-]+?)(?:\.git)?\/(?<endpoint>info\/refs|git-upload-pack|git-receive-pack)$/u;35-33 /** A push reads `info/refs` for receive-pack, then posts to it; everything else reads. */34 const writes = (endpoint: string, url: URL) =>35 endpoint === "git-receive-pack" ||36 (endpoint === "info/refs" &&37 url.searchParams.get("service") === "git-receive-pack");38 39 const RESULT = "application/x-git-receive-pack-result";40 44-const plain = (45- status: number,46- text: string,47- headers: Readonly<Record<string, string>> = {}48-) =>49- new Response(`${text}\n`, {50- headers: { "content-type": "text/plain; charset=utf-8", ...headers },51- status,52- });53-41 /**42 * git asks its credential helper for a password only after a 401 that names43 * Basic; the helper answers with the person's platform token.44 */109 unmodified lines154 /** The response to a git request, if `request` is one the gateway serves. */155 export const serveGit = (156 request: Request157 ): Option.Option<Effect.Effect<Response, never, GitServices>> =>171- Option.map(172- Option.fromNullishOr(ROUTE.exec(new URL(request.url).pathname)?.groups),173- ({ endpoint = "", name = "" }) =>174- Effect.flatMap(principalOf(request.headers), (principal) =>175- Option.match(principal, {176- onNone: () => Effect.succeed(signIn("that token is not one we know")),177- onSome: (known) => serve(request, { endpoint, name }, known),178- })179- )158+ Option.map(gitRoute(new URL(request.url).pathname), ({ endpoint, name }) =>159+ Effect.flatMap(principalOf(request.headers), (principal) =>160+ Option.match(principal, {161+ onNone: () => Effect.succeed(signIn("that token is not one we know")),162+ onSome: (known) => serve(request, { endpoint, name }, known),163+ })164+ )165 );modified:apps/platform/src/surfaces.ts+11 added-32 removed
92 unmodified lines93 resource: origin,94 });95 96 /**97- * The platform as an OAuth authorization server (RFC 8414), until W3 316's98- * provider answers this path itself: the endpoints it mounts, PKCE with99- * S256 only, and public clients.100- */101-const authorizationServerMetadata = (origin: string) => ({102- authorization_endpoint: `${origin}/authorize`,103- code_challenge_methods_supported: ["S256"],104- grant_types_supported: ["authorization_code", "refresh_token"],105- issuer: origin,106- response_types_supported: ["code"],107- token_endpoint: `${origin}/token`,108- token_endpoint_auth_methods_supported: ["none"],109-});110-111-/**97 * A 401 for `request`: it asks for a bearer token and names where to learn98 * how to get one (RFC 9728 §5.1, which MCP's authorization requires). Its99 * `error` is `invalid_token` only for a bearer token the platform does not100 * know; a request with no credential, or one of another scheme, gets no171 unmodified lines272 );273 })274 );275 291-/** The two OAuth discovery documents, each by its path. */292-const DISCOVERY_DOCUMENTS = [293- [PROTECTED_RESOURCE_PATH, protectedResourceMetadata],294- ["/.well-known/oauth-authorization-server", authorizationServerMetadata],295-] as const;296-276 /**298- * The two OAuth discovery documents, answered to anyone: where a client299- * learns that the platform is its own authorization server.277+ * The protected-resource document (RFC 9728), answered to anyone: where a278+ * client learns that the platform is its own authorization server. The279+ * authorization server's document is the sign-in provider's, which answers280+ * its path before the surfaces see it (`auth/provider.ts`, W3 316).281 */282 const discovery = HttpRouter.use((router) =>302- Effect.gen(function* () {303- for (const [path, document] of DISCOVERY_DOCUMENTS) {304- yield* router.add("GET", path, (request) =>305- Effect.succeed(306- HttpServerResponse.jsonUnsafe(document(originOf(request)))307- )308- );309- }310- })283+ router.add("GET", PROTECTED_RESOURCE_PATH, (request) =>284+ Effect.succeed(285+ HttpServerResponse.jsonUnsafe(286+ protectedResourceMetadata(originOf(request))287+ )288+ )289+ )290 );291 292 /** A git request, as the gateway answers it; 404 for a path it does not serve. */293 const toGateway = (request: HttpServerRequest.HttpServerRequest) =>43 unmodified linesmodified:apps/platform/test/workflows/on-push.test.ts+2 added-65 removed
4 unmodified lines5 import { AlarmsMemory } from "@repo/project/alarms/memory";6 import { AnswerRuns } from "@repo/project/answer-runs";7 import { Lander } from "@repo/project/lander";8 import { projectService } from "@repo/project/project";9-import type { ProjectApi, PushReport } from "@repo/project/project";9+import type { ProjectApi } from "@repo/project/project";10 import { ProjectStore } from "@repo/project/project-store";11 import { ProjectStoreMemory } from "@repo/project/project-store/memory";12 import { ProjectionMemory } from "@repo/project/projection/memory";13 import { Projects } from "@repo/project/projects";3 unmodified lines17 import { Policy } from "@repo/protocol/domain/policy";18 import {19 AskId,20 CommitSha,21- DecisionId,21 Handle,22 LandedSha,23 ProjectName,24 RepoName,122 unmodified lines147 const answerHead = sha("datekit:answer");148 149 const canonical = RepoKind.Canonical({ project: datekit });150 152-const canonicalRepo = RepoName.make(datekit);153-151 const bobsFork = RepoKind.ClaimFork({152 ask: parseIso,153 handle: Handle.make("bob"),154 project: datekit,227 unmodified lines382 : Effect.fail(new UnknownProject({ project })),383 })384 );385 389-/**390- * `api` whose `recordPush` of a push to canonical `main` records the push391- * event and opens a `StrayPush` decision, default revert, in one commit, so392- * the same event recorded twice opens one decision. That is the DO's part393- * 313 needs (its issue's Comments): W2's service runs the gate over such a394- * push and opens nothing, so this test stands in for it, writing the395- * decision as `packages/project/test/deciders.test.ts` does.396- */397-const openingStrays = (api: ProjectApi) =>398- Effect.gen(function* () {399- const store = yield* ProjectStore;400-401- const open = (report: PushReport) =>402- Effect.gen(function* () {403- const now = yield* DateTime.now;404- const { decisions } = yield* store.load();405- const number = String(decisions.length + 1).padStart(6, "0");406-407- yield* store.commit({408- decisions: [409- {410- deciders: [scenario.initializer],411- default: "revert",412- evidence: [],413- expiresAt: DateTime.add(now, { days: 14 }),414- id: DecisionId.make(`dec-${number}`),415- openedAt: now,416- project: datekit,417- subject: DecisionSubject.cases.StrayPush.make({418- after: report.after,419- before: Option.getOrElse(report.before, () => ZeroSha),420- ref: RefNameText.make(report.ref),421- }),422- },423- ],424- pushEvents: [425- {426- after: report.after,427- at: now,428- eventId: report.eventId,429- ref: report.ref,430- repo: report.repo,431- ...Option.match(report.before, {432- onNone: () => ({}),433- onSome: (before) => ({ before }),434- }),435- },436- ],437- });438-439- return [];440- });441-442- return {443- ...api,444- recordPush: (report: PushReport) =>445- report.repo === canonicalRepo ? open(report) : api.recordPush(report),446- } satisfies ProjectApi;447- });448-386 /** datekit's service over its seeded store, and `Projects` holding it, at noon. */387 const world = Effect.gen(function* () {388 yield* advanceTo("2026-10-07T12:00:00Z");389 yield* seeded;390 454- const api = yield* openingStrays(yield* projectService(datekit));391+ const api = yield* projectService(datekit);392 393 return { api, projects: projectsOf(api), store: yield* ProjectStore };394 }).pipe(Effect.provide(ports));395 416 unmodified linesmodified:apps/platform/test/auth.test.ts-20 removed
99 unmodified lines100 })101 );102 103 it.effect(104- "answers the authorization server's document from a placeholder until sign-in mounts its own",105- () =>106- Effect.gen(function* () {107- const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));108-109- const response = yield* fetch(110- new Request(`${origin}/.well-known/oauth-authorization-server`)111- );112-113- expect(response.status).toBe(200);114- expect(yield* Effect.promise(() => response.json())).toMatchObject({115- authorization_endpoint: `${origin}/authorize`,116- code_challenge_methods_supported: ["S256"],117- issuer: origin,118- token_endpoint: `${origin}/token`,119- });120- })121- );122-123- it.effect(104 "never turns away /health or the sign-in paths, whatever credential they carry",105 () =>106 Effect.gen(function* () {107 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));378 unmodified linesmodified:apps/platform/test/project-do.fixtures.ts+34 added-3 removed
165 unmodified lines166 SetAlarms,167 { readonly all: Effect.Effect<readonly number[]> }168 >()("test/SetAlarms") {}169 170-/** Every `Answer` Workflow instance made, in order, and how many creates were tried. */170+/** How an `Answer` Workflow instance stands, as its `status()` reports it. */171+export type InstanceState = Awaited<172+ ReturnType<Awaited<ReturnType<AnswerWorkflow["get"]>>["status"]>173+>["status"];174+175+/**176+ * Every `Answer` Workflow instance made, in order, how many creates were177+ * tried, and every restart asked for; `end` moves an instance to a state178+ * the engine would (its run completed, errored or was terminated).179+ */180 export class Instances extends Context.Service<181 Instances,182 {183+ readonly end: (id: string, state: InstanceState) => Effect.Effect<void>;184 readonly made: Effect.Effect<185 readonly {186 readonly id: string;187 readonly params: typeof AnswerParams.Encoded;188 }[]189 >;190+ readonly restarts: Effect.Effect<readonly string[]>;191 readonly tries: Effect.Effect<number>;192 }193 >()("test/Instances") {}194 90 unmodified lines285 );286 287 /**288 * The `Answer` Workflow binding: an instance per id, made once. Like the278- * real one, `create` refuses an id it has, and `get` finds it.289+ * real one, `create` refuses an id it has, `get` finds it, an instance runs290+ * once made, and `restart` runs it again from its first step.291 */292 export const answerWorkflow = () => {293 const made = new Map<string, typeof AnswerParams.Encoded>();294+ const states = new Map<string, InstanceState>();295 const tries: string[] = [];296+ const restarts: string[] = [];297 298+ const instance = (id: string) => ({299+ id,300+ restart: () => {301+ restarts.push(id);302+ states.set(id, "running");303+304+ return Promise.resolve();305+ },306+ status: () => Promise.resolve({ status: states.get(id) ?? "running" }),307+ });308+309 const workflow: AnswerWorkflow = {310 create: ({ id, params }) => {311 tries.push(id);312 1 unmodified line314 return Promise.reject(new Error(`instance ${id} already exists`));315 }316 317 made.set(id, params);318+ states.set(id, "running");319 320 return Promise.resolve({ id });321 },322 get: (id) =>323 made.has(id)298- ? Promise.resolve({ id })324+ ? Promise.resolve(instance(id))325 : Promise.reject(new Error(`no instance ${id}`)),326 };327 328 const instances = Instances.of({329+ end: (id, state) =>330+ Effect.sync(() => {331+ states.set(id, state);332+ }),333 made: Effect.sync(() => [...made].map(([id, params]) => ({ id, params }))),334+ restarts: Effect.sync(() => [...restarts]),335 tries: Effect.sync(() => tries.length),336 });337 338 return { instances, workflow };136 unmodified linesmodified:apps/platform/test/project-do.test.ts+31 added
183 unmodified lines184 })185 );186 187 it.effect(188+ "runs an instance again when its run has ended, and leaves a live one alone",189+ () =>190+ Effect.gen(function* () {191+ const { instances, workflow } = answerWorkflow();192+ const live = RequestId.make("req-live0001");193+194+ const ended = [195+ RequestId.make("req-done0001"),196+ RequestId.make("req-fail0001"),197+ RequestId.make("req-stop0001"),198+ ] as const;199+200+ const runs = yield* AnswerRuns.pipe(201+ Effect.provide(AnswerRunsWorkflow(workflow, project))202+ );203+204+ yield* Effect.forEach([live, ...ended], (id) => runs.start(id, queue));205+ yield* instances.end(live, "waiting");206+ yield* instances.end(ended[0], "complete");207+ yield* instances.end(ended[1], "errored");208+ yield* instances.end(ended[2], "terminated");209+ yield* Effect.forEach([live, ...ended], (id) => runs.start(id, queue));210+211+ expect({212+ made: (yield* instances.made).length,213+ restarts: yield* instances.restarts,214+ }).toStrictEqual({ made: 4, restarts: [...ended] });215+ })216+ );217+218+ it.effect(219 "dies when the Workflow can neither make nor find the instance",220 () =>221 Effect.gen(function* () {222 const runs = yield* AnswerRuns.pipe(19 unmodified linesmodified:apps/platform/test/sandbox-adapters.test.ts+2 added-2 removed
410 unmodified lines411 });412 413 describe("the sandbox Lander", () => {414 it.effect(415- "merges with read tokens on canonical and the fork, and nothing more",415+ "merges with a read token on canonical and a write token on the fork, for the merged commit's ref, and nothing more",416 () =>417 Effect.gen(function* () {418 const { host, lander, minted, seen } = yield* world();419 1 unmodified line421 Exit.succeed(merged)422 );423 expect(mintsOf(minted)).toStrictEqual([424 { repo: canonical, scope: "read" },425- { repo: fork, scope: "read" },425+ { repo: fork, scope: "write" },426 ]);427 expect(428 seen.merge.map((wire) => ({429 fork: opened(wire.fork),317 unmodified linesmodified:apps/platform/test/step.test.ts+13 added-12 removed
139 unmodified lines140 })141 );142 143 it.effect(144- "records nothing for a step that failed, so the next run tries again",144+ "keeps a step that failed past its retries failed: a replay does not run it again, and dies as the engine's does",145 () =>146 Effect.gen(function* () {147 const steps = yield* memoSteps();148 const runs = yield* Ref.make(0);149 const stale = new StaleBase({ base: sha, conflicts: [], main: sha });150 151- const failing = StepRunner.use(({ step }) =>151+ const run = StepRunner.use(({ step }) =>152 step(153 "land#1",154 Landing,155 Effect.andThen(156 Ref.update(runs, (n) => n + 1),157 Effect.fail(stale)158- )158+ ),159+ { backoff: "constant", delayMs: 0, limit: 1 }160 )160- ).pipe(Effect.provide(steps), Effect.flip);161+ ).pipe(162+ Effect.provide(steps),163+ Effect.flip,164+ Effect.catchDefect(() => Effect.succeed("died"))165+ );166 162- expect(yield* failing).toStrictEqual(stale);163-164- const landed = StepRunner.use(({ step }) =>165- step("land#1", Landing, counted(runs))166- ).pipe(Effect.provide(steps));167-168- expect(yield* landed).toStrictEqual(landing);169- expect(yield* Ref.get(runs)).toBe(2);167+ expect({168+ runs: [yield* run, yield* run],169+ tries: yield* Ref.get(runs),170+ }).toStrictEqual({ runs: [stale, "died"], tries: 2 });171 })172 );173 });modified:apps/sandbox/src/box/sdk.ts+12 added-2 removed
72 unmodified lines73 catch: failed("exec"),74 try: (signal) => container.exec([...argv], execOptions(options, signal)),75 });76 77+ // Effect aborts `exec`'s signal only while `exec` itself is pending;78+ // once the process runs, an interrupt (a lane's time limit) kills it,79+ // or it would run on beside the lanes after it (W3 315 #11).80 const output = yield* Effect.tryPromise({81 catch: failed("exec"),82 try: () => process.output(),80- });83+ }).pipe(84+ Effect.onInterrupt(() =>85+ Effect.sync(() => {86+ process.kill();87+ })88+ )89+ );90 91 return {92 exitCode: output.exitCode,93 stderr: text.decode(output.stderr),11 unmodified lines105 exec: (argv, options = {}) =>106 Effect.flatMap(started(container, start), (running) => {107 const command = run(running, argv, options);108 100- // Interrupting the command aborts its signal, which stops it.109+ // Interrupting the command stops it: its signal while it starts,110+ // a kill once it runs.111 return options.timeoutMs === undefined112 ? command113 : Effect.timeoutOrElse(command, {114 duration: Duration.millis(options.timeoutMs),19 unmodified linesmodified:apps/sandbox/src/lander/run.ts+88 added-36 removed
58 unmodified lines59 lsRemote,60 lsTree,61 mainCopy,62 mainRef,63+ mergeRef,64 mergeScript,65 mergeTree,66 notesCopy,67 objectType,177 unmodified lines245 return { blocked, run } satisfies Steps;246 });247 };248 248-/**249- * The answer's head merged onto canonical `main` with its base as the merge250- * base: the merged tree and the answer's changes, or `StaleBase` with the251- * paths that conflict. Nothing is pushed.252- */253-export const merge = (wire: typeof MergeWire.Type) =>254- Effect.gen(function* () {255- const { job } = wire;256-257- const { run } = yield* runner({258- fork: wire.fork.token,259- main: wire.main.token,260- });261-262- const script = mergeScript(job, {263- fork: wire.fork.url,264- main: wire.main.url,265- });266-267- yield* Effect.forEach(script.fetch, run, { discard: true });268-269- const merged = readMerge((yield* run(script.merge)).stdout);270-271- if (merged.conflicts.length > 0) {272- return yield* new StaleBase({273- base: job.base,274- conflicts: merged.conflicts,275- main: job.main,276- });277- }278-279- const changes = readChanges((yield* run(script.changes)).stdout);280-281- return { changes, tree: merged.tree };282- });283-249 /** Clock time, in the whole seconds a git signature holds. */250 const seconds = Effect.map(Clock.currentTimeMillis, (millis) =>251 Math.floor(millis / 1000)252 );84 unmodified lines337 338 return CommitSha.make(ran.stdout.trim());339 });340 341+/**342+ * The merged tree as a commit on `main` and the head, pushed to the fork's343+ * `mergeRef(tree)`, where a Checker's fetch of the fork's refs finds it344+ * (W3 304 #1). It is dated at the epoch, so merging the same sides again345+ * makes the same commit, and pushing it again changes nothing.346+ */347+const keptForChecks = (348+ job: Job,349+ sides: {350+ readonly head: CommitSha;351+ readonly main: LandedSha;352+ readonly tree: TreeSha;353+ }354+) =>355+ Effect.gen(function* () {356+ yield* prepared(job);357+358+ const commit = yield* committed(job, {359+ at: 0,360+ author: committerLine,361+ message: `Merge ${sides.head} onto ${sides.main}, for its checks\n`,362+ parents: [sides.main, sides.head],363+ tree: sides.tree,364+ });365+366+ const ref = mergeRef(sides.tree);367+368+ const push = pushRef(job.repo, job.url, {369+ ref,370+ remote: "fork",371+ to: commit,372+ });373+374+ const ran = yield* job.run(push);375+376+ return readPush(ran, ref) === "moved"377+ ? commit378+ : yield* job.blocked(push, printed(ran));379+ });380+381+/**382+ * The answer's head merged onto canonical `main` with its base as the merge383+ * base: the merged tree and the answer's changes, or `StaleBase` with the384+ * paths that conflict. Nothing is pushed.385+ */386+export const merge = (wire: typeof MergeWire.Type) =>387+ Effect.gen(function* () {388+ const { job } = wire;389+390+ const steps = yield* runner({391+ fork: wire.fork.token,392+ main: wire.main.token,393+ });394+395+ const { run } = steps;396+397+ const script = mergeScript(job, {398+ fork: wire.fork.url,399+ main: wire.main.url,400+ });401+402+ yield* Effect.forEach(script.fetch, run, { discard: true });403+404+ const merged = readMerge((yield* run(script.merge)).stdout);405+406+ if (merged.conflicts.length > 0) {407+ return yield* new StaleBase({408+ base: job.base,409+ conflicts: merged.conflicts,410+ main: job.main,411+ });412+ }413+414+ const changes = readChanges((yield* run(script.changes)).stdout);415+416+ yield* keptForChecks(417+ { ...steps, repo: job.repo, url: wire.fork.url },418+ {419+ head: job.head,420+ main: job.main,421+ tree: merged.tree,422+ }423+ );424+425+ return { changes, tree: merged.tree };426+ });427+428 /** A path's folders and file name; one that cannot name a file is a defect upstream. */429 const placed = ({ path }: { readonly path: string }) =>430 path.split("/").every((segment) => !["", ".", "..", ".git"].includes(segment))431 ? Effect.void544 unmodified linesmodified:apps/sandbox/src/lander/script.ts+19 added-4 removed
8 unmodified lines9 * helper, no redirects and no automatic maintenance, in a bare repo: the10 * Lander checks nothing out and runs nothing from the trees it handles.11 * Nothing here pushes with force, `--force-with-lease` or `--atomic` to12 * `main` (S1 #4, #6): a landing is a plain push, which git refuses when13- * `main` moved, and only a compose ref, never `main`, moves by a lease.13+ * `main` moved, and only a compose ref, never `main`, moves by a lease. A14+ * merge pushes one ref, to the answer's fork alone: the merged commit, for15+ * the Checker to fetch (W3 304 #1).16 */17 import { Brand } from "@repo/brand";18 import type { LandJob, Merged, MergeJob } from "@repo/project/lander/wire";19 import { BlobSha, CommitSha, RepoPath, TreeSha } from "@repo/protocol/ids";41 unmodified lines61 62 /** The canonical branch a landing moves. */63 export const mainRef = "refs/heads/main";64 65+/**66+ * Where a merged commit waits, in the answer's fork, for a Checker to fetch67+ * its tree: named by the tree, so a ref an answerer rewrote cannot change68+ * what is checked (at worst the Checker finds no such tree).69+ */70+export const mergeRef = (tree: string) => `${Brand.refsPrefix}merge/${tree}`;71+72 // Each git command: no hooks, no helper that could see a token, no redirect73 // a header could follow, and nothing running in the background.74 const safety = [75 "-c",121 unmodified lines197 /** The answer's changes against its own base, not main's. */198 readonly changes: GitStep;199 }200 192-/** A merge, start to end. It writes nothing to either remote. */201+/** A merge's fetches and merge; it writes nothing to canonical. */202 export const mergeScript = (203 job: typeof MergeJob.Type,204 remotes: { readonly main: string; readonly fork: string }205 ): MergeScript => ({13 unmodified lines219 */220 export const pushRef = (221 repo: RepoName,222 url: string,214- update: { readonly to: string; readonly ref: string; readonly lease?: string }223+ update: {224+ readonly to: string;225+ readonly ref: string;226+ readonly lease?: string;227+ /** The remote it reaches: canonical, unless it is the fork. */228+ readonly remote?: RemoteName;229+ }230 ): GitStep => ({231 argv: git(232 repo,233 "push",5 unmodified lines239 url,240 `${update.to}:${update.ref}`241 ),242 expect: "push",228- remote: "main",243+ remote: update.remote ?? "main",244 });245 246 /** The two pushes of a landing. */247 export interface LandScript {486 unmodified linesmodified:apps/sandbox/test/box-sdk.test.ts+53 added-2 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { untouchable } from "@repo/testkit/untouchable";3-import { Effect } from "effect";3+import { Effect, Fiber } from "effect";4+import { TestClock } from "effect/testing";5 5-import { Box } from "../src/box.ts";6+import { Box, BoxFailed } from "../src/box.ts";7 import { SdkBox } from "../src/box/sdk.ts";8 9 /** `text` as the Container API hands output back: a plain `ArrayBuffer`. */10 const bytes = (text: string) => {41 unmodified lines52 };53 54 const start = { enableInternet: false, image: "check" };55 56+/** A running container whose one command never ends until it is killed. */57+const hungContainer = () => {58+ const killed: (number | undefined)[] = [];59+60+ const container = untouchable<Container>("container", {61+ exec: () =>62+ Promise.resolve(63+ untouchable<ExecProcess>("process", {64+ kill: (signal) => {65+ killed.push(signal);66+ },67+ // A race of nothing never settles: the command runs until it is killed.68+ output: () => Promise.race<ExecOutput>([]),69+ })70+ ),71+ running: true,72+ });73+74+ return { container, killed };75+};76+77 describe("Box over the Sandbox SDK", () => {78 it.effect(79 "runs a command in the container and reads its output as text",80 () =>36 unmodified lines117 { enableInternet: false, image: "check" },118 ]);119 })120 );121+122+ it.effect(123+ "kills a command that runs past its time limit, so it stops beside the lanes after it",124+ () =>125+ Effect.gen(function* () {126+ const hung = hungContainer();127+128+ const running = yield* Box.use(({ exec }) =>129+ exec(["bun", "test"], { timeoutMs: 1000 })130+ ).pipe(131+ Effect.provide(SdkBox.layer(hung.container, start)),132+ Effect.flip,133+ Effect.forkChild134+ );135+136+ yield* TestClock.adjust("2 seconds");137+138+ expect({139+ failed: yield* Fiber.join(running),140+ killed: hung.killed.length,141+ }).toStrictEqual({142+ failed: new BoxFailed({143+ operation: "exec",144+ reason: "timed out after 1000 ms",145+ }),146+ killed: 1,147+ });148+ })149+ );150 });modified:apps/sandbox/test/lander.test.ts+18 added-12 removed
333 unmodified lines334 335 describe("the Lander's git", () => {336 describe(merge, () => {337 it.live(338- "merges a clean answer onto main: the tree git's own merge makes, the answer's changes, and nothing written to either repo",338+ "merges a clean answer onto main: the tree git's own merge makes, the answer's changes, nothing written to canonical, and the merged commit kept on the fork for the Checker",339 () =>340 Effect.gen(function* () {341 const repos = yield* world;342 const { base, head, main } = yield* diverged(repos);343+ const before = yield* repos.stateOf(repos.canonical);344 344- const before = yield* Effect.all([345- repos.stateOf(repos.canonical),346- repos.stateOf(repos.fork),347- ]);348-345 const merged = yield* merge(346 mergeWire(repos, { base, head, main })347 ).pipe(Effect.provide(box(repos.work)), Effect.exit);348 349+ const tree = yield* repos.mergedTree(main, head);350+351+ const kept = yield* repos.revision(352+ repos.fork,353+ `${Brand.refsPrefix}merge/${tree}`354+ );355+356 expect(merged).toStrictEqual(357 Exit.succeed({358 changes: [359 {7 unmodified lines367 path: RepoPath.make("test/iso.test.ts"),368 status: "added",369 },370 ],368- tree: yield* repos.mergedTree(main, head),371+ tree,372 })373 );374+ expect(yield* repos.stateOf(repos.canonical)).toStrictEqual(before);375 expect(372- yield* Effect.all([373- repos.stateOf(repos.canonical),374- repos.stateOf(repos.fork),375- ])376- ).toStrictEqual(before);376+ yield* Effect.forEach(Option.toArray(kept), (commit) =>377+ Effect.all([378+ gitOk(repos.fork, "rev-parse", `${commit}^{tree}`),379+ gitOk(repos.fork, "rev-parse", `${commit}^1`, `${commit}^2`),380+ ])381+ )382+ ).toStrictEqual([[tree, `${main}\n${head}`]]);383 }).pipe(Effect.scoped, Effect.provide(TestServices))384 );385 386 it.live(842 unmodified linesmodified:docs/reference/mcp-tools.md-2 removed
9165 unmodified lines9166 "assisted",9167 "author",9168 "credits",9169 "landedAt",9170- "parent",9170 "project",9171 "sha"9172 ],9173 "type": "object"3434 unmodified lines12608 "assisted",12609 "author",12610 "credits",12611 "landedAt",12613- "parent",12612 "project",12613 "sha"12614 ],12615 "type": "object"10408 unmodified linesmodified:docs/reference/protocol.schema.jsonnot shown
Its text is not shown, modified.
modified:packages/artifacts/src/repo-host/binding.tsnot shown
Its text is not shown, modified.
modified:packages/artifacts/test/binding.test.tsnot shown
Its text is not shown, modified.
modified:packages/git/src/gateway.tsnot shown
Its text is not shown, modified.
modified:packages/git/test/gateway.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/lander/wire.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/answer-runs.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/deciders.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/lander.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/project.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/deciders.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/project.test.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/src/domain/landing.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/src/authenticate.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/src/ids.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/src/render.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/test/authenticate.test.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/test/render.test.tsnot shown
Its text is not shown, modified.
modified:scripts/startup-budget.tsnot shown
Its text is not shown, modified.
modified:AGENTS.md+6 added-6 removed
19 unmodified lines20 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) |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, `apps/platform/src/platform.ts` decodes it once, and `apps/platform/test/platform.test.ts` proves a bad env fails at start; `apps/platform/test/bindings.test.ts`: the decoded bindings, vars and secrets equal each wrangler.jsonc block's, and each port's factory takes its binding as the generated Env types it, without a cast |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`; `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) |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); `apps/platform/src/ports.ts` composes every port from the decoded env in one place, each beta dependency behind its port with a memory adapter beside it, and `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` fail when a binding is lost or the Worker cannot start on its real adapters |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`); `apps/platform/test/bindings.test.ts` (the platform's Env has no private-namespace binding until W6 adds one deliberately); `apps/sandbox/test/checker.test.ts` (the Checker takes no snapshot once the held-back slot is reached). No fence yet: the gateway's layer guard (W6 606); the web Worker's Env type test, no private namespace (W5 501 `apps/web/test/env.test-d.ts`) |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); `apps/platform/test/workflows/answer.test.ts` (the Answer Workflow run twice over one step record, or replayed from the engine's, lands once); `apps/platform/test/workflows/on-push.test.ts` (one push event, replayed or delivered twice, opens one decision); `apps/platform/test/core-loop.test.ts` (a replayed request id returns the first receipt and lands nothing). No fence yet: one push deduped by (repo, sha) across the gateway's record and OnPush's, which today dedupe by their own event ids (W3 313 #2) |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; `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) |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`; `infra/deploy.ts` refuses without a known stage and spawns nothing, runs `verify` first and `scripts/smoke.ts` after (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`). No fence yet: `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; `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; `apps/platform/test/project-do.test.ts` (the Project Durable Object hydrates, transitions, persists and settles per call, has only call and alarm as methods, and sets its alarm to the next deadline) |35 36 ## Fence37 38 `bun run verify` is the gate (see Commands). Run it before you stop. When a hook or check fails, fix the cause. Loosening, skipping or disabling a check needs the user's sign-off.115 unmodified linesmodified:PROVENANCE.md+3 added
13 unmodified lines14 | `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+| `packages/rules/src/prelude.ts` (`installFrozenGlobals`' `generator.next`, about 8 lines) | mulberry32, Tommy Ettinger's 32-bit seeded generator, written from the published algorithm | Public domain; no licence text to keep | The Dynamic Worker prelude's `Math.random`, `crypto.getRandomValues` and `crypto.randomUUID`, number for number the same as `bun-prelude.ts`'s, so the `/worker` and `/bun` rules adapters give one bundle the same policy (principle 8). The generator is reset before each job, so a warm worker gives the numbers a cold one would. |19 | `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`. |20 21 ## Ideas, no code22 3 unmodified lines26 | Counting escapes with a second oxlint config, run as `-A all -D <rule> --format json` | Rat Stack's `scripts/oxlint-debt-ledger.config.ts` and its content build | `oxlint.debt.config.ts`, `scripts/debt.ts` |27 | A release-age gate and exact pins on every install | Rat Stack's `pnpm-workspace.yaml` (`minimumReleaseAge`, `minimumReleaseAgeExclude`) | `bunfig.toml` |28 | A merged command catalog (`commands.json`) | cf's command catalog | `scripts/lib/gen.ts` |29 | Skills as numbered playbooks: each step ends on a done-when, then a gate step and a Report list | Rat Stack's `skills/add-a-capability` and `skills/add-a-store` at `fba26d8` | `.agents/skills/{add-operation,add-refusal,add-check-kind,add-port}/SKILL.md` |30+| A Workers rate-limit binding behind one Effect service: `limit({ key })` through `tryPromise`, with a failing binding as a defect | Rat Stack's `apps/mischief/src/rate-limits.ts` at `fba26d8` | `apps/platform/src/adapters/rate-limits.ts` (`WorkerRateLimits`) |31+| A Worker Loader binding typed structurally, and a stub disposed quietly after each request | Rat Stack's `apps/mischief/src/sandbox-worker-loader.ts` at `fba26d8` (the idea only; no lines copied) | `packages/rules/src/rules-evaluator/worker.ts` (`LoaderBinding`) |