Type a project's visibility, and give the platform a private namespace and a master key it cannot start without
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- protocol/domain/visibility.ts: Members ("deciders" or named handles); Layer gains readers and writers (required on the wire, the sdk defaults them); SealedChecks (layer, areas by glob, area-bit result, attempts, optional admit, pin at claim, salted Merkle commitment, canary); VisibilityPolicy (layers, checks, flows, notice, env setters); SealedCheck with its Q17 clause, and LayerManifest. Policy gains visibility as an optionalKey: absent, the project is Open. - Decision: a sealed area whose name is no AreaName is refused, not dropped. Schema.Record keyed by a refined schema drops a failing key silently (spec 7.4), and with it that area's checks; the areas record checks every property name first (isPropertyNames), then decodes to Record(AreaName, Glob). - Decision (tightening): notice.narrowingDays is NoneOrMore and the attempt and admission counts are AtLeastOne, as the policy's other spans are. - platform: ARTIFACTS_PRIVATE is a binding the env decode requires, and MASTER_KEY a RedactedFromValue of 64 hex characters; either missing or malformed fails InvalidEnv naming the key only. wrangler.jsonc binds ARTIFACTS_PRIVATE to layers-<stage> in each stage block and requires MASTER_KEY in every secrets block; worker-configuration.d.ts regenerated. apps/web and apps/sandbox configs are unchanged. - .env.schema declares MASTER_KEY (@required @sensitive, isLength=64 and a hex regex), saying that losing it loses every stored value. No key value is generated here: the user sets it (H5), or 699 under O1 for the dev stage. - infra: stages.ts names layers-<s>; bootstrap's plan creates it beside projects-<s> the same way, and reads both namespaces back. New --dry-run reads what exists and prints the plan, creating and writing nothing (live against dev-oscabriel: "create Artifacts namespace layers-dev-oscabriel; would create 1"). stages.md lists the namespace, the secret, the dry run and the teardown of both namespaces. - packages/visibility: the skeleton ("." and "./*" exports), with @env-spec/parser 0.6.1 exact (published 2026-09-26, past the release-age gate). Declarations only: the EnvSchemaParser port with its parsed structures (ParsedValue covers text, flags, lists, calls and bare arguments, so the memory fake's fixtures are plain data) and EnvSchemaUnreadable; WriteOnlyValues and SealedValue (base64 fields); LayerRepos, a RepoHost under its own tag. Nothing depends on it yet (609 decides where it plugs in). - AGENTS.md principle 7 names the platform's type test beside the web's. - Tests added: domain.test.ts decodes OSR 4.1's example and a layer that holds source as VisibilityPolicy, a LayerManifest, and a Policy carrying visibility; refuses an unknown audience, a negative perClaim, a sealed area with no glob or a bad name, a layer nobody may read, a negative notice, a check without a clause and a clause from neither ask nor doc; both schemas' JSON Schemas carry no Infinity or null. platform.test.ts: InvalidEnv{ARTIFACTS_PRIVATE}, InvalidEnv{MASTER_KEY} for missing, short and non-hex keys (none printed), and a decoded key that prints as <redacted>. env.test-d.ts: the platform's Env holds ARTIFACTS and ARTIFACTS_PRIVATE and no other Artifacts binding; bindings.test.ts's "no private namespace yet" case is now its positive side. Bootstrap: plan and dry-run lines with layers-<s>, the stage table's namespaces. visibility's smoke test holds the ports' keys and SealedValue. - ASSUMPTION: the top-level (local) block binds layers-local, not the issue's "layers", as every other top-level resource carries -local.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
26 files+1190 added−41 removed
- tests:+720 added−12 removed
- other:+470 added−29 removed
Provenance
- Commit
8b5b0d9- Tree
6789c86- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
0e95d48
26 files changed+1190 added−41 removed
modified:apps/platform/src/platform.ts+17 added-1 removed
34 unmodified lines35 36 /** A bearer token: long enough that guessing one is hopeless. */37 const Token = Schema.String.check(Schema.isMinLength(32));38 39+/** A 256-bit key, written as 64 hex characters. */40+const HexKey = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/iu));41+42 /**43 * Named sessions: token → handle. A record with a refined key would drop a44 * short token silently, so the whole table is checked instead.45 */21 unmodified lines67 */68 export const PlatformBindings = Schema.Struct({69 ANSWER: binding<Env["ANSWER"]>("the Answer Workflow"),70 ARTIFACTS: binding<Env["ARTIFACTS"]>("an Artifacts namespace"),71+ /**72+ * The private namespace that holds every project's layer repos (W6; OSR73+ * §5.1). Only this Worker binds it: the Workers that serve public pages74+ * bind no namespace at all (principle 7).75+ */76+ ARTIFACTS_PRIVATE: binding<Env["ARTIFACTS_PRIVATE"]>(77+ "the private Artifacts namespace"78+ ),79 CLAIM_LIMIT: binding<Env["CLAIM_LIMIT"]>("a rate limit"),80 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),81 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),82 LOADER: binding<Env["LOADER"]>("a Worker Loader"),26 unmodified lines109 /**110 * The secrets `.env.schema` declares, each redacted but Google's client id.111 * Every one but `SESSION_TOKENS` and Google's pair is required112 * (`wrangler.jsonc`'s `secrets.required`): sign-in's cookie key and pepper102- * too, since accounts are the platform's own.113+ * too, since accounts are the platform's own, and the master key.114 */115 export const PlatformSecrets = Schema.Struct({116 /** Seals a sign-in in progress into its form (`auth/state.ts`). */117 COOKIE_KEY: Schema.RedactedFromValue(Token),6 unmodified lines124 /** The secret of Google sign-in's OAuth client, set with its id. */125 GOOGLE_CLIENT_SECRET: Schema.optionalKey(126 Schema.RedactedFromValue(Schema.NonEmptyString)127 ),128+ /**129+ * Wraps the data key of every write-only env value (W6; VL §9). Losing it130+ * loses every value stored under it.131+ */132+ MASTER_KEY: Schema.RedactedFromValue(HexKey),133 OPERATOR_TOKEN: Schema.RedactedFromValue(Token),134 /** HMAC'd with every password before PBKDF2 (`auth/password.ts`). */135 PASSWORD_PEPPER: Schema.RedactedFromValue(Token),136 /** Named sessions beside accounts (spec §8 D9): JSON, token → handle. */122 unmodified linesmodified:apps/platform/test/bindings.test.ts+10 added-3 removed
304 unmodified lines305 >306 >();307 });308 309- it("have no private namespace yet (principle 7; W6 adds it deliberately)", () => {310- expectTypeOf<Env>().not.toHaveProperty("ARTIFACTS_PRIVATE");311- expectTypeOf<PlatformConfig>().not.toHaveProperty("ARTIFACTS_PRIVATE");309+ // Principle 7: this Worker binds the private namespace deliberately (W6);310+ // the web's `test/env.test-d.ts` holds that no public-serving Worker does.311+ it("hold the private namespace, decoded as the public one is", () => {312+ expectTypeOf<Env>().toHaveProperty("ARTIFACTS_PRIVATE");313+ expectTypeOf<PlatformConfig["ARTIFACTS_PRIVATE"]>().toEqualTypeOf<314+ Env["ARTIFACTS_PRIVATE"]315+ >();316+ expectTypeOf<Env["ARTIFACTS_PRIVATE"]>().toExtend<317+ Parameters<(typeof RepoHostBinding)["layer"]>[0]318+ >();319 });320 321 it("are each taken by its port's factory as Env types it, without a cast", () => {322 expectTypeOf<Env["ARTIFACTS"]>().toExtend<66 unmodified linesadded:apps/platform/test/env.test-d.ts+22 added
12345678910111213141516171819202122/** * Principle 7's type fence, the positive side: the platform Worker's * generated `Env` (from `wrangler.jsonc`, by `bun run types`) holds both * Artifacts namespaces, the public one and the private one the layers live * in, deliberately. The web's `test/env.test-d.ts` is the negative side: * a Worker that serves public pages holds neither. */import { describe, expectTypeOf, it } from "vitest";
describe("the platform Worker's Env", () => { it("holds the public namespace and the private one", () => { expectTypeOf<Env>().toHaveProperty("ARTIFACTS"); expectTypeOf<Env>().toHaveProperty("ARTIFACTS_PRIVATE"); expectTypeOf<Env["ARTIFACTS_PRIVATE"]>().toEqualTypeOf<Env["ARTIFACTS"]>(); });
it("holds no other Artifacts binding", () => { expectTypeOf<Extract<keyof Env, `ARTIFACTS${string}`>>().toEqualTypeOf< "ARTIFACTS" | "ARTIFACTS_PRIVATE" >(); });});modified:apps/platform/test/fake-env.ts+9 added-1 removed
45 unmodified lines464748495051525354555657585980 unmodified lines14014114214313814414514614714814915015115215315415515615715815916016116216316417 unmodified lines45 unmodified linesexport const cookieKey = "cookie-key-0123456789abcdef0123456789";
export const passwordPepper = "pepper-0123456789abcdef0123456789abcdef";
/** * The master key in every fake env (W6): 64 hex characters, the 256-bit key * that wraps write-only values. A test value, never a stage's. */export const masterKey = "0123456789abcdef".repeat(4);
/** One call a fake Project DO was sent: the DO's name, the method, and who called. */export interface ProjectCallSeen { readonly project: string; readonly method: ProjectMethod;80 unmodified lines};
/** * The platform Worker's env at stage `local`, as `wrangler.jsonc` declares * it: every var and the required secret set, every binding a fake that * it: every var and every required secret set, every binding a fake that * throws if touched, so a test proves what building the platform touches. * `PROJECT` is the exception: its DOs hold no project and answer calls on * one with `UnknownProject`, each noted (`callsTo`). The optional secrets * are absent. */export const fakeEnv = (): Env => ({ ANSWER: untouchable("ANSWER"), ARTIFACTS: untouchable("ARTIFACTS"), ARTIFACTS_PRIVATE: untouchable("ARTIFACTS_PRIVATE"), CLAIM_LIMIT: untouchable("CLAIM_LIMIT"), COOKIE_KEY: cookieKey, EVIDENCE: untouchable("EVIDENCE"), FRONT_PAGE: untouchable("FRONT_PAGE"), LANDER_ADAPTER: "container", LOADER: untouchable("LOADER"), MASTER_KEY: masterKey, OAUTH_KV: untouchable("OAUTH_KV"), ON_PUSH: untouchable("ON_PUSH"), OPERATOR_HANDLE: "oscabriel", OPERATOR_TOKEN: operatorToken,17 unmodified linesmodified:apps/platform/test/platform.test.ts+60 added-2 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { ProjectName } from "@repo/protocol/ids";3-import { Effect, Layer } from "effect";3+import { Effect, Layer, Redacted } from "effect";4 5 import { decodeEnv, InvalidEnv, platform } from "../src/platform.ts";6-import { emptyFrontPage, fakeEnv, operatorToken, without } from "./fake-env.ts";6+import {7+ emptyFrontPage,8+ fakeEnv,9+ masterKey,10+ operatorToken,11+ without,12+} from "./fake-env.ts";13 import { rpcClient, served, toolCall } from "./harness.ts";14 15 const project = ProjectName.make("datekit");16 52 unmodified lines69 expect(failure).toStrictEqual(new InvalidEnv({ keys: ["ARTIFACTS"] }));70 })71 );72 73+ // OSR §5.1: layer repos live in a namespace of their own, which only74+ // this Worker binds.75+ it.effect("fails to start without the private namespace", () =>76+ Effect.gen(function* () {77+ const failure = yield* failureOf(without(fakeEnv(), "ARTIFACTS_PRIVATE"));78+79+ expect(failure).toStrictEqual(80+ new InvalidEnv({ keys: ["ARTIFACTS_PRIVATE"] })81+ );82+ })83+ );84+85+ it.effect(86+ "fails to start without a master key of 64 hex characters, naming the key only",87+ () =>88+ Effect.gen(function* () {89+ const missing = yield* failureOf(without(fakeEnv(), "MASTER_KEY"));90+91+ const short = yield* failureOf({92+ ...fakeEnv(),93+ MASTER_KEY: masterKey.slice(2),94+ });95+96+ const notHex = yield* failureOf({97+ ...fakeEnv(),98+ MASTER_KEY: `${masterKey.slice(2)}zz`,99+ });100+101+ expect([missing, short, notHex]).toStrictEqual([102+ new InvalidEnv({ keys: ["MASTER_KEY"] }),103+ new InvalidEnv({ keys: ["MASTER_KEY"] }),104+ new InvalidEnv({ keys: ["MASTER_KEY"] }),105+ ]);106+ expect(JSON.stringify([short, notHex])).not.toContain(107+ masterKey.slice(2)108+ );109+ })110+ );111+112+ it.effect("keeps the master key redacted once decoded", () =>113+ Effect.gen(function* () {114+ const { MASTER_KEY } = yield* decodeEnv(fakeEnv());115+116+ expect(Redacted.isRedacted(MASTER_KEY)).toBeTruthy();117+ // A redacted value prints as its `toString`, never as the value.118+ expect(JSON.stringify({ MASTER_KEY })).toBe(119+ '{"MASTER_KEY":"<redacted>"}'120+ );121+ expect(Redacted.value(MASTER_KEY)).toBe(masterKey);122+ })123+ );124+125 it.effect("names every missing binding and var at once", () =>126 Effect.gen(function* () {127 const failure = yield* failureOf(128 without(without(fakeEnv(), "SANDBOX"), "STAGE")109 unmodified linesmodified:apps/platform/.env.schema+8 added
39 unmodified lines40 41 # Google sign-in (W4 419), optional: that client's secret, set with its id.42 # @optional @sensitive43 GOOGLE_CLIENT_SECRET=44+45+# Write-only env values (W6): the 256-bit key, as 64 hex characters, that46+# wraps the data key of every value a decider sets (WebCrypto, AES-GCM).47+# Losing it loses every stored value: nobody, the platform included, can48+# open one again. Keep a copy outside this machine. Changing it needs every49+# value re-wrapped first.50+# @required @sensitive @type=string(isLength=64, matches=regex("^[0-9a-fA-F]{64}$"))51+MASTER_KEY=modified:apps/platform/worker-configuration.d.ts+8 added-2 removed
1 /* eslint-disable */2-// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 0d5a77aaf4d6fddaaa331efcd6e9ef1b)2+// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: 8c12fe014598b33e00210997684fcc6b)3 interface __BaseEnv_Env {4 OAUTH_KV: KVNamespace;5 EVIDENCE: R2Bucket;6 RELEASES: R2Bucket;7 FRONT_PAGE: D1Database;8 ARTIFACTS: Artifacts;9+ ARTIFACTS_PRIVATE: Artifacts;10 CLAIM_LIMIT: RateLimit;11 PROPOSAL_LIMIT: RateLimit;12 SIGN_IN_LIMIT: RateLimit;13 LOADER: WorkerLoader;2 unmodified lines16 LANDER_ADAPTER: string;17 OPERATOR_TOKEN: string;18 COOKIE_KEY: string;19 PASSWORD_PEPPER: string;20+ MASTER_KEY: string;21 PROJECT: DurableObjectNamespace<import("./src/worker").Project>;22 SANDBOX: Fetcher /* sandbox-dev-oscabriel */ | Fetcher /* sandbox-demo */ | Fetcher /* sandbox */;23 ANSWER: Workflow<Parameters<import("./src/worker").Answer['run']>[0]['payload']>;24 ON_PUSH: Workflow<Parameters<import("./src/worker").OnPush['run']>[0]['payload']>;8 unmodified lines33 EVIDENCE: R2Bucket;34 RELEASES: R2Bucket;35 FRONT_PAGE: D1Database;36 ARTIFACTS: Artifacts;37+ ARTIFACTS_PRIVATE: Artifacts;38 CLAIM_LIMIT: RateLimit;39 PROPOSAL_LIMIT: RateLimit;40 SIGN_IN_LIMIT: RateLimit;41 LOADER: WorkerLoader;2 unmodified lines44 LANDER_ADAPTER: string;45 OPERATOR_TOKEN: string;46 COOKIE_KEY: string;47 PASSWORD_PEPPER: string;48+ MASTER_KEY: string;49 PROJECT: DurableObjectNamespace<import("./src/worker").Project>;50 SANDBOX: Fetcher /* sandbox-dev-oscabriel */;51 ANSWER: Workflow<Parameters<import("./src/worker").Answer['run']>[0]['payload']>;52 ON_PUSH: Workflow<Parameters<import("./src/worker").OnPush['run']>[0]['payload']>;3 unmodified lines56 EVIDENCE: R2Bucket;57 RELEASES: R2Bucket;58 FRONT_PAGE: D1Database;59 ARTIFACTS: Artifacts;60+ ARTIFACTS_PRIVATE: Artifacts;61 CLAIM_LIMIT: RateLimit;62 PROPOSAL_LIMIT: RateLimit;63 SIGN_IN_LIMIT: RateLimit;64 LOADER: WorkerLoader;2 unmodified lines67 LANDER_ADAPTER: string;68 OPERATOR_TOKEN: string;69 COOKIE_KEY: string;70 PASSWORD_PEPPER: string;71+ MASTER_KEY: string;72 PROJECT: DurableObjectNamespace<import("./src/worker").Project>;73 SANDBOX: Fetcher /* sandbox-demo */;74 ANSWER: Workflow<Parameters<import("./src/worker").Answer['run']>[0]['payload']>;75 ON_PUSH: Workflow<Parameters<import("./src/worker").OnPush['run']>[0]['payload']>;4 unmodified lines80 type StringifyValues<EnvType extends Record<string, unknown>> = {81 [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;82 };83 declare namespace NodeJS {78- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "OPERATOR_HANDLE" | "STAGE" | "LANDER_ADAPTER" | "OPERATOR_TOKEN" | "COOKIE_KEY" | "PASSWORD_PEPPER">> {}84+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "OPERATOR_HANDLE" | "STAGE" | "LANDER_ADAPTER" | "OPERATOR_TOKEN" | "COOKIE_KEY" | "PASSWORD_PEPPER" | "MASTER_KEY">> {}85 }modified:apps/platform/wrangler.jsonc+32 added-6 removed
33 unmodified lines34 },35 "secrets": {36 // Declared in .env.schema; the user sets the values. SESSION_TOKENS is37 // optional; sign-in's cookie key and pepper are not, since accounts are38- // the platform's own and need no third party.39- "required": ["OPERATOR_TOKEN", "COOKIE_KEY", "PASSWORD_PEPPER"],38+ // the platform's own and need no third party. MASTER_KEY wraps every39+ // write-only env value (W6): without it none can be stored or opened.40+ "required": [41+ "OPERATOR_TOKEN",42+ "COOKIE_KEY",43+ "PASSWORD_PEPPER",44+ "MASTER_KEY",45+ ],46 },47 "durable_objects": {48 "bindings": [{ "name": "PROJECT", "class_name": "Project" }],49 },50 "workflows": [51 { "name": "answer-local", "binding": "ANSWER", "class_name": "Answer" },52 { "name": "on-push-local", "binding": "ON_PUSH", "class_name": "OnPush" },53 ],48- "artifacts": [{ "binding": "ARTIFACTS", "namespace": "projects-local" }],54+ // The public namespace, and the private one that holds every project's55+ // layer repos (W6). Only this Worker binds the private one: the Workers56+ // that serve public pages bind neither (principle 7).57+ "artifacts": [58+ { "binding": "ARTIFACTS", "namespace": "projects-local" },59+ { "binding": "ARTIFACTS_PRIVATE", "namespace": "layers-local" },60+ ],61 "d1_databases": [62 {63 "binding": "FRONT_PAGE",64 "database_name": "front-page-local",49 unmodified lines114 "STAGE": "dev-oscabriel",115 "LANDER_ADAPTER": "container",116 },117 "secrets": {106- "required": ["OPERATOR_TOKEN", "COOKIE_KEY", "PASSWORD_PEPPER"],118+ "required": [119+ "OPERATOR_TOKEN",120+ "COOKIE_KEY",121+ "PASSWORD_PEPPER",122+ "MASTER_KEY",123+ ],124 },125 "durable_objects": {126 "bindings": [{ "name": "PROJECT", "class_name": "Project" }],127 },10 unmodified lines138 },139 ],140 "artifacts": [141 { "binding": "ARTIFACTS", "namespace": "projects-dev-oscabriel" },142+ { "binding": "ARTIFACTS_PRIVATE", "namespace": "layers-dev-oscabriel" },143 ],144 "d1_databases": [145 {146 "binding": "FRONT_PAGE",49 unmodified lines196 "STAGE": "demo",197 "LANDER_ADAPTER": "container",198 },199 "secrets": {182- "required": ["OPERATOR_TOKEN", "COOKIE_KEY", "PASSWORD_PEPPER"],200+ "required": [201+ "OPERATOR_TOKEN",202+ "COOKIE_KEY",203+ "PASSWORD_PEPPER",204+ "MASTER_KEY",205+ ],206 },207 "durable_objects": {208 "bindings": [{ "name": "PROJECT", "class_name": "Project" }],209 },4 unmodified lines214 "binding": "ON_PUSH",215 "class_name": "OnPush",216 },217 ],195- "artifacts": [{ "binding": "ARTIFACTS", "namespace": "projects-demo" }],218+ "artifacts": [219+ { "binding": "ARTIFACTS", "namespace": "projects-demo" },220+ { "binding": "ARTIFACTS_PRIVATE", "namespace": "layers-demo" },221+ ],222 "d1_databases": [223 {224 "binding": "FRONT_PAGE",225 "database_name": "front-page-demo",45 unmodified linesmodified:infra/bootstrap.ts+40 added-16 removed
1 unmodified line2 * bootstrap: `bun run bootstrap -- --stage dev-<user>|demo`. Makes a stage's3 * Cloudflare resources once, and is safe to run again: a second run creates4 * nothing (spec §4.4).5 *6- * 1. Reads what exists: the stage's public Artifacts namespace (over REST,7- * with the infra token `varlock run --path infra/` provides), and the8- * account's D1 databases, KV namespaces and R2 buckets (with Wrangler's9- * own login: the infra token can't write them, so Wrangler never sees10- * it).6+ * 1. Reads what exists: the stage's two Artifacts namespaces, the public7+ * one and the private one the layers live in (over REST, with the infra8+ * token `varlock run --path infra/` provides), and the account's D19+ * databases, KV namespaces and R2 buckets (with Wrangler's own login: the10+ * infra token can't write them, so Wrangler never sees it).11 * 2. `plan`s and creates only what is missing.12 * 3. Writes the D1 and KV ids into the stage's block of13 * `apps/platform/wrangler.jsonc` (`writeIds`, comments untouched).14 * 4. Applies the front page's migrations, once `apps/platform/migrations`3 unmodified lines18 * 6. Checks, by name only, that the deployed platform has every secret its19 * `.env.schema` requires. Before the first deploy there is no Worker to20 * hold them: that deploy must carry them through varlock.21 *22+ * `--dry-run` does only the first step and prints the plan: it creates23+ * nothing and writes no file.24+ *25 * `--check-triggers` does only the last step a deploy needs: it reads the26 * platform's triggers back (`GET /triggers/platform-<s>`) and compares them27 * with what `wrangler.jsonc` declares (`checkTriggers`). Wrangler's dry run28 * prints no triggers, so only this read proves the push-event trigger57 unmodified lines86 export const plan = (stage: Stage, existing: Existing): readonly Step[] => {87 const names = resources(stage);88 89 return [87- ...(existing.namespaces.includes(names.projects)88- ? []89- : [Step.CreateNamespace({ name: names.projects })]),90+ ...[names.projects, names.layers].flatMap((name) =>91+ existing.namespaces.includes(name) ? [] : [Step.CreateNamespace({ name })]92+ ),93 ...(existing.d1.some(({ name }) => name === names.frontPage)94 ? []95 : [Step.CreateD1({ name: names.frontPage })]),96 ...(existing.kv.some(({ title }) => title === names.oauth)374 unmodified lines471 472 /** What exists of `stage`'s resources on the account. */473 const readExisting = (root: string, credentials: Credentials, stage: Stage) =>474 Effect.gen(function* () {472- const { projects } = resources(stage);475+ const { layers, projects } = resources(stage);476 474- const namespace = yield* exists(475- credentials,476- `/artifacts/namespaces/${projects}`477+ const namespaces = yield* Effect.filter([projects, layers], (name) =>478+ exists(credentials, `/artifacts/namespaces/${name}`)479 );480 481 return {482 d1: yield* wrangler(root, ["d1", "list", "--json"]).pipe(1 unmodified line484 ),485 kv: yield* wrangler(root, ["kv", "namespace", "list"]).pipe(486 Effect.flatMap(kvFrom)487 ),486- namespaces: namespace ? [projects] : [],488+ namespaces,489 r2: bucketsFrom(yield* wrangler(root, ["r2", "bucket", "list"])),490 } satisfies Existing;491 });492 5 unmodified lines498 CreateNamespace: ({ name }) => `create Artifacts namespace ${name}`,499 CreateR2: ({ name }) => `create R2 ${name}`,500 });501 502+/** What a dry run of `stage` prints for `steps`: each step, then that nothing changed. */503+export const planLines = (504+ stage: Stage,505+ steps: readonly Step[]506+): readonly string[] => [507+ ...steps.map((step) => `bootstrap ${stage} (dry run): ${describe(step)}`),508+ `bootstrap ${stage} (dry run): would create ${steps.length}; nothing was changed`,509+];510+511 /**512 * Wrangler's create commands offer to add the binding to `wrangler.jsonc`513 * themselves, at top level; bootstrap writes the stage's block instead.514 */115 unmodified lines630 )631 : Effect.fail(new MissingSecrets({ names: missing, stage }));632 });633 634+/** Reads what exists of `stage` and prints what `make` would create, creating and writing nothing. */635+const dryRun = (root: string, credentials: Credentials, stage: Stage) =>636+ Effect.gen(function* () {637+ const steps = plan(stage, yield* readExisting(root, credentials, stage));638+639+ yield* Console.log(planLines(stage, steps).join("\n"));640+ });641+642 /** Makes what `stage` lacks, writes its ids and checks its secrets. */643 const make = (root: string, credentials: Credentials, stage: Stage) =>644 Effect.gen(function* () {645 const fs = yield* FileSystem.FileSystem;57 unmodified lines703 });704 705 /**706 * Bootstraps the stage `argv`'s `--stage` names; with `--check-triggers`,688- * only reads its push-event trigger back.707+ * only reads its push-event trigger back; with `--dry-run`, only reads what708+ * exists and lists what it would create.709 */710 export const bootstrap = (argv: readonly string[]) =>711 Effect.gen(function* () {712 const stage = yield* stageOf(argv);713 const credentials = yield* Credentials;714 const root = yield* repoRoot;715 716+ if (argv.includes("--check-triggers")) {717+ return yield* triggers(credentials, stage);718+ }719+696- return yield* argv.includes("--check-triggers")697- ? triggers(credentials, stage)720+ return yield* argv.includes("--dry-run")721+ ? dryRun(root, credentials, stage)722 : make(root, credentials, stage);723 });724 725 if (import.meta.main) {8 unmodified linesmodified:infra/stages.md+7 added-3 removed
1 # Stages2 3-A stage is one full copy of the platform on Cloudflare: its own Workers, Workflows, Artifacts namespace, database, KV namespace and bucket. `infra/stages.ts` is the one table of stage names and resource names. Every other file, both `wrangler.jsonc` files included, matches it, and `packages/config/test/bootstrap.test.ts` checks that they do.3+A stage is one full copy of the platform on Cloudflare: its own Workers, Workflows, Artifacts namespaces (public and private), database, KV namespace and buckets. `infra/stages.ts` is the one table of stage names and resource names. Every other file, both `wrangler.jsonc` files included, matches it, and `packages/config/test/bootstrap.test.ts` checks that they do.4 5 | Stage | What it is for |6 | --- | --- |7 | `dev-<user>` | One person's iteration. Today there is one, `dev-oscabriel`. Deploy it as often as you like. |9 unmodified lines17 | --- | --- | --- |18 | Workers | `platform-<s>`, `sandbox-<s>`, `web-<s>` (once `apps/web` exists) | deploy |19 | Workflows | `answer-<s>`, `on-push-<s>` | deploy (they live in `platform-<s>`) |20 | Artifacts namespace (public) | `projects-<s>` | bootstrap |21+| Artifacts namespace (private: every project's layer repos, bound only by the platform) | `layers-<s>` | bootstrap |22 | D1 database (the front page) | `front-page-<s>` | bootstrap |23 | KV namespace (OAuth grants) | `oauth-<s>` | bootstrap |24 | R2 bucket (lane evidence) | `evidence-<s>` | bootstrap |25 | R2 bucket (CLI releases, served at `/install.sh` and `/releases/*`) | `releases-<s>` | bootstrap |14 unmodified lines40 ```41 42 It refuses a stage that `stages.ts` doesn't declare. Then it:43 43-1. reads what exists: the stage's Artifacts namespace over REST, and the account's D1 databases, KV namespaces and R2 buckets through Wrangler;44+1. reads what exists: the stage's two Artifacts namespaces (`projects-<s>` and `layers-<s>`) over REST, and the account's D1 databases, KV namespaces and R2 buckets through Wrangler;45 2. creates only what is missing, so a second run creates nothing;46 3. writes the new D1 and KV ids into the stage's block of `apps/platform/wrangler.jsonc`, touching nothing else in the file (commit that change);47 4. applies the front page's migrations (`wrangler d1 migrations apply front-page-<s> --remote --env <s>`), once `apps/platform/migrations/` exists;48 5. records the account's workers.dev subdomain in `infra/workers-dev.json`, so smoke knows where the stage lives;49 6. checks by name that the deployed platform holds every secret its `.env.schema` requires. Before the first deploy there is no Worker to hold them, so it says which ones that deploy has to carry.50 51 It never deletes anything and never prints or reads a secret's value.52 53+`bun run bootstrap -- --stage <s> --dry-run` does only the first step and lists what the run would create. It creates nothing and writes no file.54+55 ## Secrets56 57 `apps/platform/.env.schema` names them. Values never go in the repo.58 2 unmodified lines61 | `OPERATOR_TOKEN` | Always. The operator's bearer token, at least 32 characters. |62 | `SESSION_TOKENS` | Optional. A JSON object from token to handle, for the demo's named people (spec §8 D9). |63 | `COOKIE_KEY` | Always. Seals a sign-in in progress into its form (HMAC-SHA-256), at least 32 characters. |64 | `PASSWORD_PEPPER` | Always. Every password is HMAC'd with it before PBKDF2, at least 32 characters. Changing it makes every stored password fail to verify. |65+| `MASTER_KEY` | Always (W6). 64 hex characters: the 256-bit key that wraps every write-only env value. Losing it loses every stored value, so keep a copy outside the machine. |66 67 To set them for a stage, do one of these:68 69 - **varlock (H5).** Write `NAME=varlock(prompt)` for each one into `apps/platform/.env.local`, run `./node_modules/.bin/varlock load --path apps/platform/` in your own terminal, then deploy. `varlock-wrangler` hands the values to the Worker.46 unmodified lines116 117 None of this is automated: the scripts never delete, and nobody runs `wrangler delete` or cf's `delete` without the user's OK (`wrangler delete` auto-confirms in a non-interactive shell). Tear down only what this build created, which means only names from the table above, and never `witness`. A person runs these in their own terminal. Wrangler's commands run from the app's folder with that app's `node_modules/.bin/wrangler`.118 119 1. The Workers: `wrangler delete --env <s>` in `apps/web` (if deployed), then `apps/platform`, then `apps/sandbox`. Then `wrangler workflows delete answer-<s>` and `wrangler workflows delete on-push-<s>`, if they remain.116-2. The Artifacts repos, then the namespace. List the repos with `bun run ops -- artifacts namespaces repos list --namespace projects-<s>`, delete each one with `bun run ops -- artifacts namespaces repos delete <repo> --namespace projects-<s> --force`, then `bun run ops -- artifacts namespaces delete --namespace projects-<s>`. A namespace has to be empty before it can be deleted.120+2. The Artifacts repos, then the namespaces, `projects-<s>` and `layers-<s>` alike. List a namespace's repos with `bun run ops -- artifacts namespaces repos list --namespace <namespace>`, delete each one with `bun run ops -- artifacts namespaces repos delete <repo> --namespace <namespace> --force`, then `bun run ops -- artifacts namespaces delete --namespace <namespace>`. A namespace has to be empty before it can be deleted.121 3. The database: `wrangler d1 delete front-page-<s>`.122 4. The KV namespace: `wrangler kv namespace delete --namespace-id <id>`. The id is in the stage's block of `apps/platform/wrangler.jsonc`.123 5. The buckets: empty `evidence-<s>` and `releases-<s>`, then run `wrangler r2 bucket delete evidence-<s>` and `wrangler r2 bucket delete releases-<s>`.124 6. Put the stage's placeholder ids back in `apps/platform/wrangler.jsonc`.modified:infra/stages.ts+3 added
39 unmodified lines40 /** The web Worker (W5). */41 readonly web: string;42 /** The public Artifacts namespace. */43 readonly projects: string;44+ /** The private Artifacts namespace: every project's layer repos (W6). */45+ readonly layers: string;46 /** The D1 database behind the front page. */47 readonly frontPage: string;48 /** The KV namespace that holds OAuth grants. */49 readonly oauth: string;11 unmodified lines61 export const resources = (stage: Stage): Resources => ({62 answer: `answer-${stage}`,63 evidence: `evidence-${stage}`,64 frontPage: `front-page-${stage}`,65+ layers: `layers-${stage}`,66 oauth: `oauth-${stage}`,67 onPush: `on-push-${stage}`,68 platform: `platform-${stage}`,69 projects: `projects-${stage}`,90 unmodified linesmodified:packages/config/test/bootstrap.test.ts+35 added-4 removed
9 unmodified lines10 kvFrom,11 MissingSecrets,12 missingSecrets,13 plan,14+ planLines,15 secretNames,16 Step,17 TriggerMismatch,18 TriggersResponse,16 unmodified lines35 }).pipe(Effect.provide(NodeServices.layer));36 37 /** What this test reads of a stage's block in the platform's `wrangler.jsonc`. */38 const PlatformStage = Schema.Struct({38- artifacts: Schema.Tuple([Schema.Struct({ namespace: Schema.String })]),39+ artifacts: Schema.Array(40+ Schema.Struct({ binding: Schema.String, namespace: Schema.String })41+ ),42 d1_databases: Schema.Tuple([43 Schema.Struct({ binding: Schema.String, database_name: Schema.String }),44 ]),45 r2_buckets: Schema.Array(48 unmodified lines94 kv: [95 { id: "33333333333333333333333333333333", title: "oauth-dev-oscabriel" },96 { id: "44444444444444444444444444444444", title: "oauth-demo" },97 ],95- namespaces: ["projects-dev-oscabriel", "projects-demo"],98+ namespaces: [99+ "projects-dev-oscabriel",100+ "layers-dev-oscabriel",101+ "projects-demo",102+ "layers-demo",103+ ],104 r2: [105 "evidence-dev-oscabriel",106 "evidence-demo",107 "releases-dev-oscabriel",16 unmodified lines124 const names = resources(stage);125 126 return {127 frontPage: names.frontPage,128+ // The public namespace, then the private one the layers live in.129+ namespaces: [names.projects, names.layers],130 onPush: [names.onPush, names.onPush],131 platform: names.platform,132 projects: [names.projects, names.projects],133 sandbox: names.sandbox,6 unmodified lines140 const block = platform.env[stage];141 142 return {143 frontPage: block?.d1_databases[0].database_name,144+ namespaces: block?.artifacts.map(({ namespace }) => namespace),145 onPush: [146 block?.triggers.events[0].targets[0].workflow_name,147 block?.workflows.find(({ binding }) => binding === "ON_PUSH")148 ?.name,149 ],150 // Wrangler names a stage's Worker `<name>-<env>`.151 platform: `${platform.name}-${stage}`,152 projects: [142- block?.artifacts[0].namespace,153+ block?.artifacts.find(({ binding }) => binding === "ARTIFACTS")154+ ?.namespace,155 block?.triggers.events[0].filter.namespace,156 ],157 sandbox: block?.services[0].service,158 stage: block?.vars.STAGE,32 unmodified lines191 describe("the bootstrap plan", () => {192 it("creates every resource of a stage that has none", () => {193 expect(plan("dev-oscabriel", nothing)).toStrictEqual([194 Step.CreateNamespace({ name: "projects-dev-oscabriel" }),195+ Step.CreateNamespace({ name: "layers-dev-oscabriel" }),196 Step.CreateD1({ name: "front-page-dev-oscabriel" }),197 Step.CreateKv({ title: "oauth-dev-oscabriel" }),198 Step.CreateR2({ name: "evidence-dev-oscabriel" }),199 Step.CreateR2({ name: "releases-dev-oscabriel" }),15 unmodified lines215 id: "33333333333333333333333333333333",216 title: "oauth-dev-oscabriel",217 },218 ],206- namespaces: ["projects-demo"],219+ namespaces: ["projects-demo", "layers-demo", "layers-dev-oscabriel"],220 r2: ["evidence-dev-oscabriel", "releases-demo"],221 };222 223 expect(plan("dev-oscabriel", demoOnly)).toStrictEqual([3 unmodified lines227 ]);228 });229 });230 231+describe("a dry run", () => {232+ it("lists each step the plan would take, the private namespace among them, and says nothing changed", () => {233+ expect(planLines("demo", plan("demo", nothing))).toStrictEqual([234+ "bootstrap demo (dry run): create Artifacts namespace projects-demo",235+ "bootstrap demo (dry run): create Artifacts namespace layers-demo",236+ "bootstrap demo (dry run): create D1 front-page-demo",237+ "bootstrap demo (dry run): create KV oauth-demo",238+ "bootstrap demo (dry run): create R2 evidence-demo",239+ "bootstrap demo (dry run): create R2 releases-demo",240+ "bootstrap demo (dry run): would create 6; nothing was changed",241+ ]);242+ expect(planLines("demo", [])).toStrictEqual([243+ "bootstrap demo (dry run): would create 0; nothing was changed",244+ ]);245+ });246+});247+248 /** The lines of `after` that differ from `before`'s, by line. */249 const changed = (before: string, after: string) => {250 const old = before.split("\n");251 237 unmodified lines489 { name: "COOKIE_KEY", required: true },490 { name: "PASSWORD_PEPPER", required: true },491 { name: "GOOGLE_CLIENT_ID", required: false },492 { name: "GOOGLE_CLIENT_SECRET", required: false },493+ { name: "MASTER_KEY", required: true },494 ]);495 })496 );497 84 unmodified linesmodified:packages/protocol/src/domain/policy.ts+3 added
6 unmodified lines7 import { AtLeastOne, Glob, NoneOrMore } from "./common.ts";8 import { AskKind } from "./kind.ts";9 import { RunBlock } from "./run.ts";10 import { Territory } from "./territory.ts";11+import { VisibilityPolicy } from "./visibility.ts";12 13 /** Where a policy came from: the config folder, or the defaults when there is none. */14 const Source = Schema.Literals(["config", "defaults"]);15 76 unmodified lines92 ratchets: Schema.Array(RatchetSpec),93 record: RecordWindow,94 run: RunBlock,95 source: Source,96+ /** The project's layers and held-back checks; absent, it is Open. */97+ visibility: Schema.optionalKey(VisibilityPolicy),98 vouch: Vouch,99 /** The vouch file's lines, parsed. */100 vouches: Schema.Array(101 Schema.Struct({83 unmodified linesmodified:packages/protocol/src/domain/visibility.ts+120 added
1 import { Schema } from "effect";2 3 import {4 AreaName,5+ CommitSha,6 DecisionId,7 EnvKey,8 Handle,9 LandedSha,10 LayerName,11 ProjectName,12 RepoName,13+ RepoPath,14 SuiteRoot,15 } from "../ids.ts";16 import { Posture } from "../posture.ts";17+import { AtLeastOne, Glob, NoneOrMore } from "./common.ts";18 19 /** Who may read a layer. */20 export const Audience = Schema.Literals([21 "public",37 unmodified lines59 60 export type LayerKind = typeof LayerKind.Type;61 62 /**63+ * Who a rule names: the project's deciders, whoever they are at the landed64+ * commit, or the people listed.65+ */66+export const Members = Schema.Union([67+ Schema.Literal("deciders"),68+ Schema.NonEmptyArray(Handle),69+]);70+71+export type Members = typeof Members.Type;72+73+/**74 * A layer: a separate repo holding one audience's files for a project,75 * overlaid on main's paths only where that audience may read.76 */77 export const Layer = Schema.Struct({2 unmodified lines80 holds: Schema.NonEmptyArray(LayerKind),81 /** The longest its content may stay unreleased. */82 maxDays: Schema.optionalKey(Schema.Int),83 name: LayerName,84+ /** Who may clone it. The sdk defaults it to the deciders; the wire always says. */85+ readers: Members,86 reason: Schema.NonEmptyString,87 /** Its repo, `<project>--<layer>`; absent for a layer that is config only. */88 repo: Schema.optionalKey(RepoName),89 /** When its content is due for release. */90 sunsetDays: Schema.optionalKey(Schema.Int),91+ /** Who may push to it. The sdk defaults it to the deciders; the wire always says. */92+ writers: Members,93 });94 95 export type Layer = typeof Layer.Type;96 97 /**98+ * Each sealed area's name and the code it guards. A key that is no area99+ * name is refused, not dropped: a `Schema.Record` keyed by `AreaName` alone100+ * would drop it silently, and with it the area's checks.101+ */102+const Areas = Schema.Record(Schema.String, Schema.NonEmptyString)103+ .check(Schema.isPropertyNames(AreaName))104+ .pipe(Schema.decodeTo(Schema.Record(AreaName, Glob)));105+106+/**107+ * Held-back checks, as the public config folder declares them: which layer108+ * holds them, the areas they guard by name and code glob, and the rules109+ * they are run by. Their paths and names stay in the layer's own manifest.110+ */111+export const SealedChecks = Schema.Struct({112+ /**113+ * When a new check joins the suite: after this many green runs on main114+ * and at least this many red runs on known-bad trees. Absent: at once.115+ */116+ admit: Schema.optionalKey(117+ Schema.Struct({118+ greenOnMainRuns: AtLeastOne,119+ redOnKnownBadAtLeast: AtLeastOne,120+ })121+ ),122+ /** Each area's name, public, and the code it guards: `{ export: "src/export/**" }`. */123+ areas: Areas,124+ /** How often an answer may fail them: per claim, and per person, area and week. */125+ attempts: Schema.Struct({126+ perClaim: AtLeastOne,127+ perPersonPerAreaPerWeek: AtLeastOne,128+ }),129+ /** A canary string in every sealed file, so a leak can be found. */130+ canary: Schema.Boolean,131+ /** How the suite is committed to in public: a salted SHA-256 Merkle root. */132+ commit: Schema.Literal("salted-sha256-merkle"),133+ /** The layer that holds the check files. */134+ layer: LayerName,135+ /** An answer is judged by the suite as it stood when its claim opened. */136+ pin: Schema.Literal("claim"),137+ /** What a failure tells the answerer: one bit per area, never a name or output. */138+ result: Schema.Literal("area-bit"),139+});140+141+export type SealedChecks = typeof SealedChecks.Type;142+143+/**144+ * A project's `visibility.ts`, evaluated: its layers, its held-back checks,145+ * how content flows between them, how long a narrowing waits, and who may146+ * set write-only env values. A project without one is Open.147+ */148+export const VisibilityPolicy = Schema.Struct({149+ checks: Schema.optionalKey(SealedChecks),150+ /** Who may set a write-only value. The sdk defaults it to the deciders. */151+ env: Schema.Struct({ setters: Members }),152+ flows: Schema.Struct({153+ /** Nothing moves from a layer into a wider audience but a credited release. */154+ noWriteDown: Schema.Boolean,155+ /** Who may release. */156+ release: Members,157+ }),158+ layers: Schema.Array(Layer),159+ /** How many days a change that narrows visibility waits before it lands; `0` lands it at once. */160+ notice: Schema.Struct({ narrowingDays: NoneOrMore }),161+});162+163+export type VisibilityPolicy = typeof VisibilityPolicy.Type;164+165+/**166+ * One held-back check, as its layer's own manifest lists it: where it is,167+ * the area it guards, the clause of an ask or a doc it enforces (a check168+ * that cites none is `UnstatedRequirement`), and who wrote it.169+ */170+export const SealedCheck = Schema.Struct({171+ area: AreaName,172+ author: Handle,173+ clause: Schema.Struct({174+ /** The clause's words, quoted. */175+ quote: Schema.NonEmptyString,176+ /** The ask's id, or the doc's path and anchor. */177+ ref: Schema.NonEmptyString,178+ source: Schema.Literals(["ask", "doc"]),179+ }),180+ path: RepoPath,181+});182+183+export type SealedCheck = typeof SealedCheck.Type;184+185+/**186+ * The manifest inside a layer repo (`<config folder>/layer.ts` there,187+ * evaluated like the public config): its checks' paths and names stay in188+ * the layer, and its known-bad commits feed admission.189+ */190+export const LayerManifest = Schema.Struct({191+ checks: Schema.Array(SealedCheck),192+ /** Commits every new check must fail on before it is admitted. */193+ knownBad: Schema.Array(CommitSha),194+ layer: LayerName,195+});196+197+export type LayerManifest = typeof LayerManifest.Type;198+199+/**200 * One entry of a project's ledger, numbered in order. A value set is recorded201 * by who and when, never by the value.202 */203 export const LedgerEntry = Schema.TaggedUnion({74 unmodified linesmodified:packages/protocol/test/fixtures/domain.json+491 added-1 removed
272 unmodified lines273 "command": "asks",274 "ok": true,275 "v": 1276 }277+ },278+ "a layer for an audience the platform does not know": {279+ "schema": "VisibilityPolicy",280+ "value": {281+ "checks": {282+ "admit": {283+ "greenOnMainRuns": 3,284+ "redOnKnownBadAtLeast": 1285+ },286+ "areas": {287+ "export": "src/export/**",288+ "parser": "src/parser/**"289+ },290+ "attempts": {291+ "perClaim": 3,292+ "perPersonPerAreaPerWeek": 10293+ },294+ "canary": true,295+ "commit": "salted-sha256-merkle",296+ "layer": "maintainers",297+ "pin": "claim",298+ "result": "area-bit"299+ },300+ "env": {301+ "setters": "deciders"302+ },303+ "flows": {304+ "noWriteDown": true,305+ "release": "deciders"306+ },307+ "layers": [308+ {309+ "audience": "everyone",310+ "disclose": "sealed",311+ "holds": ["checks", "agent-config", "notes", "experiment"],312+ "name": "maintainers",313+ "readers": "deciders",314+ "reason": "Held-back checks for parser and export; maintainers' review rubrics",315+ "writers": "deciders"316+ },317+ {318+ "audience": "security",319+ "disclose": "counted",320+ "holds": ["fix"],321+ "maxDays": 14,322+ "name": "security",323+ "readers": ["alice", "bob"],324+ "reason": "Embargoed fixes, released with their advisory",325+ "writers": "deciders"326+ }327+ ],328+ "notice": {329+ "narrowingDays": 7330+ }331+ }332+ },333+ "sealed checks a claim may attempt a negative number of times": {334+ "schema": "VisibilityPolicy",335+ "value": {336+ "checks": {337+ "admit": {338+ "greenOnMainRuns": 3,339+ "redOnKnownBadAtLeast": 1340+ },341+ "areas": {342+ "export": "src/export/**",343+ "parser": "src/parser/**"344+ },345+ "attempts": {346+ "perClaim": -1,347+ "perPersonPerAreaPerWeek": 10348+ },349+ "canary": true,350+ "commit": "salted-sha256-merkle",351+ "layer": "maintainers",352+ "pin": "claim",353+ "result": "area-bit"354+ },355+ "env": {356+ "setters": "deciders"357+ },358+ "flows": {359+ "noWriteDown": true,360+ "release": "deciders"361+ },362+ "layers": [363+ {364+ "audience": "maintainers",365+ "disclose": "sealed",366+ "holds": ["checks", "agent-config", "notes", "experiment"],367+ "name": "maintainers",368+ "readers": "deciders",369+ "reason": "Held-back checks for parser and export; maintainers' review rubrics",370+ "writers": "deciders"371+ },372+ {373+ "audience": "security",374+ "disclose": "counted",375+ "holds": ["fix"],376+ "maxDays": 14,377+ "name": "security",378+ "readers": ["alice", "bob"],379+ "reason": "Embargoed fixes, released with their advisory",380+ "writers": "deciders"381+ }382+ ],383+ "notice": {384+ "narrowingDays": 7385+ }386+ }387+ },388+ "a sealed area with no glob": {389+ "schema": "VisibilityPolicy",390+ "value": {391+ "checks": {392+ "admit": {393+ "greenOnMainRuns": 3,394+ "redOnKnownBadAtLeast": 1395+ },396+ "areas": {397+ "export": "src/export/**",398+ "parser": ""399+ },400+ "attempts": {401+ "perClaim": 3,402+ "perPersonPerAreaPerWeek": 10403+ },404+ "canary": true,405+ "commit": "salted-sha256-merkle",406+ "layer": "maintainers",407+ "pin": "claim",408+ "result": "area-bit"409+ },410+ "env": {411+ "setters": "deciders"412+ },413+ "flows": {414+ "noWriteDown": true,415+ "release": "deciders"416+ },417+ "layers": [418+ {419+ "audience": "maintainers",420+ "disclose": "sealed",421+ "holds": ["checks", "agent-config", "notes", "experiment"],422+ "name": "maintainers",423+ "readers": "deciders",424+ "reason": "Held-back checks for parser and export; maintainers' review rubrics",425+ "writers": "deciders"426+ },427+ {428+ "audience": "security",429+ "disclose": "counted",430+ "holds": ["fix"],431+ "maxDays": 14,432+ "name": "security",433+ "readers": ["alice", "bob"],434+ "reason": "Embargoed fixes, released with their advisory",435+ "writers": "deciders"436+ }437+ ],438+ "notice": {439+ "narrowingDays": 7440+ }441+ }442+ },443+ "a sealed area whose name is not an area name": {444+ "schema": "VisibilityPolicy",445+ "value": {446+ "checks": {447+ "admit": {448+ "greenOnMainRuns": 3,449+ "redOnKnownBadAtLeast": 1450+ },451+ "areas": {452+ "Parser": "src/parser/**",453+ "export": "src/export/**"454+ },455+ "attempts": {456+ "perClaim": 3,457+ "perPersonPerAreaPerWeek": 10458+ },459+ "canary": true,460+ "commit": "salted-sha256-merkle",461+ "layer": "maintainers",462+ "pin": "claim",463+ "result": "area-bit"464+ },465+ "env": {466+ "setters": "deciders"467+ },468+ "flows": {469+ "noWriteDown": true,470+ "release": "deciders"471+ },472+ "layers": [473+ {474+ "audience": "maintainers",475+ "disclose": "sealed",476+ "holds": ["checks", "agent-config", "notes", "experiment"],477+ "name": "maintainers",478+ "readers": "deciders",479+ "reason": "Held-back checks for parser and export; maintainers' review rubrics",480+ "writers": "deciders"481+ },482+ {483+ "audience": "security",484+ "disclose": "counted",485+ "holds": ["fix"],486+ "maxDays": 14,487+ "name": "security",488+ "readers": ["alice", "bob"],489+ "reason": "Embargoed fixes, released with their advisory",490+ "writers": "deciders"491+ }492+ ],493+ "notice": {494+ "narrowingDays": 7495+ }496+ }497+ },498+ "a layer nobody may read": {499+ "schema": "VisibilityPolicy",500+ "value": {501+ "checks": {502+ "admit": {503+ "greenOnMainRuns": 3,504+ "redOnKnownBadAtLeast": 1505+ },506+ "areas": {507+ "export": "src/export/**",508+ "parser": "src/parser/**"509+ },510+ "attempts": {511+ "perClaim": 3,512+ "perPersonPerAreaPerWeek": 10513+ },514+ "canary": true,515+ "commit": "salted-sha256-merkle",516+ "layer": "maintainers",517+ "pin": "claim",518+ "result": "area-bit"519+ },520+ "env": {521+ "setters": "deciders"522+ },523+ "flows": {524+ "noWriteDown": true,525+ "release": "deciders"526+ },527+ "layers": [528+ {529+ "audience": "maintainers",530+ "disclose": "sealed",531+ "holds": ["checks", "agent-config", "notes", "experiment"],532+ "name": "maintainers",533+ "readers": "deciders",534+ "reason": "Held-back checks for parser and export; maintainers' review rubrics",535+ "writers": "deciders"536+ },537+ {538+ "audience": "security",539+ "disclose": "counted",540+ "holds": ["fix"],541+ "maxDays": 14,542+ "name": "security",543+ "readers": [],544+ "reason": "Embargoed fixes, released with their advisory",545+ "writers": "deciders"546+ }547+ ],548+ "notice": {549+ "narrowingDays": 7550+ }551+ }552+ },553+ "a narrowing that waits a negative number of days": {554+ "schema": "VisibilityPolicy",555+ "value": {556+ "checks": {557+ "admit": {558+ "greenOnMainRuns": 3,559+ "redOnKnownBadAtLeast": 1560+ },561+ "areas": {562+ "export": "src/export/**",563+ "parser": "src/parser/**"564+ },565+ "attempts": {566+ "perClaim": 3,567+ "perPersonPerAreaPerWeek": 10568+ },569+ "canary": true,570+ "commit": "salted-sha256-merkle",571+ "layer": "maintainers",572+ "pin": "claim",573+ "result": "area-bit"574+ },575+ "env": {576+ "setters": "deciders"577+ },578+ "flows": {579+ "noWriteDown": true,580+ "release": "deciders"581+ },582+ "layers": [583+ {584+ "audience": "maintainers",585+ "disclose": "sealed",586+ "holds": ["checks", "agent-config", "notes", "experiment"],587+ "name": "maintainers",588+ "readers": "deciders",589+ "reason": "Held-back checks for parser and export; maintainers' review rubrics",590+ "writers": "deciders"591+ },592+ {593+ "audience": "security",594+ "disclose": "counted",595+ "holds": ["fix"],596+ "maxDays": 14,597+ "name": "security",598+ "readers": ["alice", "bob"],599+ "reason": "Embargoed fixes, released with their advisory",600+ "writers": "deciders"601+ }602+ ],603+ "notice": {604+ "narrowingDays": -7605+ }606+ }607+ },608+ "a sealed check that cites no clause": {609+ "schema": "LayerManifest",610+ "value": {611+ "checks": [612+ {613+ "area": "export",614+ "author": "alice",615+ "path": "checks/export/escapes-titles.test.ts"616+ },617+ {618+ "area": "parser",619+ "author": "bob",620+ "clause": {621+ "quote": "Week 1 is the week with the year's first Thursday.",622+ "ref": "docs/parsing.md#iso-weeks",623+ "source": "doc"624+ },625+ "path": "checks/parser/iso-week-boundaries.test.ts"626+ }627+ ],628+ "knownBad": ["8888888888888888888888888888888888888888"],629+ "layer": "maintainers"630+ }631+ },632+ "a clause from neither an ask nor a doc": {633+ "schema": "LayerManifest",634+ "value": {635+ "checks": [636+ {637+ "area": "export",638+ "author": "alice",639+ "clause": {640+ "quote": "Every export format escapes a title it writes.",641+ "ref": "export-escapes-titles",642+ "source": "ask"643+ },644+ "path": "checks/export/escapes-titles.test.ts"645+ },646+ {647+ "area": "parser",648+ "author": "bob",649+ "clause": {650+ "quote": "Week 1 is the week with the year's first Thursday.",651+ "ref": "docs/parsing.md#iso-weeks",652+ "source": "chat"653+ },654+ "path": "checks/parser/iso-week-boundaries.test.ts"655+ }656+ ],657+ "knownBad": ["8888888888888888888888888888888888888888"],658+ "layer": "maintainers"659+ }660 }661 },662 "roundTrip": {663 "AgentTrailer": [679 unmodified lines1343 "maxDays": 365,1344 "name": "maintainers",1345 "reason": "Held-back checks for the parser.",1346 "repo": "datekit--maintainers",964- "sunsetDays": 901347+ "sunsetDays": 90,1348+ "readers": "deciders",1349+ "writers": "deciders"1350 }1351 ],1352 "posture": "openWithSealedEvidence",1353 "postureLabel": "Open with sealed evidence",749 unmodified lines2103 "stage": "checks",2104 "tree": "5555555555555555555555555555555555555555",2105 "verifier": "platform"2106 }2107+ ],2108+ "VisibilityPolicy": [2109+ {2110+ "checks": {2111+ "admit": {2112+ "greenOnMainRuns": 3,2113+ "redOnKnownBadAtLeast": 12114+ },2115+ "areas": {2116+ "export": "src/export/**",2117+ "parser": "src/parser/**"2118+ },2119+ "attempts": {2120+ "perClaim": 3,2121+ "perPersonPerAreaPerWeek": 102122+ },2123+ "canary": true,2124+ "commit": "salted-sha256-merkle",2125+ "layer": "maintainers",2126+ "pin": "claim",2127+ "result": "area-bit"2128+ },2129+ "env": {2130+ "setters": "deciders"2131+ },2132+ "flows": {2133+ "noWriteDown": true,2134+ "release": "deciders"2135+ },2136+ "layers": [2137+ {2138+ "audience": "maintainers",2139+ "disclose": "sealed",2140+ "holds": ["checks", "agent-config", "notes", "experiment"],2141+ "name": "maintainers",2142+ "readers": "deciders",2143+ "reason": "Held-back checks for parser and export; maintainers' review rubrics",2144+ "writers": "deciders"2145+ },2146+ {2147+ "audience": "security",2148+ "disclose": "counted",2149+ "holds": ["fix"],2150+ "maxDays": 14,2151+ "name": "security",2152+ "readers": ["alice", "bob"],2153+ "reason": "Embargoed fixes, released with their advisory",2154+ "writers": "deciders"2155+ }2156+ ],2157+ "notice": {2158+ "narrowingDays": 72159+ }2160+ },2161+ {2162+ "env": {2163+ "setters": ["alice"]2164+ },2165+ "flows": {2166+ "noWriteDown": true,2167+ "release": ["alice"]2168+ },2169+ "layers": [2170+ {2171+ "audience": "team",2172+ "disclose": "declared",2173+ "holds": ["source"],2174+ "name": "team",2175+ "readers": ["alice", "bob"],2176+ "reason": "The billing adapter ships closed",2177+ "writers": ["alice"]2178+ }2179+ ],2180+ "notice": {2181+ "narrowingDays": 72182+ }2183+ }2184+ ],2185+ "LayerManifest": [2186+ {2187+ "checks": [2188+ {2189+ "area": "export",2190+ "author": "alice",2191+ "clause": {2192+ "quote": "Every export format escapes a title it writes.",2193+ "ref": "export-escapes-titles",2194+ "source": "ask"2195+ },2196+ "path": "checks/export/escapes-titles.test.ts"2197+ },2198+ {2199+ "area": "parser",2200+ "author": "bob",2201+ "clause": {2202+ "quote": "Week 1 is the week with the year's first Thursday.",2203+ "ref": "docs/parsing.md#iso-weeks",2204+ "source": "doc"2205+ },2206+ "path": "checks/parser/iso-week-boundaries.test.ts"2207+ }2208+ ],2209+ "knownBad": ["8888888888888888888888888888888888888888"],2210+ "layer": "maintainers"2211+ }2212 ]2213 },2214 "withoutDefaults": {2215 "asks": [67 unmodified linesmodified:packages/protocol/test/domain.test.ts+33 added-1 removed
18 unmodified lines19 import { Proposal } from "../src/domain/proposal.ts";20 import { CreditSummary } from "../src/domain/record.ts";21 import { RunBlock } from "../src/domain/run.ts";22 import { Territory } from "../src/domain/territory.ts";23+import {24+ LayerManifest,25+ Ledger,26+ VisibilityPolicy,23-import { Ledger } from "../src/domain/visibility.ts";27+} from "../src/domain/visibility.ts";28 import { Envelope } from "../src/envelope.ts";29 import {30 AreaName,31 AskId,54 unmodified lines86 Envelope: Listed,87 Evidence,88 FrontPageEntry,89 LandingView,90+ LayerManifest,91 Ledger,92 Outcome,93 Policy,94 PolicyInput,5 unmodified lines100 RunBlock,101 Territory,102 Today,103 Verdict,104+ VisibilityPolicy,105 } as const;106 107 const schemaNamed = new Map<string, Schema.Codec<unknown, unknown>>(108 Object.entries(schemas)50 unmodified lines159 ["Policy", Policy],160 ["Verdict", Verdict],161 ["Outcome", Outcome],162 ["ProjectEvent", ProjectEvent],163+ ["VisibilityPolicy", VisibilityPolicy],164+ ["LayerManifest", LayerManifest],165 ] as const)(166 "%s has a JSON Schema with no non-finite numbers and no nulls",167 (_name, schema) => {168 const document = JSON.stringify(Schema.toJsonSchemaDocument(schema));51 unmodified lines220 ).toBeFalsy();221 });222 });223 224+describe("a project's visibility", () => {225+ // OSR §4.1's `visibility.ts`, as the data the sdk writes for it.226+ const [stated] = wire.roundTrip.VisibilityPolicy;227+228+ const [policy] = wire.roundTrip.Policy;229+230+ it("rides on the policy at a landed commit", () => {231+ const withVisibility = { ...policy, visibility: stated };232+233+ expect(234+ Schema.encodeSync(Policy)(235+ Schema.decodeUnknownSync(Policy)(withVisibility)236+ )237+ ).toStrictEqual(withVisibility);238+ });239+240+ // No `visibility.ts` means no layers and the posture Open (OSR §4.1).241+ it("is absent from a policy whose config folder declares none", () => {242+ expect(Schema.decodeUnknownSync(Policy)(policy)).not.toHaveProperty(243+ "visibility"244+ );245+ });246+});247+248 describe("names and ids", () => {249 // GitHub tells logins apart without case, and claim forks lowercase them,250 // so a vouch file's or a policy's `Alice` is the person signed in as `alice`.251 it("tell two handles apart without case, as sign-in does", () => {85 unmodified linesadded:packages/visibility/src/env-schema.ts+89 added
1+/**2+ * The parser seam (VL §8.3): the one place a project's `.env.schema` is3+ * parsed, at a landed SHA. `@env-spec/parser` is reached only through an4+ * adapter of this port (`./env-schema/env-spec`, issue 603), with a fake5+ * beside it (`./env-schema/memory`). Parsing reads text and nothing else: no6+ * value expression is evaluated, no plugin is loaded, and no import outside7+ * the repo is followed.8+ */9+import { RepoPath } from "@repo/protocol/ids";10+import { Context, Schema } from "effect";11+import type { Effect } from "effect";12+13+/**14+ * A decorator's value as the schema writes it, never evaluated: text or a15+ * number (`infer`, `sentry.io`), a flag (a bare `@required` is `true`), a16+ * list (`[APP_ENV]`), a function call (`forEnv(production)`; a `$APP_ENV`17+ * reference arrives as the call `ref(APP_ENV)`), or arguments alone (a bare18+ * call's, `@proxy(domain="sentry.io")`, or an object's, `{preventLeaks=false}`).19+ */20+export type ParsedValue =21+ | string22+ | number23+ | boolean24+ | readonly ParsedValue[]25+ | ParsedCall26+ | ParsedArgs;27+28+/** One `key=value` argument. */29+export interface ParsedNamedArg {30+ readonly key: string;31+ readonly value: ParsedValue;32+}33+34+/** Arguments as written: the positional ones, then the `key=value` ones. */35+export interface ParsedArgs {36+ readonly positional: readonly ParsedValue[];37+ readonly named: readonly ParsedNamedArg[];38+}39+40+/** A function call, never run, and its text as written: `enum(development, test)`. */41+export interface ParsedCall extends ParsedArgs {42+ readonly fn: string;43+ readonly text: string;44+}45+46+/** One decorator: `@sensitive`, `@type=string(minLength=32)`, `@import(../shared/)`. */47+export interface ParsedDecorator {48+ readonly name: string;49+ readonly value: ParsedValue;50+}51+52+/** One item: its key, its description comment, its decorators, and its value text if it has one. */53+export interface ParsedItem {54+ readonly key: string;55+ readonly description?: string;56+ readonly decorators: readonly ParsedDecorator[];57+ readonly value?: string;58+}59+60+/**61+ * A `.env.schema`, parsed: the header's decorators (above its `# ---`),62+ * every item in order, and the files its `@import`s name, recorded and63+ * never merged.64+ */65+export interface ParsedEnvSchema {66+ readonly header: readonly ParsedDecorator[];67+ readonly items: readonly ParsedItem[];68+ readonly imports: readonly string[];69+}70+71+/**72+ * A `.env.schema` that cannot be read as one: it does not parse, or it73+ * imports from outside the repo. Names the file and why, never a value.74+ */75+export class EnvSchemaUnreadable extends Schema.TaggedError<EnvSchemaUnreadable>()(76+ "EnvSchemaUnreadable",77+ { file: RepoPath, reason: Schema.String }78+) {}79+80+/** Parses a `.env.schema`'s text; reads nothing else. */81+export class EnvSchemaParser extends Context.Service<82+ EnvSchemaParser,83+ {84+ readonly parse: (85+ file: RepoPath,86+ text: string87+ ) => Effect.Effect<ParsedEnvSchema, EnvSchemaUnreadable>;88+ }89+>()("visibility/EnvSchemaParser") {}added:packages/visibility/src/index.ts+20 added
1+/**2+ * Typed visibility (W6): layers, sealed checks, the ledger, the env shape3+ * and write-only values, as a cartridge the platform plugs in. Each module4+ * is its own subpath too (`@repo/visibility/env-schema`).5+ */6+export { EnvSchemaParser, EnvSchemaUnreadable } from "./env-schema.ts";7+8+export type {9+ ParsedArgs,10+ ParsedCall,11+ ParsedDecorator,12+ ParsedEnvSchema,13+ ParsedItem,14+ ParsedNamedArg,15+ ParsedValue,16+} from "./env-schema.ts";17+18+export { LayerRepos } from "./layer-repos.ts";19+20+export { SealedValue, WriteOnlyValues } from "./vault.ts";added:packages/visibility/src/layer-repos.ts+13 added
1+/**2+ * The private namespace's repos (OSR §5.1): every project's layer repos,3+ * `<project>--<layer>`, behind a `RepoHost` of their own. The platform binds4+ * it over `ARTIFACTS_PRIVATE`; code that asks for the public `RepoHost` is5+ * never handed it, and no Worker that serves public pages binds it.6+ */7+import type { RepoHost } from "@repo/artifacts/repo-host";8+import { Context } from "effect";9+10+export class LayerRepos extends Context.Service<11+ LayerRepos,12+ RepoHost["Service"]13+>()("visibility/LayerRepos") {}added:packages/visibility/src/vault.ts+46 added
1+/**2+ * Write-only values (VL §8.4, §8.6; OSR §2.2 `writeOnly`): a decider sets a3+ * value for a `@sensitive` item, and nobody reads it back, the decider and4+ * the platform's contracts included. Each value is sealed under a random5+ * data key, wrapped by the platform's `MASTER_KEY`6+ * (`./vault/webcrypto`, issue 610).7+ */8+import type { EnvKey } from "@repo/protocol/ids";9+import type { ValueTooShort } from "@repo/protocol/refusal";10+import { Context, Schema } from "effect";11+import type { Effect, Redacted } from "effect";12+13+/** Bytes as base64 text. */14+const Base64 = Schema.String.check(Schema.isBase64());15+16+/**17+ * A value as the Project DO stores it: its ciphertext, the IV it was sealed18+ * with, its data key wrapped by the master key, and which master key that19+ * was. Nothing in it is the value.20+ */21+export const SealedValue = Schema.Struct({22+ ciphertext: Base64,23+ iv: Base64,24+ keyVersion: Schema.Int,25+ wrappedKey: Base64,26+});27+28+export type SealedValue = typeof SealedValue.Type;29+30+/** Seals values, and opens one only for a landed run. */31+export class WriteOnlyValues extends Context.Service<32+ WriteOnlyValues,33+ {34+ /**35+ * Seals `value` for `key`. A short value is `ValueTooShort` unless the36+ * decider acknowledged it; a very short one is refused even then.37+ */38+ readonly put: (input: {39+ readonly key: EnvKey;40+ readonly value: Redacted.Redacted;41+ readonly acknowledgeShort: boolean;42+ }) => Effect.Effect<SealedValue, ValueTooShort>;43+ /** Opens a sealed value, for a landed run only; never behind a contract. */44+ readonly open: (sealed: SealedValue) => Effect.Effect<Redacted.Redacted>;45+ }46+>()("visibility/WriteOnlyValues") {}added:packages/visibility/test/smoke.test.ts+60 added
1+import { describe, expect, expectTypeOf, it } from "@effect/vitest";2+import { RepoHost } from "@repo/artifacts/repo-host";3+import { Result, Schema } from "effect";4+5+import manifest from "../package.json" with { type: "json" };6+import { EnvSchemaParser } from "../src/env-schema.ts";7+import { LayerRepos } from "../src/layer-repos.ts";8+import { SealedValue, WriteOnlyValues } from "../src/vault.ts";9+10+// The skeleton's test (601): the ports W6's group A builds against. The11+// issues that fill them add their own tests beside this one.12+describe("the package", () => {13+ it("is @repo/visibility", () => {14+ expect(manifest.name).toBe("@repo/visibility");15+ });16+17+ it("declares each port under a key of its own", () => {18+ expect([19+ EnvSchemaParser.key,20+ LayerRepos.key,21+ WriteOnlyValues.key,22+ ]).toStrictEqual([23+ "visibility/EnvSchemaParser",24+ "visibility/LayerRepos",25+ "visibility/WriteOnlyValues",26+ ]);27+ });28+29+ // OSR §5.1: the private namespace is a RepoHost of its own, so code that30+ // asks for the public one can never be handed the layers' repos.31+ it("keeps the layers' repos behind a RepoHost of their own", () => {32+ expect(LayerRepos.key).not.toBe(RepoHost.key);33+ expectTypeOf<LayerRepos["Service"]>().toEqualTypeOf<RepoHost["Service"]>();34+ });35+36+ it("seals a value as base64 fields and a key version, never the value", () => {37+ const sealed = {38+ ciphertext: "c2VhbGVk",39+ iv: "aXYtMTItYnl0ZXM=",40+ keyVersion: 1,41+ wrappedKey: "d3JhcHBlZA==",42+ };43+44+ expect(Schema.decodeSync(SealedValue)(sealed)).toStrictEqual(sealed);45+ expect(46+ Result.isFailure(47+ Schema.decodeResult(SealedValue)({48+ ...sealed,49+ ciphertext: "not base64!",50+ })51+ )52+ ).toBeTruthy();53+ expect(Object.keys(SealedValue.fields).toSorted()).toStrictEqual([54+ "ciphertext",55+ "iv",56+ "keyVersion",57+ "wrappedKey",58+ ]);59+ });60+});added:packages/visibility/package.json+30 added
1+{2+ "name": "@repo/visibility",3+ "private": true,4+ "type": "module",5+ "exports": {6+ ".": "./src/index.ts",7+ "./*": "./src/*.ts"8+ },9+ "scripts": {10+ "typecheck": "tsc --noEmit -p tsconfig.json",11+ "test": "vitest run"12+ },13+ "dependencies": {14+ "@env-spec/parser": "0.6.1",15+ "@repo/artifacts": "workspace:*",16+ "@repo/brand": "workspace:*",17+ "@repo/checks": "workspace:*",18+ "@repo/git": "workspace:*",19+ "@repo/protocol": "workspace:*",20+ "effect": "catalog:"21+ },22+ "devDependencies": {23+ "@cloudflare/workers-types": "5.20261006.1",24+ "@effect/vitest": "catalog:",25+ "@repo/config": "workspace:*",26+ "@repo/testkit": "workspace:*",27+ "typescript": "catalog:",28+ "vitest": "catalog:"29+ }30+}added:packages/visibility/tsconfig.json+8 added
1+{2+ "extends": "../../tsconfig.base.json",3+ "compilerOptions": {4+ "allowImportingTsExtensions": true,5+ "types": ["@cloudflare/workers-types"]6+ },7+ "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]8+}added:packages/visibility/vitest.config.ts+1 added
1+export { preset as default } from "@repo/config/vitest";modified:AGENTS.md+1 added-1 removed
22 unmodified lines23 | 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`; `packages/protocol/test/render.test.ts`; `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `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); `apps/platform/test/mcp.test.ts` (each refusing MCP contract comes back as its exact refusal); `apps/cli/test/policy.test.ts`; `apps/cli/test/local/check.test.ts` (the local check gives the gateway's stage-1 refusals for the same commit) |24 | 4 | **One schema, many surfaces.** Change `packages/protocol`; every surface derives from it. Projections live only in `apps/*/src/surfaces.ts`. The CLI's command list is `commandDocs` in `@repo/agent-kit`, which the platform's skill, the CLI's MCP prompt and the web's `llms.txt` all read. | `apps/cli/test/commands-doc.test.ts` (the command list against the real CLI's commands, flags and positionals); `packages/protocol/test/mcp.test.ts` (every MCP tool's schemas, with no JSON Schema leak); per-package `allowedUnstableApis` with `unstableApiUsage` at error |25 | 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`) |26 | 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/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build). No fence: import direction and module-level state |27-| 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`, raised by the gate's stage 1 (`packages/gate/test/shape.test.ts`); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace or Artifacts binding). No fence yet: the gateway's layer guard (W6 606) |27+| 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`, raised by the gate's stage 1 (`packages/gate/test/shape.test.ts`); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace or Artifacts binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both). No fence yet: the gateway's layer guard (W6 606) |28 | 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`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`. No fence yet: one push deduped by (repo, sha) across the gateway's record and OnPush's (W3 313 #2) |29 | 9 | **Effect v4 only.** Read `node_modules/effect/src` 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` |30 | 10 | **Escapes need a reason.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries its reason after `--`, and is added only where no idiomatic code does the job. | `check` fails on an unused directive. No fence: the reason |31 | 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`) |113 unmodified linesmodified:bun.lock+24 added
335 unmodified lines336 "typescript": "catalog:",337 "vitest": "catalog:",338 },339 },340+ "packages/visibility": {341+ "name": "@repo/visibility",342+ "dependencies": {343+ "@env-spec/parser": "0.6.1",344+ "@repo/artifacts": "workspace:*",345+ "@repo/brand": "workspace:*",346+ "@repo/checks": "workspace:*",347+ "@repo/git": "workspace:*",348+ "@repo/protocol": "workspace:*",349+ "effect": "catalog:",350+ },351+ "devDependencies": {352+ "@cloudflare/workers-types": "5.20261006.1",353+ "@effect/vitest": "catalog:",354+ "@repo/config": "workspace:*",355+ "@repo/testkit": "workspace:*",356+ "typescript": "catalog:",357+ "vitest": "catalog:",358+ },359+ },360 },361 "catalog": {362 "@effect/platform-bun": "4.0.1",363 "@effect/vitest": "4.0.1",193 unmodified lines557 "@effect/vitest": ["@effect/vitest@4.0.1", "", { "peerDependencies": { "effect": "^4.0.1", "vitest": ">=5.0.0 <6.0.0" } }, "sha512-DbY9kf/018zBxRIX7rJwBnPVPzSarnUpcshm0vfYPFiDkSa7AFrXTh2BlDNUbrdrmqcIOBhVZ7GkEtxf8WiQrg=="],558 559 "@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],560 561+ "@env-spec/parser": ["@env-spec/parser@0.6.1", "", {}, "sha512-eEo2e45H5+UqkjpzT5Uf+rJWRn2OvZxQ4TUfDTOZx+W2QH+jEGjgU8145T9/eOvfd7uUCqP5xUAqvz+E6FOHSA=="],562+563 "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.1", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ=="],564 565 "@esbuild/android-arm": ["@esbuild/android-arm@0.28.1", "", { "os": "android", "cpu": "arm" }, "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ=="],566 302 unmodified lines869 "@repo/sdk": ["@repo/sdk@workspace:packages/sdk"],870 871 "@repo/testkit": ["@repo/testkit@workspace:packages/testkit"],872 873+ "@repo/visibility": ["@repo/visibility@workspace:packages/visibility"],874+875 "@repo/web": ["@repo/web@workspace:apps/web"],876 877 "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],878 1475 unmodified lines