Skip to content
Myr

Generate a project's contribute skill, its AGENTS.md block, the platform's skill, both plugin bundles and the well-known index from policy, each Markdown file stamped so a stale or hand-edited copy shows

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

Issue 406. packages/agent-kit's generators return GeneratedFile values only (no disk, no network); 409 writes the platform's files, 410 lands a project's. - projectSkill: `.agents/skills/<project>-contribute/SKILL.md` and the same bytes under `.claude/skills/`. The body has the five-step loop (`<cli> ask` + `claim` -> work -> `<cli> check` -> `git push <slug> HEAD:main` -> read the verdict note, match on `_tag`), claim terms, the territory/public-files/judge/marker/ratchet rules (each naming the refusal that holds it), the run block, each ask kind, the answer refusals with retryable and next, and "No fence yet" for the two norms nothing checks. - frontmatter: only `name`, `description`, `metadata`; `managed-by`, `landed` (when there is one) and `content-hash: sha256:<body>` under metadata. Values are YAML double-quoted, since YAML would read an all-digit SHA as a number. Hashing is WebCrypto through Effect.tryPromise (a failure is a defect). - No body names the landing, so isStale compares hashes only: None for a fresh copy or one from an older landing with the same text; Some({landed, hash}) of the copy when the policy's text changed or the body no longer hashes to what it records; a copy without the frontmatter gives landed None and the file's hash. readManaged is None for unstamped or foreign-managed files. - agentsBlock: markers `<!-- BEGIN <slug> contribute (generated; content-hash: sha256:...) -->` / `<!-- END <slug> contribute -->`; upsertAgentsBlock appends after a blank line or replaces from marker to marker whatever the old hash, leaves every other byte, and is idempotent. - platformSkill, claudePlugin (plugin.json, the skill, .mcp.json: http to `<url>/mcp` or `<cli> mcp`, hooks.json: PreToolUse matcher Edit|Write|MultiEdit|NotebookEdit, SessionStart and Stop to `<cli> hook <event> --json`, names from hook-events.ts) and agentPluginsBundle (closed Agent Plugins 1.0 plugin.json and mcp.json). Both manifests share plugins/<slug>/: no path is read by both (checked against agent-plugins.org 1.0.0 and Claude Code's plugin reference), so no separate directory; 409 dedupes the shared SKILL.md by path. - wellKnownSkills: discovery 0.2.0 index, entries sorted by name, sha256 digests of each file, descriptions cut to 1024 units at whole graphemes. - CommandDoc, contractCommandDocs (from Description, Cli, ReadOnly, NeedsApproval, Surfaces; flags are payload fields, --json, --yes when approval is needed, --dry-run unless read-only; contracts a local command of the same name stands in for are left to it) and localCommandDocs (login, logout, init, check, why, env set, hook, credential, mcp, schema; 409 holds them to the CLI). - The refusal table reads tag, retryable and a fixed next from the union's schemas; what to do is a table typed `satisfies Record<AnswerTag, Repair>`, so a refusal added to an answer group fails the typecheck until it has a line. - hook-events.ts gains `guardedTools`, additively. - Outside the strict territory (401's files): agent-kit's package.json dev-depends on @cloudflare/workers-types 5.20261006.1 (types `crypto`) and @effect/platform-node 4.0.1 (golden files), tsconfig types the Workers globals; bun.lock gains two workspace lines. Both versions were already locked. - Tests, red by assertion first against generators returning empty values: generate.test.ts (eight golden files in test/golden/*.txt with __CLI__/__SLUG__/__NAME__ placeholders, UPDATE_GOLDEN=1 rewrites; every generator twice gives the same files; frontmatter keys; hooks.json and both MCP entries exact; index digest of "hello\n" and description cut), stale.test.ts (frontmatter bytes with the known sha256 of "hello\n", readManaged, isStale's five cases), agents-block.test.ts (append, empty file, no final newline, replace between markers, twice is a no-op, another tool's markers; the block's hash moves with the run block, not the landing), command-doc.test.ts. - ASSUMPTION: the texts follow 404's claim render (remote `<slug>`, `git push <slug> HEAD:main`) and spec §5 step 10's notes commands; loopSteps in src/sections.ts is the one place to change them. - ASSUMPTION: the skill lists no asks (a list would force a generated landing after every ask landing); it points at `<cli> asks`. - bun run fix && bun run verify green: agent-kit 53 tests; gen:check current, imports:check no violations, debt at baseline, brand:check no leaks.

authored by oscabriel · committed by oscabriel · parent 650cb35 · Browse files · 28 files+3392 added−4 removed
This commit

State

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

Diff stats

28 files+3392 added−4 removed

  • tests:+1896 added−0 removed
  • other:+1496 added−4 removed

28 files+3392 added−4 removed

added:packages/agent-kit/src/agents-block.ts+132 added
1/**2 * The AGENTS.md block: the brief every harness reads without installing3 * anything, between markers the platform owns. The first marker carries the4 * body's hash, so a hand-edited block is detectable; everything outside the5 * markers belongs to the project and is never touched.6 */7import { Brand } from "@repo/brand";8import type { Policy } from "@repo/protocol/domain/policy";9import type { LandedSha, ProjectName } from "@repo/protocol/ids";10import { Effect, Option } from "effect";1112import { contentHash } from "./generated-file.ts";13import { contributeSkillName, contributeSkillPaths } from "./project-skill.ts";14import { lanesOf, loopSteps, unfencedNorms } from "./sections.ts";15import { code, listed, page } from "./text.ts";1617/** The block: its two marker lines and the text between them. */18export interface AgentsBlock {19 readonly begin: string;20 readonly end: string;21 readonly body: string;22}2324const BEGIN = `<!-- BEGIN ${Brand.slug} contribute`;2526const END = `<!-- END ${Brand.slug} contribute -->`;2728const rules = (policy: Policy) => {29 const { judge, run, weakening } = policy;30 const closure = [...judge.paths, ...judge.pointers];3132 return [33 "- Change only files in the ask's territory; a push that changes anything else is refused with `OutOfScope`.",34 ...(closure.length === 035 ? []36 : [37 `- Never change the judge closure (${closure.map(code).join(", ")}); a push that does is refused with \`TouchedJudge\`.`,38 ]),39 ...(weakening.markers.length === 040 ? []41 : [42 `- Never add a marker that turns a check off (${weakening.markers.map(code).join(", ")}); one without a reason is refused with \`Weakened\`.`,43 ]),44 `- Test one file with ${code(run.test)}. The lanes are ${listed(lanesOf(run).map(([lane, command]) => `${code(lane)} (${code(command)})`))}.`,45 "- Every refusal has a `_tag`, `retryable` and `next`: run `next`. Add `--json` to any command for JSON.",46 ];47};4849const bodyOf = (project: ProjectName, policy: Policy) => {50 const [agentsPath] = contributeSkillPaths(project);5152 return page([53 `## Contributing to ${project}`,54 "",55 `This project takes changes through ${Brand.name}: an answer to one of its asks lands only by passing the gate. This block is generated from the config folder, and the gate decides what lands. The full guide is the ${code(contributeSkillName(project))} skill (${code(agentsPath ?? "")}).`,56 "",57 ...loopSteps(),58 "",59 ...rules(policy),60 "",61 "No fence yet: nothing checks these, so the gate won't refuse you for them.",62 "",63 ...unfencedNorms(policy.agents),64 ]);65};6667/**68 * The block for a project's AGENTS.md, from its policy alone: the landing69 * changes nothing in it, so a landing that leaves the policy's text alone70 * leaves the block, and its hash, as they were.71 */72export const agentsBlock = (input: {73 readonly project: ProjectName;74 readonly policy: Policy;75 readonly landed: LandedSha;76}): Effect.Effect<AgentsBlock> => {77 const body = bodyOf(input.project, input.policy);7879 return contentHash(body).pipe(80 Effect.map((hash) => ({81 begin: `${BEGIN} (generated; content-hash: ${hash}) -->`,82 body,83 end: END,84 }))85 );86};8788/** The block as a file holds it: the markers on lines of their own. */89const written = (block: AgentsBlock) =>90 `${block.begin}\n${block.body}${block.body.endsWith("\n") ? "" : "\n"}${block.end}`;9192/** Where an existing block starts and ends, whatever hash its first marker carries. */93const locate = (94 existing: string,95 end: string96): Option.Option<{ readonly from: number; readonly to: number }> => {97 const to = existing.indexOf(end);9899 if (to === -1) {100 return Option.none();101 }102103 const from = existing.lastIndexOf(BEGIN, to);104105 const marker =106 from !== -1 &&107 (from === 0 || existing[from - 1] === "\n") &&108 existing[from + BEGIN.length] === " ";109110 return marker ? Option.some({ from, to: to + end.length }) : Option.none();111};112113/** What goes between a file's last text and an appended block: one blank line. */114const separator = (existing: string) => {115 if (existing === "" || existing.endsWith("\n\n")) {116 return "";117 }118119 return existing.endsWith("\n") ? "\n" : "\n\n";120};121122/**123 * `existing` with the block in it: replacing the text from the first marker124 * to the last where a block is, appending it after a blank line where none125 * is. Every other byte stays as it was, and a second call changes nothing.126 */127export const upsertAgentsBlock = (existing: string, block: AgentsBlock) =>128 Option.match(locate(existing, block.end), {129 onNone: () => `${existing}${separator(existing)}${written(block)}\n`,130 onSome: ({ from, to }) =>131 `${existing.slice(0, from)}${written(block)}${existing.slice(to)}`,132 });
added:packages/agent-kit/src/command-doc.ts+229 added
1/**2 * One row per CLI command, the list `docs/reference/commands.json`, the3 * platform's skill and `llms.txt` all render from (SYN §14). Contract rows4 * come from each contract's annotations; the hand-written commands are5 * listed here, and issue 409's test holds the list to the CLI.6 */7import {8 Cli,9 Description,10 NeedsApproval,11 ReadOnly,12 Surfaces,13} from "@repo/protocol/contracts";14import type { Contracts } from "@repo/protocol/contracts";15import { Context, Schema, SchemaAST } from "effect";1617export const CommandDoc = Schema.Struct({18 /** The contract it calls: always for a contract's row, sometimes for a local one. */19 contract: Schema.optionalKey(Schema.NonEmptyString),20 /** Every flag it takes, as typed: `--project`. */21 flags: Schema.Array(Schema.NonEmptyString),22 /** It runs only with `--yes`; `--dry-run` prints what it would send. */23 needsApproval: Schema.Boolean,24 /** The words after the CLI's name: `["env", "set"]`. */25 path: Schema.NonEmptyArray(Schema.NonEmptyString),26 /** The arguments it takes in order, by name. */27 positional: Schema.Array(Schema.NonEmptyString),28 readOnly: Schema.Boolean,29 source: Schema.Literals(["contract", "local"]),30 summary: Schema.NonEmptyString,31});3233export type CommandDoc = typeof CommandDoc.Type;3435/**36 * The CLI's hand-written commands. `init` and `env set` stand in for the37 * contracts they call (`initProject`, `setEnv`), so those contracts get no38 * row of their own.39 */40export const localCommandDocs: readonly CommandDoc[] = [41 {42 flags: [43 "--url",44 "--profile",45 "--token-stdin",46 "--no-browser",47 "--no-git-config",48 "--json",49 ],50 needsApproval: false,51 path: ["login"],52 positional: [],53 readOnly: false,54 source: "local",55 summary: "Sign in to a platform; git and this CLI then use its token.",56 },57 {58 flags: ["--profile", "--json"],59 needsApproval: false,60 path: ["logout"],61 positional: [],62 readOnly: false,63 source: "local",64 summary: "Forget a platform's stored token.",65 },66 {67 contract: "initProject",68 flags: [69 "--project",70 "--import",71 "--branch",72 "--yes",73 "--dry-run",74 "--push",75 "--no-push",76 "--json",77 ],78 needsApproval: true,79 path: ["init"],80 positional: [],81 readOnly: false,82 source: "local",83 summary:84 "Make this repo, or a public HTTPS repo, a project: find its checks, write its config and push.",85 },86 {87 flags: [88 "--ask",89 "--project",90 "--base",91 "--offline",92 "--shape-only",93 "--lane",94 "--dir",95 "--json",96 ],97 needsApproval: false,98 path: ["check"],99 positional: [],100 readOnly: true,101 source: "local",102 summary: "Run the gate's checks on your answer locally, before you push.",103 },104 {105 contract: "landing",106 flags: ["--project", "--json"],107 needsApproval: false,108 path: ["why"],109 positional: ["location"],110 readOnly: true,111 source: "local",112 summary:113 "Explain a line: the ask, the answer and the people that landed it.",114 },115 {116 contract: "setEnv",117 flags: ["--project", "--acknowledge-short", "--yes", "--dry-run", "--json"],118 needsApproval: true,119 path: ["env", "set"],120 positional: ["key"],121 readOnly: false,122 source: "local",123 summary:124 "Set a sensitive env item's value from stdin; nobody can read it back.",125 },126 {127 flags: ["--json"],128 needsApproval: false,129 path: ["hook"],130 positional: ["event"],131 readOnly: true,132 source: "local",133 summary:134 "Answer a harness hook (session-start, pre-tool-use, stop) with the gate's policy.",135 },136 {137 flags: [],138 needsApproval: false,139 path: ["credential"],140 positional: ["operation"],141 readOnly: false,142 source: "local",143 summary:144 "Be git's credential helper: hand git the stored token for a platform.",145 },146 {147 flags: [],148 needsApproval: false,149 path: ["mcp"],150 positional: [],151 readOnly: false,152 source: "local",153 summary: "Serve the platform's tools over MCP on stdio.",154 },155 {156 flags: [],157 needsApproval: false,158 path: ["schema"],159 positional: ["command"],160 readOnly: true,161 source: "local",162 summary: "Print the JSON Schema of a command's payload.",163 },164];165166/** The contracts a local command calls in their place, by the command's name. */167const standIns = new Map(168 localCommandDocs.flatMap(({ contract, path }) =>169 contract === undefined ? [] : [[path.join(" "), contract] as const]170 )171);172173/** A payload's field names, in the schema's order; none for a payload of no fields. */174const fieldsOf = (ast: SchemaAST.AST) =>175 SchemaAST.isObjects(ast)176 ? ast.propertySignatures.map(({ name }) => String(name))177 : [];178179/**180 * One row per contract the CLI serves (its `Surfaces` include `cli`), in the181 * group's order, from its annotations: the `Cli` name split into words, its182 * positional fields, then every other payload field as a flag, `--json`,183 * `--yes` when it needs approval, and `--dry-run` unless it only reads. A184 * contract a local command calls under the same name is left to that185 * command's row.186 */187export const contractCommandDocs = (188 group: typeof Contracts189): readonly CommandDoc[] =>190 [...group.requests.values()].flatMap((rpc) => {191 const { annotations } = rpc;192 const cli = Context.get(annotations, Cli);193 const name = cli.name ?? rpc._tag;194 const [first, ...rest] = name.split(" ");195196 if (197 first === undefined ||198 !Context.get(annotations, Surfaces).includes("cli") ||199 standIns.has(name)200 ) {201 return [];202 }203204 const positional = cli.positional ?? [];205 const readOnly = Context.get(annotations, ReadOnly);206 const needsApproval = Context.get(annotations, NeedsApproval);207208 const flags = fieldsOf(rpc.payloadSchema.ast)209 .filter((field) => !positional.includes(field))210 .map((field) => `--${field}`);211212 return [213 {214 contract: rpc._tag,215 flags: [216 ...flags,217 "--json",218 ...(needsApproval ? ["--yes"] : []),219 ...(readOnly ? [] : ["--dry-run"]),220 ],221 needsApproval,222 path: [first, ...rest],223 positional: [...positional],224 readOnly,225 source: "contract",226 summary: Context.get(annotations, Description),227 },228 ];229 });
added:packages/agent-kit/src/generated-file.ts+186 added
1/**2 * A generated file, and how it says it was generated. A Markdown file opens3 * with Agent Skills frontmatter whose `metadata` names who manages it, the4 * landing it came from and the SHA-256 of its body, so a stale copy (its5 * body differs from the one the current policy gives) and a hand-edited copy6 * (its body no longer hashes to what it records) are both detectable.7 */8import { Brand } from "@repo/brand";9import { LandedSha } from "@repo/protocol/ids";10import { Array as Arr, Effect, Option, Schema } from "effect";1112/** One file a generator makes: where it goes, and every byte of it. */13export interface GeneratedFile {14 readonly path: string;15 readonly content: string;16}1718/** What a managed file says about itself, and the body it says it of. */19export interface Managed {20 /** The landing it was generated from; none for the platform's own files. */21 readonly landed: Option.Option<LandedSha>;22 /** `sha256:<64 hex>`, as its frontmatter records it. */23 readonly hash: string;24 readonly body: string;25}2627const hex = (bytes: ArrayBuffer) =>28 [...new Uint8Array(bytes)]29 .map((byte) => byte.toString(16).padStart(2, "0"))30 .join("");3132/**33 * `sha256:<64 hex>` of the text's UTF-8 bytes, through WebCrypto, which the34 * platform Worker and Node both have. SHA-256 of bytes in memory cannot fail35 * for a reason a caller could handle, so a failure is a defect.36 */37export const contentHash = (text: string): Effect.Effect<string> =>38 Effect.tryPromise(() =>39 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))40 ).pipe(41 Effect.orDie,42 Effect.map((digest) => `sha256:${hex(digest)}`)43 );4445// Every value but the name is a YAML double-quoted string, written as JSON46// writes one: a description has colons, and YAML would read a SHA made only47// of digits as a number.48const quoted = (value: string) => JSON.stringify(value);4950/**51 * A Markdown file with Agent Skills frontmatter: only the spec's `name`,52 * `description` and `metadata`, with `managed-by`, `landed` (when it came53 * from one) and `content-hash` (of `body`) under `metadata`.54 */55export const frontmatter = (input: {56 readonly name: string;57 readonly description: string;58 readonly landed: Option.Option<LandedSha>;59 readonly body: string;60}): Effect.Effect<string> =>61 contentHash(input.body).pipe(62 Effect.map((hash) =>63 [64 "---",65 `name: ${input.name}`,66 `description: ${quoted(input.description)}`,67 "metadata:",68 ` managed-by: ${quoted(Brand.slug)}`,69 ...Option.toArray(input.landed).map(70 (sha) => ` landed: ${quoted(sha)}`71 ),72 ` content-hash: ${quoted(hash)}`,73 "---",74 input.body,75 ].join("\n")76 )77 );7879const OPEN = "---\n";8081const CLOSE = "\n---\n";8283const decodeQuoted = Schema.decodeUnknownOption(84 Schema.fromJsonString(Schema.String)85);8687/** A frontmatter value: a quoted one decoded, a plain one as it stands. */88const valueOf = (raw: string) =>89 raw.startsWith('"') ? decodeQuoted(raw) : Option.some(raw);9091/** The `key: value` lines indented under `metadata:`, by key. */92const metadataOf = (head: string) => {93 const lines = head.split("\n");94 const start = lines.indexOf("metadata:");9596 const nested =97 start === -198 ? []99 : Arr.takeWhile(lines.slice(start + 1), (line) => line.startsWith(" "));100101 return new Map(102 nested.flatMap((line) => {103 const { key, raw } =104 /^ {2}(?<key>[a-z-]+): (?<raw>.+)$/u.exec(line)?.groups ?? {};105106 return key === undefined || raw === undefined107 ? []108 : Option.toArray(valueOf(raw)).map((value) => [key, value] as const);109 })110 );111};112113const decodeLanded = Schema.decodeUnknownOption(LandedSha);114115/**116 * What a file this platform manages says about itself: none for a file117 * without the frontmatter, or one someone else manages.118 */119export const readManaged = (file: string): Option.Option<Managed> => {120 if (!file.startsWith(OPEN)) {121 return Option.none();122 }123124 const close = file.indexOf(CLOSE, OPEN.length - 1);125126 if (close === -1) {127 return Option.none();128 }129130 const metadata = metadataOf(file.slice(OPEN.length, close));131 const hash = metadata.get("content-hash");132133 if (metadata.get("managed-by") !== Brand.slug || hash === undefined) {134 return Option.none();135 }136137 return Option.some({138 body: file.slice(close + CLOSE.length),139 hash,140 landed: Option.fromNullishOr(metadata.get("landed")).pipe(141 Option.flatMap(decodeLanded)142 ),143 });144};145146/**147 * Whether the copy on disk differs from the file the current policy gives:148 * its body hashes to something other than what it records (edited by hand),149 * or what it records is not the current body's hash (generated from other150 * text). The landing alone never makes a copy stale: a landing that left151 * the text alone leaves the copy current. Some names the copy's own landing152 * and recorded hash; a copy without the frontmatter has no landing, and its153 * hash is the whole file's.154 */155export const isStale = (156 onDisk: string,157 current: GeneratedFile158): Effect.Effect<159 Option.Option<{160 readonly landed: Option.Option<LandedSha>;161 readonly hash: string;162 }>163> =>164 Effect.gen(function* () {165 const wanted = yield* Option.match(readManaged(current.content), {166 onNone: () => contentHash(current.content),167 onSome: ({ hash }) => Effect.succeed(hash),168 });169170 const copy = readManaged(onDisk);171172 if (Option.isNone(copy)) {173 const hash = yield* contentHash(onDisk);174175 return hash === wanted176 ? Option.none()177 : Option.some({ hash, landed: Option.none() });178 }179180 const { body, hash, landed } = copy.value;181 const actual = yield* contentHash(body);182183 return actual === hash && hash === wanted184 ? Option.none()185 : Option.some({ hash, landed });186 });
modified:packages/agent-kit/src/hook-events.ts+12 added
modified:packages/agent-kit/src/index.ts+37 added-3 removed
added:packages/agent-kit/src/platform.ts+218 added
1/**2 * The repo's own `skills/<slug>/` and `plugins/<slug>/`, which `bun run gen`3 * writes (issue 409): the platform's skill, the Claude Code plugin with its4 * three hooks, and the Agent Plugins bundle. The plugin is what a person5 * installs, so it is the only place executable hooks ship; a project's own6 * generated files are data.7 *8 * Both plugin manifests share one directory: Claude Code reads9 * `.claude-plugin/plugin.json`, `.mcp.json` and `hooks/hooks.json`, Agent10 * Plugins 1.0 reads `plugin.json` and `mcp.json`, and both read `skills/`.11 * No path is read by both, so neither manifest overrides the other.12 */13import { Brand } from "@repo/brand";14import { Array as Arr, Effect, Option, Order } from "effect";1516import type { CommandDoc } from "./command-doc.ts";17import { frontmatter } from "./generated-file.ts";18import type { GeneratedFile } from "./generated-file.ts";19import { claudeEventOf, guardedTools, HookEvent } from "./hook-events.ts";20import { refusalSection } from "./refusals.ts";21import { loopSteps, unfencedSection } from "./sections.ts";22import { code, page, printJson, table } from "./text.ts";2324export interface PlatformInput {25 /** Every CLI command, as `docs/reference/commands.json` lists them. */26 readonly commands: readonly CommandDoc[];27 /** The platform's origin, for its MCP endpoint; without it, MCP runs through the CLI. */28 readonly platformUrl?: string;29}3031const SKILL = `skills/${Brand.slug}/SKILL.md`;3233const PLUGIN = `plugins/${Brand.slug}`;3435// --- The platform's skill ------------------------------------------------------3637const description = `Contribute to projects on ${Brand.name} with the \`${Brand.cli}\` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on ${Brand.name}, or when a push was refused with a refusal such as OutOfScope or StaleBase.`;3839const usage = ({ path, positional }: CommandDoc) =>40 code(41 [Brand.cli, ...path, ...positional.map((name) => `<${name}>`)].join(" ")42 );4344const notes = ({ needsApproval, readOnly }: CommandDoc) =>45 [46 ...(readOnly ? ["Only reads."] : []),47 ...(needsApproval ? ["Runs only with `--yes`."] : []),48 ].join(" ");4950const byWords = Order.mapInput(Order.String, (command: CommandDoc) =>51 command.path.join(" ")52);5354const commandsSection = (commands: readonly CommandDoc[]) => [55 "## Commands",56 "",57 ...table(58 ["Command", "Flags", "What it does"],59 Arr.sort(commands, byWords).map((command) => [60 usage(command),61 command.flags.map(code).join(" "),62 [command.summary, notes(command)].filter((text) => text !== "").join(" "),63 ])64 ),65 "",66];6768const mcpSection = (platformUrl: string | undefined) => [69 "## MCP",70 "",71 platformUrl === undefined72 ? `${code(`${Brand.cli} mcp`)} serves the platform's contracts as MCP tools over stdio, with your stored token.`73 : `The platform serves its contracts as MCP tools at ${code(`${platformUrl}/mcp`)}; ${code(`${Brand.cli} mcp`)} serves the same tools over stdio, with your stored token.`,74 "",75];7677const platformBody = (input: PlatformInput) =>78 page([79 `# ${Brand.name}`,80 "",81 `${Brand.name} is a git platform where a change lands only by passing a typed gate. A project states each change it wants as an ask; you answer one with a commit pushed to your claim's fork, and the platform checks it and lands it, or answers with refusals that say what to do next.`,82 "",83 "## The loop",84 "",85 `Find an ask with ${code(`${Brand.cli} asks`)}, then, in the project's repo:`,86 "",87 ...loopSteps(),88 "",89 `A project's own \`<project>-contribute\` skill and the block in its AGENTS.md give its territories, its run block and its ask kinds.`,90 "",91 "## Output",92 "",93 "Every command prints Markdown; `--json` prints one versioned JSON envelope instead. A command that needs a person's approval runs only with `--yes`, and `--dry-run` prints what it would send.",94 "",95 ...commandsSection(input.commands),96 ...mcpSection(input.platformUrl),97 ...refusalSection(),98 ...unfencedSection(),99 ]);100101const skillFile = (input: PlatformInput) =>102 frontmatter({103 body: platformBody(input),104 description,105 landed: Option.none(),106 name: Brand.slug,107 });108109/** `skills/<slug>/SKILL.md`: the platform's skill, which comes from no landing. */110export const platformSkill = (111 input: PlatformInput112): Effect.Effect<readonly GeneratedFile[]> =>113 skillFile(input).pipe(Effect.map((content) => [{ content, path: SKILL }]));114115// --- The Claude Code plugin ------------------------------------------------------116117const hookCommand = (event: HookEvent) => ({118 hooks: [{ command: `${Brand.cli} hook ${event} --json`, type: "command" }],119});120121/**122 * `hooks/hooks.json`: before an edit, the scope guard; at the session's123 * start, the claimed ask's brief; at Stop, the verdict gate. Each runs124 * `<cli> hook <event> --json`, which fails open: hooks are early feedback,125 * and the gateway decides.126 */127const hooksJson = () =>128 printJson({129 hooks: Object.fromEntries(130 HookEvent.literals.map((event) => [131 claudeEventOf[event],132 [133 event === "pre-tool-use"134 ? { ...hookCommand(event), matcher: guardedTools.join("|") }135 : hookCommand(event),136 ],137 ])138 ),139 });140141const pluginDescription = `The ${Brand.name} CLI's skill, MCP server and hooks: the gate's scope guard before an edit, the claimed ask's brief at the start, and its verdict before you stop.`;142143const homepage = (platformUrl: string | undefined) =>144 platformUrl === undefined ? {} : { homepage: platformUrl };145146/**147 * `plugins/<slug>/`: `.claude-plugin/plugin.json`, the platform's skill,148 * `.mcp.json` (the platform's `/mcp` over HTTP, or `<cli> mcp` without a149 * URL) and `hooks/hooks.json`.150 */151export const claudePlugin = (152 input: PlatformInput153): Effect.Effect<readonly GeneratedFile[]> =>154 skillFile(input).pipe(155 Effect.map((skill) => [156 {157 content: printJson({158 description: pluginDescription,159 name: Brand.slug,160 ...homepage(input.platformUrl),161 }),162 path: `${PLUGIN}/.claude-plugin/plugin.json`,163 },164 { content: skill, path: `${PLUGIN}/${SKILL}` },165 {166 content: printJson({167 mcpServers: {168 [Brand.slug]:169 input.platformUrl === undefined170 ? { args: ["mcp"], command: Brand.cli }171 : { type: "http", url: `${input.platformUrl}/mcp` },172 },173 }),174 path: `${PLUGIN}/.mcp.json`,175 },176 { content: hooksJson(), path: `${PLUGIN}/hooks/hooks.json` },177 ])178 );179180// --- The Agent Plugins bundle ----------------------------------------------------181182const SCHEMAS = "https://agent-plugins.org/schemas/1.0.0";183184/**185 * `plugins/<slug>/plugin.json`, the same skill and `mcp.json`: the Agent186 * Plugins 1.0 package, whose manifests are closed (only `$schema` and the187 * listed fields) and carry no hooks, which that standard leaves to each188 * client.189 */190export const agentPluginsBundle = (191 input: PlatformInput192): Effect.Effect<readonly GeneratedFile[]> =>193 skillFile(input).pipe(194 Effect.map((skill) => [195 {196 content: printJson({197 $schema: `${SCHEMAS}/plugin.schema.json`,198 description: `The ${Brand.name} CLI's skill and MCP server: find an ask, claim it, check your answer locally, push it, and read the verdict.`,199 name: Brand.slug,200 ...homepage(input.platformUrl),201 }),202 path: `${PLUGIN}/plugin.json`,203 },204 { content: skill, path: `${PLUGIN}/${SKILL}` },205 {206 content: printJson({207 $schema: `${SCHEMAS}/mcp.schema.json`,208 mcpServers: {209 [Brand.slug]:210 input.platformUrl === undefined211 ? { args: ["mcp"], command: Brand.cli, type: "stdio" }212 : { type: "streamable-http", url: `${input.platformUrl}/mcp` },213 },214 }),215 path: `${PLUGIN}/mcp.json`,216 },217 ])218 );
added:packages/agent-kit/src/project-skill.ts+79 added
added:packages/agent-kit/src/refusals.ts+177 added
1/**2 * The refusals an answer can meet, read from the closed union: each one's3 * tag, whether retrying can help and its `next` come from its schema, and4 * what to do about it from the table below, which the type holds to the5 * union's groups (a refusal added to one fails the typecheck until it has6 * a line here).7 */8import { Brand } from "@repo/brand";9import { groups } from "@repo/protocol/refusal";10import { Exit, Predicate, SchemaAST } from "effect";1112import { code, table } from "./text.ts";1314/** The groups whose refusals an answer can meet, from claim to verdict. */15const answerGroups = [16 "Push and claim",17 "Shape",18 "Merge",19 "Checks",20 "Never counted against the answerer",21] as const;2223type Group = (typeof groups)[number];2425type Member = Group["members"][number];2627type AnswerMember = Extract<28 Group,29 { readonly name: (typeof answerGroups)[number] }30>["members"][number];3132type AnswerTag = InstanceType<AnswerMember>["_tag"];3334/**35 * What to do on meeting it. A refusal whose `next` is set when it is raised36 * gives the command's form here, or what it names when no form fits.37 */38interface Repair {39 readonly todo: string;40 readonly next?: string;41 readonly nextNames?: string;42}4344const cli = (...words: readonly string[]) => [Brand.cli, ...words].join(" ");4546const repairs = {47 AskBlocked: {48 todo: "Wait for the asks it names to land, or answer one of them first.",49 },50 AskFull: { todo: "Someone else holds the claim: pick another ask." },51 AttemptsExhausted: {52 todo: "Wait until `resetsAt`: you used every attempt on that area's held-back checks for now.",53 },54 CapReached: {55 todo: "Release a claim you hold, or land one, before you take another.",56 },57 ChecksFailed: {58 nextNames: "the command that reproduces the failure",59 todo: "Run `next` to see the failure, fix it, and push again.",60 },61 ClaimLapsed: {62 next: cli("claim", "<ask>"),63 todo: "Your claim lapsed after a spell without a push: claim the ask again if it is still open.",64 },65 Denounced: {66 todo: "The project's vouch file denounces you: it takes no claims or proposals from you.",67 },68 DirectPush: {69 todo: "Main moves only by a landing: push your answer to your claim's fork.",70 },71 Flake: {72 todo: "Nothing: the check failed and then passed on the same tree, and the platform runs it again.",73 },74 HeldBackFailed: {75 todo: "A held-back check failed; you see only its area and suite. Fix the behaviour and push again.",76 },77 NoAsk: {78 todo: "Push to the fork your claim gave you, which names its ask.",79 },80 NotClaimed: {81 next: cli("claim", "<ask>"),82 todo: "Claim the ask, then push again.",83 },84 NotVouched: { todo: "Ask a member of the project to vouch for you." },85 OutOfScope: {86 todo: "Undo your changes to the paths it names: they are outside the ask's territory.",87 },88 PrivatePathInPublicTree: {89 todo: "Take the held-back paths it names out of your answer.",90 },91 ReachedInternals: {92 todo: "Import the other module only through its public files.",93 },94 RepoBusy: { todo: "Push again." },95 StaleBase: {96 todo: "Main moved: rebase onto it, resolve the conflicts it names, and push again.",97 },98 StaleLayer: { todo: "Nothing: the answer is checked again." },99 TouchedJudge: {100 todo: "Undo your changes to the paths it names: they decide what the checks do.",101 },102 VerifierBlocked: {103 todo: "Nothing: the platform could not run the checks, and runs them again.",104 },105 Weakened: {106 todo: "Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet.",107 },108} as const satisfies Record<AnswerTag, Repair>;109110const repairOf = new Map<string, Repair>(Object.entries(repairs));111112/** A field's value when the constructor fills it in, as it does a fixed `next`. */113const constructorDefault = (ast: SchemaAST.AST) => {114 const fill = ast.context?.constructorDefault;115116 return fill !== undefined &&117 Exit.isExit(fill) &&118 Exit.isSuccess(fill) &&119 Predicate.isString(fill.value)120 ? fill.value121 : undefined;122};123124/** One refusal an answer can meet, as the skills list it. */125export interface AnswerRefusal {126 readonly tag: string;127 readonly retryable: boolean;128 /** Its `next`, in Markdown: the command as a code span, or what it names. */129 readonly next: string;130 readonly todo: string;131}132133const nextOf = (fixed: string | undefined, repair: Repair | undefined) => {134 if (fixed !== undefined) {135 return code(fixed);136 }137138 return repair?.next === undefined139 ? (repair?.nextNames ?? "")140 : code(repair.next);141};142143/** Every refusal an answer can meet, in the union's order. */144export const answerRefusals: readonly AnswerRefusal[] = groups145 .flatMap((group): readonly Member[] =>146 answerGroups.some((answer) => answer === group.name) ? group.members : []147 )148 .map((member) => {149 const { ast: retryable } = member.fields.retryable;150 const fixed = constructorDefault(member.fields.next.ast);151 const repair = repairOf.get(member.identifier);152153 return {154 next: nextOf(fixed, repair),155 retryable: SchemaAST.isLiteral(retryable) && retryable.literal === true,156 tag: member.identifier,157 todo: repair?.todo ?? "",158 };159 });160161/** The refusals section every skill carries. */162export const refusalSection = () => [163 "## Refusals",164 "",165 `Instead of landing an answer, the platform answers with refusals. Git prints them on its \`remote:\` lines, \`${cli("check")}\` and \`${cli("status")}\` print them, and the verdict note holds them as JSON. Each one has a \`_tag\`, \`retryable\` (whether trying the same thing again can help) and \`next\` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.`,166 "",167 ...table(168 ["`_tag`", "Retryable", "`next`", "What to do"],169 answerRefusals.map(({ next, retryable, tag, todo }) => [170 code(tag),171 retryable ? "yes" : "no",172 next,173 todo,174 ])175 ),176 "",177];
added:packages/agent-kit/src/sections.ts+272 added
1/**2 * The sections the contribute skill, the AGENTS.md block and the platform's3 * own skill are made of, each from the policy or the brand alone. None4 * names the landing, so a landing that leaves the policy's text alone5 * leaves every generated body, and its hash, as it was.6 */7import { Brand } from "@repo/brand";8import { RatchetMeasure } from "@repo/protocol/domain/check";9import type { AskKind, CheckKind, ClaimRule } from "@repo/protocol/domain/kind";10import type { Policy } from "@repo/protocol/domain/policy";11import type { RunBlock } from "@repo/protocol/domain/run";12import { Array as Arr, Order, Predicate } from "effect";1314import { code, listed, table } from "./text.ts";1516const cli = (...words: readonly string[]) =>17 code([Brand.cli, ...words].join(" "));1819const remote = Brand.slug;2021const notesRef = `refs/notes/${Brand.slug}`;2223// --- The loop ----------------------------------------------------------------2425/**26 * The five steps every answer takes: read and claim, work, check, push,27 * read the verdict. The same in every generated file, so an agent that read28 * one knows them all.29 */30export const loopSteps = () => [31 `1. Read the ask, then claim it: ${cli("ask", "<ask>")}, then ${cli("claim", "<ask>")}. The claim prints your fork's remote; add it with ${code(`git remote add ${remote} <remote>`)}.`,32 "2. Work inside the ask's territory until its check passes.",33 `3. Run ${cli("check")}. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.`,34 `4. Push your answer to your fork: ${code(`git push ${remote} HEAD:main`)}. The push itself can be refused; follow the answer with ${cli("status")}.`,35 `5. Read the verdict on your head: ${code(`git fetch ${remote} ${notesRef}:${notesRef}`)}, then ${code(`git notes --ref=${Brand.slug} show HEAD`)}. It is JSON: match on its \`_tag\`, and run a refusal's \`next\`.`,36];3738const unitsOfTime = [39 { ms: 86_400_000 * 7, one: "week" },40 { ms: 86_400_000, one: "day" },41 { ms: 3_600_000, one: "hour" },42 { ms: 60_000, one: "minute" },43 { ms: 1000, one: "second" },44] as const;4546/** A span as a person says it: `2 hours`, `1 day`, `90 minutes`. */47export const span = (ms: number) => {48 const unit = unitsOfTime.find((each) => ms % each.ms === 0) ?? unitsOfTime[4];4950 const count = Math.round(ms / unit.ms);5152 return `${count} ${unit.one}${count === 1 ? "" : "s"}`;53};5455/** What the project's policy says about holding a claim. */56export const claimTerms = (policy: Policy) =>57 `A claim stays alive only while you push to it: after ${span(policy.claims.warnAfterMs)} without a push it is warned, and after ${span(policy.claims.lapseAfterMs)} it lapses. You may hold ${policy.caps.claimsPerPerson} ${policy.caps.claimsPerPerson === 1 ? "claim" : "claims"} at once in this project.`;5859// --- What an answer may change -------------------------------------------------6061const byName = <A>(name: (item: A) => string) =>62 Order.mapInput(Order.String, name);6364const judgeLines = (judge: Policy["judge"]) => [65 ...judge.paths.map((path) => `- ${code(path)}`),66 ...judge.pointers.map(67 (pointer) => `- ${code(pointer)} (only that part of the file)`68 ),69];7071const measureOf = RatchetMeasure.match({72 Count: ({ command, rule }) =>73 rule === undefined74 ? `the lint findings ${code(command)} prints`75 : `the ${code(rule)} findings ${code(command)} prints`,76 Metric: ({ command, path }) =>77 `the number at ${code(path)} in the JSON ${code(command)} prints`,78});7980const ratchetLines = (ratchets: Policy["ratchets"]) =>81 Arr.sort(82 ratchets,83 byName((ratchet: Policy["ratchets"][number]) => ratchet.name)84 ).map(85 (ratchet) =>86 `- ${code(ratchet.name)}${ratchet.territory === undefined ? "" : ` in ${code(ratchet.territory)}`}: ${measureOf(ratchet.measure)}`87 );8889/**90 * The territory rule, the public files rule, the judge closure, the91 * weakening markers and the ratchets: each held by a refusal the gate92 * gives, which the section names.93 */94export const changeSection = (policy: Policy) => {95 const { judge, modules, ratchets, weakening } = policy;9697 const publicFiles = modules.some(98 ({ publicFiles: files }) => files !== undefined99 );100101 const territories = Arr.sort(102 modules,103 byName((module: Policy["modules"][number]) => module.module)104 );105106 return [107 "## What an answer may change",108 "",109 `Change files only inside the ask's territory, the module ${cli("ask", "<ask>")} names; a push that changes anything else is refused with \`OutOfScope\`.`,110 ...(territories.length === 0111 ? []112 : [113 "",114 ...table(115 ["Module", "Paths", "Public files"],116 territories.map((module) => [117 code(module.module),118 module.paths.map(code).join(", "),119 module.publicFiles === undefined120 ? "every file"121 : module.publicFiles.map(code).join(", "),122 ])123 ),124 ]),125 ...(publicFiles126 ? [127 "",128 "Import another module only through its public files; an import that reaches past them is refused with `ReachedInternals`.",129 ]130 : []),131 ...(judge.paths.length + judge.pointers.length === 0132 ? []133 : [134 "",135 "Never change the judge closure, the files that decide what the checks do; a push that changes one is refused with `TouchedJudge`:",136 "",137 ...judgeLines(judge),138 ]),139 ...(weakening.markers.length === 0140 ? []141 : [142 "",143 `Never add a marker that turns a check off: ${weakening.markers.map(code).join(", ")}. One without a reason is refused with \`Weakened\`; one with a reason waits for a decider.`,144 ]),145 ...(ratchets.length === 0146 ? []147 : [148 "",149 "Ratchets only go down: an answer that raises one is refused with `Weakened`, and only a decider raises one.",150 "",151 ...ratchetLines(ratchets),152 ]),153 "",154 ];155};156157// --- The run block -------------------------------------------------------------158159/** The run block's lanes, by name. */160export const lanesOf = (run: RunBlock) =>161 Arr.sort(162 Object.entries(run.checks),163 byName(([lane]: readonly [string, string]) => lane)164 );165166export const runSection = (run: RunBlock) => [167 "## The run block",168 "",169 `The project's own commands. The platform runs them exactly as written, on the merged tree, in the ${code(run.image ?? "checker:default")} image; ${cli("check")} runs them on your machine.`,170 "",171 ...(run.setup === undefined ? [] : [`- Setup, once: ${code(run.setup)}`]),172 ...(run.setupEgress === undefined || run.setupEgress.length === 0173 ? []174 : [175 `- Setup may reach ${run.setupEgress.map(code).join(", ")}; the checks reach no network.`,176 ]),177 ...(run.doctor === undefined ? [] : [`- Doctor: ${code(run.doctor)}`]),178 `- One check file: ${code(run.test)}, with \`{path}\` the ask's check file`,179 "- Lanes, each run on every answer:",180 ...lanesOf(run).map(181 ([lane, command]) => ` - ${code(lane)}: ${code(command)}`182 ),183 "",184];185186// --- Ask kinds -----------------------------------------------------------------187188const checkKindText = (kind: CheckKind, run: RunBlock) =>189 ({190 lintToZero:191 "a lint rule's findings in the territory go to zero; the ask names the rule and the command that counts them.",192 migrate:193 "every use of one name moves to another; the ask names the command that counts the uses left.",194 ratchet: "a named ratchet goes down; the ask names it.",195 redThenGreen: `one check file fails on main by an assertion, and passes with your answer; ${cli("check")} runs it with ${code(run.test)}.`,196 symbolAbsent:197 "the last step of a migrate: a name is gone; the ask names the command that counts its uses.",198 })[kind];199200const claimerText = (rule: ClaimRule, vouchFile: string) => {201 if (Predicate.isString(rule)) {202 return rule === "anyone"203 ? "anyone signed in."204 : `anyone a member has vouched for in ${code(vouchFile)}.`;205 }206207 return "record" in rule208 ? `anyone whose record has at least ${rule.record.atLeast} ${rule.record.atLeast === 1 ? "landing" : "landings"} in ${code(rule.record.area)}.`209 : `a newcomer, with ${code(rule.newcomer.mentor)} as mentor.`;210};211212const finishText = {213 never: "none: a passing answer lands as it is.",214 optional:215 "a decider may add commits of their own to a passing answer before it lands, credited `Finished-by`.",216 required:217 "a passing answer waits for a decider's commits on top before it lands, credited `Finished-by`.",218} as const satisfies Record<AskKind["finish"], string>;219220const kindLines = (kind: AskKind, policy: Policy) => [221 `### ${code(kind.name)}`,222 "",223 `- Check: ${checkKindText(kind.checkKind, policy.run)}`,224 `- Who may claim: ${claimerText(kind.claimers, policy.vouch.file)}`,225 kind.race === 1226 ? "- Claims at once: 1; the claim is exclusive."227 : `- Claims at once: up to ${kind.race}.`,228 `- Finish: ${finishText[kind.finish]}`,229 ...(kind.oneWay ? ["- One way: a later answer can't undo its answers."] : []),230 ...(kind.requires.length === 0231 ? []232 : [`- The brief states: ${listed(kind.requires)}.`]),233 "",234];235236export const kindsSection = (policy: Policy) =>237 policy.kinds.length === 0238 ? []239 : [240 "## Ask kinds",241 "",242 `Each ask is of one kind, which says how its check judges an answer, who may claim it and whether a decider finishes it; ${cli("ask", "<ask>")} names it.`,243 "",244 ...Arr.sort(245 policy.kinds,246 byName((kind: AskKind) => kind.name)247 ).flatMap((kind) => kindLines(kind, policy)),248 ];249250// --- No fence yet ----------------------------------------------------------------251252/**253 * Norms the generated files state that nothing checks yet, listed as such254 * rather than as rules. Without a project, the default `agents` policy.255 */256export const unfencedNorms = (agents: Policy["agents"] = "trailer") => [257 "- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.",258 ...(agents === "none"259 ? []260 : [261 "- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.",262 ]),263];264265export const unfencedSection = (agents: Policy["agents"] = "trailer") => [266 "## No fence yet",267 "",268 "Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.",269 "",270 ...unfencedNorms(agents),271 "",272];
added:packages/agent-kit/src/text.ts+76 added
added:packages/agent-kit/src/well-known.ts+72 added
added:packages/agent-kit/test/golden/agent-plugins-stdio.txt+97 added
1==> plugins/__SLUG__/plugin.json <==2{3 "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",4 "description": "The __NAME__ CLI's skill and MCP server: find an ask, claim it, check your answer locally, push it, and read the verdict.",5 "name": "__SLUG__"6}78==> plugins/__SLUG__/skills/__SLUG__/SKILL.md <==9---10name: __SLUG__11description: "Contribute to projects on __NAME__ with the `__SLUG__` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on __NAME__, or when a push was refused with a refusal such as OutOfScope or StaleBase."12metadata:13 managed-by: "__SLUG__"14 content-hash: "sha256:8a8ea9eed71ff4e3bf0de80fce9b559d693e027826022b91151ba8aae2a375c1"15---16# __NAME__1718__NAME__ is a git platform where a change lands only by passing a typed gate. A project states each change it wants as an ask; you answer one with a commit pushed to your claim's fork, and the platform checks it and lands it, or answers with refusals that say what to do next.1920## The loop2122Find an ask with `__CLI__ asks`, then, in the project's repo:23241. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.252. Work inside the ask's territory until its check passes.263. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.274. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.285. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.2930A project's own `<project>-contribute` skill and the block in its AGENTS.md give its territories, its run block and its ask kinds.3132## Output3334Every command prints Markdown; `--json` prints one versioned JSON envelope instead. A command that needs a person's approval runs only with `--yes`, and `--dry-run` prints what it would send.3536## Commands3738| Command | Flags | What it does |39| --- | --- | --- |40| `__CLI__ asks` | `--project` `--json` | List a project's open asks. Only reads. |41| `__CLI__ check` | `--ask` `--project` `--base` `--json` | Run the gate's checks on your answer locally, before you push. Only reads. |42| `__CLI__ claim <ask>` | `--project` `--json` `--dry-run` | Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim. |43| `__CLI__ vouch` | `--project` `--handle` `--verdict` `--note` `--json` `--yes` `--dry-run` | Vouch for a person, or denounce them, by landing a line in the project's vouch file. Runs only with `--yes`. |4445## MCP4647`__CLI__ mcp` serves the platform's contracts as MCP tools over stdio, with your stored token.4849## Refusals5051Instead of landing an answer, the platform answers with refusals. Git prints them on its `remote:` lines, `__CLI__ check` and `__CLI__ status` print them, and the verdict note holds them as JSON. Each one has a `_tag`, `retryable` (whether trying the same thing again can help) and `next` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.5253| `_tag` | Retryable | `next` | What to do |54| --- | --- | --- | --- |55| `NotClaimed` | yes | `__CLI__ claim <ask>` | Claim the ask, then push again. |56| `ClaimLapsed` | yes | `__CLI__ claim <ask>` | Your claim lapsed after a spell without a push: claim the ask again if it is still open. |57| `NotVouched` | no | `__CLI__ status` | Ask a member of the project to vouch for you. |58| `CapReached` | yes | `__CLI__ status` | Release a claim you hold, or land one, before you take another. |59| `AskFull` | yes | `__CLI__ asks` | Someone else holds the claim: pick another ask. |60| `NoAsk` | no | `__CLI__ asks` | Push to the fork your claim gave you, which names its ask. |61| `RepoBusy` | yes | `git push` | Push again. |62| `DirectPush` | no | `__CLI__ asks` | Main moves only by a landing: push your answer to your claim's fork. |63| `AskBlocked` | yes | `__CLI__ asks` | Wait for the asks it names to land, or answer one of them first. |64| `Denounced` | no | `__CLI__ status` | The project's vouch file denounces you: it takes no claims or proposals from you. |65| `OutOfScope` | no | `__CLI__ check` | Undo your changes to the paths it names: they are outside the ask's territory. |66| `TouchedJudge` | no | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |67| `Weakened` | no | `__CLI__ check` | Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet. |68| `PrivatePathInPublicTree` | no | `__CLI__ check` | Take the held-back paths it names out of your answer. |69| `ReachedInternals` | no | `__CLI__ check` | Import the other module only through its public files. |70| `StaleBase` | yes | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |71| `StaleLayer` | yes | `__CLI__ status` | Nothing: the answer is checked again. |72| `ChecksFailed` | no | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |73| `HeldBackFailed` | no | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |74| `AttemptsExhausted` | yes | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |75| `Flake` | yes | `__CLI__ status` | Nothing: the check failed and then passed on the same tree, and the platform runs it again. |76| `VerifierBlocked` | yes | `__CLI__ status` | Nothing: the platform could not run the checks, and runs them again. |7778## No fence yet7980Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.8182- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.83- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.8485==> plugins/__SLUG__/mcp.json <==86{87 "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",88 "mcpServers": {89 "__SLUG__": {90 "args": [91 "mcp"92 ],93 "command": "__SLUG__",94 "type": "stdio"95 }96 }97}
added:packages/agent-kit/test/golden/agent-plugins.txt+95 added
1==> plugins/__SLUG__/plugin.json <==2{3 "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",4 "description": "The __NAME__ CLI's skill and MCP server: find an ask, claim it, check your answer locally, push it, and read the verdict.",5 "homepage": "https://__SLUG__.technology",6 "name": "__SLUG__"7}89==> plugins/__SLUG__/skills/__SLUG__/SKILL.md <==10---11name: __SLUG__12description: "Contribute to projects on __NAME__ with the `__SLUG__` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on __NAME__, or when a push was refused with a refusal such as OutOfScope or StaleBase."13metadata:14 managed-by: "__SLUG__"15 content-hash: "sha256:64e2711bd027ebf274c67139c56f14d73128ffe058c57609223d3e39c08fabd3"16---17# __NAME__1819__NAME__ is a git platform where a change lands only by passing a typed gate. A project states each change it wants as an ask; you answer one with a commit pushed to your claim's fork, and the platform checks it and lands it, or answers with refusals that say what to do next.2021## The loop2223Find an ask with `__CLI__ asks`, then, in the project's repo:24251. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.262. Work inside the ask's territory until its check passes.273. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.284. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.295. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.3031A project's own `<project>-contribute` skill and the block in its AGENTS.md give its territories, its run block and its ask kinds.3233## Output3435Every command prints Markdown; `--json` prints one versioned JSON envelope instead. A command that needs a person's approval runs only with `--yes`, and `--dry-run` prints what it would send.3637## Commands3839| Command | Flags | What it does |40| --- | --- | --- |41| `__CLI__ asks` | `--project` `--json` | List a project's open asks. Only reads. |42| `__CLI__ check` | `--ask` `--project` `--base` `--json` | Run the gate's checks on your answer locally, before you push. Only reads. |43| `__CLI__ claim <ask>` | `--project` `--json` `--dry-run` | Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim. |44| `__CLI__ vouch` | `--project` `--handle` `--verdict` `--note` `--json` `--yes` `--dry-run` | Vouch for a person, or denounce them, by landing a line in the project's vouch file. Runs only with `--yes`. |4546## MCP4748The platform serves its contracts as MCP tools at `https://__SLUG__.technology/mcp`; `__CLI__ mcp` serves the same tools over stdio, with your stored token.4950## Refusals5152Instead of landing an answer, the platform answers with refusals. Git prints them on its `remote:` lines, `__CLI__ check` and `__CLI__ status` print them, and the verdict note holds them as JSON. Each one has a `_tag`, `retryable` (whether trying the same thing again can help) and `next` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.5354| `_tag` | Retryable | `next` | What to do |55| --- | --- | --- | --- |56| `NotClaimed` | yes | `__CLI__ claim <ask>` | Claim the ask, then push again. |57| `ClaimLapsed` | yes | `__CLI__ claim <ask>` | Your claim lapsed after a spell without a push: claim the ask again if it is still open. |58| `NotVouched` | no | `__CLI__ status` | Ask a member of the project to vouch for you. |59| `CapReached` | yes | `__CLI__ status` | Release a claim you hold, or land one, before you take another. |60| `AskFull` | yes | `__CLI__ asks` | Someone else holds the claim: pick another ask. |61| `NoAsk` | no | `__CLI__ asks` | Push to the fork your claim gave you, which names its ask. |62| `RepoBusy` | yes | `git push` | Push again. |63| `DirectPush` | no | `__CLI__ asks` | Main moves only by a landing: push your answer to your claim's fork. |64| `AskBlocked` | yes | `__CLI__ asks` | Wait for the asks it names to land, or answer one of them first. |65| `Denounced` | no | `__CLI__ status` | The project's vouch file denounces you: it takes no claims or proposals from you. |66| `OutOfScope` | no | `__CLI__ check` | Undo your changes to the paths it names: they are outside the ask's territory. |67| `TouchedJudge` | no | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |68| `Weakened` | no | `__CLI__ check` | Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet. |69| `PrivatePathInPublicTree` | no | `__CLI__ check` | Take the held-back paths it names out of your answer. |70| `ReachedInternals` | no | `__CLI__ check` | Import the other module only through its public files. |71| `StaleBase` | yes | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |72| `StaleLayer` | yes | `__CLI__ status` | Nothing: the answer is checked again. |73| `ChecksFailed` | no | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |74| `HeldBackFailed` | no | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |75| `AttemptsExhausted` | yes | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |76| `Flake` | yes | `__CLI__ status` | Nothing: the check failed and then passed on the same tree, and the platform runs it again. |77| `VerifierBlocked` | yes | `__CLI__ status` | Nothing: the platform could not run the checks, and runs them again. |7879## No fence yet8081Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.8283- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.84- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.8586==> plugins/__SLUG__/mcp.json <==87{88 "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",89 "mcpServers": {90 "__SLUG__": {91 "type": "streamable-http",92 "url": "https://__SLUG__.technology/mcp"93 }94 }95}
added:packages/agent-kit/test/golden/agents-block.txt+23 added
1==> AGENTS.md <==2<!-- BEGIN __SLUG__ contribute (generated; content-hash: sha256:8bc87e18feaa6e1f6a121ec99a78a92f3edaa1fdc2eead4181dee67ee60b7b71) -->3## Contributing to datekit45This project takes changes through __NAME__: an answer to one of its asks lands only by passing the gate. This block is generated from the config folder, and the gate decides what lands. The full guide is the `datekit-contribute` skill (`.agents/skills/datekit-contribute/SKILL.md`).671. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.82. Work inside the ask's territory until its check passes.93. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.104. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.115. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.1213- Change only files in the ask's territory; a push that changes anything else is refused with `OutOfScope`.14- Never change the judge closure (`.__SLUG__/**`, `bunfig.toml`, `tsconfig.json`, `package.json#/scripts`); a push that does is refused with `TouchedJudge`.15- Never add a marker that turns a check off (`.skip(`, `.only(`, `@ts-ignore`); one without a reason is refused with `Weakened`.16- Test one file with `bun test {path}`. The lanes are `lint` (`bun run lint`), `types` (`bun run typecheck`) and `unit` (`bun test`).17- Every refusal has a `_tag`, `retryable` and `next`: run `next`. Add `--json` to any command for JSON.1819No fence yet: nothing checks these, so the gate won't refuse you for them.2021- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.22- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.23<!-- END __SLUG__ contribute -->
added:packages/agent-kit/test/golden/claude-plugin-stdio.txt+131 added
1==> plugins/__SLUG__/.claude-plugin/plugin.json <==2{3 "description": "The __NAME__ CLI's skill, MCP server and hooks: the gate's scope guard before an edit, the claimed ask's brief at the start, and its verdict before you stop.",4 "name": "__SLUG__"5}67==> plugins/__SLUG__/skills/__SLUG__/SKILL.md <==8---9name: __SLUG__10description: "Contribute to projects on __NAME__ with the `__SLUG__` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on __NAME__, or when a push was refused with a refusal such as OutOfScope or StaleBase."11metadata:12 managed-by: "__SLUG__"13 content-hash: "sha256:8a8ea9eed71ff4e3bf0de80fce9b559d693e027826022b91151ba8aae2a375c1"14---15# __NAME__1617__NAME__ is a git platform where a change lands only by passing a typed gate. A project states each change it wants as an ask; you answer one with a commit pushed to your claim's fork, and the platform checks it and lands it, or answers with refusals that say what to do next.1819## The loop2021Find an ask with `__CLI__ asks`, then, in the project's repo:22231. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.242. Work inside the ask's territory until its check passes.253. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.264. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.275. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.2829A project's own `<project>-contribute` skill and the block in its AGENTS.md give its territories, its run block and its ask kinds.3031## Output3233Every command prints Markdown; `--json` prints one versioned JSON envelope instead. A command that needs a person's approval runs only with `--yes`, and `--dry-run` prints what it would send.3435## Commands3637| Command | Flags | What it does |38| --- | --- | --- |39| `__CLI__ asks` | `--project` `--json` | List a project's open asks. Only reads. |40| `__CLI__ check` | `--ask` `--project` `--base` `--json` | Run the gate's checks on your answer locally, before you push. Only reads. |41| `__CLI__ claim <ask>` | `--project` `--json` `--dry-run` | Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim. |42| `__CLI__ vouch` | `--project` `--handle` `--verdict` `--note` `--json` `--yes` `--dry-run` | Vouch for a person, or denounce them, by landing a line in the project's vouch file. Runs only with `--yes`. |4344## MCP4546`__CLI__ mcp` serves the platform's contracts as MCP tools over stdio, with your stored token.4748## Refusals4950Instead of landing an answer, the platform answers with refusals. Git prints them on its `remote:` lines, `__CLI__ check` and `__CLI__ status` print them, and the verdict note holds them as JSON. Each one has a `_tag`, `retryable` (whether trying the same thing again can help) and `next` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.5152| `_tag` | Retryable | `next` | What to do |53| --- | --- | --- | --- |54| `NotClaimed` | yes | `__CLI__ claim <ask>` | Claim the ask, then push again. |55| `ClaimLapsed` | yes | `__CLI__ claim <ask>` | Your claim lapsed after a spell without a push: claim the ask again if it is still open. |56| `NotVouched` | no | `__CLI__ status` | Ask a member of the project to vouch for you. |57| `CapReached` | yes | `__CLI__ status` | Release a claim you hold, or land one, before you take another. |58| `AskFull` | yes | `__CLI__ asks` | Someone else holds the claim: pick another ask. |59| `NoAsk` | no | `__CLI__ asks` | Push to the fork your claim gave you, which names its ask. |60| `RepoBusy` | yes | `git push` | Push again. |61| `DirectPush` | no | `__CLI__ asks` | Main moves only by a landing: push your answer to your claim's fork. |62| `AskBlocked` | yes | `__CLI__ asks` | Wait for the asks it names to land, or answer one of them first. |63| `Denounced` | no | `__CLI__ status` | The project's vouch file denounces you: it takes no claims or proposals from you. |64| `OutOfScope` | no | `__CLI__ check` | Undo your changes to the paths it names: they are outside the ask's territory. |65| `TouchedJudge` | no | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |66| `Weakened` | no | `__CLI__ check` | Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet. |67| `PrivatePathInPublicTree` | no | `__CLI__ check` | Take the held-back paths it names out of your answer. |68| `ReachedInternals` | no | `__CLI__ check` | Import the other module only through its public files. |69| `StaleBase` | yes | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |70| `StaleLayer` | yes | `__CLI__ status` | Nothing: the answer is checked again. |71| `ChecksFailed` | no | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |72| `HeldBackFailed` | no | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |73| `AttemptsExhausted` | yes | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |74| `Flake` | yes | `__CLI__ status` | Nothing: the check failed and then passed on the same tree, and the platform runs it again. |75| `VerifierBlocked` | yes | `__CLI__ status` | Nothing: the platform could not run the checks, and runs them again. |7677## No fence yet7879Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.8081- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.82- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.8384==> plugins/__SLUG__/.mcp.json <==85{86 "mcpServers": {87 "__SLUG__": {88 "args": [89 "mcp"90 ],91 "command": "__SLUG__"92 }93 }94}9596==> plugins/__SLUG__/hooks/hooks.json <==97{98 "hooks": {99 "PreToolUse": [100 {101 "hooks": [102 {103 "command": "__CLI__ hook pre-tool-use --json",104 "type": "command"105 }106 ],107 "matcher": "Edit|Write|MultiEdit|NotebookEdit"108 }109 ],110 "SessionStart": [111 {112 "hooks": [113 {114 "command": "__CLI__ hook session-start --json",115 "type": "command"116 }117 ]118 }119 ],120 "Stop": [121 {122 "hooks": [123 {124 "command": "__CLI__ hook stop --json",125 "type": "command"126 }127 ]128 }129 ]130 }131}
added:packages/agent-kit/test/golden/claude-plugin.txt+130 added
1==> plugins/__SLUG__/.claude-plugin/plugin.json <==2{3 "description": "The __NAME__ CLI's skill, MCP server and hooks: the gate's scope guard before an edit, the claimed ask's brief at the start, and its verdict before you stop.",4 "homepage": "https://__SLUG__.technology",5 "name": "__SLUG__"6}78==> plugins/__SLUG__/skills/__SLUG__/SKILL.md <==9---10name: __SLUG__11description: "Contribute to projects on __NAME__ with the `__SLUG__` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on __NAME__, or when a push was refused with a refusal such as OutOfScope or StaleBase."12metadata:13 managed-by: "__SLUG__"14 content-hash: "sha256:64e2711bd027ebf274c67139c56f14d73128ffe058c57609223d3e39c08fabd3"15---16# __NAME__1718__NAME__ is a git platform where a change lands only by passing a typed gate. A project states each change it wants as an ask; you answer one with a commit pushed to your claim's fork, and the platform checks it and lands it, or answers with refusals that say what to do next.1920## The loop2122Find an ask with `__CLI__ asks`, then, in the project's repo:23241. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.252. Work inside the ask's territory until its check passes.263. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.274. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.285. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.2930A project's own `<project>-contribute` skill and the block in its AGENTS.md give its territories, its run block and its ask kinds.3132## Output3334Every command prints Markdown; `--json` prints one versioned JSON envelope instead. A command that needs a person's approval runs only with `--yes`, and `--dry-run` prints what it would send.3536## Commands3738| Command | Flags | What it does |39| --- | --- | --- |40| `__CLI__ asks` | `--project` `--json` | List a project's open asks. Only reads. |41| `__CLI__ check` | `--ask` `--project` `--base` `--json` | Run the gate's checks on your answer locally, before you push. Only reads. |42| `__CLI__ claim <ask>` | `--project` `--json` `--dry-run` | Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim. |43| `__CLI__ vouch` | `--project` `--handle` `--verdict` `--note` `--json` `--yes` `--dry-run` | Vouch for a person, or denounce them, by landing a line in the project's vouch file. Runs only with `--yes`. |4445## MCP4647The platform serves its contracts as MCP tools at `https://__SLUG__.technology/mcp`; `__CLI__ mcp` serves the same tools over stdio, with your stored token.4849## Refusals5051Instead of landing an answer, the platform answers with refusals. Git prints them on its `remote:` lines, `__CLI__ check` and `__CLI__ status` print them, and the verdict note holds them as JSON. Each one has a `_tag`, `retryable` (whether trying the same thing again can help) and `next` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.5253| `_tag` | Retryable | `next` | What to do |54| --- | --- | --- | --- |55| `NotClaimed` | yes | `__CLI__ claim <ask>` | Claim the ask, then push again. |56| `ClaimLapsed` | yes | `__CLI__ claim <ask>` | Your claim lapsed after a spell without a push: claim the ask again if it is still open. |57| `NotVouched` | no | `__CLI__ status` | Ask a member of the project to vouch for you. |58| `CapReached` | yes | `__CLI__ status` | Release a claim you hold, or land one, before you take another. |59| `AskFull` | yes | `__CLI__ asks` | Someone else holds the claim: pick another ask. |60| `NoAsk` | no | `__CLI__ asks` | Push to the fork your claim gave you, which names its ask. |61| `RepoBusy` | yes | `git push` | Push again. |62| `DirectPush` | no | `__CLI__ asks` | Main moves only by a landing: push your answer to your claim's fork. |63| `AskBlocked` | yes | `__CLI__ asks` | Wait for the asks it names to land, or answer one of them first. |64| `Denounced` | no | `__CLI__ status` | The project's vouch file denounces you: it takes no claims or proposals from you. |65| `OutOfScope` | no | `__CLI__ check` | Undo your changes to the paths it names: they are outside the ask's territory. |66| `TouchedJudge` | no | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |67| `Weakened` | no | `__CLI__ check` | Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet. |68| `PrivatePathInPublicTree` | no | `__CLI__ check` | Take the held-back paths it names out of your answer. |69| `ReachedInternals` | no | `__CLI__ check` | Import the other module only through its public files. |70| `StaleBase` | yes | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |71| `StaleLayer` | yes | `__CLI__ status` | Nothing: the answer is checked again. |72| `ChecksFailed` | no | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |73| `HeldBackFailed` | no | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |74| `AttemptsExhausted` | yes | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |75| `Flake` | yes | `__CLI__ status` | Nothing: the check failed and then passed on the same tree, and the platform runs it again. |76| `VerifierBlocked` | yes | `__CLI__ status` | Nothing: the platform could not run the checks, and runs them again. |7778## No fence yet7980Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.8182- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.83- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.8485==> plugins/__SLUG__/.mcp.json <==86{87 "mcpServers": {88 "__SLUG__": {89 "type": "http",90 "url": "https://__SLUG__.technology/mcp"91 }92 }93}9495==> plugins/__SLUG__/hooks/hooks.json <==96{97 "hooks": {98 "PreToolUse": [99 {100 "hooks": [101 {102 "command": "__CLI__ hook pre-tool-use --json",103 "type": "command"104 }105 ],106 "matcher": "Edit|Write|MultiEdit|NotebookEdit"107 }108 ],109 "SessionStart": [110 {111 "hooks": [112 {113 "command": "__CLI__ hook session-start --json",114 "type": "command"115 }116 ]117 }118 ],119 "Stop": [120 {121 "hooks": [122 {123 "command": "__CLI__ hook stop --json",124 "type": "command"125 }126 ]127 }128 ]129 }130}
added:packages/agent-kit/test/golden/platform-skill.txt+76 added
1==> skills/__SLUG__/SKILL.md <==2---3name: __SLUG__4description: "Contribute to projects on __NAME__ with the `__SLUG__` CLI: find an ask, claim it, check your answer locally, push it to your fork, and read the verdict. Use when a repo's remote is on __NAME__, or when a push was refused with a refusal such as OutOfScope or StaleBase."5metadata:6 managed-by: "__SLUG__"7 content-hash: "sha256:64e2711bd027ebf274c67139c56f14d73128ffe058c57609223d3e39c08fabd3"8---9# __NAME__1011__NAME__ is a git platform where a change lands only by passing a typed gate. A project states each change it wants as an ask; you answer one with a commit pushed to your claim's fork, and the platform checks it and lands it, or answers with refusals that say what to do next.1213## The loop1415Find an ask with `__CLI__ asks`, then, in the project's repo:16171. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.182. Work inside the ask's territory until its check passes.193. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.204. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.215. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.2223A project's own `<project>-contribute` skill and the block in its AGENTS.md give its territories, its run block and its ask kinds.2425## Output2627Every command prints Markdown; `--json` prints one versioned JSON envelope instead. A command that needs a person's approval runs only with `--yes`, and `--dry-run` prints what it would send.2829## Commands3031| Command | Flags | What it does |32| --- | --- | --- |33| `__CLI__ asks` | `--project` `--json` | List a project's open asks. Only reads. |34| `__CLI__ check` | `--ask` `--project` `--base` `--json` | Run the gate's checks on your answer locally, before you push. Only reads. |35| `__CLI__ claim <ask>` | `--project` `--json` `--dry-run` | Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim. |36| `__CLI__ vouch` | `--project` `--handle` `--verdict` `--note` `--json` `--yes` `--dry-run` | Vouch for a person, or denounce them, by landing a line in the project's vouch file. Runs only with `--yes`. |3738## MCP3940The platform serves its contracts as MCP tools at `https://__SLUG__.technology/mcp`; `__CLI__ mcp` serves the same tools over stdio, with your stored token.4142## Refusals4344Instead of landing an answer, the platform answers with refusals. Git prints them on its `remote:` lines, `__CLI__ check` and `__CLI__ status` print them, and the verdict note holds them as JSON. Each one has a `_tag`, `retryable` (whether trying the same thing again can help) and `next` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.4546| `_tag` | Retryable | `next` | What to do |47| --- | --- | --- | --- |48| `NotClaimed` | yes | `__CLI__ claim <ask>` | Claim the ask, then push again. |49| `ClaimLapsed` | yes | `__CLI__ claim <ask>` | Your claim lapsed after a spell without a push: claim the ask again if it is still open. |50| `NotVouched` | no | `__CLI__ status` | Ask a member of the project to vouch for you. |51| `CapReached` | yes | `__CLI__ status` | Release a claim you hold, or land one, before you take another. |52| `AskFull` | yes | `__CLI__ asks` | Someone else holds the claim: pick another ask. |53| `NoAsk` | no | `__CLI__ asks` | Push to the fork your claim gave you, which names its ask. |54| `RepoBusy` | yes | `git push` | Push again. |55| `DirectPush` | no | `__CLI__ asks` | Main moves only by a landing: push your answer to your claim's fork. |56| `AskBlocked` | yes | `__CLI__ asks` | Wait for the asks it names to land, or answer one of them first. |57| `Denounced` | no | `__CLI__ status` | The project's vouch file denounces you: it takes no claims or proposals from you. |58| `OutOfScope` | no | `__CLI__ check` | Undo your changes to the paths it names: they are outside the ask's territory. |59| `TouchedJudge` | no | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |60| `Weakened` | no | `__CLI__ check` | Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet. |61| `PrivatePathInPublicTree` | no | `__CLI__ check` | Take the held-back paths it names out of your answer. |62| `ReachedInternals` | no | `__CLI__ check` | Import the other module only through its public files. |63| `StaleBase` | yes | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |64| `StaleLayer` | yes | `__CLI__ status` | Nothing: the answer is checked again. |65| `ChecksFailed` | no | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |66| `HeldBackFailed` | no | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |67| `AttemptsExhausted` | yes | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |68| `Flake` | yes | `__CLI__ status` | Nothing: the check failed and then passed on the same tree, and the platform runs it again. |69| `VerifierBlocked` | yes | `__CLI__ status` | Nothing: the platform could not run the checks, and runs them again. |7071## No fence yet7273Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.7475- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.76- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.
added:packages/agent-kit/test/golden/project-skill.txt+221 added
1==> .agents/skills/datekit-contribute/SKILL.md <==2---3name: datekit-contribute4description: "Answer one of datekit's asks on __NAME__: claim it, change only its territory, run `__CLI__ check`, push it to your fork, and read the verdict. Use when working on datekit, or when a push to it was refused."5metadata:6 managed-by: "__SLUG__"7 landed: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"8 content-hash: "sha256:46fa2ac0a9b213b2e9a5f9a1c3e54246809e6c2326fc80c97a0881034932e369"9---10# Contribute to datekit1112How to answer datekit's asks on __NAME__. It is generated from datekit's config folder: the gate decides what lands, and where this text and the gate differ, the gate wins. Don't edit it by hand; it is regenerated when the config changes.1314## The loop15161. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.172. Work inside the ask's territory until its check passes.183. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.194. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.205. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.2122A claim stays alive only while you push to it: after 2 hours without a push it is warned, and after 1 day it lapses. You may hold 3 claims at once in this project.2324List the open asks with `__CLI__ asks`. Add `--json` to any command for one JSON envelope instead of Markdown.2526## What an answer may change2728Change files only inside the ask's territory, the module `__CLI__ ask <ask>` names; a push that changes anything else is refused with `OutOfScope`.2930| Module | Paths | Public files |31| --- | --- | --- |32| `format` | `packages/format/**` | `packages/format/src/index.ts` |33| `parse` | `packages/parse/**` | `packages/parse/src/index.ts` |3435Import another module only through its public files; an import that reaches past them is refused with `ReachedInternals`.3637Never change the judge closure, the files that decide what the checks do; a push that changes one is refused with `TouchedJudge`:3839- `.__SLUG__/**`40- `bunfig.toml`41- `tsconfig.json`42- `package.json#/scripts` (only that part of the file)4344Never add a marker that turns a check off: `.skip(`, `.only(`, `@ts-ignore`. One without a reason is refused with `Weakened`; one with a reason waits for a decider.4546## The run block4748The project's own commands. The platform runs them exactly as written, on the merged tree, in the `checker:default` image; `__CLI__ check` runs them on your machine.4950- One check file: `bun test {path}`, with `{path}` the ask's check file51- Lanes, each run on every answer:52 - `lint`: `bun run lint`53 - `types`: `bun run typecheck`54 - `unit`: `bun test`5556## Ask kinds5758Each ask is of one kind, which says how its check judges an answer, who may claim it and whether a decider finishes it; `__CLI__ ask <ask>` names it.5960### `fix`6162- Check: one check file fails on main by an assertion, and passes with your answer; `__CLI__ check` runs it with `bun test {path}`.63- Who may claim: anyone a member has vouched for in `.__SLUG__/vouched.td`.64- Claims at once: 1; the claim is exclusive.65- Finish: a decider may add commits of their own to a passing answer before it lands, credited `Finished-by`.66- The brief states: want, check and territory.6768### `lint`6970- Check: a lint rule's findings in the territory go to zero; the ask names the rule and the command that counts them.71- Who may claim: anyone signed in.72- Claims at once: up to 2.73- Finish: none: a passing answer lands as it is.74- The brief states: want and check.7576## Refusals7778Instead of landing an answer, the platform answers with refusals. Git prints them on its `remote:` lines, `__CLI__ check` and `__CLI__ status` print them, and the verdict note holds them as JSON. Each one has a `_tag`, `retryable` (whether trying the same thing again can help) and `next` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.7980| `_tag` | Retryable | `next` | What to do |81| --- | --- | --- | --- |82| `NotClaimed` | yes | `__CLI__ claim <ask>` | Claim the ask, then push again. |83| `ClaimLapsed` | yes | `__CLI__ claim <ask>` | Your claim lapsed after a spell without a push: claim the ask again if it is still open. |84| `NotVouched` | no | `__CLI__ status` | Ask a member of the project to vouch for you. |85| `CapReached` | yes | `__CLI__ status` | Release a claim you hold, or land one, before you take another. |86| `AskFull` | yes | `__CLI__ asks` | Someone else holds the claim: pick another ask. |87| `NoAsk` | no | `__CLI__ asks` | Push to the fork your claim gave you, which names its ask. |88| `RepoBusy` | yes | `git push` | Push again. |89| `DirectPush` | no | `__CLI__ asks` | Main moves only by a landing: push your answer to your claim's fork. |90| `AskBlocked` | yes | `__CLI__ asks` | Wait for the asks it names to land, or answer one of them first. |91| `Denounced` | no | `__CLI__ status` | The project's vouch file denounces you: it takes no claims or proposals from you. |92| `OutOfScope` | no | `__CLI__ check` | Undo your changes to the paths it names: they are outside the ask's territory. |93| `TouchedJudge` | no | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |94| `Weakened` | no | `__CLI__ check` | Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet. |95| `PrivatePathInPublicTree` | no | `__CLI__ check` | Take the held-back paths it names out of your answer. |96| `ReachedInternals` | no | `__CLI__ check` | Import the other module only through its public files. |97| `StaleBase` | yes | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |98| `StaleLayer` | yes | `__CLI__ status` | Nothing: the answer is checked again. |99| `ChecksFailed` | no | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |100| `HeldBackFailed` | no | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |101| `AttemptsExhausted` | yes | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |102| `Flake` | yes | `__CLI__ status` | Nothing: the check failed and then passed on the same tree, and the platform runs it again. |103| `VerifierBlocked` | yes | `__CLI__ status` | Nothing: the platform could not run the checks, and runs them again. |104105## No fence yet106107Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.108109- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.110- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.111112==> .claude/skills/datekit-contribute/SKILL.md <==113---114name: datekit-contribute115description: "Answer one of datekit's asks on __NAME__: claim it, change only its territory, run `__CLI__ check`, push it to your fork, and read the verdict. Use when working on datekit, or when a push to it was refused."116metadata:117 managed-by: "__SLUG__"118 landed: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"119 content-hash: "sha256:46fa2ac0a9b213b2e9a5f9a1c3e54246809e6c2326fc80c97a0881034932e369"120---121# Contribute to datekit122123How to answer datekit's asks on __NAME__. It is generated from datekit's config folder: the gate decides what lands, and where this text and the gate differ, the gate wins. Don't edit it by hand; it is regenerated when the config changes.124125## The loop1261271. Read the ask, then claim it: `__CLI__ ask <ask>`, then `__CLI__ claim <ask>`. The claim prints your fork's remote; add it with `git remote add __SLUG__ <remote>`.1282. Work inside the ask's territory until its check passes.1293. Run `__CLI__ check`. It gives the refusals a push would get, then runs the ask's check and the project's lanes; fix everything it reports.1304. Push your answer to your fork: `git push __SLUG__ HEAD:main`. The push itself can be refused; follow the answer with `__CLI__ status`.1315. Read the verdict on your head: `git fetch __SLUG__ refs/notes/__SLUG__:refs/notes/__SLUG__`, then `git notes --ref=__SLUG__ show HEAD`. It is JSON: match on its `_tag`, and run a refusal's `next`.132133A claim stays alive only while you push to it: after 2 hours without a push it is warned, and after 1 day it lapses. You may hold 3 claims at once in this project.134135List the open asks with `__CLI__ asks`. Add `--json` to any command for one JSON envelope instead of Markdown.136137## What an answer may change138139Change files only inside the ask's territory, the module `__CLI__ ask <ask>` names; a push that changes anything else is refused with `OutOfScope`.140141| Module | Paths | Public files |142| --- | --- | --- |143| `format` | `packages/format/**` | `packages/format/src/index.ts` |144| `parse` | `packages/parse/**` | `packages/parse/src/index.ts` |145146Import another module only through its public files; an import that reaches past them is refused with `ReachedInternals`.147148Never change the judge closure, the files that decide what the checks do; a push that changes one is refused with `TouchedJudge`:149150- `.__SLUG__/**`151- `bunfig.toml`152- `tsconfig.json`153- `package.json#/scripts` (only that part of the file)154155Never add a marker that turns a check off: `.skip(`, `.only(`, `@ts-ignore`. One without a reason is refused with `Weakened`; one with a reason waits for a decider.156157## The run block158159The project's own commands. The platform runs them exactly as written, on the merged tree, in the `checker:default` image; `__CLI__ check` runs them on your machine.160161- One check file: `bun test {path}`, with `{path}` the ask's check file162- Lanes, each run on every answer:163 - `lint`: `bun run lint`164 - `types`: `bun run typecheck`165 - `unit`: `bun test`166167## Ask kinds168169Each ask is of one kind, which says how its check judges an answer, who may claim it and whether a decider finishes it; `__CLI__ ask <ask>` names it.170171### `fix`172173- Check: one check file fails on main by an assertion, and passes with your answer; `__CLI__ check` runs it with `bun test {path}`.174- Who may claim: anyone a member has vouched for in `.__SLUG__/vouched.td`.175- Claims at once: 1; the claim is exclusive.176- Finish: a decider may add commits of their own to a passing answer before it lands, credited `Finished-by`.177- The brief states: want, check and territory.178179### `lint`180181- Check: a lint rule's findings in the territory go to zero; the ask names the rule and the command that counts them.182- Who may claim: anyone signed in.183- Claims at once: up to 2.184- Finish: none: a passing answer lands as it is.185- The brief states: want and check.186187## Refusals188189Instead of landing an answer, the platform answers with refusals. Git prints them on its `remote:` lines, `__CLI__ check` and `__CLI__ status` print them, and the verdict note holds them as JSON. Each one has a `_tag`, `retryable` (whether trying the same thing again can help) and `next` (the command to run next). The refusals about an answer's files arrive together, so one push hears about all of them.190191| `_tag` | Retryable | `next` | What to do |192| --- | --- | --- | --- |193| `NotClaimed` | yes | `__CLI__ claim <ask>` | Claim the ask, then push again. |194| `ClaimLapsed` | yes | `__CLI__ claim <ask>` | Your claim lapsed after a spell without a push: claim the ask again if it is still open. |195| `NotVouched` | no | `__CLI__ status` | Ask a member of the project to vouch for you. |196| `CapReached` | yes | `__CLI__ status` | Release a claim you hold, or land one, before you take another. |197| `AskFull` | yes | `__CLI__ asks` | Someone else holds the claim: pick another ask. |198| `NoAsk` | no | `__CLI__ asks` | Push to the fork your claim gave you, which names its ask. |199| `RepoBusy` | yes | `git push` | Push again. |200| `DirectPush` | no | `__CLI__ asks` | Main moves only by a landing: push your answer to your claim's fork. |201| `AskBlocked` | yes | `__CLI__ asks` | Wait for the asks it names to land, or answer one of them first. |202| `Denounced` | no | `__CLI__ status` | The project's vouch file denounces you: it takes no claims or proposals from you. |203| `OutOfScope` | no | `__CLI__ check` | Undo your changes to the paths it names: they are outside the ask's territory. |204| `TouchedJudge` | no | `__CLI__ check` | Undo your changes to the paths it names: they decide what the checks do. |205| `Weakened` | no | `__CLI__ check` | Take the marker out, or give it a reason for a decider to weigh; never raise a ratchet. |206| `PrivatePathInPublicTree` | no | `__CLI__ check` | Take the held-back paths it names out of your answer. |207| `ReachedInternals` | no | `__CLI__ check` | Import the other module only through its public files. |208| `StaleBase` | yes | `git pull --rebase` | Main moved: rebase onto it, resolve the conflicts it names, and push again. |209| `StaleLayer` | yes | `__CLI__ status` | Nothing: the answer is checked again. |210| `ChecksFailed` | no | the command that reproduces the failure | Run `next` to see the failure, fix it, and push again. |211| `HeldBackFailed` | no | `__CLI__ status` | A held-back check failed; you see only its area and suite. Fix the behaviour and push again. |212| `AttemptsExhausted` | yes | `__CLI__ status` | Wait until `resetsAt`: you used every attempt on that area's held-back checks for now. |213| `Flake` | yes | `__CLI__ status` | Nothing: the check failed and then passed on the same tree, and the platform runs it again. |214| `VerifierBlocked` | yes | `__CLI__ status` | Nothing: the platform could not run the checks, and runs them again. |215216## No fence yet217218Norms that nothing checks yet. Keep them; the gate does not refuse an answer that breaks one.219220- Keep an answer to its ask's want. The gate holds the files you change to the territory, but nothing measures how much you change inside it.221- Name the agent you work through. A landing carries an `Assisted-by:` trailer for the agent your harness's environment names; a harness that names none goes unnamed.
added:packages/agent-kit/test/golden/well-known.txt+20 added
1==> .well-known/agent-skills/index.json <==2{3 "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",4 "skills": [5 {6 "description": "Contribute to calendar.",7 "digest": "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03",8 "name": "calendar-contribute",9 "type": "skill-md",10 "url": "/.well-known/agent-skills/calendar-contribute/SKILL.md"11 },12 {13 "description": "Contribute to datekit.",14 "digest": "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03",15 "name": "datekit-contribute",16 "type": "skill-md",17 "url": "/.well-known/agent-skills/datekit-contribute/SKILL.md"18 }19 ]20}
added:packages/agent-kit/test/agents-block.test.ts+120 added
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Effect } from "effect";45import { agentsBlock, upsertAgentsBlock } from "../src/agents-block.ts";6import {7 landed,8 later,9 policy,10 policyWithNewLint,11 project,12} from "./fixtures.ts";1314const end = `<!-- END ${Brand.slug} contribute -->`;1516const beginWith = (digit: string) =>17 `<!-- BEGIN ${Brand.slug} contribute (generated; content-hash: sha256:${digit.repeat(64)}) -->`;1819const block = {20 begin: beginWith("1"),21 body: "## Contributing\n\nNew text.\n",22 end,23};2425const older = {26 begin: beginWith("0"),27 body: "## Contributing\n\nOld text,\nover two lines.\n",28 end,29};3031/** The block as it sits in a file. */32const written = ({ begin, body }: typeof block) => `${begin}\n${body}${end}`;3334describe(upsertAgentsBlock, () => {35 it("inserts the block at the end of an AGENTS.md without one", () => {36 const existing = "# Project\n\nOur own words.\n";3738 expect(upsertAgentsBlock(existing, block)).toBe(39 `${existing}\n${written(block)}\n`40 );41 });4243 it("starts an empty AGENTS.md with the block alone", () => {44 expect(upsertAgentsBlock("", block)).toBe(`${written(block)}\n`);45 });4647 it("puts a blank line after a last line that has no newline", () => {48 expect(upsertAgentsBlock("# Project", block)).toBe(49 `# Project\n\n${written(block)}\n`50 );51 });5253 it("replaces only the text between the markers, whatever the old hash", () => {54 const before = "# Project\n\nOur own words.\n\n";55 const after = "\n## Ours again\n\nMore of our words.\n";5657 expect(upsertAgentsBlock(`${before}${written(older)}${after}`, block)).toBe(58 `${before}${written(block)}${after}`59 );60 });6162 it("is a no-op when applied twice", () => {63 const appended = upsertAgentsBlock("# Project\n\nOur own words.\n", block);6465 const replaced = upsertAgentsBlock(66 `# Project\n\n${written(older)}\n\nAfter.\n`,67 block68 );6970 expect(upsertAgentsBlock(appended, block)).toBe(appended);71 expect(upsertAgentsBlock(replaced, block)).toBe(replaced);72 });7374 it("leaves another tool's markers alone", () => {75 const existing =76 "# Project\n\n<!-- BEGIN other contribute -->\nTheirs.\n<!-- END other contribute -->\n";7778 expect(upsertAgentsBlock(existing, block)).toBe(79 `${existing}\n${written(block)}\n`80 );81 });82});8384describe(agentsBlock, () => {85 it.effect(86 "brackets its body between markers, the first carrying the body's hash",87 () =>88 Effect.gen(function* () {89 const generated = yield* agentsBlock({ landed, policy, project });9091 expect(generated.begin).toMatch(92 new RegExp(93 `^<!-- BEGIN ${Brand.slug} contribute \\(generated; content-hash: sha256:[0-9a-f]{64}\\) -->$`,94 "u"95 )96 );97 expect(generated.end).toBe(end);98 expect(generated.body).toContain(`${Brand.cli} check`);99 })100 );101102 it.effect(103 "changes its hash when the run block changes, not the landing",104 () =>105 Effect.gen(function* () {106 const first = yield* agentsBlock({ landed, policy, project });107 const again = yield* agentsBlock({ landed: later, policy, project });108109 const changed = yield* agentsBlock({110 landed: later,111 policy: policyWithNewLint,112 project,113 });114115 expect(again).toStrictEqual(first);116 expect(changed.begin).not.toBe(first.begin);117 expect(changed.body).toContain("bunx oxlint --deny-warnings");118 })119 );120});
added:packages/agent-kit/test/command-doc.test.ts+104 added
1import { describe, expect, it } from "@effect/vitest";2import { Contracts } from "@repo/protocol/contracts";3import { Schema } from "effect";45import {6 CommandDoc,7 contractCommandDocs,8 localCommandDocs,9} from "../src/command-doc.ts";1011const contract = contractCommandDocs(Contracts);1213const all = [...contract, ...localCommandDocs];1415const named = (words: string) =>16 all.filter(({ path }) => path.join(" ") === words);1718describe(contractCommandDocs, () => {19 it("makes one row per CLI contract, from its annotations", () => {20 expect(named("claim")).toStrictEqual([21 {22 contract: "claim",23 flags: ["--project", "--json", "--dry-run"],24 needsApproval: false,25 path: ["claim"],26 positional: ["ask"],27 readOnly: false,28 source: "contract",29 summary:30 "Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim.",31 },32 ]);33 });3435 it("splits a nested name into words, and gives a read no --dry-run", () => {36 expect(named("env shape")).toStrictEqual([37 {38 contract: "envShape",39 flags: ["--project", "--json"],40 needsApproval: false,41 path: ["env", "shape"],42 positional: [],43 readOnly: true,44 source: "contract",45 summary:46 "Show a project's env shape: the public schema of its environment variables, and who set each write-only value; never a value.",47 },48 ]);49 });5051 it("gives a contract that needs approval --yes", () => {52 expect(named("vouch")[0]?.flags).toStrictEqual([53 "--handle",54 "--note",55 "--project",56 "--verdict",57 "--json",58 "--yes",59 "--dry-run",60 ]);61 });6263 it("leaves out a stream, which has no command", () => {64 expect(contract.some(({ contract: tag }) => tag === "watch")).toBeFalsy();65 });6667 it("leaves a contract to the local command that stands in for it", () => {68 expect(named("init")).toStrictEqual(69 localCommandDocs.filter(({ path }) => path.join(" ") === "init")70 );71 expect(named("env set")).toHaveLength(1);72 expect(named("env set")[0]?.source).toBe("local");73 });74});7576describe("every command row", () => {77 it("is a CommandDoc", () => {78 expect(all.length).toBeGreaterThan(0);79 expect(all.filter((row) => !Schema.is(CommandDoc)(row))).toStrictEqual([]);80 });8182 it("has a path no other row has", () => {83 const paths = all.map(({ path }) => path.join(" "));8485 expect(paths).toStrictEqual([...new Set(paths)]);86 });8788 it("includes each hand-written command the CLI has", () => {89 expect(90 localCommandDocs.map(({ path }) => path.join(" ")).toSorted()91 ).toStrictEqual([92 "check",93 "credential",94 "env set",95 "hook",96 "init",97 "login",98 "logout",99 "mcp",100 "schema",101 "why",102 ]);103 });104});
added:packages/agent-kit/test/fixtures.ts+217 added
1/**2 * A datekit-shaped project at one landed commit: two ask kinds, three asks,3 * two modules and the run block `{test: "bun test {path}", checks: {lint,4 * types, unit}}`. Decoded with the domain's own schema, so a fixture the5 * domain would refuse throws here.6 */7import { Brand } from "@repo/brand";8import { CheckSpec } from "@repo/protocol/domain/check";9import { Command } from "@repo/protocol/domain/common";10import type { AskKind } from "@repo/protocol/domain/kind";11import { Policy } from "@repo/protocol/domain/policy";12import { LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";13import { Schema } from "effect";1415import type { CommandDoc } from "../src/command-doc.ts";1617export const project = ProjectName.make("datekit");1819export const landed = LandedSha.make("a".repeat(40));2021/** A later landing, for a copy generated before it. */22export const later = LandedSha.make("b".repeat(40));2324const encodeCheck = Schema.encodeSync(CheckSpec);2526const fix: typeof AskKind.Encoded = {27 checkKind: "redThenGreen",28 claimers: "vouched",29 finish: "optional",30 name: "fix",31 oneWay: false,32 race: 1,33 requires: ["want", "check", "territory"],34 strength: "assertion",35};3637const lint: typeof AskKind.Encoded = {38 checkKind: "lintToZero",39 claimers: "anyone",40 finish: "never",41 name: "lint",42 oneWay: false,43 race: 2,44 requires: ["want", "check"],45 strength: "assertion",46};4748const parse = { module: "parse", paths: ["packages/parse/**"] } as const;4950const format = { module: "format", paths: ["packages/format/**"] } as const;5152const askedBy = "alice";5354const openedAt = "2026-10-07T12:00:00.000Z";5556const encoded: typeof Policy.Encoded = {57 agents: "trailer",58 asks: [59 {60 askedBy,61 blockedBy: [],62 brief: { want: "Parsing an ISO week date gives that week's Monday." },63 check: encodeCheck(64 CheckSpec.cases.RedThenGreen.make({65 path: RepoPath.make("packages/parse/test/iso-week.test.ts"),66 })67 ),68 file: `${Brand.configDir}/asks/iso-week.ask.ts`,69 id: "iso-week",70 kind: "fix",71 openedAt,72 openedIn: landed,73 project,74 state: "open",75 territory: parse,76 },77 {78 askedBy,79 blockedBy: [],80 brief: {81 want: "Formatting a day of the month gives its English ordinal.",82 },83 check: encodeCheck(84 CheckSpec.cases.RedThenGreen.make({85 path: RepoPath.make("packages/format/test/ordinal.test.ts"),86 })87 ),88 file: `${Brand.configDir}/asks/ordinals.ask.ts`,89 id: "ordinals",90 kind: "fix",91 openedAt,92 openedIn: landed,93 project,94 state: "claimed",95 territory: format,96 },97 {98 askedBy,99 blockedBy: [],100 brief: { want: "The format module has no explicit any." },101 check: encodeCheck(102 CheckSpec.cases.LintToZero.make({103 command: Command.make("bunx oxlint --format json"),104 rule: "typescript/no-explicit-any",105 territory: "format",106 })107 ),108 file: `${Brand.configDir}/asks/no-any.ask.ts`,109 id: "no-any",110 kind: "lint",111 openedAt,112 openedIn: landed,113 project,114 state: "open",115 territory: format,116 },117 ],118 at: landed,119 budget: { decisionsPerDay: 5, expireDays: 14 },120 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },121 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },122 deciders: [{ handles: [askedBy], paths: "**" }],123 functions: { admit: false, opensAlone: false },124 judge: {125 paths: [`${Brand.configDir}/**`, "bunfig.toml", "tsconfig.json"],126 pointers: ["package.json#/scripts"],127 },128 kinds: [fix, lint],129 modules: [130 { ...parse, publicFiles: ["packages/parse/src/index.ts"] },131 { ...format, publicFiles: ["packages/format/src/index.ts"] },132 ],133 ratchets: [],134 record: { countsAfterDays: 30, windowDays: 365 },135 run: {136 checks: {137 lint: "bun run lint",138 types: "bun run typecheck",139 unit: "bun test",140 },141 test: "bun test {path}",142 },143 source: "config",144 vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },145 vouches: [],146 weakening: { markers: [".skip(", ".only(", "@ts-ignore"] },147};148149export const policy = Schema.decodeSync(Policy)(encoded);150151/** The same project after a landing that changed one lane of its run block. */152export const policyWithNewLint = Schema.decodeSync(Policy)({153 ...encoded,154 run: {155 ...encoded.run,156 checks: { ...encoded.run.checks, lint: "bunx oxlint --deny-warnings" },157 },158});159160/**161 * A few CLI commands as the generators take them: hand-written here, so a162 * contract's wording changing elsewhere leaves these golden files alone.163 */164export const commands: readonly CommandDoc[] = [165 {166 contract: "listAsks",167 flags: ["--project", "--json"],168 needsApproval: false,169 path: ["asks"],170 positional: [],171 readOnly: true,172 source: "contract",173 summary: "List a project's open asks.",174 },175 {176 contract: "claim",177 flags: ["--project", "--json", "--dry-run"],178 needsApproval: false,179 path: ["claim"],180 positional: ["ask"],181 readOnly: false,182 source: "contract",183 summary:184 "Claim an ask: an exclusive, expiring right to answer it, with a fork to push to; claiming it again returns the same claim.",185 },186 {187 contract: "vouch",188 flags: [189 "--project",190 "--handle",191 "--verdict",192 "--note",193 "--json",194 "--yes",195 "--dry-run",196 ],197 needsApproval: true,198 path: ["vouch"],199 positional: [],200 readOnly: false,201 source: "contract",202 summary:203 "Vouch for a person, or denounce them, by landing a line in the project's vouch file.",204 },205 {206 flags: ["--ask", "--project", "--base", "--json"],207 needsApproval: false,208 path: ["check"],209 positional: [],210 readOnly: true,211 source: "local",212 summary: "Run the gate's checks on your answer locally, before you push.",213 },214];215216/** Where the platform serves its routes in these tests. */217export const platformUrl = `https://${Brand.domain}`;
added:packages/agent-kit/test/generate.test.ts+392 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Effect, Schema } from "effect";56import { agentsBlock, upsertAgentsBlock } from "../src/agents-block.ts";7import type { GeneratedFile } from "../src/generated-file.ts";8import type { HookEvent } from "../src/hook-events.ts";9import { claudeEventOf } from "../src/hook-events.ts";10import {11 agentPluginsBundle,12 claudePlugin,13 platformSkill,14} from "../src/platform.ts";15import { projectSkill } from "../src/project-skill.ts";16import { wellKnownSkills } from "../src/well-known.ts";17import { commands, landed, platformUrl, policy, project } from "./fixtures.ts";18import { expectGolden, transcript } from "./golden.ts";1920const plugin = `plugins/${Brand.slug}`;2122const skill = `${project}-contribute`;2324/** `sha256("hello\n")`, as every tool that hashes prints it. */25const helloDigest =26 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";2728interface Case {29 /** Its golden file: `test/golden/<golden>.txt`. */30 readonly golden: string;31 readonly what: string;32 readonly paths: readonly string[];33 readonly run: Effect.Effect<readonly GeneratedFile[]>;34}3536const cases: readonly Case[] = [37 {38 golden: "project-skill",39 paths: [40 `.agents/skills/${skill}/SKILL.md`,41 `.claude/skills/${skill}/SKILL.md`,42 ],43 run: projectSkill({ landed, policy, project }),44 what: "the contribute skill, in both skill folders",45 },46 {47 golden: "agents-block",48 paths: ["AGENTS.md"],49 run: agentsBlock({ landed, policy, project }).pipe(50 Effect.map((block) => [51 { content: upsertAgentsBlock("", block), path: "AGENTS.md" },52 ])53 ),54 what: "the AGENTS.md block, alone in a new AGENTS.md",55 },56 {57 golden: "platform-skill",58 paths: [`skills/${Brand.slug}/SKILL.md`],59 run: platformSkill({ commands, platformUrl }),60 what: "the platform's own skill",61 },62 {63 golden: "claude-plugin",64 paths: [65 `${plugin}/.claude-plugin/plugin.json`,66 `${plugin}/skills/${Brand.slug}/SKILL.md`,67 `${plugin}/.mcp.json`,68 `${plugin}/hooks/hooks.json`,69 ],70 run: claudePlugin({ commands, platformUrl }),71 what: "the Claude Code plugin, reaching the platform's MCP over HTTP",72 },73 {74 golden: "claude-plugin-stdio",75 paths: [76 `${plugin}/.claude-plugin/plugin.json`,77 `${plugin}/skills/${Brand.slug}/SKILL.md`,78 `${plugin}/.mcp.json`,79 `${plugin}/hooks/hooks.json`,80 ],81 run: claudePlugin({ commands }),82 what: "the Claude Code plugin, reaching MCP through the CLI without a URL",83 },84 {85 golden: "agent-plugins",86 paths: [87 `${plugin}/plugin.json`,88 `${plugin}/skills/${Brand.slug}/SKILL.md`,89 `${plugin}/mcp.json`,90 ],91 run: agentPluginsBundle({ commands, platformUrl }),92 what: "the Agent Plugins bundle, reaching the platform's MCP over HTTP",93 },94 {95 golden: "agent-plugins-stdio",96 paths: [97 `${plugin}/plugin.json`,98 `${plugin}/skills/${Brand.slug}/SKILL.md`,99 `${plugin}/mcp.json`,100 ],101 run: agentPluginsBundle({ commands }),102 what: "the Agent Plugins bundle, reaching MCP through the CLI without a URL",103 },104 {105 golden: "well-known",106 paths: [".well-known/agent-skills/index.json"],107 run: wellKnownSkills([108 {109 content: "hello\n",110 description: "Contribute to datekit.",111 name: skill,112 url: `/.well-known/agent-skills/${skill}/SKILL.md`,113 },114 {115 content: "hello\n",116 description: "Contribute to calendar.",117 name: "calendar-contribute",118 url: "/.well-known/agent-skills/calendar-contribute/SKILL.md",119 },120 ]).pipe(Effect.map((file) => [file])),121 what: "the well-known skills index",122 },123];124125const byPath = (files: readonly GeneratedFile[], path: string) =>126 files.find((file) => file.path === path)?.content ?? "";127128const JsonObject = Schema.fromJsonString(129 Schema.Record(Schema.String, Schema.Json)130);131132const parsed = Schema.decodeSync(JsonObject);133134const eventsOf = Schema.decodeUnknownSync(135 Schema.Struct({ hooks: Schema.Record(Schema.String, Schema.Unknown) })136);137138/** A SKILL.md's frontmatter keys: top level, and under `metadata`. */139const frontmatterKeys = (content: string) => {140 const [, head = ""] = content.split("---\n");141 const lines = head.split("\n");142143 return {144 metadata: lines.flatMap(145 (line) => /^ {2}(?<key>[a-z-]+):/u.exec(line)?.groups?.key ?? []146 ),147 top: lines.flatMap(148 (line) => /^(?<key>[a-z-]+):/u.exec(line)?.groups?.key ?? []149 ),150 };151};152153/** The hook entry that runs `<cli> hook <event> --json`. */154const hookCommand = (event: HookEvent) => [155 { command: `${Brand.cli} hook ${event} --json`, type: "command" },156];157158describe("each generator", () => {159 for (const { golden, paths, run, what } of cases) {160 it.effect(`makes ${what}, as its golden file holds it`, () =>161 Effect.gen(function* () {162 const files = yield* run;163164 expect(files.map(({ path }) => path)).toStrictEqual(paths);165166 yield* expectGolden(golden, transcript(files));167 }).pipe(Effect.provide(NodeServices.layer))168 );169170 it.effect(`makes ${what} the same way twice`, () =>171 Effect.gen(function* () {172 const first = yield* run;173 const second = yield* run;174175 expect(first.length).toBeGreaterThan(0);176 expect(second).toStrictEqual(first);177 })178 );179 }180});181182describe("the contribute skill", () => {183 it.effect("is the same file in .agents and in .claude", () =>184 Effect.gen(function* () {185 const [agents, claude] = yield* projectSkill({186 landed,187 policy,188 project,189 });190191 expect(agents?.content).toBeDefined();192 expect(claude?.content).toBe(agents?.content);193 })194 );195});196197describe("every SKILL.md", () => {198 const skills = Effect.all([199 projectSkill({ landed, policy, project }),200 platformSkill({ commands }),201 claudePlugin({ commands }),202 agentPluginsBundle({ commands }),203 ]).pipe(204 Effect.map((all) =>205 all.flat().filter(({ path }) => path.endsWith("/SKILL.md"))206 )207 );208209 it.effect(210 "keeps to the Agent Skills spec's six fields, with who manages it and its hash under metadata",211 () =>212 Effect.gen(function* () {213 const files = yield* skills;214215 expect(files.length).toBeGreaterThan(0);216217 expect(218 files.map(({ content, path }) => {219 const { metadata, top } = frontmatterKeys(content);220221 return {222 managed: ["managed-by", "content-hash"].every((key) =>223 metadata.includes(key)224 ),225 path,226 top,227 };228 })229 ).toStrictEqual(230 files.map(({ path }) => ({231 managed: true,232 path,233 top: ["name", "description", "metadata"],234 }))235 );236 })237 );238239 it.effect("names the landing it came from when it came from one", () =>240 Effect.gen(function* () {241 const [contribute] = yield* projectSkill({ landed, policy, project });242 const [own] = yield* platformSkill({ commands });243244 expect(frontmatterKeys(contribute?.content ?? "").metadata).toStrictEqual(245 ["managed-by", "landed", "content-hash"]246 );247 expect(frontmatterKeys(own?.content ?? "").metadata).toStrictEqual([248 "managed-by",249 "content-hash",250 ]);251 })252 );253});254255describe("the Claude Code plugin's hooks", () => {256 it.effect(257 "send PreToolUse on edits, Stop and SessionStart to the CLI's hook command",258 () =>259 Effect.gen(function* () {260 const files = yield* claudePlugin({ commands });261262 expect(files.map(({ path }) => path)).toContain(263 `${plugin}/hooks/hooks.json`264 );265266 const hooks = parsed(byPath(files, `${plugin}/hooks/hooks.json`));267268 expect(hooks).toStrictEqual({269 hooks: {270 [claudeEventOf["pre-tool-use"]]: [271 {272 hooks: hookCommand("pre-tool-use"),273 matcher: "Edit|Write|MultiEdit|NotebookEdit",274 },275 ],276 [claudeEventOf["session-start"]]: [277 { hooks: hookCommand("session-start") },278 ],279 [claudeEventOf.stop]: [{ hooks: hookCommand("stop") }],280 },281 });282 expect(Object.keys(eventsOf(hooks).hooks).toSorted()).toStrictEqual([283 "PreToolUse",284 "SessionStart",285 "Stop",286 ]);287 })288 );289});290291describe("the MCP entries", () => {292 it.effect("reach the platform's /mcp when given a URL", () =>293 Effect.gen(function* () {294 const claude = yield* claudePlugin({ commands, platformUrl });295 const portable = yield* agentPluginsBundle({ commands, platformUrl });296297 expect([...claude, ...portable].map(({ path }) => path)).toStrictEqual(298 expect.arrayContaining([`${plugin}/.mcp.json`, `${plugin}/mcp.json`])299 );300301 expect(parsed(byPath(claude, `${plugin}/.mcp.json`))).toStrictEqual({302 mcpServers: {303 [Brand.slug]: { type: "http", url: `${platformUrl}/mcp` },304 },305 });306 expect(parsed(byPath(portable, `${plugin}/mcp.json`))).toStrictEqual({307 $schema: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",308 mcpServers: {309 [Brand.slug]: { type: "streamable-http", url: `${platformUrl}/mcp` },310 },311 });312 })313 );314315 it.effect("run the CLI's mcp command without one", () =>316 Effect.gen(function* () {317 const claude = yield* claudePlugin({ commands });318 const portable = yield* agentPluginsBundle({ commands });319320 expect([...claude, ...portable].map(({ path }) => path)).toStrictEqual(321 expect.arrayContaining([`${plugin}/.mcp.json`, `${plugin}/mcp.json`])322 );323324 expect(parsed(byPath(claude, `${plugin}/.mcp.json`))).toStrictEqual({325 mcpServers: { [Brand.slug]: { args: ["mcp"], command: Brand.cli } },326 });327 expect(parsed(byPath(portable, `${plugin}/mcp.json`))).toStrictEqual({328 $schema: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",329 mcpServers: {330 [Brand.slug]: { args: ["mcp"], command: Brand.cli, type: "stdio" },331 },332 });333 })334 );335});336337describe("the well-known skills index", () => {338 it.effect(339 "lists each skill by name with the SHA-256 digest of its file",340 () =>341 Effect.gen(function* () {342 const index = yield* wellKnownSkills([343 {344 content: "hello\n",345 description: "Say hello.",346 name: "hello",347 url: "/.well-known/agent-skills/hello/SKILL.md",348 },349 ]);350351 expect(index.path).toBe(".well-known/agent-skills/index.json");352 expect(parsed(index.content)).toStrictEqual({353 $schema: "https://schemas.agentskills.io/discovery/0.2.0/schema.json",354 skills: [355 {356 description: "Say hello.",357 digest: helloDigest,358 name: "hello",359 type: "skill-md",360 url: "/.well-known/agent-skills/hello/SKILL.md",361 },362 ],363 });364 })365 );366367 it.effect("cuts a description to the 1024 characters the index allows", () =>368 Effect.gen(function* () {369 const index = yield* wellKnownSkills([370 {371 content: "hello\n",372 description: "a".repeat(2000),373 name: "hello",374 url: "/.well-known/agent-skills/hello/SKILL.md",375 },376 ]);377378 expect(index.path).toBe(".well-known/agent-skills/index.json");379380 const { skills } = yield* Schema.decodeUnknownEffect(381 Schema.Struct({382 skills: Schema.Array(Schema.Struct({ description: Schema.String })),383 })384 )(parsed(index.content));385386 const [entry] = skills;387388 expect(entry?.description).toHaveLength(1024);389 expect(entry?.description.endsWith("a…")).toBeTruthy();390 })391 );392});
added:packages/agent-kit/test/golden.ts+75 added
1/**2 * Golden files for the generators: each generator's files in one3 * `test/golden/<name>.txt`, with the product's name as placeholders so no4 * golden file spells it (`brand:check`) and a renamed brand still matches.5 * `UPDATE_GOLDEN=1` rewrites them; read the diff before committing it.6 */7import { expect } from "@effect/vitest";8import { Brand } from "@repo/brand";9import { Config, Effect, FileSystem } from "effect";1011import type { GeneratedFile } from "../src/generated-file.ts";1213const DIR = "test/golden";1415const escaped = (text: string) =>16 text.replaceAll(/[$()*+.?[\\\]^{|}]/gu, String.raw`\$&`);1718// Letters on either side make it another word, not the name.19const NAME = new RegExp(`(?<![A-Za-z])${escaped(Brand.name)}(?![a-z])`, "gu");2021// The CLI where a command starts: in a code span or a JSON string, before a22// subcommand.23const CLI = new RegExp(`(?<=^|[\`"])${escaped(Brand.cli)}(?= [a-z])`, "gmu");2425const SLUG = new RegExp(`(?<![A-Za-z])${escaped(Brand.slug)}(?![a-z])`, "gu");2627/** A golden file's text with its placeholders filled in from `Brand`. */28export const branded = (golden: string) =>29 golden30 .replaceAll("__NAME__", Brand.name)31 .replaceAll("__CLI__", Brand.cli)32 .replaceAll("__SLUG__", Brand.slug);3334/** Generated text as a golden file holds it: the brand as placeholders. */35const unbranded = (text: string) =>36 text37 .replaceAll(NAME, "__NAME__")38 .replaceAll(CLI, "__CLI__")39 .replaceAll(SLUG, "__SLUG__");4041/** Several files as one text: each under a `==> <path> <==` line. */42export const transcript = (files: readonly GeneratedFile[]) =>43 files.map(({ content, path }) => `==> ${path} <==\n${content}`).join("\n");4445/**46 * Asserts that `actual` is `test/golden/<name>.txt` with its placeholders47 * filled in, byte for byte. Under `UPDATE_GOLDEN=1` it writes the file.48 */49export const expectGolden = (name: string, actual: string) =>50 Effect.gen(function* () {51 const fs = yield* FileSystem.FileSystem;52 const file = `${DIR}/${name}.txt`;5354 const update = yield* Config.Boolean("UPDATE_GOLDEN").pipe(55 Config.withDefault(false)56 );5758 if (update) {59 yield* fs.makeDirectory(DIR, { recursive: true });60 yield* fs.writeFileString(file, unbranded(actual));6162 return;63 }6465 const exists = yield* fs.exists(file);6667 expect(68 exists,69 `no golden file ${file} yet: run this package's tests with UPDATE_GOLDEN=1, then read it`70 ).toBe(true);7172 const golden = yield* fs.readFileString(file);7374 expect(actual).toBe(branded(golden));75 }).pipe(Effect.orDie);
added:packages/agent-kit/test/stale.test.ts+195 added
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Effect, Option } from "effect";45import { frontmatter, isStale, readManaged } from "../src/generated-file.ts";6import { projectSkill } from "../src/project-skill.ts";7import {8 landed,9 later,10 policy,11 policyWithNewLint,12 project,13} from "./fixtures.ts";1415/** `sha256("hello\n")`, as every tool that hashes prints it. */16const helloDigest =17 "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";1819/** The hash a file's frontmatter records, read with a pattern of its own. */20const recordedHash = (file: string) =>21 /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(file)?.groups22 ?.hash ?? "";2324const contributeSkill = (input: {25 readonly policy: typeof policy;26 readonly landed: typeof landed;27}) =>28 projectSkill({ ...input, project }).pipe(29 Effect.map((files) => files[0] ?? { content: "", path: "" })30 );3132describe(frontmatter, () => {33 it.effect(34 "says who manages the file, the landing it came from and its body's SHA-256",35 () =>36 Effect.gen(function* () {37 const file = yield* frontmatter({38 body: "hello\n",39 description: "Say hello: politely.",40 landed: Option.some(landed),41 name: "hello",42 });4344 expect(file).toBe(45 [46 "---",47 "name: hello",48 'description: "Say hello: politely."',49 "metadata:",50 ` managed-by: "${Brand.slug}"`,51 ` landed: "${landed}"`,52 ` content-hash: "${helloDigest}"`,53 "---",54 "hello",55 "",56 ].join("\n")57 );58 })59 );6061 it.effect("leaves the landing out when the file came from none", () =>62 Effect.gen(function* () {63 const file = yield* frontmatter({64 body: "hello\n",65 description: "Say hello.",66 landed: Option.none(),67 name: "hello",68 });6970 expect(file).not.toContain("landed:");71 expect(recordedHash(file)).toBe(helloDigest);72 })73 );74});7576describe(readManaged, () => {77 it.effect("reads back the landing, the hash and the body", () =>78 Effect.gen(function* () {79 const file = yield* frontmatter({80 body: "hello\n",81 description: "Say hello.",82 landed: Option.some(landed),83 name: "hello",84 });8586 expect(readManaged(file)).toStrictEqual(87 Option.some({88 body: "hello\n",89 hash: helloDigest,90 landed: Option.some(landed),91 })92 );93 })94 );9596 it("is None for a file without the frontmatter", () => {97 expect(readManaged("# Contribute\n\nBy hand.\n")).toStrictEqual(98 Option.none()99 );100 });101102 it("is None for a file someone else manages", () => {103 const file = [104 "---",105 "name: hello",106 'description: "Say hello."',107 "metadata:",108 ' managed-by: "someone-else"',109 ` content-hash: "${helloDigest}"`,110 "---",111 "hello",112 "",113 ].join("\n");114115 expect(readManaged(file)).toStrictEqual(Option.none());116 });117});118119describe(isStale, () => {120 it.effect("is None for a fresh copy", () =>121 Effect.gen(function* () {122 const current = yield* contributeSkill({ landed, policy });123124 expect(yield* isStale(current.content, current)).toStrictEqual(125 Option.none()126 );127 })128 );129130 it.effect(131 "is None for a copy from an earlier landing that left the policy's text alone",132 () =>133 Effect.gen(function* () {134 const onDisk = yield* contributeSkill({ landed, policy });135 const current = yield* contributeSkill({ landed: later, policy });136137 expect(onDisk.content).not.toBe(current.content);138 expect(yield* isStale(onDisk.content, current)).toStrictEqual(139 Option.none()140 );141 })142 );143144 it.effect(145 "names the copy's landing and hash when the run block changed since",146 () =>147 Effect.gen(function* () {148 const onDisk = yield* contributeSkill({ landed, policy });149150 const current = yield* contributeSkill({151 landed: later,152 policy: policyWithNewLint,153 });154155 expect(recordedHash(onDisk.content)).not.toBe(156 recordedHash(current.content)157 );158 expect(yield* isStale(onDisk.content, current)).toStrictEqual(159 Option.some({160 hash: recordedHash(onDisk.content),161 landed: Option.some(landed),162 })163 );164 })165 );166167 it.effect(168 "names the copy's landing and hash when its body was edited by hand",169 () =>170 Effect.gen(function* () {171 const current = yield* contributeSkill({ landed, policy });172 const edited = current.content.replace("bun test {path}", "npm test");173174 expect(edited).not.toBe(current.content);175 expect(yield* isStale(edited, current)).toStrictEqual(176 Option.some({177 hash: recordedHash(current.content),178 landed: Option.some(landed),179 })180 );181 })182 );183184 it.effect(185 "is Some, with no landing and the file's own hash, for a copy without the frontmatter",186 () =>187 Effect.gen(function* () {188 const current = yield* contributeSkill({ landed, policy });189190 expect(yield* isStale("hello\n", current)).toStrictEqual(191 Option.some({ hash: helloDigest, landed: Option.none() })192 );193 })194 );195});
modified:packages/agent-kit/package.json+2 added
15 unmodified lines
16 "@repo/protocol": "workspace:*",17 "effect": "catalog:"18 },19 "devDependencies": {20 "@cloudflare/workers-types": "5.20261006.1",21 "@effect/platform-node": "4.0.1",22 "@effect/vitest": "catalog:",23 "@repo/config": "workspace:*",24 "typescript": "catalog:",25 "vitest": "catalog:"
2 unmodified lines
modified:packages/agent-kit/tsconfig.json+2 added-1 removed
1{2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "allowImportingTsExtensions": true4 "allowImportingTsExtensions": true,5 "types": ["@cloudflare/workers-types"]6 },7 "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]8}
modified:bun.lock+2 added
108 unmodified lines
109 "@repo/protocol": "workspace:*",110 "effect": "catalog:",111 },112 "devDependencies": {113 "@cloudflare/workers-types": "5.20261006.1",114 "@effect/platform-node": "4.0.1",115 "@effect/vitest": "catalog:",116 "@repo/config": "workspace:*",117 "typescript": "catalog:",118 "vitest": "catalog:",
1412 unmodified lines