Skip to content
Myr

generate.test.ts

This file

Path

packages/agent-kit/test/generate.test.ts

449 lines · 13.3 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { keyOf } from "@repo/protocol/ids";5import { Effect, Option, Schema } from "effect";67import { agentsBlock, upsertAgentsBlock } from "../src/agents-block.ts";8import {9  contentHash,10  describedIn,11  readManaged,12} from "../src/generated-file.ts";13import type { GeneratedFile } from "../src/generated-file.ts";14import type { HookEvent } from "../src/hook-events.ts";15import { claudeEventOf } from "../src/hook-events.ts";16import {17  agentPluginsBundle,18  claudePlugin,19  platformSkill,20  platformSkillParts,21} from "../src/platform.ts";22import { projectSkill } from "../src/project-skill.ts";23import { wellKnownSkills } from "../src/well-known.ts";24import { commands, landed, platformUrl, policy, project } from "./fixtures.ts";25import { expectGolden, transcript } from "./golden.ts";2627const plugin = `plugins/${Brand.slug}`;2829const frontmatterName = (content: string) =>30  Option.fromNullishOr(/^name: (?<name>.+)$/mu.exec(content)?.groups?.name);3132const skill = `${keyOf(project)}-contribute`;3334const helloDigest =35  "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03";3637interface Case {38  readonly golden: string;39  readonly what: string;40  readonly paths: readonly string[];41  readonly run: Effect.Effect<readonly GeneratedFile[]>;42}4344const cases: readonly Case[] = [45  {46    golden: "project-skill",47    paths: [48      `.agents/skills/${skill}/SKILL.md`,49      `.claude/skills/${skill}/SKILL.md`,50    ],51    run: projectSkill({ landed, policy, project }),52    what: "the contribute skill, in both skill folders",53  },54  {55    golden: "agents-block",56    paths: ["AGENTS.md"],57    run: agentsBlock({ landed, policy, project }).pipe(58      Effect.map((block) => [59        { content: upsertAgentsBlock("", block), path: "AGENTS.md" },60      ])61    ),62    what: "the AGENTS.md block, alone in a new AGENTS.md",63  },64  {65    golden: "platform-skill",66    paths: [`skills/${Brand.slug}/SKILL.md`],67    run: platformSkill({ commands, platformUrl }),68    what: "the platform's own skill",69  },70  {71    golden: "claude-plugin",72    paths: [73      `${plugin}/.claude-plugin/plugin.json`,74      `${plugin}/skills/${Brand.slug}/SKILL.md`,75      `${plugin}/.mcp.json`,76      `${plugin}/hooks/hooks.json`,77    ],78    run: claudePlugin({ commands, platformUrl }),79    what: "the Claude Code plugin, reaching the platform's MCP over HTTP",80  },81  {82    golden: "claude-plugin-stdio",83    paths: [84      `${plugin}/.claude-plugin/plugin.json`,85      `${plugin}/skills/${Brand.slug}/SKILL.md`,86      `${plugin}/.mcp.json`,87      `${plugin}/hooks/hooks.json`,88    ],89    run: claudePlugin({ commands }),90    what: "the Claude Code plugin, reaching MCP through the CLI without a URL",91  },92  {93    golden: "agent-plugins",94    paths: [95      `${plugin}/plugin.json`,96      `${plugin}/skills/${Brand.slug}/SKILL.md`,97      `${plugin}/mcp.json`,98    ],99    run: agentPluginsBundle({ commands, platformUrl }),100    what: "the Agent Plugins bundle, reaching the platform's MCP over HTTP",101  },102  {103    golden: "agent-plugins-stdio",104    paths: [105      `${plugin}/plugin.json`,106      `${plugin}/skills/${Brand.slug}/SKILL.md`,107      `${plugin}/mcp.json`,108    ],109    run: agentPluginsBundle({ commands }),110    what: "the Agent Plugins bundle, reaching MCP through the CLI without a URL",111  },112  {113    golden: "well-known",114    paths: [".well-known/agent-skills/index.json"],115    run: wellKnownSkills([116      {117        content: "hello\n",118        description: "Contribute to datekit.",119        name: skill,120        url: `/.well-known/agent-skills/${skill}/SKILL.md`,121      },122      {123        content: "hello\n",124        description: "Contribute to calendar.",125        name: "calendar-contribute",126        url: "/.well-known/agent-skills/calendar-contribute/SKILL.md",127      },128    ]).pipe(Effect.map((file) => [file])),129    what: "the well-known skills index",130  },131];132133const byPath = (files: readonly GeneratedFile[], path: string) =>134  files.find((file) => file.path === path)?.content ?? "";135136const JsonObject = Schema.fromJsonString(137  Schema.Record(Schema.String, Schema.Json)138);139140const parsed = Schema.decodeSync(JsonObject);141142const eventsOf = Schema.decodeUnknownSync(143  Schema.Struct({ hooks: Schema.Record(Schema.String, Schema.Unknown) })144);145146const frontmatterKeys = (content: string) => {147  const [, head = ""] = content.split("---\n");148  const lines = head.split("\n");149150  return {151    metadata: lines.flatMap(152      (line) => /^ {2}(?<key>[a-z-]+):/u.exec(line)?.groups?.key ?? []153    ),154    top: lines.flatMap(155      (line) => /^(?<key>[a-z-]+):/u.exec(line)?.groups?.key ?? []156    ),157  };158};159160const bodyOf = (content: string) => {161  const close = content.indexOf("\n---\n", 3);162163  return close === -1 ? content : content.slice(close + "\n---\n".length);164};165166const recordedHash = (content: string) =>167  /^ {2}content-hash: "(?<hash>sha256:[0-9a-f]{64})"$/mu.exec(content)?.groups168    ?.hash ?? "";169170const hookCommand = (event: HookEvent) => [171  { command: `${Brand.cli} hook ${event} --json`, type: "command" },172];173174describe("each generator", () => {175  for (const { golden, paths, run, what } of cases) {176    it.effect(`makes ${what}, as its golden file holds it`, () =>177      Effect.gen(function* () {178        const files = yield* run;179180        expect(files.map(({ path }) => path)).toStrictEqual(paths);181182        yield* expectGolden(golden, transcript(files));183      }).pipe(Effect.provide(NodeServices.layer))184    );185186    it.effect(`makes ${what} the same way twice`, () =>187      Effect.gen(function* () {188        const first = yield* run;189        const second = yield* run;190191        expect(first.length).toBeGreaterThan(0);192        expect(second).toStrictEqual(first);193      })194    );195  }196});197198describe("the contribute skill", () => {199  it.effect("is the same file in .agents and in .claude", () =>200    Effect.gen(function* () {201      const [agents, claude] = yield* projectSkill({202        landed,203        policy,204        project,205      });206207      expect(agents?.content).toBeDefined();208      expect(claude?.content).toBe(agents?.content);209    })210  );211});212213describe("every SKILL.md", () => {214  const skills = Effect.all([215    projectSkill({ landed, policy, project }),216    platformSkill({ commands }),217    claudePlugin({ commands }),218    agentPluginsBundle({ commands }),219  ]).pipe(220    Effect.map((all) =>221      all.flat().filter(({ path }) => path.endsWith("/SKILL.md"))222    )223  );224225  it.effect(226    "keeps to the Agent Skills spec's six fields, with who manages it and its hash under metadata",227    () =>228      Effect.gen(function* () {229        const files = yield* skills;230231        expect(files.length).toBeGreaterThan(0);232233        expect(234          files.map(({ content, path }) => {235            const { metadata, top } = frontmatterKeys(content);236237            return {238              managed: ["managed-by", "content-hash"].every((key) =>239                metadata.includes(key)240              ),241              path,242              top,243            };244          })245        ).toStrictEqual(246          files.map(({ path }) => ({247            managed: true,248            path,249            top: ["name", "description", "metadata"],250          }))251        );252      })253  );254255  it.effect("records the SHA-256 of its own body", () =>256    Effect.gen(function* () {257      const files = yield* skills;258259      expect(files.length).toBeGreaterThan(0);260261      const computed = yield* Effect.forEach(files, ({ content, path }) =>262        contentHash(bodyOf(content)).pipe(263          Effect.map((hash) => ({ hash, path }))264        )265      );266267      expect(268        files.map(({ content, path }) => ({269          hash: recordedHash(content),270          path,271        }))272      ).toStrictEqual(computed);273    })274  );275276  it.effect("names the landing it came from when it came from one", () =>277    Effect.gen(function* () {278      const [contribute] = yield* projectSkill({ landed, policy, project });279      const [own] = yield* platformSkill({ commands });280281      expect(frontmatterKeys(contribute?.content ?? "").metadata).toStrictEqual(282        ["managed-by", "landed", "content-hash"]283      );284      expect(frontmatterKeys(own?.content ?? "").metadata).toStrictEqual([285        "managed-by",286        "content-hash",287      ]);288    })289  );290});291292describe("the platform's skill as the prompt contribute serves it", () => {293  it.effect("has the name, description and body its SKILL.md gives", () =>294    Effect.gen(function* () {295      const [own] = yield* platformSkill({ commands, platformUrl });296      const content = own?.content ?? "";297      const parts = platformSkillParts({ commands, platformUrl });298299      expect({300        body: Option.map(readManaged(content), ({ body }) => body),301        description: describedIn(content),302        name: frontmatterName(content),303      }).toStrictEqual({304        body: Option.some(parts.body),305        description: Option.some(parts.description),306        name: Option.some(parts.name),307      });308    })309  );310});311312describe("the Claude Code plugin's hooks", () => {313  it.effect(314    "send PreToolUse on edits, Stop and SessionStart to the CLI's hook command",315    () =>316      Effect.gen(function* () {317        const files = yield* claudePlugin({ commands });318319        expect(files.map(({ path }) => path)).toContain(320          `${plugin}/hooks/hooks.json`321        );322323        const hooks = parsed(byPath(files, `${plugin}/hooks/hooks.json`));324325        expect(hooks).toStrictEqual({326          hooks: {327            [claudeEventOf["pre-tool-use"]]: [328              {329                hooks: hookCommand("pre-tool-use"),330                matcher: "Edit|Write|MultiEdit|NotebookEdit",331              },332            ],333            [claudeEventOf["session-start"]]: [334              { hooks: hookCommand("session-start") },335            ],336            [claudeEventOf.stop]: [{ hooks: hookCommand("stop") }],337          },338        });339        expect(Object.keys(eventsOf(hooks).hooks).toSorted()).toStrictEqual([340          "PreToolUse",341          "SessionStart",342          "Stop",343        ]);344      })345  );346});347348describe("the MCP entries", () => {349  it.effect("reach the platform's /mcp when given a URL", () =>350    Effect.gen(function* () {351      const claude = yield* claudePlugin({ commands, platformUrl });352      const portable = yield* agentPluginsBundle({ commands, platformUrl });353354      expect([...claude, ...portable].map(({ path }) => path)).toStrictEqual(355        expect.arrayContaining([`${plugin}/.mcp.json`, `${plugin}/mcp.json`])356      );357358      expect(parsed(byPath(claude, `${plugin}/.mcp.json`))).toStrictEqual({359        mcpServers: {360          [Brand.slug]: { type: "http", url: `${platformUrl}/mcp` },361        },362      });363      expect(parsed(byPath(portable, `${plugin}/mcp.json`))).toStrictEqual({364        $schema: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",365        mcpServers: {366          [Brand.slug]: { type: "streamable-http", url: `${platformUrl}/mcp` },367        },368      });369    })370  );371372  it.effect("run the CLI's mcp command without one", () =>373    Effect.gen(function* () {374      const claude = yield* claudePlugin({ commands });375      const portable = yield* agentPluginsBundle({ commands });376377      expect([...claude, ...portable].map(({ path }) => path)).toStrictEqual(378        expect.arrayContaining([`${plugin}/.mcp.json`, `${plugin}/mcp.json`])379      );380381      expect(parsed(byPath(claude, `${plugin}/.mcp.json`))).toStrictEqual({382        mcpServers: { [Brand.slug]: { args: ["mcp"], command: Brand.cli } },383      });384      expect(parsed(byPath(portable, `${plugin}/mcp.json`))).toStrictEqual({385        $schema: "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",386        mcpServers: {387          [Brand.slug]: { args: ["mcp"], command: Brand.cli, type: "stdio" },388        },389      });390    })391  );392});393394describe("the well-known skills index", () => {395  it.effect(396    "lists each skill by name with the SHA-256 digest of its file",397    () =>398      Effect.gen(function* () {399        const index = yield* wellKnownSkills([400          {401            content: "hello\n",402            description: "Say hello.",403            name: "hello",404            url: "/.well-known/agent-skills/hello/SKILL.md",405          },406        ]);407408        expect(index.path).toBe(".well-known/agent-skills/index.json");409        expect(parsed(index.content)).toStrictEqual({410          $schema: "https://schemas.agentskills.io/discovery/0.2.0/schema.json",411          skills: [412            {413              description: "Say hello.",414              digest: helloDigest,415              name: "hello",416              type: "skill-md",417              url: "/.well-known/agent-skills/hello/SKILL.md",418            },419          ],420        });421      })422  );423424  it.effect("cuts a description to the 1024 characters the index allows", () =>425    Effect.gen(function* () {426      const index = yield* wellKnownSkills([427        {428          content: "hello\n",429          description: "a".repeat(2000),430          name: "hello",431          url: "/.well-known/agent-skills/hello/SKILL.md",432        },433      ]);434435      expect(index.path).toBe(".well-known/agent-skills/index.json");436437      const { skills } = yield* Schema.decodeUnknownEffect(438        Schema.Struct({439          skills: Schema.Array(Schema.Struct({ description: Schema.String })),440        })441      )(parsed(index.content));442443      const [entry] = skills;444445      expect(entry?.description).toHaveLength(1024);446      expect(entry?.description.endsWith("a…")).toBeTruthy();447    })448  );449});