Skip to content
Myr

Merge build/410-project-skill-at-landing: a project's contribute skill stays current, re-landed when its config changes and flagged when a copy is stale

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 16e418b, caf329b · Browse files · 8 files+1702 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+1702 added−9 removed

  • tests:+1091 added−0 removed
  • other:+611 added−9 removed

8 files+1702 added−9 removed

modified:apps/cli/src/local/check.ts+64 added-3 removed
28 unmodified lines
29import {30 AskId,31 CommitSha,32 Handle,33 LandedSha,34 ProjectName,35 RepoName,36} from "@repo/protocol/ids";37import { Person } from "@repo/protocol/principal";
29 unmodified lines
67 ConfigBundler,68 ConfigBundlerBun,69 localPolicy,70} from "./local-policy.ts";71import { staleGenerated } from "./stale.ts";72import type { StaleCopy } from "./stale.ts";7374const COMMAND = "check";7573/** What `check --json` prints on success: the ask, the diff it judged, and each lane. */76/** A generated file in the working copy that main's config no longer gives (`stale.ts`). */77const Stale = Schema.Struct({78 /** The landing the copy says it came from, when it names one. */79 landed: Schema.optionalKey(LandedSha),80 path: Schema.String,81});8283/**84 * What `check --json` prints on success: the ask, the diff it judged, each85 * lane, and the generated files that are out of date, when any are.86 */87const Checked = Schema.Struct({88 ask: AskId,89 base: CommitSha,90 head: CommitSha,91 lanes: Schema.Array(LaneResult),92 /** The last stage that ran: `shape` with `--shape-only`, else `checks`. */93 stage: Schema.Literals(["shape", "checks"]),94 stale: Schema.optionalKey(Schema.NonEmptyArray(Stale)),95});9697type Checked = typeof Checked.Type;98
27 unmodified lines
126 Effect.fail(new Reported())127 )128 );129130/**131 * What a stale copy is told: which file, the landing it names, why it can132 * differ (an older config or a hand edit; the copy alone can't say which),133 * and how to get a current one.134 */135const staleNote = ({ landed, path }: StaleCopy) =>136 `${path} differs from what main's config gives${Option.match(landed, {137 onNone: () => "",138 onSome: (sha) => ` (it says it was generated at ${sha})`,139 })}: it was generated for an older config, or edited by hand. The platform regenerates it whenever the config changes; pull main for the current copy instead of editing it.`;140141/** The stale copies as `--json` lists them: absent when there are none. */142const staleField = (stale: readonly StaleCopy[]) =>143 Array.match(stale, {144 onEmpty: () => ({}),145 onNonEmpty: (copies) => ({146 stale: Array.map(copies, ({ landed, path }) =>147 Option.match(landed, {148 onNone: () => ({ path }),149 onSome: (sha) => ({ landed: sha, path }),150 })151 ),152 }),153 });154155/** The signed-in profile's handle, when `login` learned one. */156const signedInHandle = Effect.flatMap(157 Effect.serviceOption(Credentials),158 Option.match({
345 unmodified lines
504 )505 )506 );507508 // Copies of the generated agent files main's config no longer gives.509 const stale = yield* staleGenerated({510 landed: policy.at,511 policy,512 project,513 root: context.root,514 });515516 yield* Effect.forEach(stale, (copy) => output.note(staleNote(copy)), {517 discard: true,518 });519520 const ask = Array.findFirst(policy.asks, ({ id }) => id === askId);521522 if (Option.isNone(ask)) {523 return yield* refuse(json, [new UnknownAsk({ ask: askId })]);
50 unmodified lines
574575 const judged = { ask: askId, base: facts.base, head: facts.head };576577 if (flags.noLanes) {527 const checked: Checked = { ...judged, lanes: [], stage: "shape" };578 const checked: Checked = {579 ...judged,580 lanes: [],581 stage: "shape",582 ...staleField(stale),583 };584585 return yield* output.success({586 command: COMMAND,587 data: yield* Effect.orDie(encodeChecked(checked)),
68 unmodified lines
656 if (Array.isReadonlyArrayNonEmpty(failed)) {657 return yield* refuse(json, failed);658 }659604 const checked: Checked = { ...judged, lanes: run.lanes, stage: "checks" };660 const checked: Checked = {661 ...judged,662 lanes: run.lanes,663 stage: "checks",664 ...staleField(stale),665 };666667 return yield* output.success({668 command: COMMAND,669 data: yield* Effect.orDie(encodeChecked(checked)),
9 unmodified lines
added:apps/cli/src/local/stale.ts+86 added
1/**2 * Stale generated files in a working copy (W4 410): the project's3 * contribute skill (`.agents/skills/<project>-contribute/SKILL.md` and its4 * `.claude/skills/` copy) and the block in its AGENTS.md, regenerated here5 * with `@repo/agent-kit` from the policy at `main` and compared with what is6 * on disk. The platform lands them again whenever the config changes what7 * they say, so a copy that differs was generated for an older config, or8 * was edited by hand; `<cli> check` warns about each one and lists it.9 *10 * Read only: nothing here writes a file. A missing file is no copy, and11 * never stale; nor is an AGENTS.md with no block, whose text is all the12 * project's own. A skill copy without the platform's frontmatter is stale:13 * its path is the platform's, so the frontmatter was taken off (`isStale`).14 */15import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";16import { isStale } from "@repo/agent-kit/generated-file";17import { projectSkill } from "@repo/agent-kit/project-skill";18import type { Policy } from "@repo/protocol/domain/policy";19import type { LandedSha, ProjectName } from "@repo/protocol/ids";20import { Effect, FileSystem, Option, Path } from "effect";2122/** A generated file on disk that is not what main's policy gives, and the landing its copy names. */23export interface StaleCopy {24 readonly path: string;25 /** The landing the copy says it came from; none for the AGENTS.md block, which names none, and for a skill copy without frontmatter. */26 readonly landed: Option.Option<LandedSha>;27}2829const agentsFile = "AGENTS.md";3031/**32 * Every generated file in the working copy at `root` that differs from the33 * one `policy` (read at the landing `landed`) gives: the skill's copies by34 * their recorded hash (`isStale`), the AGENTS.md block by its text.35 */36export const staleGenerated = (input: {37 readonly root: string;38 readonly project: ProjectName;39 readonly policy: Policy;40 readonly landed: LandedSha;41}): Effect.Effect<42 readonly StaleCopy[],43 never,44 FileSystem.FileSystem | Path.Path45> =>46 Effect.gen(function* () {47 const fs = yield* FileSystem.FileSystem;48 const path = yield* Path.Path;49 const { landed, policy, project } = input;5051 const onDisk = (file: string) =>52 Effect.option(fs.readFileString(path.join(input.root, file)));5354 const skills = yield* projectSkill({ landed, policy, project });5556 const staleSkills = yield* Effect.forEach(skills, (current) =>57 Effect.gen(function* () {58 const copy = yield* onDisk(current.path);5960 if (Option.isNone(copy)) {61 return [];62 }6364 const stale = yield* isStale(copy.value, current);6566 return Option.match(stale, {67 onNone: (): readonly StaleCopy[] => [],68 onSome: (found) => [{ landed: found.landed, path: current.path }],69 });70 })71 );7273 const block = yield* agentsBlock({ landed, policy, project });74 const agents = yield* onDisk(agentsFile);7576 const blockStale = Option.exists(77 agents,78 (text) =>79 text.includes(block.end) && upsertAgentsBlock(text, block) !== text80 );8182 return [83 ...staleSkills.flat(),84 ...(blockStale ? [{ landed: Option.none(), path: agentsFile }] : []),85 ];86 });
added:apps/cli/test/local/stale.test.ts+231 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";4import { projectSkill } from "@repo/agent-kit/project-skill";5import { Client } from "@repo/protocol/contracts";6import type { Policy } from "@repo/protocol/domain/policy";7import { RunBlock } from "@repo/protocol/domain/run";8import { Handle, LandedSha, ProjectName } from "@repo/protocol/ids";9import { gitOk } from "@repo/testkit/git";10import { Effect, Exit, FileSystem, Layer, Path, Schema } from "effect";11import { CliOutput } from "effect/cli";12import { TestConsole } from "effect/testing";1314import { ConfigBundlerBun, localPolicy } from "../../src/local/local-policy.ts";15import { program } from "../../src/main.ts";16import { OutputPlain } from "../../src/output.ts";17import { SignedOut } from "../signed-out.ts";18import { aCheckRepo, handle, project } from "./fixture.ts";19import type { CheckRepo } from "./fixture.ts";2021/** A platform no offline run may call. */22const unreachable = Layer.mock(Client)({});2324const services = Layer.mergeAll(25 TestConsole.layer,26 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),27 unreachable,28 OutputPlain,29 SignedOut30).pipe(Layer.provideMerge(NodeServices.layer));3132/** `check --offline --shape-only --json` in the repo: how it ended, and what it printed where. */33const checked = (root: string) =>34 Effect.gen(function* () {35 const exit = yield* Effect.exit(36 program(["check", "--dir", root, "--offline", "--shape-only", "--json"])37 );3839 const [out = ""] = (yield* TestConsole.logLines).map(String);4041 return {42 envelope: yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(43 out44 ),45 err: (yield* TestConsole.errorLines).map(String).join("\n"),46 exit,47 };48 }).pipe(Effect.provide(services));4950const name = ProjectName.make(project);5152const skill = `.agents/skills/${project}-contribute/SKILL.md`;5354/** The landing an older copy of the skill came from. */55const older = LandedSha.make("a".repeat(40));5657/** The policy at the fixture's main, as `check` reads it. */58const policyAtMain = (repo: CheckRepo) =>59 localPolicy(repo.root, "main", {60 initializer: Handle.make(handle),61 project: name,62 }).pipe(Effect.provide(ConfigBundlerBun));6364/** An older run block: one lane, `ok`, where main has two. */65const olderRun = Schema.decodeSync(RunBlock)({66 checks: { ok: "true" },67 test: "true {path}",68});6970/** The policy at main with the older run block. */71const withOlderRun = (policy: Policy): Policy => ({ ...policy, run: olderRun });7273/** Writes `content` at `file` in the repo's work tree, leaving it uncommitted. */74const writeFile = (repo: CheckRepo, file: string, content: string) =>75 Effect.gen(function* () {76 const fs = yield* FileSystem.FileSystem;77 const path = yield* Path.Path;78 const at = path.join(repo.root, file);7980 yield* fs.makeDirectory(path.dirname(at), { recursive: true });81 yield* fs.writeFileString(at, content);82 });8384/** The fixture with HEAD on its clean answer, which the shape stage passes. */85const cleanRepo = Effect.gen(function* () {86 const repo = yield* aCheckRepo;8788 yield* gitOk(repo.root, "checkout", "--quiet", "clean");8990 return repo;91});9293describe("check, on generated files", () => {94 it.live(95 "notes a contribute skill generated for an older run block, naming it and the landing it came from",96 () =>97 Effect.gen(function* () {98 const repo = yield* cleanRepo;99 const policy = yield* policyAtMain(repo);100101 const [copy] = yield* projectSkill({102 landed: older,103 policy: withOlderRun(policy),104 project: name,105 });106107 yield* writeFile(repo, skill, copy?.content ?? "");108109 const printed = yield* checked(repo.root);110111 expect(Exit.isSuccess(printed.exit)).toBeTruthy();112 expect(printed.envelope).toMatchObject({113 data: { stale: [{ landed: older, path: skill }] },114 ok: true,115 });116 expect(printed.err).toContain(117 `${skill} differs from what main's config gives`118 );119 expect(printed.err).toContain(older);120 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))121 );122123 it.live(124 "notes a contribute skill edited by hand since it was generated, naming the landing it came from",125 () =>126 Effect.gen(function* () {127 const repo = yield* cleanRepo;128 const policy = yield* policyAtMain(repo);129130 const [copy] = yield* projectSkill({131 landed: older,132 policy,133 project: name,134 });135136 yield* writeFile(137 repo,138 skill,139 `${copy?.content ?? ""}\nOne more rule of our own.\n`140 );141142 const printed = yield* checked(repo.root);143144 expect(printed.envelope).toMatchObject({145 data: { stale: [{ landed: older, path: skill }] },146 ok: true,147 });148 expect(printed.err).toContain(149 `${skill} differs from what main's config gives (it says it was generated at ${older})`150 );151 expect(printed.err).toContain("edited by hand");152 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))153 );154155 it.live(156 "notes an AGENTS.md block that is not the one main's policy gives",157 () =>158 Effect.gen(function* () {159 const repo = yield* cleanRepo;160 const policy = yield* policyAtMain(repo);161162 const block = yield* agentsBlock({163 landed: older,164 policy: withOlderRun(policy),165 project: name,166 });167168 yield* writeFile(169 repo,170 "AGENTS.md",171 upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)172 );173174 const printed = yield* checked(repo.root);175176 expect(printed.envelope).toMatchObject({177 data: { stale: [{ path: "AGENTS.md" }] },178 ok: true,179 });180 expect(printed.err).toContain(181 "AGENTS.md differs from what main's config gives"182 );183 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))184 );185186 it.live("says nothing of copies generated from main's policy", () =>187 Effect.gen(function* () {188 const repo = yield* cleanRepo;189 const policy = yield* policyAtMain(repo);190191 const copies = yield* projectSkill({192 landed: older,193 policy,194 project: name,195 });196197 const block = yield* agentsBlock({198 landed: older,199 policy,200 project: name,201 });202203 for (const copy of copies) {204 yield* writeFile(repo, copy.path, copy.content);205 }206207 yield* writeFile(208 repo,209 "AGENTS.md",210 upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)211 );212213 const printed = yield* checked(repo.root);214215 expect(Exit.isSuccess(printed.exit)).toBeTruthy();216 expect(printed.envelope).toStrictEqual({217 command: "check",218 data: {219 ask: "fix-a",220 base: repo.main,221 head: repo.clean,222 lanes: [],223 stage: "shape",224 },225 ok: true,226 v: 1,227 });228 expect(printed.err).not.toContain("differs from");229 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))230 );231});
added:apps/platform/src/workflows/generated.ts+41 added
added:apps/platform/test/generated.test.ts+537 added
1/**2 * The project's contribute skill kept current on the platform (W4 410): a3 * landing that changes what the generated files say is followed by the4 * platform's own landing of only those files, regenerated with5 * `@repo/agent-kit` as the platform's Project DOs do it6 * (`workflows/generated.ts`), credited `Decided-by` the decider whose7 * landing changed the config. Node world, memory adapters: `RepoHostMemory`,8 * W2's isomorphic-git `Lander` over it, a scripted Checker, `ProjectsMemory`,9 * and a rules evaluator whose run block is the config folder's `run.json`.10 */11import { describe, expect, it } from "@effect/vitest";12import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";13import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";14import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";15import { Brand } from "@repo/brand";16import { CheckAt, CheckRunner } from "@repo/checks/check-runner";17import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";18import { authorLine, creditsOf, parseTrailers } from "@repo/git/trailers";19import { treeDiff } from "@repo/git/tree-diff";20import { AlarmsMemory } from "@repo/project/alarms/memory";21import { AnswerRunsInline } from "@repo/project/answer-runs/inline";22import { platformHandle } from "@repo/project/attention/effects";23import { Lander } from "@repo/project/lander";24import { LanderIsogit } from "@repo/project/lander/isogit";25import { ProjectionMemory } from "@repo/project/projection/memory";26import { Projects } from "@repo/project/projects";27import { ProjectsMemory } from "@repo/project/projects/memory";28import type { LaneResult } from "@repo/protocol/domain/answer";29import { Outcome } from "@repo/protocol/domain/outcome";30import { RunBlock } from "@repo/protocol/domain/run";31import type { CommitSha } from "@repo/protocol/ids";32import {33 LandedSha,34 LaneName,35 RepoName,36 RepoPath,37 RequestId,38 TreeSha,39} from "@repo/protocol/ids";40import { Person } from "@repo/protocol/principal";41import { RepoBusy, VerifierBlocked } from "@repo/protocol/refusal";42import { RulesEvaluator } from "@repo/rules/rules-evaluator";43import { advanceTo } from "@repo/testkit/clock";44import { gitClient } from "@repo/testkit/git-client";45import type { Files } from "@repo/testkit/git-client";46import { aProject } from "@repo/testkit/scenarios";47import { Context, Effect, Exit, Layer, Option, Ref, Schema } from "effect";4849import { ProjectSkillGenerator } from "../src/workflows/generated.ts";5051const scenario = aProject();5253const { project } = scenario;5455const repo = RepoName.make(project);5657const alice = Person.make({ handle: scenario.initializer });5859const mainRef = RefName.make("refs/heads/main");6061const runFile = `${Brand.configDir}/run.json`;6263const skill = `.agents/skills/${project}-contribute/SKILL.md`;6465const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;6667const generatedPaths = [skill, claudeSkill, "AGENTS.md"];6869const lintOnly = { checks: { lint: "bun run lint" }, test: "bun test {path}" };7071const withUnit = {72 checks: { lint: "bun run lint", unit: "bun run test" },73 test: "bun test {path}",74};7576/** What alice pushes first: a package, the run block, and notes of the project's own. */77const start: Files = [78 ["package.json", '{ "name": "datekit" }\n'],79 ["src/parse.ts", "export const parse = (s) => ({});\n"],80 [runFile, `${JSON.stringify(lintOnly)}\n`],81 ["AGENTS.md", "# Datekit\n\nOur own notes for agents.\n"],82];8384const decodeRun = Schema.decodeEffect(Schema.fromJsonString(RunBlock));8586/**87 * The scenario's policy at any commit, with the run block its config88 * folder's `run.json` states, or lint alone when it states none.89 */90const rules = Layer.succeed(91 RulesEvaluator,92 RulesEvaluator.of({93 call: () => Effect.succeed(false),94 evaluate: ({ at, modules }) =>95 Effect.map(96 Effect.orDie(97 decodeRun(modules.modules[runFile] ?? JSON.stringify(lintOnly))98 ),99 (run) => ({ ...scenario.policy, at, run })100 ),101 })102);103104/** What the Checker answers: every lane passes on any tree the test names. */105class Passing extends Context.Service<106 Passing,107 {108 readonly on: (at: CheckAt, lanes: readonly string[]) => Effect.Effect<void>;109 }110>()("test/Passing") {}111112const checker = Layer.effectContext(113 Effect.gen(function* () {114 const script = new Map<string, readonly LaneResult[]>();115116 const memory = Context.get(117 yield* Layer.build(CheckRunnerMemory.layer(script)),118 CheckRunner119 );120121 return Context.make(CheckRunner, memory).pipe(122 Context.add(Passing, {123 on: (at, lanes) =>124 Effect.sync(() => {125 for (const name of lanes) {126 const lane = LaneName.make(name);127128 script.set(scriptKey(at, lane), [129 {130 command: `run ${lane}`,131 durationMs: 1,132 lane,133 result: "passed",134 },135 ]);136 }137 }),138 })139 );140 })141);142143/**144 * What goes wrong with the next follow-up's land, once: nothing, a busy145 * repo before anything is pushed, or a push that went through and whose146 * answer was lost on the way back (a Lander call that timed out after it).147 */148type Mishap = "none" | "busy" | "lost";149150class Mishaps extends Context.Service<151 Mishaps,152 { readonly next: (mishap: Mishap) => Effect.Effect<void> }153>()("test/Mishaps") {}154155/** W2's isomorphic-git Lander, with the next follow-up's mishap played on its land. */156const mishapLander = Layer.effectContext(157 Effect.gen(function* () {158 const real = Context.get(yield* Layer.build(LanderIsogit), Lander);159 const next = yield* Ref.make<Mishap>("none");160161 const land: Lander["Service"]["land"] = (job) =>162 Effect.gen(function* () {163 const mishap = job.requestId.startsWith("gen-")164 ? yield* Ref.getAndSet(next, "none")165 : "none";166167 if (mishap === "busy") {168 return yield* new RepoBusy({});169 }170171 const landed = yield* real.land(job);172173 return mishap === "lost" ? yield* new VerifierBlocked({}) : landed;174 });175176 return Context.make(Lander, Lander.of({ ...real, land })).pipe(177 Context.add(Mishaps, { next: (mishap) => Ref.set(next, mishap) })178 );179 })180);181182/** Commits made the way git would make them, pushed to a repo's `main`. */183class Pusher extends Context.Service<184 Pusher,185 {186 readonly push: (187 to: RepoName,188 parent: Option.Option<CommitSha>,189 files: Files190 ) => Effect.Effect<CommitSha>;191 }192>()("test/Pusher") {}193194const pusher = Layer.effect(195 Pusher,196 Effect.gen(function* () {197 const host = yield* RepoHost;198 const client = yield* gitClient(memoryFs());199200 return Pusher.of({201 push: (to, parent, files) =>202 Effect.gen(function* () {203 const sha = yield* client.commit(204 "Work",205 files,206 Option.toArray(parent)207 );208209 yield* host210 .push(to, client.source, [{ from: parent, ref: mainRef, to: sha }])211 .pipe(Effect.orDie);212213 return sha;214 }),215 });216 })217);218219/**220 * The project's ports, the generator only among the Project's own, as a221 * Project DO's shell gives them: the calls the test makes run without it.222 */223const world = Layer.mergeAll(224 ProjectsMemory.pipe(Layer.provide(ProjectSkillGenerator)),225 pusher226).pipe(227 Layer.provideMerge(228 Layer.mergeAll(AnswerRunsInline, AlarmsMemory, ProjectionMemory, rules)229 ),230 Layer.provideMerge(Layer.merge(mishapLander, checker)),231 Layer.provideMerge(RepoHostMemory)232);233234/** Where canonical `main` stands. */235const mainTip = Effect.gen(function* () {236 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);237238 return LandedSha.make(239 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))240 );241});242243const commitAt = (sha: CommitSha) =>244 Effect.flatMap(RepoHost, (host) =>245 host246 .readCommit(repo, sha)247 .pipe(Effect.orDie, Effect.flatMap(Effect.fromOption))248 ).pipe(Effect.orDie);249250/** A file's text at a commit of the canonical repo. */251const textAt = (sha: CommitSha, path: string) =>252 Effect.flatMap(RepoHost, (host) =>253 host254 .readFile(repo, Revision.Commit({ sha }), RepoPath.make(path))255 .pipe(256 Effect.orDie,257 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes)))258 )259 );260261/** What one commit changed against its first parent, by path. */262const changedBy = (sha: CommitSha) =>263 Effect.gen(function* () {264 const commit = yield* commitAt(sha);265 const parent = yield* commitAt(commit.parents[0] ?? sha);266267 const changes = yield* treeDiff(268 repo,269 TreeSha.make(parent.tree),270 TreeSha.make(commit.tree)271 ).pipe(Effect.orDie);272273 return changes.map(({ path }) => path).toSorted();274 });275276/** The platform's follow-up at `sha`: its parent, what it changed, who it credits and names. */277const followUpAt = (sha: CommitSha) =>278 Effect.gen(function* () {279 const commit = yield* commitAt(sha);280281 return {282 author: commit.author,283 changed: yield* changedBy(sha),284 credits: creditsOf(commit.message).credits,285 parent: commit.parents[0],286 requestId: parseTrailers(commit.message).find(287 ({ key }) => key === "Request-Id"288 )?.value,289 subject: commit.message.split("\n")[0],290 };291 });292293/** Every file of the tree at `sha` the test knows of, as a commit on it would carry them. */294const filesAt = (sha: CommitSha, run: typeof RunBlock.Encoded) =>295 Effect.gen(function* () {296 const generated = yield* Effect.forEach(generatedPaths, (path) =>297 Effect.map(298 textAt(sha, path),299 (text) => [path, Option.getOrElse(text, () => "")] as const300 )301 );302303 return [304 ...start.filter(([path]) => path !== runFile && path !== "AGENTS.md"),305 [runFile, `${JSON.stringify(run)}\n`],306 ...generated,307 ] satisfies Files;308 });309310/** The project made, and alice's first push to it recorded. */311const firstPushed = Effect.gen(function* () {312 yield* advanceTo("2026-10-07T12:00:00Z");313314 const api = yield* Projects.use((each) => each.create(project)).pipe(315 Effect.orDie316 );317318 yield* api.initProject(alice, {}).pipe(Effect.orDie);319320 const first = yield* Pusher.use((each) =>321 each.push(repo, Option.none(), start)322 );323324 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);325326 return { api, first };327});328329/** alice's own change from her working fork, `files` on top of `base`, made ready to land. */330const aliceLands = (base: LandedSha, files: Files, requestId: string) =>331 Effect.gen(function* () {332 const api = yield* Projects.use((each) => each.get(project)).pipe(333 Effect.orDie334 );335336 const { fork } = yield* api.fork(alice).pipe(Effect.orDie);337338 const head = yield* Pusher.use((each) =>339 each.push(fork, Option.some(base), files)340 );341342 const merged = yield* Lander.use((lander) =>343 lander.merge({ base, fork, head, main: base, repo })344 ).pipe(Effect.orDie);345346 yield* Passing.use((passing) =>347 passing.on(CheckAt.cases.Tree.make({ tree: merged.tree }), [348 "lint",349 "unit",350 ])351 );352353 const request = {354 base,355 head,356 message: "Change the project",357 requestId: RequestId.make(requestId),358 };359360 return { api, land: () => api.land(alice, request).pipe(Effect.orDie) };361 });362363const landedSha = (outcome: Outcome) =>364 Outcome.guards.Landed(outcome) ? Option.some(outcome.sha) : Option.none();365366describe("the contribute skill, regenerated by the platform", () => {367 it.effect(368 "follows the first push with a landing of the generated files alone, credited to the initializer",369 () =>370 Effect.gen(function* () {371 const { api, first } = yield* firstPushed;372 const tip = yield* mainTip;373374 expect(yield* followUpAt(tip)).toStrictEqual({375 author: authorLine(platformHandle),376 changed: generatedPaths.toSorted(),377 credits: [{ handle: alice.handle, role: "Decided-by" }],378 parent: first,379 requestId: `gen-${first}`,380 subject: "Regenerate the contribute skill and the AGENTS.md block",381 });382383 const agents = Option.getOrElse(384 yield* textAt(tip, "AGENTS.md"),385 () => ""386 );387388 expect(agents).toMatch(389 /^# Datekit\n\nOur own notes for agents\.\n\n<!-- BEGIN /u390 );391 expect(yield* textAt(tip, skill)).toStrictEqual(392 yield* textAt(tip, claudeSkill)393 );394395 // The same first push recorded again is still the project's first push.396 expect(397 yield* Effect.exit(api.recordFirstPush(alice, first))398 ).toStrictEqual(Exit.succeed({ landed: first }));399 expect(yield* mainTip).toBe(tip);400 }).pipe(Effect.provide(world))401 );402403 it.effect(404 "follows a landing that changed the run block with one more platform commit, and a replay lands nothing",405 () =>406 Effect.gen(function* () {407 yield* firstPushed;408409 const generatedOnce = yield* mainTip;410411 const changed = yield* aliceLands(412 generatedOnce,413 yield* filesAt(generatedOnce, withUnit),414 "land-alice-unit-lane"415 );416417 const landed = Option.getOrThrow(418 landedSha((yield* changed.land()).outcome)419 );420421 const tip = yield* mainTip;422423 expect(yield* changedBy(landed)).toStrictEqual([runFile]);424 expect(yield* followUpAt(tip)).toStrictEqual({425 author: authorLine(platformHandle),426 changed: generatedPaths.toSorted(),427 credits: [{ handle: alice.handle, role: "Decided-by" }],428 parent: landed,429 requestId: `gen-${landed}`,430 subject: "Regenerate the contribute skill and the AGENTS.md block",431 });432 expect(Option.getOrElse(yield* textAt(tip, skill), () => "")).toContain(433 "bun run test"434 );435436 const replayed = yield* changed.land();437438 expect(landedSha(replayed.outcome)).toStrictEqual(Option.some(landed));439 expect(yield* mainTip).toBe(tip);440 }).pipe(Effect.provide(world))441 );442443 it.effect(444 "lands nothing of its own after a landing that changed only src/",445 () =>446 Effect.gen(function* () {447 yield* firstPushed;448449 const generatedOnce = yield* mainTip;450 const files = yield* filesAt(generatedOnce, lintOnly);451452 const changed = yield* aliceLands(453 generatedOnce,454 files.map(([path, text]) =>455 path === "src/parse.ts"456 ? ([457 path,458 "export const parse = (s) => ({ year: 2026 });\n",459 ] as const)460 : ([path, text] as const)461 ),462 "land-alice-parse"463 );464465 const landed = landedSha((yield* changed.land()).outcome);466467 expect(Option.some(yield* mainTip)).toStrictEqual(landed);468 }).pipe(Effect.provide(world))469 );470471 it.effect(472 "leaves the landing it follows standing when the follow-up could not land",473 () =>474 Effect.gen(function* () {475 yield* firstPushed;476477 const generatedOnce = yield* mainTip;478479 const changed = yield* aliceLands(480 generatedOnce,481 yield* filesAt(generatedOnce, withUnit),482 "land-alice-unit-lane"483 );484485 yield* Mishaps.use((each) => each.next("busy"));486487 const landed = landedSha((yield* changed.land()).outcome);488489 expect(Option.some(yield* mainTip)).toStrictEqual(landed);490 expect(yield* changedBy(Option.getOrThrow(landed))).toStrictEqual([491 runFile,492 ]);493 }).pipe(Effect.provide(world))494 );495496 it.effect(497 "fails the call when the follow-up reached main but its answer was lost, and the call run again records both landings",498 () =>499 Effect.gen(function* () {500 yield* firstPushed;501502 const generatedOnce = yield* mainTip;503504 const changed = yield* aliceLands(505 generatedOnce,506 yield* filesAt(generatedOnce, withUnit),507 "land-alice-unit-lane"508 );509510 yield* Mishaps.use((each) => each.next("lost"));511512 const lost = yield* Effect.exit(changed.land());513 const tip = yield* mainTip;514 const followed = yield* followUpAt(tip);515 const again = yield* changed.land();516517 expect({518 followed: followed.requestId,519 lost: Exit.isFailure(lost),520 main: yield* mainTip,521 }).toStrictEqual({522 followed: `gen-${followed.parent}`,523 lost: true,524 main: tip,525 });526 expect(landedSha(again.outcome)).toStrictEqual(527 Option.some(followed.parent)528 );529530 const recorded = yield* changed.api531 .landing(alice, tip)532 .pipe(Effect.orDie);533534 expect(recorded.landing.requestId).toBe(`gen-${followed.parent}`);535 }).pipe(Effect.provide(world))536 );537});
added:packages/project/src/generated.ts+196 added
1/**2 * A project's generated files after a landing (spec D12, W4 410): the3 * contribute skill and the AGENTS.md block a stranger's agent reads, kept4 * current without anyone writing them. When a landing changes what they say5 * (the run block, the kinds, the judge closure, anything the generator reads6 * from the policy), the platform follows it with a landing of its own that7 * holds only the regenerated files: never folded into the landing that8 * changed the config ("land only the checked tree"), and never made when9 * nothing they say changed.10 *11 * Host-free and generator-free: the generator comes in as a function12 * (`Generate`), since `packages/project` may not import `@repo/agent-kit`13 * (spec §4.1). The platform gives the project its generator through14 * `ProjectGenerator`; a project given none generates nothing.15 */16import { Brand } from "@repo/brand";17import { formatLanding } from "@repo/git/trailers";18import type { Credit } from "@repo/protocol/domain/credit";19import type { LandingView } from "@repo/protocol/domain/landing";20import type { Policy } from "@repo/protocol/domain/policy";21import { RepoPath, RequestId, sameHandle } from "@repo/protocol/ids";22import type { Handle, LandedSha, ProjectName } from "@repo/protocol/ids";23import { Array, Context, Effect, Option } from "effect";2425import { decidersFor } from "./attention/decisions.ts";26import { platformHandle } from "./attention/effects.ts";2728/** One file a generator makes: where it goes, and every byte of it. */29export interface GeneratedFile {30 readonly path: string;31 readonly content: string;32}3334/** A file's text in the tree a landing left, if the tree has it. */35export type ReadAt = (path: string) => Effect.Effect<Option.Option<string>>;3637/**38 * Every generated file for one policy at one landing. `read` gives a file's39 * text at that landing, for a file the generator writes into rather than40 * over (AGENTS.md, whose text outside its block is the project's own).41 */42export type Generate = (input: {43 readonly project: ProjectName;44 readonly policy: Policy;45 readonly landed: LandedSha;46 readonly read: ReadAt;47}) => Effect.Effect<readonly GeneratedFile[]>;4849/** The platform's landing that follows another with the regenerated files. */50export interface FollowUp {51 /** The platform: it writes the files, nobody's answer does. */52 readonly author: Handle;53 /** `Decided-by` the decider whose landing changed what the files say. */54 readonly credits: readonly Credit[];55 /** The files whose text the tree does not hold yet, and only those. */56 readonly files: Array.NonEmptyReadonlyArray<GeneratedFile>;57 /** The whole commit message, trailers included. */58 readonly message: string;59 /** `gen-<landed>`: the same follow-up landed again finds the first one. */60 readonly requestId: RequestId;61}6263/**64 * How a host gives a project its generator (`@repo/agent-kit`'s, in the65 * platform). The default makes no files, so a project given none follows66 * no landing with one of its own.67 */68export const ProjectGenerator = Context.Reference<Generate>(69 "project/ProjectGenerator",70 { defaultValue: () => () => Effect.succeed([]) }71);7273/** The request a follow-up of the landing at `landed` lands as. */74export const generatedRequestId = (landed: LandedSha) =>75 RequestId.make(`gen-${landed}`);7677/** Where the config lives: whoever decides for it decides what the files say. */78const configPath = RepoPath.make(`${Brand.configDir}/project.ts`);7980/**81 * Who the follow-up credits: the landing's `Decided-by`, else its author82 * when they decide for the config, else the person who made the project.83 */84const deciderOf = (input: {85 readonly after: Policy;86 readonly initializer: Handle;87 readonly landing: LandingView;88}): Handle => {89 const { author, credits } = input.landing;9091 const decided = Array.findFirst(92 credits,93 ({ role }) => role === "Decided-by"94 ).pipe(Option.map(({ handle }) => handle));9596 const authorDecides = decidersFor(input.after, [configPath]).some((each) =>97 sameHandle(each, author)98 );99100 return Option.getOrElse(101 Option.orElse(decided, () =>102 authorDecides ? Option.some(author) : Option.none()103 ),104 () => input.initializer105 );106};107108/** Whether two generations say the same, file for file. */109const sameFiles = (110 one: readonly GeneratedFile[],111 other: readonly GeneratedFile[]112) =>113 one.length === other.length &&114 one.every(115 ({ content, path }, index) =>116 other[index]?.path === path && other[index]?.content === content117 );118119const messageOf = (input: {120 readonly credits: readonly Credit[];121 readonly files: readonly GeneratedFile[];122 readonly landed: LandedSha;123 readonly requestId: RequestId;124}) =>125 formatLanding({126 assisted: [],127 body: [128 `The config at ${input.landed} changed what these files say, so the platform wrote them again from it:`,129 "",130 ...input.files.map(({ path }) => `- ${path}`),131 ].join("\n"),132 credits: input.credits,133 requestId: input.requestId,134 subject: "Regenerate the contribute skill and the AGENTS.md block",135 });136137/**138 * The landing that follows `landing` with the regenerated files, or none.139 * None when the generator makes nothing, when the policy before the landing140 * gave the same files as the policy after it (the landing changed nothing141 * they say), or when the landed tree already holds every file as generated142 * (a replay after the follow-up landed, or a landing that brought them).143 * The first adoption has no policy before it, so it is followed unless its144 * tree holds the files already. The same input always gives the same files.145 */146export const generatedFollowUp = (147 input: {148 readonly project: ProjectName;149 /** The person who made the project: credited when no one else decided. */150 readonly initializer: Handle;151 /** The policy before the landing; none for the first adoption. */152 readonly before: Option.Option<Policy>;153 /** The policy read at the landing. */154 readonly after: Policy;155 readonly landing: LandingView;156 /** A file's text at the landed SHA. */157 readonly read: ReadAt;158 },159 generate: Generate160): Effect.Effect<Option.Option<FollowUp>> =>161 Effect.gen(function* () {162 const { landing, project, read } = input;163 const landed = landing.sha;164 const at = (policy: Policy) => generate({ landed, policy, project, read });165 const after = yield* at(input.after);166167 if (Option.isSome(input.before)) {168 const before = yield* at(input.before.value);169170 if (sameFiles(before, after)) {171 return Option.none();172 }173 }174175 const differing = yield* Effect.filter(after, ({ content, path }) =>176 Effect.map(read(path), (held) => !Option.contains(held, content))177 );178179 if (!Array.isReadonlyArrayNonEmpty(differing)) {180 return Option.none();181 }182183 const credits: readonly Credit[] = [184 { handle: deciderOf(input), role: "Decided-by" },185 ];186187 const requestId = generatedRequestId(landed);188189 return Option.some({190 author: platformHandle,191 credits,192 files: differing,193 message: messageOf({ credits, files: differing, landed, requestId }),194 requestId,195 });196 });
modified:packages/project/src/project.ts+224 added-6 removed
12 unmodified lines
13 * its arguments and its result against the contract's or the domain's14 * schemas (`MethodSchemas`, principle 2), which W3's Durable Object boundary15 * reuses.16 */17import { BranchName, RefName, RepoHost } from "@repo/artifacts/repo-host";17import {18 BranchName,19 RefName,20 RepoHost,21 Revision,22} from "@repo/artifacts/repo-host";23import type { RepoNotFound } from "@repo/artifacts/repo-host";24import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";25import { Brand } from "@repo/brand";26import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";
104 unmodified lines
131import { Finishers } from "@repo/rules/finish";132import { RulesEvaluator, sdkVersion } from "@repo/rules/rules-evaluator";133import {134 Array,135 Cause,136 Context,137 DateTime,138 Effect,139 Layer,
37 unmodified lines
177 nextDecisionId,178 strayDecision,179} from "./deciders.ts";180import type { DeciderApi, Opening } from "./deciders.ts";175import { askClosed, askOpened, judged, listingOf, numbered } from "./events.ts";176import type { ProjectEventInput } from "./events.ts";181import {182 askClosed,183 askOpened,184 judged,185 listingOf,186 numbered,187 ProjectEventInput,188} from "./events.ts";189import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";190import type { MissingCommit } from "./facts.ts";191import {192 generatedFollowUp,193 generatedRequestId,194 ProjectGenerator,195} from "./generated.ts";196import { Lander, Rebuild } from "./lander.ts";197import type { ComposedFile } from "./lander.ts";198import {199 LandingCommand,
901 unmodified lines
1101 const lander = Context.get(ports, Lander);1102 const runner = Context.get(ports, CheckRunner);1103 const rules = Context.get(ports, RulesEvaluator);1104 const alarms = Context.get(ports, Alarms);1105 // Read once, as the ports are: a call runs in its caller's context.1106 const generate = yield* ProjectGenerator;1107 const lock = yield* Semaphore.make(1);1108 const repo = RepoName.make(name);11091110 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>
215 unmodified lines
1326 /**1327 * One call that writes: under the project's lock it hydrates, runs1328 * `body` (pure transitions, and the port calls that decide them), and1329 * commits what it gathered; then, outside the lock, settles the outbox1311 * rows it wrote. A body that fails commits nothing.1330 * rows it wrote. A body that fails commits nothing. Every method calls1331 * it through `write`, which adds the generated follow-up to the body.1332 */1313 const write = <A, E>(1333 const writeLocked = <A, E>(1334 queue: AnswerQueue,1335 body: (1336 h: Hydrated,1337 writes: Writes,
170 unmodified lines
1508 })),1509 })1510 );15111512 // --------------------------------------------------------- generated15131514 /** A file's text at a landed commit of the canonical repo; none where it has no such file. */1515 const textAt = (at: LandedSha) => (path: string) =>1516 host1517 .readFile(repo, Revision.Commit({ sha: at }), RepoPath.make(path))1518 .pipe(1519 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))),1520 Effect.orDie1521 );15221523 /**1524 * The platform's own landing of the regenerated files on top of1525 * `landed`, recorded with the landing it follows: the files composed1526 * onto main and landed through the Lander, a compare-and-swap push of1527 * `main` then the mirror, as every platform landing is, with the request1528 * id `gen-<landed>`, so a replay finds its commit.1529 */1530 const landFollowUp = (input: {1531 readonly h: Hydrated;1532 readonly landed: LandedSha;1533 readonly landing: LandingView;1534 readonly now: DateTime.Utc;1535 /** The policy read at `landed`, encoded as the row holds it. */1536 readonly policy: Exclude<ProjectRow["policy"], undefined>;1537 readonly row: ProjectRow;1538 readonly writes: Writes;1539 }) =>1540 Effect.gen(function* () {1541 const { h, landed, landing, now, row, writes } = input;15421543 const made = yield* generatedFollowUp(1544 {1545 after: yield* Effect.orDie(decodePolicy(input.policy)),1546 before: h.policy,1547 initializer: row.initializer,1548 landing,1549 project: name,1550 read: textAt(landed),1551 },1552 generate1553 );15541555 if (Option.isNone(made)) {1556 return;1557 }15581559 const { author, credits, message, requestId } = made.value;15601561 const files = Array.map(made.value.files, ({ content, path }) => ({1562 content,1563 path: RepoPath.make(path),1564 }));15651566 const composed = yield* lander.compose({ files, main: landed, repo });15671568 const { sha } = yield* lander.land({1569 author,1570 main: landed,1571 message,1572 rebuild: Rebuild.Compose({ files }),1573 repo,1574 requestId,1575 tree: composed.tree,1576 verdict: Option.none(),1577 });15781579 const view: LandingView = {1580 assisted: [],1581 author,1582 credits,1583 landedAt: now,1584 parent: landed,1585 project: name,1586 requestId,1587 sha,1588 };15891590 const moved = yield* withPolicyAt({ ...row, landed: sha }, sha, now);15911592 writes.landings.push(view);1593 writes.events.push(1594 ProjectEventInput.Landed({ at: now, landing: view })1595 );1596 writes.project.set("row", moved);1597 });15981599 /**1600 * A follow-up that did not land. When canonical `main` still stands at1601 * `landed`, nothing of it reached main: the landing it follows stands,1602 * and the failure is logged. When main moved on (the push went through1603 * and the Lander's answer was lost), or where it stands can't be read,1604 * the call fails and commits nothing, so the project's landed SHA never1605 * falls behind main: the same call run again finds both commits by their1606 * request ids.1607 */1608 const unlanded = <E>(landed: LandedSha, cause: Cause.Cause<E>) =>1609 Effect.gen(function* () {1610 const refs = yield* Effect.option(host.refs(repo));16111612 if (Option.exists(refs, (all) => all.get(mainRef) === landed)) {1613 return yield* Effect.logWarning(1614 "the regenerated contribute skill and AGENTS.md block did not land",1615 cause1616 );1617 }16181619 yield* Effect.logError(1620 `main moved past ${landed} while the regenerated files landed: the call records nothing, so it can run again`,1621 cause1622 );16231624 return yield* Effect.orDie(Effect.failCause(cause));1625 });16261627 /**1628 * After a call moved the landed SHA (the first adoption, an answer, a1629 * decider's own landing, an ask opened, a vouch): the platform's own1630 * landing of the regenerated contribute skill and AGENTS.md block on1631 * top, when the policy read at the new landed SHA changes what they say1632 * (spec D12, W4 410). It never joins the landing that changed the config1633 * ("land only the checked tree"), and it is recorded in the same commit1634 * as the landing it follows, under the project's lock. It is1635 * bookkeeping: one that cannot land is logged, and the landing it follows1636 * stands; the next landing that changes the config writes the files1637 * again (`unlanded`).1638 */1639 const followUp = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>1640 Effect.gen(function* () {1641 const row = writes.project.get("row");1642 const landed = row?.landed;1643 const policy = row?.policy;16441645 if (1646 row === undefined ||1647 policy === undefined ||1648 landed === undefined ||1649 row.policyAt !== landed ||1650 Option.exists(h.project, (before) => before.landed === landed)1651 ) {1652 return;1653 }16541655 const requestId = generatedRequestId(landed);1656 const landing = writes.landings.find(({ sha }) => sha === landed);16571658 const followed = [...h.landings, ...writes.landings].some(1659 (each) => each.requestId === requestId1660 );16611662 if (landing === undefined || followed) {1663 return;1664 }16651666 yield* landFollowUp({1667 h,1668 landed,1669 landing,1670 now,1671 policy,1672 row,1673 writes,1674 }).pipe(1675 Effect.catchCause((cause) =>1676 Cause.hasInterruptsOnly(cause)1677 ? Effect.interrupt1678 : unlanded(landed, cause)1679 )1680 );1681 });16821683 /**1684 * One call that writes (`writeLocked`), with the generated follow-up of1685 * any landing the body recorded, in the same commit.1686 */1687 const write = <A, E>(1688 queue: AnswerQueue,1689 body: (1690 h: Hydrated,1691 writes: Writes,1692 now: DateTime.Utc1693 ) => Effect.Effect<A, E>1694 ): Effect.Effect<A, E> =>1695 writeLocked(queue, (h, writes, now) =>1696 Effect.tap(body(h, writes, now), () => followUp(h, writes, now))1697 );16981699 /** A `main` for an imported repo whose branch had another name, at its tip. */1700 const mainAt = (tip: CommitSha) =>1701 Effect.gen(function* () {1702 const empty = { fs: memoryFs(), gitdir: "/adopt.git" };
597 unmodified lines
2300 }23012302 const landed = LandedSha.make(head);23032304 // The same first push again: still the project's adoption (the one2305 // landing with no parent), whatever the platform landed on top of2306 // it since, such as the regenerated contribute skill.2307 if (row.state === "live") {2308 const adopted = h.landings.some(2309 ({ parent, sha }) => sha === landed && parent === undefined2310 );23112098 return row.landed === landed ? { landed } : yield* refused;2312 return row.landed === landed || adopted2313 ? { landed }2314 : yield* refused;2315 }23162317 writes.landings.push(adoption(row.initializer, landed, now));2318 writes.project.set(
936 unmodified lines
3255 const writes = writesOf();32563257 yield* tickAll(h, writes, now);3258 yield* decided.expire(h, writes, now);3259 // A decision that took its default may have landed (a revert).3260 yield* followUp(h, writes, now);32613262 return [...(yield* commit(h, writes, now)), ...h.outbox];3263 })3264 );
182 unmodified lines
added:packages/project/test/generated.test.ts+323 added
1import { describe, expect, it } from "@effect/vitest";2import { creditsOf, parseTrailers } from "@repo/git/trailers";3import type { LandingView } from "@repo/protocol/domain/landing";4import type { Policy } from "@repo/protocol/domain/policy";5import { RunBlock } from "@repo/protocol/domain/run";6import { Handle, LandedSha } from "@repo/protocol/ids";7import { aProject } from "@repo/testkit/scenarios";8import { DateTime, Effect, Option, Schema } from "effect";910import { platformHandle } from "../src/attention/effects.ts";11import { generatedFollowUp } from "../src/generated.ts";12import type { Generate } from "../src/generated.ts";1314const scenario = aProject({ deciders: ["alice", "dora"], people: ["bob"] });1516const { initializer, project } = scenario;1718const alice = initializer;1920const dora = Handle.make("dora");2122const bob = Handle.make("bob");2324const parent = LandedSha.make("1".repeat(40));2526const landed = LandedSha.make("2".repeat(40));2728/** The policy before the landing: lint and types. */29const before: Policy = { ...scenario.policy, at: parent };3031/** The same policy at the landing, read again there: nothing it says changed. */32const unchanged: Policy = { ...scenario.policy, at: landed };3334/** The policy at the landing, with a unit lane added to the run block. */35const withUnit: Policy = {36 ...unchanged,37 run: Schema.decodeSync(RunBlock)({38 checks: {39 lint: "bun run lint",40 types: "bun run typecheck",41 unit: "bun run test",42 },43 test: "bun test {path}",44 }),45};4647const skill = `.agents/skills/${project}-contribute/SKILL.md`;4849const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;5051/**52 * A generator as `@repo/agent-kit` is one, in miniature: the skill, twice,53 * naming the landing and the run block's lanes, and AGENTS.md with only the54 * text between its markers written over (appended when there are none).55 */56const generate: Generate = ({ landed: at, policy, read }) =>57 Effect.gen(function* () {58 const lanes = Object.entries(policy.run.checks)59 .map(([lane, command]) => `${lane}: ${command}`)60 .join(", ");6162 const content = `---\nlanded: ${at}\n---\nLanes: ${lanes}\n`;63 const block = `<!-- BEGIN -->\nLanes: ${lanes}\n<!-- END -->`;64 const existing = Option.getOrElse(yield* read("AGENTS.md"), () => "");65 const begin = existing.indexOf("<!-- BEGIN -->");66 const end = existing.indexOf("<!-- END -->");6768 const agents =69 begin === -1 || end === -170 ? `${existing}${block}\n`71 : `${existing.slice(0, begin)}${block}${existing.slice(end + "<!-- END -->".length)}`;7273 return [74 { content, path: skill },75 { content, path: claudeSkill },76 { content: agents, path: "AGENTS.md" },77 ];78 });7980/** The project's own AGENTS.md, with a block the platform wrote before. */81const ownAgents = [82 "# Datekit",83 "",84 "Our notes.",85 "",86 "<!-- BEGIN -->",87 "Lanes: lint: bun run lint",88 "<!-- END -->",89 "",90 "More notes.",91 "",92].join("\n");9394/** A tree that holds `files` and nothing else. */95const treeOf =96 (files: Readonly<Record<string, string>>) =>97 (path: string): Effect.Effect<Option.Option<string>> =>98 Effect.succeed(Option.fromUndefinedOr(files[path]));99100const at = DateTime.makeUnsafe("2026-10-07T12:00:00Z");101102/** alice's own landing from her working fork, which changed the config. */103const aliceLands: LandingView = {104 assisted: [],105 author: alice,106 credits: [{ handle: alice, role: "Signed-off-by" }],107 landedAt: at,108 parent,109 project,110 sha: landed,111};112113/** The first adoption: the initializer's first push, crediting no one. */114const firstPush: LandingView = {115 assisted: [],116 author: alice,117 credits: [],118 landedAt: at,119 project,120 sha: landed,121};122123const followUp = (input: {124 readonly before: Option.Option<Policy>;125 readonly after: Policy;126 readonly landing: LandingView;127 readonly tree?: Readonly<Record<string, string>>;128}) =>129 generatedFollowUp(130 {131 after: input.after,132 before: input.before,133 initializer,134 landing: input.landing,135 project,136 read: treeOf(input.tree ?? { "AGENTS.md": ownAgents }),137 },138 generate139 );140141const subjectOf = (message: string) => message.split("\n")[0] ?? "";142143/** Whom the follow-up of `landing`, after the run block changed, credits. */144const creditOf = (landing: LandingView) =>145 Effect.map(146 followUp({ after: withUnit, before: Option.some(before), landing }),147 Option.map(({ credits }) => credits)148 );149150describe(generatedFollowUp, () => {151 it.effect(152 "follows a landing that changed the run block with the regenerated files alone, credited to its decider",153 () =>154 Effect.gen(function* () {155 const made = yield* followUp({156 after: withUnit,157 before: Option.some(before),158 landing: aliceLands,159 });160161 const lanes =162 "Lanes: lint: bun run lint, types: bun run typecheck, unit: bun run test";163164 const skillText = `---\nlanded: ${landed}\n---\n${lanes}\n`;165166 expect(Option.map(made, ({ files }) => files)).toStrictEqual(167 Option.some([168 { content: skillText, path: skill },169 { content: skillText, path: claudeSkill },170 {171 content: [172 "# Datekit",173 "",174 "Our notes.",175 "",176 "<!-- BEGIN -->",177 lanes,178 "<!-- END -->",179 "",180 "More notes.",181 "",182 ].join("\n"),183 path: "AGENTS.md",184 },185 ])186 );187188 const { author, credits, message, requestId } = Option.getOrThrow(made);189190 expect({191 author,192 credits,193 requestId,194 subject: subjectOf(message),195 trailers: creditsOf(message).credits,196 trailersRequest: parseTrailers(message).find(197 ({ key }) => key === "Request-Id"198 )?.value,199 }).toStrictEqual({200 author: platformHandle,201 credits: [{ handle: alice, role: "Decided-by" }],202 requestId: `gen-${landed}`,203 subject: "Regenerate the contribute skill and the AGENTS.md block",204 trailers: [{ handle: alice, role: "Decided-by" }],205 trailersRequest: `gen-${landed}`,206 });207 })208 );209210 it.effect("lands nothing after a landing that changed only src/", () =>211 Effect.gen(function* () {212 expect(213 yield* followUp({214 after: unchanged,215 before: Option.some(before),216 landing: aliceLands,217 tree: {},218 })219 ).toStrictEqual(Option.none());220 })221 );222223 it.effect("makes the same files from the same input", () =>224 Effect.gen(function* () {225 const input = {226 after: withUnit,227 before: Option.some(before),228 landing: aliceLands,229 };230231 expect(yield* followUp(input)).toStrictEqual(yield* followUp(input));232 })233 );234235 it.effect(236 "lands nothing when the tree already holds the regenerated files, as after a replay",237 () =>238 Effect.gen(function* () {239 const made = Option.getOrThrow(240 yield* followUp({241 after: withUnit,242 before: Option.some(before),243 landing: aliceLands,244 })245 );246247 const regenerated = Object.fromEntries(248 made.files.map(({ content, path }) => [path, content])249 );250251 expect(252 yield* followUp({253 after: withUnit,254 before: Option.some(before),255 landing: aliceLands,256 tree: regenerated,257 })258 ).toStrictEqual(Option.none());259 })260 );261262 it.effect(263 "follows the first adoption, which had no policy before, crediting the initializer",264 () =>265 Effect.gen(function* () {266 const made = yield* followUp({267 after: unchanged,268 before: Option.none(),269 landing: firstPush,270 tree: {},271 });272273 expect(274 Option.map(made, ({ credits, files }) => ({275 credits,276 paths: files.map(({ path }) => path),277 }))278 ).toStrictEqual(279 Option.some({280 credits: [{ handle: alice, role: "Decided-by" }],281 paths: [skill, claudeSkill, "AGENTS.md"],282 })283 );284 })285 );286287 it.effect(288 "credits the landing's Decided-by first, then its author if they decide the config, else the initializer",289 () =>290 Effect.gen(function* () {291 const decidedByDora: LandingView = {292 ...aliceLands,293 author: bob,294 credits: [295 { handle: bob, role: "Signed-off-by" },296 { handle: dora, role: "Decided-by" },297 ],298 };299300 const doraLands: LandingView = {301 ...aliceLands,302 author: dora,303 credits: [{ handle: dora, role: "Signed-off-by" }],304 };305306 const bobAlone: LandingView = {307 ...aliceLands,308 author: bob,309 credits: [{ handle: bob, role: "Signed-off-by" }],310 };311312 expect({313 decidedBy: yield* creditOf(decidedByDora),314 deciderAuthor: yield* creditOf(doraLands),315 neither: yield* creditOf(bobAlone),316 }).toStrictEqual({317 decidedBy: Option.some([{ handle: dora, role: "Decided-by" }]),318 deciderAuthor: Option.some([{ handle: dora, role: "Decided-by" }]),319 neither: Option.some([{ handle: alice, role: "Decided-by" }]),320 });321 })322 );323});