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
Provenance
- Commit
defaf32- Tree
c14104e- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
16e418b- Parent 2
caf329b
8 files changed+1702 added−9 removed
modified:apps/cli/src/local/check.ts+64 added-3 removed
28 unmodified lines29 import {30 AskId,31 CommitSha,32 Handle,33+ LandedSha,34 ProjectName,35 RepoName,36 } from "@repo/protocol/ids";37 import { Person } from "@repo/protocol/principal";29 unmodified lines67 ConfigBundler,68 ConfigBundlerBun,69 localPolicy,70 } from "./local-policy.ts";71+import { staleGenerated } from "./stale.ts";72+import type { StaleCopy } from "./stale.ts";73 74 const COMMAND = "check";75 73-/** 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`). */77+const 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+});82+83+/**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+ */87 const 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 });96 97 type Checked = typeof Checked.Type;98 27 unmodified lines126 Effect.fail(new Reported())127 )128 );129 130+/**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+ */135+const 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.`;140+141+/** The stale copies as `--json` lists them: absent when there are none. */142+const 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+ });154+155 /** The signed-in profile's handle, when `login` learned one. */156 const signedInHandle = Effect.flatMap(157 Effect.serviceOption(Credentials),158 Option.match({345 unmodified lines504 )505 )506 );507 508+ // 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+ });515+516+ yield* Effect.forEach(stale, (copy) => output.note(staleNote(copy)), {517+ discard: true,518+ });519+520 const ask = Array.findFirst(policy.asks, ({ id }) => id === askId);521 522 if (Option.isNone(ask)) {523 return yield* refuse(json, [new UnknownAsk({ ask: askId })]);50 unmodified lines574 575 const judged = { ask: askId, base: facts.base, head: facts.head };576 577 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+ };584 585 return yield* output.success({586 command: COMMAND,587 data: yield* Effect.orDie(encodeChecked(checked)),68 unmodified lines656 if (Array.isReadonlyArrayNonEmpty(failed)) {657 return yield* refuse(json, failed);658 }659 604- 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+ };666 667 return yield* output.success({668 command: COMMAND,669 data: yield* Effect.orDie(encodeChecked(checked)),9 unmodified linesadded: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+ */15+import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";16+import { isStale } from "@repo/agent-kit/generated-file";17+import { projectSkill } from "@repo/agent-kit/project-skill";18+import type { Policy } from "@repo/protocol/domain/policy";19+import type { LandedSha, ProjectName } from "@repo/protocol/ids";20+import { Effect, FileSystem, Option, Path } from "effect";21+22+/** A generated file on disk that is not what main's policy gives, and the landing its copy names. */23+export 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+}28+29+const agentsFile = "AGENTS.md";30+31+/**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+ */36+export 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;50+51+ const onDisk = (file: string) =>52+ Effect.option(fs.readFileString(path.join(input.root, file)));53+54+ const skills = yield* projectSkill({ landed, policy, project });55+56+ const staleSkills = yield* Effect.forEach(skills, (current) =>57+ Effect.gen(function* () {58+ const copy = yield* onDisk(current.path);59+60+ if (Option.isNone(copy)) {61+ return [];62+ }63+64+ const stale = yield* isStale(copy.value, current);65+66+ return Option.match(stale, {67+ onNone: (): readonly StaleCopy[] => [],68+ onSome: (found) => [{ landed: found.landed, path: current.path }],69+ });70+ })71+ );72+73+ const block = yield* agentsBlock({ landed, policy, project });74+ const agents = yield* onDisk(agentsFile);75+76+ const blockStale = Option.exists(77+ agents,78+ (text) =>79+ text.includes(block.end) && upsertAgentsBlock(text, block) !== text80+ );81+82+ return [83+ ...staleSkills.flat(),84+ ...(blockStale ? [{ landed: Option.none(), path: agentsFile }] : []),85+ ];86+ });added:apps/cli/test/local/stale.test.ts+231 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";4+import { projectSkill } from "@repo/agent-kit/project-skill";5+import { Client } from "@repo/protocol/contracts";6+import type { Policy } from "@repo/protocol/domain/policy";7+import { RunBlock } from "@repo/protocol/domain/run";8+import { Handle, LandedSha, ProjectName } from "@repo/protocol/ids";9+import { gitOk } from "@repo/testkit/git";10+import { Effect, Exit, FileSystem, Layer, Path, Schema } from "effect";11+import { CliOutput } from "effect/cli";12+import { TestConsole } from "effect/testing";13+14+import { ConfigBundlerBun, localPolicy } from "../../src/local/local-policy.ts";15+import { program } from "../../src/main.ts";16+import { OutputPlain } from "../../src/output.ts";17+import { SignedOut } from "../signed-out.ts";18+import { aCheckRepo, handle, project } from "./fixture.ts";19+import type { CheckRepo } from "./fixture.ts";20+21+/** A platform no offline run may call. */22+const unreachable = Layer.mock(Client)({});23+24+const services = Layer.mergeAll(25+ TestConsole.layer,26+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),27+ unreachable,28+ OutputPlain,29+ SignedOut30+).pipe(Layer.provideMerge(NodeServices.layer));31+32+/** `check --offline --shape-only --json` in the repo: how it ended, and what it printed where. */33+const checked = (root: string) =>34+ Effect.gen(function* () {35+ const exit = yield* Effect.exit(36+ program(["check", "--dir", root, "--offline", "--shape-only", "--json"])37+ );38+39+ const [out = ""] = (yield* TestConsole.logLines).map(String);40+41+ 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));49+50+const name = ProjectName.make(project);51+52+const skill = `.agents/skills/${project}-contribute/SKILL.md`;53+54+/** The landing an older copy of the skill came from. */55+const older = LandedSha.make("a".repeat(40));56+57+/** The policy at the fixture's main, as `check` reads it. */58+const policyAtMain = (repo: CheckRepo) =>59+ localPolicy(repo.root, "main", {60+ initializer: Handle.make(handle),61+ project: name,62+ }).pipe(Effect.provide(ConfigBundlerBun));63+64+/** An older run block: one lane, `ok`, where main has two. */65+const olderRun = Schema.decodeSync(RunBlock)({66+ checks: { ok: "true" },67+ test: "true {path}",68+});69+70+/** The policy at main with the older run block. */71+const withOlderRun = (policy: Policy): Policy => ({ ...policy, run: olderRun });72+73+/** Writes `content` at `file` in the repo's work tree, leaving it uncommitted. */74+const 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);79+80+ yield* fs.makeDirectory(path.dirname(at), { recursive: true });81+ yield* fs.writeFileString(at, content);82+ });83+84+/** The fixture with HEAD on its clean answer, which the shape stage passes. */85+const cleanRepo = Effect.gen(function* () {86+ const repo = yield* aCheckRepo;87+88+ yield* gitOk(repo.root, "checkout", "--quiet", "clean");89+90+ return repo;91+});92+93+describe("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);100+101+ const [copy] = yield* projectSkill({102+ landed: older,103+ policy: withOlderRun(policy),104+ project: name,105+ });106+107+ yield* writeFile(repo, skill, copy?.content ?? "");108+109+ const printed = yield* checked(repo.root);110+111+ 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+ );122+123+ 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);129+130+ const [copy] = yield* projectSkill({131+ landed: older,132+ policy,133+ project: name,134+ });135+136+ yield* writeFile(137+ repo,138+ skill,139+ `${copy?.content ?? ""}\nOne more rule of our own.\n`140+ );141+142+ const printed = yield* checked(repo.root);143+144+ 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+ );154+155+ 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);161+162+ const block = yield* agentsBlock({163+ landed: older,164+ policy: withOlderRun(policy),165+ project: name,166+ });167+168+ yield* writeFile(169+ repo,170+ "AGENTS.md",171+ upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)172+ );173+174+ const printed = yield* checked(repo.root);175+176+ 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+ );185+186+ 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);190+191+ const copies = yield* projectSkill({192+ landed: older,193+ policy,194+ project: name,195+ });196+197+ const block = yield* agentsBlock({198+ landed: older,199+ policy,200+ project: name,201+ });202+203+ for (const copy of copies) {204+ yield* writeFile(repo, copy.path, copy.content);205+ }206+207+ yield* writeFile(208+ repo,209+ "AGENTS.md",210+ upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)211+ );212+213+ const printed = yield* checked(repo.root);214+215+ 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
1234567891011121314151617181920212223242526272829303132333435363738394041/** * The platform's generator for a project's own agent files (spec D12, W4 * 410): the contribute skill (`.agents/skills/<project>-contribute/SKILL.md` * and its `.claude/skills/` copy) and the block in the project's AGENTS.md, * from `@repo/agent-kit`, which `@repo/project` may not import (spec §4.1). * * The Project DO runs it after any landing that moved its landed SHA * (`@repo/project/generated`): when the policy read there changes what the * files say, the DO lands them as a separate platform commit, composed onto * main and landed through the Lander like every platform landing, with the * request id `gen-<landed>`. `ProjectSkillGenerator` is the layer a DO's * ports carry it in; a project whose ports leave it out generates nothing. */import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";import { projectSkill } from "@repo/agent-kit/project-skill";import { ProjectGenerator } from "@repo/project/generated";import type { Generate } from "@repo/project/generated";import { Effect, Layer, Option } from "effect";
/** The project's own AGENTS.md: only the block between the platform's markers is written. */const agentsFile = "AGENTS.md";
/** * The skill, in both places harnesses read it, and AGENTS.md as the landed * tree has it with the block put in (appended after a blank line when the * file has none; made when there is no file). */export const generate: Generate = ({ landed, policy, project, read }) => Effect.gen(function* () { const skills = yield* projectSkill({ landed, policy, project }); const block = yield* agentsBlock({ landed, policy, project }); const existing = Option.getOrElse(yield* read(agentsFile), () => "");
return [ ...skills, { content: upsertAgentsBlock(existing, block), path: agentsFile }, ]; });
/** The generator, for a Project DO's ports. */export const ProjectSkillGenerator = Layer.succeed(ProjectGenerator, generate);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+ */11+import { describe, expect, it } from "@effect/vitest";12+import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";13+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";14+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";15+import { Brand } from "@repo/brand";16+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";17+import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";18+import { authorLine, creditsOf, parseTrailers } from "@repo/git/trailers";19+import { treeDiff } from "@repo/git/tree-diff";20+import { AlarmsMemory } from "@repo/project/alarms/memory";21+import { AnswerRunsInline } from "@repo/project/answer-runs/inline";22+import { platformHandle } from "@repo/project/attention/effects";23+import { Lander } from "@repo/project/lander";24+import { LanderIsogit } from "@repo/project/lander/isogit";25+import { ProjectionMemory } from "@repo/project/projection/memory";26+import { Projects } from "@repo/project/projects";27+import { ProjectsMemory } from "@repo/project/projects/memory";28+import type { LaneResult } from "@repo/protocol/domain/answer";29+import { Outcome } from "@repo/protocol/domain/outcome";30+import { RunBlock } from "@repo/protocol/domain/run";31+import type { CommitSha } from "@repo/protocol/ids";32+import {33+ LandedSha,34+ LaneName,35+ RepoName,36+ RepoPath,37+ RequestId,38+ TreeSha,39+} from "@repo/protocol/ids";40+import { Person } from "@repo/protocol/principal";41+import { RepoBusy, VerifierBlocked } from "@repo/protocol/refusal";42+import { RulesEvaluator } from "@repo/rules/rules-evaluator";43+import { advanceTo } from "@repo/testkit/clock";44+import { gitClient } from "@repo/testkit/git-client";45+import type { Files } from "@repo/testkit/git-client";46+import { aProject } from "@repo/testkit/scenarios";47+import { Context, Effect, Exit, Layer, Option, Ref, Schema } from "effect";48+49+import { ProjectSkillGenerator } from "../src/workflows/generated.ts";50+51+const scenario = aProject();52+53+const { project } = scenario;54+55+const repo = RepoName.make(project);56+57+const alice = Person.make({ handle: scenario.initializer });58+59+const mainRef = RefName.make("refs/heads/main");60+61+const runFile = `${Brand.configDir}/run.json`;62+63+const skill = `.agents/skills/${project}-contribute/SKILL.md`;64+65+const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;66+67+const generatedPaths = [skill, claudeSkill, "AGENTS.md"];68+69+const lintOnly = { checks: { lint: "bun run lint" }, test: "bun test {path}" };70+71+const withUnit = {72+ checks: { lint: "bun run lint", unit: "bun run test" },73+ test: "bun test {path}",74+};75+76+/** What alice pushes first: a package, the run block, and notes of the project's own. */77+const 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+];83+84+const decodeRun = Schema.decodeEffect(Schema.fromJsonString(RunBlock));85+86+/**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+ */90+const 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+);103+104+/** What the Checker answers: every lane passes on any tree the test names. */105+class Passing extends Context.Service<106+ Passing,107+ {108+ readonly on: (at: CheckAt, lanes: readonly string[]) => Effect.Effect<void>;109+ }110+>()("test/Passing") {}111+112+const checker = Layer.effectContext(113+ Effect.gen(function* () {114+ const script = new Map<string, readonly LaneResult[]>();115+116+ const memory = Context.get(117+ yield* Layer.build(CheckRunnerMemory.layer(script)),118+ CheckRunner119+ );120+121+ 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);127+128+ 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+);142+143+/**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+ */148+type Mishap = "none" | "busy" | "lost";149+150+class Mishaps extends Context.Service<151+ Mishaps,152+ { readonly next: (mishap: Mishap) => Effect.Effect<void> }153+>()("test/Mishaps") {}154+155+/** W2's isomorphic-git Lander, with the next follow-up's mishap played on its land. */156+const 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");160+161+ 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";166+167+ if (mishap === "busy") {168+ return yield* new RepoBusy({});169+ }170+171+ const landed = yield* real.land(job);172+173+ return mishap === "lost" ? yield* new VerifierBlocked({}) : landed;174+ });175+176+ return Context.make(Lander, Lander.of({ ...real, land })).pipe(177+ Context.add(Mishaps, { next: (mishap) => Ref.set(next, mishap) })178+ );179+ })180+);181+182+/** Commits made the way git would make them, pushed to a repo's `main`. */183+class 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") {}193+194+const pusher = Layer.effect(195+ Pusher,196+ Effect.gen(function* () {197+ const host = yield* RepoHost;198+ const client = yield* gitClient(memoryFs());199+200+ 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+ );208+209+ yield* host210+ .push(to, client.source, [{ from: parent, ref: mainRef, to: sha }])211+ .pipe(Effect.orDie);212+213+ return sha;214+ }),215+ });216+ })217+);218+219+/**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+ */223+const 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+);233+234+/** Where canonical `main` stands. */235+const mainTip = Effect.gen(function* () {236+ const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);237+238+ return LandedSha.make(239+ Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))240+ );241+});242+243+const 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);249+250+/** A file's text at a commit of the canonical repo. */251+const 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+ );260+261+/** What one commit changed against its first parent, by path. */262+const changedBy = (sha: CommitSha) =>263+ Effect.gen(function* () {264+ const commit = yield* commitAt(sha);265+ const parent = yield* commitAt(commit.parents[0] ?? sha);266+267+ const changes = yield* treeDiff(268+ repo,269+ TreeSha.make(parent.tree),270+ TreeSha.make(commit.tree)271+ ).pipe(Effect.orDie);272+273+ return changes.map(({ path }) => path).toSorted();274+ });275+276+/** The platform's follow-up at `sha`: its parent, what it changed, who it credits and names. */277+const followUpAt = (sha: CommitSha) =>278+ Effect.gen(function* () {279+ const commit = yield* commitAt(sha);280+281+ 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+ });292+293+/** Every file of the tree at `sha` the test knows of, as a commit on it would carry them. */294+const 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+ );302+303+ return [304+ ...start.filter(([path]) => path !== runFile && path !== "AGENTS.md"),305+ [runFile, `${JSON.stringify(run)}\n`],306+ ...generated,307+ ] satisfies Files;308+ });309+310+/** The project made, and alice's first push to it recorded. */311+const firstPushed = Effect.gen(function* () {312+ yield* advanceTo("2026-10-07T12:00:00Z");313+314+ const api = yield* Projects.use((each) => each.create(project)).pipe(315+ Effect.orDie316+ );317+318+ yield* api.initProject(alice, {}).pipe(Effect.orDie);319+320+ const first = yield* Pusher.use((each) =>321+ each.push(repo, Option.none(), start)322+ );323+324+ yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);325+326+ return { api, first };327+});328+329+/** alice's own change from her working fork, `files` on top of `base`, made ready to land. */330+const 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+ );335+336+ const { fork } = yield* api.fork(alice).pipe(Effect.orDie);337+338+ const head = yield* Pusher.use((each) =>339+ each.push(fork, Option.some(base), files)340+ );341+342+ const merged = yield* Lander.use((lander) =>343+ lander.merge({ base, fork, head, main: base, repo })344+ ).pipe(Effect.orDie);345+346+ yield* Passing.use((passing) =>347+ passing.on(CheckAt.cases.Tree.make({ tree: merged.tree }), [348+ "lint",349+ "unit",350+ ])351+ );352+353+ const request = {354+ base,355+ head,356+ message: "Change the project",357+ requestId: RequestId.make(requestId),358+ };359+360+ return { api, land: () => api.land(alice, request).pipe(Effect.orDie) };361+ });362+363+const landedSha = (outcome: Outcome) =>364+ Outcome.guards.Landed(outcome) ? Option.some(outcome.sha) : Option.none();365+366+describe("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;373+374+ 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+ });382+383+ const agents = Option.getOrElse(384+ yield* textAt(tip, "AGENTS.md"),385+ () => ""386+ );387+388+ 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+ );394+395+ // 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+ );402+403+ 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;408+409+ const generatedOnce = yield* mainTip;410+411+ const changed = yield* aliceLands(412+ generatedOnce,413+ yield* filesAt(generatedOnce, withUnit),414+ "land-alice-unit-lane"415+ );416+417+ const landed = Option.getOrThrow(418+ landedSha((yield* changed.land()).outcome)419+ );420+421+ const tip = yield* mainTip;422+423+ 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+ );435+436+ const replayed = yield* changed.land();437+438+ expect(landedSha(replayed.outcome)).toStrictEqual(Option.some(landed));439+ expect(yield* mainTip).toBe(tip);440+ }).pipe(Effect.provide(world))441+ );442+443+ it.effect(444+ "lands nothing of its own after a landing that changed only src/",445+ () =>446+ Effect.gen(function* () {447+ yield* firstPushed;448+449+ const generatedOnce = yield* mainTip;450+ const files = yield* filesAt(generatedOnce, lintOnly);451+452+ 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+ );464+465+ const landed = landedSha((yield* changed.land()).outcome);466+467+ expect(Option.some(yield* mainTip)).toStrictEqual(landed);468+ }).pipe(Effect.provide(world))469+ );470+471+ it.effect(472+ "leaves the landing it follows standing when the follow-up could not land",473+ () =>474+ Effect.gen(function* () {475+ yield* firstPushed;476+477+ const generatedOnce = yield* mainTip;478+479+ const changed = yield* aliceLands(480+ generatedOnce,481+ yield* filesAt(generatedOnce, withUnit),482+ "land-alice-unit-lane"483+ );484+485+ yield* Mishaps.use((each) => each.next("busy"));486+487+ const landed = landedSha((yield* changed.land()).outcome);488+489+ expect(Option.some(yield* mainTip)).toStrictEqual(landed);490+ expect(yield* changedBy(Option.getOrThrow(landed))).toStrictEqual([491+ runFile,492+ ]);493+ }).pipe(Effect.provide(world))494+ );495+496+ 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;501+502+ const generatedOnce = yield* mainTip;503+504+ const changed = yield* aliceLands(505+ generatedOnce,506+ yield* filesAt(generatedOnce, withUnit),507+ "land-alice-unit-lane"508+ );509+510+ yield* Mishaps.use((each) => each.next("lost"));511+512+ const lost = yield* Effect.exit(changed.land());513+ const tip = yield* mainTip;514+ const followed = yield* followUpAt(tip);515+ const again = yield* changed.land();516+517+ 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+ );529+530+ const recorded = yield* changed.api531+ .landing(alice, tip)532+ .pipe(Effect.orDie);533+534+ 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+ */16+import { Brand } from "@repo/brand";17+import { formatLanding } from "@repo/git/trailers";18+import type { Credit } from "@repo/protocol/domain/credit";19+import type { LandingView } from "@repo/protocol/domain/landing";20+import type { Policy } from "@repo/protocol/domain/policy";21+import { RepoPath, RequestId, sameHandle } from "@repo/protocol/ids";22+import type { Handle, LandedSha, ProjectName } from "@repo/protocol/ids";23+import { Array, Context, Effect, Option } from "effect";24+25+import { decidersFor } from "./attention/decisions.ts";26+import { platformHandle } from "./attention/effects.ts";27+28+/** One file a generator makes: where it goes, and every byte of it. */29+export interface GeneratedFile {30+ readonly path: string;31+ readonly content: string;32+}33+34+/** A file's text in the tree a landing left, if the tree has it. */35+export type ReadAt = (path: string) => Effect.Effect<Option.Option<string>>;36+37+/**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+ */42+export type Generate = (input: {43+ readonly project: ProjectName;44+ readonly policy: Policy;45+ readonly landed: LandedSha;46+ readonly read: ReadAt;47+}) => Effect.Effect<readonly GeneratedFile[]>;48+49+/** The platform's landing that follows another with the regenerated files. */50+export 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+}62+63+/**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+ */68+export const ProjectGenerator = Context.Reference<Generate>(69+ "project/ProjectGenerator",70+ { defaultValue: () => () => Effect.succeed([]) }71+);72+73+/** The request a follow-up of the landing at `landed` lands as. */74+export const generatedRequestId = (landed: LandedSha) =>75+ RequestId.make(`gen-${landed}`);76+77+/** Where the config lives: whoever decides for it decides what the files say. */78+const configPath = RepoPath.make(`${Brand.configDir}/project.ts`);79+80+/**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+ */84+const deciderOf = (input: {85+ readonly after: Policy;86+ readonly initializer: Handle;87+ readonly landing: LandingView;88+}): Handle => {89+ const { author, credits } = input.landing;90+91+ const decided = Array.findFirst(92+ credits,93+ ({ role }) => role === "Decided-by"94+ ).pipe(Option.map(({ handle }) => handle));95+96+ const authorDecides = decidersFor(input.after, [configPath]).some((each) =>97+ sameHandle(each, author)98+ );99+100+ return Option.getOrElse(101+ Option.orElse(decided, () =>102+ authorDecides ? Option.some(author) : Option.none()103+ ),104+ () => input.initializer105+ );106+};107+108+/** Whether two generations say the same, file for file. */109+const 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+ );118+119+const 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+ });136+137+/**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+ */146+export 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);166+167+ if (Option.isSome(input.before)) {168+ const before = yield* at(input.before.value);169+170+ if (sameFiles(before, after)) {171+ return Option.none();172+ }173+ }174+175+ const differing = yield* Effect.filter(after, ({ content, path }) =>176+ Effect.map(read(path), (held) => !Option.contains(held, content))177+ );178+179+ if (!Array.isReadonlyArrayNonEmpty(differing)) {180+ return Option.none();181+ }182+183+ const credits: readonly Credit[] = [184+ { handle: deciderOf(input), role: "Decided-by" },185+ ];186+187+ const requestId = generatedRequestId(landed);188+189+ 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 lines13 * 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 */17-import { BranchName, RefName, RepoHost } from "@repo/artifacts/repo-host";17+import {18+ BranchName,19+ RefName,20+ RepoHost,21+ Revision,22+} from "@repo/artifacts/repo-host";23 import type { RepoNotFound } from "@repo/artifacts/repo-host";24 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";25 import { Brand } from "@repo/brand";26 import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";104 unmodified lines131 import { Finishers } from "@repo/rules/finish";132 import { RulesEvaluator, sdkVersion } from "@repo/rules/rules-evaluator";133 import {134 Array,135+ Cause,136 Context,137 DateTime,138 Effect,139 Layer,37 unmodified lines177 nextDecisionId,178 strayDecision,179 } from "./deciders.ts";180 import type { DeciderApi, Opening } from "./deciders.ts";175-import { askClosed, askOpened, judged, listingOf, numbered } from "./events.ts";176-import type { ProjectEventInput } from "./events.ts";181+import {182+ askClosed,183+ askOpened,184+ judged,185+ listingOf,186+ numbered,187+ ProjectEventInput,188+} from "./events.ts";189 import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";190 import type { MissingCommit } from "./facts.ts";191+import {192+ generatedFollowUp,193+ generatedRequestId,194+ ProjectGenerator,195+} from "./generated.ts";196 import { Lander, Rebuild } from "./lander.ts";197 import type { ComposedFile } from "./lander.ts";198 import {199 LandingCommand,901 unmodified lines1101 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);1109 1110 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>215 unmodified lines1326 /**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 lines1508 })),1509 })1510 );1511 1512+ // --------------------------------------------------------- generated1513+1514+ /** 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+ );1522+1523+ /**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;1542+1543+ 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+ );1554+1555+ if (Option.isNone(made)) {1556+ return;1557+ }1558+1559+ const { author, credits, message, requestId } = made.value;1560+1561+ const files = Array.map(made.value.files, ({ content, path }) => ({1562+ content,1563+ path: RepoPath.make(path),1564+ }));1565+1566+ const composed = yield* lander.compose({ files, main: landed, repo });1567+1568+ 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+ });1578+1579+ const view: LandingView = {1580+ assisted: [],1581+ author,1582+ credits,1583+ landedAt: now,1584+ parent: landed,1585+ project: name,1586+ requestId,1587+ sha,1588+ };1589+1590+ const moved = yield* withPolicyAt({ ...row, landed: sha }, sha, now);1591+1592+ writes.landings.push(view);1593+ writes.events.push(1594+ ProjectEventInput.Landed({ at: now, landing: view })1595+ );1596+ writes.project.set("row", moved);1597+ });1598+1599+ /**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));1611+1612+ 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+ }1618+1619+ yield* Effect.logError(1620+ `main moved past ${landed} while the regenerated files landed: the call records nothing, so it can run again`,1621+ cause1622+ );1623+1624+ return yield* Effect.orDie(Effect.failCause(cause));1625+ });1626+1627+ /**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;1644+1645+ 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+ }1654+1655+ const requestId = generatedRequestId(landed);1656+ const landing = writes.landings.find(({ sha }) => sha === landed);1657+1658+ const followed = [...h.landings, ...writes.landings].some(1659+ (each) => each.requestId === requestId1660+ );1661+1662+ if (landing === undefined || followed) {1663+ return;1664+ }1665+1666+ 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+ });1682+1683+ /**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+ );1698+1699 /** 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 lines2300 }2301 2302 const landed = LandedSha.make(head);2303 2304+ // 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+ );2311+2098- return row.landed === landed ? { landed } : yield* refused;2312+ return row.landed === landed || adopted2313+ ? { landed }2314+ : yield* refused;2315 }2316 2317 writes.landings.push(adoption(row.initializer, landed, now));2318 writes.project.set(936 unmodified lines3255 const writes = writesOf();3256 3257 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);3261 3262 return [...(yield* commit(h, writes, now)), ...h.outbox];3263 })3264 );182 unmodified linesadded:packages/project/test/generated.test.ts+323 added
1+import { describe, expect, it } from "@effect/vitest";2+import { creditsOf, parseTrailers } from "@repo/git/trailers";3+import type { LandingView } from "@repo/protocol/domain/landing";4+import type { Policy } from "@repo/protocol/domain/policy";5+import { RunBlock } from "@repo/protocol/domain/run";6+import { Handle, LandedSha } from "@repo/protocol/ids";7+import { aProject } from "@repo/testkit/scenarios";8+import { DateTime, Effect, Option, Schema } from "effect";9+10+import { platformHandle } from "../src/attention/effects.ts";11+import { generatedFollowUp } from "../src/generated.ts";12+import type { Generate } from "../src/generated.ts";13+14+const scenario = aProject({ deciders: ["alice", "dora"], people: ["bob"] });15+16+const { initializer, project } = scenario;17+18+const alice = initializer;19+20+const dora = Handle.make("dora");21+22+const bob = Handle.make("bob");23+24+const parent = LandedSha.make("1".repeat(40));25+26+const landed = LandedSha.make("2".repeat(40));27+28+/** The policy before the landing: lint and types. */29+const before: Policy = { ...scenario.policy, at: parent };30+31+/** The same policy at the landing, read again there: nothing it says changed. */32+const unchanged: Policy = { ...scenario.policy, at: landed };33+34+/** The policy at the landing, with a unit lane added to the run block. */35+const 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+};46+47+const skill = `.agents/skills/${project}-contribute/SKILL.md`;48+49+const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;50+51+/**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+ */56+const 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(", ");61+62+ 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 -->");67+68+ const agents =69+ begin === -1 || end === -170+ ? `${existing}${block}\n`71+ : `${existing.slice(0, begin)}${block}${existing.slice(end + "<!-- END -->".length)}`;72+73+ return [74+ { content, path: skill },75+ { content, path: claudeSkill },76+ { content: agents, path: "AGENTS.md" },77+ ];78+ });79+80+/** The project's own AGENTS.md, with a block the platform wrote before. */81+const 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");93+94+/** A tree that holds `files` and nothing else. */95+const treeOf =96+ (files: Readonly<Record<string, string>>) =>97+ (path: string): Effect.Effect<Option.Option<string>> =>98+ Effect.succeed(Option.fromUndefinedOr(files[path]));99+100+const at = DateTime.makeUnsafe("2026-10-07T12:00:00Z");101+102+/** alice's own landing from her working fork, which changed the config. */103+const 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+};112+113+/** The first adoption: the initializer's first push, crediting no one. */114+const firstPush: LandingView = {115+ assisted: [],116+ author: alice,117+ credits: [],118+ landedAt: at,119+ project,120+ sha: landed,121+};122+123+const 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+ );140+141+const subjectOf = (message: string) => message.split("\n")[0] ?? "";142+143+/** Whom the follow-up of `landing`, after the run block changed, credits. */144+const creditOf = (landing: LandingView) =>145+ Effect.map(146+ followUp({ after: withUnit, before: Option.some(before), landing }),147+ Option.map(({ credits }) => credits)148+ );149+150+describe(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+ });160+161+ const lanes =162+ "Lanes: lint: bun run lint, types: bun run typecheck, unit: bun run test";163+164+ const skillText = `---\nlanded: ${landed}\n---\n${lanes}\n`;165+166+ 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+ );187+188+ const { author, credits, message, requestId } = Option.getOrThrow(made);189+190+ 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+ );209+210+ 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+ );222+223+ 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+ };230+231+ expect(yield* followUp(input)).toStrictEqual(yield* followUp(input));232+ })233+ );234+235+ 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+ );246+247+ const regenerated = Object.fromEntries(248+ made.files.map(({ content, path }) => [path, content])249+ );250+251+ 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+ );261+262+ 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+ });272+273+ 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+ );286+287+ 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+ };299+300+ const doraLands: LandingView = {301+ ...aliceLands,302+ author: dora,303+ credits: [{ handle: dora, role: "Signed-off-by" }],304+ };305+306+ const bobAlone: LandingView = {307+ ...aliceLands,308+ author: bob,309+ credits: [{ handle: bob, role: "Signed-off-by" }],310+ };311+312+ 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+});