Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent b08d5f6 · Browse files · 8 files+1480 added−8 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+1480 added−8 removed

  • tests:+938 added−0 removed
  • other:+542 added−8 removed

8 files+1480 added−8 removed

modified:apps/cli/src/local/check.ts+61 added-3 removed
28 unmodified lines
29import {30 AskId,31 CommitSha,32 Handle,33 LandedSha,34 ProjectName,35 RepoName,36} from "@repo/protocol/ids";37import { Person } from "@repo/protocol/principal";
29 unmodified lines
67 ConfigBundler,68 ConfigBundlerBun,69 localPolicy,70} from "./local-policy.ts";71import { staleGenerated } from "./stale.ts";72import type { StaleCopy } from "./stale.ts";7374const COMMAND = "check";7573/** What `check --json` prints on success: the ask, the diff it judged, and each lane. */76/** A generated file in the working copy that main's config no longer gives (`stale.ts`). */77const Stale = Schema.Struct({78 /** The landing the copy says it came from, when it names one. */79 landed: Schema.optionalKey(LandedSha),80 path: Schema.String,81});8283/**84 * What `check --json` prints on success: the ask, the diff it judged, each85 * lane, and the generated files that are out of date, when any are.86 */87const Checked = Schema.Struct({88 ask: AskId,89 base: CommitSha,90 head: CommitSha,91 lanes: Schema.Array(LaneResult),92 /** The last stage that ran: `shape` with `--shape-only`, else `checks`. */93 stage: Schema.Literals(["shape", "checks"]),94 stale: Schema.optionalKey(Schema.NonEmptyArray(Stale)),95});9697type Checked = typeof Checked.Type;98
27 unmodified lines
126 Effect.fail(new Reported())127 )128 );129130/** What a stale copy is told: which file, the landing it names, and how to get a current one. */131const 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.`;137138/** The stale copies as `--json` lists them: absent when there are none. */139const 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 });151152/** The signed-in profile's handle, when `login` learned one. */153const signedInHandle = Effect.flatMap(154 Effect.serviceOption(Credentials),155 Option.match({
345 unmodified lines
501 )502 )503 );504505 // 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 });512513 yield* Effect.forEach(stale, (copy) => output.note(staleNote(copy)), {514 discard: true,515 });516517 const ask = Array.findFirst(policy.asks, ({ id }) => id === askId);518519 if (Option.isNone(ask)) {520 return yield* refuse(json, [new UnknownAsk({ ask: askId })]);
50 unmodified lines
571572 const judged = { ask: askId, base: facts.base, head: facts.head };573574 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 };581582 return yield* output.success({583 command: COMMAND,584 data: yield* Effect.orDie(encodeChecked(checked)),
68 unmodified lines
653 if (Array.isReadonlyArrayNonEmpty(failed)) {654 return yield* refuse(json, failed);655 }656604 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 };663664 return yield* output.success({665 command: COMMAND,666 data: yield* Effect.orDie(encodeChecked(checked)),
9 unmodified lines
added: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 */14import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";15import { isStale } from "@repo/agent-kit/generated-file";16import { projectSkill } from "@repo/agent-kit/project-skill";17import type { Policy } from "@repo/protocol/domain/policy";18import type { LandedSha, ProjectName } from "@repo/protocol/ids";19import { Effect, FileSystem, Option, Path } from "effect";2021/** A generated file on disk that is not what main's policy gives, and the landing its copy names. */22export 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}2728const agentsFile = "AGENTS.md";2930/**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 */35export 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;4950 const onDisk = (file: string) =>51 Effect.option(fs.readFileString(path.join(input.root, file)));5253 const skills = yield* projectSkill({ landed, policy, project });5455 const staleSkills = yield* Effect.forEach(skills, (current) =>56 Effect.gen(function* () {57 const copy = yield* onDisk(current.path);5859 if (Option.isNone(copy)) {60 return [];61 }6263 const stale = yield* isStale(copy.value, current);6465 return Option.match(stale, {66 onNone: (): readonly StaleCopy[] => [],67 onSome: (found) => [{ landed: found.landed, path: current.path }],68 });69 })70 );7172 const block = yield* agentsBlock({ landed, policy, project });73 const agents = yield* onDisk(agentsFile);7475 const blockStale = Option.exists(76 agents,77 (text) =>78 text.includes(block.end) && upsertAgentsBlock(text, block) !== text79 );8081 return [82 ...staleSkills.flat(),83 ...(blockStale ? [{ landed: Option.none(), path: agentsFile }] : []),84 ];85 });
added:apps/cli/test/local/stale.test.ts+195 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { agentsBlock, upsertAgentsBlock } from "@repo/agent-kit/agents-block";4import { projectSkill } from "@repo/agent-kit/project-skill";5import { Client } from "@repo/protocol/contracts";6import type { Policy } from "@repo/protocol/domain/policy";7import { RunBlock } from "@repo/protocol/domain/run";8import { Handle, LandedSha, ProjectName } from "@repo/protocol/ids";9import { gitOk } from "@repo/testkit/git";10import { Effect, Exit, FileSystem, Layer, Path, Schema } from "effect";11import { CliOutput } from "effect/cli";12import { TestConsole } from "effect/testing";1314import { ConfigBundlerBun, localPolicy } from "../../src/local/local-policy.ts";15import { program } from "../../src/main.ts";16import { OutputPlain } from "../../src/output.ts";17import { SignedOut } from "../signed-out.ts";18import { aCheckRepo, handle, project } from "./fixture.ts";19import type { CheckRepo } from "./fixture.ts";2021/** A platform no offline run may call. */22const unreachable = Layer.mock(Client)({});2324const services = Layer.mergeAll(25 TestConsole.layer,26 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),27 unreachable,28 OutputPlain,29 SignedOut30).pipe(Layer.provideMerge(NodeServices.layer));3132/** `check --offline --shape-only --json` in the repo: how it ended, and what it printed where. */33const checked = (root: string) =>34 Effect.gen(function* () {35 const exit = yield* Effect.exit(36 program(["check", "--dir", root, "--offline", "--shape-only", "--json"])37 );3839 const [out = ""] = (yield* TestConsole.logLines).map(String);4041 return {42 envelope: yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(43 out44 ),45 err: (yield* TestConsole.errorLines).map(String).join("\n"),46 exit,47 };48 }).pipe(Effect.provide(services));4950const name = ProjectName.make(project);5152const skill = `.agents/skills/${project}-contribute/SKILL.md`;5354/** The landing an older copy of the skill came from. */55const older = LandedSha.make("a".repeat(40));5657/** The policy at the fixture's main, as `check` reads it. */58const policyAtMain = (repo: CheckRepo) =>59 localPolicy(repo.root, "main", {60 initializer: Handle.make(handle),61 project: name,62 }).pipe(Effect.provide(ConfigBundlerBun));6364/** An older run block: one lane, `ok`, where main has two. */65const olderRun = Schema.decodeSync(RunBlock)({66 checks: { ok: "true" },67 test: "true {path}",68});6970/** The policy at main with the older run block. */71const withOlderRun = (policy: Policy): Policy => ({ ...policy, run: olderRun });7273/** Writes `content` at `file` in the repo's work tree, leaving it uncommitted. */74const writeFile = (repo: CheckRepo, file: string, content: string) =>75 Effect.gen(function* () {76 const fs = yield* FileSystem.FileSystem;77 const path = yield* Path.Path;78 const at = path.join(repo.root, file);7980 yield* fs.makeDirectory(path.dirname(at), { recursive: true });81 yield* fs.writeFileString(at, content);82 });8384/** The fixture with HEAD on its clean answer, which the shape stage passes. */85const cleanRepo = Effect.gen(function* () {86 const repo = yield* aCheckRepo;8788 yield* gitOk(repo.root, "checkout", "--quiet", "clean");8990 return repo;91});9293describe("check, on generated files", () => {94 it.live(95 "notes a contribute skill generated for an older run block, naming it and the landing it came from",96 () =>97 Effect.gen(function* () {98 const repo = yield* cleanRepo;99 const policy = yield* policyAtMain(repo);100101 const [copy] = yield* projectSkill({102 landed: older,103 policy: withOlderRun(policy),104 project: name,105 });106107 yield* writeFile(repo, skill, copy?.content ?? "");108109 const printed = yield* checked(repo.root);110111 expect(Exit.isSuccess(printed.exit)).toBeTruthy();112 expect(printed.envelope).toMatchObject({113 data: { stale: [{ landed: older, path: skill }] },114 ok: true,115 });116 expect(printed.err).toContain(`${skill} is out of date`);117 expect(printed.err).toContain(older);118 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))119 );120121 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);127128 const block = yield* agentsBlock({129 landed: older,130 policy: withOlderRun(policy),131 project: name,132 });133134 yield* writeFile(135 repo,136 "AGENTS.md",137 upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)138 );139140 const printed = yield* checked(repo.root);141142 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 );149150 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);154155 const copies = yield* projectSkill({156 landed: older,157 policy,158 project: name,159 });160161 const block = yield* agentsBlock({162 landed: older,163 policy,164 project: name,165 });166167 for (const copy of copies) {168 yield* writeFile(repo, copy.path, copy.content);169 }170171 yield* writeFile(172 repo,173 "AGENTS.md",174 upsertAgentsBlock("# Fixture\n\nOur notes.\n", block)175 );176177 const printed = yield* checked(repo.root);178179 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
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 */11import { describe, expect, it } from "@effect/vitest";12import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";13import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";14import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";15import { Brand } from "@repo/brand";16import { CheckAt, CheckRunner } from "@repo/checks/check-runner";17import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";18import { authorLine, creditsOf, parseTrailers } from "@repo/git/trailers";19import { treeDiff } from "@repo/git/tree-diff";20import { AlarmsMemory } from "@repo/project/alarms/memory";21import { AnswerRunsInline } from "@repo/project/answer-runs/inline";22import { platformHandle } from "@repo/project/attention/effects";23import { Lander } from "@repo/project/lander";24import { LanderIsogit } from "@repo/project/lander/isogit";25import { ProjectionMemory } from "@repo/project/projection/memory";26import { Projects } from "@repo/project/projects";27import { ProjectsMemory } from "@repo/project/projects/memory";28import type { LaneResult } from "@repo/protocol/domain/answer";29import { Outcome } from "@repo/protocol/domain/outcome";30import { RunBlock } from "@repo/protocol/domain/run";31import type { CommitSha } from "@repo/protocol/ids";32import {33 LandedSha,34 LaneName,35 RepoName,36 RepoPath,37 RequestId,38 TreeSha,39} from "@repo/protocol/ids";40import { Person } from "@repo/protocol/principal";41import { RulesEvaluator } from "@repo/rules/rules-evaluator";42import { advanceTo } from "@repo/testkit/clock";43import { gitClient } from "@repo/testkit/git-client";44import type { Files } from "@repo/testkit/git-client";45import { aProject } from "@repo/testkit/scenarios";46import { Context, Effect, Layer, Option, Schema } from "effect";4748import { ProjectSkillGenerator } from "../src/workflows/generated.ts";4950const scenario = aProject();5152const { project } = scenario;5354const repo = RepoName.make(project);5556const alice = Person.make({ handle: scenario.initializer });5758const mainRef = RefName.make("refs/heads/main");5960const runFile = `${Brand.configDir}/run.json`;6162const skill = `.agents/skills/${project}-contribute/SKILL.md`;6364const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;6566const generatedPaths = [skill, claudeSkill, "AGENTS.md"];6768const lintOnly = { checks: { lint: "bun run lint" }, test: "bun test {path}" };6970const withUnit = {71 checks: { lint: "bun run lint", unit: "bun run test" },72 test: "bun test {path}",73};7475/** What alice pushes first: a package, the run block, and notes of the project's own. */76const 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];8283const decodeRun = Schema.decodeEffect(Schema.fromJsonString(RunBlock));8485/**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 */89const 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);102103/** What the Checker answers: every lane passes on any tree the test names. */104class Passing extends Context.Service<105 Passing,106 {107 readonly on: (at: CheckAt, lanes: readonly string[]) => Effect.Effect<void>;108 }109>()("test/Passing") {}110111const checker = Layer.effectContext(112 Effect.gen(function* () {113 const script = new Map<string, readonly LaneResult[]>();114115 const memory = Context.get(116 yield* Layer.build(CheckRunnerMemory.layer(script)),117 CheckRunner118 );119120 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);126127 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);141142/** Commits made the way git would make them, pushed to a repo's `main`. */143class 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") {}153154const pusher = Layer.effect(155 Pusher,156 Effect.gen(function* () {157 const host = yield* RepoHost;158 const client = yield* gitClient(memoryFs());159160 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 );168169 yield* host170 .push(to, client.source, [{ from: parent, ref: mainRef, to: sha }])171 .pipe(Effect.orDie);172173 return sha;174 }),175 });176 })177);178179/**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 */183const 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);193194/** Where canonical `main` stands. */195const mainTip = Effect.gen(function* () {196 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);197198 return LandedSha.make(199 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))200 );201});202203const 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);209210/** A file's text at a commit of the canonical repo. */211const 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 );220221/** What one commit changed against its first parent, by path. */222const changedBy = (sha: CommitSha) =>223 Effect.gen(function* () {224 const commit = yield* commitAt(sha);225 const parent = yield* commitAt(commit.parents[0] ?? sha);226227 const changes = yield* treeDiff(228 repo,229 TreeSha.make(parent.tree),230 TreeSha.make(commit.tree)231 ).pipe(Effect.orDie);232233 return changes.map(({ path }) => path).toSorted();234 });235236/** The platform's follow-up at `sha`: its parent, what it changed, who it credits and names. */237const followUpAt = (sha: CommitSha) =>238 Effect.gen(function* () {239 const commit = yield* commitAt(sha);240241 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 });252253/** Every file of the tree at `sha` the test knows of, as a commit on it would carry them. */254const 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 );262263 return [264 ...start.filter(([path]) => path !== runFile && path !== "AGENTS.md"),265 [runFile, `${JSON.stringify(run)}\n`],266 ...generated,267 ] satisfies Files;268 });269270/** The project made, and alice's first push to it recorded. */271const firstPushed = Effect.gen(function* () {272 yield* advanceTo("2026-10-07T12:00:00Z");273274 const api = yield* Projects.use((each) => each.create(project)).pipe(275 Effect.orDie276 );277278 yield* api.initProject(alice, {}).pipe(Effect.orDie);279280 const first = yield* Pusher.use((each) =>281 each.push(repo, Option.none(), start)282 );283284 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);285286 return { api, first };287});288289/** alice lands a change of her own from her working fork: `files` on top of `base`. */290const 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 );295296 const { fork } = yield* api.fork(alice).pipe(Effect.orDie);297298 const head = yield* Pusher.use((each) =>299 each.push(fork, Option.some(base), files)300 );301302 const merged = yield* Lander.use((lander) =>303 lander.merge({ base, fork, head, main: base, repo })304 ).pipe(Effect.orDie);305306 yield* Passing.use((passing) =>307 passing.on(CheckAt.cases.Tree.make({ tree: merged.tree }), [308 "lint",309 "unit",310 ])311 );312313 const request = {314 base,315 head,316 message: "Change the project",317 requestId: RequestId.make(requestId),318 };319320 return {321 receipt: yield* api.land(alice, request).pipe(Effect.orDie),322 replay: () => api.land(alice, request).pipe(Effect.orDie),323 };324 });325326const landedSha = (outcome: Outcome) =>327 Outcome.guards.Landed(outcome) ? Option.some(outcome.sha) : Option.none();328329describe("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;336337 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 });345346 const agents = Option.getOrElse(347 yield* textAt(tip, "AGENTS.md"),348 () => ""349 );350351 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 );359360 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;365366 const generatedOnce = yield* mainTip;367368 const changed = yield* aliceLands(369 generatedOnce,370 yield* filesAt(generatedOnce, withUnit),371 "land-alice-unit-lane"372 );373374 const landed = Option.getOrThrow(landedSha(changed.receipt.outcome));375 const tip = yield* mainTip;376377 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 );389390 const replayed = yield* changed.replay();391392 expect(landedSha(replayed.outcome)).toStrictEqual(Option.some(landed));393 expect(yield* mainTip).toBe(tip);394 }).pipe(Effect.provide(world))395 );396397 it.effect(398 "lands nothing of its own after a landing that changed only src/",399 () =>400 Effect.gen(function* () {401 yield* firstPushed;402403 const generatedOnce = yield* mainTip;404 const files = yield* filesAt(generatedOnce, lintOnly);405406 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 );418419 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 */16import { Brand } from "@repo/brand";17import { formatLanding } from "@repo/git/trailers";18import type { Credit } from "@repo/protocol/domain/credit";19import type { LandingView } from "@repo/protocol/domain/landing";20import type { Policy } from "@repo/protocol/domain/policy";21import { RepoPath, RequestId, sameHandle } from "@repo/protocol/ids";22import type { Handle, LandedSha, ProjectName } from "@repo/protocol/ids";23import { Array, Context, Effect, Option } from "effect";2425import { decidersFor } from "./attention/decisions.ts";26import { platformHandle } from "./attention/effects.ts";2728/** One file a generator makes: where it goes, and every byte of it. */29export interface GeneratedFile {30 readonly path: string;31 readonly content: string;32}3334/** A file's text in the tree a landing left, if the tree has it. */35export type ReadAt = (path: string) => Effect.Effect<Option.Option<string>>;3637/**38 * Every generated file for one policy at one landing. `read` gives a file's39 * text at that landing, for a file the generator writes into rather than40 * over (AGENTS.md, whose text outside its block is the project's own).41 */42export type Generate = (input: {43 readonly project: ProjectName;44 readonly policy: Policy;45 readonly landed: LandedSha;46 readonly read: ReadAt;47}) => Effect.Effect<readonly GeneratedFile[]>;4849/** The platform's landing that follows another with the regenerated files. */50export interface FollowUp {51 /** The platform: it writes the files, nobody's answer does. */52 readonly author: Handle;53 /** `Decided-by` the decider whose landing changed what the files say. */54 readonly credits: readonly Credit[];55 /** The files whose text the tree does not hold yet, and only those. */56 readonly files: Array.NonEmptyReadonlyArray<GeneratedFile>;57 /** The whole commit message, trailers included. */58 readonly message: string;59 /** `gen-<landed>`: the same follow-up landed again finds the first one. */60 readonly requestId: RequestId;61}6263/**64 * How a host gives a project its generator (`@repo/agent-kit`'s, in the65 * platform). The default makes no files, so a project given none follows66 * no landing with one of its own.67 */68export const ProjectGenerator = Context.Reference<Generate>(69 "project/ProjectGenerator",70 { defaultValue: () => () => Effect.succeed([]) }71);7273/** The request a follow-up of the landing at `landed` lands as. */74export const generatedRequestId = (landed: LandedSha) =>75 RequestId.make(`gen-${landed}`);7677/** Where the config lives: whoever decides for it decides what the files say. */78const configPath = RepoPath.make(`${Brand.configDir}/project.ts`);7980/**81 * Who the follow-up credits: the landing's `Decided-by`, else its author82 * when they decide for the config, else the person who made the project.83 */84const deciderOf = (input: {85 readonly after: Policy;86 readonly initializer: Handle;87 readonly landing: LandingView;88}): Handle => {89 const { author, credits } = input.landing;9091 const decided = Array.findFirst(92 credits,93 ({ role }) => role === "Decided-by"94 ).pipe(Option.map(({ handle }) => handle));9596 const authorDecides = decidersFor(input.after, [configPath]).some((each) =>97 sameHandle(each, author)98 );99100 return Option.getOrElse(101 Option.orElse(decided, () =>102 authorDecides ? Option.some(author) : Option.none()103 ),104 () => input.initializer105 );106};107108/** Whether two generations say the same, file for file. */109const sameFiles = (110 one: readonly GeneratedFile[],111 other: readonly GeneratedFile[]112) =>113 one.length === other.length &&114 one.every(115 ({ content, path }, index) =>116 other[index]?.path === path && other[index]?.content === content117 );118119const messageOf = (input: {120 readonly credits: readonly Credit[];121 readonly files: readonly GeneratedFile[];122 readonly landed: LandedSha;123 readonly requestId: RequestId;124}) =>125 formatLanding({126 assisted: [],127 body: [128 `The config at ${input.landed} changed what these files say, so the platform wrote them again from it:`,129 "",130 ...input.files.map(({ path }) => `- ${path}`),131 ].join("\n"),132 credits: input.credits,133 requestId: input.requestId,134 subject: "Regenerate the contribute skill and the AGENTS.md block",135 });136137/**138 * The landing that follows `landing` with the regenerated files, or none.139 * None when the generator makes nothing, when the policy before the landing140 * gave the same files as the policy after it (the landing changed nothing141 * they say), or when the landed tree already holds every file as generated142 * (a replay after the follow-up landed, or a landing that brought them).143 * The first adoption has no policy before it, so it is followed unless its144 * tree holds the files already. The same input always gives the same files.145 */146export const generatedFollowUp = (147 input: {148 readonly project: ProjectName;149 /** The person who made the project: credited when no one else decided. */150 readonly initializer: Handle;151 /** The policy before the landing; none for the first adoption. */152 readonly before: Option.Option<Policy>;153 /** The policy read at the landing. */154 readonly after: Policy;155 readonly landing: LandingView;156 /** A file's text at the landed SHA. */157 readonly read: ReadAt;158 },159 generate: Generate160): Effect.Effect<Option.Option<FollowUp>> =>161 Effect.gen(function* () {162 const { landing, project, read } = input;163 const landed = landing.sha;164 const at = (policy: Policy) => generate({ landed, policy, project, read });165 const after = yield* at(input.after);166167 if (Option.isSome(input.before)) {168 const before = yield* at(input.before.value);169170 if (sameFiles(before, after)) {171 return Option.none();172 }173 }174175 const differing = yield* Effect.filter(after, ({ content, path }) =>176 Effect.map(read(path), (held) => !Option.contains(held, content))177 );178179 if (!Array.isReadonlyArrayNonEmpty(differing)) {180 return Option.none();181 }182183 const credits: readonly Credit[] = [184 { handle: deciderOf(input), role: "Decided-by" },185 ];186187 const requestId = generatedRequestId(landed);188189 return Option.some({190 author: platformHandle,191 credits,192 files: differing,193 message: messageOf({ credits, files: differing, landed, requestId }),194 requestId,195 });196 });
modified:packages/project/src/project.ts+159 added-5 removed
12 unmodified lines
13 * its arguments and its result against the contract's or the domain's14 * schemas (`MethodSchemas`, principle 2), which W3's Durable Object boundary15 * reuses.16 */17import { BranchName, RefName, RepoHost } from "@repo/artifacts/repo-host";17import {18 BranchName,19 RefName,20 RepoHost,21 Revision,22} from "@repo/artifacts/repo-host";23import type { RepoNotFound } from "@repo/artifacts/repo-host";24import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";25import { Brand } from "@repo/brand";26import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";
104 unmodified lines
131import { Finishers } from "@repo/rules/finish";132import { RulesEvaluator, sdkVersion } from "@repo/rules/rules-evaluator";133import {134 Array,135 Cause,136 Context,137 DateTime,138 Effect,139 Layer,
37 unmodified lines
177 nextDecisionId,178 strayDecision,179} from "./deciders.ts";180import type { DeciderApi, Opening } from "./deciders.ts";175import { askClosed, askOpened, judged, listingOf, numbered } from "./events.ts";176import type { ProjectEventInput } from "./events.ts";181import {182 askClosed,183 askOpened,184 judged,185 listingOf,186 numbered,187 ProjectEventInput,188} from "./events.ts";189import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";190import type { MissingCommit } from "./facts.ts";191import {192 generatedFollowUp,193 generatedRequestId,194 ProjectGenerator,195} from "./generated.ts";196import { Lander, Rebuild } from "./lander.ts";197import type { ComposedFile } from "./lander.ts";198import {199 LandingCommand,
901 unmodified lines
1101 const lander = Context.get(ports, Lander);1102 const runner = Context.get(ports, CheckRunner);1103 const rules = Context.get(ports, RulesEvaluator);1104 const alarms = Context.get(ports, Alarms);1105 // Read once, as the ports are: a call runs in its caller's context.1106 const generate = yield* ProjectGenerator;1107 const lock = yield* Semaphore.make(1);1108 const repo = RepoName.make(name);11091110 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>
215 unmodified lines
1326 /**1327 * One call that writes: under the project's lock it hydrates, runs1328 * `body` (pure transitions, and the port calls that decide them), and1329 * commits what it gathered; then, outside the lock, settles the outbox1311 * rows it wrote. A body that fails commits nothing.1330 * rows it wrote. A body that fails commits nothing. Every method calls1331 * it through `write`, which adds the generated follow-up to the body.1332 */1313 const write = <A, E>(1333 const writeLocked = <A, E>(1334 queue: AnswerQueue,1335 body: (1336 h: Hydrated,1337 writes: Writes,
170 unmodified lines
1508 })),1509 })1510 );15111512 // --------------------------------------------------------- generated15131514 /** A file's text at a landed commit of the canonical repo; none where it has no such file. */1515 const textAt = (at: LandedSha) => (path: string) =>1516 host1517 .readFile(repo, Revision.Commit({ sha: at }), RepoPath.make(path))1518 .pipe(1519 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))),1520 Effect.orDie1521 );15221523 /**1524 * 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;15421543 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 }15511552 const requestId = generatedRequestId(landed);1553 const landing = writes.landings.find(({ sha }) => sha === landed);15541555 const followed = [...h.landings, ...writes.landings].some(1556 (each) => each.requestId === requestId1557 );15581559 if (landing === undefined || followed) {1560 return;1561 }15621563 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 );15741575 if (Option.isNone(made)) {1576 return;1577 }15781579 const { author, credits, message } = made.value;15801581 const files = Array.map(made.value.files, ({ content, path }) => ({1582 content,1583 path: RepoPath.make(path),1584 }));15851586 const composed = yield* lander.compose({ files, main: landed, repo });15871588 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 });15981599 const view: LandingView = {1600 assisted: [],1601 author,1602 credits,1603 landedAt: now,1604 parent: landed,1605 project: name,1606 requestId,1607 sha,1608 };16091610 const moved = yield* withPolicyAt({ ...row, landed: sha }, sha, now);16111612 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 );16271628 /**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 );16431644 /** 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 lines
3191 const writes = writesOf();31923193 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);31973198 return [...(yield* commit(h, writes, now)), ...h.outbox];3199 })3200 );
182 unmodified lines
added:packages/project/test/generated.test.ts+319 added
1import { describe, expect, it } from "@effect/vitest";2import { creditsOf, parseTrailers } from "@repo/git/trailers";3import type { LandingView } from "@repo/protocol/domain/landing";4import type { Policy } from "@repo/protocol/domain/policy";5import { RunBlock } from "@repo/protocol/domain/run";6import { Handle, LandedSha } from "@repo/protocol/ids";7import { aProject } from "@repo/testkit/scenarios";8import { DateTime, Effect, Option, Schema } from "effect";910import { platformHandle } from "../src/attention/effects.ts";11import { generatedFollowUp, generatedRequestId } from "../src/generated.ts";12import type { Generate } from "../src/generated.ts";1314const scenario = aProject({ deciders: ["alice", "dora"], people: ["bob"] });1516const { initializer, project } = scenario;1718const alice = initializer;1920const dora = Handle.make("dora");2122const bob = Handle.make("bob");2324const parent = LandedSha.make("1".repeat(40));2526const landed = LandedSha.make("2".repeat(40));2728/** The policy before the landing: lint and types. */29const before: Policy = { ...scenario.policy, at: parent };3031/** The same policy at the landing, read again there: nothing it says changed. */32const unchanged: Policy = { ...scenario.policy, at: landed };3334/** The policy at the landing, with a unit lane added to the run block. */35const withUnit: Policy = {36 ...unchanged,37 run: Schema.decodeSync(RunBlock)({38 checks: {39 lint: "bun run lint",40 types: "bun run typecheck",41 unit: "bun run test",42 },43 test: "bun test {path}",44 }),45};4647const skill = `.agents/skills/${project}-contribute/SKILL.md`;4849const claudeSkill = `.claude/skills/${project}-contribute/SKILL.md`;5051/**52 * A generator as `@repo/agent-kit` is one, in miniature: the skill, twice,53 * naming the landing and the run block's lanes, and AGENTS.md with only the54 * text between its markers written over (appended when there are none).55 */56const generate: Generate = ({ landed: at, policy, read }) =>57 Effect.gen(function* () {58 const lanes = Object.entries(policy.run.checks)59 .map(([lane, command]) => `${lane}: ${command}`)60 .join(", ");6162 const content = `---\nlanded: ${at}\n---\nLanes: ${lanes}\n`;63 const block = `<!-- BEGIN -->\nLanes: ${lanes}\n<!-- END -->`;64 const existing = Option.getOrElse(yield* read("AGENTS.md"), () => "");65 const begin = existing.indexOf("<!-- BEGIN -->");66 const end = existing.indexOf("<!-- END -->");6768 const agents =69 begin === -1 || end === -170 ? `${existing}${block}\n`71 : `${existing.slice(0, begin)}${block}${existing.slice(end + "<!-- END -->".length)}`;7273 return [74 { content, path: skill },75 { content, path: claudeSkill },76 { content: agents, path: "AGENTS.md" },77 ];78 });7980/** The project's own AGENTS.md, with a block the platform wrote before. */81const ownAgents = [82 "# Datekit",83 "",84 "Our notes.",85 "",86 "<!-- BEGIN -->",87 "Lanes: lint: bun run lint",88 "<!-- END -->",89 "",90 "More notes.",91 "",92].join("\n");9394/** A tree that holds `files` and nothing else. */95const treeOf =96 (files: Readonly<Record<string, string>>) =>97 (path: string): Effect.Effect<Option.Option<string>> =>98 Effect.succeed(Option.fromUndefinedOr(files[path]));99100const at = DateTime.makeUnsafe("2026-10-07T12:00:00Z");101102/** alice's own landing from her working fork, which changed the config. */103const aliceLands: LandingView = {104 assisted: [],105 author: alice,106 credits: [{ handle: alice, role: "Signed-off-by" }],107 landedAt: at,108 parent,109 project,110 sha: landed,111};112113/** The first adoption: the initializer's first push, crediting no one. */114const firstPush: LandingView = {115 assisted: [],116 author: alice,117 credits: [],118 landedAt: at,119 project,120 sha: landed,121};122123const followUp = (input: {124 readonly before: Option.Option<Policy>;125 readonly after: Policy;126 readonly landing: LandingView;127 readonly tree?: Readonly<Record<string, string>>;128}) =>129 generatedFollowUp(130 {131 after: input.after,132 before: input.before,133 initializer,134 landing: input.landing,135 project,136 read: treeOf(input.tree ?? { "AGENTS.md": ownAgents }),137 },138 generate139 );140141const subjectOf = (message: string) => message.split("\n")[0] ?? "";142143/** Whom the follow-up of `landing`, after the run block changed, credits. */144const creditOf = (landing: LandingView) =>145 Effect.map(146 followUp({ after: withUnit, before: Option.some(before), landing }),147 Option.map(({ credits }) => credits)148 );149150describe(generatedFollowUp, () => {151 it.effect(152 "follows a landing that changed the run block with the regenerated files alone, credited to its decider",153 () =>154 Effect.gen(function* () {155 const made = yield* followUp({156 after: withUnit,157 before: Option.some(before),158 landing: aliceLands,159 });160161 const lanes =162 "Lanes: lint: bun run lint, types: bun run typecheck, unit: bun run test";163164 const skillText = `---\nlanded: ${landed}\n---\n${lanes}\n`;165166 expect(Option.map(made, ({ files }) => files)).toStrictEqual(167 Option.some([168 { content: skillText, path: skill },169 { content: skillText, path: claudeSkill },170 {171 content: [172 "# Datekit",173 "",174 "Our notes.",175 "",176 "<!-- BEGIN -->",177 lanes,178 "<!-- END -->",179 "",180 "More notes.",181 "",182 ].join("\n"),183 path: "AGENTS.md",184 },185 ])186 );187188 const { author, credits, message, requestId } = Option.getOrThrow(made);189190 expect({191 author,192 credits,193 requestId,194 subject: subjectOf(message),195 trailers: creditsOf(message).credits,196 trailersRequest: parseTrailers(message).find(197 ({ key }) => key === "Request-Id"198 )?.value,199 }).toStrictEqual({200 author: platformHandle,201 credits: [{ handle: alice, role: "Decided-by" }],202 requestId: `gen-${landed}`,203 subject: "Regenerate the contribute skill and the AGENTS.md block",204 trailers: [{ handle: alice, role: "Decided-by" }],205 trailersRequest: `gen-${landed}`,206 });207 })208 );209210 it.effect("lands nothing after a landing that changed only src/", () =>211 Effect.gen(function* () {212 expect(213 yield* followUp({214 after: unchanged,215 before: Option.some(before),216 landing: aliceLands,217 tree: {},218 })219 ).toStrictEqual(Option.none());220 })221 );222223 it.effect("makes the same files from the same input", () =>224 Effect.gen(function* () {225 const input = {226 after: withUnit,227 before: Option.some(before),228 landing: aliceLands,229 };230231 expect(yield* followUp(input)).toStrictEqual(yield* followUp(input));232 })233 );234235 it.effect(236 "lands nothing when the tree already holds the regenerated files, as after a replay",237 () =>238 Effect.gen(function* () {239 const made = Option.getOrThrow(240 yield* followUp({241 after: withUnit,242 before: Option.some(before),243 landing: aliceLands,244 })245 );246247 const regenerated = Object.fromEntries(248 made.files.map(({ content, path }) => [path, content])249 );250251 expect(252 yield* followUp({253 after: withUnit,254 before: Option.some(before),255 landing: aliceLands,256 tree: regenerated,257 })258 ).toStrictEqual(Option.none());259 })260 );261262 it.effect(263 "follows the first adoption, which had no policy before, crediting the initializer",264 () =>265 Effect.gen(function* () {266 const made = yield* followUp({267 after: unchanged,268 before: Option.none(),269 landing: firstPush,270 tree: {},271 });272273 expect(274 Option.map(made, ({ credits, files }) => ({275 credits,276 paths: files.map(({ path }) => path),277 }))278 ).toStrictEqual(279 Option.some({280 credits: [{ handle: alice, role: "Decided-by" }],281 paths: [skill, claudeSkill, "AGENTS.md"],282 })283 );284 })285 );286287 it.effect(288 "credits the landing's Decided-by first, then its author if they decide the config, else the initializer",289 () =>290 Effect.gen(function* () {291 const decidedByDora: LandingView = {292 ...aliceLands,293 author: bob,294 credits: [295 { handle: bob, role: "Signed-off-by" },296 { handle: dora, role: "Decided-by" },297 ],298 };299300 const bobAlone: LandingView = {301 ...aliceLands,302 author: bob,303 credits: [{ handle: bob, role: "Signed-off-by" }],304 };305306 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 );315316 it("names its request for the landing it follows", () => {317 expect(generatedRequestId(landed)).toBe(`gen-${landed}`);318 });319});