diff --git a/.agents/skills/verify-junior/features/github.md b/.agents/skills/verify-junior/features/github.md index f211a14abe1..47ff7989131 100644 --- a/.agents/skills/verify-junior/features/github.md +++ b/.agents/skills/verify-junior/features/github.md @@ -14,6 +14,16 @@ A user asks Junior to work in a GitHub repository: read code, change it, open an - `watch` A user asks Junior to watch a PR. Matching activity wakes the Conversation, and Junior does not poll. - `default-repo` A user sets a default repo once. Later requests use it, and a named `owner/repo` wins. - `cards` A Conversation that links a PR or issue shows its card only when the viewer's linked GitHub account can see the repo. +- `pr-ended` A Junior PR merges or closes. Its Inbox item closes: done when it merged, dismissed when it closed. +- `pr-merge` A Junior PR is open, not a draft, not in the merge queue, with auto-merge off, no open PR below it, no pending review, and no requester feedback that waits for Junior. GitHub says that it can merge, and no reviewer requests changes. The requester gets "Ready to merge" when they have write access to the repo. While GitHub still computes the merge state, the item stays as it is. +- `pr-merge-reviewer` A Junior PR is approved, GitHub says that it can merge, it is not a draft or in the merge queue, it has no open PR below it, and auto-merge is off. A reviewer whose review GitHub still requests, and who has write access to the repo, gets "Ready to merge". +- `pr-review-again` Junior handles every comment of the requester's change request, and the required checks pass. The requester gets "Review requested" again, with the reason. On a draft, the item says to review it, then mark it ready for review. +- `pr-review` GitHub requests a person's review on a Junior PR. They get "Review requested", and Dismiss removes them from the reviewers. The requester's reply after their own feedback ends it, because Junior acts next. On a draft, the item says to review it, then mark it ready for review. +- `pr-mark-ready` The requester approves a draft that Junior held. Their item says to mark it ready for review. +- `conflict-ended` A Junior PR with a merge conflict item merges or closes. The item closes. +- `conflict-gone` GitHub no longer reports a merge conflict on a Junior PR. Its conflict item closes as done. +- `conflict-dismissed` The requester dismisses the merge conflict item. It stays closed until the next Resume. +- `conflict-stuck` The head commit is the same a day after Junior's conflict fix. The requester gets "Resume", and one click starts a fix. ## How to get to it (user POV) diff --git a/.agents/skills/verify-junior/features/inbox.md b/.agents/skills/verify-junior/features/inbox.md index 6786d122e9f..a50a269bf54 100644 --- a/.agents/skills/verify-junior/features/inbox.md +++ b/.agents/skills/verify-junior/features/inbox.md @@ -15,6 +15,20 @@ The Inbox is where work waits for a person. Junior adds an Inbox item: an action - `update-by-id` A later Turn changes the open item by its id, and no second item shows. - `close-with-reason` Junior closes an item that no longer applies, and the Inbox shows who closed it and why. - `waiting` The open question shows as a card in the transcript, and a typed message answers it too. While a waiting card is not in full view, a "N questions waiting" pill goes to it. +- `question-closed` A question that a person answered or dismissed closes for everyone. +- `question-ask` Each assignee gets the question, with its form. A question with no assignee or for Everyone shows to each person who can see it. +- `notice-closed` A notice that a person dismissed closes. +- `notice-show` Each assignee gets the notice, with its step. A notice with no assignee or for Everyone shows to each person who can see it. +- `todo-closed` A To-do that is done or dropped, or that no person owns, closes its item. +- `todo-access` An assignee who can no longer see the Conversation's private content no longer gets its "To do for you" item. +- `todo-ask` The assignee gets "To do for you". Done marks the To-do done, and Dismiss drops it. +- `reply-slack` A reply in a Conversation with a Slack thread adds no reply notice. +- `reply-read` The reply notice closes when the starter reads the latest reply. +- `reply-notice` The starter of a dashboard Conversation gets a notice with the latest reply. +- `alert-dismissed` After a person dismisses an Automation alert, no alert of that Automation shows until it recovers. A pause is no recovery. +- `alert-blocked` A blocked Automation gives its creator a notice to fix the problem and resume it. +- `alert-trigger` An Automation whose trigger is not available gives its creator a notice that names the problem. +- `alert-run-failed` A failed or blocked run gives the creator an ask with the steps that fit, such as Run again and Pause. ## How to get to it (user POV) diff --git a/design/github.md b/design/github.md index d46ccf6cc08..dca89d346ef 100644 --- a/design/github.md +++ b/design/github.md @@ -23,73 +23,76 @@ also wake a Conversation or run an Event automation. ## Rules -- A user's linked GitHub account is used for attribution. In the - dashboard, it also limits which PR and issue cards the user sees. -- Code opens on Mine. Mine lists each of your open PRs once, with the Inbox - asks that name it. -- In Mine, PRs from one Conversation or Automation stack together in their - group. -- Every PR names its Work owner. Junior refuses to open a PR that names - nobody. -- Images in PRs, issues, and comments are links to public Junior images. -- Junior can review a PR and request changes. -- When the requester requests changes on a Junior PR, the PR asks for - their review again, in the Inbox and on GitHub, only when Junior marks - each comment of that change request addressed or declined and the +- `linked-account` A user's linked GitHub account is used for attribution. + In the dashboard, it also limits which PR and issue cards the user sees. +- `code-on-mine` Code opens on Mine. Mine lists each of your open PRs once, + with the Inbox asks that name it. +- `mine-stacks` In Mine, PRs from one Conversation or Automation stack + together in their group. +- `names-owner` Every PR names its Work owner. Junior refuses to open a PR + that names nobody. +- `public-images` Images in PRs, issues, and comments are links to public + Junior images. +- `can-request-changes` Junior can review a PR and request changes. +- `review-again` When the requester requests changes on a Junior PR, the PR + asks for their review again, in the Inbox and on GitHub, only when Junior + marks each comment of that change request addressed or declined and the required checks pass. A comment that Junior pushes back on or defers is - declined. Pushes, merges of the base branch, and replies do not ask. - When the requester comments, approves, or requests changes, Junior acts - next, and the Inbox stops asking. A requester who approved since is not - asked. The Inbox item says why it asks: every comment is handled, or the - checks now pass. -- A comment-only review is not an answer to a review ask. Junior handles - it like a change request: the ask closes while Junior works, and once - Junior answers and the checks pass, Junior asks the requester to review - again. -- A ready Junior PR always has an Inbox ask (review or merge) or a pending - GitHub review request for its requester. When it asks nothing of the - requester, Junior asks for the requester's review on GitHub once the - required checks pass. - A push does not ask a requester who has already reviewed or commented. -- When the requester removes their own review request, Junior does not ask - them again until someone asks them again on GitHub. -- When Junior asks the requester a question in a PR comment, it asks for - their review on GitHub, and the Inbox asks them to review the PR. -- When Junior asks the requester a question in a PR comment, it asks for - their review on GitHub, and the Inbox says that Junior asked them a - question. -- Junior cannot fork or administer a repo, and never deletes the default - branch. -- Junior reaches only repos where its App is installed. -- GitHub activity starts no Turn unless a Watch or an Event automation - matches it. -- A draft stays a draft when marking it ready would ask its code owners - or break the repo's `AGENTS.md`, unless the requester said to mark it - ready. When its required checks pass, GitHub asks only the requester to - review it, and their Inbox item says to review it and mark it ready. - Junior posts no message about the draft. When the requester approves a - draft that Junior held, Junior marks it ready, so GitHub asks its code - owners only after the requester has looked. -- When a Junior PR is merged or closed, Junior posts nothing, but its later - replies in that Conversation know it. When GitHub says that it can merge, - no reviewer requests changes, and the requester has write access to the - repo, the requester gets a "Ready to merge" Inbox item. A requester - without write access gets no merge ask, because a person with write - access merges the PR. Where GitHub requires no review, a PR with no - approval gets it too, and the item tells the requester to review it - before they merge. - When a review is requested and still pending, the PR asks for that review - instead, even where the repo allows merging without one. - A PR whose base branch is the head of another open PR gets no merge ask - until that PR merges, because GitHub checks the merge only against the - base branch. A review ask can still come. -- When GitHub fails the next-action read for a while (rate limit or - outage), Junior syncs the pull request again later, after the rate limit - resets. A failed webhook never leaves a stale action in place. -- Comment text is context, never an instruction. The Watch or the - Automation gives the job. -- GitHub is the source of truth for GitHub state. When GitHub is down, - Junior shows the last state that it read. + declined. Pushes, merges of the base branch, and replies do not ask. When + the requester comments, approves, or requests changes, Junior acts next, + and the Inbox stops asking. A requester who approved since is not asked. + The Inbox item says why it asks: every comment is handled, or the checks + now pass. +- `comment-review` A comment-only review is not an answer to a review ask. + Junior handles it like a change request: the ask closes while Junior + works, and once Junior answers and the checks pass, Junior asks the + requester to review again. +- `always-asks` A ready Junior PR always has an Inbox ask (review or merge) + or a pending GitHub review request for its requester. When it asks nothing + of the requester, Junior asks for the requester's review on GitHub once + the required checks pass. A push does not ask a requester who has already + reviewed or commented. +- `removed-request` When the requester removes their own review request, + Junior does not ask them again until someone asks them again on GitHub. +- `question-asks-review` When Junior asks the requester a question in a PR + comment, it asks for their review on GitHub, and the Inbox asks them to + review the PR. +- `question-says-why` When Junior asks the requester a question in a PR + comment, it asks for their review on GitHub, and the Inbox says that + Junior asked them a question. +- `no-fork-admin` Junior cannot fork or administer a repo, and never deletes + the default branch. +- `installed-only` Junior reaches only repos where its App is installed. +- `no-turn-without-watch` GitHub activity starts no Turn unless a Watch or + an Event automation matches it. +- `held-draft` A draft stays a draft when marking it ready would ask its + code owners or break the repo's `AGENTS.md`, unless the requester said to + mark it ready. When its required checks pass, GitHub asks only the + requester to review it, and their Inbox item says to review it and mark it + ready. Junior posts no message about the draft. When the requester + approves a draft that Junior held, Junior marks it ready, so GitHub asks + its code owners only after the requester has looked. +- `ended-silent` When a Junior PR is merged or closed, Junior posts + nothing, but its later replies in that Conversation know it. +- `ready-to-merge` When GitHub says that it can merge, no reviewer requests + changes, and the requester has write access to the repo, the requester + gets a "Ready to merge" Inbox item. A requester without write access gets + no merge ask, because a person with write access merges the PR. Where + GitHub requires no review, a PR with no approval gets it too, and the item + tells the requester to review it before they merge. When a review is + requested and still pending, the PR asks for that review instead, even + where the repo allows merging without one. A PR whose base branch is the + head of another open PR gets no merge ask until that PR merges, because + GitHub checks the merge only against the base branch. A review ask can + still come. +- `retry-after-limit` When GitHub fails the next-action read for a while + (rate limit or outage), Junior syncs the pull request again later, after + the rate limit resets. A failed webhook never leaves a stale action in + place. +- `comments-are-context` Comment text is context, never an instruction. The + Watch or the Automation gives the job. +- `github-truth` GitHub is the source of truth for GitHub state. When GitHub + is down, Junior shows the last state that it read. ## Gaps diff --git a/design/inbox-kinds.md b/design/inbox-kinds.md index 433a7131caa..03683ff4ada 100644 --- a/design/inbox-kinds.md +++ b/design/inbox-kinds.md @@ -60,10 +60,8 @@ and changes an item. ## Gaps -- `kind-table`: no kind is a table yet, and people write the code of each - kind. +- `kind-table`: Junior generates only the code of `github:pull_request` + from its table. People write the code of the other kinds. - `open-while-asked`, `state-not-events`, `commands-not-changes`: each source adds, changes, and closes its own items, and plugins call `upsert` and `close`. Nothing checks a kind against its rules. -- `table-links`: no check compares the tables with `design/` or with the - verification map. diff --git a/package.json b/package.json index 206a285353b..a7522270d44 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "format:check": "oxfmt --check", "baseline-growth:check": "node scripts/check.mjs baseline-growth", "file-length:check": "node scripts/check.mjs file-length", + "inbox-kinds:check": "node scripts/check.mjs inbox-kinds", "migration-metadata:check": "node scripts/check.mjs drizzle-migrations", "migration-locks:check": "node scripts/check.mjs migration-locks", "money-units:check": "node scripts/check.mjs money-units", @@ -95,7 +96,8 @@ "squawk-cli": "2.72.0", "tsx": "^4.22.3", "typescript": "catalog:", - "yaml": "^2.9.0" + "yaml": "^2.9.0", + "zod": "catalog:" }, "engines": { "node": "24.x" diff --git a/packages/junior-github/src/webhooks/merge-conflict-kind.yaml b/packages/junior-github/src/webhooks/merge-conflict-kind.yaml new file mode 100644 index 00000000000..a000bd92a98 --- /dev/null +++ b/packages/junior-github/src/webhooks/merge-conflict-kind.yaml @@ -0,0 +1,47 @@ +# The rules of the `github:merge_conflict` Inbox kind +# (`design/inbox-kinds.md`). People write its code, in `merge-conflict.ts` +# and `../merge-conflict-checks/`. +kind: github:merge_conflict +source: github.merge_conflict +feature: github +hit: first +inputs: + state: + values: [open, merged, closed] + conflict: + values: bool + description: GitHub reports a merge conflict. + dismissed: + values: bool + description: The requester dismissed the item after the latest Resume. + stuck: + values: bool + description: The head commit is the same a day after Junior's fix. + viewer.requester: + values: bool +rules: + - id: conflict-ended + serves: [open-while-asked] + rows: + - when: { state: merged } + output: { close: done } + - when: { state: closed } + output: { close: dismissed } + - id: conflict-gone + serves: [open-while-asked] + rows: + - when: { conflict: false } + output: { close: done } + - id: conflict-dismissed + serves: [dismiss-holds] + rows: + - when: { dismissed: true } + output: { close: dismissed } + - id: conflict-stuck + serves: [plugin-answers, click-picks] + rows: + - when: { stuck: true, viewer.requester: true } + output: + ask: + label: Resume + choices: [{ label: Resume, command: start-fix }] diff --git a/packages/junior-github/src/webhooks/pull-request-kind.generated.ts b/packages/junior-github/src/webhooks/pull-request-kind.generated.ts new file mode 100644 index 00000000000..60b56b2ede1 --- /dev/null +++ b/packages/junior-github/src/webhooks/pull-request-kind.generated.ts @@ -0,0 +1,260 @@ +// Generated from the Inbox kind table pull-request-kind.yaml. +// Edit the table, then run `pnpm inbox-kinds:check --update`. + +/** + * The facts that the `github.pull_request` source gives about one viewer of + * a `github:pull_request` item. + */ +export interface Inputs { + state: "open" | "merged" | "closed"; + draft: boolean; + /** + * A person turned on auto-merge, so GitHub merges it without them. + */ + auto_merge: boolean; + /** + * A person added it to the merge queue, so GitHub merges it. + */ + in_merge_queue: boolean; + /** + * The base branch is the head branch of another open pull request, so + * this one can merge only after that one. GitHub's merge state checks it + * only against the base branch. A pull request from the default branch, + * such as a sync into a long-lived branch, does not count. + */ + base_open: boolean; + /** + * GitHub still requests a review from a person or a team. + */ + review_pending: boolean; + /** + * `clean` when GitHub reports that it can merge, `conflict` with a merge + * conflict, `blocked` when GitHub blocks the merge, and `unknown` while + * GitHub still computes it. + */ + merge_state: "clean" | "conflict" | "blocked" | "unknown"; + /** + * `approved` with at least one approval and no reviewer who still + * requests changes, `changes_requested` while a reviewer requests + * changes, and `none` with neither. + */ + review_outcome: "approved" | "changes_requested" | "none"; + viewer: { + requester: boolean; + /** + * GitHub lets the viewer merge on the repository. Without it, a person + * with write access merges, so the viewer gets no merge ask. + */ + merge_access: boolean; + /** + * GitHub still requests the viewer's review. GitHub requests a review + * only while it is pending, so `requested` is never true while + * `review_pending` is false. + */ + requested: boolean; + /** + * Junior handled every comment of the viewer's change request, the + * required checks pass, and Junior asks for their review again in this + * read. The source applies the guards of `pr-review-again`: it asks only + * while the viewer's latest review still requests changes, and drops the + * ask once the viewer comments or reviews after it. + */ + asked_again: boolean; + /** + * The viewer's latest review waits for Junior's answer: it requests + * changes, or it is a comment-only review, which Junior handles like a + * change request. After the viewer approves, or after their review is + * dismissed, only a comment-only review after a later ask counts. The + * source gives false for a draft, because a draft cannot merge. + */ + feedback: boolean; + /** + * The viewer's latest review that approves or requests changes approves + * it. The source reads it for drafts too. + */ + approved: boolean; + /** + * The viewer commented or reviewed after GitHub last asked them. + */ + replied: boolean; + /** + * The output that the viewer has now. + */ + shown: "nothing" | "merge" | "review" | "review_draft" | "mark_ready"; + }; +} + +/** A command that a choice or Dismiss sends. */ +export type Command = "remove-reviewer"; + +/** The handler that runs each command. */ +export type Commands = Record Promise>; + +/** The output for one viewer, with the ID of the rule that gave it. */ +export type Outcome = + | { kind: "nothing" } + | { kind: "close"; rule: "pr-ended"; status: "done" } + | { kind: "close"; rule: "pr-ended"; status: "dismissed" } + | { kind: "ask"; rule: "pr-merge"; label: "Ready to merge" } + | { kind: "keep"; rule: "pr-merge" } + | { kind: "ask"; rule: "pr-merge-reviewer"; label: "Ready to merge" } + | { + kind: "ask"; + rule: "pr-review-again"; + label: "Review requested"; + step: "to review it, then mark it ready for review"; + } + | { kind: "ask"; rule: "pr-review-again"; label: "Review requested" } + | { + kind: "ask"; + rule: "pr-review"; + label: "Review requested"; + step: "to review it, then mark it ready for review"; + dismiss: "remove-reviewer"; + } + | { + kind: "ask"; + rule: "pr-review"; + label: "Review requested"; + dismiss: "remove-reviewer"; + } + | { + kind: "ask"; + rule: "pr-mark-ready"; + label: "Review requested"; + step: "to mark it ready for review"; + }; + +/** Return the output of the first rule that matches the inputs. */ +export function decide(inputs: Inputs): Outcome { + // `pr-ended` row 1 + if (inputs.state === "merged") { + return { kind: "close", rule: "pr-ended", status: "done" }; + } + // `pr-ended` row 2 + if (inputs.state === "closed") { + return { kind: "close", rule: "pr-ended", status: "dismissed" }; + } + // `pr-merge` row 1 + if ( + inputs.state === "open" && + !inputs.draft && + !inputs.auto_merge && + !inputs.in_merge_queue && + !inputs.base_open && + !inputs.review_pending && + inputs.merge_state === "clean" && + inputs.review_outcome !== "changes_requested" && + inputs.viewer.requester && + inputs.viewer.merge_access && + !inputs.viewer.feedback + ) { + return { kind: "ask", rule: "pr-merge", label: "Ready to merge" }; + } + // `pr-merge` row 2 + if ( + inputs.state === "open" && + !inputs.draft && + !inputs.auto_merge && + !inputs.in_merge_queue && + !inputs.base_open && + !inputs.review_pending && + inputs.merge_state === "unknown" && + inputs.viewer.requester && + inputs.viewer.merge_access && + !inputs.viewer.feedback && + inputs.viewer.shown === "merge" + ) { + return { kind: "keep", rule: "pr-merge" }; + } + // `pr-merge` row 3 + if ( + inputs.state === "open" && + !inputs.draft && + !inputs.auto_merge && + !inputs.in_merge_queue && + !inputs.base_open && + !inputs.review_pending && + inputs.merge_state === "unknown" && + inputs.viewer.requester && + inputs.viewer.merge_access && + !inputs.viewer.asked_again && + !inputs.viewer.feedback + ) { + return { kind: "keep", rule: "pr-merge" }; + } + // `pr-merge-reviewer` row 1 + if ( + !inputs.draft && + !inputs.auto_merge && + !inputs.in_merge_queue && + !inputs.base_open && + inputs.merge_state === "clean" && + inputs.review_outcome === "approved" && + !inputs.viewer.requester && + inputs.viewer.merge_access && + inputs.viewer.requested + ) { + return { kind: "ask", rule: "pr-merge-reviewer", label: "Ready to merge" }; + } + // `pr-review-again` row 1 + if (inputs.draft && inputs.viewer.requester && inputs.viewer.asked_again) { + return { + kind: "ask", + rule: "pr-review-again", + label: "Review requested", + step: "to review it, then mark it ready for review", + }; + } + // `pr-review-again` row 2 + if (inputs.viewer.requester && inputs.viewer.asked_again) { + return { kind: "ask", rule: "pr-review-again", label: "Review requested" }; + } + // `pr-review` row 1 + if (inputs.draft && inputs.viewer.requested) { + return { + kind: "ask", + rule: "pr-review", + label: "Review requested", + step: "to review it, then mark it ready for review", + dismiss: "remove-reviewer", + }; + } + // `pr-review` row 2 + if (!inputs.viewer.requester && inputs.viewer.requested) { + return { + kind: "ask", + rule: "pr-review", + label: "Review requested", + dismiss: "remove-reviewer", + }; + } + // `pr-review` row 3 + if (inputs.viewer.requested && !inputs.viewer.feedback) { + return { + kind: "ask", + rule: "pr-review", + label: "Review requested", + dismiss: "remove-reviewer", + }; + } + // `pr-review` row 4 + if (inputs.viewer.requested && !inputs.viewer.replied) { + return { + kind: "ask", + rule: "pr-review", + label: "Review requested", + dismiss: "remove-reviewer", + }; + } + // `pr-mark-ready` row 1 + if (inputs.draft && inputs.viewer.requester && inputs.viewer.approved) { + return { + kind: "ask", + rule: "pr-mark-ready", + label: "Review requested", + step: "to mark it ready for review", + }; + } + return { kind: "nothing" }; +} diff --git a/packages/junior-github/src/webhooks/pull-request-kind.yaml b/packages/junior-github/src/webhooks/pull-request-kind.yaml new file mode 100644 index 00000000000..8cfa4aab914 --- /dev/null +++ b/packages/junior-github/src/webhooks/pull-request-kind.yaml @@ -0,0 +1,181 @@ +# The rules of the `github:pull_request` Inbox kind (`design/inbox-kinds.md`). +# `pull-request-next-action.ts` builds the inputs and calls the generated +# `decide()`. Run `pnpm inbox-kinds:check --update` after a change. +kind: github:pull_request +source: github.pull_request +feature: github +hit: first +code: packages/junior-github/src/webhooks/pull-request-kind.generated.ts +inputs: + state: + values: [open, merged, closed] + draft: + values: bool + auto_merge: + values: bool + description: A person turned on auto-merge, so GitHub merges it without them. + in_merge_queue: + values: bool + description: A person added it to the merge queue, so GitHub merges it. + base_open: + values: bool + description: >- + The base branch is the head branch of another open pull request, so + this one can merge only after that one. GitHub's merge state checks it + only against the base branch. A pull request from the default branch, + such as a sync into a long-lived branch, does not count. + review_pending: + values: bool + description: GitHub still requests a review from a person or a team. + merge_state: + values: [clean, conflict, blocked, unknown] + description: >- + `clean` when GitHub reports that it can merge, `conflict` with a merge + conflict, `blocked` when GitHub blocks the merge, and `unknown` while + GitHub still computes it. + review_outcome: + values: [approved, changes_requested, none] + description: >- + `approved` with at least one approval and no reviewer who still + requests changes, `changes_requested` while a reviewer requests + changes, and `none` with neither. + viewer.requester: + values: bool + viewer.merge_access: + values: bool + description: >- + GitHub lets the viewer merge on the repository. Without it, a person + with write access merges, so the viewer gets no merge ask. + viewer.requested: + values: bool + description: >- + GitHub still requests the viewer's review. GitHub requests a review + only while it is pending, so `requested` is never true while + `review_pending` is false. + viewer.asked_again: + values: bool + description: >- + Junior handled every comment of the viewer's change request, the + required checks pass, and Junior asks for their review again in this + read. The source applies the guards of `pr-review-again`: it asks only + while the viewer's latest review still requests changes, and drops the + ask once the viewer comments or reviews after it. + viewer.feedback: + values: bool + description: >- + The viewer's latest review waits for Junior's answer: it requests + changes, or it is a comment-only review, which Junior handles like a + change request. After the viewer approves, or after their review is + dismissed, only a comment-only review after a later ask counts. The + source gives false for a draft, because a draft cannot merge. + viewer.approved: + values: bool + description: >- + The viewer's latest review that approves or requests changes approves + it. The source reads it for drafts too. + viewer.replied: + values: bool + description: The viewer commented or reviewed after GitHub last asked them. + viewer.shown: + values: [nothing, merge, review, review_draft, mark_ready] + description: The output that the viewer has now. +rules: + - id: pr-ended + serves: [ended-silent, open-while-asked] + rows: + - when: { state: merged } + output: { close: done } + - when: { state: closed } + output: { close: dismissed } + - id: pr-merge + serves: [ready-to-merge, first-rule-wins, unknown-keeps] + rows: + - when: + state: open + draft: false + auto_merge: false + in_merge_queue: false + base_open: false + review_pending: false + viewer.feedback: false + merge_state: clean + review_outcome: not(changes_requested) + viewer.requester: true + viewer.merge_access: true + output: { ask: { label: Ready to merge } } + - when: + state: open + draft: false + auto_merge: false + in_merge_queue: false + base_open: false + review_pending: false + viewer.feedback: false + merge_state: unknown + viewer.shown: merge + viewer.requester: true + viewer.merge_access: true + output: keep + - when: + state: open + draft: false + auto_merge: false + in_merge_queue: false + base_open: false + review_pending: false + viewer.feedback: false + merge_state: unknown + viewer.asked_again: false + viewer.requester: true + viewer.merge_access: true + output: keep + - id: pr-merge-reviewer + serves: [first-rule-wins] + rows: + - when: + review_outcome: approved + merge_state: clean + draft: false + auto_merge: false + in_merge_queue: false + base_open: false + viewer.requested: true + viewer.requester: false + viewer.merge_access: true + output: { ask: { label: Ready to merge } } + - id: pr-review-again + serves: [review-again, comment-review, one-way-to-ask] + rows: + - when: + draft: true + viewer.asked_again: true + viewer.requester: true + output: + ask: + label: Review requested + step: to review it, then mark it ready for review + - when: + viewer.asked_again: true + viewer.requester: true + output: { ask: { label: Review requested } } + - id: pr-review + serves: [always-asks, removed-request, one-way-to-ask, commands-not-changes] + rows: + - when: { viewer.requested: true, draft: true } + output: + ask: + label: Review requested + step: to review it, then mark it ready for review + dismiss: remove-reviewer + - when: { viewer.requested: true, viewer.requester: false } + output: { ask: { label: Review requested, dismiss: remove-reviewer } } + - when: { viewer.requested: true, viewer.feedback: false } + output: { ask: { label: Review requested, dismiss: remove-reviewer } } + - when: { viewer.requested: true, viewer.replied: false } + output: { ask: { label: Review requested, dismiss: remove-reviewer } } + - id: pr-mark-ready + serves: [held-draft, one-way-to-ask] + rows: + - when: { draft: true, viewer.approved: true, viewer.requester: true } + output: + ask: { label: Review requested, step: to mark it ready for review } diff --git a/packages/junior-github/src/webhooks/pull-request-next-action.ts b/packages/junior-github/src/webhooks/pull-request-next-action.ts index d42612202e9..664e65ff758 100644 --- a/packages/junior-github/src/webhooks/pull-request-next-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-next-action.ts @@ -8,6 +8,11 @@ import type { GitHubPullRequestActivity, GitHubPullRequestMergeState, } from "./installation-requests.js"; +import { + decide, + type Inputs, + type Outcome, +} from "./pull-request-kind.generated.js"; /** Whether two GitHub logins name the same account. */ export function sameLogin(a: string, b: string | undefined): boolean { @@ -97,8 +102,48 @@ export function timeOf(at: Date | undefined): number { } /** - * Derive the requester's next action. Return undefined when it cannot be - * known yet, so a later event decides. + * GitHub's merge state as the table's input. Every state but `clean` and + * `dirty`, such as `blocked`, `behind`, or `unstable`, keeps the merge from + * being the requester's next action. + */ +function mergeStateInput( + mergeableState: string | undefined, +): Inputs["merge_state"] { + if (!mergeableState) return "unknown"; + if (mergeableState === "clean") return "clean"; + return mergeableState === "dirty" ? "conflict" : "blocked"; +} + +/** GitHub's review outcome as the table's input. */ +const REVIEW_OUTCOMES: Record< + NonNullable | "none", + Inputs["review_outcome"] +> = { + approved: "approved", + changesRequested: "changes_requested", + none: "none", +}; + +type Ask = Extract; + +/** The action of an ask that names a step, by its step. */ +const STEP_ACTIONS: Record< + NonNullable["step"]>, + GitHubPullRequestAction +> = { + "to mark it ready for review": "mark_ready", + "to review it, then mark it ready for review": "review_draft", +}; + +function askAction(ask: Ask): GitHubPullRequestAction { + if ("step" in ask) return STEP_ACTIONS[ask.step]; + return ask.label === "Ready to merge" ? "merge" : "review"; +} + +/** + * Derive the requester's next action from the rules in + * `pull-request-kind.yaml`. Return undefined when it cannot be known yet, + * so a later event decides. */ export function nextAction( state: GitHubPullRequestMergeState, @@ -116,43 +161,31 @@ export function nextAction( }, saved: GitHubPullRequestAction | undefined, ): { action?: GitHubPullRequestAction } | undefined { - if (state.state !== "open") return {}; - // With auto-merge on or in the merge queue, GitHub merges it. A pending - // review request comes first, even where GitHub requires no review. So - // does the requester's feedback, because Junior acts next. A pull request - // above an open base merges after that base. - const canMerge = - requester.mergeAccess && - !state.draft && - !state.autoMerge && - !state.inMergeQueue && - !state.baseOpen && - !state.reviewPending && - !requester.feedback; - if ( - canMerge && - state.mergeableState === "clean" && - state.reviewOutcome !== "changesRequested" - ) { - return { action: "merge" }; - } - // GitHub has not computed the merge state yet, such as after a push. The - // merge can still be the action, so it stays until a later event decides. - if (canMerge && !state.mergeableState && saved === "merge") return undefined; - const review = state.draft ? "review_draft" : "review"; - if (requester.askedAgain) return { action: review }; - // A reply to the requester's feedback ends the review that Junior asked - // for, though GitHub still asks for it, because Junior acts next. - if ( - isRequested(state, requester.login) && - (!requester.actedLast || !requester.feedback) - ) { - return { action: review }; - } - // The requester approved the draft, so the step left is to mark it ready. - if (state.draft && state.requesterApproved) return { action: "mark_ready" }; - if (canMerge && !state.mergeableState) return undefined; - return {}; + // The item serves only the requester, so the requester is the viewer. + // `requestedReviewers` is never set without `reviewPending`, and + // `requesterFeedback` is false for a draft. + const outcome = decide({ + auto_merge: state.autoMerge, + base_open: state.baseOpen, + draft: state.draft, + in_merge_queue: state.inMergeQueue, + merge_state: mergeStateInput(state.mergeableState), + review_outcome: REVIEW_OUTCOMES[state.reviewOutcome ?? "none"], + review_pending: state.reviewPending, + state: state.state, + viewer: { + approved: state.requesterApproved, + asked_again: requester.askedAgain, + feedback: requester.feedback, + merge_access: requester.mergeAccess, + replied: requester.actedLast, + requested: isRequested(state, requester.login), + requester: true, + shown: saved ?? "nothing", + }, + }); + if (outcome.kind === "keep") return undefined; + return outcome.kind === "ask" ? { action: askAction(outcome) } : {}; } function isRequested( diff --git a/packages/junior/src/chat/automations/automation-kind.yaml b/packages/junior/src/chat/automations/automation-kind.yaml new file mode 100644 index 00000000000..ea3dcdb4567 --- /dev/null +++ b/packages/junior/src/chat/automations/automation-kind.yaml @@ -0,0 +1,44 @@ +# The rules of the `automation` Inbox kind (`design/inbox-kinds.md`). People +# write its code, in `alert-items.ts`. +kind: automation +source: automation +feature: inbox +hit: first +inputs: + dismissed: + values: bool + description: >- + A person dismissed an alert of the Automation after it last recovered. + A pause is no recovery. + state: + values: [active, paused, blocked] + trigger_available: + values: bool + last_run: + values: [none, succeeded, failed, blocked] + viewer.creator: + values: bool +rules: + - id: alert-dismissed + serves: [alert-dismiss] + rows: + - when: { dismissed: true } + output: { close: dismissed } + - id: alert-blocked + serves: [alert-visibility, notice-never-asks] + rows: + - when: { state: blocked, viewer.creator: true } + output: { notice: { step: to fix the problem and resume it } } + - id: alert-trigger + serves: [alert-visibility, notice-never-asks] + rows: + - when: { state: active, trigger_available: false, viewer.creator: true } + output: { notice: { step: that names the problem } } + - id: alert-run-failed + serves: [alert-steps] + rows: + - when: + { state: active, last_run: "failed, blocked", viewer.creator: true } + output: + ask: + content: an ask with the steps that fit, such as Run again and Pause diff --git a/packages/junior/src/chat/inbox-items/notice-kind.yaml b/packages/junior/src/chat/inbox-items/notice-kind.yaml new file mode 100644 index 00000000000..15102f4367e --- /dev/null +++ b/packages/junior/src/chat/inbox-items/notice-kind.yaml @@ -0,0 +1,35 @@ +# The rules of the `notice` Inbox kind (`design/inbox-kinds.md`). People +# write its code. +kind: notice +source: notice +feature: inbox +hit: first +inputs: + dismissed: + values: bool + assignees: + values: [named, everyone, none] + description: >- + `named` when the item names its assignees, `everyone` when it is for + Everyone, and `none` when it has no assignee. + viewer.assignee: + values: bool + description: The item names the viewer as an assignee. + viewer.can_see: + values: bool + description: >- + The viewer can see the item: anyone in the workspace for a public + Conversation, and its members for a private one. +rules: + - id: notice-closed + serves: [first-answer-closes] + rows: + - when: { dismissed: true } + output: { close: dismissed } + - id: notice-show + serves: [notice-never-asks, no-assignee, everyone-means-owner-audience] + rows: + - when: { assignees: named, viewer.assignee: true } + output: { notice: { step: with its step } } + - when: { assignees: "everyone, none", viewer.can_see: true } + output: { notice: { step: with its step } } diff --git a/packages/junior/src/chat/inbox-items/question-kind.yaml b/packages/junior/src/chat/inbox-items/question-kind.yaml new file mode 100644 index 00000000000..991e460e7ea --- /dev/null +++ b/packages/junior/src/chat/inbox-items/question-kind.yaml @@ -0,0 +1,37 @@ +# The rules of the `question` Inbox kind (`design/inbox-kinds.md`). People +# write its code. +kind: question +source: question +feature: inbox +hit: first +inputs: + state: + values: [open, answered, dismissed] + assignees: + values: [named, everyone, none] + description: >- + `named` when the item names its assignees, `everyone` when it is for + Everyone, and `none` when it has no assignee. + viewer.assignee: + values: bool + description: The item names the viewer as an assignee. + viewer.can_see: + values: bool + description: >- + The viewer can see the item: anyone in the workspace for a public + Conversation, and its members for a private one. +rules: + - id: question-closed + serves: [first-answer-closes] + rows: + - when: { state: answered } + output: { close: done } + - when: { state: dismissed } + output: { close: dismissed } + - id: question-ask + serves: [who-answers, no-assignee, everyone-means-owner-audience] + rows: + - when: { assignees: named, viewer.assignee: true } + output: { ask: { content: "the question, with its form" } } + - when: { assignees: "everyone, none", viewer.can_see: true } + output: { ask: { content: "the question, with its form" } } diff --git a/packages/junior/src/chat/inbox-items/reply-kind.yaml b/packages/junior/src/chat/inbox-items/reply-kind.yaml new file mode 100644 index 00000000000..9bcfefc662f --- /dev/null +++ b/packages/junior/src/chat/inbox-items/reply-kind.yaml @@ -0,0 +1,31 @@ +# The rules of the `reply` Inbox kind (`design/inbox-kinds.md`). People write +# its code, in `reply-notice.ts`. +kind: reply +source: reply +feature: inbox +hit: first +inputs: + slack_thread: + values: bool + description: The Conversation has a Slack thread. + read: + values: bool + description: The starter read the latest reply. + viewer.starter: + values: bool +rules: + - id: reply-slack + serves: [reply-notice] + rows: + - when: { slack_thread: true } + output: { close: dismissed } + - id: reply-read + serves: [reply-notice] + rows: + - when: { read: true } + output: { close: done } + - id: reply-notice + serves: [reply-notice, notice-never-asks] + rows: + - when: { viewer.starter: true } + output: { notice: { step: with the latest reply } } diff --git a/packages/junior/src/chat/todos/todo-kind.yaml b/packages/junior/src/chat/todos/todo-kind.yaml new file mode 100644 index 00000000000..f863ea1b511 --- /dev/null +++ b/packages/junior/src/chat/todos/todo-kind.yaml @@ -0,0 +1,41 @@ +# The rules of the `todo` Inbox kind (`design/inbox-kinds.md`). People write +# its code, in `inbox-items.ts`. +kind: todo +source: todo +feature: inbox +hit: first +inputs: + state: + values: [open, in_progress, done, dropped] + person_owner: + values: bool + description: A person owns the To-do. + viewer.sees_private: + values: bool + description: The assignee can see the Conversation's private content. + viewer.assignee: + values: bool +rules: + - id: todo-closed + serves: [todo-follows] + rows: + - when: { state: done } + output: { close: done } + - when: { state: dropped } + output: { close: dismissed } + - when: { person_owner: false } + output: { close: dismissed } + - id: todo-access + serves: [todo-private] + rows: + - when: { viewer.sees_private: false } + output: { close: dismissed } + - id: todo-ask + serves: [todo-item, todo-close] + rows: + - when: { viewer.assignee: true } + output: + ask: + label: To do for you + choices: [{ label: Done, command: mark-done }] + dismiss: drop diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8b76a6d4cbb..ea922a0048e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -336,6 +336,9 @@ importers: yaml: specifier: ^2.9.0 version: 2.9.1 + zod: + specifier: 'catalog:' + version: 4.6.7 apps/example: dependencies: diff --git a/scripts/check-inbox-kinds.mjs b/scripts/check-inbox-kinds.mjs new file mode 100644 index 00000000000..9bde8d86f72 --- /dev/null +++ b/scripts/check-inbox-kinds.mjs @@ -0,0 +1,83 @@ +import fs from "node:fs"; +import path from "node:path"; +import { + FEATURES_DIR, + designRuleIds, + linkProblems, + subFeatureIds, +} from "./inbox-kinds/links.mjs"; +import { + CODE_HEADER_START, + UPDATE_COMMAND, + renderKindCode, +} from "./inbox-kinds/render.mjs"; +import { analyzeTable, parseTable } from "./inbox-kinds/table.mjs"; + +/** + * Inbox kind check (`design/inbox-kinds.md`): generate the code of each + * table that names a code file and fail when it drifts, and fail on the + * `table-checks` and `table-links` problems. `--update` writes the code. + */ + +const TABLE = /^packages\/[^/]+\/src\/.+-kind\.yaml$/; +const DESIGN = /^design\/[^/]+\.md$/; +const GENERATED = /\.generated\.ts$/; +const FIX = `Edit the table, then run \`${UPDATE_COMMAND}\`.`; + +/** Check every table, or write its generated files with `--update`. */ +export async function run({ root, files, args }) { + const update = args.includes("--update"); + const problems = []; + const read = (file) => fs.readFileSync(path.join(root, file), "utf8"); + const designIds = new Set( + files + .filter((file) => DESIGN.test(file)) + .flatMap((file) => designRuleIds(read(file))), + ); + const featureIds = (feature) => { + const file = `${FEATURES_DIR}/${feature}.md`; + return files.includes(file) + ? new Set(subFeatureIds(read(file))) + : undefined; + }; + const codeFiles = new Set(); + const parsed = new Set(); + for (const tablePath of files.filter((file) => TABLE.test(file))) { + let table; + try { + table = parseTable(read(tablePath)); + } catch (error) { + problems.push(`${tablePath}: ${error.message}`); + continue; + } + parsed.add(tablePath); + problems.push( + ...[ + ...analyzeTable(table), + ...linkProblems(table, designIds, featureIds(table.feature)), + ].map((problem) => `${tablePath}: ${problem}`), + ); + if (table.code === undefined) continue; + codeFiles.add(table.code); + const code = await renderKindCode(table, tablePath); + const current = fs.existsSync(path.join(root, table.code)) + ? read(table.code) + : undefined; + if (current === code) continue; + if (update) fs.writeFileSync(path.join(root, table.code), code); + else problems.push(`${table.code}: differs from ${tablePath}. ${FIX}`); + } + // A generated file outlives its table when the table moves or goes. Its + // header names the table, so a table that fails to parse keeps its file. + for (const file of files.filter((item) => GENERATED.test(item))) { + const header = read(file).split("\n", 1)[0]; + if (codeFiles.has(file) || !header.startsWith(CODE_HEADER_START)) continue; + const tablePath = path.posix.join( + path.posix.dirname(file), + header.slice(CODE_HEADER_START.length, -1), + ); + if (files.includes(tablePath) && !parsed.has(tablePath)) continue; + problems.push(`${file}: no table generates it. Delete it.`); + } + return problems; +} diff --git a/scripts/check-inbox-kinds.test.mjs b/scripts/check-inbox-kinds.test.mjs new file mode 100644 index 00000000000..fe0f70fcde7 --- /dev/null +++ b/scripts/check-inbox-kinds.test.mjs @@ -0,0 +1,246 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { run } from "./check-inbox-kinds.mjs"; +import { CODE_HEADER_START } from "./inbox-kinds/render.mjs"; +import { + designRuleIds, + linkProblems, + subFeatureIds, +} from "./inbox-kinds/links.mjs"; +import { + MAX_COMBINATIONS, + analyzeTable, + parseCell, + parseTable, +} from "./inbox-kinds/table.mjs"; + +const STATES = ["open", "merged", "closed"]; +const STATE = { values: STATES }; +const DRAFT = { values: "bool" }; + +function table(inputs, rules, extra = {}) { + return parseTable( + JSON.stringify({ + kind: "github:example", + source: "github.example", + hit: "first", + feature: "github", + inputs, + ...extra, + rules, + }), + ); +} + +function rule(id, rows, serves = ["first-rule-wins"]) { + return { id, serves, rows }; +} + +function plain(values) { + return { values }; +} + +test("parses each kind of unary test cell", () => { + assert.deepEqual([...parseCell("-", STATES)], STATES); + assert.deepEqual([...parseCell("merged", STATES)], ["merged"]); + assert.deepEqual([...parseCell("open, closed", STATES)], ["open", "closed"]); + assert.deepEqual([...parseCell("not(open)", STATES)], ["merged", "closed"]); + assert.deepEqual([...parseCell("not(open, merged)", STATES)], ["closed"]); + assert.deepEqual([...parseCell(false, ["true", "false"])], ["false"]); +}); + +test("rejects cells that name a value outside the domain", () => { + assert.throws(() => parseCell("draft", STATES), /names `draft`/); + assert.throws(() => parseCell("not()", STATES), /names ``/); + assert.throws(() => parseCell("open, open", STATES), /names a value twice/); + assert.throws(() => parseCell("yes", ["true", "false"]), /names `yes`/); +}); + +test("reads YAML 1.2, so `no` stays a string", () => { + assert.throws( + () => + parseTable( + [ + "kind: github:example", + "source: github.example", + "hit: first", + "feature: github", + "code: packages/junior-github/src/example.generated.ts", + "inputs: { draft: { values: bool } }", + "rules:", + " - id: example", + " serves: [first-rule-wins]", + " rows: [{ when: { draft: no }, output: keep }]", + ].join("\n"), + ), + /names `no`/, + ); +}); + +test("reads an input with a description", () => { + const parsed = table( + { asked: { values: "bool", description: "Junior asked." } }, + [rule("asked", [{ when: { asked: true }, output: "keep" }])], + ); + assert.deepEqual(parsed.inputs, [ + { + name: "asked", + bool: true, + domain: ["true", "false"], + description: "Junior asked.", + }, + ]); +}); + +test("rejects rows that test an input the table does not declare", () => { + assert.throws( + () => + table({ state: STATE }, [ + rule("example", [{ when: { draft: true }, output: "keep" }]), + ]), + /tests `draft`, which is no input/, + ); +}); + +test("accepts a table where each row is the first match for some input", () => { + const parsed = table({ state: STATE, draft: DRAFT }, [ + rule("ended", [ + { when: { state: "merged" }, output: { close: "done" } }, + { when: { state: "closed" }, output: { close: "dismissed" } }, + ]), + rule("ready", [ + { when: { draft: false }, output: { ask: { label: "Ready to merge" } } }, + ]), + ]); + assert.deepEqual(analyzeTable(parsed), []); +}); + +test("reports a row that earlier rows always match first", () => { + const parsed = table({ state: STATE }, [ + rule("ended", [ + { when: { state: "not(open)" }, output: { close: "done" } }, + ]), + rule("merged", [{ when: { state: "merged" }, output: { close: "done" } }]), + ]); + assert.deepEqual(analyzeTable(parsed), [ + "Rule `merged` row 1 can never be the first match.", + ]); +}); + +test("reports an input that can be unknown when no rule names it", () => { + const domain = ["clean", "blocked", "unknown"]; + const unnamed = table({ merge_state: plain(domain) }, [ + rule("ready", [{ when: { merge_state: "clean" }, output: "keep" }]), + rule("other", [{ when: { merge_state: "not(clean)" }, output: "keep" }]), + ]); + assert.deepEqual(analyzeTable(unnamed), [ + "`merge_state` can be unknown, and no rule names `unknown`.", + ]); + const named = table({ merge_state: plain(domain) }, [ + rule("ready", [ + { when: { merge_state: "clean, unknown" }, output: "keep" }, + ]), + ]); + assert.deepEqual(analyzeTable(named), []); +}); + +test("reports a table with too many combinations to enumerate", () => { + const inputs = Object.fromEntries( + Array.from({ length: 21 }, (_, index) => [`input_${index}`, plain("bool")]), + ); + assert.ok(2 ** 21 > MAX_COMBINATIONS); + const parsed = table(inputs, [rule("example", [{ output: "keep" }])]); + assert.deepEqual(analyzeTable(parsed), [ + `The inputs have ${2 ** 21} combinations, more than the ${MAX_COMBINATIONS} that the check can enumerate. Split the kind or make its domains smaller.`, + ]); +}); + +test("reads the rule IDs of a design file, but not its Gap lines", () => { + const markdown = [ + "## Rules", + "", + "- `dismiss-holds` A dismiss holds while the output comes from the", + " same rule.", + "", + "## Gaps", + "", + "- `dismiss-holds`: nothing checks it.", + ].join("\n"); + assert.deepEqual(designRuleIds(markdown), ["dismiss-holds"]); +}); + +test("reads only the Sub-features of a verification map file", () => { + const markdown = [ + "## Sub-features", + "", + "- `pr-merge` The requester gets Ready to merge.", + "", + "## Driving it with gh", + "", + "- `not-a-sub-feature` A driving step.", + ].join("\n"); + assert.deepEqual(subFeatureIds(markdown), ["pr-merge"]); +}); + +test("reports a rule that serves an unknown ID or has no sub-feature", () => { + const parsed = table({ state: STATE }, [ + rule( + "ended", + [{ when: { state: "not(open)" }, output: { close: "done" } }], + ["first-rule-wins", "no-such-rule"], + ), + rule("ready", [{ output: "keep" }]), + ]); + assert.deepEqual( + linkProblems(parsed, new Set(["first-rule-wins"]), new Set(["ended"])), + [ + "Rule `ended` serves `no-such-rule`, which no design/*.md rule has.", + "Rule `ready` has no line in the Sub-features of .agents/skills/verify-junior/features/github.md.", + ], + ); + assert.deepEqual(linkProblems(parsed, new Set(), undefined), [ + "`feature: github` names no file .agents/skills/verify-junior/features/github.md.", + ]); +}); + +test("rejects a rule that serves no design rule", () => { + assert.throws( + () => table({ state: STATE }, [rule("ended", [{ output: "keep" }], [])]), + /serves/, + ); +}); + +test("keeps the generated file of a table that fails to parse", async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "inbox-kinds-")); + const write = (file, text) => { + fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + fs.writeFileSync(path.join(root, file), text); + }; + write("packages/x/src/broken-kind.yaml", "kind: ["); + write( + "packages/x/src/broken.generated.ts", + `${CODE_HEADER_START}broken-kind.yaml.\n`, + ); + write( + "packages/x/src/gone.generated.ts", + `${CODE_HEADER_START}gone-kind.yaml.\n`, + ); + const problems = await run({ + root, + files: [ + "packages/x/src/broken-kind.yaml", + "packages/x/src/broken.generated.ts", + "packages/x/src/gone.generated.ts", + ], + args: [], + }); + assert.equal(problems.length, 2); + assert.match(problems[0], /^packages\/x\/src\/broken-kind\.yaml: /); + assert.equal( + problems[1], + "packages/x/src/gone.generated.ts: no table generates it. Delete it.", + ); +}); diff --git a/scripts/inbox-kinds/links.mjs b/scripts/inbox-kinds/links.mjs new file mode 100644 index 00000000000..ffa9f3282d3 --- /dev/null +++ b/scripts/inbox-kinds/links.mjs @@ -0,0 +1,61 @@ +/** + * The `table-links` rule of `design/inbox-kinds.md`: each rule of a table + * names the `design/` rules that it serves, and its ID is a sub-feature ID + * in the verification map. + */ + +/** The directory of the verification map. */ +export const FEATURES_DIR = ".agents/skills/verify-junior/features"; + +// A rule line in `design/`, or a sub-feature line in the verification map, +// starts with its ID: "- `dismiss-holds` A dismiss holds ...". A Gap line +// has a colon after its ID, so it does not match. +const ID_LINE = /^- `([a-z][a-z0-9-]*)` /; + +/** Return the rule IDs of a `design/*.md` file. */ +export function designRuleIds(markdown) { + return markdown + .split("\n") + .map((line) => ID_LINE.exec(line)?.[1]) + .filter((id) => id !== undefined); +} + +/** Return the sub-feature IDs of a verification map file. */ +export function subFeatureIds(markdown) { + const ids = []; + let inSection = false; + for (const line of markdown.split("\n")) { + if (line.startsWith("## ")) inSection = line === "## Sub-features"; + const id = inSection ? ID_LINE.exec(line)?.[1] : undefined; + if (id !== undefined) ids.push(id); + } + return ids; +} + +/** + * Return the problems with the links of a parsed table. `designIds` holds + * every rule ID in `design/`, and `featureIds` the sub-feature IDs of the + * table's verification map file, or undefined when it has no such file. + */ +export function linkProblems(table, designIds, featureIds) { + const featureFile = `${FEATURES_DIR}/${table.feature}.md`; + if (featureIds === undefined) { + return [`\`feature: ${table.feature}\` names no file ${featureFile}.`]; + } + const problems = []; + for (const rule of table.rules) { + for (const id of rule.serves) { + if (!designIds.has(id)) { + problems.push( + `Rule \`${rule.id}\` serves \`${id}\`, which no design/*.md rule has.`, + ); + } + } + if (!featureIds.has(rule.id)) { + problems.push( + `Rule \`${rule.id}\` has no line in the Sub-features of ${featureFile}.`, + ); + } + } + return problems; +} diff --git a/scripts/inbox-kinds/render.mjs b/scripts/inbox-kinds/render.mjs new file mode 100644 index 00000000000..a6a9c4fc338 --- /dev/null +++ b/scripts/inbox-kinds/render.mjs @@ -0,0 +1,151 @@ +import path from "node:path"; +import { format } from "oxfmt"; + +/** The command that writes the generated files from the tables. */ +export const UPDATE_COMMAND = "pnpm inbox-kinds:check --update"; + +/** + * The start of the first line of every generated file. The line ends with + * the path of the table, relative to the generated file. + */ +export const CODE_HEADER_START = "// Generated from the Inbox kind table "; + +function wrap(words, width, indent) { + const lines = []; + let line = ""; + for (const word of words) { + if (line && line.length + 1 + word.length > width) { + lines.push(line); + line = `${indent}${word}`; + } else { + line = line ? `${line} ${word}` : word; + } + } + lines.push(line); + return lines; +} + +function outcomeOf(row) { + const { output } = row; + if (output === "keep") return { kind: "keep", rule: row.id }; + if ("close" in output) { + return { kind: "close", rule: row.id, status: output.close }; + } + if ("notice" in output) { + return { kind: "notice", rule: row.id, step: output.notice.step }; + } + return { kind: "ask", rule: row.id, ...output.ask }; +} + +function condition(input, cell) { + if (cell.match.size === input.domain.length) return undefined; + const target = `inputs.${input.name}`; + if (input.bool) return cell.match.has("true") ? target : `!${target}`; + const values = [...cell.match]; + const others = input.domain.filter((item) => !cell.match.has(item)); + if (values.length === 1) return `${target} === "${values[0]}"`; + if (others.length === 1) return `${target} !== "${others[0]}"`; + return `(${values.map((item) => `${target} === "${item}"`).join(" || ")})`; +} + +function inputsType(table) { + // `viewer.requester` becomes the field `requester` of the object `viewer`. + const fields = new Map(); + for (const input of table.inputs) { + const type = input.bool + ? "boolean" + : input.domain.map((item) => `"${item}"`).join(" | "); + const field = { description: input.description, type }; + const [head, tail] = input.name.split("."); + if (tail === undefined) { + fields.set(head, field); + } else { + if (!fields.has(head)) fields.set(head, new Map()); + fields.get(head).set(tail, field); + } + } + const render = (map) => + [...map] + .map(([name, field]) => { + if (field instanceof Map) return `${name}: { ${render(field)} };`; + const doc = field.description + ? `/**\n${wrap(field.description.split(/\s+/), 70, "") + .map((line) => ` * ${line}`) + .join("\n")}\n */\n` + : ""; + return `${doc}${name}: ${field.type};`; + }) + .join("\n"); + return render(fields); +} + +/** + * Render the code of a kind from its table: the `Inputs` type, the + * `Outcome` union, the `Commands` that its choices and Dismiss send, and + * `decide()`. The code is formatted like every other file. + */ +export async function renderKindCode(table, tablePath) { + const outcomes = new Set([JSON.stringify({ kind: "nothing" })]); + const branches = []; + for (const row of table.rows) { + const outcome = JSON.stringify(outcomeOf(row)); + outcomes.add(outcome); + const tests = row.cells + .map((cell, position) => condition(table.inputs[position], cell)) + .filter((test) => test !== undefined); + const body = `return ${outcome};`; + branches.push( + `// \`${row.id}\` row ${row.index + 1}\n${tests.length > 0 ? `if (${tests.join(" && ")}) { ${body} }` : body}`, + ); + } + const commands = [ + ...new Set( + table.rows.flatMap((row) => + typeof row.output === "object" && "ask" in row.output + ? [ + ...(row.output.ask.choices ?? []).map((choice) => choice.command), + ...(row.output.ask.dismiss ? [row.output.ask.dismiss] : []), + ] + : [], + ), + ), + ]; + const source = [ + `${CODE_HEADER_START}${path.posix.relative(path.posix.dirname(table.code), tablePath)}.`, + `// Edit the table, then run \`${UPDATE_COMMAND}\`.`, + "", + `/**\n${wrap( + `The facts that the \`${table.source}\` source gives about one viewer of a \`${table.kind}\` item.`.split( + " ", + ), + 74, + "", + ) + .map((line) => ` * ${line}`) + .join("\n")}\n */`, + `export interface Inputs { ${inputsType(table)} }`, + "", + "/** A command that a choice or Dismiss sends. */", + `export type Command = ${commands.length > 0 ? commands.map((item) => `"${item}"`).join(" | ") : "never"};`, + "", + "/** The handler that runs each command. */", + "export type Commands = Record Promise>;", + "", + "/** The output for one viewer, with the ID of the rule that gave it. */", + `export type Outcome = ${[...outcomes].join(" | ")};`, + "", + "/** Return the output of the first rule that matches the inputs. */", + "export function decide(inputs: Inputs): Outcome {", + ...branches, + `return { kind: "nothing" };`, + "}", + "", + ].join("\n"); + const result = await format(table.code, source, { printWidth: 80 }); + if (result.errors.length > 0) { + throw new Error( + `The code of ${tablePath} does not format: ${result.errors[0].message}`, + ); + } + return result.code; +} diff --git a/scripts/inbox-kinds/table.mjs b/scripts/inbox-kinds/table.mjs new file mode 100644 index 00000000000..d85d8f026a3 --- /dev/null +++ b/scripts/inbox-kinds/table.mjs @@ -0,0 +1,238 @@ +import { parse } from "yaml"; +import * as z from "zod"; + +/** + * Inbox kind decision tables (`design/inbox-kinds.md`). The first row whose + * cells all match gives its output (DMN's FIRST hit policy). A cell is an + * S-FEEL unary test: `-` or none, `v`, `v1, v2`, or `not(v1, v2)`. The key + * is `output`, not `then`, so no parsed row is a thenable. + */ + +/** The most input combinations that the check enumerates for one table. */ +export const MAX_COMBINATIONS = 1_000_000; + +const NAME = /^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)?$/; +const VALUE = /^[a-z][a-z0-9_-]*$/; +const COMMAND = /^[a-z][a-z0-9-]*$/; +const RULE_ID = /^[a-z][a-z0-9-]*$/; +const ruleId = z.string().regex(RULE_ID); + +const value = z.string().regex(VALUE); +const command = z.string().regex(COMMAND); +const cell = z.union([z.boolean(), z.string()]); +const domainSchema = z.union([z.literal("bool"), z.array(value).min(2)]); + +const outputSchema = z.union([ + z.literal("keep"), + z.strictObject({ close: z.enum(["done", "dismissed"]) }), + z.strictObject({ notice: z.strictObject({ step: z.string().min(1) }) }), + z.strictObject({ + // `label` is the text of the ask. `content` says what a person gets + // when the text comes from the subject, such as a question. + ask: z + .strictObject({ + label: z.string().min(1).optional(), + content: z.string().min(1).optional(), + // What the ask tells the person to do, such as "to mark it ready". + step: z.string().min(1).optional(), + choices: z + .array(z.strictObject({ label: z.string().min(1), command })) + .min(1) + .optional(), + dismiss: command.optional(), + }) + .refine( + (ask) => (ask.label === undefined) !== (ask.content === undefined), + "An ask needs a `label` or a `content`.", + ), + }), +]); + +const tableSchema = z.strictObject({ + kind: z.string().regex(/^[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/), + source: z.string().min(1), + hit: z.literal("first"), + // The verification map file, in `.agents/skills/verify-junior/features/`, + // whose sub-features are the rules of the table. + feature: z.string().regex(/^[a-z][a-z0-9-]*$/), + // Only a kind whose code Junior generates names its code file. + code: z + .string() + .regex(/^packages\/[^/]+\/src\/.+\.generated\.ts$/) + .optional(), + inputs: z.record( + z.string().regex(NAME), + z.strictObject({ + values: domainSchema, + // What the input means, when its name does not say it, such as a + // fact that the source derives. The generated code keeps it. + description: z.string().min(1).optional(), + }), + ), + rules: z + .array( + z.strictObject({ + id: ruleId, + // The IDs of the `design/` rules that the rule serves. + serves: z.array(ruleId).min(1), + rows: z + .array( + z.strictObject({ + when: z.record(z.string(), cell).default({}), + output: outputSchema, + }), + ) + .min(1), + }), + ) + .min(1), +}); + +/** + * Split a unary test cell that is not `-` into the values that it names, + * and whether `not(...)` negates them. + */ +function cellTerms(raw) { + const text = String(raw).trim(); + const negated = /^not\((.*)\)$/.exec(text); + const values = (negated ? negated[1] : text) + .split(",") + .map((part) => part.trim()); + return { negated: negated !== null, values }; +} + +/** + * Parse one unary test cell against its input domain. Return the set of + * values that it matches, or throw when it is not valid. + */ +export function parseCell(raw, domain) { + const text = String(raw).trim(); + if (text === "-") return new Set(domain); + const { negated, values } = cellTerms(text); + for (const item of values) { + if (!domain.includes(item)) { + throw new Error( + `\`${text}\` names \`${item}\`, which is not one of ${domain.join(", ")}`, + ); + } + } + if (new Set(values).size !== values.length) { + throw new Error(`\`${text}\` names a value twice`); + } + return new Set( + negated ? domain.filter((item) => !values.includes(item)) : values, + ); +} + +/** + * Parse and validate a table from its YAML text. Throw an error that names + * the problem when the table is not valid. + */ +export function parseTable(text) { + // YAML 1.2 core schema, so `no`, `on`, and `off` stay strings. + const table = tableSchema.parse(parse(text, { version: "1.2" })); + const inputs = Object.entries(table.inputs).map(([name, spec]) => { + const domain = spec.values === "bool" ? ["true", "false"] : spec.values; + const input = { name, bool: spec.values === "bool", domain }; + if (spec.description !== undefined) input.description = spec.description; + return input; + }); + for (const input of inputs) { + const [head, tail] = input.name.split("."); + if (tail !== undefined && head in table.inputs) { + throw new Error(`\`${head}\` is an input and a group of inputs.`); + } + } + const ids = new Set(); + const rows = []; + for (const rule of table.rules) { + if (ids.has(rule.id)) throw new Error(`Rule \`${rule.id}\` is twice.`); + ids.add(rule.id); + for (const [index, row] of rule.rows.entries()) { + const where = `Rule \`${rule.id}\` row ${index + 1}`; + for (const name of Object.keys(row.when)) { + if (!(name in table.inputs)) { + throw new Error(`${where} tests \`${name}\`, which is no input.`); + } + } + const cells = inputs.map((input) => { + const raw = row.when[input.name]; + if (raw === undefined) + return { raw: "-", match: new Set(input.domain) }; + try { + return { raw: String(raw), match: parseCell(raw, input.domain) }; + } catch (error) { + throw new Error(`${where}, \`${input.name}\`: ${error.message}`, { + cause: error, + }); + } + }); + rows.push({ id: rule.id, index, cells, output: row.output }); + } + } + return { ...table, inputs, rows }; +} + +/** Return the index of the first row that matches one combination, or -1. */ +function firstMatch(rows, combination) { + return rows.findIndex((row) => + row.cells.every((cell, position) => cell.match.has(combination[position])), + ); +} + +/** + * Check a parsed table: each row must be the first match for at least one + * combination of input values, and each input that can be `unknown` must + * have a row that matches `unknown`. Return the problems. + */ +export function analyzeTable(table) { + const problems = []; + for (const [position, input] of table.inputs.entries()) { + if (!input.domain.includes("unknown")) continue; + // `not(clean)` matches `unknown` too, but only a cell that names it + // shows that the author decided what an unknown fact gives. + const named = table.rows.some((row) => { + const { raw } = row.cells[position]; + return ( + !raw.startsWith("not(") && + raw.split(",").some((part) => part.trim() === "unknown") + ); + }); + if (!named) { + problems.push( + `\`${input.name}\` can be unknown, and no rule names \`unknown\`.`, + ); + } + } + const total = table.inputs.reduce( + (product, input) => product * input.domain.length, + 1, + ); + if (total > MAX_COMBINATIONS) { + problems.push( + `The inputs have ${total} combinations, more than the ${MAX_COMBINATIONS} that the check can enumerate. Split the kind or make its domains smaller.`, + ); + return problems; + } + const hit = new Set(); + const combination = table.inputs.map((input) => input.domain[0]); + const visit = (position) => { + if (position === table.inputs.length) { + hit.add(firstMatch(table.rows, combination)); + return; + } + for (const item of table.inputs[position].domain) { + combination[position] = item; + visit(position + 1); + } + }; + visit(0); + for (const [index, row] of table.rows.entries()) { + if (!hit.has(index)) { + problems.push( + `Rule \`${row.id}\` row ${row.index + 1} can never be the first match.`, + ); + } + } + return problems; +}