diff --git a/changes/fix-api-entity-groups.md b/changes/fix-api-entity-groups.md new file mode 100644 index 0000000..858d838 --- /dev/null +++ b/changes/fix-api-entity-groups.md @@ -0,0 +1,10 @@ +### Changed — experimental + +- **A GraphQL CLI's agent skill has one API page per entity, not one for queries and one for mutations.** + `adaptGraphql` now gives each operation two tags. The first is the entity its field name acts on + (`issueLabelCreate` → `issue-label`, `searchIssues` → `issue`), or `query` / `mutation` for a name with no entity in + it. The second is `query` or `mutation`, as before. `apiSkillFiles` files a page per first tag, so an agent that + wants to archive an issue reads ` skill show api-issue` instead of Linear's 4,335-line `api-mutation` page. + Regenerating rewrites `references/api/`, and `api show` prints both tags. Commands, their names and permission keys + stay the same. `api list tag:mutation` still works, and `tag:issue` now works too. A CLI that groups its `api` + commands by tag (`names.groups: "tags"`) would mount them by entity; no GraphQL CLI does today. diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 3ce4364..a588e29 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -265,9 +265,12 @@ and `pageInfo`. `graphqlDocument(binding, selection?)` builds the one document a declared and passed; a caller that needs more (`state { type }`) passes its own selection. Each argument is a body flag, the variables are the request body, and the answer is `data.`, typed by the field's type; the fields of an answer type are all optional, since a selection asks for some. A query reads; a mutation writes; one whose name ends in -`Delete` or `Archive` (not `Unarchive`) deletes, so `permissions` gives it `.delete`. A connection with an `after` -argument pages as `cursor`: `after` and `first` in the variables, `pageInfo.endCursor` and `pageInfo.hasNextPage` in the -answer, rows under `nodes`. Each scalar the schema defines beyond GraphQL's five is mapped in `scalars` +`Delete` or `Archive` (not `Unarchive`) deletes, so `permissions` gives it `.delete`. Its first tag is the entity +its name acts on: the earliest, then longest, run of the field name's words that names an object with an `id`, its last +word read singular (`issueLabels` → `issue-label`, `searchIssues` → `issue`), never a mutation's whole name +(`projectUpdate` changes a `Project`); with none, `query` or `mutation`. Its second tag is always `query` or `mutation`. +The agent skill files one page per first tag. A connection with an `after` argument pages as `cursor`: `after` and +`first` in the variables, `pageInfo.endCursor` and `pageInfo.hasNextPage` in the answer, rows under `nodes`. Each scalar the schema defines beyond GraphQL's five is mapped in `scalars` (`{ DateTime: { type: "string" } }`), else generation stops; SDL is not read, since that needs graphql-js. `exclude` names a field, or `query.` / `mutation.` when both roots have it. Sign-in is not in a GraphQL schema: `generate`'s `auth` gives it. `graphqlFake({ operations, definitions, url, auth, answers })` diff --git a/docs/standards/kit-surface.md b/docs/standards/kit-surface.md index 91cfcb1..090e343 100644 --- a/docs/standards/kit-surface.md +++ b/docs/standards/kit-surface.md @@ -178,9 +178,9 @@ source whose subtypes the definitions cannot tell apart. `apiSkillFiles({ cli, folder, files, service, skill, operations, commands, banner })` writes the API part of the CLI's skill, in the shape of [openapi-to-skills](https://github.com/neutree-ai/openapi-to-skills): `references/api.md`, a short index of the groups with their effects, and `references/api/api-.md`, one file per group. An -operation's group is its `group` (WC-CMD-33), else its first tag; one without either is in `api-untagged.md`. A tag with no Latin letter or digit -cannot name a file and stops the generation. An agent reads -the index, then only the group it needs, with ` skill show api-`. The `skill` command already ships and +operation's group is its `group` (WC-CMD-33), else its first tag (for GraphQL, the entity its field acts on); one +without either is in `api-untagged.md`. A tag with no Latin letter or digit cannot name a file and stops the +generation. An agent reads the index, then only the group it needs, with ` skill show api-`. The `skill` command already ships and shows every file beside `SKILL.md`; nothing else is needed. - `commands` is `describeProgram(createProgram())` from the built program, made with the CLI's own copy of cli-base. diff --git a/src/codegen/graphql.test.ts b/src/codegen/graphql.test.ts index 423b1fc..38c22f2 100644 --- a/src/codegen/graphql.test.ts +++ b/src/codegen/graphql.test.ts @@ -71,6 +71,30 @@ describe("adaptGraphql", () => { }) }) + it("tags each operation with the entity its name acts on, then its kind", () => { + const tags = Object.fromEntries(model().operations.map((one) => [one.id, one.tags])) + expect(tags).toMatchObject({ + issue: ["issue", "query"], + issueDelete: ["issue", "mutation"], + issues: ["issue", "query"], + maybeIssue: ["issue", "query"], + recentIssues: ["issue", "query"], + search: ["query", "query"], + viewer: ["query", "query"], + workflowStates: ["workflow-state", "query"], + }) + const snake = trackerIntrospection() + const mutation = snake.data.__schema.types.find((one) => one.name === "Mutation") as unknown as { + fields: { name: string }[] + } + const create = mutation.fields.find((one) => one.name === "issueCreate") + mutation.fields.push({ ...create, name: "team_users" }, { ...create, name: "workflowState" }) + const named = adaptGraphql(snake, { url: URL_, scalars }).operations + expect(named.find((one) => one.id === "team_users")?.tags).toEqual(["team", "mutation"]) + // A mutation named like an entity acts on something else: Linear's projectUpdate changes a project. + expect(named.find((one) => one.id === "workflowState")?.tags).toEqual(["mutation", "mutation"]) + }) + it("binds a field with its variables' GraphQL types and a default selection one level deep", () => { const issues = operation("issues") expect(issues.binding).toEqual({ diff --git a/src/codegen/graphql.ts b/src/codegen/graphql.ts index 8428867..169c702 100644 --- a/src/codegen/graphql.ts +++ b/src/codegen/graphql.ts @@ -6,11 +6,14 @@ * One field of `Query` or `Mutation` is one operation. Its arguments are the request body (the variables), each also a * flag; its answer is `data.`, typed by the field's type. A query reads; a mutation writes, and one whose name * ends in `Delete` or `Archive` deletes. A Relay connection pages as a `cursor`: `after`, `pageInfo.endCursor`. + * Its first tag is the entity its name acts on (`issueLabelCreate` → `issue-label`), its second `query` or `mutation`: + * the agent skill files one page per first tag, and an agent looking for an issue's writes reads only the issue page. * SDL is not read: that needs graphql-js, and codegen adds no runtime dependency. */ import { mkdirSync, readFileSync, writeFileSync } from "node:fs" import { join } from "node:path" import type { ApiModel, ApiOperation, ApiSchema, GraphqlBinding, Pagination, SchemaNode } from "./model.js" +import { kebab } from "./names.js" import { CodegenError } from "./pipeline.js" import { sha256, sortKeys } from "./snapshot.js" @@ -222,6 +225,40 @@ export const adaptGraphql = (introspection: unknown, options: GraphqlOptions): A return node ? `nodes { ${oneLevel(node)} } pageInfo { hasNextPage endCursor }` : oneLevel(name) } + const entities = new Map( + [...types.values()] + .filter((type) => fieldsOf(type.name)?.some((one) => one.name === "id")) + .map((type) => [type.name.toLowerCase(), type.name]), + ) + const singulars = (word: string) => [ + word, + ...(word.endsWith("ies") ? [`${word.slice(0, -3)}y`] : []), + ...(word.endsWith("es") ? [word.slice(0, -2)] : []), + ...(word.endsWith("s") ? [word.slice(0, -1)] : []), + ] + /** + * The earliest, then longest, run of the name's words that names an object with an id, its last word read singular + * too: `issueLabels` → `issue-label`, `searchIssues` → `issue`. A mutation's whole name is never its entity, as + * `projectUpdate` changes a project while the type `ProjectUpdate` is a status post. None: its kind, one page for + * the few leftovers rather than a page per verb. + */ + const entityOf = (name: string, operation: "query" | "mutation"): string => { + const words = name + .split(/_+|(?=[A-Z])/) + .filter(Boolean) + .map((word) => word.toLowerCase()) + for (let start = 0; start < words.length; start++) + for (let end = words.length; end > start; end--) { + if (operation === "mutation" && start === 0 && end === words.length) continue + const head = words.slice(start, end - 1).join("") + const found = singulars(words[end - 1] ?? "") + .map((last) => entities.get(head + last)) + .find(Boolean) + if (found) return kebab(found) + } + return operation + } + // An answer that is only a reference is named after its type, which would drop a nullable field's null: such an // answer is wrapped, so it gets a name of its own that keeps it. const answerOf = (node: SchemaNode): SchemaNode => @@ -288,7 +325,7 @@ export const adaptGraphql = (introspection: unknown, options: GraphqlOptions): A binding, ...(summary ? { summary } : {}), ...described(field.description), - tags: [operation], + tags: [entityOf(field.name, operation), operation], parameters: field.args.map((one) => ({ name: one.name, in: "body" as const,