Keep a project's contribute skill current: the platform follows a landing that changes what it says with its own landing of the regenerated files, and check warns about stale copies
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- packages/project/src/generated.ts: `generatedFollowUp(input, generate)` is pure and takes the generator as a function, since project may not import agent-kit (spec §4.1). It returns none when the generator makes nothing, when the policy before the landing gives the same files as the policy after it, or when the landed tree already holds every file byte for byte (a replay). Otherwise it returns only the differing files, a message (subject "Regenerate the contribute skill and the AGENTS.md block", the paths, `Decided-by`, `Request-Id: gen-<landed>`) and author the platform. Credit goes to the landing's `Decided-by`, else its author when they decide for the config, else the initializer. `ProjectGenerator` is a `Context.Reference` whose default makes no files. - packages/project/src/project.ts: every writing call (`write`, now `writeLocked` plus the hook, so the deciders' kernel is covered too) and the alarm path run `followUp` after the body. When the call moved the landed SHA and read the policy there, it composes the follow-up's files onto main and lands them through the Lander (`Rebuild.Compose`, CAS push of main, then the mirror) under the project's lock with request id `gen-<landed>`. The landing (row, `Landed` event, landed SHA, policy read again) is recorded in the same commit as the landing it follows. A follow-up that cannot land is logged, and the landing it follows stands. The generator is read once when the service is built, as the ports are. - Why in the DO and not after `runAnswer` (issue 410 Comment 1): answers never touch the config (`TouchedJudge`). The config changes through a decider's own `land`, which runs inside the DO call, and through the first adoption. So the hook in `write` catches every such landing, with no new ProjectApi method, no Answer Workflow change, and no `gen-` request through `AnswerRuns` (one would have died as `UnknownRequest` in `runAnswer`). - apps/platform/src/workflows/generated.ts: `generate` writes agent-kit's `projectSkill` (both copies) and AGENTS.md with `agentsBlock` upserted into the landed text. `ProjectSkillGenerator` is its layer. Wiring it into the Project DO's ports in `project-do.ts` is outside this issue's territory and is left to the integrator (issue Comments), so the feature is off in production until then (about 20 KB more entry). - apps/cli/src/local/stale.ts and check.ts: `staleGenerated` regenerates the skill and the AGENTS.md block from the policy at main and compares them with the working copy. Skills are compared through `isStale`, so a landing alone never makes a copy stale. The block is compared by text when the file has one. `check` notes each stale copy on stderr, naming it and the landing it came from. `--json` success data gains `stale: [{path, landed?}]` only when one is stale. - Tests: packages/project/test/generated.test.ts covers the run block changed, src/ only, determinism, a tree already holding the files, first adoption, and credit order. apps/platform/test/generated.test.ts uses a Node world with memory adapters and the real generator. The first push is followed by a platform commit of the three files credited to the initializer. A decider's landing that changes the run block is followed by one more commit of only those files with `Decided-by`, and its replay leaves main alone. A src-only landing gets no follow-up. The generator is given to `ProjectsMemory` alone, which caught a call-time read of the reference. apps/cli/test/local/stale.test.ts covers an older skill copy, an older AGENTS.md block, and fresh copies with no note. Each test was red by assertion first. - Interface drift: `Generate` also takes `read` (AGENTS.md keeps the project's own text). `generatedFollowUp` takes `initializer`. `FollowUp` adds `author` and `requestId`, and its `message` carries the trailers. `staleGenerated` takes `{root, project, policy, landed}`. - ASSUMPTION: the policy at the follow-up's commit is read again (one more `bundleRules`), not copied from the one it follows, because rules may read the root files the follow-up adds. - verify green: project 337, platform 326, cli 237; platform entry 1,550,511 of 1,665,000.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+1480 added−8 removed
- tests:+938 added−0 removed
- other:+542 added−8 removed
Provenance
- Commit
a30d422- Tree
a5d6f56- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
b08d5f6
8 files changed+1480 added−8 removed
modified:apps/cli/src/local/check.ts+61 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+/** What a stale copy is told: which file, the landing it names, and how to get a current one. */131+const staleNote = ({ landed, path }: StaleCopy) =>132+ `${path} is out of date: ${Option.match(landed, {133+ onNone: () => "it is not what main's config gives",134+ onSome: (sha) =>135+ `it was generated at ${sha}, and main's config now gives other text`,136+ })}. The platform regenerates it whenever the config changes; pull main for the current copy instead of editing it.`;137+138+/** The stale copies as `--json` lists them: absent when there are none. */139+const staleField = (stale: readonly StaleCopy[]) =>140+ Array.match(stale, {141+ onEmpty: () => ({}),142+ onNonEmpty: (copies) => ({143+ stale: Array.map(copies, ({ landed, path }) =>144+ Option.match(landed, {145+ onNone: () => ({ path }),146+ onSome: (sha) => ({ landed: sha, path }),147+ })148+ ),149+ }),150+ });151+152 /** The signed-in profile's handle, when `login` learned one. */153 const signedInHandle = Effect.flatMap(154 Effect.serviceOption(Credentials),155 Option.match({345 unmodified lines501 )502 )503 );504 505+ // Copies of the generated agent files main's config no longer gives.506+ const stale = yield* staleGenerated({507+ landed: policy.at,508+ policy,509+ project,510+ root: context.root,511+ });512+513+ yield* Effect.forEach(stale, (copy) => output.note(staleNote(copy)), {514+ discard: true,515+ });516+517 const ask = Array.findFirst(policy.asks, ({ id }) => id === askId);518 519 if (Option.isNone(ask)) {520 return yield* refuse(json, [new UnknownAsk({ ask: askId })]);50 unmodified lines571 572 const judged = { ask: askId, base: facts.base, head: facts.head };573 574 if (flags.noLanes) {527- const checked: Checked = { ...judged, lanes: [], stage: "shape" };575+ const checked: Checked = {576+ ...judged,577+ lanes: [],578+ stage: "shape",579+ ...staleField(stale),580+ };581 582 return yield* output.success({583 command: COMMAND,584 data: yield* Effect.orDie(encodeChecked(checked)),68 unmodified lines653 if (Array.isReadonlyArrayNonEmpty(failed)) {654 return yield* refuse(json, failed);655 }656 604- const checked: Checked = { ...judged, lanes: run.lanes, stage: "checks" };657+ const checked: Checked = {658+ ...judged,659+ lanes: run.lanes,660+ stage: "checks",661+ ...staleField(stale),662+ };663 664 return yield* output.success({665 command: COMMAND,666 data: yield* Effect.orDie(encodeChecked(checked)),9 unmodified linesadded:apps/cli/src/local/stale.ts+85 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 file that is missing, or one the11+ * platform does not manage (a skill with no frontmatter of ours, an12+ * AGENTS.md with no block), is no copy, and never stale.13+ */14+import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";15+import { isStale } from "@repo/agent-kit/generated-file";16+import { projectSkill } from "@repo/agent-kit/project-skill";17+import type { Policy } from "@repo/protocol/domain/policy";18+import type { LandedSha, ProjectName } from "@repo/protocol/ids";19+import { Effect, FileSystem, Option, Path } from "effect";20+21+/** A generated file on disk that is not what main's policy gives, and the landing its copy names. */22+export interface StaleCopy {23+ readonly path: string;24+ /** The landing the copy says it came from; none for the AGENTS.md block, which names none. */25+ readonly landed: Option.Option<LandedSha>;26+}27+28+const agentsFile = "AGENTS.md";29+30+/**31+ * Every generated file in the working copy at `root` that differs from the32+ * one `policy` (read at the landing `landed`) gives: the skill's copies by33+ * their recorded hash (`isStale`), the AGENTS.md block by its text.34+ */35+export const staleGenerated = (input: {36+ readonly root: string;37+ readonly project: ProjectName;38+ readonly policy: Policy;39+ readonly landed: LandedSha;40+}): Effect.Effect<41+ readonly StaleCopy[],42+ never,43+ FileSystem.FileSystem | Path.Path44+> =>45+ Effect.gen(function* () {46+ const fs = yield* FileSystem.FileSystem;47+ const path = yield* Path.Path;48+ const { landed, policy, project } = input;49+50+ const onDisk = (file: string) =>51+ Effect.option(fs.readFileString(path.join(input.root, file)));52+53+ const skills = yield* projectSkill({ landed, policy, project });54+55+ const staleSkills = yield* Effect.forEach(skills, (current) =>56+ Effect.gen(function* () {57+ const copy = yield* onDisk(current.path);58+59+ if (Option.isNone(copy)) {60+ return [];61+ }62+63+ const stale = yield* isStale(copy.value, current);64+65+ return Option.match(stale, {66+ onNone: (): readonly StaleCopy[] => [],67+ onSome: (found) => [{ landed: found.landed, path: current.path }],68+ });69+ })70+ );71+72+ const block = yield* agentsBlock({ landed, policy, project });73+ const agents = yield* onDisk(agentsFile);74+75+ const blockStale = Option.exists(76+ agents,77+ (text) =>78+ text.includes(block.end) && upsertAgentsBlock(text, block) !== text79+ );80+81+ return [82+ ...staleSkills.flat(),83+ ...(blockStale ? [{ landed: Option.none(), path: agentsFile }] : []),84+ ];85+ });added:apps/cli/test/local/stale.test.ts+195 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(`${skill} is out of date`);117+ expect(printed.err).toContain(older);118+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))119+ );120+121+ it.live(122+ "notes an AGENTS.md block that is not the one main's policy gives",123+ () =>124+ Effect.gen(function* () {125+ const repo = yield* cleanRepo;126+ const policy = yield* policyAtMain(repo);127+128+ const block = yield* agentsBlock({129+ landed: older,130+ policy: withOlderRun(policy),131+ project: name,132+ });133+134+ yield* writeFile(135+ repo,136+ "AGENTS.md",137+ upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)138+ );139+140+ const printed = yield* checked(repo.root);141+142+ expect(printed.envelope).toMatchObject({143+ data: { stale: [{ path: "AGENTS.md" }] },144+ ok: true,145+ });146+ expect(printed.err).toContain("AGENTS.md");147+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))148+ );149+150+ it.live("says nothing of copies generated from main's policy", () =>151+ Effect.gen(function* () {152+ const repo = yield* cleanRepo;153+ const policy = yield* policyAtMain(repo);154+155+ const copies = yield* projectSkill({156+ landed: older,157+ policy,158+ project: name,159+ });160+161+ const block = yield* agentsBlock({162+ landed: older,163+ policy,164+ project: name,165+ });166+167+ for (const copy of copies) {168+ yield* writeFile(repo, copy.path, copy.content);169+ }170+171+ yield* writeFile(172+ repo,173+ "AGENTS.md",174+ upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)175+ );176+177+ const printed = yield* checked(repo.root);178+179+ expect(Exit.isSuccess(printed.exit)).toBeTruthy();180+ expect(printed.envelope).toStrictEqual({181+ command: "check",182+ data: {183+ ask: "fix-a",184+ base: repo.main,185+ head: repo.clean,186+ lanes: [],187+ stage: "shape",188+ },189+ ok: true,190+ v: 1,191+ });192+ expect(printed.err).not.toContain("out of date");193+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))194+ );195+});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+424 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 { RulesEvaluator } from "@repo/rules/rules-evaluator";42+import { advanceTo } from "@repo/testkit/clock";43+import { gitClient } from "@repo/testkit/git-client";44+import type { Files } from "@repo/testkit/git-client";45+import { aProject } from "@repo/testkit/scenarios";46+import { Context, Effect, Layer, Option, Schema } from "effect";47+48+import { ProjectSkillGenerator } from "../src/workflows/generated.ts";49+50+const scenario = aProject();51+52+const { project } = scenario;53+54+const repo = RepoName.make(project);55+56+const alice = Person.make({ handle: scenario.initializer });57+58+const mainRef = RefName.make("refs/heads/main");59+60+const runFile = `${Brand.configDir}/run.json`;61+62+const skill = `.agents/skills/${project}-contribute/SKILL.md`;63+64+const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;65+66+const generatedPaths = [skill, claudeSkill, "AGENTS.md"];67+68+const lintOnly = { checks: { lint: "bun run lint" }, test: "bun test {path}" };69+70+const withUnit = {71+ checks: { lint: "bun run lint", unit: "bun run test" },72+ test: "bun test {path}",73+};74+75+/** What alice pushes first: a package, the run block, and notes of the project's own. */76+const start: Files = [77+ ["package.json", '{ "name": "datekit" }\n'],78+ ["src/parse.ts", "export const parse = (s) => ({});\n"],79+ [runFile, `${JSON.stringify(lintOnly)}\n`],80+ ["AGENTS.md", "# Datekit\n\nOur own notes for agents.\n"],81+];82+83+const decodeRun = Schema.decodeEffect(Schema.fromJsonString(RunBlock));84+85+/**86+ * The scenario's policy at any commit, with the run block its config87+ * folder's `run.json` states, or lint alone when it states none.88+ */89+const rules = Layer.succeed(90+ RulesEvaluator,91+ RulesEvaluator.of({92+ call: () => Effect.succeed(false),93+ evaluate: ({ at, modules }) =>94+ Effect.map(95+ Effect.orDie(96+ decodeRun(modules.modules[runFile] ?? JSON.stringify(lintOnly))97+ ),98+ (run) => ({ ...scenario.policy, at, run })99+ ),100+ })101+);102+103+/** What the Checker answers: every lane passes on any tree the test names. */104+class Passing extends Context.Service<105+ Passing,106+ {107+ readonly on: (at: CheckAt, lanes: readonly string[]) => Effect.Effect<void>;108+ }109+>()("test/Passing") {}110+111+const checker = Layer.effectContext(112+ Effect.gen(function* () {113+ const script = new Map<string, readonly LaneResult[]>();114+115+ const memory = Context.get(116+ yield* Layer.build(CheckRunnerMemory.layer(script)),117+ CheckRunner118+ );119+120+ return Context.make(CheckRunner, memory).pipe(121+ Context.add(Passing, {122+ on: (at, lanes) =>123+ Effect.sync(() => {124+ for (const name of lanes) {125+ const lane = LaneName.make(name);126+127+ script.set(scriptKey(at, lane), [128+ {129+ command: `run ${lane}`,130+ durationMs: 1,131+ lane,132+ result: "passed",133+ },134+ ]);135+ }136+ }),137+ })138+ );139+ })140+);141+142+/** Commits made the way git would make them, pushed to a repo's `main`. */143+class Pusher extends Context.Service<144+ Pusher,145+ {146+ readonly push: (147+ to: RepoName,148+ parent: Option.Option<CommitSha>,149+ files: Files150+ ) => Effect.Effect<CommitSha>;151+ }152+>()("test/Pusher") {}153+154+const pusher = Layer.effect(155+ Pusher,156+ Effect.gen(function* () {157+ const host = yield* RepoHost;158+ const client = yield* gitClient(memoryFs());159+160+ return Pusher.of({161+ push: (to, parent, files) =>162+ Effect.gen(function* () {163+ const sha = yield* client.commit(164+ "Work",165+ files,166+ Option.toArray(parent)167+ );168+169+ yield* host170+ .push(to, client.source, [{ from: parent, ref: mainRef, to: sha }])171+ .pipe(Effect.orDie);172+173+ return sha;174+ }),175+ });176+ })177+);178+179+/**180+ * The project's ports, the generator only among the Project's own, as a181+ * Project DO's shell gives them: the calls the test makes run without it.182+ */183+const world = Layer.mergeAll(184+ ProjectsMemory.pipe(Layer.provide(ProjectSkillGenerator)),185+ pusher186+).pipe(187+ Layer.provideMerge(188+ Layer.mergeAll(AnswerRunsInline, AlarmsMemory, ProjectionMemory, rules)189+ ),190+ Layer.provideMerge(Layer.merge(LanderIsogit, checker)),191+ Layer.provideMerge(RepoHostMemory)192+);193+194+/** Where canonical `main` stands. */195+const mainTip = Effect.gen(function* () {196+ const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);197+198+ return LandedSha.make(199+ Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))200+ );201+});202+203+const commitAt = (sha: CommitSha) =>204+ Effect.flatMap(RepoHost, (host) =>205+ host206+ .readCommit(repo, sha)207+ .pipe(Effect.orDie, Effect.flatMap(Effect.fromOption))208+ ).pipe(Effect.orDie);209+210+/** A file's text at a commit of the canonical repo. */211+const textAt = (sha: CommitSha, path: string) =>212+ Effect.flatMap(RepoHost, (host) =>213+ host214+ .readFile(repo, Revision.Commit({ sha }), RepoPath.make(path))215+ .pipe(216+ Effect.orDie,217+ Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes)))218+ )219+ );220+221+/** What one commit changed against its first parent, by path. */222+const changedBy = (sha: CommitSha) =>223+ Effect.gen(function* () {224+ const commit = yield* commitAt(sha);225+ const parent = yield* commitAt(commit.parents[0] ?? sha);226+227+ const changes = yield* treeDiff(228+ repo,229+ TreeSha.make(parent.tree),230+ TreeSha.make(commit.tree)231+ ).pipe(Effect.orDie);232+233+ return changes.map(({ path }) => path).toSorted();234+ });235+236+/** The platform's follow-up at `sha`: its parent, what it changed, who it credits and names. */237+const followUpAt = (sha: CommitSha) =>238+ Effect.gen(function* () {239+ const commit = yield* commitAt(sha);240+241+ return {242+ author: commit.author,243+ changed: yield* changedBy(sha),244+ credits: creditsOf(commit.message).credits,245+ parent: commit.parents[0],246+ requestId: parseTrailers(commit.message).find(247+ ({ key }) => key === "Request-Id"248+ )?.value,249+ subject: commit.message.split("\n")[0],250+ };251+ });252+253+/** Every file of the tree at `sha` the test knows of, as a commit on it would carry them. */254+const filesAt = (sha: CommitSha, run: typeof RunBlock.Encoded) =>255+ Effect.gen(function* () {256+ const generated = yield* Effect.forEach(generatedPaths, (path) =>257+ Effect.map(258+ textAt(sha, path),259+ (text) => [path, Option.getOrElse(text, () => "")] as const260+ )261+ );262+263+ return [264+ ...start.filter(([path]) => path !== runFile && path !== "AGENTS.md"),265+ [runFile, `${JSON.stringify(run)}\n`],266+ ...generated,267+ ] satisfies Files;268+ });269+270+/** The project made, and alice's first push to it recorded. */271+const firstPushed = Effect.gen(function* () {272+ yield* advanceTo("2026-10-07T12:00:00Z");273+274+ const api = yield* Projects.use((each) => each.create(project)).pipe(275+ Effect.orDie276+ );277+278+ yield* api.initProject(alice, {}).pipe(Effect.orDie);279+280+ const first = yield* Pusher.use((each) =>281+ each.push(repo, Option.none(), start)282+ );283+284+ yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);285+286+ return { api, first };287+});288+289+/** alice lands a change of her own from her working fork: `files` on top of `base`. */290+const aliceLands = (base: LandedSha, files: Files, requestId: string) =>291+ Effect.gen(function* () {292+ const api = yield* Projects.use((each) => each.get(project)).pipe(293+ Effect.orDie294+ );295+296+ const { fork } = yield* api.fork(alice).pipe(Effect.orDie);297+298+ const head = yield* Pusher.use((each) =>299+ each.push(fork, Option.some(base), files)300+ );301+302+ const merged = yield* Lander.use((lander) =>303+ lander.merge({ base, fork, head, main: base, repo })304+ ).pipe(Effect.orDie);305+306+ yield* Passing.use((passing) =>307+ passing.on(CheckAt.cases.Tree.make({ tree: merged.tree }), [308+ "lint",309+ "unit",310+ ])311+ );312+313+ const request = {314+ base,315+ head,316+ message: "Change the project",317+ requestId: RequestId.make(requestId),318+ };319+320+ return {321+ receipt: yield* api.land(alice, request).pipe(Effect.orDie),322+ replay: () => api.land(alice, request).pipe(Effect.orDie),323+ };324+ });325+326+const landedSha = (outcome: Outcome) =>327+ Outcome.guards.Landed(outcome) ? Option.some(outcome.sha) : Option.none();328+329+describe("the contribute skill, regenerated by the platform", () => {330+ it.effect(331+ "follows the first push with a landing of the generated files alone, credited to the initializer",332+ () =>333+ Effect.gen(function* () {334+ const { first } = yield* firstPushed;335+ const tip = yield* mainTip;336+337+ expect(yield* followUpAt(tip)).toStrictEqual({338+ author: authorLine(platformHandle),339+ changed: generatedPaths.toSorted(),340+ credits: [{ handle: alice.handle, role: "Decided-by" }],341+ parent: first,342+ requestId: `gen-${first}`,343+ subject: "Regenerate the contribute skill and the AGENTS.md block",344+ });345+346+ const agents = Option.getOrElse(347+ yield* textAt(tip, "AGENTS.md"),348+ () => ""349+ );350+351+ expect(agents).toMatch(352+ /^# Datekit\n\nOur own notes for agents\.\n\n<!-- BEGIN /u353+ );354+ expect(yield* textAt(tip, skill)).toStrictEqual(355+ yield* textAt(tip, claudeSkill)356+ );357+ }).pipe(Effect.provide(world))358+ );359+360+ it.effect(361+ "follows a landing that changed the run block with one more platform commit, and a replay lands nothing",362+ () =>363+ Effect.gen(function* () {364+ yield* firstPushed;365+366+ const generatedOnce = yield* mainTip;367+368+ const changed = yield* aliceLands(369+ generatedOnce,370+ yield* filesAt(generatedOnce, withUnit),371+ "land-alice-unit-lane"372+ );373+374+ const landed = Option.getOrThrow(landedSha(changed.receipt.outcome));375+ const tip = yield* mainTip;376+377+ expect(yield* changedBy(landed)).toStrictEqual([runFile]);378+ expect(yield* followUpAt(tip)).toStrictEqual({379+ author: authorLine(platformHandle),380+ changed: generatedPaths.toSorted(),381+ credits: [{ handle: alice.handle, role: "Decided-by" }],382+ parent: landed,383+ requestId: `gen-${landed}`,384+ subject: "Regenerate the contribute skill and the AGENTS.md block",385+ });386+ expect(Option.getOrElse(yield* textAt(tip, skill), () => "")).toContain(387+ "bun run test"388+ );389+390+ const replayed = yield* changed.replay();391+392+ expect(landedSha(replayed.outcome)).toStrictEqual(Option.some(landed));393+ expect(yield* mainTip).toBe(tip);394+ }).pipe(Effect.provide(world))395+ );396+397+ it.effect(398+ "lands nothing of its own after a landing that changed only src/",399+ () =>400+ Effect.gen(function* () {401+ yield* firstPushed;402+403+ const generatedOnce = yield* mainTip;404+ const files = yield* filesAt(generatedOnce, lintOnly);405+406+ const changed = yield* aliceLands(407+ generatedOnce,408+ files.map(([path, text]) =>409+ path === "src/parse.ts"410+ ? ([411+ path,412+ "export const parse = (s) => ({ year: 2026 });\n",413+ ] as const)414+ : ([path, text] as const)415+ ),416+ "land-alice-parse"417+ );418+419+ expect(yield* mainTip).toStrictEqual(420+ Option.getOrThrow(landedSha(changed.receipt.outcome))421+ );422+ }).pipe(Effect.provide(world))423+ );424+});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+159 added-5 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+ * After a call moved the landed SHA (the first adoption, an answer, a1525+ * decider's own landing, an ask opened, a vouch): the platform's own1526+ * landing of the regenerated contribute skill and AGENTS.md block on1527+ * top, when the policy read at the new landed SHA changes what they say1528+ * (spec D12, W4 410). It never joins the landing that changed the config1529+ * ("land only the checked tree"): its files are composed onto main and1530+ * landed through the Lander, a compare-and-swap push of `main` then the1531+ * mirror, as every platform landing is, under the project's lock, with1532+ * the request id `gen-<landed>`, so a replay finds its commit. It is1533+ * recorded in the same commit as the landing it follows. It is1534+ * bookkeeping: one that cannot land is logged, and the landing it follows1535+ * stands; the next landing that changes the config writes the files1536+ * again.1537+ */1538+ const followUp = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>1539+ Effect.gen(function* () {1540+ const row = writes.project.get("row");1541+ const landed = row?.landed;1542+1543+ if (1544+ row?.policy === undefined ||1545+ landed === undefined ||1546+ row.policyAt !== landed ||1547+ Option.exists(h.project, (before) => before.landed === landed)1548+ ) {1549+ return;1550+ }1551+1552+ const requestId = generatedRequestId(landed);1553+ const landing = writes.landings.find(({ sha }) => sha === landed);1554+1555+ const followed = [...h.landings, ...writes.landings].some(1556+ (each) => each.requestId === requestId1557+ );1558+1559+ if (landing === undefined || followed) {1560+ return;1561+ }1562+1563+ const made = yield* generatedFollowUp(1564+ {1565+ after: yield* Effect.orDie(decodePolicy(row.policy)),1566+ before: h.policy,1567+ initializer: row.initializer,1568+ landing,1569+ project: name,1570+ read: textAt(landed),1571+ },1572+ generate1573+ );1574+1575+ if (Option.isNone(made)) {1576+ return;1577+ }1578+1579+ const { author, credits, message } = made.value;1580+1581+ const files = Array.map(made.value.files, ({ content, path }) => ({1582+ content,1583+ path: RepoPath.make(path),1584+ }));1585+1586+ const composed = yield* lander.compose({ files, main: landed, repo });1587+1588+ const { sha } = yield* lander.land({1589+ author,1590+ main: landed,1591+ message,1592+ rebuild: Rebuild.Compose({ files }),1593+ repo,1594+ requestId,1595+ tree: composed.tree,1596+ verdict: Option.none(),1597+ });1598+1599+ const view: LandingView = {1600+ assisted: [],1601+ author,1602+ credits,1603+ landedAt: now,1604+ parent: landed,1605+ project: name,1606+ requestId,1607+ sha,1608+ };1609+1610+ const moved = yield* withPolicyAt({ ...row, landed: sha }, sha, now);1611+1612+ writes.landings.push(view);1613+ writes.events.push(1614+ ProjectEventInput.Landed({ at: now, landing: view })1615+ );1616+ writes.project.set("row", moved);1617+ }).pipe(1618+ Effect.catchCause((cause) =>1619+ Cause.hasInterruptsOnly(cause)1620+ ? Effect.interrupt1621+ : Effect.logWarning(1622+ "the regenerated contribute skill and AGENTS.md block did not land",1623+ cause1624+ )1625+ )1626+ );1627+1628+ /**1629+ * One call that writes (`writeLocked`), with the generated follow-up of1630+ * any landing the body recorded, in the same commit.1631+ */1632+ const write = <A, E>(1633+ queue: AnswerQueue,1634+ body: (1635+ h: Hydrated,1636+ writes: Writes,1637+ now: DateTime.Utc1638+ ) => Effect.Effect<A, E>1639+ ): Effect.Effect<A, E> =>1640+ writeLocked(queue, (h, writes, now) =>1641+ Effect.tap(body(h, writes, now), () => followUp(h, writes, now))1642+ );1643+1644 /** A `main` for an imported repo whose branch had another name, at its tip. */1645 const mainAt = (tip: CommitSha) =>1646 Effect.gen(function* () {1647 const empty = { fs: memoryFs(), gitdir: "/adopt.git" };1543 unmodified lines3191 const writes = writesOf();3192 3193 yield* tickAll(h, writes, now);3194 yield* decided.expire(h, writes, now);3195+ // A decision that took its default may have landed (a revert).3196+ yield* followUp(h, writes, now);3197 3198 return [...(yield* commit(h, writes, now)), ...h.outbox];3199 })3200 );182 unmodified linesadded:packages/project/test/generated.test.ts+319 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, generatedRequestId } 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 bobAlone: LandingView = {301+ ...aliceLands,302+ author: bob,303+ credits: [{ handle: bob, role: "Signed-off-by" }],304+ };305+306+ expect({307+ bob: yield* creditOf(bobAlone),308+ dora: yield* creditOf(decidedByDora),309+ }).toStrictEqual({310+ bob: Option.some([{ handle: alice, role: "Decided-by" }]),311+ dora: Option.some([{ handle: dora, role: "Decided-by" }]),312+ });313+ })314+ );315+316+ it("names its request for the landing it follows", () => {317+ expect(generatedRequestId(landed)).toBe(`gen-${landed}`);318+ });319+});